use std::fmt;
use std::time::SystemTime;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum PersonalDimension {
CognitiveState,
EmotionalTone,
EnergyLevel,
PerceivedUrgency,
BodySignals,
}
impl fmt::Display for PersonalDimension {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::CognitiveState => write!(f, "cognitive_state"),
Self::EmotionalTone => write!(f, "emotional_tone"),
Self::EnergyLevel => write!(f, "energy_level"),
Self::PerceivedUrgency => write!(f, "perceived_urgency"),
Self::BodySignals => write!(f, "body_signals"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum SignalSource {
Declared,
Inferred,
InferredLocal,
Preset,
Decayed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LifecycleState {
Set,
Active,
Decaying,
Stale,
Expired,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum DecayCurve {
Exponential,
Linear,
Step,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PersonalSignal {
pub category: String,
pub intensity: u8,
pub source: SignalSource,
pub confidence: f64,
pub declared_at: Option<SystemTime>,
}
impl PersonalSignal {
pub fn new(category: impl Into<String>, intensity: u8) -> Self {
Self {
category: category.into(),
intensity: intensity.clamp(1, 5),
source: SignalSource::Declared,
confidence: 1.0,
declared_at: None,
}
}
#[must_use]
pub fn with_source(mut self, source: SignalSource) -> Self {
self.source = source;
self
}
#[must_use]
pub fn with_confidence(mut self, confidence: f64) -> Self {
self.confidence = confidence.clamp(0.0, 1.0);
self
}
#[must_use]
pub fn with_declared_at(mut self, at: SystemTime) -> Self {
self.declared_at = Some(at);
self
}
}
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct PersonalContext {
pub cognitive_state: Option<PersonalSignal>,
pub emotional_tone: Option<PersonalSignal>,
pub energy_level: Option<PersonalSignal>,
pub perceived_urgency: Option<PersonalSignal>,
pub body_signals: Option<PersonalSignal>,
}
impl PersonalContext {
pub fn has_any_signal(&self) -> bool {
self.cognitive_state.is_some()
|| self.emotional_tone.is_some()
|| self.energy_level.is_some()
|| self.perceived_urgency.is_some()
|| self.body_signals.is_some()
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct StepThreshold {
pub after_seconds: f64,
pub intensity: u8,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DecayConfig {
pub half_life_seconds: f64,
pub baseline: u8,
pub reset_on_engagement: bool,
pub curve: DecayCurve,
pub stale_threshold: f64,
pub fresh_window_seconds: f64,
pub pinned: bool,
pub full_decay_seconds: Option<f64>,
pub step_thresholds: Vec<StepThreshold>,
}
impl DecayConfig {
pub fn exponential(half_life_seconds: f64) -> Self {
Self {
half_life_seconds,
baseline: 1,
reset_on_engagement: false,
curve: DecayCurve::Exponential,
stale_threshold: 0.3,
fresh_window_seconds: 60.0,
pinned: false,
full_decay_seconds: None,
step_thresholds: Vec::new(),
}
}
pub fn linear(full_decay_seconds: f64) -> Self {
Self {
half_life_seconds: 0.0,
baseline: 1,
reset_on_engagement: false,
curve: DecayCurve::Linear,
stale_threshold: 0.3,
fresh_window_seconds: 60.0,
pinned: false,
full_decay_seconds: Some(full_decay_seconds),
step_thresholds: Vec::new(),
}
}
#[must_use]
pub fn with_baseline(mut self, baseline: u8) -> Self {
self.baseline = baseline;
self
}
#[must_use]
pub fn with_reset_on_engagement(mut self, reset: bool) -> Self {
self.reset_on_engagement = reset;
self
}
#[must_use]
pub fn with_pinned(mut self, pinned: bool) -> Self {
self.pinned = pinned;
self
}
#[must_use]
pub fn with_stale_threshold(mut self, stale_threshold: f64) -> Self {
self.stale_threshold = stale_threshold;
self
}
#[must_use]
pub fn with_fresh_window_seconds(mut self, fresh_window_seconds: f64) -> Self {
self.fresh_window_seconds = fresh_window_seconds;
self
}
}
pub fn default_decay_config(dim: PersonalDimension) -> DecayConfig {
match dim {
PersonalDimension::PerceivedUrgency => DecayConfig::exponential(900.0) .with_stale_threshold(0.35)
.with_fresh_window_seconds(60.0),
PersonalDimension::BodySignals => DecayConfig::exponential(14400.0) .with_stale_threshold(0.15)
.with_fresh_window_seconds(600.0),
PersonalDimension::CognitiveState => DecayConfig::exponential(720.0) .with_reset_on_engagement(true)
.with_stale_threshold(0.3)
.with_fresh_window_seconds(60.0),
PersonalDimension::EmotionalTone => DecayConfig::exponential(1800.0) .with_stale_threshold(0.25)
.with_fresh_window_seconds(60.0),
PersonalDimension::EnergyLevel => DecayConfig::exponential(7200.0) .with_stale_threshold(0.2)
.with_fresh_window_seconds(300.0),
}
}
pub fn compute_decayed_intensity(
declared_intensity: u8,
declared_at: SystemTime,
config: &DecayConfig,
now: SystemTime,
) -> u8 {
if config.pinned {
return declared_intensity;
}
let elapsed = match now.duration_since(declared_at) {
Ok(d) => d.as_secs_f64(),
Err(_) => return declared_intensity, };
if elapsed <= 0.0 {
return declared_intensity;
}
match config.curve {
DecayCurve::Exponential => {
if !config.half_life_seconds.is_finite() || config.half_life_seconds <= 0.0 {
return declared_intensity;
}
if declared_intensity <= config.baseline {
return config.baseline;
}
let lambda = (2.0_f64).ln() / config.half_life_seconds;
let decayed = f64::from(config.baseline)
+ f64::from(declared_intensity.saturating_sub(config.baseline))
* (-lambda * elapsed).exp();
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let floored = decayed.clamp(0.0, 255.0).floor() as u8;
floored.max(config.baseline)
}
DecayCurve::Linear => {
let full_decay = match config.full_decay_seconds {
Some(fd) if fd.is_finite() && fd > 0.0 => fd,
_ => return declared_intensity,
};
if declared_intensity <= config.baseline {
return config.baseline;
}
let fraction = (elapsed / full_decay).min(1.0);
let decayed = f64::from(declared_intensity)
- f64::from(declared_intensity.saturating_sub(config.baseline)) * fraction;
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let floored = decayed.clamp(0.0, 255.0).floor() as u8;
floored.max(config.baseline)
}
DecayCurve::Step => {
if config.step_thresholds.is_empty() {
return declared_intensity;
}
let mut sorted: Vec<&StepThreshold> = config
.step_thresholds
.iter()
.filter(|threshold| {
threshold.after_seconds.is_finite() && threshold.after_seconds >= 0.0
})
.collect();
sorted.sort_by(|a, b| b.after_seconds.total_cmp(&a.after_seconds));
for threshold in &sorted {
if elapsed >= threshold.after_seconds {
return threshold.intensity.max(config.baseline);
}
}
declared_intensity
}
}
}
pub fn compute_lifecycle_state(
declared_intensity: u8,
declared_at: SystemTime,
config: &DecayConfig,
now: SystemTime,
) -> LifecycleState {
if config.pinned {
return LifecycleState::Active;
}
let elapsed = match now.duration_since(declared_at) {
Ok(d) => d.as_secs_f64(),
Err(_) => return LifecycleState::Set,
};
if elapsed <= 0.0 {
return LifecycleState::Set;
}
if elapsed < config.fresh_window_seconds {
return LifecycleState::Active;
}
let effective = compute_decayed_intensity(declared_intensity, declared_at, config, now);
if effective <= config.baseline {
return LifecycleState::Expired;
}
let stale_level = f64::from(config.baseline)
+ f64::from(declared_intensity - config.baseline) * config.stale_threshold;
if f64::from(effective) <= stale_level {
LifecycleState::Stale
} else {
LifecycleState::Decaying
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
fn time_plus_secs(base: SystemTime, secs: f64) -> SystemTime {
base + Duration::from_secs_f64(secs)
}
#[test]
fn test_personal_signal_clamps_intensity() {
let sig = PersonalSignal::new("focused", 0);
assert_eq!(sig.intensity, 1);
let sig = PersonalSignal::new("focused", 10);
assert_eq!(sig.intensity, 5);
let sig = PersonalSignal::new("focused", 3);
assert_eq!(sig.intensity, 3);
}
#[test]
fn test_personal_context_has_any_signal() {
let ctx = PersonalContext::default();
assert!(!ctx.has_any_signal());
let ctx = PersonalContext {
cognitive_state: Some(PersonalSignal::new("focused", 3)),
..Default::default()
};
assert!(ctx.has_any_signal());
}
#[test]
fn test_exponential_decay_no_elapsed() {
let config = DecayConfig::exponential(900.0);
let now = SystemTime::now();
let result = compute_decayed_intensity(5, now, &config, now);
assert_eq!(result, 5);
}
#[test]
fn test_exponential_decay_one_half_life() {
let config = DecayConfig::exponential(900.0);
let base = SystemTime::now();
let now = time_plus_secs(base, 900.0);
let result = compute_decayed_intensity(5, base, &config, now);
assert_eq!(result, 3);
}
#[test]
fn test_exponential_decay_many_half_lives() {
let config = DecayConfig::exponential(900.0);
let base = SystemTime::now();
let now = time_plus_secs(base, 9000.0); let result = compute_decayed_intensity(5, base, &config, now);
assert_eq!(result, 1); }
#[test]
fn test_pinned_never_decays() {
let config = DecayConfig::exponential(900.0).with_pinned(true);
let base = SystemTime::now();
let now = time_plus_secs(base, 99999.0);
let result = compute_decayed_intensity(5, base, &config, now);
assert_eq!(result, 5);
}
#[test]
fn test_linear_decay() {
let config = DecayConfig::linear(100.0);
let base = SystemTime::now();
let now = time_plus_secs(base, 50.0);
let result = compute_decayed_intensity(5, base, &config, now);
assert_eq!(result, 3);
}
#[test]
fn test_linear_decay_fully_elapsed() {
let config = DecayConfig::linear(100.0);
let base = SystemTime::now();
let now = time_plus_secs(base, 200.0);
let result = compute_decayed_intensity(5, base, &config, now);
assert_eq!(result, 1);
}
#[test]
fn test_step_decay() {
let config = DecayConfig {
half_life_seconds: 0.0,
baseline: 1,
reset_on_engagement: false,
curve: DecayCurve::Step,
stale_threshold: 0.3,
fresh_window_seconds: 60.0,
pinned: false,
full_decay_seconds: None,
step_thresholds: vec![
StepThreshold {
after_seconds: 60.0,
intensity: 4,
},
StepThreshold {
after_seconds: 120.0,
intensity: 3,
},
StepThreshold {
after_seconds: 300.0,
intensity: 1,
},
],
};
let base = SystemTime::now();
assert_eq!(
compute_decayed_intensity(5, base, &config, time_plus_secs(base, 30.0)),
5
);
assert_eq!(
compute_decayed_intensity(5, base, &config, time_plus_secs(base, 90.0)),
4
);
assert_eq!(
compute_decayed_intensity(5, base, &config, time_plus_secs(base, 200.0)),
3
);
assert_eq!(
compute_decayed_intensity(5, base, &config, time_plus_secs(base, 500.0)),
1
);
}
#[test]
fn invalid_decay_parameters_are_ignored_without_panicking() {
let base = SystemTime::now();
let now = time_plus_secs(base, 120.0);
for half_life in [0.0, -1.0, f64::NAN, f64::INFINITY] {
let config = DecayConfig::exponential(half_life);
assert_eq!(compute_decayed_intensity(5, base, &config, now), 5);
}
let mut config = DecayConfig::linear(f64::INFINITY);
assert_eq!(compute_decayed_intensity(5, base, &config, now), 5);
config.curve = DecayCurve::Step;
config.step_thresholds = vec![
StepThreshold {
after_seconds: f64::NAN,
intensity: 1,
},
StepThreshold {
after_seconds: -1.0,
intensity: 2,
},
StepThreshold {
after_seconds: 60.0,
intensity: 3,
},
];
assert_eq!(compute_decayed_intensity(5, base, &config, now), 3);
}
#[test]
fn test_lifecycle_state_set() {
let config = DecayConfig::exponential(900.0);
let now = SystemTime::now();
let state = compute_lifecycle_state(5, now, &config, now);
assert_eq!(state, LifecycleState::Set);
}
#[test]
fn test_lifecycle_state_active() {
let config = DecayConfig::exponential(900.0);
let base = SystemTime::now();
let now = time_plus_secs(base, 30.0); let state = compute_lifecycle_state(5, base, &config, now);
assert_eq!(state, LifecycleState::Active);
}
#[test]
fn test_lifecycle_state_expired() {
let config = DecayConfig::exponential(900.0);
let base = SystemTime::now();
let now = time_plus_secs(base, 99999.0);
let state = compute_lifecycle_state(5, base, &config, now);
assert_eq!(state, LifecycleState::Expired);
}
#[test]
fn test_lifecycle_state_pinned() {
let config = DecayConfig::exponential(900.0).with_pinned(true);
let base = SystemTime::now();
let now = time_plus_secs(base, 99999.0);
let state = compute_lifecycle_state(5, base, &config, now);
assert_eq!(state, LifecycleState::Active);
}
#[test]
fn test_default_decay_configs() {
let urg = default_decay_config(PersonalDimension::PerceivedUrgency);
assert!((urg.half_life_seconds - 900.0).abs() < f64::EPSILON);
assert!(!urg.reset_on_engagement);
assert!((urg.stale_threshold - 0.35).abs() < f64::EPSILON);
assert!((urg.fresh_window_seconds - 60.0).abs() < f64::EPSILON);
let cog = default_decay_config(PersonalDimension::CognitiveState);
assert!((cog.half_life_seconds - 720.0).abs() < f64::EPSILON);
assert!(cog.reset_on_engagement);
assert!((cog.stale_threshold - 0.3).abs() < f64::EPSILON);
assert!((cog.fresh_window_seconds - 60.0).abs() < f64::EPSILON);
let emo = default_decay_config(PersonalDimension::EmotionalTone);
assert!((emo.half_life_seconds - 1800.0).abs() < f64::EPSILON);
assert!((emo.stale_threshold - 0.25).abs() < f64::EPSILON);
assert!((emo.fresh_window_seconds - 60.0).abs() < f64::EPSILON);
let energy = default_decay_config(PersonalDimension::EnergyLevel);
assert!((energy.half_life_seconds - 7200.0).abs() < f64::EPSILON);
assert!((energy.stale_threshold - 0.2).abs() < f64::EPSILON);
assert!((energy.fresh_window_seconds - 300.0).abs() < f64::EPSILON);
let body = default_decay_config(PersonalDimension::BodySignals);
assert!((body.half_life_seconds - 14400.0).abs() < f64::EPSILON);
assert!((body.stale_threshold - 0.15).abs() < f64::EPSILON);
assert!((body.fresh_window_seconds - 600.0).abs() < f64::EPSILON);
}
#[test]
fn test_personal_dimension_display() {
assert_eq!(
PersonalDimension::CognitiveState.to_string(),
"cognitive_state"
);
assert_eq!(PersonalDimension::BodySignals.to_string(), "body_signals");
}
}