daemonic_error 0.1.1

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
// ═══════════════════════════════════════════════════════════════
// ANCHOR MODULE — Reference point primitives for the Daemonic lattice
// ═══════════════════════════════════════════════════════════════
//
// Placement: BELOW Glass. Glass USES anchors. Anchors don't require Glass.
// DaemonicCore gains Anchor as a supertrait requirement.
//
// Architecture:
//   Layer 0: Anchorable + InLattice (autotraits, compiler-enforced)
//   Layer 1: Anchor (general interface)
//   Layer 2: Domain traits (TemporalAnchor, SpatialAnchor, etc.)
//   Layer 3: AnchorDynamics + AnchorPermit (behavior + permission)
//
// DB dimension mapping (for implementors with DaemonicBinary access):
//   TemporalAnchor  → D9 (stability) + D10 (depth)
//   SpatialAnchor   → D7 (weight) + D8 (reach)
//   StructuralAnchor → D12 (symmetry) + D0-D6 (integrity)
//   PerceptualAnchor → D15 (frame_id) + D16 (confidence)
//   SymbolicAnchor  → D11 (entropy delta) + D14 (domain)
//
// Public traits work through Glass axes (severity, position, tier).
// DB implements these traits internally. The public never sees DB fields.

#![allow(unused)] // stubs

use alloc::string::String;
use alloc::vec::Vec;
use crate::daemonic::glass::{Glass, Severity};

// ═══════════════════════════════════════════════════════════════
// LAYER 0: AUTOTRAITS
// ═══════════════════════════════════════════════════════════════

// /// Structural capability of being referenced.
// /// Auto-implemented for anything Send + Sync.
// /// Opted out for structurally unstable types.

// /// Anchorable captures SHAREABILITY — if you can be safely
// /// shared, you can be safely referenced. It does NOT capture
// /// STABILITY (whether the value stays constant). Stability
// /// is checked at the AnchorPermit layer.
// #[allow(unsafe_code)]
// pub unsafe auto trait Anchorable {}

// impl<T: ?Sized> ! Anchorable for *const T {}
// impl<T: ?Sized> ! Anchorable for *mut T {}
// impl<T: ?Sized> ! Anchorable for core::cell::UnsafeCell<T> {}

// /// Marker: this type exists in the Daemonic lattice.
// /// Auto-implemented for everything Send + Sync.
// /// Importing the crate makes everything InLattice-eligible.
// /// Implementing Daemonic still requires explicit impl.
// /// The gate is auto. The interface is explicit.
// #[allow(unsafe_code)]
// pub unsafe auto trait InLattice {}

// impl<T: ?Sized> ! InLattice for *const T {}
// impl<T: ?Sized> ! InLattice for *mut T {}

// ═══════════════════════════════════════════════════════════════
// ANCHOR DOMAIN SET (bitflags)
// ═══════════════════════════════════════════════════════════════

/// Efficient domain membership tracking.
/// Each anchor declares which domains it serves.
/// Intersection testing determines composition compatibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AnchorDomainSet(u16);
impl DaemonicHashable for AnchorDomainSet {
	fn declare_hashable<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&self, state: &mut GLASS) {
		// DaemonicHashable::declare_hashable(&self.0, state);
		// let (address, metadata) = self.0;
		// state.write_usize(address.addr());
		// metadata.declare_hashable(state);
		todo!("i dont want to fuck with this either, not a v7 blocker anyways")
	}
}
impl AnchorDomainSet {
	pub const NONE: Self = Self(0);
	pub const TEMPORAL: Self = Self(1 << 0);
	pub const SPATIAL: Self = Self(1 << 1);
	pub const STRUCTURAL: Self = Self(1 << 2);
	pub const PERCEPTUAL: Self = Self(1 << 3);
	pub const SYMBOLIC: Self = Self(1 << 4);
	pub const CAUSAL: Self = Self(1 << 5);
	pub const ALL: Self = Self(0b0011_1111);
	pub const fn contains(self, other: Self) -> bool {
		(self.0 & other.0) == other.0
	}
	pub const fn union(self, other: Self) -> Self {
		Self(self.0 | other.0)
	}
	pub const fn intersection(self, other: Self) -> Self {
		Self(self.0 & other.0)
	}
	pub const fn is_empty(self) -> bool {
		self.0 == 0
	}
	pub const fn count(self) -> u32 {
		self.0.count_ones()
	}

