Skip to main content

vibe/
observer.rs

1//! Observer context, heraldic lexicon, multi-scale sheaves, civic time,
2//! and agent characteristics (W7, W9, W14, W15, T59).
3//!
4//! ## W7: Measurement context / observer stalk
5//!
6//! A measurement context captures *who* observed *what*, *when*, and
7//! *with what instrument*. It is the observer's stalk — the local view
8//! from which a measurement was made. This is distinct from the raw
9//! measurement value: the same value observed from different contexts
10//! carries different epistemic weight.
11//!
12//! ## W9: Oral / heraldic lexicon modalities as identifier views
13//!
14//! An identifier can have multiple *views* — visual (IRI), oral
15//! (spoken name), heraldic (emblem/sigil). These are not separate
16//! identifiers; they are presentations of the same identity. The
17//! heraldic lexicon maps an IRI to its modality-specific views.
18//!
19//! ## W14: Multi-scale / filtered sheaves (LOD as physics)
20//!
21//! A multi-scale sheaf is a sheaf filtered at a given level of detail
22//! (LOD). The LOD is not a rendering parameter — it is a physical
23//! scale at which the sheaf's sections are defined. Different scales
24//! reveal different structure (e.g. continuum vs. molecular vs.
25//! atomic).
26//!
27//! ## W15: Civic time + authority to assert it
28//!
29//! Civic time is time asserted by a civic authority (e.g. NIST,
30//! GPS, a national metrology institute). A `CivicInstant` carries
31//! the instant value AND the authority that asserted it, so the
32//! provenance of the time claim is explicit.
33//!
34//! ## T59: Agent characteristics KB
35//!
36//! A knowledge base of agent characteristics — logged from behaviour,
37//! not declared. Records what an agent *does*, not what it *claims*.
38//! Used for governance, routing, and trust assessment.
39//!
40//! Reference: `docs/vibescript-full-impl-PLAN.md` wish list W7, W9,
41//! W14, W15, and §8.12 T59.
42
43use crate::value::Value;
44use std::collections::BTreeMap;
45
46// ── W7: Measurement context / observer stalk ─────────────────────────────────
47
48/// A measurement context — the observer's stalk (W7).
49///
50/// Captures who observed, with what instrument, at what instant, and
51/// the frame of reference. The measurement value itself is separate;
52/// this is the epistemic context.
53#[derive(Debug, Clone, PartialEq)]
54pub struct MeasurementContext {
55    /// The observer's DID or IRI.
56    pub observer: String,
57    /// The instrument identifier (e.g. "sensor:thermometer-0").
58    pub instrument: String,
59    /// Unix seconds when the measurement was taken.
60    pub instant_secs: i64,
61    /// Nanoseconds within the second.
62    pub instant_nanos: u32,
63    /// The frame of reference IRI (e.g. "frame:lab-inertial").
64    pub frame: Option<String>,
65    /// The measurement uncertainty (± in the same units as the value).
66    pub uncertainty: Option<f64>,
67    /// The stalk ID this measurement belongs to.
68    pub stalk_id: Option<u64>,
69}
70
71impl MeasurementContext {
72    /// Creates a new `MeasurementContext`.
73    pub fn new(observer: &str, instrument: &str, instant_secs: i64) -> Self {
74        Self {
75            observer: observer.into(),
76            instrument: instrument.into(),
77            instant_secs,
78            instant_nanos: 0,
79            frame: None,
80            uncertainty: None,
81            stalk_id: None,
82        }
83    }
84
85    /// Builder — sets frame.
86    pub fn with_frame(mut self, frame: &str) -> Self {
87        self.frame = Some(frame.into());
88        self
89    }
90
91    /// Builder — sets uncertainty.
92    pub fn with_uncertainty(mut self, u: f64) -> Self {
93        self.uncertainty = Some(u);
94        self
95    }
96
97    /// Builder — sets stalk.
98    pub fn with_stalk(mut self, stalk_id: u64) -> Self {
99        self.stalk_id = Some(stalk_id);
100        self
101    }
102
103    /// Convert to a Value::Record.
104    pub fn to_value(&self) -> Value {
105        let mut rec = BTreeMap::new();
106        rec.insert("observer".into(), Value::String(self.observer.clone()));
107        rec.insert("instrument".into(), Value::String(self.instrument.clone()));
108        rec.insert("instant_secs".into(), Value::I64(self.instant_secs));
109        rec.insert(
110            "instant_nanos".into(),
111            Value::U64(self.instant_nanos as u64),
112        );
113        if let Some(ref f) = self.frame {
114            rec.insert("frame".into(), Value::String(f.clone()));
115        }
116        if let Some(u) = self.uncertainty {
117            rec.insert("uncertainty".into(), Value::F64(u));
118        }
119        if let Some(s) = self.stalk_id {
120            rec.insert("stalk_id".into(), Value::U64(s));
121        }
122        Value::Record(rec)
123    }
124
125    /// Extract from a Value::Record, if possible.
126    pub fn from_value(val: &Value) -> Option<Self> {
127        let rec = match val {
128            Value::Record(r) => r,
129            _ => return None,
130        };
131        let observer = match rec.get("observer") {
132            Some(Value::String(s)) => s.clone(),
133            _ => return None,
134        };
135        let instrument = match rec.get("instrument") {
136            Some(Value::String(s)) => s.clone(),
137            _ => return None,
138        };
139        let instant_secs = match rec.get("instant_secs") {
140            Some(Value::I64(n)) => *n,
141            _ => return None,
142        };
143        let instant_nanos = match rec.get("instant_nanos") {
144            Some(Value::U64(n)) => *n as u32,
145            _ => 0,
146        };
147        let frame = match rec.get("frame") {
148            Some(Value::String(s)) => Some(s.clone()),
149            _ => None,
150        };
151        let uncertainty = match rec.get("uncertainty") {
152            Some(Value::F64(n)) => Some(*n),
153            _ => None,
154        };
155        let stalk_id = match rec.get("stalk_id") {
156            Some(Value::U64(n)) => Some(*n),
157            _ => None,
158        };
159        Some(Self {
160            observer,
161            instrument,
162            instant_secs,
163            instant_nanos,
164            frame,
165            uncertainty,
166            stalk_id,
167        })
168    }
169}
170
171// ── W9: Oral / heraldic lexicon modalities ───────────────────────────────────
172
173/// The modality of an identifier view (W9).
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175pub enum IdentifierModality {
176    /// Visual: the canonical IRI or text representation.
177    Visual,
178    /// Oral: a spoken name, for audio output.
179    Oral,
180    /// Heraldic: an emblem, sigil, or icon.
181    Heraldic,
182    /// Tactile: a Braille or haptic representation.
183    Tactile,
184}
185
186impl IdentifierModality {
187    /// `str` form.
188    pub fn as_str(&self) -> &'static str {
189        match self {
190            Self::Visual => "visual",
191            Self::Oral => "oral",
192            Self::Heraldic => "heraldic",
193            Self::Tactile => "tactile",
194        }
195    }
196
197    /// Constructs from str.
198    pub fn from_str(s: &str) -> Option<Self> {
199        match s {
200            "visual" => Some(Self::Visual),
201            "oral" => Some(Self::Oral),
202            "heraldic" => Some(Self::Heraldic),
203            "tactile" => Some(Self::Tactile),
204            _ => None,
205        }
206    }
207}
208
209/// An identifier view — one modality's presentation of an identity (W9).
210#[derive(Debug, Clone, PartialEq)]
211pub struct IdentifierView {
212    /// The canonical IRI this view represents.
213    pub iri: String,
214    /// The modality of this view.
215    pub modality: IdentifierModality,
216    /// The view's content (spoken name, emblem description, etc.).
217    pub content: String,
218    /// Optional locale code (e.g. "en", "zh").
219    pub locale: Option<String>,
220}
221
222impl IdentifierView {
223    /// Creates a new `IdentifierView`.
224    pub fn new(iri: &str, modality: IdentifierModality, content: &str) -> Self {
225        Self {
226            iri: iri.into(),
227            modality,
228            content: content.into(),
229            locale: None,
230        }
231    }
232
233    /// Builder — sets locale.
234    pub fn with_locale(mut self, locale: &str) -> Self {
235        self.locale = Some(locale.into());
236        self
237    }
238
239    /// Converts to value.
240    pub fn to_value(&self) -> Value {
241        let mut rec = BTreeMap::new();
242        rec.insert("iri".into(), Value::String(self.iri.clone()));
243        rec.insert(
244            "modality".into(),
245            Value::String(self.modality.as_str().into()),
246        );
247        rec.insert("content".into(), Value::String(self.content.clone()));
248        if let Some(ref l) = self.locale {
249            rec.insert("locale".into(), Value::String(l.clone()));
250        }
251        Value::Record(rec)
252    }
253}
254
255// ── W14: Multi-scale / filtered sheaves ───────────────────────────────────────
256
257/// A level of detail (LOD) for multi-scale sheaves (W14).
258///
259/// The LOD is a physical scale, not a rendering parameter. Different
260/// scales reveal different structure.
261#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
262pub enum LevelOfDetail {
263    /// Continuum scale (macroscopic, field equations).
264    Continuum,
265    /// Mesoscopic scale (grain-level, homogenization).
266    Mesoscopic,
267    /// Molecular scale (individual molecules).
268    Molecular,
269    /// Atomic scale (individual atoms).
270    Atomic,
271    /// Subatomic scale (nucleons, quarks).
272    Subatomic,
273}
274
275impl LevelOfDetail {
276    /// `str` form.
277    pub fn as_str(&self) -> &'static str {
278        match self {
279            Self::Continuum => "continuum",
280            Self::Mesoscopic => "mesoscopic",
281            Self::Molecular => "molecular",
282            Self::Atomic => "atomic",
283            Self::Subatomic => "subatomic",
284        }
285    }
286
287    /// Constructs from str.
288    pub fn from_str(s: &str) -> Option<Self> {
289        match s {
290            "continuum" => Some(Self::Continuum),
291            "mesoscopic" => Some(Self::Mesoscopic),
292            "molecular" => Some(Self::Molecular),
293            "atomic" => Some(Self::Atomic),
294            "subatomic" => Some(Self::Subatomic),
295            _ => None,
296        }
297    }
298
299    /// Returns true if this LOD is coarser (larger scale) than `other`.
300    pub fn is_coarser_than(&self, other: &Self) -> bool {
301        self < other
302    }
303}
304
305/// A multi-scale sheaf filter — a sheaf viewed at a specific LOD (W14).
306#[derive(Debug, Clone, PartialEq)]
307pub struct MultiScaleSheaf {
308    /// The sheaf name/identifier.
309    pub sheaf_id: String,
310    /// The level of detail at which this sheaf is filtered.
311    pub lod: LevelOfDetail,
312    /// The scale parameter (e.g. characteristic length in meters).
313    pub scale: f64,
314    /// Whether this is the finest available LOD.
315    pub is_finest: bool,
316}
317
318impl MultiScaleSheaf {
319    /// Creates a new `MultiScaleSheaf`.
320    pub fn new(sheaf_id: &str, lod: LevelOfDetail, scale: f64) -> Self {
321        Self {
322            sheaf_id: sheaf_id.into(),
323            lod,
324            scale,
325            is_finest: false,
326        }
327    }
328
329    /// Finest observer resolution.
330    pub fn finest(sheaf_id: &str, lod: LevelOfDetail, scale: f64) -> Self {
331        Self {
332            sheaf_id: sheaf_id.into(),
333            lod,
334            scale,
335            is_finest: true,
336        }
337    }
338
339    /// Converts to value.
340    pub fn to_value(&self) -> Value {
341        let mut rec = BTreeMap::new();
342        rec.insert("sheaf_id".into(), Value::String(self.sheaf_id.clone()));
343        rec.insert("lod".into(), Value::String(self.lod.as_str().into()));
344        rec.insert("scale".into(), Value::F64(self.scale));
345        rec.insert("is_finest".into(), Value::Bool(self.is_finest));
346        Value::Record(rec)
347    }
348}
349
350// ── W15: Civic time + authority ───────────────────────────────────────────────
351
352/// A civic instant — time asserted by a civic authority (W15).
353///
354/// The authority is the metrology institute or time source that
355/// asserts the instant. This makes the provenance of time claims
356/// explicit — "NIST says it's 12:00" is different from "my local
357/// clock says it's 12:00".
358#[derive(Debug, Clone, PartialEq)]
359pub struct CivicInstant {
360    /// Unix seconds.
361    pub secs: i64,
362    /// Nanoseconds within the second.
363    pub nanos: u32,
364    /// The authority IRI that asserted this time (e.g.
365    /// "did:civic:nist", "did:civic:gps").
366    pub authority: String,
367    /// The uncertainty in the asserted time (nanoseconds).
368    pub uncertainty_nanos: Option<u64>,
369}
370
371impl CivicInstant {
372    /// Creates a new `CivicInstant`.
373    pub fn new(secs: i64, nanos: u32, authority: &str) -> Self {
374        Self {
375            secs,
376            nanos,
377            authority: authority.into(),
378            uncertainty_nanos: None,
379        }
380    }
381
382    /// Builder — sets uncertainty.
383    pub fn with_uncertainty(mut self, uncertainty_nanos: u64) -> Self {
384        self.uncertainty_nanos = Some(uncertainty_nanos);
385        self
386    }
387
388    /// Converts to value.
389    pub fn to_value(&self) -> Value {
390        let mut rec = BTreeMap::new();
391        rec.insert("secs".into(), Value::I64(self.secs));
392        rec.insert("nanos".into(), Value::U64(self.nanos as u64));
393        rec.insert("authority".into(), Value::String(self.authority.clone()));
394        if let Some(u) = self.uncertainty_nanos {
395            rec.insert("uncertainty_nanos".into(), Value::U64(u));
396        }
397        Value::Record(rec)
398    }
399}
400
401// ── T59: Agent characteristics KB ─────────────────────────────────────────────
402
403/// A characteristic of an agent, logged from behaviour (T59).
404#[derive(Debug, Clone, PartialEq)]
405pub struct AgentCharacteristic {
406    /// The agent's DID or IRI.
407    pub agent_id: String,
408    /// The characteristic name (e.g. "latency_p50_ms", "success_rate").
409    pub name: String,
410    /// The measured value.
411    pub value: f64,
412    /// When this characteristic was observed (Unix seconds).
413    pub observed_at: i64,
414    /// Number of observations that contributed to this value.
415    pub sample_count: u64,
416}
417
418impl AgentCharacteristic {
419    /// Creates a new `AgentCharacteristic`.
420    pub fn new(agent_id: &str, name: &str, value: f64, observed_at: i64) -> Self {
421        Self {
422            agent_id: agent_id.into(),
423            name: name.into(),
424            value,
425            observed_at,
426            sample_count: 1,
427        }
428    }
429
430    /// Builder — sets sample-count.
431    pub fn with_sample_count(mut self, count: u64) -> Self {
432        self.sample_count = count;
433        self
434    }
435
436    /// Converts to value.
437    pub fn to_value(&self) -> Value {
438        let mut rec = BTreeMap::new();
439        rec.insert("agent_id".into(), Value::String(self.agent_id.clone()));
440        rec.insert("name".into(), Value::String(self.name.clone()));
441        rec.insert("value".into(), Value::F64(self.value));
442        rec.insert("observed_at".into(), Value::I64(self.observed_at));
443        rec.insert("sample_count".into(), Value::U64(self.sample_count));
444        Value::Record(rec)
445    }
446}
447
448/// An agent characteristics KB — a log of agent characteristics
449/// observed from behaviour (T59).
450#[derive(Debug, Clone, Default)]
451pub struct AgentCharacteristicsKb {
452    entries: Vec<AgentCharacteristic>,
453}
454
455impl AgentCharacteristicsKb {
456    /// Creates a new `AgentCharacteristicsKb`.
457    pub fn new() -> Self {
458        Self::default()
459    }
460
461    /// Log a characteristic observation.
462    pub fn log(&mut self, entry: AgentCharacteristic) -> &mut Self {
463        self.entries.push(entry);
464        self
465    }
466
467    /// Get all characteristics for a given agent.
468    pub fn for_agent(&self, agent_id: &str) -> Vec<&AgentCharacteristic> {
469        self.entries
470            .iter()
471            .filter(|e| e.agent_id == agent_id)
472            .collect()
473    }
474
475    /// Get the latest value of a named characteristic for an agent.
476    pub fn latest(&self, agent_id: &str, name: &str) -> Option<&AgentCharacteristic> {
477        self.entries
478            .iter()
479            .filter(|e| e.agent_id == agent_id && e.name == name)
480            .max_by_key(|e| e.observed_at)
481    }
482
483    /// Get the mean value of a named characteristic for an agent.
484    pub fn mean(&self, agent_id: &str, name: &str) -> Option<f64> {
485        let matches: Vec<&AgentCharacteristic> = self
486            .entries
487            .iter()
488            .filter(|e| e.agent_id == agent_id && e.name == name)
489            .collect();
490        if matches.is_empty() {
491            return None;
492        }
493        let total: f64 = matches.iter().map(|e| e.value).sum();
494        Some(total / matches.len() as f64)
495    }
496
497    /// Number of entries.
498    pub fn len(&self) -> usize {
499        self.entries.len()
500    }
501
502    /// Is the KB empty?
503    pub fn is_empty(&self) -> bool {
504        self.entries.is_empty()
505    }
506
507    /// All entries as a List of Records.
508    pub fn to_value_list(&self) -> Value {
509        Value::List(self.entries.iter().map(|e| e.to_value()).collect())
510    }
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516
517    // ── W7: MeasurementContext tests ─────────────────────────────────
518
519    #[test]
520    fn w7_measurement_context_basic() {
521        let mc = MeasurementContext::new("did:alice", "sensor:therm-0", 1000);
522        assert_eq!(mc.observer, "did:alice");
523        assert_eq!(mc.instrument, "sensor:therm-0");
524        assert_eq!(mc.instant_secs, 1000);
525        assert_eq!(mc.instant_nanos, 0);
526        assert!(mc.frame.is_none());
527        assert!(mc.uncertainty.is_none());
528    }
529
530    #[test]
531    fn w7_measurement_context_with_options() {
532        let mc = MeasurementContext::new("did:bob", "sensor:accel-1", 2000)
533            .with_frame("frame:lab")
534            .with_uncertainty(0.01)
535            .with_stalk(42);
536        assert_eq!(mc.frame, Some("frame:lab".into()));
537        assert_eq!(mc.uncertainty, Some(0.01));
538        assert_eq!(mc.stalk_id, Some(42));
539    }
540
541    #[test]
542    fn w7_measurement_context_round_trip() {
543        let mc = MeasurementContext::new("did:alice", "sensor:therm-0", 1000)
544            .with_uncertainty(0.5)
545            .with_stalk(7);
546        let v = mc.to_value();
547        let restored = MeasurementContext::from_value(&v).unwrap();
548        assert_eq!(restored.observer, "did:alice");
549        assert_eq!(restored.instrument, "sensor:therm-0");
550        assert_eq!(restored.instant_secs, 1000);
551        assert_eq!(restored.uncertainty, Some(0.5));
552        assert_eq!(restored.stalk_id, Some(7));
553    }
554
555    #[test]
556    fn w7_measurement_context_from_non_record() {
557        let v = Value::I64(42);
558        assert!(MeasurementContext::from_value(&v).is_none());
559    }
560
561    // ── W9: IdentifierView tests ──────────────────────────────────────
562
563    #[test]
564    fn w9_identifier_modality_round_trip() {
565        for m in &[
566            IdentifierModality::Visual,
567            IdentifierModality::Oral,
568            IdentifierModality::Heraldic,
569            IdentifierModality::Tactile,
570        ] {
571            let s = m.as_str();
572            assert_eq!(IdentifierModality::from_str(s), Some(*m));
573        }
574        assert_eq!(IdentifierModality::from_str("unknown"), None);
575    }
576
577    #[test]
578    fn w9_identifier_view_basic() {
579        let v = IdentifierView::new("did:alice", IdentifierModality::Oral, "Alice");
580        assert_eq!(v.iri, "did:alice");
581        assert_eq!(v.modality, IdentifierModality::Oral);
582        assert_eq!(v.content, "Alice");
583        assert!(v.locale.is_none());
584    }
585
586    #[test]
587    fn w9_identifier_view_with_locale() {
588        let v =
589            IdentifierView::new("did:alice", IdentifierModality::Oral, "爱丽丝").with_locale("zh");
590        assert_eq!(v.locale, Some("zh".into()));
591    }
592
593    #[test]
594    fn w9_identifier_view_to_value() {
595        let v = IdentifierView::new("did:alice", IdentifierModality::Heraldic, "rose sigil")
596            .with_locale("en");
597        let val = v.to_value();
598        match &val {
599            Value::Record(r) => {
600                assert_eq!(r.len(), 4);
601                assert!(r.contains_key("iri"));
602                assert!(r.contains_key("modality"));
603                assert!(r.contains_key("content"));
604                assert!(r.contains_key("locale"));
605            }
606            _ => panic!("expected Record"),
607        }
608    }
609
610    // ── W14: MultiScaleSheaf tests ────────────────────────────────────
611
612    #[test]
613    fn w14_lod_round_trip() {
614        for l in &[
615            LevelOfDetail::Continuum,
616            LevelOfDetail::Mesoscopic,
617            LevelOfDetail::Molecular,
618            LevelOfDetail::Atomic,
619            LevelOfDetail::Subatomic,
620        ] {
621            let s = l.as_str();
622            assert_eq!(LevelOfDetail::from_str(s), Some(*l));
623        }
624    }
625
626    #[test]
627    fn w14_lod_ordering() {
628        assert!(LevelOfDetail::Continuum.is_coarser_than(&LevelOfDetail::Molecular));
629        assert!(LevelOfDetail::Molecular.is_coarser_than(&LevelOfDetail::Atomic));
630        assert!(!LevelOfDetail::Atomic.is_coarser_than(&LevelOfDetail::Continuum));
631    }
632
633    #[test]
634    fn w14_multi_scale_sheaf_basic() {
635        let s = MultiScaleSheaf::new("sheaf:fluid", LevelOfDetail::Continuum, 1.0);
636        assert_eq!(s.sheaf_id, "sheaf:fluid");
637        assert_eq!(s.lod, LevelOfDetail::Continuum);
638        assert_eq!(s.scale, 1.0);
639        assert!(!s.is_finest);
640    }
641
642    #[test]
643    fn w14_multi_scale_sheaf_finest() {
644        let s = MultiScaleSheaf::finest("sheaf:fluid", LevelOfDetail::Atomic, 1e-10);
645        assert!(s.is_finest);
646    }
647
648    #[test]
649    fn w14_multi_scale_sheaf_to_value() {
650        let s = MultiScaleSheaf::new("sheaf:fluid", LevelOfDetail::Molecular, 1e-9);
651        let v = s.to_value();
652        match &v {
653            Value::Record(r) => {
654                assert_eq!(r.len(), 4);
655                assert!(r.contains_key("sheaf_id"));
656                assert!(r.contains_key("lod"));
657                assert!(r.contains_key("scale"));
658                assert!(r.contains_key("is_finest"));
659            }
660            _ => panic!("expected Record"),
661        }
662    }
663
664    // ── W15: CivicInstant tests ───────────────────────────────────────
665
666    #[test]
667    fn w15_civic_instant_basic() {
668        let ci = CivicInstant::new(1000, 500_000_000, "did:civic:nist");
669        assert_eq!(ci.secs, 1000);
670        assert_eq!(ci.nanos, 500_000_000);
671        assert_eq!(ci.authority, "did:civic:nist");
672        assert!(ci.uncertainty_nanos.is_none());
673    }
674
675    #[test]
676    fn w15_civic_instant_with_uncertainty() {
677        let ci = CivicInstant::new(1000, 0, "did:civic:gps").with_uncertainty(100);
678        assert_eq!(ci.uncertainty_nanos, Some(100));
679    }
680
681    #[test]
682    fn w15_civic_instant_to_value() {
683        let ci = CivicInstant::new(2000, 0, "did:civic:nist").with_uncertainty(50);
684        let v = ci.to_value();
685        match &v {
686            Value::Record(r) => {
687                assert_eq!(r.len(), 4);
688                assert!(r.contains_key("secs"));
689                assert!(r.contains_key("nanos"));
690                assert!(r.contains_key("authority"));
691                assert!(r.contains_key("uncertainty_nanos"));
692            }
693            _ => panic!("expected Record"),
694        }
695    }
696
697    // ── T59: AgentCharacteristicsKb tests ─────────────────────────────
698
699    #[test]
700    fn t59_agent_characteristic_basic() {
701        let c = AgentCharacteristic::new("did:agent-1", "latency_p50_ms", 42.5, 1000);
702        assert_eq!(c.agent_id, "did:agent-1");
703        assert_eq!(c.name, "latency_p50_ms");
704        assert_eq!(c.value, 42.5);
705        assert_eq!(c.sample_count, 1);
706    }
707
708    #[test]
709    fn t59_agent_characteristic_with_sample_count() {
710        let c = AgentCharacteristic::new("did:agent-1", "success_rate", 0.95, 1000)
711            .with_sample_count(100);
712        assert_eq!(c.sample_count, 100);
713    }
714
715    #[test]
716    fn t59_kb_log_and_query() {
717        let mut kb = AgentCharacteristicsKb::new();
718        kb.log(AgentCharacteristic::new(
719            "did:agent-1",
720            "latency_ms",
721            42.0,
722            1000,
723        ));
724        kb.log(AgentCharacteristic::new(
725            "did:agent-1",
726            "latency_ms",
727            38.0,
728            2000,
729        ));
730        kb.log(AgentCharacteristic::new(
731            "did:agent-2",
732            "latency_ms",
733            55.0,
734            1000,
735        ));
736        assert_eq!(kb.len(), 3);
737        let a1 = kb.for_agent("did:agent-1");
738        assert_eq!(a1.len(), 2);
739        let a2 = kb.for_agent("did:agent-2");
740        assert_eq!(a2.len(), 1);
741    }
742
743    #[test]
744    fn t59_kb_latest() {
745        let mut kb = AgentCharacteristicsKb::new();
746        kb.log(AgentCharacteristic::new(
747            "did:agent-1",
748            "latency_ms",
749            42.0,
750            1000,
751        ));
752        kb.log(AgentCharacteristic::new(
753            "did:agent-1",
754            "latency_ms",
755            38.0,
756            2000,
757        ));
758        kb.log(AgentCharacteristic::new(
759            "did:agent-1",
760            "latency_ms",
761            40.0,
762            1500,
763        ));
764        let latest = kb.latest("did:agent-1", "latency_ms").unwrap();
765        assert_eq!(latest.value, 38.0);
766        assert_eq!(latest.observed_at, 2000);
767    }
768
769    #[test]
770    fn t59_kb_mean() {
771        let mut kb = AgentCharacteristicsKb::new();
772        kb.log(AgentCharacteristic::new(
773            "did:agent-1",
774            "latency_ms",
775            40.0,
776            1000,
777        ));
778        kb.log(AgentCharacteristic::new(
779            "did:agent-1",
780            "latency_ms",
781            60.0,
782            2000,
783        ));
784        let mean = kb.mean("did:agent-1", "latency_ms").unwrap();
785        assert!((mean - 50.0).abs() < 1e-9);
786    }
787
788    #[test]
789    fn t59_kb_latest_missing() {
790        let kb = AgentCharacteristicsKb::new();
791        assert!(kb.latest("did:unknown", "anything").is_none());
792    }
793
794    #[test]
795    fn t59_kb_mean_missing() {
796        let kb = AgentCharacteristicsKb::new();
797        assert!(kb.mean("did:unknown", "anything").is_none());
798    }
799
800    #[test]
801    fn t59_kb_empty() {
802        let kb = AgentCharacteristicsKb::new();
803        assert!(kb.is_empty());
804        assert_eq!(kb.len(), 0);
805    }
806
807    #[test]
808    fn t59_kb_to_value_list() {
809        let mut kb = AgentCharacteristicsKb::new();
810        kb.log(AgentCharacteristic::new(
811            "did:agent-1",
812            "latency_ms",
813            42.0,
814            1000,
815        ));
816        let v = kb.to_value_list();
817        match &v {
818            Value::List(xs) => assert_eq!(xs.len(), 1),
819            _ => panic!("expected List"),
820        }
821    }
822}