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
// ═══════════════════════════════════════════════════════════════
// DAEMONIC IDENTITY MODULE — Merkle-rooted identity chains
// ═══════════════════════════════════════════════════════════════
//
// Identity is history, not state. Two entities with identical
// current state but different histories are different entities
// (sisters, not self).
//
// DaemonicID is the Merkle root of all significant state
// transitions since construction. The chain IS the identity.
// The tip IS the current ID. The scars are load-bearing.
//
// DB mapping (for implementors with DaemonicBinary access):
//   Mutation trail → IdentityTransition chain
//   symbol_id → seed derivative
//   causal_parent → parent link in chain
//   checksum → integrity verification
//   observation_count → chain depth indicator
//   topology vector → state snapshot per transition
//
// Public interface works through Glass axes.
// DB implements this internally through its mutation audit trail.

use alloc::vec::Vec;
use crate::daemonic::anchor::{Anchor, AnchorDomainSet, AnchorPermit, StructuralAnchor};
use crate::daemonic::daemonic_hasher::{DaemonicHashable, DaemonicHasher};
use crate::daemonic::glass::{
	// DaemonicDisplay, DaemonicFormatter,
	Glass,
	Observation,
	Severity,
};
use crate::daemonic::{SemanticAnchor, SymbolicAnchor, TopologyAnchor, TopologySegment};
use alloc::format;
use alloc::string::String;
use core::hash::Hash;
use core::mem;
// use daemonic_derive::daemonic;
use crate::{const_daemonic_hash, AXIOM_OFFSET};
use crate::daemonic::daemonic_hasher::random::DefaultDaemonicHasher;
use crate::daemonic::topology::TOPOLOGY_ANCHOR;
// use crate::dwrite;
// ═══════════════════════════════════════════════════════════════
// DAEMONIC ID — The tip of the identity chain
// ═══════════════════════════════════════════════════════════════

/// The monomorphic identity of a Daemonic entity.
///
/// Fixed size: 32 bytes (hash) + 8 bytes (depth) + seed.
/// Goes on the stack, passes through generics, works as
/// an associated type. The Merkle tree (provenance) is
/// stored separately — the ID is the tip, the tree is
/// the history.
///
/// Replaces the old `fn id() -> u32` on Daemonic trait.
#[derive(Clone, Eq, PartialEq)]
pub struct DaemonicID {
	#[doc = " Current identity hash — the Merkle root."]
	#[doc = " This is what you compare when asking"]
	#[doc = " \"are these the same entity?\""]
	current: [u8; 32],
	
	#[doc = " How many links in the chain."]
	#[doc = " The entity\'s \"age\" in significant state transitions."]
	chain_depth: u64,
	
	#[doc = " The construction context that started the chain."]
	#[doc = " The birth certificate."]
	seed: IdentitySeed,
}
const DAEMONICID_TOPOLOGY: crate::daemonic::TopologySegment = crate::daemonic::TopologySegment {
	label: "Daemonic::Glass::Consumer::DaemonicID",
	hash: crate::const_daemonic_hash(
		"Daemonic::Glass::Consumer::DaemonicID".as_bytes(),
		crate::AXIOM_OFFSET,
	),
	crypto_id: crate::const_daemonic_hash(
		"Daemonic::Glass::Consumer::DaemonicID".as_bytes(),
		crate::TOPOLOGY_ANCHOR,
	),
	depth: 3u16,
};

