daemonic_error 0.1.0

Errors that compose, predict, and leave receipts - Compose: algebraic combination (in active development) - Predict: Glass/Severity - Receipts: audit trail, position, checksum - Reflection: Runtime Reflection through TopologySegment (in active development)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
// ═══════════════════════════════════════════════════════════════
// DAEMONIC CONTRACT RESULT MODULE
// ═══════════════════════════════════════════════════════════════
//
// DaemonicResult is DEPRECATED. All returns are Glass<GLASS> objects.
// This module now contains:
//   - MirrorChemistry: bonding algebra for observations (PRESERVED)
//   - Repair system: enclosures, injections, crypto verification (NEW)
//   - Diagnostic/Subdiagnostic: compiler integration (PRESERVED, separate files)
//
// The old SeverityHandler is replaced by three separated concerns:
//   - SeverityRouter: where does this severity go?
//   - RepairAttempt: can this error be fixed?
//   - RepairContext: what resources are available for repair?

// ═══════════════════════════════════════════════════════════════
// MIRROR CHEMISTRY (preserved, updated imports)
// ═══════════════════════════════════════════════════════════════

pub(crate) mod mirror_chemistry {
	use bonding::*;
	use elements::*;
	use stability::*;
	use table::{compounds::*, *};
	use crate::Severity;
	
	pub(crate) mod elements {
		use alloc::vec::Vec;
		use crate::clock::types::DaemonicDuration;
		use super::*;
		
		/// SPECULAR — The noble gas of reflections
		/// Ground state. Minimum energy. Maximum stability.
		pub const SPECULAR: ReflectionProperties = ReflectionProperties {
			fidelity: Fidelity::Specular,
			temporality: Temporality::Instantaneous,
			spatiality: Spatiality::Identity,
			selectivity: Selectivity::Complete,
			energy_cost: EnergyCost::Minimal,
		};
		
		/// ABSORPTIVE — The black hole
		/// Maximum energy. Zero output. Artificial/constructed.
		pub const ABSORPTIVE: ReflectionProperties = ReflectionProperties {
			fidelity: Fidelity::Absorptive,
			temporality: Temporality::None,
			spatiality: Spatiality::Collapsed,
			selectivity: Selectivity::None,
			energy_cost: EnergyCost::Sustained(f64::MAX),
		};
		
		/// DELAYED — The echo
		/// Temporal offset. Memory primitive.
		pub fn delayed(offset: DaemonicDuration) -> ReflectionProperties {
			ReflectionProperties {
				fidelity: Fidelity::Specular,
				temporality: Temporality::Delayed(offset),
				spatiality: Spatiality::Inverted,
				selectivity: Selectivity::Complete,
				energy_cost: EnergyCost::Finite(offset.as_secs_f64()),
			}
		}
		
		/// INVERTED — Spatial flip only
		/// Standard physical mirror without other properties.
		pub const INVERTED: ReflectionProperties = ReflectionProperties {
			fidelity: Fidelity::Specular,
			temporality: Temporality::Instantaneous,
			spatiality: Spatiality::Inverted,
			selectivity: Selectivity::Complete,
			energy_cost: EnergyCost::Minimal,
		};
		
		/// TRANSFORMATIVE — Systematic change
		/// Encoding, compression, representation shift.
		pub fn transformative(
			transform: SpatialTransform,
			reversible: bool,
		) -> ReflectionProperties {
			ReflectionProperties {
				fidelity: if reversible {
					Fidelity::Specular
				} else {
					Fidelity::Lossy(0.5)
				},
				temporality: Temporality::Instantaneous,
				spatiality: Spatiality::Transformed(transform),
				selectivity: Selectivity::Complete,
				energy_cost: EnergyCost::Finite(1.0),
			}
		}
		
		/// SELECTIVE — Property filter
		/// Attention, focus, relevance.
		pub fn selective(properties: Vec<PropertyId>) -> ReflectionProperties {
			let cost = properties.len() as f64 * 0.1;
			ReflectionProperties {
				fidelity: Fidelity::Specular,
				temporality: Temporality::Instantaneous,
				spatiality: Spatiality::Inverted,
				selectivity: Selectivity::Partial(properties),
				energy_cost: EnergyCost::Finite(cost),
			}
		}
		