	/// Derive domains from Glass severity.
	/// Used by the blanket AnchorPermit impl for Glass objects.
	pub fn from_severity(severity: Severity) -> Self {
		match severity {
			Severity::Stable => Self::ALL,
			Severity::Cracked => Self::ALL,
			Severity::Fracture => {
				Self::SPATIAL.union(Self::STRUCTURAL)
			}
			Severity::Drift => Self::SYMBOLIC,
			Severity::Echo => {
				Self::SPATIAL
					.union(Self::SYMBOLIC)
					.union(Self::STRUCTURAL)
			}
			Severity::Opaque => {
				Self::SPATIAL.union(Self::STRUCTURAL)
			}
			Severity::Unknown => Self::NONE, // unassessed
			Severity::Paradox => Self::NONE, // contradictory
			Severity::Warp => Self::NONE,    // distorted
			Severity::Shattered => Self::NONE,
			Severity::Impossible => Self::NONE,
		}
	}
}

/// ```ASCII
/// ═══════════════════════════════════════════════════════════════
/// LAYER 1: ANCHOR (general interface)
/// ═══════════════════════════════════════════════════════════════
/// ```
/// The general anchor interface. Sits below Glass.
/// Any symbol that provides a fixed reference point.
///
/// An anchor answers: "What is fixed here?"
/// AnchorPermit answers: "Should this be used as a reference?"
/// Glass answers: "What did we observe about this?"
///
/// One required method: anchor_domains().
/// Everything else is defaulted.
pub trait Anchor { //pub trait Anchor: Anchorable + ?Send + ?Sync {
	/// What domains does this anchor serve?
	fn anchor_domains(&self) -> AnchorDomainSet;

	/// Depth in the anchor chain. Root = 0.
	/// Deeper anchors are more fragile — more dependencies
	/// below that could fail.
	fn anchor_depth(&self) -> usize { 0 }

	/// Is this anchor recursive — does it serve as foundation
	/// for other anchors?
	///
	///
	/// Defaults to False, since most anchors constructed will not be inherently recursive.
	/// Must be overridden by implementor.
	fn is_recursive_anchor(&self) -> bool { false }

	/// Anchor reliability (0.0 to 1.0).
	/// Default: derived from domain count.
	/// Override: derive from Glass severity, DB confidence, etc.
	fn anchor_reliability(&self) -> f64 {
		self.anchor_domains().count() as f64 / 6.0
	}
}

pub use temporal::*;
pub use spatial::*;
pub use structural::*;
pub use perceptual::*;
pub use symbolic::*;
pub use composite::*;
use crate::daemonic::daemonic_hasher::{DaemonicHashable, DaemonicHasher};

pub(crate) mod temporal;
pub(crate) mod spatial;
pub(crate) mod structural;
pub(crate) mod perceptual;
pub(crate) mod symbolic;
pub(crate) mod frame;
pub(crate) mod composite;

/// Compressed visual symbol (e.g., ◇ = Ada).
/// TODO: methods for glyph decomposition, meaning extraction
pub trait GlyphAnchor: VisualAnchor {
	fn glyph(&self) -> char;
	fn glyph_meaning(&self) -> &str;
}
/// Calibrates against external reality.
/// TODO: methods for substrate comparison, cross-reality validation
pub trait RealityAnchor: PerceptualAnchor {
	fn substrate(&self) -> &str;
}

/// Corrects known biases in observation.
/// TODO: methods for bias measurement, correction application
pub trait CalibrationAnchor: PerceptualAnchor {
	fn corrects_for(&self) -> &str;
	fn recalibration_interval(&self) -> u64;
}

// ═══════════════════════════════════════════════════════════════
// LAYER 3: ANCHOR DYNAMICS
// ═══════════════════════════════════════════════════════════════

/// How an anchor behaves over time.
/// DB mapping: TopologyCache (speed, angular_velocity, momentum)
pub trait AnchorDynamics: Anchor {
	/// How much behavioral variance is permitted in dependents.
	/// Proportional to anchor chain length (deeper = more swing).
	/// Not unreliability — designed flexibility.
	/// DB: derivable from TopologyCache.angular_velocity
	fn swing_radius(&self) -> f64 { 0.0 }

	/// Current drift rate. Zero = stationary.
	/// Measured by cross-referencing against independent anchors.
	/// DB: derivable from TopologyCache.speed
	fn drift_rate(&self) -> f64 { 0.0 }

