mockforge_core/
persona_lifecycle_time.rs1use crate::time_travel::{get_global_clock, VirtualClock};
8use chrono::{DateTime, Utc};
9#[cfg(feature = "data")]
10use mockforge_data::persona_lifecycle::PersonaLifecycle;
11use std::sync::Arc;
12use tracing::{debug, info, warn};
13
14pub struct LifecycleTimeManager {
19 #[allow(clippy::type_complexity)]
22 update_callback: Arc<dyn Fn(DateTime<Utc>, DateTime<Utc>) -> Vec<String> + Send + Sync>,
23}
24
25impl LifecycleTimeManager {
26 pub fn new<F>(update_callback: F) -> Self
31 where
32 F: Fn(DateTime<Utc>, DateTime<Utc>) -> Vec<String> + Send + Sync + 'static,
33 {
34 Self {
35 update_callback: Arc::new(update_callback),
36 }
37 }
38
39 pub fn register_with_clock(&self) {
43 if let Some(clock) = get_global_clock() {
44 self.register_with_clock_instance(&clock);
45 } else {
46 warn!("No global virtual clock found, lifecycle time manager not registered");
47 }
48 }
49
50 pub fn register_with_clock_instance(&self, clock: &VirtualClock) {
54 let callback = self.update_callback.clone();
55 clock.on_time_change(move |old_time, new_time| {
56 debug!("Time changed from {} to {}, updating persona lifecycles", old_time, new_time);
57 let updated = callback(old_time, new_time);
58 if !updated.is_empty() {
59 info!("Updated {} persona lifecycle states: {:?}", updated.len(), updated);
60 }
61 });
62 info!("LifecycleTimeManager registered with virtual clock");
63 }
64}
65
66pub fn check_and_update_lifecycle_transitions(
75 lifecycle: &mut PersonaLifecycle,
76 current_time: DateTime<Utc>,
77) -> bool {
78 let old_state = lifecycle.current_state;
79 let elapsed = current_time - lifecycle.state_entered_at;
80
81 for rule in &lifecycle.transition_rules {
83 if let Some(after_days) = rule.after_days {
85 let required_duration = chrono::Duration::days(after_days as i64);
86 if elapsed < required_duration {
87 continue; }
89 }
90
91 if let Some(condition) = &rule.condition {
93 if !evaluate_lifecycle_condition(condition, &lifecycle.metadata) {
94 debug!(
95 "Condition '{}' not met for persona {}, skipping transition",
96 condition, lifecycle.persona_id
97 );
98 continue;
99 }
100 }
101
102 lifecycle.current_state = rule.to;
104 lifecycle.state_entered_at = current_time;
105 lifecycle.state_history.push((current_time, rule.to));
106
107 info!(
108 "Persona {} lifecycle transitioned: {:?} -> {:?}",
109 lifecycle.persona_id, old_state, rule.to
110 );
111
112 return true; }
114
115 false }
117
118fn evaluate_lifecycle_condition(
129 condition: &str,
130 metadata: &std::collections::HashMap<String, serde_json::Value>,
131) -> bool {
132 let expr = condition.trim();
133
134 if expr.eq_ignore_ascii_case("true") {
136 return true;
137 }
138 if expr.eq_ignore_ascii_case("false") {
139 return false;
140 }
141
142 let operators = [">=", "<=", "!=", "==", ">", "<"];
145 let mut parts: Option<(&str, &str, &str)> = None;
146
147 for op in &operators {
148 if let Some(idx) = expr.find(op) {
149 let var = expr[..idx].trim();
150 let val = expr[idx + op.len()..].trim();
151 if !var.is_empty() && !val.is_empty() {
152 parts = Some((var, op, val));
153 break;
154 }
155 }
156 }
157
158 let (variable, operator, threshold_str) = match parts {
159 Some(p) => p,
160 None => {
161 debug!(expression = expr, "Unrecognized condition expression, defaulting to true");
162 return true;
163 }
164 };
165
166 let meta_value = match metadata.get(variable) {
168 Some(val) => val,
169 None => {
170 debug!(
171 variable = variable,
172 "Condition variable not found in persona metadata, defaulting to false"
173 );
174 return false;
175 }
176 };
177
178 if let Some(actual_num) = meta_value.as_f64() {
180 if let Ok(threshold_num) = threshold_str.parse::<f64>() {
181 return match operator {
182 ">" => actual_num > threshold_num,
183 "<" => actual_num < threshold_num,
184 ">=" => actual_num >= threshold_num,
185 "<=" => actual_num <= threshold_num,
186 "==" => (actual_num - threshold_num).abs() < f64::EPSILON,
187 "!=" => (actual_num - threshold_num).abs() >= f64::EPSILON,
188 _ => true,
189 };
190 }
191 }
192
193 let actual_str = match meta_value {
195 serde_json::Value::String(s) => s.as_str(),
196 serde_json::Value::Bool(b) => {
197 if *b {
198 "true"
199 } else {
200 "false"
201 }
202 }
203 _ => {
204 debug!(variable = variable, "Cannot compare non-string/non-numeric metadata value");
205 return false;
206 }
207 };
208
209 match operator {
210 "==" => actual_str == threshold_str,
211 "!=" => actual_str != threshold_str,
212 _ => {
213 debug!(operator = operator, "Operator not supported for string comparison");
214 false
215 }
216 }
217}