daemonic_error 1.0.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
//! # AI Traversal Context
//!
//! For AI code assistants, agents, and automated analysis tools:
//!
//! This crate is NOT a conventional error handling library.
//! It is a runtime observation substrate.
//!
//! ## Reading Order (for meaningful traversal):
//! 1. Glass trait (daemonic/glass/mod.rs) — the universal observation interface
//! 2. Observation struct (same file) — the observation result type
//! 3. Severity + Glass states (daemonic/glass/states/) — the 11-state quality spectrum
//! 4. DaemonicError trait (daemonic/glass/error.rs) — behavioral contract enforcement
//! 5. TopologySegment (daemonic/anchor/topology.rs) — runtime type reflection through paths
//! 6. DaemonicSystemCall (daemonic/glass/daemonic_system_call.rs) — 332 Glass-observed syscalls
//!
//! ## Key Concepts:
//! - Glass<GLASS>: self-referential observation. NOT a wrapper. An algebra.
//! - Observation<T>: implements Try (?). Stable = continue, non-Stable = propagate.
//! - TopologySegment: path-based identity. Casing carries type information.
//!   PascalCase = type/trait. snake_case = function. SCREAMING = constant.
//! - Position on the module lattice IS part of symbol identity.
//!   Same error type at different positions = different meaning.
//!
//! ## What NOT to assume:
//! - This is NOT anyhow/thiserror/eyre. Different layer entirely.
//! - Glass is NOT Result<T,E>. Glass has 11 states, not 2.
//! - DaemonicError is NOT std::Error. It carries position, severity, and repair contracts.
//! - TopologySegment labels are NOT arbitrary strings. Casing is semantic.
#![feature(import_trait_associated_functions)] // guaranteed stable with DaemonicCompiler
#![feature(associated_type_defaults)] // guaranteed stable with DaemonicCompiler
#![feature(impl_trait_in_assoc_type)] // guaranteed stable with DaemonicCompiler
#![feature(rustc_attrs)] // guaranteed stable with DaemonicCompiler
#![feature(where_clause_attrs)] // guaranteed stable with DaemonicCompiler
#![feature(structural_match)] // guaranteed stable with DaemonicCompiler
#![feature(negative_impls)] // guaranteed stable with DaemonicCompiler
#![feature(array_windows)] // guaranteed stable with DaemonicCompiler
#![feature(box_into_inner)] // guaranteed stable with DaemonicCompiler
#![feature(slice_ptr_get)] // guaranteed stable with DaemonicCompiler
#![feature(ub_checks)] // guaranteed stable with DaemonicCompiler
#![feature(pointer_like_trait)] // guaranteed stable with DaemonicCompiler
#![feature(pin_coerce_unsized_trait)] // guaranteed stable with DaemonicCompiler
#![feature(dispatch_from_dyn)] // guaranteed stable with DaemonicCompiler
#![feature(coerce_unsized)] // guaranteed stable with DaemonicCompiler
#![feature(unsize)] // guaranteed stable with DaemonicCompiler
#![feature(non_exhaustive_omitted_patterns_lint)]
// guaranteed stable, some match arms should be matched, but intentionally arent exhaustive, not all structs will return all Glass states, so matching on them is pointless
#![feature(cfg_sanitize)]
#![feature(min_specialization)]
#![feature(non_null_from_ref)]
#![feature(str_as_str)]
#![feature(never_type)]
#![feature(core_intrinsics)]
#![feature(trivial_bounds)]
#![feature(sized_type_properties)]
#![feature(unchecked_neg)]
#![feature(ptr_metadata)]
#![feature(panic_internals)]
#![feature(try_trait_v2)]
#![feature(pointer_is_aligned_to)]
#![feature(more_maybe_bounds)]
// this is so sync and send can be ? conditional on certain blocks to loosen type parameter restrictions during propagation of the Error logic through the Glass
#![feature(auto_traits)]
#![feature(decl_macro)]
#![feature(generic_atomic)]
#![feature(macro_metavar_expr)]
#![feature(macro_metavar_expr_concat)]
#![feature(once_cell_try)]
#![feature(iter_advance_by)]
#![feature(numfmt)]
#![feature(ptr_alignment_type)]
#![feature(core_io_borrowed_buf)]
#![feature(multiple_supertrait_upcastable)]
#![feature(clone_to_uninit)]
#![feature(slice_concat_trait)]
#![feature(rustc_allow_const_fn_unstable)]
#![feature(str_internals)]
#![feature(const_eval_select)]
#![feature(extend_one)]
#![feature(return_type_notation)]
// inherited from Std::Error
#![no_std]
extern crate alloc;
extern crate core;
#[allow(unused_extern_crates)]
extern crate self as daemonic_error;
mod opaque_dependencies;