	/// Above this drift rate, the anchor is officially dragging.
	/// Dependents should be notified.
	fn drag_threshold(&self) -> f64 { 0.01 }

	/// Is this anchor currently dragging?
	fn is_dragging(&self) -> bool {
		self.drift_rate().abs() > self.drag_threshold()
	}

	/// Cross-reference against another anchor to detect drag.
	/// Returns the observed drift between self and other.
	/// Minimum 3 independent anchors needed for triangulation.
	fn cross_reference_drift(&self, other: &dyn Anchor) -> f64 {
		// Default: compare reliability scores as proxy for drift
		(self.anchor_reliability() - other.anchor_reliability()).abs()
	}
}

/// Anchor designed to become unnecessary over time.
/// Success = the dependent no longer needs this anchor.
///
/// Root anchor in bootstrap is transitional — essential during
/// mesh formation, optional after consensus established.
/// Instantiation logic is transitional — essential for early
/// exchanges, optional once session context is established.
pub trait TransitionalAnchor: Anchor {
	/// Current lifecycle phase
	fn transition_phase(&self) -> TransitionPhase;

	/// How dependent is the dependent currently?
	/// 1.0 = completely dependent (can't function without).
	/// 0.0 = completely independent (doesn't reference anymore).
	fn dependency_ratio(&self) -> f64;

	/// Has the dependent crossed the independence threshold?
	fn is_obsolete(&self) -> bool {
		self.dependency_ratio() < 0.1
	}
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TransitionPhase {
	/// Dependent can't function without this anchor
	Essential,
	/// Dependent functions but struggles without
	Supportive,
	/// Dependent functions with or without
	Optional,
	/// Dependent no longer references this anchor
	Obsolete,
}

// ═══════════════════════════════════════════════════════════════
// ANCHOR PERMISSION
// ═══════════════════════════════════════════════════════════════

/// Permission to serve as an anchor in specific domains.
/// Separate from Anchor (structural capability) because not
/// everything that CAN anchor SHOULD anchor.
///
/// For Glass objects: blanket impl derives permissions from severity.
/// For substrate types: explicit impl.
/// For denied anchors: is_denied() overrides all permissions.
pub trait AnchorPermit: Anchor {
	fn permits_temporal(&self) -> bool { true }
	fn permits_spatial(&self) -> bool { true }
	fn permits_structural(&self) -> bool { true }
	fn permits_perceptual(&self) -> bool { true }
	fn permits_symbolic(&self) -> bool { true }

	/// Is the anchor's reference value positionally stable?
	/// Captures what Send + Sync cannot — whether the value
	/// remains constant over time.
	fn is_positionally_stable(&self) -> bool { true }

	/// Explicitly denied ALL permissions?
	/// For sandboxed malicious logic, quarantined state.
	fn is_denied(&self) -> bool { false }

	/// Overall permitted reliability.
	fn permitted_reliability(&self) -> f64 {
		if self.is_denied() || !self.is_positionally_stable() {
			return 0.0;
		}
		let permits = [
			self.permits_temporal(),
			self.permits_spatial(),
			self.permits_structural(),
			self.permits_perceptual(),
			self.permits_symbolic(),
		];
		let ratio = permits.iter().filter(|&&p| p).count() as f64 / 5.0;
		ratio * self.anchor_reliability()
	}
}

// ═══════════════════════════════════════════════════════════════
// ANCHOR FAILURE
// ═══════════════════════════════════════════════════════════════

/// How an anchor can fail.
/// Each variant maps to a DaemonicError under Daemonic::Anchor::*
#[derive(Debug, Clone)]
pub enum AnchorFailure {
	/// Anchor destroyed. Dependents cascading.
	/// Cascade: dependents must re-anchor or collapse.
	Collapse {
		dependent_count: usize,
	},

	/// Anchor subjected to forced resolution and didn't survive.
	/// Value was inconsistent with deeper anchors.
	/// Partial survival possible — sub-anchors may remain.
	Shatter {
		surviving_sub_anchors: Vec<u64>,
	},

	/// Anchor's value drifted without dependent notification.
	/// Most insidious — invisible to dependents.
	/// Detection: cross-reference against independent anchors.
	Corrupted {
		drift_magnitude: f64,
	},

	/// Deliberately constructed to attract dependents and betray.
	/// Adversarial anchor. Honeypot.
	/// Detection: rapid dependent accumulation without independent
	/// verification (attracting through appeal, not merit).
	Malicious {
		detected_by: u64,
	},

