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)
//! Glass<GLASS> — The observation effect.
//!
//! Models a transition that produced (or failed to produce) a GLASS object (mirror).
//! GLASS is not inside the Glass. GLASS IS what was reflected through it.
//! The glass state describes what happened during the transition.
//!
//! Glass is the step, not the destination.
//! Meaning lives in the steps between nodes.
//!
//! # Glass as Pattern Matching Engine
//!
//! Glass<GLASS> is the type-level expression of a self-bootstrapping pattern matcher.
//! Every Glass implementation is a template. Every observation through Glass is a match
//! operation. Every match result is a new template. The system generates its own matching
//! patterns through operation.
//!
//! # Sizing Invariant
//!
//! Glass is FRAME AGNOSTIC with respect to sizing. Both Sized and Unsized types
//! can implement this trait. The `GLASS` type parameter carries no `Sized` bound.
//! Methods that require moving the payload by value (`into_payload`) are gated
//! behind `where Self: Sized`. This is not a limitation — it's correct behavior.
//! An unsized type's Glass can be observed but not consumed.
//!
//! If the Glass can only handle Sized OR Unsized objects but not both,
//! that is DESIGN FAILURE.
// pub use crate::daemonic::observation::display::*;
use alloc::string::{String, ToString};
use core::fmt::{Formatter, Pointer};
use core::marker::PhantomData;
use core::ops::{ControlFlow, FromResidual, Try};
use crate::daemonic::{
	// Anchorable,
	Daemonic, SymbolicAnchor, TopologySegment};
use crate::daemonic::{Anchor, AnchorDomainSet, TemporalAnchor};
use crate::{const_daemonic_hash, DaemonicError, AXIOM_OFFSET};
pub mod error;
pub mod states;
pub mod primitive_implementations;
pub mod daemonic_path_buffer;
pub use error::*;
use crate::daemonic::glass::daemonic_system_call::DaemonicSystemCall;
use crate::daemonic::TopologyAnchor;

pub mod glass_flags;


// ═══════════════════════════════════════════════════════════════
// SEVERITY (Primary axis: match quality)
// ═══════════════════════════════════════════════════════════════

/// Primary axis: what survived the transition.
///
/// Severity is the MATCH QUALITY of the observation — how well the input
/// resolved against the Glass. Every Glass observation produces a Severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Severity {
	/// Perfect match. Payload guaranteed.
	Stable,
	/// Partial match with minor discrepancies. Payload present but annotated.
	Cracked,
	/// Partial match with significant loss. Payload may or may not be present.
	Fractured,
	/// The observation changed between measurements.
	Drift,
	/// The observation came back different from what was sent.
	Warped,
	/// Complete match failure. No usable payload.
	Shattered,
	/// This state should not exist. Physics/axiom violation.
	Impossible,
	/// Multiple contradictory but individually valid matches.
	Paradox,
	/// Match exists but cannot be observed from this reference frame.
	Opaque,
	/// Valid observation from a different temporal frame.
	Echo,
	/// Matching has not been attempted.
	Unknown,
}
impl core::fmt::Display for Severity {
	fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
		f.write_str(match self {
			Severity::Stable => "Stable",
			Severity::Cracked => "Cracked",
			Severity::Fractured => "Fractured",
			Severity::Drift => "Drift",
			Severity::Warped => "Warped",
			Severity::Shattered => "Shattered",
			Severity::Impossible => "Impossible",
			Severity::Paradox => "Paradox",
			Severity::Opaque => "Opaque",
			Severity::Echo => "Echo",
			Severity::Unknown => "Unknown",
		})
	}
}
// ═══════════════════════════════════════════════════════════════
// OBSERVATION TIER
// ═══════════════════════════════════════════════════════════════

/// At what abstraction tier was this observation made?
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ObservationTier {
	/// Cannot be broken down further. Finite, fully enumerable.
	Absolute,
	/// Conceptually atomic but substrate-decomposable. u8, i32, bool, char.
	Primitive,
	/// Structures composed from primitives. Most application types.
	Composed,
	/// Symbols that carry their own instruction logic. Glass states, errors.
	GlyphicExecutable,
	Unknown,
	Opaque,
}

