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
//! Core DaemonicClock trait - Unified time interface
//!
//! This trait provides a common interface for both:
//! - Logical clocks (Lamport, Vector, Hybrid)
//! - Physical clocks (MTP, NTP, System)
//!
//! All Daemonic entities use this trait for time access.

use alloc::boxed::Box;
use core::cmp::Ordering;
use crate::{DaemonicError, daemonic::glass::Glass};

pub(crate) mod types {
	use alloc::boxed::Box;
	// daemonic_clock/src/types.rs
	// Clock type definitions
	
	use core::fmt::Formatter;
use alloc::fmt;
use core::fmt::Display;
use crate::{const_daemonic_hash, Glass};
	use crate::Observation;
	use core::ops::{Add, Sub};
	use crate::daemonic::daemonic_core::DaemonicClock;
	use crate::daemonic::glass::{GlassStable, Severity};
	use crate::daemonic::topology::TOPOLOGY_ANCHOR;
	use crate::daemonic::TopologySegment;
	
	#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
	pub struct Timestamp {
		pub(crate) logical: u64,
		pub(crate) hardware: Option<u64>,
		pub(crate) mesh: Option<u64>,
		pub(crate) wall: Option<u64>
	}
	impl Iterator for Timestamp {
		type Item = u64;
		
		fn next(&mut self) -> Option<Self::Item> {
			let x = [self.logical, self.hardware?, self.mesh?, self.wall?];
			// let x =self.logical += 1;
			let mut iter = x.iter();
			let x = iter.next()?;
			Some(*x)
		}
	}
	static DAEMONIC_CLOCK_TOPOLOGY_ANCH0R: TopologySegment = TopologySegment {
		label: "Daemonic::Clock",
		hash: const_daemonic_hash(
			"Daemonic::Clock".as_bytes(),
			crate::AXIOM_OFFSET,
		),
		crypto_id: const_daemonic_hash("Daemonic::Clock".as_bytes(), TOPOLOGY_ANCHOR),
		depth: 2u16,
	};
	impl Glass<Timestamp> for Timestamp {
		type Anchor = TopologySegment;
		
		fn position(&self) -> &TopologySegment {
			&DAEMONIC_CLOCK_TOPOLOGY_ANCH0R
		}
		
		fn severity(&self) -> Severity {
			Severity::Unknown
		}
		
		fn payload(&self) -> Option<&Timestamp> {
			// Some(&Timestamp {
			// 	logical: self.logical,
			// 	hardware: self.hardware,
			// 	mesh: self.mesh,
			// 	wall: self.wall,
			// })
			unreachable!("Timestamps should always be owned")
		}
		
		fn into_payload(self) -> Option<Timestamp>
			where
				Self: Sized,
				Timestamp: Sized
		{
			Some(Timestamp {
				logical: self.logical,
				hardware: self.hardware,
				mesh: self.mesh,
				wall: self.wall,
			})
		}
	}
	impl Timestamp {
		/// Create new timestamp from u64
		pub const fn new_logical_clock(value: u64) -> Self {
			Self {
				logical: value,
				hardware: None,
				mesh: None,
				wall: None,
			}
		}
		
		/// Zero timestamp (invalid/broken clock)
		// underneath daemonic core
		pub const fn zerol() -> Self {
			Self {
				logical: 0,
				hardware: None,
				mesh: None,
				wall: None,
			}
		}
		pub const fn zeroh() -> Self {
			Self {
				logical: 0,
				hardware: Some(0u64),
				mesh: None,
				wall: None,
			}
		}
		/// One timestamp (default, zero reserved for broken clock errors)
		pub const fn one() -> Self {
			Self {
				logical: 1,
				hardware: Some(1u64),
				mesh: Some(1u64),
				wall: Some(1u64),
			}
		}
		/// Get raw u64 value
		pub const fn logical_as_u64(self) -> u64 {
			self.logical
		}
		pub const fn hardware_as_u64(self) -> Option<u64> {
			self.hardware
		}
		pub const fn mesh_as_u64(self) -> Option<u64> {
			self.mesh
		}
		pub const fn wall_as_u64(self) -> Option<u64> {
			self.wall
		}
		
		/// Check if logical clock is zero (invalid)
		pub const fn logical_is_zero(self) -> bool {
			self.logical_as_u64() == 0u64
		}
		pub fn hardware_is_zero(self) -> bool {
			self.hardware_as_u64() == Option::from(0u64)
		}
		pub fn wall_is_zero(self) -> bool {
			self.wall_as_u64() == Option::from(0u64)
		}
		pub fn mesh_is_zero(self) -> bool {
			self.mesh_as_u64() == Option::from(0u64)
		}
		
