1use crate::value::Value;
7use std::collections::BTreeMap;
8
9#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct AffectiveStatus {
12 pub safety_threat_index: f32,
14 pub emotional_valence: f32,
16 pub arousal_level: f32,
18 pub dissociation_index: f32,
20 pub trauma_reactivity: f32,
22}
23
24impl Default for AffectiveStatus {
25 fn default() -> Self {
26 Self {
27 safety_threat_index: 0.0,
28 emotional_valence: 0.0,
29 arousal_level: 0.5,
30 dissociation_index: 0.0,
31 trauma_reactivity: 0.0,
32 }
33 }
34}
35
36impl AffectiveStatus {
37 pub fn clamped(&self) -> Self {
39 Self {
40 safety_threat_index: self.safety_threat_index.clamp(-1.0, 1.0),
41 emotional_valence: self.emotional_valence.clamp(-1.0, 1.0),
42 arousal_level: self.arousal_level.clamp(0.0, 1.0),
43 dissociation_index: self.dissociation_index.clamp(0.0, 1.0),
44 trauma_reactivity: self.trauma_reactivity.clamp(0.0, 1.0),
45 }
46 }
47
48 pub fn is_hyper_vigilant(&self) -> bool {
54 self.safety_threat_index < -0.8
55 || self.arousal_level > 0.9
56 || (self.arousal_level >= 0.9 && self.trauma_reactivity > 0.0)
57 }
58
59 pub fn to_value(&self) -> Value {
61 let mut rec = BTreeMap::new();
62 rec.insert(
63 "safety_threat_index".into(),
64 Value::F64(self.safety_threat_index as f64),
65 );
66 rec.insert(
67 "emotional_valence".into(),
68 Value::F64(self.emotional_valence as f64),
69 );
70 rec.insert(
71 "arousal_level".into(),
72 Value::F64(self.arousal_level as f64),
73 );
74 rec.insert(
75 "dissociation_index".into(),
76 Value::F64(self.dissociation_index as f64),
77 );
78 rec.insert(
79 "trauma_reactivity".into(),
80 Value::F64(self.trauma_reactivity as f64),
81 );
82 Value::Record(rec)
83 }
84}
85
86#[derive(Debug, Clone, PartialEq)]
88pub struct DoxasticBelief {
89 pub proposition_iri: String,
90 pub mu: f32,
92 pub lambda: f32,
94}
95
96impl DoxasticBelief {
97 pub fn to_value(&self) -> Value {
99 let mut rec = BTreeMap::new();
100 rec.insert(
101 "proposition_iri".into(),
102 Value::String(self.proposition_iri.clone()),
103 );
104 rec.insert("mu".into(), Value::F64(self.mu as f64));
105 rec.insert("lambda".into(), Value::F64(self.lambda as f64));
106 Value::Record(rec)
107 }
108}
109
110#[derive(Debug, Clone, PartialEq)]
112pub struct CognitiveLens {
113 pub lens_id: String,
114 pub sensory_acuity: f32,
116 pub worldview_filter: bool,
118}
119
120impl Default for CognitiveLens {
121 fn default() -> Self {
122 Self {
123 lens_id: "default".into(),
124 sensory_acuity: 1.0,
125 worldview_filter: false,
126 }
127 }
128}
129
130#[derive(Debug, Clone)]
137pub struct ObserverFiber {
138 pub observer_did: String,
139 pub semantic_cohort: Option<String>,
140 pub affective_state: AffectiveStatus,
141 pub epistemic_beliefs: Vec<DoxasticBelief>,
142 pub cognitive_lens: CognitiveLens,
143 pub perceived_frame_usi: String,
144 pub shared_anchor_id: Option<u64>,
146 pub shared_anchor_var: f64,
148 pub local_chart_var: f64,
150}
151
152impl ObserverFiber {
153 pub fn new(observer_did: &str, perceived_frame: &str) -> Self {
155 Self {
156 observer_did: observer_did.into(),
157 semantic_cohort: None,
158 affective_state: AffectiveStatus::default(),
159 epistemic_beliefs: Vec::new(),
160 cognitive_lens: CognitiveLens::default(),
161 perceived_frame_usi: perceived_frame.into(),
162 shared_anchor_id: None,
163 shared_anchor_var: 0.0,
164 local_chart_var: 0.0,
165 }
166 }
167
168 pub fn with_correlated_uncertainty(
170 mut self,
171 shared_anchor_id: u64,
172 shared_anchor_var: f64,
173 local_chart_var: f64,
174 ) -> Self {
175 self.shared_anchor_id = Some(shared_anchor_id);
176 self.shared_anchor_var = shared_anchor_var.max(0.0);
177 self.local_chart_var = local_chart_var.max(0.0);
178 self
179 }
180
181 pub fn is_hyper_vigilant(&self) -> bool {
183 self.affective_state.safety_threat_index < -0.8
184 || self.affective_state.arousal_level > 0.9
185 || self.affective_state.is_hyper_vigilant()
186 }
187
188 pub fn total_positional_variance(&self) -> f64 {
190 self.shared_anchor_var.max(0.0) + self.local_chart_var.max(0.0)
191 }
192
193 pub fn relative_displacement_variance(&self, other: &Self) -> f64 {
199 let local_sum = self.local_chart_var.max(0.0) + other.local_chart_var.max(0.0);
200 match (self.shared_anchor_id, other.shared_anchor_id) {
201 (Some(a), Some(b)) if a == b => local_sum,
202 _ => local_sum + self.shared_anchor_var.max(0.0) + other.shared_anchor_var.max(0.0),
203 }
204 }
205
206 pub fn relative_displacement_std(&self, other: &Self) -> f64 {
208 self.relative_displacement_variance(other).sqrt()
209 }
210
211 pub fn check_presheaf_overlap(
220 &self,
221 other: &Self,
222 max_belief_divergence: f32,
223 ) -> Result<(), String> {
224 if let (Some(a), Some(b)) = (self.shared_anchor_id, other.shared_anchor_id) {
225 if a == b {
226 let diff = (self.shared_anchor_var - other.shared_anchor_var).abs();
227 let scale = self
228 .shared_anchor_var
229 .abs()
230 .max(other.shared_anchor_var.abs())
231 .max(1.0);
232 if diff / scale > 1e-3 {
233 return Err(format!(
234 "Presheaf overlap mismatch on shared_anchor_id {}: anchor variance {} vs {}",
235 a, self.shared_anchor_var, other.shared_anchor_var
236 ));
237 }
238 }
239 }
240
241 for b1 in &self.epistemic_beliefs {
242 if let Some(b2) = other
243 .epistemic_beliefs
244 .iter()
245 .find(|cand| cand.proposition_iri == b1.proposition_iri)
246 {
247 let d_mu = (b1.mu - b2.mu).abs();
248 let d_lambda = (b1.lambda - b2.lambda).abs();
249 if d_mu > max_belief_divergence || d_lambda > max_belief_divergence {
250 return Err(format!(
251 "Presheaf section conflict on proposition '{}': (mu={}, lambda={}) vs (mu={}, lambda={})",
252 b1.proposition_iri, b1.mu, b1.lambda, b2.mu, b2.lambda
253 ));
254 }
255 }
256 }
257 Ok(())
258 }
259
260 pub fn merge_presheaf_compatible(
265 &self,
266 other: &Self,
267 max_belief_divergence: f32,
268 ) -> Result<ObserverFiber, String> {
269 self.check_presheaf_overlap(other, max_belief_divergence)?;
270
271 let mut merged_beliefs = self.epistemic_beliefs.clone();
272 for b2 in &other.epistemic_beliefs {
273 if let Some(existing) = merged_beliefs
274 .iter_mut()
275 .find(|cand| cand.proposition_iri == b2.proposition_iri)
276 {
277 existing.mu = 0.5 * (existing.mu + b2.mu);
278 existing.lambda = 0.5 * (existing.lambda + b2.lambda);
279 } else {
280 merged_beliefs.push(b2.clone());
281 }
282 }
283
284 let merged_local_var = if self.local_chart_var > 0.0 && other.local_chart_var > 0.0 {
285 1.0 / (1.0 / self.local_chart_var + 1.0 / other.local_chart_var)
286 } else {
287 self.local_chart_var.max(other.local_chart_var)
288 };
289
290 Ok(ObserverFiber {
291 observer_did: self.observer_did.clone(),
292 semantic_cohort: self
293 .semantic_cohort
294 .clone()
295 .or_else(|| other.semantic_cohort.clone()),
296 affective_state: self.affective_state,
297 epistemic_beliefs: merged_beliefs,
298 cognitive_lens: self.cognitive_lens.clone(),
299 perceived_frame_usi: self.perceived_frame_usi.clone(),
300 shared_anchor_id: self.shared_anchor_id.or(other.shared_anchor_id),
301 shared_anchor_var: self.shared_anchor_var.max(other.shared_anchor_var),
302 local_chart_var: merged_local_var,
303 })
304 }
305
306 pub fn epistemic_divergence(
312 &self,
313 empirical_frame_coords: &[f64],
314 perceived_coords: &[f64],
315 ) -> f64 {
316 if empirical_frame_coords.len() != perceived_coords.len() {
317 return f64::INFINITY;
318 }
319 let sum_sq: f64 = empirical_frame_coords
320 .iter()
321 .zip(perceived_coords.iter())
322 .map(|(e, p)| {
323 let d = e - p;
324 d * d
325 })
326 .sum();
327 let base = sum_sq.sqrt();
328 let weight = 1.0
330 + self.affective_state.dissociation_index as f64
331 + self.affective_state.trauma_reactivity as f64;
332 base * weight
333 }
334
335 pub fn needs_grounding(&self) -> bool {
337 self.is_hyper_vigilant() || self.affective_state.dissociation_index >= 0.7
338 }
339
340 pub fn to_epistemic_claim_record(&self) -> Value {
344 let mut rec = BTreeMap::new();
345 rec.insert("plane".into(), Value::String("ClaimOpinion".into()));
346 rec.insert(
347 "observer_handle".into(),
348 Value::String(self.observer_did.clone()),
349 );
350 rec.insert(
351 "perceived_frame_usi".into(),
352 Value::String(self.perceived_frame_usi.clone()),
353 );
354 rec.insert(
355 "is_hyper_vigilant".into(),
356 Value::Bool(self.is_hyper_vigilant()),
357 );
358 rec.insert(
359 "needs_grounding".into(),
360 Value::Bool(self.needs_grounding()),
361 );
362 rec.insert("affective_state".into(), self.affective_state.to_value());
363 rec.insert(
364 "beliefs".into(),
365 Value::List(
366 self.epistemic_beliefs
367 .iter()
368 .map(DoxasticBelief::to_value)
369 .collect(),
370 ),
371 );
372 rec.insert(
373 "shared_anchor_var".into(),
374 Value::F64(self.shared_anchor_var),
375 );
376 rec.insert("local_chart_var".into(), Value::F64(self.local_chart_var));
377 Value::Record(rec)
378 }
379
380 pub fn to_value(&self) -> Value {
382 let mut rec = BTreeMap::new();
383 rec.insert(
384 "observer_did".into(),
385 Value::String(self.observer_did.clone()),
386 );
387 if let Some(cohort) = &self.semantic_cohort {
388 rec.insert("semantic_cohort".into(), Value::String(cohort.clone()));
389 }
390 rec.insert("affective_state".into(), self.affective_state.to_value());
391 rec.insert(
392 "perceived_frame_usi".into(),
393 Value::String(self.perceived_frame_usi.clone()),
394 );
395 Value::Record(rec)
396 }
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 #[test]
404 fn default_affective_is_neutral() {
405 let a = AffectiveStatus::default();
406 assert_eq!(a.safety_threat_index, 0.0);
407 assert_eq!(a.emotional_valence, 0.0);
408 assert_eq!(a.arousal_level, 0.5);
409 }
410
411 #[test]
412 fn hyper_vigilant_detection() {
413 let threat = AffectiveStatus {
415 safety_threat_index: -0.9,
416 ..Default::default()
417 };
418 assert!(threat.is_hyper_vigilant());
419
420 let high_arousal = AffectiveStatus {
422 arousal_level: 0.95,
423 ..Default::default()
424 };
425 assert!(high_arousal.is_hyper_vigilant());
426
427 let safe = AffectiveStatus {
429 safety_threat_index: 0.9,
430 ..Default::default()
431 };
432 assert!(!safe.is_hyper_vigilant());
433 }
434
435 #[test]
436 fn not_hyper_vigilant() {
437 let a = AffectiveStatus::default();
438 assert!(!a.is_hyper_vigilant());
439 }
440
441 #[test]
442 fn affective_clamp() {
443 let a = AffectiveStatus {
444 safety_threat_index: 5.0,
445 emotional_valence: -3.0,
446 arousal_level: 2.0,
447 dissociation_index: -1.0,
448 trauma_reactivity: 10.0,
449 };
450 let c = a.clamped();
451 assert_eq!(c.safety_threat_index, 1.0);
452 assert_eq!(c.emotional_valence, -1.0);
453 assert_eq!(c.arousal_level, 1.0);
454 assert_eq!(c.dissociation_index, 0.0);
455 assert_eq!(c.trauma_reactivity, 1.0);
456 }
457
458 #[test]
459 fn epistemic_divergence_zero() {
460 let obs = ObserverFiber::new("did:q42:person:test", "urn:omni:v1:phenomenology:test");
461 let coords = [1.0, 2.0, 3.0];
462 let d = obs.epistemic_divergence(&coords, &coords);
463 assert!(d.abs() < 1e-10);
464 }
465
466 #[test]
467 fn epistemic_divergence_nonzero() {
468 let obs = ObserverFiber::new("did:q42:person:test", "urn:omni:v1:phenomenology:test");
469 let empirical = [0.0, 0.0, 0.0];
470 let perceived = [3.0, 4.0, 0.0]; let d = obs.epistemic_divergence(&empirical, &perceived);
472 assert!((d - 5.0).abs() < 1e-10, "got {} expected 5.0", d);
473 }
474
475 #[test]
476 fn epistemic_divergence_weighted_by_dissociation() {
477 let mut obs = ObserverFiber::new("did:q42:person:test", "urn:omni:v1:phenomenology:test");
478 obs.affective_state.dissociation_index = 1.0;
479 let empirical = [0.0, 0.0, 0.0];
480 let perceived = [3.0, 4.0, 0.0]; let d = obs.epistemic_divergence(&empirical, &perceived);
482 assert!((d - 10.0).abs() < 1e-10, "got {} expected 10.0", d);
484 }
485
486 #[test]
487 fn needs_grounding_hyper_vigilant() {
488 let mut obs = ObserverFiber::new("did:q42:person:test", "frame");
489 obs.affective_state.safety_threat_index = -0.9;
490 assert!(obs.is_hyper_vigilant());
491 assert!(obs.needs_grounding());
492 }
493
494 #[test]
495 fn needs_grounding_dissociation() {
496 let mut obs = ObserverFiber::new("did:q42:person:test", "frame");
497 obs.affective_state.dissociation_index = 0.8;
498 assert!(obs.needs_grounding());
499 }
500
501 #[test]
502 fn correlated_anchor_variance_cancels_for_shared_anchor() {
503 let obs_a = ObserverFiber::new("did:q42:obs:a", "urn:omni:v1:phenomenology:a")
507 .with_correlated_uncertainty(42, 1.0e12, 1.0e-6);
508 let obs_b = ObserverFiber::new("did:q42:obs:b", "urn:omni:v1:phenomenology:b")
509 .with_correlated_uncertainty(42, 1.0e12, 1.0e-6);
510 let obs_unshared = ObserverFiber::new("did:q42:obs:c", "urn:omni:v1:phenomenology:c")
511 .with_correlated_uncertainty(99, 1.0e12, 1.0e-6);
512
513 let rel_var_shared = obs_a.relative_displacement_variance(&obs_b);
514 assert!(
515 (rel_var_shared - 2.0e-6).abs() < 1e-12,
516 "shared anchor variance must cancel: got {}",
517 rel_var_shared
518 );
519 assert!((obs_a.relative_displacement_std(&obs_b) - (2.0e-6_f64).sqrt()).abs() < 1e-9);
520
521 let rel_var_unshared = obs_a.relative_displacement_variance(&obs_unshared);
522 assert!(rel_var_unshared > 1.9e12);
523 }
524
525 #[test]
526 fn presheaf_overlap_compatibility_and_epistemic_claim_projection() {
527 let mut obs_a = ObserverFiber::new("did:q42:obs:a", "urn:omni:v1:phenomenology:a")
528 .with_correlated_uncertainty(7, 100.0, 0.04);
529 obs_a.epistemic_beliefs.push(DoxasticBelief {
530 proposition_iri: "urn:qualia:prop:door-locked".into(),
531 mu: 0.85,
532 lambda: 0.05,
533 });
534
535 let mut obs_b = ObserverFiber::new("did:q42:obs:b", "urn:omni:v1:phenomenology:b")
536 .with_correlated_uncertainty(7, 100.0, 0.04);
537 obs_b.epistemic_beliefs.push(DoxasticBelief {
538 proposition_iri: "urn:qualia:prop:door-locked".into(),
539 mu: 0.80,
540 lambda: 0.08,
541 });
542
543 let merged = obs_a.merge_presheaf_compatible(&obs_b, 0.10).unwrap();
544 assert_eq!(merged.epistemic_beliefs.len(), 1);
545 assert!((merged.local_chart_var - 0.02).abs() < 1e-9);
546
547 let mut obs_conflict = obs_b.clone();
549 obs_conflict.epistemic_beliefs[0].mu = 0.10;
550 obs_conflict.epistemic_beliefs[0].lambda = 0.85;
551 assert!(obs_a.merge_presheaf_compatible(&obs_conflict, 0.10).is_err());
552
553 let claim = obs_a.to_epistemic_claim_record();
555 match claim {
556 Value::Record(r) => {
557 assert_eq!(
558 r.get("plane"),
559 Some(&Value::String("ClaimOpinion".into()))
560 );
561 assert_eq!(
562 r.get("observer_handle"),
563 Some(&Value::String("did:q42:obs:a".into()))
564 );
565 }
566 _ => panic!("expected ClaimOpinion Record"),
567 }
568 }
569
570 #[test]
571 fn observer_to_value() {
572 let obs = ObserverFiber::new("did:q42:person:alice", "urn:omni:v1:phenomenology:alice");
573 let v = obs.to_value();
574 match v {
575 Value::Record(r) => {
576 assert_eq!(
577 r.get("observer_did"),
578 Some(&Value::String("did:q42:person:alice".into()))
579 );
580 assert!(r.contains_key("affective_state"));
581 }
582 _ => panic!("expected Record"),
583 }
584 }
585
586 #[test]
587 fn affective_to_value() {
588 let a = AffectiveStatus::default();
589 let v = a.to_value();
590 match v {
591 Value::Record(r) => {
592 assert!(r.contains_key("safety_threat_index"));
593 assert!(r.contains_key("emotional_valence"));
594 }
595 _ => panic!("expected Record"),
596 }
597 }
598}