// ═══════════════════════════════════════════════════════════════
// SUPPORTING ENUMS
// ═══════════════════════════════════════════════════════════════

/// What's attached to the observation
#[derive(Clone, Debug)]
pub enum Annotation {
	None,
	Note(String),
	Help(String),
	Suggestion(String),
	/// Sensitive annotation — redacted in serialized output
	Sensitive(String),
}
impl core::fmt::Display for Annotation {
	fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
		f.write_str(match self {
			Annotation::None => "",
			Annotation::Note(s) => s,
			Annotation::Help(s) => s,
			Annotation::Suggestion(s) => s,
			Annotation::Sensitive(_) => "Sensitive",
		})
	}
}
/// When did this observation originate relative to current frame
#[derive(Debug, Clone, Copy)]
pub enum Temporal {
	Current,
	Echo { original_tick: u64 },
	Drift { from_severity: Severity, to_severity: Severity },
}

impl Anchor for Temporal {
	fn anchor_domains(&self) -> AnchorDomainSet {
		AnchorDomainSet::TEMPORAL
	}
}

impl TemporalAnchor for Temporal {
	fn anchor_tick(&self) -> u64 {
		1
	}
}
/// Can the observer see through
#[derive(Debug, Clone)]
pub enum Accessibility {
	Clear,
	Opaque { reason: String },
}


/// One observation or contradictory multiples
#[derive(Debug, Clone, Copy)]
pub enum Consistency {
	Singular,
	Paradox,
}

/// Has fidelity been assessed
#[derive(Debug, Clone, Copy)]
pub enum Assessment {
	Assessed,
	Unknown,
}

/// What should the observer do
#[derive(Debug, Clone, Copy)]
pub enum FidelityAction {
	Continue,
	Attend,
	Warn,
	Halt,
	Abort,
	/// Emergency containment — destroy the Glass to prevent propagation.
	Drop,
}

// ═══════════════════════════════════════════════════════════════
// GLASS TRAIT
// ═══════════════════════════════════════════════════════════════

/// The core observation trait. Everything passes through Glass.
/// ```text
/// Glass ≅ ∀F. (Glass → F(Glass)) → F(Glass)
/// ```
pub trait Glass<GLASS: ?Sized>:
{
	type Anchor: TopologyAnchor;
	// ── Axes (what happened during this transition) ─────
	
	fn position(&self) -> &TopologySegment;
	fn severity(&self) -> Severity;
	
	fn annotation(&self) -> Annotation {
		Annotation::None
	}
	
	fn temporal(&self) -> Temporal {
		Temporal::Current
	}
	
	fn accessibility(&self) -> Accessibility {
		Accessibility::Clear
	}
	
	fn consistency(&self) -> Consistency {
		Consistency::Singular
	}
	
	fn assessment(&self) -> Assessment {
		Assessment::Unknown
	}
	
	fn tier(&self) -> ObservationTier {
		ObservationTier::Composed
	}
	
	// ── Payload (what resulted from this transition) ────
	
	fn payload(&self) -> Option<&GLASS>;
	
	fn into_payload(self) -> Option<GLASS>
		where
			Self: Sized,
			GLASS: Sized;
	
	// ── Derived (free, computed from axes) ──────────────
	
	fn fidelity_action(&self) -> FidelityAction {
		severity_to_fidelity(self.severity())
	}
	
	fn has_payload(&self) -> bool {
		self.payload().is_some()
	}
	
	fn is_clear(&self) -> bool {
		matches!(self.severity(), Severity::Stable)
			&& matches!(self.assessment(), Assessment::Assessed)
	}
	
	// ── Reporting (type-erased observation export) ──────
	fn as_report(&self) -> GlassReport {
		GlassReport {
			position: self.position().clone(),
			severity: self.severity(),
			tier: self.tier(),
			annotation: self.annotation(),
			temporal: self.temporal(),
			accessibility: self.accessibility(),
			consistency: self.consistency(),
			assessment: self.assessment(),
			fidelity_action: self.fidelity_action(),
		}
	}
}

