daemonic_error 0.1.2

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
//! # 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)] // inherited from Std::Error
#![no_std]
extern crate alloc;
extern crate core;
mod opaque_dependencies;
use alloc::format;
use alloc::string::{String, ToString};
// use daemonic_derive::*;
// pub use opaque_dependencies::termcolor::*;
// use std::marker::PhantomPinned;
// ── Bridge: From<std::error::Error> ────────────────
use crate::{
	daemonic::{
		glass::{
			Assessment,
			Annotation,
			Accessibility,
			Consistency,
			FidelityAction,
			GlassReport,
			ObservationTier,
			Temporal,
			daemonic::DaemonicSystemCall,
			generic::{Generic, GenericError},
			daemonic_path_buffer::DaemonicPathBuf as PathBuf,
		},
		// Anchorable,
		TopologyAnchor,
		SymbolicAnchor,
		TopologySegment,
		SemanticAnchor,
		SpatialAnchor,
		StructuralAnchor,
		topology::TOPOLOGY_ANCHOR
	}
};
use daemonic::observation::Severity;
pub use daemonic::{daemonic_core::clock::types::Timestamp};
pub(crate) use daemonic::{
	daemonic_contract::{daemonic_result::mirror_chemistry::*, *},
	daemonic_core::*,
	// observation::display::non_null::{NonNull as DaemonicNonNull, Unique as DaemonicUnique},
	glass::Glass,
	glass::*,
};
use crate::daemonic::Anchor;
use crate::daemonic::frame::ReferenceFrame;
use crate::daemonic::glass::daemonic::GlassError;

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)           │
// │  ├─ GenericError (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;

/// # 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)
/// - Fracture: payload MAY be present (partial data, possibly corrupted)
/// - Warp: 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<'_, GLASS>>`.
/// 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, Fracture),
/// payload may contain partial or recoverable data.
#[allow(multiple_supertrait_upcastable)] // inherited from Std::Error
pub trait DaemonicError<'error>: 'error
{
	fn position(&self) -> &TopologySegment;
	
	fn emit(&self) -> Error;
	/// 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).
	/// Fracture/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)
	}
	
	/// Where did the error originate in source (if different from position)?
	/// Default: None (position IS the source position).
	fn source_position(&self) -> Option<&TopologySegment> {
		None
	}
	
	/// Observation tier for this error.
	/// Default: Composed (most errors are about composed types).
	fn error_tier(&self) -> ObservationTier {
		ObservationTier::Composed
	}
	
	/// Temporal state of this error observation.
	/// Default: Current (the error is happening now).
	fn error_temporal(&self) -> Temporal {
		Temporal::Current
	}
	
	/// Annotation attached to this error.
	/// Default: None. Override to attach notes, help text, or suggestions.
	fn error_annotation(&self) -> Annotation {
		Annotation::None
	}
	
	// ── Reporting (free, derived from above) ────────
	
	/// Produce a type-erased report of this error.
	/// Free for all DaemonicError implementors. No allocation beyond Position clone.
	///
	/// GlassReport captures all observation AXES without the PAYLOAD.
	/// This is the universal error exchange format — log it, serialize it,
	/// aggregate it, alert on it. No type parameters needed to read a report.
	fn as_error_report(&self) -> GlassReport {
		let severity = self.severity_level();
		GlassReport {
			position: self.position().clone(),
			severity,
			tier: self.error_tier(),
			annotation: self.error_annotation(),
			temporal: self.error_temporal(),
			accessibility: Accessibility::Clear,
			consistency: Consistency::Singular,
			assessment: Assessment::Assessed,
			fidelity_action: severity_to_fidelity(severity),
		}
	}
}

/// 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::Fracture => FidelityAction::Halt,
		Severity::Warp => 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) -> crate::daemonic::glass::Severity {
		crate::daemonic::glass::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>,
}