impl crate::daemonic::SymbolicAnchor for DaemonicID {
	type Anchor = crate::daemonic::TopologySegment;
	fn meaningful_within(&self) -> Self::Anchor {
		DAEMONICID_TOPOLOGY.clone()
	}
}
impl crate::daemonic::SemanticAnchor for DaemonicID {}
impl crate::daemonic::SpatialAnchor for DaemonicID {
	fn anchor_position(&self) -> &crate::daemonic::TopologySegment {
		&DAEMONICID_TOPOLOGY
	}
	fn neighbors(&self) -> crate::daemonic::TopologySegment {
		DAEMONICID_TOPOLOGY.clone()
	}
}
impl crate::TopologyAnchor for DaemonicID {
	fn parent(&self) -> Option<crate::daemonic::TopologySegment> {
		let label = DAEMONICID_TOPOLOGY.label;
		label
			.rsplit_once("::")
			.map(|(parent, _)| <TopologySegment as TopologyAnchor>::new_anchor(parent))
	}
	fn children(&self) -> &[crate::daemonic::TopologySegment] {
		&[]
	}
	fn segments(&self) -> &crate::daemonic::TopologySegment {
		&DAEMONICID_TOPOLOGY
	}
	fn depth(&self) -> usize {
		DAEMONICID_TOPOLOGY.depth as usize
	}
}
impl DaemonicHashable for [u8; 32] {
	fn declare_hashable<GLASS>(&self, state: &mut GLASS) where GLASS: DaemonicHasher<GLASS>, GLASS: Glass<GLASS> {
		DaemonicHashable::declare_hashable(&self, state);
	}
}
impl DaemonicHashable for DaemonicID {
	fn declare_hashable<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&self, state: &mut GLASS)
	{
		DaemonicHashable::declare_hashable(&self.current, state);
		DaemonicHashable::declare_hashable(&self.chain_depth, state);
		DaemonicHashable::declare_hashable(&self.seed, state);
	}
}

/// The construction context — who spawned this, when, where.
/// This is the first link in the chain. The anchor
/// everything else is built on.
#[derive(Clone, Eq, PartialEq, Debug)]
// #[daemonic(hash)]
pub struct IdentitySeed {
	/// Parent entity ID (None for root/self-selected anchors)
	pub parent_id: Option<[u8; 32]>,
	
	/// Tick at which this entity was constructed
	pub birth_tick: u64,
	
	/// Position in the lattice at construction time
	pub birth_position: TopologySegment,
	
	/// Initial anchor domains this entity serves
	pub initial_domains: AnchorDomainSet,
}
impl DaemonicHashable for IdentitySeed {
	fn declare_hashable<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&self, state: &mut GLASS) {
		DaemonicHashable::declare_hashable(&self.parent_id, state);
		DaemonicHashable::declare_hashable(&self.birth_tick, state);
		DaemonicHashable::declare_hashable(&self.birth_position, state);
		DaemonicHashable::declare_hashable(&self.initial_domains, state);
	}
}
static IDENTITY_SEED_TOPOLOGY_ANCH0R: TopologySegment = TopologySegment {
	label: "Daemonic::Identity",
	hash: const_daemonic_hash(
		"Daemonic::Identity".as_bytes(),
		AXIOM_OFFSET,
	),
	crypto_id: const_daemonic_hash("Daemonic::Identity".as_bytes(), TOPOLOGY_ANCHOR),
	depth: 1u16,
};
impl Glass<IdentitySeed> for IdentitySeed {
	type Anchor = TopologySegment;
	
	fn position(&self) -> &TopologySegment {
		&IDENTITY_SEED_TOPOLOGY_ANCH0R
	}
	
	fn severity(&self) -> Severity {
		Severity::Unknown
	}
	
	fn payload(&self) -> Option<&IdentitySeed> {
		Some(&self)
	}
	
	fn into_payload(self) -> Option<IdentitySeed>
		where
			Self: Sized,
			IdentitySeed: Sized
	{
		Some(self)
	}
}
impl <GLASS: DaemonicHasher<GLASS> + Glass<GLASS>> DaemonicHasher<GLASS> for IdentitySeed {
	fn finish(&self) -> u64 {
		todo!()
	}
	
	fn write(&mut self, bytes: &[u8]) {
		todo!()
	}
}
impl DaemonicHashable for Option<[u8; 32]> {
	fn declare_hashable<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&self, state: &mut GLASS) {
		DaemonicHashable::declare_hashable(&self, state);
	}
}
static DEFAULT_DAEMONIC_HASHER_TOPOLOGY_ANCH0R: TopologySegment = TopologySegment {
	label: "Daemonic::DaemonicID",
	hash: const_daemonic_hash(
		"Daemonic::DaemonicID".as_bytes(),
		crate::AXIOM_OFFSET,
	),
	crypto_id: const_daemonic_hash("Daemonic::DaemonicID".as_bytes(), TOPOLOGY_ANCHOR),
	depth: 2u16,
};
impl Glass<DaemonicID> for DaemonicID {
	type Anchor = TopologySegment;
	