/// Map severity to fidelity action.
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,
	}
}

// ═══════════════════════════════════════════════════════════════
// GLASS REPORT (type-erased observation)
// ═══════════════════════════════════════════════════════════════

/// Type-erased Glass observation report.
/// Contains all observation AXES but not the PAYLOAD.
/// Universal exchange format for Glass observations.
// #[derive(Debug, Clone)]
pub struct GlassReport {
	pub position: TopologySegment,
	pub severity: Severity,
	pub tier: ObservationTier,
	pub annotation: Annotation,
	pub temporal: Temporal,
	pub accessibility: Accessibility,
	pub consistency: Consistency,
	pub assessment: Assessment,
	pub fidelity_action: FidelityAction,
}

impl GlassReport {
	pub fn is_clear(&self) -> bool {
		matches!(self.severity, Severity::Stable)
			&& matches!(self.assessment, Assessment::Assessed)
	}
	
	pub fn needs_attention(&self) -> bool {
		!matches!(self.fidelity_action, FidelityAction::Continue)
	}
	
	pub fn category(&self) -> &str {
		todo!(
			"GlassReport::category() is not yet implemented"
		)
	}
}

// ═══════════════════════════════════════════════════════════════
// GLASS STATE TRAITS
// ═══════════════════════════════════════════════════════════════

/// Guaranteed payload — Stable ALWAYS has a value.
pub use states::*;
/// Clear glass. Payload guaranteed. Passthrough.
///
/// Types implementing GlassStable are making a compile-time
/// promise: there IS a value here. Not Option. Not maybe.
/// The transition succeeded fully.
pub use {GlassStable};
/// Damaged but contained. Non-propagating.
/// The crack exists but isn't spreading.
/// Key property: can_cascade returns false.
pub use {GlassCracked};
/// Information lost. Structure holds but data is incomplete.
/// Unlike Cracked, Fractured CAN cascade.
pub use {GlassFractured};
/// Total information loss. Nothing came through.
/// The glass absorbed everything.
/// May carry debris — fragments that can be inspected
/// but not used as values.
pub use {GlassShattered};
/// Unassessed observation. Fidelity genuinely unknown.
/// Payload may or may not exist.
/// Not an error — just hasn't been evaluated yet.
/// Resolution: re-observe with more context.
pub use {GlassUnknown};
/// Temporally displaced observation.
/// Data may be perfect but it's from a different time.
/// The reflection arrived late.
pub use {GlassEcho};
/// Should not exist. Medium or observer is broken.
/// Propagation ceiling exceeded. Laws violated.
/// If you're holding this, something is deeply wrong
/// and it's not the data — it's the system.
/// Impossible (hard): The state CANNOT be constructed. The type system prevents it. 
/// If you're holding an Impossible, a language invariant broke — the compiler failed to prevent something it should have prevented. 
/// This is a substrate-level failure. The entity didn't do anything wrong. The floor fell out from under it. 
/// The correct response is Broken Sword — document everything and terminate, 
/// because the system's guarantees have been violated and nothing can be trusted.
/// Paradox (soft impossible): The state LOOKS impossible from the current reference 
/// frame but might be valid from another frame. Incomplete context produces apparent 
/// impossibility. Two observations that each survive adversarial testing independently but 
/// contradict each other. This isn't a substrate failure — it's an information failure. The
/// correct response is Attend, not Abort. Gather more context. Check other frames. The paradox
/// might resolve with additional observation.
pub use {GlassImpossible};
/// Faithful but uninterpretable by current observer.
/// Information exists behind the glass but can't be seen through.
/// The Black glass protocol's external face.
pub use {GlassOpaque};
/// Irreversible transformation. State cannot be trusted.
/// What came back is not what was sent.
/// Non-reversible by definition.
pub use {GlassWarped};
/// glass state changed during observation.
/// The observation is smeared across a fidelity transition.
/// Need both the starting and ending state to interpret.
pub use {GlassDrift};
pub use {GlassParadox};
use crate::daemonic::topology::TOPOLOGY_ANCHOR;
use super::observation::*;
pub(crate) mod daemonic_system_call;