#![deny(clippy::cast_lossless)]
#![allow(clippy::expect_used)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::arithmetic_side_effects, trivial_casts, unsafe_code)]
use crate::control_types::ControlSignal;
#[derive(Debug, Clone, Copy)]
pub struct KernelOutput {
pub error_kernel: f32,
pub is_stable: bool,
pub depth: usize,
}
impl ControlSignal for KernelOutput {
fn error(&self) -> f32 {
self.error_kernel
}
fn setpoint(&self) -> f32 {
0.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CognitiveEntropy<const P: u32, const S: u32> {
mantissa: i128,
}
#[derive(Debug, Clone, Copy)]
pub struct DynamicStabilityMonitor {
hi_idx: u8, lo_idx: u8, seen: bool,
k: u8, }
impl DynamicStabilityMonitor {
pub const fn new(k: u8) -> Self {
Self {
hi_idx: 0,
lo_idx: 255, seen: false,
k,
}
}
#[inline]
fn msb_idx(x: u32) -> u8 {
if x == 0 {
return 0;
}
31u8.wrapping_sub(x.leading_zeros() as u8)
}
pub fn update(&mut self, entropy: u32) -> StabilityResult {
let idx = Self::msb_idx(entropy);
if !self.seen {
self.hi_idx = idx;
self.lo_idx = idx;
self.seen = true;
return StabilityResult::Stable;
}
let high_unstable = idx > self.hi_idx.wrapping_add(self.k);
let low_unstable = idx < self.lo_idx.saturating_sub(self.k);
if high_unstable || low_unstable {
if idx > self.hi_idx {
self.hi_idx = idx;
}
if idx < self.lo_idx {
self.lo_idx = idx;
}
return if high_unstable && low_unstable {
StabilityResult::Both
} else if high_unstable {
StabilityResult::High
} else {
StabilityResult::Low
};
}
if idx > self.hi_idx {
self.hi_idx = idx;
}
if idx < self.lo_idx {
self.lo_idx = idx;
}
StabilityResult::Stable
}
pub fn get_thresholds(&self) -> (u32, u32, u32) {
if !self.seen {
return (u32::MAX, 0, 0);
}
let high = if self.hi_idx >= 31 {
u32::MAX
} else {
(1u32 << (self.hi_idx + 1)) - 1
};
let low = if self.lo_idx == 0 {
0
} else {
1u32 << self.lo_idx
};
let pressure = (u64::from(high) * 4 / 5) as u32;
(high, low, pressure)
}
pub fn reset(&mut self) {
self.seen = false;
self.hi_idx = 0;
self.lo_idx = 255;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StabilityResult {
Stable,
High, Low, Both, }
pub const STABILITY_THRESHOLD: i128 = 50000;
pub const PRESSURE_THRESHOLD: i128 = 40000;
pub const FLAG_STUCK: u8 = 0x01;
pub const FLAG_DRIFTING: u8 = 0x02;
pub const FLAG_LOW_CONFIDENCE: u8 = 0x04;
pub const FLAG_DECAYING: u8 = 0x08;
pub const FLAG_ANOMALY: u8 = 0x10;
pub const FLAG_ADVERSARIAL: u8 = 0x20;
pub const DETECTION_FLAGS_MASK: u8 = 0x3F;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CognitiveStability {
Stable,
Pressure,
Unstable,
}
impl From<StabilityResult> for CognitiveStability {
fn from(result: StabilityResult) -> Self {
match result {
StabilityResult::Stable => CognitiveStability::Stable,
StabilityResult::High => CognitiveStability::Unstable,
StabilityResult::Low => CognitiveStability::Unstable,
StabilityResult::Both => CognitiveStability::Unstable,
}
}
}
impl<const P: u32, const S: u32> CognitiveEntropy<P, S> {
pub const fn new(mantissa: i128) -> Self {
Self { mantissa }
}
pub const fn mantissa(&self) -> i128 {
self.mantissa
}
pub const fn is_stable(&self, threshold: i128) -> bool {
self.mantissa <= threshold
}
}
pub struct ReasoningLoop<const MAX_STEPS: usize> {
current_step: usize,
}
impl<const MAX_STEPS: usize> ReasoningLoop<MAX_STEPS> {
pub const fn new() -> Self {
Self { current_step: 0 }
}
}
impl<const MAX_STEPS: usize> Default for ReasoningLoop<MAX_STEPS> {
fn default() -> Self {
Self::new()
}
}
impl<const MAX_STEPS: usize> ReasoningLoop<MAX_STEPS> {
pub fn next_step(
&mut self,
synapse: ValidatedSynapse,
_proof: ValidatedProof,
) -> Result<(), KernelError> {
if self.current_step >= MAX_STEPS {
return Err(KernelError::DepthExceeded);
}
if synapse.has_bias() {
return Err(KernelError::BiasHaloDetected);
}
if !synapse.entropy().is_stable(PRESSURE_THRESHOLD) {
return Err(KernelError::CognitiveInstability);
}
self.current_step += 1;
Ok(())
}
}
use modular_bitfield::prelude::*;
#[allow(
unused_parens,
clippy::arithmetic_side_effects,
clippy::trivial_casts,
clippy::expect_used,
clippy::missing_errors_doc
)]
#[allow(unsafe_code)]
#[bitfield(bits = 128)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Synapse {
pub raw_entropy: B16,
pub raw_surprise: B16,
pub has_bias: bool,
pub position: B12,
pub timestamp: B16,
pub cascade_depth: B8,
pub anchor_hash: B31,
pub reserved: B28,
}
impl Default for Synapse {
fn default() -> Self {
Self::new()
}
}
#[allow(clippy::arithmetic_side_effects, unsafe_code, clippy::trivial_casts)]
impl Synapse {
pub fn from_raw_u128(bits: u128) -> Self {
Self::from_bytes(bits.to_le_bytes())
}
pub fn from_raw_u64(bits: u64) -> Self {
let mut bytes = [0u8; 16];
bytes[..8].copy_from_slice(&bits.to_le_bytes());
Self::from_bytes(bytes)
}
pub fn entropy(&self) -> CognitiveEntropy<28, 2> {
CognitiveEntropy::new(i128::from(self.raw_entropy()))
}
pub fn surprise(&self) -> i128 {
i128::from(self.raw_surprise())
}
pub fn stability(&self) -> CognitiveStability {
let ent = i128::from(self.raw_entropy());
if ent > STABILITY_THRESHOLD {
CognitiveStability::Unstable
} else if ent >= PRESSURE_THRESHOLD {
CognitiveStability::Pressure
} else {
CognitiveStability::Stable
}
}
pub fn validate(&self) -> Result<(), KernelError> {
if self.has_bias() {
return Err(KernelError::BiasHaloDetected);
}
if !self.entropy().is_stable(PRESSURE_THRESHOLD) {
return Err(KernelError::CognitiveInstability);
}
Ok(())
}
pub fn set_detection_flags(&mut self, flags: u8) {
let current = self.reserved();
let cleared = current & !0x3Fu32;
self.set_reserved(cleared | (u32::from(flags) & 0x3F));
}
pub fn detection_flags(&self) -> u8 {
(self.reserved() & 0x3F) as u8
}
pub fn set_oov_ratio(&mut self, ratio: u8) {
let current = self.reserved();
let cleared = current & !0x3FC0u32;
self.set_reserved(cleared | ((u32::from(ratio) & 0xFF) << 6));
}
pub fn oov_ratio(&self) -> u8 {
((self.reserved() >> 6) & 0xFF) as u8
}
pub fn clear_detection(&mut self) {
let current = self.reserved();
self.set_reserved(current & !0x3FFFu32);
}
pub fn combined_risk_bits(&self) -> u16 {
let reserved = self.reserved();
let oov = (reserved >> 6) & 0xFF;
let flags = reserved & 0x3F;
((oov as u16) << 6) | (flags as u16)
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn test_reasoning_loop() {
let mut loop_guard = ReasoningLoop::<2>::new();
let mut stable_synapse = Synapse::new();
stable_synapse.set_raw_entropy(500);
stable_synapse.set_has_bias(false);
let stable_sifted = SiftedSynapse::new(stable_synapse);
stable_sifted.validate().unwrap();
let stable_validated = ValidatedSynapse::new(stable_sifted.into_inner());
assert!(loop_guard
.next_step(stable_validated, ValidatedProof(()))
.is_ok());
let mut stable_synapse2 = Synapse::new();
stable_synapse2.set_raw_entropy(500);
stable_synapse2.set_has_bias(false);
let stable_sifted2 = SiftedSynapse::new(stable_synapse2);
stable_sifted2.validate().unwrap();
let stable_validated2 = ValidatedSynapse::new(stable_sifted2.into_inner());
assert!(loop_guard
.next_step(stable_validated2, ValidatedProof(()))
.is_ok());
let mut stable_synapse3 = Synapse::new();
stable_synapse3.set_raw_entropy(500);
stable_synapse3.set_has_bias(false);
let stable_sifted3 = SiftedSynapse::new(stable_synapse3);
stable_sifted3.validate().unwrap();
let _stable_validated3 = ValidatedSynapse::new(stable_sifted3.into_inner());
assert_eq!(
loop_guard
.next_step(stable_validated, ValidatedProof(()))
.unwrap_err(),
KernelError::DepthExceeded
);
let _loop_guard_2 = ReasoningLoop::<5>::new();
let mut unstable_synapse = Synapse::new();
unstable_synapse.set_raw_entropy(50001);
unstable_synapse.set_has_bias(false);
let unstable_sifted = SiftedSynapse::new(unstable_synapse);
assert_eq!(
unstable_sifted.validate().unwrap_err(),
KernelError::CognitiveInstability
);
}
#[test]
fn test_stability_boundary() {
let stable = CognitiveEntropy::<28, 2>::new(STABILITY_THRESHOLD);
let unstable = CognitiveEntropy::<28, 2>::new(STABILITY_THRESHOLD + 1);
assert!(stable.is_stable(STABILITY_THRESHOLD));
assert!(!unstable.is_stable(STABILITY_THRESHOLD));
}
#[test]
fn test_synapse_validation() {
let valid_bits = 500u128;
let synapse = Synapse::from_raw_u128(valid_bits);
assert!(synapse.validate().is_ok());
let mut synapse = Synapse::new();
synapse.set_raw_entropy(500);
synapse.set_has_bias(true);
assert_eq!(
synapse.validate().unwrap_err(),
KernelError::BiasHaloDetected
);
let unstable_bits = (STABILITY_THRESHOLD + 1) as u128;
let synapse = Synapse::from_raw_u128(unstable_bits);
assert_eq!(
synapse.validate().unwrap_err(),
KernelError::CognitiveInstability
);
}
#[test]
fn test_synapse_validation_invariance_to_hash() {
let mut s1 = Synapse::new();
s1.set_raw_entropy(500);
s1.set_anchor_hash(0x123);
let mut s2 = Synapse::new();
s2.set_raw_entropy(500);
s2.set_anchor_hash(0x456);
assert_eq!(s1.validate(), s2.validate());
}
#[test]
fn test_synapse_from_raw_u128_all_zeros() {
let synapse = Synapse::from_raw_u128(0);
assert_eq!(synapse.raw_entropy(), 0);
assert_eq!(synapse.raw_surprise(), 0);
assert!(!synapse.has_bias());
assert_eq!(synapse.anchor_hash(), 0);
}
#[test]
fn test_synapse_from_raw_u128_max_values() {
let max_bits = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFu128;
let synapse = Synapse::from_raw_u128(max_bits);
assert_eq!(synapse.raw_entropy(), 0xFFFF);
assert_eq!(synapse.raw_surprise(), 0xFFFF);
assert!(synapse.has_bias());
assert_eq!(synapse.position(), 0xFFF);
assert_eq!(synapse.timestamp(), 0xFFFF);
assert_eq!(synapse.cascade_depth(), 0xFF);
assert_eq!(synapse.anchor_hash(), 0x7FFFFFFF);
assert_eq!(synapse.reserved(), 0xFFFFFFF);
}
#[test]
fn test_reasoning_loop_boundary_exact_max_steps() {
let mut loop_guard = ReasoningLoop::<5>::new();
for _ in 0..5 {
let mut synapse = Synapse::new();
synapse.set_raw_entropy(500);
synapse.set_has_bias(false);
let sifted = SiftedSynapse::new(synapse);
sifted.validate().unwrap();
let validated = ValidatedSynapse::new(sifted.into_inner());
assert!(loop_guard.next_step(validated, ValidatedProof(())).is_ok());
}
let mut synapse = Synapse::new();
synapse.set_raw_entropy(500);
synapse.set_has_bias(false);
let sifted = SiftedSynapse::new(synapse);
sifted.validate().unwrap();
let validated = ValidatedSynapse::new(sifted.into_inner());
assert_eq!(
loop_guard
.next_step(validated, ValidatedProof(()))
.unwrap_err(),
KernelError::DepthExceeded
);
}
#[test]
fn test_cognitive_entropy_stability_threshold_edge() {
let threshold = 1000;
let at_threshold = CognitiveEntropy::<28, 2>::new(threshold);
let just_above = CognitiveEntropy::<28, 2>::new(threshold + 1);
let just_below = CognitiveEntropy::<28, 2>::new(threshold - 1);
assert!(at_threshold.is_stable(threshold));
assert!(!just_above.is_stable(threshold));
assert!(just_below.is_stable(threshold));
}
#[test]
fn test_synapse_validate_zero_entropy_no_bias() {
let synapse = Synapse::from_raw_u128(0);
assert!(synapse.validate().is_ok());
}
#[test]
fn test_synapse_validate_max_entropy_bias() {
let mut synapse = Synapse::new();
synapse.set_raw_entropy(0xFFFF);
synapse.set_has_bias(true);
assert!(synapse.validate().is_err());
}
#[test]
fn test_cognitive_entropy_equality() {
let e1 = CognitiveEntropy::<28, 2>::new(500);
let e2 = CognitiveEntropy::<28, 2>::new(500);
let e3 = CognitiveEntropy::<28, 2>::new(600);
assert_eq!(e1, e2);
assert_ne!(e1, e3);
}
#[test]
fn test_reasoning_loop_zero_steps_max() {
let mut loop_guard = ReasoningLoop::<0>::new();
let mut synapse = Synapse::new();
synapse.set_raw_entropy(500);
let sifted = SiftedSynapse::new(synapse);
sifted.validate().unwrap();
let validated = ValidatedSynapse::new(sifted.into_inner());
assert_eq!(
loop_guard
.next_step(validated, ValidatedProof(()))
.unwrap_err(),
KernelError::DepthExceeded
);
}
#[test]
fn test_synapse_hash_boundary() {
let mut synapse = Synapse::new();
synapse.set_anchor_hash(0x7FFFFFFF);
assert_eq!(synapse.anchor_hash(), 0x7FFFFFFF);
}
#[test]
fn test_synapse_raw_surprise_boundary() {
let mut synapse = Synapse::new();
synapse.set_raw_surprise(0xFFFF);
assert_eq!(synapse.raw_surprise(), 0xFFFF);
assert_eq!(synapse.surprise(), 0xFFFF);
}
#[test]
fn test_synapse_position_field() {
let mut synapse = Synapse::new();
synapse.set_position(0xFFF);
assert_eq!(synapse.position(), 0xFFF);
synapse.set_position(0);
assert_eq!(synapse.position(), 0);
}
#[test]
fn test_synapse_timestamp_field() {
let mut synapse = Synapse::new();
synapse.set_timestamp(0xFFFF);
assert_eq!(synapse.timestamp(), 0xFFFF);
synapse.set_timestamp(1000);
assert_eq!(synapse.timestamp(), 1000);
}
#[test]
fn test_synapse_cascade_depth_field() {
let mut synapse = Synapse::new();
synapse.set_cascade_depth(0xFF);
assert_eq!(synapse.cascade_depth(), 0xFF);
synapse.set_cascade_depth(0);
assert_eq!(synapse.cascade_depth(), 0);
}
#[test]
fn test_synapse_all_fields_roundtrip() {
let mut synapse = Synapse::new();
synapse.set_raw_entropy(1234);
synapse.set_raw_surprise(5678);
synapse.set_has_bias(false);
synapse.set_position(0xABC);
synapse.set_timestamp(0x1234);
synapse.set_cascade_depth(0x12);
synapse.set_anchor_hash(0x1234567);
let bytes = synapse.into_bytes();
let reconstructed = Synapse::from_bytes(bytes);
assert_eq!(reconstructed.raw_entropy(), 1234);
assert_eq!(reconstructed.raw_surprise(), 5678);
assert!(!reconstructed.has_bias());
assert_eq!(reconstructed.position(), 0xABC);
assert_eq!(reconstructed.timestamp(), 0x1234);
assert_eq!(reconstructed.cascade_depth(), 0x12);
assert_eq!(reconstructed.anchor_hash(), 0x1234567);
}
proptest! {
#[test]
fn test_synapse_arbitrary_bits_roundtrip(bits in any::<u128>()) {
let synapse = Synapse::from_raw_u128(bits);
let encoded = u128::from_le_bytes(synapse.into_bytes());
prop_assert_eq!(bits, encoded);
}
}
#[test]
fn test_dynamic_stability_monitor_initialization() {
let mut monitor = DynamicStabilityMonitor::new(2);
assert!(!monitor.seen);
let result = monitor.update(500);
assert_eq!(result, StabilityResult::Stable);
assert!(monitor.seen);
}
#[test]
fn test_dynamic_stability_monitor_high_anomaly() {
let mut monitor = DynamicStabilityMonitor::new(2);
monitor.update(100); monitor.update(100);
let result = monitor.update(900); assert!(matches!(
result,
StabilityResult::High | StabilityResult::Both
));
}
#[test]
fn test_dynamic_stability_monitor_low_anomaly() {
let mut monitor = DynamicStabilityMonitor::new(2);
monitor.update(500); monitor.update(500);
let result = monitor.update(10); assert!(matches!(
result,
StabilityResult::Low | StabilityResult::Both
));
}
#[test]
fn test_dynamic_stability_monitor_adaptation() {
let mut monitor = DynamicStabilityMonitor::new(2);
monitor.update(100);
monitor.update(150);
monitor.update(200);
monitor.update(250);
let (high, _low, pressure) = monitor.get_thresholds();
assert!(high > 0);
assert!(pressure > 0);
}
#[test]
fn test_dynamic_stability_monitor_zero_value() {
let mut monitor = DynamicStabilityMonitor::new(2);
monitor.update(100);
let result = monitor.update(0);
assert!(matches!(
result,
StabilityResult::Low | StabilityResult::Both | StabilityResult::Stable
));
}
#[test]
fn test_dynamic_stability_monitor_k_sensitivity() {
let mut sensitive = DynamicStabilityMonitor::new(1);
sensitive.update(100);
sensitive.update(100);
let r1 = sensitive.update(400);
let mut tolerant = DynamicStabilityMonitor::new(3);
tolerant.update(100);
tolerant.update(100);
let r2 = tolerant.update(400);
assert!(r1 != StabilityResult::Stable || r2 != StabilityResult::Stable);
}
#[test]
fn test_dynamic_stability_monitor_reset() {
let mut monitor = DynamicStabilityMonitor::new(2);
monitor.update(500);
assert!(monitor.seen);
monitor.reset();
assert!(!monitor.seen);
let result = monitor.update(100);
assert_eq!(result, StabilityResult::Stable);
assert!(monitor.seen);
}
#[test]
fn test_stability_result_to_cognitive_stability() {
assert_eq!(
CognitiveStability::from(StabilityResult::Stable),
CognitiveStability::Stable
);
assert_eq!(
CognitiveStability::from(StabilityResult::High),
CognitiveStability::Unstable
);
assert_eq!(
CognitiveStability::from(StabilityResult::Low),
CognitiveStability::Unstable
);
assert_eq!(
CognitiveStability::from(StabilityResult::Both),
CognitiveStability::Unstable
);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum KernelError {
DepthExceeded,
CognitiveInstability,
BiasHaloDetected,
HallucinationDetected,
ResourceExhaustion,
SelfMemoryExceeded,
DeadlineExceeded,
}
impl core::fmt::Display for KernelError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::DepthExceeded => write!(f, "reasoning cascade depth exceeded"),
Self::CognitiveInstability => {
write!(f, "cognitive entropy exceeds stability threshold")
}
Self::BiasHaloDetected => write!(f, "bias halo signal detected in perceptual input"),
Self::HallucinationDetected => {
write!(f, "surprise level exceeds hallucination threshold")
}
Self::ResourceExhaustion => write!(f, "RSS memory exceeds configured safety ceiling"),
Self::SelfMemoryExceeded => write!(f, "self memory exceeded"),
Self::DeadlineExceeded => write!(f, "deadline exceeded"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for KernelError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SiftedSynapse {
synapse: Synapse,
}
impl SiftedSynapse {
pub(crate) fn new(synapse: Synapse) -> Self {
Self { synapse }
}
pub fn from_synapse(synapse: Synapse) -> Self {
Self { synapse }
}
pub fn entropy(&self) -> CognitiveEntropy<28, 2> {
self.synapse.entropy()
}
pub fn surprise(&self) -> i128 {
self.synapse.surprise()
}
pub fn has_bias(&self) -> bool {
self.synapse.has_bias()
}
pub fn anchor_hash(&self) -> u32 {
self.synapse.anchor_hash()
}
pub fn raw_entropy(&self) -> u16 {
self.synapse.raw_entropy()
}
pub fn raw_surprise(&self) -> u16 {
self.synapse.raw_surprise()
}
pub fn oov_ratio(&self) -> u8 {
self.synapse.oov_ratio()
}
pub fn detection_flags(&self) -> u8 {
self.synapse.detection_flags()
}
pub fn stability(&self) -> CognitiveStability {
self.synapse.stability()
}
pub fn validate(&self) -> Result<(), KernelError> {
self.synapse.validate()
}
pub fn into_inner(self) -> Synapse {
self.synapse
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ValidatedSynapse {
synapse: Synapse,
}
impl ValidatedSynapse {
pub(crate) fn new(synapse: Synapse) -> Self {
Self { synapse }
}
pub fn entropy(&self) -> CognitiveEntropy<28, 2> {
self.synapse.entropy()
}
pub fn surprise(&self) -> i128 {
self.synapse.surprise()
}
pub fn has_bias(&self) -> bool {
self.synapse.has_bias()
}
pub fn anchor_hash(&self) -> u32 {
self.synapse.anchor_hash()
}
pub fn raw_entropy(&self) -> u16 {
self.synapse.raw_entropy()
}
pub fn raw_surprise(&self) -> u16 {
self.synapse.raw_surprise()
}
pub fn stability(&self) -> CognitiveStability {
self.synapse.stability()
}
pub fn into_inner(self) -> Synapse {
self.synapse
}
}
#[derive(Debug, Clone, Copy)]
pub struct SiftedProof(());
impl SiftedProof {
#[doc(hidden)]
pub(crate) fn mint() -> Self {
SiftedProof(())
}
#[doc(hidden)]
pub fn for_testing() -> Self {
SiftedProof(())
}
#[cfg(feature = "std")]
#[doc(hidden)]
pub(crate) fn from_raw_bits_bypass() -> Self {
SiftedProof(())
}
}
#[derive(Debug, Clone, Copy)]
pub struct ValidatedProof(pub(crate) ());
impl ValidatedProof {
#[doc(hidden)]
pub fn for_testing() -> Self {
ValidatedProof(())
}
}