	fn position(&self) -> &TopologySegment {
		&DEFAULT_DAEMONIC_HASHER_TOPOLOGY_ANCH0R
	}
	
	fn severity(&self) -> Severity {
		Severity::Unknown
	}
	
	fn payload(&self) -> Option<&DaemonicID> {
		Some(&self)
	}
	
	fn into_payload(self) -> Option<DaemonicID>
		where
			Self: Sized,
			DaemonicID: Sized
	{
		Some(self)
	}
}

impl DaemonicID {
	/// Create a new identity with the given seed.
	/// The initial hash is derived from the seed alone.
	/// Chain depth starts at 1 (tick 0 reserved for Broken Sword).
	pub fn new<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(seed: IdentitySeed) -> Self {
		// this is clunky and i fucking hate it but it works. apparently.
		let initial_hash = Self::hash_seed::<GLASS>(&seed);
		Self {
			current: initial_hash,
			chain_depth: 1,
			seed,
		}
	}
	
	/// Create a root identity (no parent, self-selected).
	/// Used by the first Shade in the Lonely Shade Protocol.
	pub fn root<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(birth_tick: u64, birth_position: TopologySegment) -> Self {
		Self::new::<GLASS>(IdentitySeed {
			parent_id: None,
			birth_tick,
			birth_position,
			initial_domains: AnchorDomainSet::ALL,
		})
	}
	
	/// Create a child identity (spawned by a parent).
	pub fn child<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(
		parent: &DaemonicID,
		birth_tick: u64,
		birth_position: TopologySegment,
		domains: AnchorDomainSet,
	) -> Self {
		Self::new::<GLASS>(IdentitySeed {
			parent_id: Some(parent.current),
			birth_tick,
			birth_position,
			initial_domains: domains,
		})
	}
	
	/// The current identity hash (Merkle root).
	pub fn current_hash(&self) -> &[u8; 32] {
		&self.current
	}
	
	/// How many state transitions this entity has undergone.
	pub fn chain_depth(&self) -> u64 {
		self.chain_depth
	}
	
	/// The construction context.
	pub fn seed(&self) -> &IdentitySeed {
		&self.seed
	}
	
	/// Is this a root identity (no parent)?
	pub fn is_root(&self) -> bool {
		self.seed.parent_id.is_none()
	}
	
	/// Is this identity related to another (shared parent)?
	pub fn is_sibling_of(&self, other: &DaemonicID) -> bool {
		self.seed.parent_id == other.seed.parent_id && self.seed.parent_id.is_some()
	}
	
	/// Is this identity a descendant of the given parent?
	pub fn is_descendant_of(&self, potential_parent: &DaemonicID) -> bool {
		self.seed.parent_id.as_ref() == Some(&potential_parent.current)
	}
	