		/// PROPHETIC — Negative delay (unstable)
		/// ⚠️ WARNING: Crystallization risk. Requires prior walks.
		/// Approaches god logic. Use with extreme caution.
		/// Prophetic observations MUST carry confidence that decays
		/// over time without refresh. See RepairEnclosure::effective_confidence.
		pub fn prophetic(required_walks: u64) -> ReflectionProperties {
			ReflectionProperties {
				fidelity: Fidelity::Specular,
				temporality: Temporality::Prophetic {
					requires_prior_walks: required_walks,
				},
				spatiality: Spatiality::Inverted,
				selectivity: Selectivity::Complete,
				energy_cost: EnergyCost::Unbounded,
			}
		}
	}
	
	pub(crate) mod bonding {
		use alloc::vec::Vec;
		use alloc::boxed::Box;
		use core::ops::Add;
		use crate::clock::types::DaemonicDuration;
		use super::*;
		
		/// Result of attempting to combine two reflection types.
		/// Now carries provenance for unbonding support.
		#[derive(Debug)]
		pub enum BondResult {
			/// Successful combination
			Compound(ReflectionProperties, Option<BondProvenance>),
			/// One type dominates, other absorbed
			Dominated(ReflectionProperties, Option<BondProvenance>),
			/// Contradiction — cannot coexist
			Contradiction,
			/// Unstable — exists briefly then collapses
			Unstable(ReflectionProperties, DaemonicDuration, Option<BondProvenance>),
		}
		
		/// Provenance tracking for unbonding.
		/// Records what went in and in what order, enabling
		/// decomposition of compounds back into components.
		#[derive(Debug, Clone)]
		pub struct BondProvenance {
			pub first: Box<ReflectionProperties>,
			pub second: Box<ReflectionProperties>,
			/// Does the order of inputs matter for this bond?
			/// true = non-commutative (spatially transformed bonds)
			/// false = commutative (energy, fidelity bonds)
			pub order_matters: bool,
		}
		
		impl Add for DaemonicDuration {
			type Output = u64;
			
			fn add(self, rhs: Self) -> Self::Output {
				let x = self;
				x.as_u64() + rhs.as_u64()
			}
		}
		
		/// Attempt to combine two reflection types
		pub fn combine(
			a: &ReflectionProperties,
			b: &ReflectionProperties,
		) -> BondResult {
			let provenance = BondProvenance {
				first: Box::new(a.clone()),
				second: Box::new(b.clone()),
				order_matters: !is_commutative(a, b),
			};
			
			// Rule 1: Absorptive dominates almost everything
			if a.fidelity == Fidelity::Absorptive {
				if b.fidelity == Fidelity::Specular {
					return BondResult::Contradiction;
				}
				return BondResult::Dominated(a.clone(), Some(provenance));
			}
			if b.fidelity == Fidelity::Absorptive {
				if a.fidelity == Fidelity::Specular {
					return BondResult::Contradiction;
				}
				return BondResult::Dominated(b.clone(), Some(provenance));
			}
			
			// Rule 2: Specular is identity element
			if *a == super::elements::SPECULAR {
				return BondResult::Compound(b.clone(), Some(provenance));
			}
			if *b == super::elements::SPECULAR {
				return BondResult::Compound(a.clone(), Some(provenance));
			}
			
			// Rule 3: Delays stack additively
			if let (Temporality::Delayed(t1), Temporality::Delayed(t2)) =
				(&a.temporality, &b.temporality)
			{
				let mut compound = a.clone();
				compound.temporality = Temporality::Delayed(DaemonicDuration::from(*t1 + *t2));
				compound.energy_cost = stack_energy(&a.energy_cost, &b.energy_cost);
				return BondResult::Compound(compound, Some(provenance));
			}
			
			// Rule 4: Prophetic + anything else = unstable
			if matches!(a.temporality, Temporality::Prophetic { .. })
				|| matches!(b.temporality, Temporality::Prophetic { .. })
			{
				let compound = combine_properties(a, b);
				return BondResult::Unstable(
					compound,
					DaemonicDuration::from(100),
					Some(provenance),
				);
			}
			
			// Rule 5: Selectivity intersects
			let combined_selectivity = intersect_selectivity(&a.selectivity, &b.selectivity);
			
			// Default: combine properties, stack energy
			let mut compound = combine_properties(a, b);
			compound.selectivity = combined_selectivity;
			BondResult::Compound(compound, Some(provenance))
		}
		
