use serde::{Deserialize, Serialize};
pub(crate) const BUNDLE_SCHEMA_VERSION: u32 = 2;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct LearningBundle {
pub schema_version: u32,
pub exported_at: String,
pub litm: crate::core::litm_calibration::LitmCalibration,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct MergeReport {
pub litm_profiles: usize,
}
pub(crate) fn export_bundle() -> LearningBundle {
LearningBundle {
schema_version: BUNDLE_SCHEMA_VERSION,
exported_at: chrono::Utc::now().to_rfc3339(),
litm: crate::core::litm_calibration::export_state(),
}
}
pub(crate) fn import_bundle(json: &str) -> Result<MergeReport, String> {
let bundle: LearningBundle =
serde_json::from_str(json).map_err(|e| format!("invalid learning bundle: {e}"))?;
if !(1..=BUNDLE_SCHEMA_VERSION).contains(&bundle.schema_version) {
return Err(format!(
"unsupported bundle schema {} (this build speaks {})",
bundle.schema_version, BUNDLE_SCHEMA_VERSION
));
}
crate::core::litm_calibration::merge_state(&bundle.litm);
Ok(MergeReport {
litm_profiles: bundle.litm.per_profile.len(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::litm_calibration::LitmCalibration;
#[test]
fn litm_merge_takes_elementwise_max() {
let mut a = LitmCalibration::default();
a.record(
"claude",
crate::core::litm_calibration::Position::Begin,
true,
);
let mut b = LitmCalibration::default();
for _ in 0..5 {
b.record(
"claude",
crate::core::litm_calibration::Position::Begin,
true,
);
}
a.merge_from(&b);
assert_eq!(a.per_profile["claude"].begin_hits, 5);
let frozen = a.clone();
a.merge_from(&frozen);
assert_eq!(a.per_profile["claude"].begin_hits, 5);
}
#[test]
fn import_rejects_wrong_schema() {
let bundle = LearningBundle {
schema_version: 99,
exported_at: "2026-06-11T00:00:00Z".to_string(),
litm: LitmCalibration::default(),
};
let json = serde_json::to_string(&bundle).unwrap();
assert!(import_bundle(&json).is_err());
}
#[test]
fn v1_bundle_with_retired_thresholds_imports() {
let json = r#"{"schema_version":1,"exported_at":"2026-06-11T00:00:00Z",
"thresholds":{"per_ext":{"rs":{"delta_entropy":0.1,"samples":3,"last_decay_day":1}}},
"litm":{"per_profile":{},"schema_version":1}}"#;
let report = import_bundle(json).expect("v1 bundle imports");
assert_eq!(report.litm_profiles, 0);
}
#[test]
fn bundle_contains_no_paths() {
let bundle = LearningBundle {
schema_version: BUNDLE_SCHEMA_VERSION,
exported_at: "2026-06-11T00:00:00Z".to_string(),
litm: LitmCalibration::default(),
};
let json = serde_json::to_string(&bundle).unwrap();
assert!(!json.contains('/'), "no path separators expected: {json}");
}
}