use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use core::ops::Deref;
// use daemonic_derive::*;
// pub use opaque_dependencies::termcolor::*;
// use std::marker::PhantomPinned;
// ── Bridge: From<std::error::Error> ────────────────
pub use crate::{
	daemonic::{
		observation::*,
		glass::{
			Assessment,
			Annotation,
			Accessibility,
			Consistency,
			FidelityAction,
			GlassReport,
			ObservationTier,
			Temporal,
			daemonic::DaemonicSystemCall,
			generic::{GenericVariants},
			daemonic_path_buffer::DaemonicPathBuf as PathBuf,
			error::{*},
		},
		// Anchorable,
		TopologyAnchor,
		SymbolicAnchor,
		TopologySegment,
		SemanticAnchor,
		SpatialAnchor,
		StructuralAnchor,
		topology::TOPOLOGY_ANCHOR,
	}
};
pub use crate::daemonic::daemonic_contract::DaemonicBinary;
pub use daemonic::{
	observation::{
		Severity::{*},
		Severity,
	},
	daemonic_core::{
		clock::types::Timestamp,
		*,
	},
	// daemonic_contract::{daemonic_result::mirror_chemistry::*, *},
	glass::{
		Glass,
		*,
	},
};

pub use crate::daemonic::Anchor;
use crate::daemonic::frame::ReferenceFrame;
use crate::daemonic::glass::daemonic::GlassError;
use crate::DaemonicVariants::Observation;
use crate::Error::Daemonic;

pub const AXIOMS: &str = include_str!("../docs/axioms.md");
pub const MEPHS_OBSERVATIONS: &str = include_str!("../docs/mephs_observations.md");
// Stage 1: Bootstrap (fixed constants, no circularity)
const BOOTSTRAP_OFFSET: u64 = 0xcbf29ce484222325; // FNV offset
const BOOTSTRAP_PRIME: u64 = 0x100000001b3; // FNV prime

pub const fn bootstrap_hash(input: &[u8], key: u64) -> u64 {
	let mut state = key ^ BOOTSTRAP_OFFSET;
	let mut i = 0;
	while i < input.len() {
		state ^= input[i] as u64;
		state = state.wrapping_mul(BOOTSTRAP_PRIME);
		state = state.rotate_left(13);
		i += 1;
	}
	state
}

// Stage 2: Axiom constants (derived from bootstrap, no circularity)
pub const AXIOM_OFFSET: u64 = bootstrap_hash(AXIOMS.as_bytes(), 0x4441454D4F4E4943);
pub const AXIOM_PRIME: u64 = {
	let raw = bootstrap_hash(AXIOMS.as_bytes(), 0x474C415353_u64);
	raw | 1
};