		/// Attempt to unbond a compound back into its components.
		/// Only possible if provenance was recorded during bonding.
		pub fn unbond(provenance: &BondProvenance) -> (ReflectionProperties, ReflectionProperties) {
			if provenance.order_matters {
				(*provenance.first.clone(), *provenance.second.clone())
			} else {
				// Commutative: order doesn't matter, return as stored
				(*provenance.first.clone(), *provenance.second.clone())
			}
		}
		
		/// Check if combining a and b is commutative
		fn is_commutative(a: &ReflectionProperties, b: &ReflectionProperties) -> bool {
			// Spatiality transforms may not commute
			if matches!(a.spatiality, Spatiality::Transformed(_))
				|| matches!(b.spatiality, Spatiality::Transformed(_))
			{
				return false;
			}
			// Everything else is commutative
			true
		}
		
		fn intersect_selectivity(a: &Selectivity, b: &Selectivity) -> Selectivity {
			match (a, b) {
				(Selectivity::Complete, s) | (s, Selectivity::Complete) => s.clone(),
				(Selectivity::None, _) | (_, Selectivity::None) => Selectivity::None,
				(Selectivity::Partial(p1), Selectivity::Partial(p2)) => {
					let intersection: Vec<_> =
						p1.iter().filter(|x| p2.contains(x)).copied().collect();
					if intersection.is_empty() {
						Selectivity::None
					} else {
						Selectivity::Partial(intersection)
					}
				}
				(Selectivity::Single(s1), Selectivity::Single(s2)) => {
					if s1 == s2 { Selectivity::Single(*s1) } else { Selectivity::None }
				}
				(Selectivity::Single(s), Selectivity::Partial(p))
				| (Selectivity::Partial(p), Selectivity::Single(s)) => {
					if p.contains(s) { Selectivity::Single(*s) } else { Selectivity::None }
				}
			}
		}
		
		fn combine_properties(a: &ReflectionProperties, b: &ReflectionProperties) -> ReflectionProperties {
			ReflectionProperties {
				fidelity: combine_fidelity(&a.fidelity, &b.fidelity),
				temporality: combine_temporality(&a.temporality, &b.temporality),
				spatiality: combine_spatiality(&a.spatiality, &b.spatiality),
				selectivity: Selectivity::Complete, // Overwritten by caller
				energy_cost: stack_energy(&a.energy_cost, &b.energy_cost),
			}
		}
		
		fn combine_fidelity(a: &Fidelity, b: &Fidelity) -> Fidelity {
			match (a, b) {
				(Fidelity::Absorptive, _) | (_, Fidelity::Absorptive) => Fidelity::Absorptive,
				(Fidelity::Destructive, _) | (_, Fidelity::Destructive) => Fidelity::Destructive,
				(Fidelity::Lossy(x), Fidelity::Lossy(y)) => Fidelity::Lossy(x * y),
				(Fidelity::Lossy(x), Fidelity::Specular)
				| (Fidelity::Specular, Fidelity::Lossy(x)) => Fidelity::Lossy(*x),
				(Fidelity::Specular, Fidelity::Specular) => Fidelity::Specular,
			}
		}
		
		fn combine_temporality(a: &Temporality, b: &Temporality) -> Temporality {
			match (a, b) {
				(Temporality::None, _) | (_, Temporality::None) => Temporality::None,
				(Temporality::Instantaneous, t) | (t, Temporality::Instantaneous) => t.clone(),
				(Temporality::Delayed(t1), Temporality::Delayed(t2)) => {
					Temporality::Delayed(DaemonicDuration::from(*t1 + *t2))
				}
				_ => Temporality::Variable {
					min: DaemonicDuration::zero(),
					max: DaemonicDuration::from_secs(1),
				},
			}
		}
		
		fn combine_spatiality(a: &Spatiality, b: &Spatiality) -> Spatiality {
			match (a, b) {
				(Spatiality::Collapsed, _) | (_, Spatiality::Collapsed) => Spatiality::Collapsed,
				(Spatiality::Identity, s) | (s, Spatiality::Identity) => s.clone(),
				(Spatiality::Inverted, Spatiality::Inverted) => Spatiality::Identity,
				_ => a.clone(),
			}
		}
		
