Skip to main content

clm_rust_core/layer5/
telemetry_hook.rs

1//! Layer 5 Meta-Circular Loop Γ Telemetry Hook (DEL-391-03, INV-391-03).
2//! Canonical Path: kernel/clm_rust_core/src/layer5/telemetry_hook.rs
3//!
4//! Wires Layer 5 Continuous Learning Stratum into execution log event streams:
5//! - Intercepts execution anomalies and telemetry events with success=false.
6//! - Formulates autonomous LearningHypothesis candidates.
7//! - Evaluates epistemic fitness gain (ΔE = S_candidate - S_baseline).
8//! - Enforces monotonicity (ΔE >= 0, INV-14) before promoting candidate recommendations.
9
10use chrono::Utc;
11use sha2::{Digest, Sha256};
12use uuid::Uuid;
13
14use crate::layer5::learning::{
15    close_gamma_loop, seal_epoch, EpochState, EpistemicFitnessReport, LearningHypothesis,
16};
17
18/// Intercepts runtime telemetry and orchestrates closed-loop Meta-Circular Loop Γ learning.
19#[derive(Debug, Clone)]
20pub struct LoopGammaTelemetryHook {
21    pub author_did: String,
22    pub current_epoch: EpochState,
23    pub evaluated_reports: Vec<EpistemicFitnessReport>,
24    pub hypotheses: Vec<LearningHypothesis>,
25}
26
27impl LoopGammaTelemetryHook {
28    pub fn new(author_did: Option<&str>, initial_epoch: Option<EpochState>) -> Self {
29        let did = author_did.unwrap_or(crate::layer0::vocabulary_identities::DID_CLM_META_LOOP_GAMMA).to_string();
30        let epoch = initial_epoch.unwrap_or_else(|| {
31            seal_epoch(1, 0.0, &"00".repeat(32), 1.0)
32        });
33
34        Self {
35            author_did: did,
36            current_epoch: epoch,
37            evaluated_reports: vec![],
38            hypotheses: vec![],
39        }
40    }
41
42    /// Processes a telemetry event. If the event denotes an execution anomaly or failure,
43    /// triggers autonomous hypothesis generation and epistemic evaluation.
44    pub fn on_telemetry_event<F>(
45        &mut self,
46        event_type: &str,
47        payload: &serde_json::Value,
48        candidate_evaluator: Option<F>,
49    ) -> Option<EpistemicFitnessReport>
50    where
51        F: FnOnce(&LearningHypothesis, &serde_json::Value) -> f64,
52    {
53        let is_failure = payload.get("success") == Some(&serde_json::Value::Bool(false))
54            || payload.get("error").is_some()
55            || payload.get("status") == Some(&serde_json::Value::String("failed".to_string()))
56            || payload.get("status") == Some(&serde_json::Value::String("error".to_string()))
57            || event_type.contains("invariant_breach");
58
59        if !is_failure {
60            return None;
61        }
62
63        // Step 1: Formulate LearningHypothesis
64        let error_msg = payload
65            .get("error")
66            .and_then(|v| v.as_str())
67            .unwrap_or("Simulated execution anomaly");
68
69        let hypo_id = format!("hypo_{}", &Uuid::new_v4().to_string().replace('-', "")[..12]);
70        let now_ts = Utc::now().timestamp_millis();
71        let state_repr = format!("{event_type}:{error_msg}:{now_ts}");
72
73        let mut hasher = Sha256::new();
74        hasher.update(state_repr.as_bytes());
75        let state_hash = format!("{:x}", hasher.finalize());
76
77        let hypothesis = LearningHypothesis {
78            hypothesis_id: hypo_id,
79            author_did: self.author_did.clone(),
80            epoch_id: self.current_epoch.epoch_id,
81            candidate_state_hash: state_hash,
82            candidate_patches: vec![serde_json::json!({
83                "target": event_type,
84                "remedy": format!("Mitigate {}", error_msg),
85            })],
86            target_invariants: vec!["INV-14".to_string(), "INV-391-03".to_string()],
87            status: "QUARANTINED".to_string(),
88        };
89        self.hypotheses.push(hypothesis.clone());
90
91        // Step 2: Evaluate candidate under Loop Γ
92        let eval_spec = serde_json::json!({
93            "anomaly_payload": payload,
94            "event_type": event_type,
95        })
96        .to_string();
97
98        let (accepted, next_epoch, report) = close_gamma_loop(
99            &hypothesis,
100            &self.current_epoch,
101            &eval_spec,
102            |hyp, _spec| {
103                if let Some(eval) = candidate_evaluator {
104                    eval(hyp, payload)
105                } else {
106                    1.0
107                }
108            },
109        );
110
111        self.evaluated_reports.push(report.clone());
112        if accepted {
113            self.current_epoch = next_epoch;
114        }
115
116        Some(report)
117    }
118
119    /// Helper for test verification: injects an anomaly event and evaluates hypothesis.
120    pub fn simulate_anomaly_and_evaluate(
121        &mut self,
122        error_message: &str,
123        candidate_fitness: f64,
124    ) -> EpistemicFitnessReport {
125        let payload = serde_json::json!({
126            "success": false,
127            "error": error_message,
128        });
129        self.on_telemetry_event(
130            "invariant_breach",
131            &payload,
132            Some(|_hyp: &LearningHypothesis, _p: &serde_json::Value| candidate_fitness),
133        )
134        .expect("Anomaly event must yield report")
135    }
136}