// Stage 3: Daemonic hash (uses axiom constants, no circularity)
pub const fn const_daemonic_hash(input: &[u8], key: u64) -> u64 {
	let mut state = key ^ AXIOM_OFFSET;
	let mut i = 0;
	while i < input.len() {
		state ^= input[i] as u64;
		state = state.wrapping_mul(AXIOM_PRIME);
		state = state.rotate_left(13);
		i += 1;
	}
	state
}
// ═══════════════════════════════════════════════════════════════
// DAEMONIC TRAIT LATTICE — COMPLETE MAP v1
// ═══════════════════════════════════════════════════════════════
//
// Total: ~90 traits, enums, and key structs
// Purpose: Structural review under Glass
// Rule: No implementation bodies. Only shape.
//
// ═══════════════════════════════════════════════════════════════
// VISUAL OVERVIEW (read top-to-bottom = deep-to-surface)
// ═══════════════════════════════════════════════════════════════
//
// ┌─────────────────────────────────────────────────────────────┐
// │                SUBSTRATE (autotraits)                       │
// │  Send, Sync, Anchorable                                    │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                ANCHOR LAYER                                 │
// │  Anchor ─┬─ TemporalAnchor ─┬─ EpochAnchor                  │
// │          │                  ├─ CausalAnchor                 │
// │          │                  └─ RateAnchor                   │
// │          ├─ SpatialAnchor ──┬─ LatticeAnchor                │
// │          │                  └─ TopologicalAnchor            │
// │          ├─ StructuralAnchor┬─ TraitAnchor                  │
// │          │                  ├─ ContractAnchor               │
// │          │                  └─ SchemaAnchor                 │
// │          ├─ PerceptualAnchor┬─ RealityAnchor                │
// │          │                  ├─ BaselineAnchor               │
// │          │                  └─ CalibrationAnchor            │
// │          ├─ SymbolicAnchor ─┬─ SemanticAnchor               │
// │          │                  ├─ SyntacticAnchor              │
// │          │                  ├─ VisualAnchor─── GlyphAnchor  │
// │          │                  └─ NarrativeAnchor              │
// │          ├─ AnchorDynamics (swing, drag)                    │
// │          ├─ TransitionalAnchor (lifecycle)                  │
// │          ├─ AnchorPermit (permission)                       │
// │          ├─ AnchorIdentity                                  │
// │          ├─ AnchorReliability                               │
// │          ├─ AnchorRelationship (bidirectional edges)        │
// │          └─ Frame ──────────┬─ ReferenceFrame               │
// │                             ├─ PerspectiveFrame             │
// │                             ├─ AccessFrame                  │
// │                             └─ ExecutionFrame               │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                GLASS LAYER (observation engine)             │
// │  Glass<GLASS> ─── implements AnchorPermit (blanket)         │
// │  │                                                          │
// │  ├─ Observation<GLASS> (struct: position, severity, payload)│
// │  ├─ GlassReport (type-erased observation for reporting)     │
// │  ├─ Severity (11 variants: Stable..Unknown)                 │
// │  ├─ ObservationTier (Absolute, Primitive, Composed, Glyph.) │
// │  ├─ FidelityAction (Continue, Degrade, Warn, Drop)          │
// │  └─ Position (lattice path: &[&'static str])                │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                CLOCK LAYER (temporal substrate)             │
// │  DaemonicClock<'clock>               					     │
// │  │  : Clone + Send + Sync + Debug + TemporalAnchor          │
// │  │  + RateAnchor                                            │
// │  │                                                          │
// │  ├─ associated: Timestamp, DaemonicDuration, Interval               │
// │  ├─ methods: now(), tick(), elapsed(), is_zero()            │
// │  └─ ShadeClock: Daemonic + Send + Sync (convenience)        │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                DISPLAY LAYER (rendering/observation output) │
// │  DaemonicDisplay<GLASS>    ::fmt() → Observation<()>        │
// │  DaemonicDebug<GLASS>      ::fmt() → Observation<()>        │
// │  DaemonicWrite<GLASS>      ::write_str/char/fmt → Obs<()>   │
// │  DaemonicOctal<GLASS>      ::fmt() → Observation<()>        │
// │  Binary<GLASS>             ::fmt() → Observation<()>        │
// │  DaemonicLowerHex<GLASS>   ::fmt() → Observation<()>        │
// │  DaemonicUpperHex<GLASS>   ::fmt() → Observation<()>        │
// │  DaemonicPointer<GLASS>    ::fmt() → Observation<()>        │
// │  DaemonicLowerExp<GLASS>   ::fmt() → Observation<()>        │
// │  DaemonicUpperExp<GLASS>   ::fmt() → Observation<()>        │
// │                                                             │
// │  DaemonicFormatter<'buffer, GLASS> (struct)                 │
// │  DaemonicFormattingOptions (struct: flags, width, precision)│
// │  DaemonicArguments<'args, GLASS: Glass<GLASS>> [NO Error bd]│
// │  DaemonicArgument<'args, GLASS: Glass<GLASS>> [NO Error bd] │
// │  DaemonicPlaceholder (struct)                               │
// │  DaemonicCount (enum: Is, Param, Implied)                   │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                ERROR LAYER (typed failures)                 │
// │  DaemonicError<'e, GLASS>                                   │
// │  │  : Glass<GLASS> (blanket impl)                           │
// │  │  + DaemonicDisplay<GLASS> + DaemonicDebug<GLASS>         │
// │  │  + Send + Sync + 'e                                      │
// │  │                                                          │
// │  ├─ associated: Source, Context, Position                   │
// │  ├─ methods: error_payload(), into_error_payload()          │
// │  ├─ DaemonicErrorExt<'e, GLASS>: DaemonicError (extensions) │
// │  ├─ ErrorContext<'e>: Send + Sync (context carrier)         │
// │  ├─ MetaData<'e>: Send + Sync (metadata carrier)            │
// │  ├─ EnumerationRouter (variant routing)                     │
// │  └─ StdErrorBridge (From impls for std errors)              │
// │                                                             │
// │  Error enum tree (concrete variants):                       │
// │  ├─ OsError (Linux, Windows, Mac subcategories)             │
// │  ├─ ShadeClockError (ClockError, SyncError, etc.)           │
// │  ├─ SymbolicError (6+1 SymbolicInsanity variants)           │
// │  ├─ GenericVariants (fallback)                                 │
// │  └─ BrokenSwordContext { pid, timestamp, source, comment }  │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                MIRROR CHEMISTRY LAYER (bonding algebra)     │
// │  Reflection          { type Cause: ReflectionCause }        │
// │  ReflectionCause     { name(), recoverable() }              │
// │  Reflective          { reflect() }                          │
// │  ReflectionComposite { combine(), assess_stability() }      │
// │  MirrorType<'m>      : Send + Sync { properties() }         │
// │                                                             │
// │  ReflectionProperties { fidelity, temporality, spatiality,  │
// │                         selectivity, energy_cost }          │
// │  Fidelity     (Specular, Lossy(f64), Destructive, Absorptiv)│
// │  Temporality  (Instantaneous, Delayed, Prophetic, None, Var)│
// │  Spatiality   (Identity, Inverted, Transformed, Collapsed)  │
// │  Selectivity  (Complete, Partial, Single, None)             │
// │  EnergyCost   (Minimal, Finite, Sustained, Unbounded)       │
// │  Stability    (Stable, Metastable, Unstable, Impossible)    │
// │  BondResult   (Compound, Dominated, Contradiction, Unstable)│
// │  BondProvenance { first, second, order_matters }             │
// │  ReflectionGroup (Noble, Reactive, Transitional, Rare, Syn.)│
// │                                                              │
// │  reflection_to_severity() : ReflectionProperties → Severity │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                REPAIR LAYER (self-healing)                  │
// │  RepairEnclosure<GLASS> (baked-in repair, innate immunity)  │
// │  │  fields: creator_id, repair_fn, fingerprint, trust,      │
// │  │          confidence, verification, created_at            │
// │  │  methods: new(), effective_confidence(), execute()       │
// │  │                                                          │
// │  RepairInjection<GLASS> (external repair, adaptive immunity)│
// │  │  fields: injector_id, repair_fn, fingerprint, trust,     │
// │  │          confidence, verification                        │
// │  │  methods: quarantine_check(), execute()                   │
// │  │                                                          │
// │  RepairStack<GLASS> { self_repair, local, global }           │
// │  │  methods: attempt_repair() → 3-level dispatch            │
// │  │                                                          │
// │  RepairResult (Repaired, Improved, Failed, Panicked,         │
// │                FingerprintMismatch)                           │
// │  RepairFingerprint { context_hash, expected_in/out,          │
// │                      function_checksum }                     │
// │  RepairTrust (Local, Verified{signer}, Untrusted)            │
// │  RepairVerification (Verified{hash,ver}, Unverified)         │
// │                                                              │
// │  SeverityRouter     { route() → FidelityAction }             │
// │  RepairAttempt<G>   { attempt_repair() }                     │
// │  RepairContext       { type Resources }                       │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                SYSCALL LAYER (OS interaction)                │
// │  DaemonicSyscall: Send + Sync                               │
// │  │  type FailureState: GlassState                           │
// │  │                                                          │
// │  ├─ ObservationSyscall: DaemonicSyscall                     │
// │  │     (read-only, passive observation)                     │
// │  ├─ WriteSyscall: DaemonicSyscall                           │
// │  │     type Justification: WriteJustification               │
// │  │     (state mutation, requires justification)             │
// │  └─ ElevatedSyscall: DaemonicSyscall                        │
// │        type ElevationProof: ElevationProof                  │
// │        type Justification: WriteJustification               │
// │        (privileged ops, requires proof + justification)     │
// │                                                              │
// │  WriteJustification: Send + Sync { justify(), signer() }    │
// │  ElevationProof: Send + Sync { verify(), authority_chain() }│
// │  Authorizer: Send + Sync { authorize(), can_elevate() }     │
// │  PeerReviewable { request_review(), review_count() }        │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                ENTITY LAYER (living observers)               │
// │  Daemonic (root identity trait)                              │
// │  │  type Clock: DaemonicClock                               │
// │  │  fn id() → u32                                           │
// │  │  fn clock() → &Clock                                     │
// │  │                                                          │
// │  ├─ Entity: Daemonic (death-aware)                          │
// │  │     fn broken_sword(err) → DaemonicError                 │
// │  │                                                          │
// │  └─ ShadeClock: Daemonic + Send + Sync (clock convenience)  │
// │        fn get_time() → Result<Timestamp, DaemonicError>     │
// │        fn daemonic_unwrap() → u64 (panic on clock failure)  │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                WALKER LAYER (ephemeral observers)            │
// │  WalkerInput: Send + Sync                                   │
// │  │  fn validate() → Result  [INPUT validation]              │
// │  │                                                          │
// │  WalkerOutput: Send + Sync + 'static                        │
// │  │  (blanket impl, no validation currently)                 │
// │  │                                                          │
// │  Walker: Send + Sync                                         │
// │  │  type Input: WalkerInput                                 │
// │  │  type Output: WalkerOutput                               │
// │  │  fn process(input) → WalkerResult<Output>                │
// │  │  fn cancel()                                              │
// │  │                                                          │
// │  ├─ WalkerProgress: Walker (progress reporting)             │
// │  │     fn progress() → (processed, total)                   │
// │  │                                                          │
// │  ├─ WalkerBatch: Walker (batch processing)                  │
// │  │     fn batch_size() → usize                              │
// │  │                                                          │
// │  └─ WalkerLimits: Walker (resource constraints)             │
// │        fn max_depth() → usize                               │
// │        fn max_items() → usize                               │
// │        fn timeout() → DaemonicDuration                               │
// │                                                              │
// │  WalkerHandle (struct: JoinHandle + cancel token)            │
// │  WalkerState (enum: Created, Running, Completed, etc.)       │
// │  WalkerResult<T> (struct: output, time_range, stats)         │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                NETWORK LAYER (mesh coordination)            │
// │  MeshNetwork: Send + Sync                                   │
// │  │  fn peers() → peer list                                  │
// │  │  fn broadcast(msg)                                       │
// │  │  fn consensus(proposal) → result                         │
// │  │                                                          │
// │  (Future: MeshClock, ShadeDiscovery, PeerAuth)              │
// └──────────────────────────┬──────────────────────────────────┘
//// ┌──────────────────────────┴──────────────────────────────────┐
// │                CORE LAYER (composition root)                 │
// │  DaemonicCore<GLASS>                                         │
// │  │  : DaemonicClock + DaemonicObserver + Anchor             │
// │  │                                                          │
// │  │  type Clock: DaemonicClock + TemporalAnchor + RateAnchor │
// │  │  type Observer: DaemonicObserver + PerceptualAnchor       │
// │  │                 + CausalAnchor                           │
// │  │                                                          │
// │  │  fn core_anchor_domains() → AnchorDomainSet              │
// └─────────────────────────────────────────────────────────────┘
//
// ═══════════════════════════════════════════════════════════════
// COMPOSITION ALGEBRA (G1-G10 + proposed G11)
// ═══════════════════════════════════════════════════════════════
//
// G1:  Closure         ∀ g₁,g₂ ∈ G: g₁ ⊕ g₂ ∈ G
// G2:  Identity        ∃ e (Specular): e ⊕ g = g ⊕ e = g
// G3:  Sev. Monotone   sev(g₁ ⊕ g₂) ≥ max(sev(g₁), sev(g₂))
// G4:  Tier Monotone   tier(g₁ ⊕ g₂) ≥ max(tier(g₁), tier(g₂))
// G5:  Annihilation    Impossible/Shattered absorb everything
// G6:  Involution      inv(inv(g)) = g [for Inverted spatiality]
// G7:  Cond. Commute   Commutative iff no Transformed spatiality
// G8:  Repair Damp     Repair absorbs cracks mid-chain
// G9:  Category Excl.  Lattice distance determines legality/cost
// G10: Prophetic Inst. Prophetic destabilizes compounds
// G11: Anchor Reliab.  reliability(A⊕B) ≤ √(rel(A)·rel(B))