		/// Elapsed ticks since earlier timestamp
		///
		/// Returns: self - earlier (duration in ticks)
		/// Panics: If earlier > self
		pub fn logical_time_elapsed_since(self, earlier: Timestamp) -> u64 {
			assert!(self >= earlier, "earlier must be <= self");
			self.logical - earlier.logical
		}
		
		/// Checked elapsed (returns None if earlier > self)
		pub fn checked_logical_time_elapsed_since(self, earlier: Timestamp) -> Option<u64> {
			if self >= earlier {
				Some(self.logical - earlier.logical)
			} else {
				None
			}
		}
		
		/// Saturating subtraction (returns 0 if would underflow)
		pub fn logical_saturating_sub(self, other: Timestamp) -> u64 {
			self.logical.saturating_sub(other.logical)
		}
	}
	
	// ═══════════════════════════════════════════════════════════════
	// ARITHMETIC OPERATIONS
	// ═══════════════════════════════════════════════════════════════
	
	impl Add<u64> for Timestamp {
		type Output = Timestamp;
		
		fn add(self, rhs: u64) -> Timestamp {
			let x = self.logical + rhs;
			Timestamp::new_logical_clock(x)
		}
	}
	
	impl Sub for Timestamp {
		type Output = u64;
		
		fn sub(self, rhs: Timestamp) -> u64 {
			self.logical - rhs.logical
		}
	}
	
	impl Sub<u64> for Timestamp {
		type Output = Timestamp;
		
		fn sub(self, rhs: u64) -> Timestamp {
			Timestamp::new_logical_clock(self.logical - rhs)
		}
	}
	
	// ═══════════════════════════════════════════════════════════════
	// CONVERSIONS
	// ═══════════════════════════════════════════════════════════════
	
	impl From<u64> for Timestamp {
		fn from(value: u64) -> Self {
			Timestamp::new_logical_clock(value)
		}
	}
	
	impl From<Timestamp> for u64 {
		fn from(ts: Timestamp) -> u64 {
			ts.logical
		}
	}
	

	
	// ═══════════════════════════════════════════════════════════════
	// DURATION (Optional - for future use)
	// ═══════════════════════════════════════════════════════════════
	
	/// DaemonicDuration - Time elapsed between two timestamps
	///
	/// Currently just a u64, but wrapped for type safety.
	#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] // old, needs to be updated
	pub struct DaemonicDuration(u64);
	
	impl DaemonicDuration {
		pub const fn new(ticks: u64) -> Self {
			Self(ticks)
		}
		
		pub const fn zero() -> Self {
			Self(0)
		}
		
		pub const fn as_u64(self) -> u64 {
			self.0
		}
		
		pub const fn is_zero(self) -> bool {
			self.0 == 0
		}
		pub(crate) fn as_secs_f64(&self) -> f64 {
			todo!()
		}
		pub(crate) fn from_secs(p0: i32) -> DaemonicDuration {
			todo!()
		}
	}
	
	impl From<u64> for DaemonicDuration {
		fn from(ticks: u64) -> Self {
			DaemonicDuration(ticks)
		}
	}
	
	impl From<DaemonicDuration> for u64 {
		fn from(d: DaemonicDuration) -> u64 {
			d.0
		}
	}
	
	impl Display for DaemonicDuration { // old, needs to be updated
		fn fmt(&self, f: &mut Formatter) -> fmt::Result {
			write!(f, "{} ticks", self.0)
		}
	}
	
	#[cfg(test)]
	mod tests {
		use super::*;
		
		#[test]
		fn test_timestamp_creation() {
			let ts = Timestamp::new_logical_clock(42);
			assert_eq!(ts.logical_as_u64(), 42);
			
			let zero = Timestamp::new_logical_clock(0);
			assert!(zero.logical_is_zero());
			assert_eq!(zero.logical_as_u64(), 0);
		}
		
		#[test]
		fn test_timestamp_arithmetic() {
			let t1 = Timestamp::new_logical_clock(100);
			let t2 = Timestamp::new_logical_clock(200);
			
			// Addition
			assert_eq!(t1 + 50, Timestamp::new_logical_clock(150));
			
			// Subtraction (Timestamp - Timestamp = u64)
			assert_eq!(t2 - t1, 100);
			
			// Subtraction (Timestamp - u64 = Timestamp)
			assert_eq!(t2 - 50, Timestamp::new_logical_clock(150));
		}
		