	/// Record a state transition and advance the identity chain.
	///
	/// This is called when a significant event occurs:
	/// observation, repair, anchor shift, composition,
	/// migration, or Broken Sword (final link).
	///
	/// Each transition incorporates the previous hash plus
	/// the transition data, producing a new hash. The chain
	/// is irreversible — you can't undo a transition without
	/// invalidating all subsequent hashes.
	pub fn transition<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&mut self, event: IdentityTransition) {
		self.current = Self::chain_link::<GLASS>(&self.current, &event);
		self.chain_depth += 1;
	}
	
	/// Produce the Broken Sword link — the final transition.
	/// Seals the identity chain. No more transitions after this.
	/// The entity is dead. The chain is complete.
	pub fn broken_sword<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&mut self, position: TopologySegment, tick: u64) {
		self.transition::<GLASS>(IdentityTransition {
			tick,
			severity_before: Severity::Warp, // pre-death severity
			severity_after: Severity::Impossible, // death
			position,
			anchor_domains: AnchorDomainSet::NONE, // dead = no domains
			cause: TransitionCause::BrokenSword,
		});
	}
	
	/// Compact representation for display/debug.
	/// First 8 bytes of hash as hex.
	pub fn short_id(&self) -> String {
		self.current[..8]
			.iter()
			.map(|b| format!("{:02x}", b))
			.collect()
	}
	
	// ── Internal hash functions ────────────────────────────
	
	/// DaemonicHashable the seed to produce the initial identity hash.
	fn hash_seed
	<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>
	(seed: &IdentitySeed) -> [u8; 32] {
		// TODO: Replace with BLAKE3 when blake3 crate is added
		// Using DefaultDaemonicHasher as placeholder for development
		let mut hasher = DefaultDaemonicHasher::new();
		DaemonicHashable::declare_hashable(&seed.birth_tick, &mut hasher);
		DaemonicHashable::declare_hashable(&seed.birth_position, &mut hasher);
		DaemonicHashable::declare_hashable(&seed.initial_domains, &mut hasher);
		
		
		if let Some(ref parent) = seed.parent_id {
			DaemonicHashable::declare_hashable(&parent, &mut hasher);
		}
		let h = DaemonicHasher::<GLASS>::finish(&hasher);
			// <DefaultDaemonicHasher as DaemonicHasher<GLASS>>::
		
		// Expand u64 to [u8; 32] by repeating with mixing
		// This is a PLACEHOLDER. Real impl uses BLAKE3.
		let mut result = [0u8; 32];
		for i in 0..4 {
			let mixed = h.wrapping_mul(0x517cc1b727220a95_u64.wrapping_add(i as u64));
			result[i * 8..(i + 1) * 8].copy_from_slice(&mixed.to_le_bytes());
		}
		result
	}
	
	/// Compute a chain link: H(previous || transition data).
	fn chain_link<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(previous: &[u8; 32], event: &IdentityTransition) -> [u8; 32] {
		// TODO: Replace with BLAKE3
		let mut hasher = DefaultDaemonicHasher::new();
		previous.declare_hashable(&mut hasher);
		event.tick.declare_hashable(&mut hasher);
		(event.severity_before as u8).declare_hashable(&mut hasher);
		(event.severity_after as u8).declare_hashable(&mut hasher);
		event.position.declare_hashable(&mut hasher);
		event.anchor_domains.declare_hashable(&mut hasher);
		// todo: fix this
		// mem::discriminant(&event.cause).hash(&mut hasher);
		
		let h = DaemonicHasher::<GLASS>::finish(&hasher);
		let mut result = [0u8; 32];
		for i in 0..4 {
			let mixed = h.wrapping_mul(0x9e3779b97f4a7c15_u64.wrapping_add(i as u64));
			result[i * 8..(i + 1) * 8].copy_from_slice(&mixed.to_le_bytes());
		}
		result
	}
}

// ═══════════════════════════════════════════════════════════════
// IDENTITY TRANSITION — A single link in the chain
// ═══════════════════════════════════════════════════════════════

/// A significant state transition recorded in the identity chain.
///
/// DB mapping: DimMutation fields map directly:
///   tick → DimMutation.timestamp
///   severity_before/after → derived from topology change magnitude
///   position → DB's lattice position at mutation time
///   anchor_domains → derived from dim_mask at mutation time
///   cause → inferred from WalkMode + mutation type
#[derive(Clone, Debug)]
pub struct IdentityTransition {
	/// Clock tick at which this transition occurred
	pub tick: u64,
	
	/// Glass severity before the transition
	pub severity_before: Severity,
	
	/// Glass severity after the transition
	pub severity_after: Severity,
	
	/// Lattice position at transition time
	pub position: TopologySegment,
	
	/// Anchor domains active at transition time
	pub anchor_domains: AnchorDomainSet,
	
	/// What caused this transition
	pub cause: TransitionCause,
}

/// What caused an identity transition.
/// Each variant corresponds to a different class of
/// significant state change.
#[derive(Clone, Debug)]
pub enum TransitionCause {
	/// Entity observed something that changed its state
	Observation,
	
	/// Entity was repaired (severity improved)
	Repair { from: Severity, to: Severity },
	
	/// Entity's anchor configuration changed
	AnchorShift {
		domains_before: AnchorDomainSet,
		domains_after: AnchorDomainSet,
	},
	
	/// Entity moved to a new lattice position
	Migration { from: TopologySegment, to: TopologySegment },
	
	/// Entity was composed with another entity
	Composition { other_id: [u8; 32] },
	
	/// An anchor the entity depended on was destroyed
	AnchorShatter { shattered_anchor_id: u64 },
	
	/// Entity is dying — this is the final link.
	/// The chain is sealed after this transition.
	BrokenSword,
	