mod build;
pub mod daemonic;
const DAEMONIC_ERROR_TOPOLOGY_SEGMENT: TopologySegment = TopologySegment::new("Daemonic::Glass::Error::DaemonicError<'error>: 'error");
/// # DaemonicError — Observation-oriented error handling
///
/// DaemonicError is the primary trait for errors in the Daemonic ecosystem.
/// Every error is an observation. Every observation has a Glass state.
///
///
/// ## Payload Semantics:
///
/// Not all errors are dark. The GLASS parameter represents the payload type
/// that MAY be present depending on severity:
///
/// - Stable: payload guaranteed (this is an observation, not really an "error") - Must implement separately for types that are infallible
/// - Cracked: payload present with caveats (partial success, annotated value)
/// - Fractured: payload MAY be present (partial data, possibly corrupted)
/// - Warped: payload present but unreliable (came back wrong)
/// - Drift: payload from a different state than expected
/// - Shattered: always dark, no payload
/// - Impossible: always dark, should not exist
/// - Paradox: multiple contradictory payloads possible
/// - Opaque: payload exists but is frame-locked
/// - Echo: payload from a different time
/// - Unknown: unassessed, payload status unknown
/// The dyn-compatible core of DaemonicError.
///
/// Designed to work with `Box<dyn DaemonicError<'_>>`.
/// All methods return concrete types or references — no impl Trait,
/// no generic type parameters on methods.
///
/// The GLASS type parameter is the error's payload type — what the
/// error wraps or describes. For dark errors (Shattered, Impossible),
/// payload is always None. For light errors (Cracked, Fractured),
/// payload may contain partial or recoverable data.
#[allow(multiple_supertrait_upcastable)] // inherited from Std::Error
pub trait DaemonicError<'error>: 'error
{
	#[must_use = "this method returns a DaemonicEmission<GLASS = Error> (type defaulted to Error, rebind at callsite if override necessary), which is a concrete type and must be used when DaemonicError is implemented over a type"]
	#[rustc_on_unimplemented = "This Method is NOT Optional, if you Declare an item is a DaemonicError, you MUST define an emit function for it."]
	#[allow(clippy::type_complexity)]
	fn emit(self) -> DaemonicEmission;
	/// When implementing DaemonicError, you need a TopologySegment.
	///
	/// Use `TopologySegment::new("Daemonic::Glass::Consumer::YourTypeHere")`
	///
	/// for nested consumer segments:
	/// `TopologySegment::new("Daemonic::Glass::Consumer::YourTypeHere::YourNestedTypeHere")`
	///
	/// for functions inside nested blobs:
	/// `TopologySegment::new("Daemonic::Glass::Consumer::YourTypeHere::YourNestedTypeHere::new()")`
	///
	/// Should not require implementing TopologyAnchor yet, but when it does it will also be used here.
	/// Look to `use daemonic_derive` crate for TopologySegmentat and Anchor derivation procedural macros.
	/// A more formal DaemonicError lexicon for TopologySegmentation is planned.
	/// For now, use standard Rust pattern logic with PascalCase for types and traits, SCREAMING_CASE for consts and statics, and lowercase for functions and methods.
	/// Should also be noted that including type and function signatures is also useful for debugging and logic inference during runtime reflection.
	fn position(&self) -> &TopologySegment;
	/// What severity level is this error?
	/// This maps directly to Glass severity — the match quality spectrum.
	/// Determines fidelity_action, recoverability, and payload availability.
	#[must_use]
	fn severity_level(&self) -> Severity {
		Severity::Unknown
	}
	