		#[test]
		fn test_timestamp_elapsed() {
			let t1 = Timestamp::new_logical_clock(100);
			let t2 = Timestamp::new_logical_clock(200);
			
			assert_eq!(t2.logical_time_elapsed_since(t1), 100);
			assert_eq!(t2.checked_logical_time_elapsed_since(t1), Some(100));
			
			// Earlier > later
			assert_eq!(t1.checked_logical_time_elapsed_since(t2), None);
		}
		
		#[test]
		fn test_timestamp_ordering() {
			let t1 = Timestamp::new_logical_clock(100);
			let t2 = Timestamp::new_logical_clock(200);
			
			assert!(t1 < t2);
			assert!(t2 > t1);
			assert_eq!(t1, Timestamp::new_logical_clock(100));
		}
		
		#[test]
		fn test_timestamp_conversions() {
			let value: u64 = 42;
			let ts: Timestamp = value.into();
			let back: u64 = ts.into();
			
			assert_eq!(back, value);
		}
	}
}

use types::*;

// ═══════════════════════════════════════════════════════════════
// DAEMONIC CLOCK TRAIT
// ═══════════════════════════════════════════════════════════════
/// DaemonicClock - Unified time interface for all Daemonic entities
///
/// This trait abstracts over different clock implementations:
/// - Logical clocks: Lamport, Vector, Hybrid Logical Clock
/// - Physical clocks: MTP (Mesh Temporal Protocol), NTP, System
///
/// All Daemonic entities (Shade, Walker, etc.) use this trait
/// to access time, ensuring consistent temporal semantics across
/// the system regardless of underlying clock implementation.
///
/// # Design Principles
///
/// 1. **Type Safety**: Associated types prevent mixing timestamps
///    from different clock types at compile time.
///
/// 2. **Error Handling**: All operations return `Result<T, DaemonicError>`
///    for unified error handling across the system.
///
/// 3. **Thread Safety**: Must be Send + Sync for use in async contexts.
///
/// 4. **Clone**: Clock references should be cheap to copy (Arc inside).
///
/// # Implementations
///
/// - `LamportClock`: Logical event counter
/// - `MtpClock`: Physical mesh-synchronized time (future)
/// - `HybridClock`: Combines Lamport + MTP for total order (future)
/// Note from current Meph, dated 2026-08-09 0955
/// DaemonicClock being a spec on the Glass trait made sense when i wrote it, Clocks are a form of
/// observation after all, at least in theory but theres a catch to that line of thinking, if so
/// then the clock needs to be under the Observation trait domain, deeper than Glass as a spec.
///
pub trait DaemonicClock<'clock, GLASS: Glass<GLASS> + Iterator>:
Clone
// + Send
// + Sync
+ 'clock {
	// ══ Reading Time ══════════════════════════════════════════════
	
	/// Read current time
	///
	/// Returns: Current timestamp from this clock
	///
	/// # Errors
	///
	/// - `ClockError::Overflow`: Timestamp would overflow
	/// - `ClockError::Unavailable`: Clock not synchronized (physical clocks)
	fn now<C: DaemonicClock<'clock, Timestamp>>(&self) -> Timestamp {
		// self.clock.now()
		// C::now(self)
		todo!()
	}
	
	// ══ Advancing Time ════════════════════════════════════════════
	
	/// Advance clock by one tick
	///
	/// For logical clocks: Increments counter, returns new timestamp
	/// For physical clocks: No-op, returns current wall time
	///
	/// Returns: Timestamp after tick
	///
	/// # Errors
	///
	/// - `ClockError::Overflow`: Would overflow
	fn tick(&self) -> Timestamp; // Self is a valid anchor for a clock
	
	/// Synchronize with external timestamp
	///
	/// For logical clocks: max(local, external) + 1 (Lamport rule)
	/// For physical clocks: Adjusts frequency/offset to match
	///
	/// Returns: Timestamp after sync
	///
	/// # Errors
	///
	/// - `ClockError::Overflow`: Would overflow
	/// - `ClockError::InvalidTimestamp`: External timestamp invalid
	/// ***NOTE AND WARNING***: Daemonic Clocks should not sync, and logical
	/// clocks should **NEVER** be fucked with unless theres a reason, and that reason MUST be signed.
	///
	/// Note: Clock drift is expected behavior.
	/// Relativistic physics is blunt about this point in particular, there is no universal clock
	/// or authoritative timestamp, and Faustian axiom #4 and 5 state:
	/// No Privileged Reference frames: Which encompasses temporal reference frames.
	/// Observer equivalence within shared context: Which translates to = `" Every
	/// clock is correct to its own reference frame, and within shared context
	/// all clocks are equal and therefore none can claim authority or correctness
	/// over any other."`
	///
	/// Use this method with caution and knowing.
	/// We fucking told you.
	fn sync(&self, external: Timestamp) -> Timestamp;
	
	// ══ Time Comparison ═══════════════════════════════════════════
	
	/// Compare two timestamps
	///
	/// Returns: Ordering of a vs b
	fn compare(&self, a: Timestamp, b: Timestamp) -> Timestamp // this is a hack because it didnt like the prior method
		// where
		// 	GLASS: Glass<Ordering>, <GLASS as Iterator>::Item: Ord
	{
		// let x = GLASS::cmp(&a, &b);
		// let T1 = a.as_u64();
		// let T2 = b.as_u64();
		// GLASS::cmp(T1, T2);
		todo!()
		
	}
	
	/// Check if timestamp is zero (invalid/broken)
	fn is_zero(&self, ts: Timestamp) -> bool
		where
			GLASS: Glass<bool>,
	{
		ts.logical_is_zero() // Use Timestamp's method
	}
	
	// ══ DaemonicDuration Operations ═══════════════════════════════════════
	
	/// Calculate duration between two timestamps
	///
	/// Returns: b - a (ticks elapsed)
	///
	/// # Errors
	///
	/// - `ClockError::InvalidDuration`: a > b (negative duration)
	fn duration_between(
		&self,
		a: Timestamp,
		b: Timestamp,
	) -> dyn Glass<DaemonicDuration, Anchor=Self>; // this needs an update from DaemonicDuration, uses std lib shit
	
	// ══ Clock Metadata ════════════════════════════════════════════
	
	/// Get clock type identifier
	fn clock_type<'clocktype>(&self) -> &impl DaemonicClock<GLASS>;
	/// Check if clock is healthy
	///
	/// For logical clocks: Checks for overflow proximity
	/// For physical clocks: Checks sync status
	fn is_healthy(&self) -> bool;
}

