use chrono::Utc;
use sha2::{Digest, Sha256};
use uuid::Uuid;
use crate::layer5::learning::{
close_gamma_loop, seal_epoch, EpochState, EpistemicFitnessReport, LearningHypothesis,
};
#[derive(Debug, Clone)]
pub struct LoopGammaTelemetryHook {
pub author_did: String,
pub current_epoch: EpochState,
pub evaluated_reports: Vec<EpistemicFitnessReport>,
pub hypotheses: Vec<LearningHypothesis>,
}
impl LoopGammaTelemetryHook {
pub fn new(author_did: Option<&str>, initial_epoch: Option<EpochState>) -> Self {
let did = author_did.unwrap_or("did:clm:meta-loop-gamma").to_string();
let epoch = initial_epoch.unwrap_or_else(|| {
seal_epoch(1, 0.0, &"00".repeat(32), 1.0)
});
Self {
author_did: did,
current_epoch: epoch,
evaluated_reports: vec![],
hypotheses: vec![],
}
}
pub fn on_telemetry_event<F>(
&mut self,
event_type: &str,
payload: &serde_json::Value,
candidate_evaluator: Option<F>,
) -> Option<EpistemicFitnessReport>
where
F: FnOnce(&LearningHypothesis, &serde_json::Value) -> f64,
{
let is_failure = payload.get("success") == Some(&serde_json::Value::Bool(false))
|| payload.get("error").is_some()
|| payload.get("status") == Some(&serde_json::Value::String("failed".to_string()))
|| payload.get("status") == Some(&serde_json::Value::String("error".to_string()))
|| event_type.contains("invariant_breach");
if !is_failure {
return None;
}
let error_msg = payload
.get("error")
.and_then(|v| v.as_str())
.unwrap_or("Simulated execution anomaly");
let hypo_id = format!("hypo_{}", &Uuid::new_v4().to_string().replace('-', "")[..12]);
let now_ts = Utc::now().timestamp_millis();
let state_repr = format!("{event_type}:{error_msg}:{now_ts}");
let mut hasher = Sha256::new();
hasher.update(state_repr.as_bytes());
let state_hash = format!("{:x}", hasher.finalize());
let hypothesis = LearningHypothesis {
hypothesis_id: hypo_id,
author_did: self.author_did.clone(),
epoch_id: self.current_epoch.epoch_id,
candidate_state_hash: state_hash,
candidate_patches: vec![serde_json::json!({
"target": event_type,
"remedy": format!("Mitigate {}", error_msg),
})],
target_invariants: vec!["INV-14".to_string(), "INV-391-03".to_string()],
status: "QUARANTINED".to_string(),
};
self.hypotheses.push(hypothesis.clone());
let eval_spec = serde_json::json!({
"anomaly_payload": payload,
"event_type": event_type,
})
.to_string();
let (accepted, next_epoch, report) = close_gamma_loop(
&hypothesis,
&self.current_epoch,
&eval_spec,
|hyp, _spec| {
if let Some(eval) = candidate_evaluator {
eval(hyp, payload)
} else {
1.0
}
},
);
self.evaluated_reports.push(report.clone());
if accepted {
self.current_epoch = next_epoch;
}
Some(report)
}
pub fn simulate_anomaly_and_evaluate(
&mut self,
error_message: &str,
candidate_fitness: f64,
) -> EpistemicFitnessReport {
let payload = serde_json::json!({
"success": false,
"error": error_message,
});
self.on_telemetry_event(
"invariant_breach",
&payload,
Some(|_hyp: &LearningHypothesis, _p: &serde_json::Value| candidate_fitness),
)
.expect("Anomaly event must yield report")
}
}