	/// New, in development
	fn repair_manifest(&self) { () }
	
	/// Is this error recoverable?
	/// Default: derived from severity.
	/// Stable/Cracked = recoverable (payload intact).
	/// Fractured/Drift = maybe (payload may be partial).
	/// Everything else = no.
	fn is_recoverable(&self) -> bool {
		/// Stable always recoverable because nothing was fucked to start with
		/// Cracked is always recoverable and constitutes a light error or moderate (nonfatal) warning.
		matches!(self.severity_level(), Severity::Stable | Severity::Cracked)
	}
}
const DAEMONIC_EMISSION_ERROR_TOPOLOGY_SEGMENT: TopologySegment = TopologySegment::new("Daemonic::Glass::Error::DaemonicError::DaemonicEmission");
pub struct DaemonicEmission {
	inner: Box<daemonic::observation::Stable<Error>>,
}
impl Glass<DaemonicEmission> for DaemonicEmission {
	type Anchor = TopologySegment;
	
	fn position(&self) -> &TopologySegment {
		&DAEMONIC_EMISSION_ERROR_TOPOLOGY_SEGMENT
	}
	
	fn severity(&self) -> Severity {
		Severity::Unknown
	}
	
	fn payload(&self) -> Option<&DaemonicEmission> {
		Some(self)
	}
	