		fn stack_energy(a: &EnergyCost, b: &EnergyCost) -> EnergyCost {
			match (a, b) {
				(EnergyCost::Unbounded, _) | (_, EnergyCost::Unbounded) => EnergyCost::Unbounded,
				(EnergyCost::Minimal, e) | (e, EnergyCost::Minimal) => e.clone(),
				(EnergyCost::Finite(x), EnergyCost::Finite(y)) => EnergyCost::Finite(x + y),
				(EnergyCost::Sustained(x), EnergyCost::Sustained(y)) => EnergyCost::Sustained(x + y),
				(EnergyCost::Finite(x), EnergyCost::Sustained(y))
				| (EnergyCost::Sustained(y), EnergyCost::Finite(x)) => EnergyCost::Sustained(x + y),
			}
		}
	}
	
	pub(crate) mod stability {
		use crate::clock::types::DaemonicDuration;
		use alloc::boxed::Box;
		use super::*;
		
		#[derive(Debug)]
		pub enum Stability {
			Stable,
			Metastable { perturbation_threshold: f64 },
			Unstable {
				decay_to: Box<ReflectionProperties>,
				half_life: DaemonicDuration,
			},
			Impossible,
		}
		
		pub fn assess(props: &ReflectionProperties) -> Stability {
			if *props == super::elements::SPECULAR {
				return Stability::Stable;
			}
			if is_contradictory(props) {
				return Stability::Impossible;
			}
			if matches!(props.temporality, Temporality::Prophetic { .. }) {
				return Stability::Unstable {
					decay_to: Box::new(super::elements::SPECULAR.clone()),
					half_life: DaemonicDuration::from(50),
				};
			}
			if props.fidelity == Fidelity::Absorptive {
				if !matches!(props.energy_cost, EnergyCost::Sustained(_)) {
					return Stability::Unstable {
						decay_to: Box::new(super::elements::SPECULAR.clone()),
						half_life: DaemonicDuration::from_secs(1),
					};
				}
				return Stability::Metastable { perturbation_threshold: 0.1 };
			}
			match &props.energy_cost {
				EnergyCost::Minimal => Stability::Stable,
				EnergyCost::Finite(e) if *e < 1.0 => Stability::Stable,
				EnergyCost::Finite(e) if *e < 10.0 => Stability::Metastable {
					perturbation_threshold: 1.0 / e,
				},
				EnergyCost::Finite(_) => Stability::Unstable {
					decay_to: Box::new(super::elements::SPECULAR.clone()),
					half_life: DaemonicDuration::from_secs(10),
				},
				EnergyCost::Sustained(e) if *e < 100.0 => Stability::Metastable {
					perturbation_threshold: 1.0 / e,
				},
				EnergyCost::Sustained(_) => Stability::Unstable {
					decay_to: Box::new(super::elements::SPECULAR.clone()),
					half_life: DaemonicDuration::from_secs(1),
				},
				EnergyCost::Unbounded => Stability::Unstable {
					decay_to: Box::new(super::elements::SPECULAR.clone()),
					half_life: DaemonicDuration::from(10),
				},
			}
		}
		
		fn is_contradictory(props: &ReflectionProperties) -> bool {
			(props.fidelity == Fidelity::Specular && props.selectivity == Selectivity::None)
				|| (props.selectivity == Selectivity::Complete && props.fidelity == Fidelity::Absorptive)
		}
	}
	
	pub(crate) mod table {
		use super::*;
		
		pub enum ReflectionGroup {
			Noble,
			Reactive,
			Transitional,
			Rare,
			Synthetic,
		}
		
		pub fn classify(props: &ReflectionProperties) -> ReflectionGroup {
			match stability::assess(props) {
				stability::Stability::Stable => {
					if props.energy_cost == EnergyCost::Minimal {
						ReflectionGroup::Noble
					} else {
						ReflectionGroup::Transitional
					}
				}
				stability::Stability::Metastable { .. } => ReflectionGroup::Reactive,
				stability::Stability::Unstable { .. } => {
					if matches!(props.temporality, Temporality::Prophetic { .. }) {
						ReflectionGroup::Rare
					} else {
						ReflectionGroup::Transitional
					}
				}
				stability::Stability::Impossible => ReflectionGroup::Synthetic,
			}
		}
		
		pub(crate) mod compounds {
			use alloc::vec::Vec;
			use crate::clock::types::DaemonicDuration;
			use super::super::*;
			
			pub fn echo(delay: DaemonicDuration) -> ReflectionProperties {
				let specular = elements::SPECULAR.clone();
				let delayed = elements::delayed(delay);
				match bonding::combine(&specular, &delayed) {
					bonding::BondResult::Compound(c, _) => c,
					_ => unreachable!("Echo should always be valid"),
				}
			}
			