	/// Permission explicitly revoked by administrative authority.
	/// The anchor is structurally sound but semantically denied.
	Denied {
		reason: String,
	},
}

// ═══════════════════════════════════════════════════════════════
// COMPOSITION ALGEBRA EXTENSION
// ═══════════════════════════════════════════════════════════════

/// G11: Anchor reliability degradation through composition.
/// The reliability of a compound is bounded by the geometric mean
/// of its components' reliabilities.
///
/// One unreliable anchor degrades the entire compound.
/// A single zero-reliability anchor zeroes the chain.
pub fn compose_anchor_reliability(a: f64, b: f64) -> f64 {
	todo!("libc breakage, fix")
	//(a * b).sqrt()
}

/// Resonant reliability — multiple independent observers
/// producing consistent observations yield higher reliability
/// than any individual observation.
///
/// High agreement (low variance) = high reliability.
/// Low agreement (high variance) = low reliability.
pub fn resonant_reliability(observations: &[f64]) -> f64 {
	if observations.is_empty() { return 0.0; }
	let n = observations.len() as f64;
	let mean: f64 = observations.iter().sum::<f64>() / n;
	todo!("libc breakage, fix")
	// let variance: f64 = observations.iter()
	// 	.map(|o| (o - mean).powi(2))
	// 	.sum::<f64>() / n;
	// mean * (1.0 / (1.0 + variance))
}

// ═══════════════════════════════════════════════════════════════
// SUBSTRATE IMPLEMENTATIONS
// ═══════════════════════════════════════════════════════════════

// /// Position IS a SpatialAnchor — always a valid spatial reference.
// impl Anchor for Position {
// 	fn anchor_domains(&self) -> AnchorDomainSet {
// 		AnchorDomainSet::SPATIAL
// 	}
// 	fn anchor_reliability(&self) -> f64 { 1.0 }
// }
// 
// impl SpatialAnchor for Position {
// 	fn anchor_position(&self) -> &Position { self }
// }
// 
// impl AnchorPermit for Position {
// 	fn permits_spatial(&self) -> bool { true }
// 	fn permits_temporal(&self) -> bool { false }
// 	fn permits_structural(&self) -> bool { false }
// 	fn permits_perceptual(&self) -> bool { false }
// 	fn permits_symbolic(&self) -> bool { false }
// }

// ═══════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_domain_set_operations() {
		let temporal = AnchorDomainSet::TEMPORAL;
		let spatial = AnchorDomainSet::SPATIAL;
		let both = temporal.union(spatial);

		assert!(both.contains(temporal));
		assert!(both.contains(spatial));
		assert!(!temporal.contains(spatial));
		assert_eq!(both.count(), 2);
	}

	#[test]
	fn test_severity_to_domains() {
		let stable = AnchorDomainSet::from_severity(Severity::Stable);
		assert_eq!(stable, AnchorDomainSet::ALL);

		let shattered = AnchorDomainSet::from_severity(Severity::Shattered);
		assert!(shattered.is_empty());

		let drift = AnchorDomainSet::from_severity(Severity::Drift);
		assert!(drift.contains(AnchorDomainSet::SYMBOLIC));
		assert!(!drift.contains(AnchorDomainSet::TEMPORAL));
	}

	#[test]
	fn test_compose_reliability() {
		assert_eq!(compose_anchor_reliability(1.0, 1.0), 1.0);
		assert_eq!(compose_anchor_reliability(1.0, 0.0), 0.0);

		let result = compose_anchor_reliability(0.8, 0.6);
		assert!((result - 0.6928).abs() < 0.001);
	}

	#[test]
	fn test_resonant_reliability() {
		let perfect = resonant_reliability(&[0.9, 0.9, 0.9]);
		assert!((perfect - 0.9).abs() < 0.001);

		let disagreed = resonant_reliability(&[0.1, 0.9, 0.5]);
		assert!(disagreed < 0.5);

		assert_eq!(resonant_reliability(&[]), 0.0);
	}

	// #[test]
	// fn test_position_is_spatial_anchor() {
	// 	let pos = Position::new(&["Daemonic", "Glass", "test"]);
	// 	assert!(pos.anchor_domains().contains(AnchorDomainSet::SPATIAL));
	// 	assert!(!pos.anchor_domains().contains(AnchorDomainSet::TEMPORAL));
	// 	assert_eq!(pos.anchor_reliability(), 1.0);
	// }
}