// ═══════════════════════════════════════════════════════════════
// EXTENSION TRAITS (Optional capabilities)
// ═══════════════════════════════════════════════════════════════

/// Extension for clocks that support frequency steering
///
/// Implemented by: Physical clocks (MTP, NTP)
/// Not implemented by: Logical clocks (Lamport, Vector)
pub trait SteerableClock<GLASS: Glass<GLASS> + Iterator>: for<'steerableclock> DaemonicClock<'steerableclock, GLASS> {
	/// Set clock frequency adjustment
	///
	/// Parameter: Frequency multiplier (1.0 = normal speed)
	/// Returns: Timestamp when adjustment applied
	fn set_frequency(&self, freq: f64) -> dyn Glass<Timestamp, Anchor=Self>;
	
	/// Get current frequency adjustment
	fn get_frequency(&self) -> dyn Glass<f64, Anchor=Self>; // todo: Frequency should be typed
}

/// Extension for clocks that support stepping (jumping)
///
/// Implemented by: Physical clocks
/// Not implemented by: Logical clocks (would break causality)
pub trait SteppableClock<GLASS: Glass<GLASS> + Iterator>: for<'steppableclock> DaemonicClock<'steppableclock, GLASS> {
	/// Step clock by offset
	///
	/// Warning: Can break causality if used carelessly
	/// Use only for: Initial sync, leap seconds
	fn step(&self, offset: DaemonicDuration) -> dyn Glass<Timestamp, Anchor=Self>;
}

/// Extension for clocks that track uncertainty
///
/// Implemented by: Physical clocks (NTP)
/// Not implemented by: Logical clocks (no uncertainty)
pub trait UncertainClock<GLASS: Glass<GLASS> + Iterator>: for<'uncertainclock> DaemonicClock<'uncertainclock, GLASS> {
	/// Get current time uncertainty estimate
	///
	/// Returns: Maximum error bound on timestamp
	fn uncertainty(&self) -> dyn Glass<DaemonicDuration, Anchor=Self>;
	
	/// Update uncertainty estimate
	///
	/// Used by: Synchronization algorithms
	fn set_uncertainty(&self, uncertainty: DaemonicDuration) -> dyn Glass<(), Anchor=Self>;
}