Skip to main content

wellfare_core/
asset_aspects.rs

1//! Asset aspect graphs — sub-graphs for assets at spatial locations with
2//! multiple temporal assertions (T71+ / user request 2026-08-20).
3//!
4//! An asset (recording, venue, event space, artwork, document, etc.) can be
5//! anchored to a spatial location and have multiple named temporal assertions:
6//! production date, recording date, publication date, event date, performance
7//! date, etc. Each assertion has its own provenance, confidence, and evidence
8//! type. These form a sub-graph that illustrates different aspects of the
9//! asset.
10//!
11//! The asset aspect graph also supports topic/concept associations — different
12//! topics or concepts in relation to different subjects — so the sub-graph can
13//! express relationships like "this recording is about topic X, performed at
14//! venue Y, published by subject Z."
15//!
16//! Architecture:
17//! - `TemporalAspect` — a single named temporal assertion (e.g., "production_date")
18//! - `AssetAspectGraph` — the full sub-graph for an asset
19//! - `TopicAssociation` — a topic/concept in relation to a subject
20//! - `SpatialAnchorLite` — lightweight geodetic position (no vibe dependency)
21//!
22//! The `SpatialAnchorLite` type mirrors the essential fields of
23//! `vibe::cosmic::ar::SpatialAnchor` without pulling in vibe as a
24//! hard dependency. Under the `qualia` feature, it converts to/from
25//! `SpatialAnchor`.
26
27use crate::record::{DurationBridge, EvidenceType, InstantBridge, NQuin, q_hash_str};
28use serde::{Deserialize, Serialize};
29
30// ── Spatial anchor lite ───────────────────────────────────────────────────
31
32/// Lightweight geodetic spatial anchor for assets (no vibe dependency).
33///
34/// Stores WGS84 [lat, lon, alt] plus an optional ENU offset and confidence
35/// radius. Under the `qualia` feature, converts to/from
36/// `vibe::cosmic::ar::SpatialAnchor`.
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38pub struct SpatialAnchorLite {
39    /// Unique anchor identifier
40    pub anchor_id: String,
41    /// WGS84 geodetic position [lat_deg, lon_deg, alt_m]
42    pub geodetic: [f64; 3],
43    /// Local ENU offset [East, North, Up] in meters
44    #[serde(default)]
45    pub enu_offset: [f32; 3],
46    /// Confidence radius in millimeters
47    #[serde(default = "default_confidence_mm")]
48    pub confidence_radius_mm: f32,
49}
50
51fn default_confidence_mm() -> f32 {
52    10.0
53}
54
55impl SpatialAnchorLite {
56    /// Create a new spatial anchor at a geodetic position.
57    pub fn new(anchor_id: &str, lat: f64, lon: f64, alt: f64) -> Self {
58        Self {
59            anchor_id: anchor_id.into(),
60            geodetic: [lat, lon, alt],
61            enu_offset: [0.0, 0.0, 0.0],
62            confidence_radius_mm: 10.0,
63        }
64    }
65
66    /// Set ENU offset.
67    pub fn with_enu_offset(mut self, east: f32, north: f32, up: f32) -> Self {
68        self.enu_offset = [east, north, up];
69        self
70    }
71
72    /// Set confidence radius in mm.
73    pub fn with_confidence(mut self, radius_mm: f32) -> Self {
74        self.confidence_radius_mm = radius_mm;
75        self
76    }
77
78    /// Whether this anchor is sub-millimeter precision.
79    pub fn is_submillimeter(&self) -> bool {
80        self.confidence_radius_mm < 1.0
81    }
82}
83
84// ── Temporal aspect ───────────────────────────────────────────────────────
85
86/// The kind of temporal assertion associated with an asset.
87///
88/// Assets can have multiple temporal aspects — e.g., a recording has both a
89/// production date (when it was made) and a publication date (when it was
90/// released). A venue has event dates. An artwork has creation and exhibition
91/// dates.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
93pub enum TemporalAspectKind {
94    /// When the asset was produced/created
95    Production,
96    /// When the asset was recorded
97    Recording,
98    /// When the asset was published/released
99    Publication,
100    /// When an event occurred (venue, event space)
101    Event,
102    /// When a performance took place
103    Performance,
104    /// When the asset was exhibited
105    Exhibition,
106    /// When the asset was modified
107    Modification,
108    /// When the asset was archived
109    Archival,
110    /// When the asset was acquired/obtained
111    Acquisition,
112    /// When the asset was decommissioned/retired
113    Decommission,
114    /// A custom named temporal aspect
115    Custom,
116}
117
118impl TemporalAspectKind {
119    /// Canonical string representation for graph predicates.
120    pub fn as_str(&self) -> &'static str {
121        match self {
122            Self::Production => "q42:productionDate",
123            Self::Recording => "q42:recordingDate",
124            Self::Publication => "q42:publicationDate",
125            Self::Event => "q42:eventDate",
126            Self::Performance => "q42:performanceDate",
127            Self::Exhibition => "q42:exhibitionDate",
128            Self::Modification => "q42:modificationDate",
129            Self::Archival => "q42:archivalDate",
130            Self::Acquisition => "q42:acquisitionDate",
131            Self::Decommission => "q42:decommissionDate",
132            Self::Custom => "q42:customDate",
133        }
134    }
135}
136
137/// A single named temporal assertion about an asset.
138///
139/// Each aspect has its own instant, optional duration (for events/
140/// performances), provenance (who asserted it), confidence, and evidence type.
141/// This allows multiple conflicting or complementary temporal assertions to
142/// coexist in the same sub-graph — e.g., a recording might have a production
143/// date asserted by the producer and a different one asserted by a historian.
144#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
145pub struct TemporalAspect {
146    /// The kind of temporal assertion
147    pub kind: TemporalAspectKind,
148    /// Custom label for Custom kind (ignored for other kinds)
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub custom_label: Option<String>,
151    /// When this aspect occurred
152    pub instant: InstantBridge,
153    /// Optional duration (for events, performances, exhibitions)
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub duration: Option<DurationBridge>,
156    /// Who asserted this temporal aspect (DID)
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub asserted_by: Option<String>,
159    /// Confidence in this assertion [0.0, 1.0]
160    #[serde(default = "default_confidence")]
161    pub confidence: f64,
162    /// How this temporal assertion was determined
163    pub evidence_type: EvidenceType,
164}
165
166fn default_confidence() -> f64 {
167    1.0
168}
169
170impl TemporalAspect {
171    /// Create a new temporal aspect.
172    pub fn new(kind: TemporalAspectKind, instant: InstantBridge) -> Self {
173        Self {
174            kind,
175            custom_label: None,
176            instant,
177            duration: None,
178            asserted_by: None,
179            confidence: 1.0,
180            evidence_type: EvidenceType::SelfReported,
181        }
182    }
183
184    /// Set a custom label (for Custom kind).
185    pub fn with_label(mut self, label: &str) -> Self {
186        self.custom_label = Some(label.into());
187        self
188    }
189
190    /// Set the duration.
191    pub fn with_duration(mut self, duration: DurationBridge) -> Self {
192        self.duration = Some(duration);
193        self
194    }
195
196    /// Set who asserted this.
197    pub fn with_asserted_by(mut self, did: &str) -> Self {
198        self.asserted_by = Some(did.into());
199        self
200    }
201
202    /// Set confidence.
203    pub fn with_confidence(mut self, confidence: f64) -> Self {
204        self.confidence = confidence;
205        self
206    }
207
208    /// Set evidence type.
209    pub fn with_evidence(mut self, evidence: EvidenceType) -> Self {
210        self.evidence_type = evidence;
211        self
212    }
213
214    /// The predicate string for this aspect (for graph Quins).
215    pub fn predicate(&self) -> &str {
216        self.kind.as_str()
217    }
218
219    /// Compile this temporal aspect to a graph Quin.
220    /// The subject is the asset ID hash, the predicate is the aspect kind,
221    /// the object is the Unix nanoseconds, and the context is the asset's
222    /// sub-graph context hash.
223    pub fn to_quin(&self, asset_id_hash: u64, context_hash: u64) -> NQuin {
224        let pred_hash = q_hash_str(self.kind.as_str());
225        let obj = self.instant.to_unix_nanos() as u64;
226        let metadata = (self.confidence * 1e6) as u64; // Pack confidence into metadata
227        NQuin::new(asset_id_hash, pred_hash, obj, context_hash, metadata)
228    }
229}
230
231// ── Topic association ─────────────────────────────────────────────────────
232
233/// A topic/concept in relation to a subject within an asset sub-graph.
234///
235/// This allows the sub-graph to express relationships like "this recording
236/// is about topic X" or "this venue is associated with subject Y" — where
237/// the topic and subject can be any IRI or string identifier.
238#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
239pub struct TopicAssociation {
240    /// The topic or concept (IRI or string)
241    pub topic: String,
242    /// The subject the topic relates to (IRI or string)
243    pub subject: String,
244    /// The relationship type (e.g., "q42:isAbout", "q42:associatedWith")
245    pub relation: String,
246    /// Optional confidence in this association
247    #[serde(default = "default_confidence")]
248    pub confidence: f64,
249}
250
251impl TopicAssociation {
252    /// Create a new topic association.
253    pub fn new(topic: &str, subject: &str, relation: &str) -> Self {
254        Self {
255            topic: topic.into(),
256            subject: subject.into(),
257            relation: relation.into(),
258            confidence: 1.0,
259        }
260    }
261
262    /// Set confidence.
263    pub fn with_confidence(mut self, confidence: f64) -> Self {
264        self.confidence = confidence;
265        self
266    }
267
268    /// Compile this topic association to a graph Quin.
269    pub fn to_quin(&self, asset_id_hash: u64, context_hash: u64) -> NQuin {
270        let pred_hash = q_hash_str(&self.relation);
271        let obj_hash = q_hash_str(&self.topic);
272        let metadata = (self.confidence * 1e6) as u64;
273        NQuin::new(asset_id_hash, pred_hash, obj_hash, context_hash, metadata)
274    }
275}
276
277// ── Asset aspect graph ────────────────────────────────────────────────────
278
279/// The kind of asset.
280#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
281pub enum AssetKind {
282    Recording,
283    Venue,
284    EventSpace,
285    Artwork,
286    Document,
287    Photograph,
288    Performance,
289    Artifact,
290    Location,
291    Custom,
292}
293
294impl AssetKind {
295    ///  form.
296    pub fn as_str(&self) -> &'static str {
297        match self {
298            Self::Recording => "q42:Recording",
299            Self::Venue => "q42:Venue",
300            Self::EventSpace => "q42:EventSpace",
301            Self::Artwork => "q42:Artwork",
302            Self::Document => "q42:Document",
303            Self::Photograph => "q42:Photograph",
304            Self::Performance => "q42:Performance",
305            Self::Artifact => "q42:Artifact",
306            Self::Location => "q42:Location",
307            Self::Custom => "q42:Asset",
308        }
309    }
310}
311
312/// A sub-graph for an asset at a spatial location with multiple temporal
313/// assertions and topic/concept associations.
314///
315/// This is the core type for the "asset sub-graph" concept. Each asset gets
316/// its own sub-graph (identified by a context hash) that contains:
317/// - A spatial anchor (where the asset is/was)
318/// - Multiple temporal aspects (when different things happened to it)
319/// - Topic/concept associations (what the asset is about)
320/// - Graph Quins (the compiled semantic graph entries)
321///
322/// Example: A live recording at a venue might have:
323/// - Spatial anchor: the venue's geodetic position
324/// - Temporal aspects:
325///   - Production date (when the recording was made)
326///   - Publication date (when it was released)
327///   - Event date (when the live performance happened)
328/// - Topic associations:
329///   - "jazz music" isAbout "this recording"
330///   - "Carnegie Hall" associatedWith "this recording"
331#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
332pub struct AssetAspectGraph {
333    /// Unique asset identifier
334    pub asset_id: String,
335    /// The kind of asset
336    pub asset_kind: AssetKind,
337    /// Optional spatial anchor (where the asset is/was)
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub spatial_anchor: Option<SpatialAnchorLite>,
340    /// Multiple temporal assertions about this asset
341    pub temporal_aspects: Vec<TemporalAspect>,
342    /// Topic/concept associations
343    #[serde(default, skip_serializing_if = "Vec::is_empty")]
344    pub topics: Vec<TopicAssociation>,
345    /// Optional owner DID
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    pub owner_did: Option<String>,
348}
349
350impl AssetAspectGraph {
351    /// Create a new asset aspect graph.
352    pub fn new(asset_id: &str, asset_kind: AssetKind) -> Self {
353        Self {
354            asset_id: asset_id.into(),
355            asset_kind,
356            spatial_anchor: None,
357            temporal_aspects: Vec::new(),
358            topics: Vec::new(),
359            owner_did: None,
360        }
361    }
362
363    /// Set the spatial anchor.
364    pub fn with_spatial_anchor(mut self, anchor: SpatialAnchorLite) -> Self {
365        self.spatial_anchor = Some(anchor);
366        self
367    }
368
369    /// Add a temporal aspect.
370    pub fn with_temporal_aspect(mut self, aspect: TemporalAspect) -> Self {
371        self.temporal_aspects.push(aspect);
372        self
373    }
374
375    /// Add a topic association.
376    pub fn with_topic(mut self, topic: TopicAssociation) -> Self {
377        self.topics.push(topic);
378        self
379    }
380
381    /// Set the owner DID.
382    pub fn with_owner(mut self, did: &str) -> Self {
383        self.owner_did = Some(did.into());
384        self
385    }
386
387    /// The context hash for this asset's sub-graph.
388    /// This is derived from the asset ID and kind, so the same asset always
389    /// maps to the same sub-graph context.
390    pub fn context_hash(&self) -> u64 {
391        let mut h = q_hash_str(self.asset_kind.as_str());
392        h ^= q_hash_str(&self.asset_id);
393        h = h.wrapping_mul(0x100000001b3);
394        h
395    }
396
397    /// The asset ID hash (used as the subject in graph Quins).
398    pub fn asset_id_hash(&self) -> u64 {
399        q_hash_str(&self.asset_id)
400    }
401
402    /// Compile the full sub-graph to Quins.
403    /// Returns a vector of NQuins representing all temporal aspects and
404    /// topic associations in this asset's sub-graph.
405    pub fn to_quins(&self) -> Vec<NQuin> {
406        let asset_hash = self.asset_id_hash();
407        let ctx_hash = self.context_hash();
408        let mut quins = Vec::new();
409
410        // Temporal aspect Quins
411        for aspect in &self.temporal_aspects {
412            quins.push(aspect.to_quin(asset_hash, ctx_hash));
413        }
414
415        // Topic association Quins
416        for topic in &self.topics {
417            quins.push(topic.to_quin(asset_hash, ctx_hash));
418        }
419
420        // Spatial anchor Quin (if present)
421        if let Some(ref anchor) = self.spatial_anchor {
422            let pred_hash = q_hash_str("q42:hasSpatialAnchor");
423            let obj_hash = q_hash_str(&anchor.anchor_id);
424            quins.push(NQuin::new(asset_hash, pred_hash, obj_hash, ctx_hash, 0));
425        }
426
427        // Asset kind Quin
428        let kind_pred = q_hash_str("q42:hasAssetKind");
429        let kind_obj = q_hash_str(self.asset_kind.as_str());
430        quins.push(NQuin::new(asset_hash, kind_pred, kind_obj, ctx_hash, 0));
431
432        quins
433    }
434
435    /// Find all temporal aspects of a specific kind.
436    pub fn aspects_of_kind(&self, kind: TemporalAspectKind) -> Vec<&TemporalAspect> {
437        self.temporal_aspects
438            .iter()
439            .filter(|a| a.kind == kind)
440            .collect()
441    }
442
443    /// The earliest temporal aspect (by instant).
444    pub fn earliest_aspect(&self) -> Option<&TemporalAspect> {
445        self.temporal_aspects
446            .iter()
447            .min_by_key(|a| a.instant.to_unix_nanos())
448    }
449
450    /// The latest temporal aspect (by instant).
451    pub fn latest_aspect(&self) -> Option<&TemporalAspect> {
452        self.temporal_aspects
453            .iter()
454            .max_by_key(|a| a.instant.to_unix_nanos())
455    }
456
457    /// The duration between the earliest and latest temporal aspects.
458    /// Useful for computing the span between production and publication, etc.
459    pub fn temporal_span(&self) -> Option<DurationBridge> {
460        let earliest = self.earliest_aspect()?;
461        let latest = self.latest_aspect()?;
462        Some(latest.instant.duration_since(&earliest.instant))
463    }
464
465    /// Find all topics with a specific relation.
466    pub fn topics_with_relation(&self, relation: &str) -> Vec<&TopicAssociation> {
467        self.topics
468            .iter()
469            .filter(|t| t.relation == relation)
470            .collect()
471    }
472
473    /// Find all topics about a specific subject.
474    pub fn topics_about(&self, subject: &str) -> Vec<&TopicAssociation> {
475        self.topics
476            .iter()
477            .filter(|t| t.subject == subject)
478            .collect()
479    }
480}
481
482// ── vibe integration (qualia feature) ────────────────────────────────
483
484#[cfg(feature = "qualia")]
485impl From<&SpatialAnchorLite> for vibe::cosmic::ar::SpatialAnchor {
486    fn from(lite: &SpatialAnchorLite) -> Self {
487        vibe::cosmic::ar::SpatialAnchor::new(&lite.anchor_id, lite.geodetic)
488            .with_enu_offset(lite.enu_offset[0], lite.enu_offset[1], lite.enu_offset[2])
489            .with_confidence(lite.confidence_radius_mm)
490    }
491}
492
493#[cfg(feature = "qualia")]
494impl From<&vibe::cosmic::ar::SpatialAnchor> for SpatialAnchorLite {
495    fn from(anchor: &vibe::cosmic::ar::SpatialAnchor) -> Self {
496        Self {
497            anchor_id: anchor.anchor_id.clone(),
498            geodetic: anchor.geodetic_anchor,
499            enu_offset: anchor.enu_offset,
500            confidence_radius_mm: anchor.confidence_radius_mm,
501        }
502    }
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508
509    #[test]
510    fn spatial_anchor_lite_basic() {
511        let a = SpatialAnchorLite::new("venue-1", 40.7128, -74.0060, 10.0);
512        assert_eq!(a.anchor_id, "venue-1");
513        assert_eq!(a.geodetic, [40.7128, -74.0060, 10.0]);
514        assert_eq!(a.enu_offset, [0.0, 0.0, 0.0]);
515        assert!(!a.is_submillimeter());
516    }
517
518    #[test]
519    fn spatial_anchor_lite_submillimeter() {
520        let a = SpatialAnchorLite::new("precise-1", 0.0, 0.0, 0.0).with_confidence(0.5);
521        assert!(a.is_submillimeter());
522    }
523
524    #[test]
525    fn temporal_aspect_kind_strings() {
526        assert_eq!(
527            TemporalAspectKind::Production.as_str(),
528            "q42:productionDate"
529        );
530        assert_eq!(
531            TemporalAspectKind::Publication.as_str(),
532            "q42:publicationDate"
533        );
534        assert_eq!(TemporalAspectKind::Event.as_str(), "q42:eventDate");
535        assert_eq!(
536            TemporalAspectKind::Performance.as_str(),
537            "q42:performanceDate"
538        );
539    }
540
541    #[test]
542    fn temporal_aspect_basic() {
543        let instant = InstantBridge::unix(1_700_000_000, 0);
544        let aspect = TemporalAspect::new(TemporalAspectKind::Production, instant);
545        assert_eq!(aspect.kind, TemporalAspectKind::Production);
546        assert_eq!(aspect.instant.secs, 1_700_000_000);
547        assert_eq!(aspect.confidence, 1.0);
548        assert!(aspect.duration.is_none());
549        assert!(aspect.asserted_by.is_none());
550    }
551
552    #[test]
553    fn temporal_aspect_with_fields() {
554        let instant = InstantBridge::unix(1_700_000_000, 0);
555        let duration = DurationBridge::from_secs(7200); // 2 hours
556        let aspect = TemporalAspect::new(TemporalAspectKind::Performance, instant)
557            .with_duration(duration)
558            .with_asserted_by("did:alice")
559            .with_confidence(0.95)
560            .with_evidence(EvidenceType::ClinicianObserved);
561        assert_eq!(aspect.duration, Some(duration));
562        assert_eq!(aspect.asserted_by, Some("did:alice".into()));
563        assert!((aspect.confidence - 0.95).abs() < 0.001);
564        assert_eq!(aspect.evidence_type, EvidenceType::ClinicianObserved);
565    }
566
567    #[test]
568    fn temporal_aspect_to_quin() {
569        let instant = InstantBridge::unix(1_700_000_000, 0);
570        let aspect = TemporalAspect::new(TemporalAspectKind::Publication, instant);
571        let asset_hash = q_hash_str("asset-1");
572        let ctx_hash = q_hash_str("ctx-1");
573        let quin = aspect.to_quin(asset_hash, ctx_hash);
574        assert_eq!(quin.subject, asset_hash);
575        assert_eq!(quin.object, 1_700_000_000_000_000_000);
576        assert_eq!(quin.context, ctx_hash);
577    }
578
579    #[test]
580    fn topic_association_basic() {
581        let t = TopicAssociation::new("jazz", "recording-1", "q42:isAbout");
582        assert_eq!(t.topic, "jazz");
583        assert_eq!(t.subject, "recording-1");
584        assert_eq!(t.relation, "q42:isAbout");
585        assert_eq!(t.confidence, 1.0);
586    }
587
588    #[test]
589    fn topic_association_with_confidence() {
590        let t = TopicAssociation::new("jazz", "recording-1", "q42:isAbout").with_confidence(0.8);
591        assert!((t.confidence - 0.8).abs() < 0.001);
592    }
593
594    #[test]
595    fn topic_association_to_quin() {
596        let t = TopicAssociation::new("jazz", "recording-1", "q42:isAbout");
597        let asset_hash = q_hash_str("asset-1");
598        let ctx_hash = q_hash_str("ctx-1");
599        let quin = t.to_quin(asset_hash, ctx_hash);
600        assert_eq!(quin.subject, asset_hash);
601        assert_eq!(quin.context, ctx_hash);
602    }
603
604    #[test]
605    fn asset_aspect_graph_basic() {
606        let graph = AssetAspectGraph::new("recording-1", AssetKind::Recording);
607        assert_eq!(graph.asset_id, "recording-1");
608        assert_eq!(graph.asset_kind, AssetKind::Recording);
609        assert!(graph.spatial_anchor.is_none());
610        assert!(graph.temporal_aspects.is_empty());
611        assert!(graph.topics.is_empty());
612    }
613
614    #[test]
615    fn asset_aspect_graph_with_spatial_anchor() {
616        let anchor = SpatialAnchorLite::new("venue-1", 40.7128, -74.0060, 10.0);
617        let graph =
618            AssetAspectGraph::new("recording-1", AssetKind::Recording).with_spatial_anchor(anchor);
619        assert!(graph.spatial_anchor.is_some());
620        assert_eq!(graph.spatial_anchor.as_ref().unwrap().anchor_id, "venue-1");
621    }
622
623    #[test]
624    fn asset_aspect_graph_with_multiple_temporal_aspects() {
625        let production = InstantBridge::unix(1_699_000_000, 0);
626        let publication = InstantBridge::unix(1_700_000_000, 0);
627        let event = InstantBridge::unix(1_699_500_000, 0);
628
629        let graph = AssetAspectGraph::new("recording-1", AssetKind::Recording)
630            .with_temporal_aspect(TemporalAspect::new(
631                TemporalAspectKind::Production,
632                production,
633            ))
634            .with_temporal_aspect(TemporalAspect::new(
635                TemporalAspectKind::Publication,
636                publication,
637            ))
638            .with_temporal_aspect(TemporalAspect::new(TemporalAspectKind::Event, event));
639
640        assert_eq!(graph.temporal_aspects.len(), 3);
641        assert_eq!(
642            graph.aspects_of_kind(TemporalAspectKind::Production).len(),
643            1
644        );
645        assert_eq!(
646            graph.aspects_of_kind(TemporalAspectKind::Publication).len(),
647            1
648        );
649        assert_eq!(graph.aspects_of_kind(TemporalAspectKind::Event).len(), 1);
650    }
651
652    #[test]
653    fn asset_aspect_graph_earliest_latest() {
654        let production = InstantBridge::unix(1_699_000_000, 0);
655        let publication = InstantBridge::unix(1_700_000_000, 0);
656        let event = InstantBridge::unix(1_699_500_000, 0);
657
658        let graph = AssetAspectGraph::new("recording-1", AssetKind::Recording)
659            .with_temporal_aspect(TemporalAspect::new(
660                TemporalAspectKind::Production,
661                production,
662            ))
663            .with_temporal_aspect(TemporalAspect::new(
664                TemporalAspectKind::Publication,
665                publication,
666            ))
667            .with_temporal_aspect(TemporalAspect::new(TemporalAspectKind::Event, event));
668
669        let earliest = graph.earliest_aspect().unwrap();
670        assert_eq!(earliest.kind, TemporalAspectKind::Production);
671        assert_eq!(earliest.instant.secs, 1_699_000_000);
672
673        let latest = graph.latest_aspect().unwrap();
674        assert_eq!(latest.kind, TemporalAspectKind::Publication);
675        assert_eq!(latest.instant.secs, 1_700_000_000);
676    }
677
678    #[test]
679    fn asset_aspect_graph_temporal_span() {
680        let production = InstantBridge::unix(1_699_000_000, 0);
681        let publication = InstantBridge::unix(1_700_000_000, 0);
682
683        let graph = AssetAspectGraph::new("recording-1", AssetKind::Recording)
684            .with_temporal_aspect(TemporalAspect::new(
685                TemporalAspectKind::Production,
686                production,
687            ))
688            .with_temporal_aspect(TemporalAspect::new(
689                TemporalAspectKind::Publication,
690                publication,
691            ));
692
693        let span = graph.temporal_span().unwrap();
694        assert_eq!(span.secs, 1_000_000); // 1M seconds between production and publication
695        assert!(span.is_positive());
696    }
697
698    #[test]
699    fn asset_aspect_graph_with_topics() {
700        let graph = AssetAspectGraph::new("recording-1", AssetKind::Recording)
701            .with_topic(TopicAssociation::new("jazz", "recording-1", "q42:isAbout"))
702            .with_topic(TopicAssociation::new(
703                "Carnegie Hall",
704                "recording-1",
705                "q42:associatedWith",
706            ));
707
708        assert_eq!(graph.topics.len(), 2);
709        assert_eq!(graph.topics_with_relation("q42:isAbout").len(), 1);
710        assert_eq!(graph.topics_with_relation("q42:associatedWith").len(), 1);
711        assert_eq!(graph.topics_about("recording-1").len(), 2);
712    }
713
714    #[test]
715    fn asset_aspect_graph_to_quins() {
716        let production = InstantBridge::unix(1_699_000_000, 0);
717        let anchor = SpatialAnchorLite::new("venue-1", 40.7128, -74.0060, 10.0);
718
719        let graph = AssetAspectGraph::new("recording-1", AssetKind::Recording)
720            .with_spatial_anchor(anchor)
721            .with_temporal_aspect(TemporalAspect::new(
722                TemporalAspectKind::Production,
723                production,
724            ))
725            .with_topic(TopicAssociation::new("jazz", "recording-1", "q42:isAbout"));
726
727        let quins = graph.to_quins();
728        // 1 temporal + 1 topic + 1 spatial + 1 kind = 4
729        assert_eq!(quins.len(), 4);
730
731        // All Quins should have the same context (sub-graph)
732        let ctx = graph.context_hash();
733        for q in &quins {
734            assert_eq!(q.context, ctx);
735        }
736
737        // All Quins should have the same subject (asset ID hash)
738        let subj = graph.asset_id_hash();
739        for q in &quins {
740            assert_eq!(q.subject, subj);
741        }
742    }
743
744    #[test]
745    fn asset_aspect_graph_context_hash_deterministic() {
746        let g1 = AssetAspectGraph::new("recording-1", AssetKind::Recording);
747        let g2 = AssetAspectGraph::new("recording-1", AssetKind::Recording);
748        assert_eq!(g1.context_hash(), g2.context_hash());
749
750        // Different assets have different contexts
751        let g3 = AssetAspectGraph::new("recording-2", AssetKind::Recording);
752        assert_ne!(g1.context_hash(), g3.context_hash());
753
754        // Different kinds have different contexts
755        let g4 = AssetAspectGraph::new("recording-1", AssetKind::Venue);
756        assert_ne!(g1.context_hash(), g4.context_hash());
757    }
758
759    #[test]
760    fn asset_aspect_graph_venue_example() {
761        // Example: a venue with event dates
762        let venue_anchor = SpatialAnchorLite::new("carnegie-hall", 40.7651, -73.9799, 0.0);
763        let event1 = InstantBridge::unix(1_699_000_000, 0);
764        let event2 = InstantBridge::unix(1_700_000_000, 0);
765
766        let graph = AssetAspectGraph::new("carnegie-hall", AssetKind::Venue)
767            .with_spatial_anchor(venue_anchor)
768            .with_temporal_aspect(
769                TemporalAspect::new(TemporalAspectKind::Event, event1)
770                    .with_duration(DurationBridge::from_secs(7200))
771                    .with_asserted_by("did:organizer-1")
772                    .with_evidence(EvidenceType::ClinicianObserved),
773            )
774            .with_temporal_aspect(
775                TemporalAspect::new(TemporalAspectKind::Event, event2)
776                    .with_duration(DurationBridge::from_secs(9000))
777                    .with_asserted_by("did:organizer-2"),
778            )
779            .with_topic(TopicAssociation::new(
780                "classical music",
781                "carnegie-hall",
782                "q42:isAbout",
783            ))
784            .with_owner("did:venue-owner");
785
786        assert_eq!(graph.asset_kind, AssetKind::Venue);
787        assert_eq!(graph.temporal_aspects.len(), 2);
788        assert_eq!(graph.aspects_of_kind(TemporalAspectKind::Event).len(), 2);
789        assert!(graph.spatial_anchor.is_some());
790        assert_eq!(graph.owner_did, Some("did:venue-owner".into()));
791
792        // Both events have durations
793        for aspect in &graph.temporal_aspects {
794            assert!(aspect.duration.is_some());
795        }
796
797        // The quins compile
798        let quins = graph.to_quins();
799        assert!(quins.len() >= 4); // 2 events + 1 topic + 1 spatial + 1 kind
800    }
801
802    #[test]
803    fn asset_aspect_graph_serde_roundtrip() {
804        let anchor = SpatialAnchorLite::new("venue-1", 40.7128, -74.0060, 10.0);
805        let graph = AssetAspectGraph::new("recording-1", AssetKind::Recording)
806            .with_spatial_anchor(anchor)
807            .with_temporal_aspect(
808                TemporalAspect::new(
809                    TemporalAspectKind::Production,
810                    InstantBridge::unix(1_699_000_000, 0),
811                )
812                .with_asserted_by("did:alice"),
813            )
814            .with_topic(TopicAssociation::new("jazz", "recording-1", "q42:isAbout"));
815
816        let json = serde_json::to_string(&graph).unwrap();
817        let restored: AssetAspectGraph = serde_json::from_str(&json).unwrap();
818        assert_eq!(graph, restored);
819    }
820
821    #[test]
822    fn asset_kind_strings() {
823        assert_eq!(AssetKind::Recording.as_str(), "q42:Recording");
824        assert_eq!(AssetKind::Venue.as_str(), "q42:Venue");
825        assert_eq!(AssetKind::EventSpace.as_str(), "q42:EventSpace");
826        assert_eq!(AssetKind::Artwork.as_str(), "q42:Artwork");
827    }
828}