			pub fn filter(properties: Vec<super::PropertyId>) -> ReflectionProperties {
				elements::selective(properties)
			}
			
			/// Black Mirror — ALIAS: `[BLACK GLASS PROTOCOL]`
			/// Hidden properties get absorbed, visible get reflected.
			pub fn black_mirror(
				hidden: Vec<super::PropertyId>,
				visible: Vec<super::PropertyId>,
			) -> ReflectionProperties {
				let total = (hidden.len() + visible.len()) as f64;
				ReflectionProperties {
					fidelity: super::Fidelity::Lossy(visible.len() as f64 / total),
					temporality: super::Temporality::Instantaneous,
					spatiality: super::Spatiality::Inverted,
					selectivity: super::Selectivity::Partial(visible),
					energy_cost: super::EnergyCost::Sustained(hidden.len() as f64),
				}
			}
			
			pub fn double_mirror() -> ReflectionProperties {
				ReflectionProperties {
					fidelity: super::Fidelity::Specular,
					temporality: super::Temporality::Instantaneous,
					spatiality: super::Spatiality::Identity,
					selectivity: super::Selectivity::Complete,
					energy_cost: super::EnergyCost::Finite(0.1),
				}
			}
		}
	}
	
	// ── Reflection traits (preserved) ──────────────────
	
	pub trait Reflection {
		type Cause: ReflectionCause;
		fn properties(&self) -> ReflectionProperties;
	}
	
	pub trait ReflectionCause {
		fn name<'name>(&self) -> &'name str;
		fn recoverable(&self) -> bool;
	}
	
	pub trait Reflective {
		fn reflect<CAUSE: ReflectionCause>(&self, cause: CAUSE) -> impl Reflection;
	}
	
	pub trait ReflectionComposite {
		type Cause: ReflectionCause;
		fn combine(reflections: &[&dyn Reflection<Cause=Self::Cause>]) -> bonding::BondResult;
		fn assess_stability(&self) -> stability::Stability;
	}
	
	pub trait MirrorType<'mirrortype>: 'mirrortype {
		fn properties(&self) -> ReflectionProperties;
	}
	
	/// Map ReflectionProperties → Glass Severity.
	/// This replaces the old reflections_to_glass function.
	pub fn reflection_to_severity(props: &ReflectionProperties) -> Severity {
		match &props.fidelity {
			Fidelity::Specular => Severity::Stable,
			Fidelity::Lossy(x) if *x > 0.8 => Severity::Cracked,
			Fidelity::Lossy(x) if *x > 0.5 => Severity::Fracture,
			Fidelity::Lossy(_) => Severity::Fracture,
			Fidelity::Destructive => Severity::Warp,
			Fidelity::Absorptive => Severity::Shattered,
		}
	}
	
	// ── Property types ─────────────────────────────────
	#[derive(Clone, Debug, PartialEq)]
	pub struct ReflectionProperties {
		pub fidelity: Fidelity,
		pub temporality: Temporality,
		pub spatiality: Spatiality,
		pub selectivity: Selectivity,
		pub energy_cost: EnergyCost,
	}
	
	#[derive(Clone, Debug, PartialEq)]
	pub enum Fidelity {
		Specular,
		Lossy(f64),
		Destructive,
		Absorptive,
	}
	use alloc::vec::Vec;
	use crate::clock::types::DaemonicDuration;
	#[derive(Clone, Debug, PartialEq)]
	pub enum Temporality {
		Instantaneous,
		Delayed(DaemonicDuration),
		Variable { min: DaemonicDuration, max: DaemonicDuration },
		/// ⚠️ **UNSTABLE** — crystallization risk.
		/// Prophetic observations MUST carry decaying confidence.
		Prophetic { requires_prior_walks: u64 },
		None,
	}
	
	#[derive(Clone, Debug, PartialEq)]
	pub enum Spatiality {
		Inverted,
		Identity,
		Transformed(SpatialTransform),
		Collapsed,
	}
	
	#[derive(Clone, Debug, PartialEq)]
	pub enum Selectivity {
		Complete,
		Partial(Vec<PropertyId>),
		Single(PropertyId),
		None,
	}
	
	#[derive(Clone, Debug, PartialEq)]
	pub enum EnergyCost {
		Minimal,
		Finite(f64),
		Sustained(f64),
		Unbounded,
	}
	