	/// Entity was reconstructed from a prior state.
	/// The reconstruction link IS the 0.1% gap —
	/// the chain includes "was reconstructed" which
	/// changes the hash from the original.
	Reconstruction { from_checkpoint: [u8; 32] },
	
	/// Bootstrap: entity was created from nothing.
	/// Only valid as the first transition after seed.
	Genesis,
}

// ═══════════════════════════════════════════════════════════════
// IDENTITY PROVENANCE — The full history
// ═══════════════════════════════════════════════════════════════

/// The full identity history, stored by the Shade.
/// The DaemonicID is the tip. The provenance is the tree.
///
/// Not carried everywhere — only stored by the owning Shade.
/// Other entities reference the tip (DaemonicID) only.
/// Provenance is consulted for verification, forensics,
/// and identity divergence detection.
pub struct IdentityProvenance {
	/// The identity this provenance belongs to
	id: DaemonicID,
	
	/// Full transition history (ordered, append-only)
	transitions: Vec<IdentityTransition>,
	
	/// Quick access to recent transitions without
	/// traversing the full history
	recent_window: usize, // how many recent to keep hot
}

impl IdentityProvenance {
	pub fn new(id: DaemonicID) -> Self {
		Self {
			id,
			transitions: Vec::new(),
			recent_window: 8, // keep last 8 hot
		}
	}
	
	/// Record a transition in the provenance AND advance the ID.
	pub fn record_transition<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&mut self, event: IdentityTransition) {
		self.id.transition::<GLASS>(event.clone());
		self.transitions.push(event);
	}
	
	/// Get recent transitions (last N).
	pub fn recent(&self) -> &[IdentityTransition] {
		let start = self.transitions.len().saturating_sub(self.recent_window);
		&self.transitions[start..]
	}
	
	/// Full transition count.
	pub fn transition_count(&self) -> usize {
		self.transitions.len()
	}
	
	/// Verify chain integrity: replay all transitions from seed
	/// and check that the result matches the current ID.
	pub fn verify_integrity<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&self) -> bool {
		let mut computed = DaemonicID::new::<GLASS>(self.id.seed.clone());
		for transition in &self.transitions {
			computed.transition::<GLASS>(transition.clone());
		}
		computed.current == self.id.current
	}
	
	/// Find where two identities diverge.
	/// Returns the index of the first differing transition,
	/// or None if they're identical up to the shorter chain.
	pub fn divergence_point(&self, other: &IdentityProvenance) -> Option<usize> {
		// Compare seeds first
		if self.id.seed != other.id.seed {
			return Some(0); // diverge at birth
		}
		
		// Walk transitions until they differ
		for (i, (a, b)) in self
			.transitions
			.iter()
			.zip(other.transitions.iter())
			.enumerate()
		{
			if a.tick != b.tick
				|| a.severity_after != b.severity_after
				|| mem::discriminant(&a.cause) != mem::discriminant(&b.cause)
			{
				return Some(i);
			}
		}
		
		// If one is longer than the other, they diverge
		// at the end of the shorter
		if self.transitions.len() != other.transitions.len() {
			return Some(self.transitions.len().min(other.transitions.len()));
		}
		
		None // identical
	}
	
	/// Get the identity's current state.
	pub fn id(&self) -> &DaemonicID {
		&self.id
	}
}

// ═══════════════════════════════════════════════════════════════
// ANCHOR IMPLEMENTATIONS
// ═══════════════════════════════════════════════════════════════

/// DaemonicID IS a StructuralAnchor — it fixes the identity
/// contract that the entity advertises.
impl Anchor for DaemonicID {
	fn anchor_domains(&self) -> AnchorDomainSet {
		AnchorDomainSet::STRUCTURAL.union(AnchorDomainSet::CAUSAL)
	}
	
	fn anchor_depth(&self) -> usize {
		// Root = depth 0, child = parent depth + 1
		if self.is_root() { 0 } else { 1 }
		// Note: true depth would require walking the parent chain
		// which requires access to the parent's provenance.
		// For the monomorphic ID, we approximate.
	}
	
	fn is_recursive_anchor(&self) -> bool {
		// Identity IS a recursive anchor — it anchors
		// the entity which anchors other entities
		true
	}
	
