1use std::collections::HashMap;
11use chrono::Utc;
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17pub struct EpistemicFitnessReport {
18 pub baseline_score: f64,
19 pub candidate_score: f64,
20 pub delta_e: f64,
21 pub monotonic: bool,
22 pub status: String,
23 pub timestamp: String,
24 pub details: serde_json::Value,
25}
26
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct EpochState {
30 pub epoch_id: u64,
31 pub epoch_hash: String,
32 pub baseline_fitness: f64,
33 pub sealed_at: String,
34 pub hypothesis_history: Vec<String>,
35}
36
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct LearningHypothesis {
40 pub hypothesis_id: String,
41 pub author_did: String,
42 pub epoch_id: u64,
43 pub candidate_state_hash: String,
44 #[serde(default)]
45 pub candidate_patches: Vec<serde_json::Value>,
46 #[serde(default)]
47 pub target_invariants: Vec<String>,
48 #[serde(default = "default_quarantined_status")]
49 pub status: String,
50}
51
52fn default_quarantined_status() -> String {
53 "QUARANTINED".to_string()
54}
55
56pub fn compute_delta_e(baseline_score: f64, candidate_score: f64) -> f64 {
61 let diff = candidate_score - baseline_score;
62 (diff * 1_000_000.0).round() / 1_000_000.0
63}
64
65fn sha256_hex(data: &str) -> String {
67 let mut hasher = Sha256::new();
68 hasher.update(data.as_bytes());
69 format!("{:x}", hasher.finalize())
70}
71
72pub fn evaluate_epistemic_fitness(
74 candidate_score: f64,
75 baseline_score: f64,
76 evaluation_spec: &str,
77) -> EpistemicFitnessReport {
78 let delta = compute_delta_e(baseline_score, candidate_score);
79 let monotonic = delta >= 0.0;
80 let status = if monotonic {
81 "COMMITTED".to_string()
82 } else {
83 "REJECTED_REGRESSION".to_string()
84 };
85
86 EpistemicFitnessReport {
87 baseline_score,
88 candidate_score,
89 delta_e: delta,
90 monotonic,
91 status,
92 timestamp: Utc::now().to_rfc3339(),
93 details: serde_json::json!({ "evaluation_spec": evaluation_spec }),
94 }
95}
96
97pub fn seal_epoch(
99 epoch_id: u64,
100 delta_e: f64,
101 hypothesis_hash: &str,
102 baseline_fitness: f64,
103) -> EpochState {
104 let state_repr = format!("epoch:{epoch_id}:fitness:{baseline_fitness}:delta:{delta_e}:hyp:{hypothesis_hash}");
105 let epoch_hash = sha256_hex(&state_repr);
106
107 EpochState {
108 epoch_id,
109 epoch_hash,
110 baseline_fitness,
111 sealed_at: Utc::now().to_rfc3339(),
112 hypothesis_history: if hypothesis_hash.is_empty() {
113 vec![]
114 } else {
115 vec![hypothesis_hash.to_string()]
116 },
117 }
118}
119
120pub fn advance_boundary(current_epoch: &EpochState, new_fitness: f64) -> EpochState {
122 let next_id = current_epoch.epoch_id + 1;
123 let state_repr = format!("epoch:{next_id}:parent:{}:fitness:{new_fitness}", current_epoch.epoch_hash);
124 let next_hash = sha256_hex(&state_repr);
125
126 EpochState {
127 epoch_id: next_id,
128 epoch_hash: next_hash,
129 baseline_fitness: new_fitness,
130 sealed_at: Utc::now().to_rfc3339(),
131 hypothesis_history: current_epoch.hypothesis_history.clone(),
132 }
133}
134
135pub fn close_gamma_loop<F>(
137 hypothesis: &LearningHypothesis,
138 current_epoch: &EpochState,
139 evaluation_spec: &str,
140 evaluator: F,
141) -> (bool, EpochState, EpistemicFitnessReport)
142where
143 F: FnOnce(&LearningHypothesis, &str) -> f64,
144{
145 let candidate_score = evaluator(hypothesis, evaluation_spec);
146 let report = evaluate_epistemic_fitness(
147 candidate_score,
148 current_epoch.baseline_fitness,
149 evaluation_spec,
150 );
151
152 if !report.monotonic {
153 return (false, current_epoch.clone(), report);
154 }
155
156 let sealed = seal_epoch(
157 current_epoch.epoch_id,
158 report.delta_e,
159 &hypothesis.candidate_state_hash,
160 report.candidate_score,
161 );
162 let next_epoch = advance_boundary(&sealed, report.candidate_score);
163
164 (true, next_epoch, report)
165}
166
167#[derive(Debug, Clone)]
171pub struct ContinuousLearningEngine {
172 pub current_epoch: EpochState,
173 pub history: Vec<EpistemicFitnessReport>,
174 pub quarantined_mutations: HashMap<String, LearningHypothesis>,
175}
176
177impl ContinuousLearningEngine {
178 pub fn new(initial_epoch: u64, initial_fitness: f64) -> Self {
179 let genesis_repr = format!("genesis:{initial_epoch}");
180 let epoch_hash = sha256_hex(&genesis_repr);
181
182 Self {
183 current_epoch: EpochState {
184 epoch_id: initial_epoch,
185 epoch_hash,
186 baseline_fitness: initial_fitness,
187 sealed_at: Utc::now().to_rfc3339(),
188 hypothesis_history: vec![],
189 },
190 history: vec![],
191 quarantined_mutations: HashMap::new(),
192 }
193 }
194
195 pub fn submit_hypothesis(
197 &mut self,
198 hypothesis_id: &str,
199 author_did: &str,
200 candidate_state_hash: &str,
201 patches: Vec<serde_json::Value>,
202 target_invariants: Vec<String>,
203 ) -> LearningHypothesis {
204 let hyp = LearningHypothesis {
205 hypothesis_id: hypothesis_id.to_string(),
206 author_did: author_did.to_string(),
207 epoch_id: self.current_epoch.epoch_id,
208 candidate_state_hash: candidate_state_hash.to_string(),
209 candidate_patches: patches,
210 target_invariants,
211 status: "QUARANTINED".to_string(),
212 };
213 self.quarantined_mutations.insert(hypothesis_id.to_string(), hyp.clone());
214 hyp
215 }
216
217 pub fn evaluate_and_commit(
219 &mut self,
220 hypothesis_id: &str,
221 evaluation_spec: &str,
222 candidate_fitness: f64,
223 ) -> Result<(bool, EpistemicFitnessReport), String> {
224 let hyp = self
225 .quarantined_mutations
226 .get(hypothesis_id)
227 .cloned()
228 .ok_or_else(|| format!("No quarantined hypothesis found for {}", hypothesis_id))?;
229
230 let (success, next_epoch, mut report) = close_gamma_loop(
231 &hyp,
232 &self.current_epoch,
233 evaluation_spec,
234 |_h, _s| candidate_fitness,
235 );
236
237 if success {
238 report.status = "COMMITTED".to_string();
239 self.current_epoch = next_epoch;
240 self.quarantined_mutations.remove(hypothesis_id);
241 self.history.push(report.clone());
242 Ok((true, report))
243 } else {
244 report.status = "REJECTED_REGRESSION".to_string();
245 self.quarantined_mutations.remove(hypothesis_id);
247 self.history.push(report.clone());
248 Ok((false, report))
249 }
250 }
251
252 pub fn can_commit_to_handle_registry(
256 &self,
257 hypothesis: &LearningHypothesis,
258 report: &EpistemicFitnessReport,
259 ) -> bool {
260 if hypothesis.status == "QUARANTINED" && report.status != "COMMITTED" {
261 return false;
262 }
263 report.monotonic && report.delta_e >= 0.0 && report.status == "COMMITTED"
264 }
265}