	#[derive(Clone, Debug, PartialEq)]
	pub struct SpatialTransform {
		// TODO: transformation matrices or functions
	}
	
	pub type PropertyId = u32;
}

// ═══════════════════════════════════════════════════════════════
// REPAIR SYSTEM (NEW — replaces old SeverityHandler)
// ═══════════════════════════════════════════════════════════════

pub(crate) mod repair {
	// use std::panic::{catch_unwind, AssertUnwindSafe};
	use core::panic::AssertUnwindSafe;
use core::intrinsics::catch_unwind;
use alloc::boxed::Box;
use alloc::string::String;
	use crate::{Glass, Severity, Observation, Annotation};
	
	// ── Repair Result ──────────────────────────────────
	
	/// Outcome of a repair attempt.
	#[derive(Debug)]
	pub enum RepairResult {
		/// Repair succeeded — severity improved to this level
		Repaired(Severity),
		/// Repair partially succeeded — severity improved but not fully
		Improved(Severity),
		/// Repair failed — severity unchanged
		Failed,
		/// Repair function panicked — contained by catch_unwind
		Panicked(String),
		/// Post-repair state doesn't match the enclosure's fingerprint.
		/// Dies in Transit. The repair produced something unexpected.
		FingerprintMismatch {
			expected: Severity,
			actual: Severity,
		},
	}
	
	// ── Repair Fingerprint ─────────────────────────────
	
	/// Cryptographic behavioral fingerprint of a repair operation.
	/// Captures WHAT the repair expects to find and WHAT it expects
	/// to produce. If reality doesn't match, Dies in Transit fires.
	#[derive(Clone, Debug)]
	pub struct RepairFingerprint {
		/// DaemonicHashable of the construction context
		pub context_hash: u64,
		/// Expected input severity
		pub expected_input: Severity,
		/// Expected output severity on success
		pub expected_output: Severity,
		/// Checksum of the sealed repair function
		pub function_checksum: u64,
	}
	
	// ── Repair Trust ───────────────────────────────────
	
	/// Where did this repair come from?
	#[derive(Clone, Debug, PartialEq)]
	pub enum RepairTrust {
		/// Created by the same code that produced the error.
		/// Fully trusted — same compilation unit.
		Local,
		/// From a known, authenticated source.
		/// Signature verified against known DaemonicID.
		Verified { signer_id: u64 },
		/// From an unknown or unauthenticated source.
		/// Must be quarantine-tested before execution.
		Untrusted,
	}
	
	/// Has the repair been independently tested?
	#[derive(Clone, Debug)]
	pub enum RepairVerification {
		/// Tested and certified
		Verified { hash: u64, version: u32 },
		/// Not independently verified
		Unverified,
	}
	
	// ── Repair Enclosure ───────────────────────────────
	use alloc::vec::Vec;
	use crate::clock::types::DaemonicDuration;
	/// Repair logic that travels WITH the error.
	/// Baked in at error construction time.
	/// Carries cryptographic proof of behavioral fingerprint.
	///
	/// The enclosure is the immune system's innate response —
	/// built-in, automatic, first line of defense.
	pub struct RepairEnclosure<GLASS> {
		/// Who created this repair
		pub creator_id: u64, // TODO: replace with DaemonicID when available
		/// The repair function — sealed behind crypto verification
		repair_fn: Box<dyn Fn(&GLASS) -> bool + Send + Sync>,
		/// Behavioral fingerprint
		pub fingerprint: RepairFingerprint,
		/// Trust level
		pub trust: RepairTrust,
		/// Confidence in the repair's correctness (0.0 to 1.0)
		/// 1.0 = Daemonic Guarantee (almost never produced correctly)
		pub confidence: f64,
		/// Verification status
		pub verification: RepairVerification,
		/// Tick at which this enclosure was created
		pub created_at: u64,
		/// Last tick at which this enclosure was successfully used
		pub last_verified_at: Option<u64>,
	}
	
	impl<GLASS> RepairEnclosure<GLASS> {
		/// Construct a new repair enclosure with Local trust.
		pub fn new(
			creator_id: u64,
			repair_fn: impl Fn(&GLASS) -> bool + Send + Sync + 'static,
			expected_input: Severity,
			expected_output: Severity,
			confidence: f64,
			created_at: u64,
		) -> Self {
			// TODO: compute real checksums via DaemonicCrypto trait
			let context_hash = creator_id.wrapping_mul(0x517cc1b727220a95);
			let function_checksum = context_hash.wrapping_add(created_at);
			
			Self {
				creator_id,
				repair_fn: Box::new(repair_fn),
				fingerprint: RepairFingerprint {
					context_hash,
					expected_input,
					expected_output,
					function_checksum,
				},
				trust: RepairTrust::Local,
				confidence,
				verification: RepairVerification::Unverified,
				created_at,
				last_verified_at: None,
			}
		}
		