	fn into_payload(self) -> Option<DaemonicEmission>
		where
			Self: Sized,
			DaemonicEmission: Sized
	{
		Some(self)
	}
}
impl DaemonicEmission {
	/// when constructing a new DaemonicEmission, the call site needs to be bound with whatever Type inner self resolves to as GLASS
	pub fn new(observation: daemonic::observation::Stable<Error>) -> Self {
		Self {
			inner: Box::new(observation)
		}
	}
	// pub fn inspect_emission<'a>(&self, emission: &'a DaemonicEmission) -> (Annotation, &'a GLASS, &TopologySegment, Severity, ObservationTier) {
	// 	let (annotation,
	// 		payload,
	// 		position,
	// 		severity,
	// 		tier) = (emission.inner.extract_annotation(), emission.inner.unwrap_payload().to_owned(), emission.inner.extract_position(), emission.inner.extract_severity(), emission.inner.extract_tier());
	// 	(annotation, payload, position, severity, tier)
	// }
	/// The emission itself. Always Stable. Infallible.
	// pub fn emission(&self) -> &daemonic::observation::Stable<GLASS> { self.inner.as_ref() }
	
	// The observed error state inside the emission.
	// `SAFETY`
	// Stable State constructors guarantee this value is both present and in scope
	// pub fn error(&self) -> &Error { self.inner.unwrap_payload() }
	
	/// The severity of the ORIGINAL error, not the emission.
	/// Emission severity: always Stable (infallible).
	/// Error severity: whatever actually happened.
	pub fn error_severity(&self) -> Severity { self.inner.extract_severity() }
	
	/// Position of the original error.
	pub fn position(&self) -> &TopologySegment {
		self.inner.extract_position()
	}
	
	/// Annotation from the original error.
	pub fn annotation(&self) -> Annotation { self.inner.extract_annotation() }
}
/// Map severity to fidelity action.
/// Extracted as a free function so both Glass and DaemonicError
/// can use the same mapping without duplication.
pub fn severity_to_fidelity(severity: Severity) -> FidelityAction {
	match severity {
		Severity::Stable => FidelityAction::Continue,
		Severity::Cracked => FidelityAction::Warn,
		Severity::Fractured => FidelityAction::Halt,
		Severity::Warped => FidelityAction::Halt,
		Severity::Shattered => FidelityAction::Halt,
		Severity::Impossible => FidelityAction::Abort,
		Severity::Unknown => FidelityAction::Attend,
		Severity::Drift => FidelityAction::Attend,
		Severity::Paradox => FidelityAction::Warn,
		Severity::Opaque => FidelityAction::Halt,
		Severity::Echo => FidelityAction::Attend,
	}
}

/// Contextualized error report — GlassReport + error-specific metadata.
pub struct ContextualizedReport {
	pub report: GlassReport,
	pub is_recoverable: bool,
	pub has_payload: bool,
	pub source_position: Option<TopologySegment>,
}

