use flate2::write::DeflateEncoder;
use flate2::Compression;
use std::io::Write;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BodenProfile {
pub tau_base: f64,
pub freedom: f64,
pub rule_flexibility: f64,
}
pub fn boden_profile(mode: &str) -> BodenProfile {
match mode {
"combinatorial" => BodenProfile {
tau_base: 0.9,
freedom: 0.8,
rule_flexibility: 0.3,
},
"transformational" => BodenProfile {
tau_base: 1.2,
freedom: 1.0,
rule_flexibility: 0.9,
},
_ => BodenProfile {
tau_base: 0.7,
freedom: 0.6,
rule_flexibility: 0.5,
},
}
}
pub fn incubation_temperature(mode: &str, novelty: f64) -> f64 {
boden_profile(mode).tau_base * (0.5 + 0.5 * novelty.clamp(0.0, 1.0))
}
pub fn compressed_len(data: &[u8]) -> usize {
let mut enc = DeflateEncoder::new(Vec::new(), Compression::best());
if enc.write_all(data).is_err() {
return data.len();
}
enc.finish().map(|v| v.len()).unwrap_or(data.len())
}
pub fn ncd(x: &[u8], y: &[u8]) -> f64 {
let cx = compressed_len(x) as f64;
let cy = compressed_len(y) as f64;
let mut xy = Vec::with_capacity(x.len() + y.len());
xy.extend_from_slice(x);
xy.extend_from_slice(y);
let cxy = compressed_len(&xy) as f64;
let denom = cx.max(cy);
if denom == 0.0 {
return 0.0;
}
((cxy - cx.min(cy)) / denom).clamp(0.0, 1.0)
}
pub fn novelty_score(baseline: &str, output: &str) -> f64 {
ncd(baseline.as_bytes(), output.as_bytes())
}
pub const NOVELTY_FLOOR_MIN: f64 = 0.15;
pub const NOVELTY_FLOOR_MAX: f64 = 0.60;
pub fn novelty_floor(novelty: f64) -> f64 {
let n = novelty.clamp(0.0, 1.0);
NOVELTY_FLOOR_MIN + (NOVELTY_FLOOR_MAX - NOVELTY_FLOOR_MIN) * n
}
#[derive(Debug, Clone, PartialEq)]
pub struct Branch {
pub output: String,
pub coherence: f64,
pub novelty: f64,
}
pub const W_COHERENCE: f64 = 0.5;
pub const W_NOVELTY: f64 = 0.5;
pub fn branch_utility(b: &Branch, nov_floor: f64) -> f64 {
let nov_term = if nov_floor > 0.0 {
(b.novelty / nov_floor).min(1.0)
} else {
1.0
};
W_COHERENCE * b.coherence + W_NOVELTY * nov_term
}
pub fn select_illumination(
branches: &[Branch],
coherence_floor: f64,
nov_floor: f64,
) -> Option<usize> {
let mut best: Option<(usize, f64)> = None;
for (i, b) in branches.iter().enumerate() {
if b.coherence < coherence_floor {
continue;
}
let u = branch_utility(b, nov_floor);
if best.map(|(_, bu)| u > bu).unwrap_or(true) {
best = Some((i, u));
}
}
best.map(|(i, _)| i)
}
#[derive(Debug, Clone, PartialEq)]
pub enum ForgeVerdict {
Accepted {
output: String,
novelty: f64,
coherence: f64,
},
Rejected(ForgeRejection),
}
#[derive(Debug, Clone, PartialEq)]
pub enum ForgeRejection {
NoFeasibleBranch,
NoveltyFloorBreached { measured: f64, floor: f64 },
}
impl ForgeRejection {
pub fn slug(&self) -> &'static str {
match self {
ForgeRejection::NoFeasibleBranch => "forge.no_feasible_branch",
ForgeRejection::NoveltyFloorBreached { .. } => "forge.novelty_floor_breached",
}
}
}
pub fn verify(winner: Option<&Branch>, nov_floor: f64) -> ForgeVerdict {
match winner {
None => ForgeVerdict::Rejected(ForgeRejection::NoFeasibleBranch),
Some(b) => {
if b.novelty < nov_floor {
ForgeVerdict::Rejected(ForgeRejection::NoveltyFloorBreached {
measured: b.novelty,
floor: nov_floor,
})
} else {
ForgeVerdict::Accepted {
output: b.output.clone(),
novelty: b.novelty,
coherence: b.coherence,
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn boden_matches_published_taxonomy() {
assert_eq!(boden_profile("combinatorial").tau_base, 0.9);
assert_eq!(boden_profile("exploratory").tau_base, 0.7);
assert_eq!(boden_profile("transformational").tau_base, 1.2);
assert_eq!(boden_profile("transformational").rule_flexibility, 0.9);
assert_eq!(boden_profile("").tau_base, 0.7);
}
#[test]
fn incubation_temperature_matches_readme_worked_example() {
let t = incubation_temperature("transformational", 0.85);
assert!((t - 1.11).abs() < 1e-9, "got {t}");
}
#[test]
fn ncd_of_identical_is_near_zero() {
let s = "the quick brown fox jumps over the lazy dog, again and again";
assert!(ncd(s.as_bytes(), s.as_bytes()) < 0.15, "identical should be ~0");
}
#[test]
fn ncd_derivative_below_unrelated() {
let baseline = "a serene mountain lake at dawn with mist over calm water and pine trees";
let derivative = "a calm mountain lake at dawn, mist over the still water and pine trees";
let novel = "recursive fractal cathedrals grown from bioluminescent coral under an ocean of liquid mercury";
let d = novelty_score(baseline, derivative);
let n = novelty_score(baseline, novel);
assert!(d < n, "derivative ({d}) must score lower novelty than a divergent concept ({n})");
}
#[test]
fn novelty_floor_is_monotonic_within_band() {
assert_eq!(novelty_floor(0.0), NOVELTY_FLOOR_MIN);
assert_eq!(novelty_floor(1.0), NOVELTY_FLOOR_MAX);
assert!(novelty_floor(0.3) < novelty_floor(0.8));
}
#[test]
fn selection_picks_highest_utility_feasible_branch() {
let branches = vec![
Branch { output: "A".into(), coherence: 0.9, novelty: 0.05 }, Branch { output: "B".into(), coherence: 0.8, novelty: 0.50 }, Branch { output: "C".into(), coherence: 0.4, novelty: 0.90 }, ];
let floor = 0.5; let nov_floor = novelty_floor(0.6);
let idx = select_illumination(&branches, floor, nov_floor).unwrap();
assert_eq!(idx, 1, "the balanced feasible branch wins");
}
#[test]
fn no_feasible_branch_rejects() {
let branches = vec![
Branch { output: "A".into(), coherence: 0.3, novelty: 0.9 },
Branch { output: "B".into(), coherence: 0.4, novelty: 0.9 },
];
assert!(select_illumination(&branches, 0.7, 0.4).is_none());
assert_eq!(verify(None, 0.4), ForgeVerdict::Rejected(ForgeRejection::NoFeasibleBranch));
}
#[test]
fn verify_rejects_a_derivative_winner_fail_closed() {
let winner = Branch { output: "derivative".into(), coherence: 0.95, novelty: 0.10 };
let v = verify(Some(&winner), novelty_floor(0.8));
match v {
ForgeVerdict::Rejected(ForgeRejection::NoveltyFloorBreached { measured, floor }) => {
assert!(measured < floor);
}
other => panic!("expected novelty-floor rejection, got {other:?}"),
}
}
#[test]
fn verify_accepts_a_novel_coherent_winner() {
let winner = Branch { output: "novel".into(), coherence: 0.85, novelty: 0.55 };
let v = verify(Some(&winner), novelty_floor(0.6));
assert!(matches!(v, ForgeVerdict::Accepted { .. }));
}
}