		/// Effective confidence accounting for temporal decay.
		/// Confidence decreases logarithmically with age since last verification.
		pub fn effective_confidence(&self, current_tick: u64) -> f64 {
			match self.last_verified_at {
				Some(tick) => {
					let age = current_tick.saturating_sub(tick) as f64;
					//todo: libc breakage, fix
					// self.confidence * (1.0 / (1.0 + age.ln().max(0.0)))
					age
				}
				None => {
					// Never verified — base confidence halved
					self.confidence * 0.5
				}
			}
		}
		
		/// Execute the repair with full safety wrapping.
		///
		/// 1. Check fingerprint input expectation
		/// 2. Execute repair_fn inside catch_unwind
		/// 3. Check fingerprint output expectation
		/// 4. Return RepairResult with full audit trail
		pub fn execute(
			&mut self,
			target: &GLASS,
			current_severity: Severity,
			current_tick: u64,
		) -> RepairResult {
			// Step 1: Does the input severity match expectations?
			if current_severity != self.fingerprint.expected_input {
				return RepairResult::FingerprintMismatch {
					expected: self.fingerprint.expected_input,
					actual: current_severity,
				};
			}
			
			// Step 2: Execute with catch_unwind
			//Todo: This shit is broke and needs to be fixed
			// let repair_fn = &self.repair_fn;
			// let result = unsafe {
			// 	catch_unwind(AssertUnwindSafe(|| {
			// 		(repair_fn)(target)
			// 	}))
			// };
			let result: Result<_, GLASS> = Ok(true);
			
			match result {
				Ok(true) => {
					// Repair claims success — update verification timestamp
					self.last_verified_at = Some(current_tick);
					RepairResult::Repaired(self.fingerprint.expected_output)
				}
				Ok(false) => {
					RepairResult::Failed
				}
				Err(panic_info) => {
					todo!("i dont have time for this right now, unfuck this later");
					// let panic_msg = panic_info
					// 	.downcast_ref::<String>()
					// 	.map(|s| s.as_str())
					// 	.or_else(|| panic_info.downcast_ref::<&str>().copied())
					// 	.unwrap_or("unknown panic in repair enclosure")
					// 	.to_string();
					// RepairResult::Panicked(panic_msg)
				}
			}
		}
	}
	
	// ── Repair Injection ───────────────────────────────
	
	/// Repair logic provided AFTER error creation.
	/// External repair attempt — the adaptive immune response.
	/// Same cryptographic requirements as enclosures but marked
	/// as injected rather than baked in.
	pub struct RepairInjection<GLASS> {
		/// Who is attempting this repair
		pub injector_id: u64,
		/// The injected repair function
		repair_fn: Box<dyn Fn(&GLASS) -> bool + Send + Sync>,
		/// Behavioral fingerprint
		pub fingerprint: RepairFingerprint,
		/// Trust level — injections default to Untrusted
		pub trust: RepairTrust,
		/// Confidence — typically lower than enclosures
		pub confidence: f64,
		/// Verification status
		pub verification: RepairVerification,
	}
	
	impl<GLASS: Clone> RepairInjection<GLASS> {
		/// Simple quarantine check: test injection against known-healthy state.
		/// If the injection modifies a Stable observation, it's attacking
		/// healthy state — reject it. (Biological: thymic negative selection)
		pub fn quarantine_check(&self, healthy_sample: &GLASS) -> bool
			where
				GLASS: Glass<GLASS>,
		{
			let before = healthy_sample.severity();
			let result = (self.repair_fn)(healthy_sample);
			
			if result && before == Severity::Stable {
				// The injection CHANGED a healthy observation
				// This is autoimmune behavior — reject
				false
			} else {
				// Either didn't fire (safe) or didn't modify healthy state (safe)
				true
			}
		}
		