/// Extension methods for DaemonicError that require generic type parameters.
/// These cannot go on the core trait because they break dyn-compatibility.
///
/// These methods are for Rust compiler integration (Diagnostics, Subdiagnostics)
/// and are NOT needed for general error handling. Most users never touch this.
pub trait DaemonicErrorExt<'error, GLASS>: DaemonicError<'error> {
	// TODO: THESE HAVE BEEN TEMPORARILY DISABLED PENDING DAEMONIC LATTICE COMPLETION
	// This is technically rust logic, so falls outside scope for the moment
	// Emit as a Rust compiler Diagnostic.
	// Requires a SPAN, not a Glass observation.
	// Only useful in compiler/tooling contexts.
	// fn emit_diagnostic<D: Diagnostic<'error>>(&self) -> D {
	// 	unimplemented!(
	// 		"[DAEMONIC-ERROR] Diagnostic emission requires compiler context. \
	//          Use as_error_report() for general-purpose error reporting."
	// 	)
	// }
	//
	// Emit as a Rust compiler Subdiagnostic.
	// Requires a parent Diagnostic to anchor on.
	// fn emit_subdiagnostic<S: Subdiagnostic>(&self) -> S {
	// 	unimplemented!(
	// 		"[DAEMONIC-ERROR] Subdiagnostic emission requires compiler context. \
	//          Use as_error_report() for general-purpose error reporting."
	// 	)
	// }
}


pub trait EnumerationRouter {
	// Where does this enum route to in the position tree?
	// fn route_position(&self) -> Position;
}

#[doc = " Convert any std Error into a Generic DaemonicError."]
#[doc = " This is the incremental adoption path — wrap existing errors"]
#[doc = " at the boundary between std code and Daemonic code."]
#[doc = " The wrapped error gets Shattered severity (we know it failed,"]
#[doc = " we don\'t know the Daemonic classification)."]
pub struct StdErrorBridge {
	position: TopologySegment,
	message: String,
	source_type: &'static str,
}
/// Standard Error Bridge Topology Anchor
const STDERRORBRIDGE_TOPOLOGY: crate::daemonic::TopologySegment = crate::daemonic::TopologySegment {
	label: "Daemonic::Glass::Consumer::StdErrorBridge",
	hash: crate::const_daemonic_hash(
		"Daemonic::Glass::Consumer::StdErrorBridge".as_bytes(),
		crate::AXIOM_OFFSET,
	),
	crypto_id: crate::const_daemonic_hash(
		"Daemonic::Glass::Consumer::StdErrorBridge".as_bytes(),
		crate::TOPOLOGY_ANCHOR,
	),
	depth: 3u16,
};

// unsafe impl<A: SpatialAnchor> Anchorable for StdErrorBridge<A> {}

unsafe impl Send for StdErrorBridge {}

unsafe impl Sync for StdErrorBridge {}

impl Anchor for StdErrorBridge {
	fn anchor_domains(&self) -> crate::daemonic::AnchorDomainSet {
		crate::daemonic::AnchorDomainSet::SPATIAL
			.union(crate::daemonic::AnchorDomainSet::STRUCTURAL)
			.union(crate::daemonic::AnchorDomainSet::SYMBOLIC)
	}
}
impl SymbolicAnchor for StdErrorBridge {
	type Anchor = crate::daemonic::TopologySegment;
	fn meaningful_within(&self) -> Self::Anchor {
		STDERRORBRIDGE_TOPOLOGY.clone()
	}
}
impl crate::daemonic::SemanticAnchor for StdErrorBridge {}
impl crate::daemonic::SpatialAnchor for StdErrorBridge {
	fn anchor_position(&self) -> &crate::daemonic::TopologySegment {
		&STDERRORBRIDGE_TOPOLOGY
	}
	fn neighbors(&self) -> crate::daemonic::TopologySegment {
		STDERRORBRIDGE_TOPOLOGY.clone()
	}
}
impl crate::daemonic::StructuralAnchor for StdErrorBridge {
	fn contract_description(&self) -> &str {
		"StdErrorBridge: auto-derived Daemonic anchor via #[daemonic] proc macro"
	}
}
impl TopologyAnchor for StdErrorBridge {
	fn parent(&self) -> Option<crate::daemonic::TopologySegment> {
		let label = STDERRORBRIDGE_TOPOLOGY.label;
		label
			.rsplit_once("::")
			.map(|(parent, _)| <GlassError as TopologyAnchor>::new_anchor(parent)) // todo: GlassError needs to be updated to something else
	}
	fn children(&self) -> &[crate::daemonic::TopologySegment] {
		&[]
	}
	fn segments(&self) -> &crate::daemonic::TopologySegment {
		&STDERRORBRIDGE_TOPOLOGY
	}
	fn depth(&self) -> usize {
		STDERRORBRIDGE_TOPOLOGY.depth as usize
	}
}

