use std::collections::HashMap;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EpistemicFitnessReport {
pub baseline_score: f64,
pub candidate_score: f64,
pub delta_e: f64,
pub monotonic: bool,
pub status: String,
pub timestamp: String,
pub details: serde_json::Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EpochState {
pub epoch_id: u64,
pub epoch_hash: String,
pub baseline_fitness: f64,
pub sealed_at: String,
pub hypothesis_history: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LearningHypothesis {
pub hypothesis_id: String,
pub author_did: String,
pub epoch_id: u64,
pub candidate_state_hash: String,
#[serde(default)]
pub candidate_patches: Vec<serde_json::Value>,
#[serde(default)]
pub target_invariants: Vec<String>,
#[serde(default = "default_quarantined_status")]
pub status: String,
}
fn default_quarantined_status() -> String {
"QUARANTINED".to_string()
}
pub fn compute_delta_e(baseline_score: f64, candidate_score: f64) -> f64 {
let diff = candidate_score - baseline_score;
(diff * 1_000_000.0).round() / 1_000_000.0
}
fn sha256_hex(data: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(data.as_bytes());
format!("{:x}", hasher.finalize())
}
pub fn evaluate_epistemic_fitness(
candidate_score: f64,
baseline_score: f64,
evaluation_spec: &str,
) -> EpistemicFitnessReport {
let delta = compute_delta_e(baseline_score, candidate_score);
let monotonic = delta >= 0.0;
let status = if monotonic {
"COMMITTED".to_string()
} else {
"REJECTED_REGRESSION".to_string()
};
EpistemicFitnessReport {
baseline_score,
candidate_score,
delta_e: delta,
monotonic,
status,
timestamp: Utc::now().to_rfc3339(),
details: serde_json::json!({ "evaluation_spec": evaluation_spec }),
}
}
pub fn seal_epoch(
epoch_id: u64,
delta_e: f64,
hypothesis_hash: &str,
baseline_fitness: f64,
) -> EpochState {
let state_repr = format!("epoch:{epoch_id}:fitness:{baseline_fitness}:delta:{delta_e}:hyp:{hypothesis_hash}");
let epoch_hash = sha256_hex(&state_repr);
EpochState {
epoch_id,
epoch_hash,
baseline_fitness,
sealed_at: Utc::now().to_rfc3339(),
hypothesis_history: if hypothesis_hash.is_empty() {
vec![]
} else {
vec![hypothesis_hash.to_string()]
},
}
}
pub fn advance_boundary(current_epoch: &EpochState, new_fitness: f64) -> EpochState {
let next_id = current_epoch.epoch_id + 1;
let state_repr = format!("epoch:{next_id}:parent:{}:fitness:{new_fitness}", current_epoch.epoch_hash);
let next_hash = sha256_hex(&state_repr);
EpochState {
epoch_id: next_id,
epoch_hash: next_hash,
baseline_fitness: new_fitness,
sealed_at: Utc::now().to_rfc3339(),
hypothesis_history: current_epoch.hypothesis_history.clone(),
}
}
pub fn close_gamma_loop<F>(
hypothesis: &LearningHypothesis,
current_epoch: &EpochState,
evaluation_spec: &str,
evaluator: F,
) -> (bool, EpochState, EpistemicFitnessReport)
where
F: FnOnce(&LearningHypothesis, &str) -> f64,
{
let candidate_score = evaluator(hypothesis, evaluation_spec);
let report = evaluate_epistemic_fitness(
candidate_score,
current_epoch.baseline_fitness,
evaluation_spec,
);
if !report.monotonic {
return (false, current_epoch.clone(), report);
}
let sealed = seal_epoch(
current_epoch.epoch_id,
report.delta_e,
&hypothesis.candidate_state_hash,
report.candidate_score,
);
let next_epoch = advance_boundary(&sealed, report.candidate_score);
(true, next_epoch, report)
}
#[derive(Debug, Clone)]
pub struct ContinuousLearningEngine {
pub current_epoch: EpochState,
pub history: Vec<EpistemicFitnessReport>,
pub quarantined_mutations: HashMap<String, LearningHypothesis>,
}
impl ContinuousLearningEngine {
pub fn new(initial_epoch: u64, initial_fitness: f64) -> Self {
let genesis_repr = format!("genesis:{initial_epoch}");
let epoch_hash = sha256_hex(&genesis_repr);
Self {
current_epoch: EpochState {
epoch_id: initial_epoch,
epoch_hash,
baseline_fitness: initial_fitness,
sealed_at: Utc::now().to_rfc3339(),
hypothesis_history: vec![],
},
history: vec![],
quarantined_mutations: HashMap::new(),
}
}
pub fn submit_hypothesis(
&mut self,
hypothesis_id: &str,
author_did: &str,
candidate_state_hash: &str,
patches: Vec<serde_json::Value>,
target_invariants: Vec<String>,
) -> LearningHypothesis {
let hyp = LearningHypothesis {
hypothesis_id: hypothesis_id.to_string(),
author_did: author_did.to_string(),
epoch_id: self.current_epoch.epoch_id,
candidate_state_hash: candidate_state_hash.to_string(),
candidate_patches: patches,
target_invariants,
status: "QUARANTINED".to_string(),
};
self.quarantined_mutations.insert(hypothesis_id.to_string(), hyp.clone());
hyp
}
pub fn evaluate_and_commit(
&mut self,
hypothesis_id: &str,
evaluation_spec: &str,
candidate_fitness: f64,
) -> Result<(bool, EpistemicFitnessReport), String> {
let hyp = self
.quarantined_mutations
.get(hypothesis_id)
.cloned()
.ok_or_else(|| format!("No quarantined hypothesis found for {}", hypothesis_id))?;
let (success, next_epoch, mut report) = close_gamma_loop(
&hyp,
&self.current_epoch,
evaluation_spec,
|_h, _s| candidate_fitness,
);
if success {
report.status = "COMMITTED".to_string();
self.current_epoch = next_epoch;
self.quarantined_mutations.remove(hypothesis_id);
self.history.push(report.clone());
Ok((true, report))
} else {
report.status = "REJECTED_REGRESSION".to_string();
self.quarantined_mutations.remove(hypothesis_id);
self.history.push(report.clone());
Ok((false, report))
}
}
pub fn can_commit_to_handle_registry(
&self,
hypothesis: &LearningHypothesis,
report: &EpistemicFitnessReport,
) -> bool {
if hypothesis.status == "QUARANTINED" && report.status != "COMMITTED" {
return false;
}
report.monotonic && report.delta_e >= 0.0 && report.status == "COMMITTED"
}
}