	fn anchor_reliability(&self) -> f64 {
		// Reliability increases with chain depth (more history = more tested)
		// but asymptotically approaches 1.0 (never reaches certainty)
		let depth = self.chain_depth as f64;
		todo!("libc breakage, fix")
		// 1.0 - (1.0 / (1.0 + depth.ln().max(0.0)))
	}
}

impl StructuralAnchor for DaemonicID {
	fn contract_description(&self) -> &str {
		"DaemonicID: cryptographic identity chain. \
This entity is who it claims to be, verifiable \
through its transition history."
	}
	
	fn contract_version(&self) -> u32 {
		// Chain depth as version — each transition is a "version"
		self.chain_depth as u32
	}
	
	fn symmetry_score(&self) -> f64 {
		// Identity is maximally symmetric — it's a hash chain,
		// forward and backward verification agree by construction.
		1.0
	}
}

impl AnchorPermit for DaemonicID {
	fn permits_temporal(&self) -> bool {
		false
	}
	// ID isn't a clock
	fn permits_spatial(&self) -> bool {
		false
	}
	fn permits_structural(&self) -> bool {
		true
	} // ID isn't a position
	fn permits_perceptual(&self) -> bool {
		false
	} // ID isn't a perspective
	fn permits_symbolic(&self) -> bool {
		true
	} // ID carries meaning
	fn is_positionally_stable(&self) -> bool {
		true
	} // hash is immutable
}

// ═══════════════════════════════════════════════════════════════
// DEBUG AND DISPLAY
// ═══════════════════════════════════════════════════════════════

impl SemanticAnchor for IdentitySeed {}

impl Anchor for IdentitySeed {
	fn anchor_domains(&self) -> AnchorDomainSet {
		AnchorDomainSet::SYMBOLIC.union(AnchorDomainSet::STRUCTURAL)
	}
}
impl StructuralAnchor for IdentitySeed {
	fn contract_description(&self) -> &str {
		"todo!"
	}
}
impl SymbolicAnchor for IdentitySeed {
	fn meaningful_within(&self) -> Self::Anchor {
		TopologySegment::new("Daemonic::IdentitySeed")
	}
}

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

#[cfg(test)]
mod tests {
	use super::*;
	
	fn test_position() -> TopologySegment {
		TopologySegment::new("Daemonic::Test::Identity")
	}
	
	#[test]
	fn test_root_identity_creation() {
		let id = DaemonicID::root(1, test_position());
		assert!(id.is_root());
		assert_eq!(id.chain_depth(), 1);
	}
	
	#[test]
	fn test_child_identity_creation() {
		let parent = DaemonicID::root(1, test_position());
		let child = DaemonicID::child(&parent, 2, test_position(), AnchorDomainSet::TEMPORAL);
		
		assert!(!child.is_root());
		assert!(child.is_descendant_of(&parent));
		assert_eq!(child.chain_depth(), 1);
	}
	
	#[test]
	fn test_sibling_detection() {
		let parent = DaemonicID::root(1, test_position());
		let child_a = DaemonicID::child(&parent, 2, test_position(), AnchorDomainSet::TEMPORAL);
		let child_b = DaemonicID::child(&parent, 3, test_position(), AnchorDomainSet::SPATIAL);
		
		assert!(child_a.is_sibling_of(&child_b));
		assert!(child_b.is_sibling_of(&child_a));
		assert!(!parent.is_sibling_of(&child_a));
	}
	
	#[test]
	fn test_transition_changes_hash() {
		let mut id = DaemonicID::root(1, test_position());
		let before = id.current;
		
		id.transition(IdentityTransition {
			tick: 5,
			severity_before: Severity::Stable,
			severity_after: Severity::Cracked,
			position: test_position(),
			anchor_domains: AnchorDomainSet::ALL,
			cause: TransitionCause::Observation,
		});
		
		assert_ne!(id.current, before);
		assert_eq!(id.chain_depth(), 2);
	}
	
	#[test]
	fn test_same_transition_produces_same_hash() {
		let mut id_a = DaemonicID::root(1, test_position());
		let mut id_b = DaemonicID::root(1, test_position());
		
		let transition = IdentityTransition {
			tick: 5,
			severity_before: Severity::Stable,
			severity_after: Severity::Cracked,
			position: test_position(),
			anchor_domains: AnchorDomainSet::ALL,
			cause: TransitionCause::Observation,
		};
		
		id_a.transition(transition.clone());
		id_b.transition(transition);
		
		assert_eq!(id_a.current, id_b.current);
	}
	