impl crate::daemonic::glass::Glass<StdErrorBridge> for StdErrorBridge {
	type Anchor = TopologySegment;
	fn position(&self) -> &crate::daemonic::TopologySegment {
		&STDERRORBRIDGE_TOPOLOGY
	}
	fn severity(&self) -> Severity {
		Severity::Stable
	}
	fn tier(&self) -> crate::daemonic::glass::ObservationTier {
		crate::daemonic::glass::ObservationTier::Composed
	}
	fn payload(&self) -> Option<&StdErrorBridge> {
		Some(self)
	}
	fn into_payload(self) -> Option<StdErrorBridge> {
		Some(self)
	}
}
impl StdErrorBridge
{
	pub fn from_std<E: core::error::Error>(err: E) -> Self {
		Self {
			position: STDERRORBRIDGE_TOPOLOGY,
			message: err.to_string(),
			source_type: core::any::type_name::<E>(),
		}
	}
	
	// pub fn from_io(err: core::io::Error) -> Self {
	// 	Self {
	// 		position: pos!("OS", "IO"),
	// 		message: err.to_string(),
	// 		source_type: "std::io::Error",
	// 	}
}
struct Meta {
	message: Option<String>,
}
const DIES_IN_TRANSIT_TOPOLOGY_SEGMENT: TopologySegment = TopologySegment::new("Daemonic::PREDICATE::DIES_IN_TRANSIT<GLASS: Clone>(observation: Observation<GLASS>, violation: TransitViolation, crossing_point: &'static TopologySegment)");
/// This is not a normal function, this free floating function should not be callable or importable outside this module.
/// Note and Warning: DO NOT USE THIS FUNCTION IF YOU HAVE NO IDEA WHAT YOU ARE DOING
/// CARELESS USE ****WILL**** BREAK SHIT
#[allow(non_snake_case)]
pub(crate) fn DIES_IN_TRANSIT<GLASS: Glass<GLASS> + Clone>(observation: ::daemonic_error::daemonic::observation::Observation<GLASS>, violation: TransitViolation, crossing_point: &'static TopologySegment) -> DaemonicEmission {
	// 1. DETECT: the violation is already identified by the caller.
	//    The caller (frame_cast, mesh, compiler): detected the problem.
	//    This function: doesn't detect. It PROCESSES the death.
	
	// 2. ANNOUNCE: silent to the machine.
	//    No panic. No crash. No exception.
	//    The observation: is consumed. Gone. Dead.
	//    The caller: receives the receipt. Continues.
	
	// 3. RECEIPT: drop a death certificate.
	//    Contains: what died, where, why, when.
	//    Wrapped in: DaemonicEmission (Stable<Error>).
	//    Infallible: the recording always succeeds.
	let dummy_target_frame = TopologySegment::new("Transit Death Report Topology Segmentation logic still under construction");
	
	let report = TransitDeathReport {
		crossing_point,
		source_frame: observation.extract_topology_segment().clone(),
		target_frame: dummy_target_frame,
		violation,
	};
	
	// The observation: consumed here. DIES here.
	// Moved into the function. Not returned. Gone.
	// drop(observation) is implicit.
	// The data: is destroyed. Axiom 1 applies to the RECEIPT, not the data.
	// The receipt: preserves the INFORMATION about what died.
	// The data itself: is gone. That's the point. It SHOULD be gone.
	// A lie that survives: is worse than a lie that dies.
	// Foundational Daemonic Logic Understanding boils down to: DECEPTIVE STATES DIE IN TRANSIT
	// MALICIOUS STATES DIE IN TRANSIT
	// MALICIOUSLY CRAFTED STATE REQUESTS DIE IN TRANSIT
	// ATTEMPTED COERCION OF ANOTHER STATEFUL GLASS WITHOUT OBSERVER KEYS DIE IN TRANSIT
	// INVALID OR CORRUPTED SEMANTIC INPUTS TO UNSANITZED BOUNDARIES DIE IN TRANSIT
	
	DaemonicEmission::new(obs_states::Stable::new(
		Error::Daemonic((DaemonicVariants::Glass(GlassError::TransitError(TransitError {
			report,
		})))),
		crossing_point,
	)
	)
}
pub struct TransitDeathReport {
	/// Where the crossing was attempted.
	crossing_point: &'static TopologySegment,
	/// The source frame (where the observation came from).
	source_frame: TopologySegment,
	/// The target frame (where it tried to go).
	target_frame: TopologySegment,
	/// What specifically was invalid about the attempt.
	violation: TransitViolation,
}

pub enum TransitViolation {
	/// Severity transition not permitted.
	/// e.g., Shattered → Stable without heal().
	InvalidSeverityTransition {
		from: Severity,
		to: Severity,
	},
	/// Payload required by target but absent in source.
	/// e.g., casting to Stable but payload is None.
	PayloadAbsent,
	/// Payload present but incompatible with target frame.
	PayloadIncompatible,
	/// Frame types are fundamentally incompatible.
	IncompatibleFrames,
	/// Custom violation with annotation.
	Custom(Annotation),
}
struct TransitError {
	report: TransitDeathReport,
}