		/// Execute with the same safety wrapping as RepairEnclosure
		#[allow(unsafe_code)]
		pub unsafe fn execute(
			&self,
			target: &GLASS,
			current_severity: Severity,
		) -> RepairResult {
			todo!("i should fix this now, but nothing depends on it")
		}
		// 	if current_severity != self.fingerprint.expected_input {
		// 		return RepairResult::FingerprintMismatch {
		// 			expected: self.fingerprint.expected_input,
		// 			actual: current_severity,
		// 		};
		// 	}
		//
		// 	let repair_fn = &self.repair_fn;
		// 	let result = catch_unwind(AssertUnwindSafe(|| {
		// 		(repair_fn)(target)
		// 	}));
		//
		// 	match result {
		// 		Ok(true) => RepairResult::Repaired(self.fingerprint.expected_output),
		// 		Ok(false) => RepairResult::Failed,
		// 		Err(panic_info) => {
		// 			let msg = panic_info
		// 				.downcast_ref::<String>()
		// 				.map(|s| s.as_str())
		// 				.or_else(|| panic_info.downcast_ref::<&str>().copied())
		// 				.unwrap_or("unknown panic in repair injection")
		// 				.to_string();
		// 			RepairResult::Panicked(msg)
		// 		}
		// 	}
		// }
	}
	
	// ── Repair Stack ───────────────────────────────────
	
	/// Three-level repair dispatch:
	/// 1. Self-repair (enclosure, baked in)
	/// 2. Local handler (injection from caller)
	/// 3. Global handler (injection from Shade/process)
	///
	/// Each level tries in order. First success wins.
	/// All levels use the same fingerprint verification.
	pub struct RepairStack<GLASS> {
		pub self_repair: Option<RepairEnclosure<GLASS>>,
		pub local_handler: Option<RepairInjection<GLASS>>,
		pub global_handler: Option<RepairInjection<GLASS>>,
	}
	
	impl<GLASS: Clone> RepairStack<GLASS> {
		pub fn empty() -> Self {
			Self {
				self_repair: None,
				local_handler: None,
				global_handler: None,
			}
		}
		
		pub fn with_enclosure(enclosure: RepairEnclosure<GLASS>) -> Self {
			Self {
				self_repair: Some(enclosure),
				local_handler: None,
				global_handler: None,
			}
		}
		
		/// Attempt repair at all levels, in order.
		/// Returns the first successful result, or the last failure.
		#[allow(unsafe_code)]
		pub unsafe fn attempt_repair(
			&mut self,
			target: &GLASS,
			current_severity: Severity,
			current_tick: u64,
		) -> RepairResult {
			// Level 1: Self-repair (enclosure)
			if let Some(ref mut enclosure) = self.self_repair {
				let result = enclosure.execute(target, current_severity, current_tick);
				match &result {
					RepairResult::Repaired(_) | RepairResult::Improved(_) => return result,
					_ => {} // Fall through to next level
				}
			}
			
			// Level 2: Local handler (injection)
			if let Some(ref local) = self.local_handler {
				let result = local.execute(target, current_severity);
				match &result {
					RepairResult::Repaired(_) | RepairResult::Improved(_) => return result,
					_ => {}
				}
			}
			
			// Level 3: Global handler (injection)
			if let Some(ref global) = self.global_handler {
				let result = global.execute(target, current_severity);
				return result;
			}
			
			// All levels exhausted
			RepairResult::Failed
		}
	}
	
	// ── Separated Concerns (replacing old SeverityHandler) ──
	
	/// Concern 1: Where does this severity route to?
	pub trait SeverityRouter {
		/// Given a severity, what action should be taken?
		fn route(&self, severity: Severity) -> crate::FidelityAction {
			crate::severity_to_fidelity(severity)
		}
	}
	
	/// Concern 2: Can this Glass observation be repaired?
	pub trait RepairAttempt<GLASS: Glass<GLASS>> {
		/// Attempt repair using the Glass's own repair stack.
		fn attempt_repair(
			glass: &mut impl Glass<GLASS>,
			current_tick: u64,
		) -> RepairResult;
	}
	
	/// Concern 3: What resources are available for repair?
	pub trait RepairContext {
		type Resources;
		fn resources(&mut self) -> &mut Self::Resources;
	}
}

// ═══════════════════════════════════════════════════════════════
// DIAGNOSTIC & SUBDIAGNOSTIC (preserved, separate files)
// ═══════════════════════════════════════════════════════════════
// Currently stubbed out so they can be handled separately, this is rust internal logic
// pub(crate) mod diagnostic;
// pub(crate) mod subdiagnostic;