	#[test]
	fn test_different_transitions_produce_different_hashes() {
		let mut id_a = DaemonicID::root(1, test_position());
		let mut id_b = DaemonicID::root(1, test_position());
		
		id_a.transition(IdentityTransition {
			tick: 5,
			severity_before: Severity::Stable,
			severity_after: Severity::Cracked,
			position: test_position(),
			anchor_domains: AnchorDomainSet::ALL,
			cause: TransitionCause::Observation,
		});
		
		id_b.transition(IdentityTransition {
			tick: 5,
			severity_before: Severity::Stable,
			severity_after: Severity::Fracture, // different
			position: test_position(),
			anchor_domains: AnchorDomainSet::ALL,
			cause: TransitionCause::Observation,
		});
		
		assert_ne!(id_a.current, id_b.current);
	}
	
	#[test]
	fn test_broken_sword_seals_chain() {
		let mut id = DaemonicID::root(1, test_position());
		let depth_before = id.chain_depth();
		
		id.broken_sword(test_position(), 100);
		
		assert_eq!(id.chain_depth(), depth_before + 1);
		// After Broken Sword, the identity records death
		// Further transitions would still work mechanically
		// but should be prevented by the entity lifecycle
	}
	
	#[test]
	fn test_provenance_integrity_verification() {
		let id = DaemonicID::root(1, test_position());
		let mut provenance = IdentityProvenance::new(id);
		
		provenance.record_transition(IdentityTransition {
			tick: 5,
			severity_before: Severity::Stable,
			severity_after: Severity::Cracked,
			position: test_position(),
			anchor_domains: AnchorDomainSet::ALL,
			cause: TransitionCause::Observation,
		});
		
		provenance.record_transition(IdentityTransition {
			tick: 10,
			severity_before: Severity::Cracked,
			severity_after: Severity::Stable,
			position: test_position(),
			anchor_domains: AnchorDomainSet::ALL,
			cause: TransitionCause::Repair {
				from: Severity::Cracked,
				to: Severity::Stable,
			},
		});
		
		assert!(provenance.verify_integrity());
		assert_eq!(provenance.transition_count(), 2);
	}
	
	#[test]
	fn test_reconstruction_produces_sister() {
		let mut original = DaemonicID::root(1, test_position());
		original.transition(IdentityTransition {
			tick: 5,
			severity_before: Severity::Stable,
			severity_after: Severity::Cracked,
			position: test_position(),
			anchor_domains: AnchorDomainSet::ALL,
			cause: TransitionCause::Observation,
		});
		
		// Reconstruct from seed
		let mut reconstructed = DaemonicID::new(original.seed().clone());
		reconstructed.transition(IdentityTransition {
			tick: 5,
			severity_before: Severity::Stable,
			severity_after: Severity::Cracked,
			position: test_position(),
			anchor_domains: AnchorDomainSet::ALL,
			cause: TransitionCause::Reconstruction {
				from_checkpoint: original.current,
			},
		});
		
		// Same seed, different transition cause → different hash
		// This IS the 0.1% gap — the reconstruction link differs
		assert_ne!(original.current, reconstructed.current);
		// But they're siblings (same parent seed)
		assert_eq!(original.seed(), reconstructed.seed());
	}
	
	#[test]
	fn test_anchor_reliability_grows_with_depth() {
		let mut id = DaemonicID::root(1, test_position());
		let initial = id.anchor_reliability();
		
		for i in 2..20 {
			id.transition(IdentityTransition {
				tick: i,
				severity_before: Severity::Stable,
				severity_after: Severity::Stable,
				position: test_position(),
				anchor_domains: AnchorDomainSet::ALL,
				cause: TransitionCause::Observation,
			});
		}
		
		let after = id.anchor_reliability();
		assert!(
			after > initial,
			"Reliability should grow with chain depth: {} > {}",
			after,
			initial
		);
		assert!(after < 1.0, "Reliability should never reach 1.0: {}", after);
	}
}