use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use crate::scoring::{NumericSample, Sample};
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum ClaimKind {
#[default]
Binary,
Numeric,
}
#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Outcome {
True,
False,
}
impl<'de> Deserialize<'de> for Outcome {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Words;
impl serde::de::Visitor<'_> for Words {
type Value = Outcome;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("an outcome: \"true\" or \"false\" (yes/no and booleans are read too)")
}
fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<Outcome, E> {
Ok(if v { Outcome::True } else { Outcome::False })
}
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Outcome, E> {
match v {
1 => Ok(Outcome::True),
0 => Ok(Outcome::False),
_ => Err(E::custom(format!("an outcome of {v}: use true or false"))),
}
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Outcome, E> {
match v.trim().to_ascii_lowercase().as_str() {
"true" | "yes" | "y" | "1" => Ok(Outcome::True),
"false" | "no" | "n" | "0" => Ok(Outcome::False),
_ => Err(E::custom(format!("an outcome of {v:?}: use true or false"))),
}
}
}
d.deserialize_any(Words)
}
}
impl Outcome {
pub fn happened(self) -> bool {
matches!(self, Outcome::True)
}
}
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
pub struct NumericForecast {
pub low: f64,
pub high: f64,
pub level: f64,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Forecast {
pub at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prob: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval: Option<NumericForecast>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub because: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Resolution {
pub at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outcome: Option<Outcome>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolved_by: Option<ResolvedBy>,
}
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum ResolvedBy {
#[default]
#[serde(rename = "self")]
Zelf,
Auto,
Human,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Claim {
pub id: String,
pub statement: String,
pub created_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolve_by: Option<NaiveDate>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub horizon_days: Option<i64>,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub kind: ClaimKind,
#[serde(default = "default_stake", skip_serializing_if = "is_default_stake")]
pub stake: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub check: Option<String>,
#[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: Extra,
pub forecasts: Vec<Forecast>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolution: Option<Resolution>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub void: Option<Void>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub amendments: Vec<Amendment>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Void {
pub at: DateTime<Utc>,
pub reason: String,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Amendment {
pub at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub old_statement: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub new_statement: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub old_tags: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub new_tags: Option<Vec<String>>,
}
fn default_stake() -> f64 {
1.0
}
fn is_default_stake(s: &f64) -> bool {
(*s - 1.0).abs() < f64::EPSILON
}
pub fn compose_reasoning(
because: Option<&str>,
reference_class: Option<&str>,
estimates: Option<(f64, f64)>,
) -> Option<String> {
let mut parts: Vec<String> = Vec::new();
if let Some(rc) = reference_class.map(str::trim).filter(|s| !s.is_empty()) {
parts.push(format!("outside view: {rc}"));
}
if let Some((p1, p2)) = estimates {
parts.push(format!(
"dialectical {p1:.2} & {p2:.2} → {:.2}",
crate::scoring::dialectical_mean(p1, p2)
));
}
if let Some(b) = because.map(str::trim).filter(|s| !s.is_empty()) {
parts.push(b.to_string());
}
(!parts.is_empty()).then(|| parts.join(" · "))
}
impl Claim {
pub fn current(&self) -> Option<&Forecast> {
self.forecasts.last()
}
pub fn current_prob(&self) -> Option<f64> {
self.forecasts.last().and_then(|f| f.prob)
}
pub fn first_prob(&self) -> Option<f64> {
self.forecasts.first().and_then(|f| f.prob)
}
pub fn current_interval(&self) -> Option<NumericForecast> {
self.forecasts.last().and_then(|f| f.interval)
}
pub fn is_resolved(&self) -> bool {
self.resolution.is_some()
}
pub fn is_void(&self) -> bool {
self.void.is_some()
}
pub fn voided_before_resolution(&self) -> bool {
match (&self.void, &self.resolution) {
(Some(v), Some(r)) => v.at <= r.at,
(Some(_), None) => true,
_ => false,
}
}
pub fn voided_after_resolution(&self) -> bool {
match (&self.void, &self.resolution) {
(Some(v), Some(r)) => v.at > r.at,
_ => false,
}
}
pub fn is_open(&self) -> bool {
self.resolution.is_none()
}
pub fn check_matches(&self, argv: &[String]) -> bool {
match &self.check {
Some(check) => crate::check::split_command(check).is_ok_and(|words| words == argv),
None => false,
}
}
pub fn is_due(&self, today: NaiveDate) -> bool {
self.is_open() && self.resolve_by.map(|d| d <= today).unwrap_or(false)
}
pub fn outcome(&self) -> Option<Outcome> {
self.resolution.as_ref().and_then(|r| r.outcome)
}
pub fn value(&self) -> Option<f64> {
self.resolution.as_ref().and_then(|r| r.value)
}
pub fn sample(&self) -> Option<Sample> {
if self.kind != ClaimKind::Binary || self.is_void() {
return None;
}
match (self.first_prob(), self.outcome()) {
(Some(p), Some(o)) => Some(Sample::new(p, o.happened())),
_ => None,
}
}
pub fn evidence_sample(&self) -> Option<Sample> {
if self.kind != ClaimKind::Binary || self.voided_before_resolution() {
return None;
}
match (self.first_prob(), self.outcome()) {
(Some(p), Some(o)) => Some(Sample::new(p, o.happened())),
_ => None,
}
}
pub fn sample_final(&self) -> Option<Sample> {
if self.kind != ClaimKind::Binary || self.is_void() {
return None;
}
match (self.current_prob(), self.outcome()) {
(Some(p), Some(o)) => Some(Sample::new(p, o.happened())),
_ => None,
}
}
pub fn has_late_update(&self) -> bool {
if self.forecasts.len() < 2 {
return false;
}
let Some(res) = self.resolution.as_ref() else {
return false;
};
let deadline = self
.resolve_by
.and_then(|d| d.and_hms_opt(23, 59, 59))
.map(|dt| dt.and_utc());
let window = (res.at - self.created_at).num_seconds().max(0) as f64;
self.forecasts.iter().skip(1).any(|f| {
if deadline.is_some_and(|d| f.at > d) {
return true;
}
if (res.at - f.at).num_seconds() <= 86_400 {
return true;
}
window > 0.0 && (f.at - self.created_at).num_seconds() as f64 > 0.9 * window
})
}
pub fn brier_time_averaged(&self) -> Option<f64> {
if self.kind != ClaimKind::Binary || self.is_void() {
return None;
}
let y = if self.outcome()?.happened() { 1.0 } else { 0.0 };
let first = self.first_prob()?;
let start = self.created_at;
let mut end = self.resolution.as_ref()?.at;
if let Some(d) = self.resolve_by {
end = end.min(d.and_hms_opt(23, 59, 59)?.and_utc());
}
let total = (end - start).num_seconds();
if total < 60 {
return Some((first - y).powi(2));
}
let mut acc = 0.0;
for (k, f) in self.forecasts.iter().enumerate() {
let p = f.prob?;
let from = if k == 0 {
start
} else {
f.at.clamp(start, end)
};
let to = self
.forecasts
.get(k + 1)
.map_or(end, |next| next.at)
.clamp(from, end);
acc += (p - y).powi(2) * (to - from).num_seconds() as f64;
}
Some(acc / total as f64)
}
pub fn numeric_sample(&self) -> Option<NumericSample> {
if self.kind != ClaimKind::Numeric || self.is_void() {
return None;
}
let iv = self.current_interval()?;
let value = self.value()?;
Some(NumericSample {
low: iv.low,
high: iv.high,
level: iv.level,
value,
})
}
pub fn was_revised(&self) -> bool {
self.forecasts.len() > 1
}
}
pub fn collapse_spaces(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
pub type Extra = serde_json::Map<String, serde_json::Value>;
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct Ledger {
#[serde(default)]
pub claims: Vec<Claim>,
#[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: Extra,
}
impl Ledger {
pub fn index_of(&self, id_prefix: &str) -> Result<usize, String> {
if let Some(i) = self.claims.iter().position(|c| c.id == id_prefix) {
return Ok(i);
}
let hits: Vec<usize> = self
.claims
.iter()
.enumerate()
.filter(|(_, c)| c.id.starts_with(id_prefix))
.map(|(i, _)| i)
.collect();
match hits.len() {
0 => Err(format!("no claim matches id '{id_prefix}'")),
1 => Ok(hits[0]),
n => Err(format!("ambiguous id '{id_prefix}' matches {n} claims")),
}
}
pub fn has_id(&self, id: &str) -> bool {
self.claims.iter().any(|c| c.id == id)
}
pub fn resolved_samples(&self) -> Vec<Sample> {
self.claims.iter().filter_map(|c| c.sample()).collect()
}
}
pub fn gen_id(statement: &str, salt: u64) -> String {
let mut h = DefaultHasher::new();
statement.hash(&mut h);
salt.hash(&mut h);
format!("{:06x}", h.finish() & 0xff_ffff)
}
pub fn normalize_tags(tags: &[String]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for t in tags {
let t = t.trim().to_lowercase();
if !t.is_empty() && !out.contains(&t) {
out.push(t);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
fn ts(y: i32, m: u32, d: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(y, m, d, 12, 0, 0).unwrap()
}
fn binary_forecast(p: f64) -> Forecast {
Forecast {
at: ts(2025, 1, 1),
prob: Some(p),
interval: None,
because: None,
}
}
fn claim(id: &str, probs: &[f64], outcome: Option<Outcome>) -> Claim {
Claim {
id: id.to_string(),
statement: format!("claim {id}"),
created_at: ts(2025, 1, 1),
horizon_days: None,
resolve_by: None,
tags: vec![],
kind: ClaimKind::Binary,
stake: 1.0,
forecasts: probs.iter().map(|&p| binary_forecast(p)).collect(),
resolution: outcome.map(|o| Resolution {
at: ts(2025, 6, 1),
outcome: Some(o),
value: None,
note: None,
resolved_by: None,
}),
void: None,
check: None,
extra: Default::default(),
amendments: Vec::new(),
}
}
#[test]
fn sample_only_when_resolved_binary() {
assert!(claim("a", &[0.7], None).sample().is_none());
let s = claim("b", &[0.7], Some(Outcome::True)).sample().unwrap();
assert_eq!(s, Sample::new(0.7, true));
}
#[test]
fn numeric_sample_round_trips() {
let c = Claim {
id: "n".into(),
statement: "how many".into(),
created_at: ts(2025, 1, 1),
horizon_days: None,
resolve_by: None,
tags: vec![],
kind: ClaimKind::Numeric,
stake: 1.0,
forecasts: vec![Forecast {
at: ts(2025, 1, 1),
prob: None,
interval: Some(NumericForecast {
low: 10.0,
high: 20.0,
level: 0.8,
}),
because: None,
}],
resolution: Some(Resolution {
at: ts(2025, 6, 1),
outcome: None,
value: Some(13.0),
note: None,
resolved_by: None,
}),
void: None,
check: None,
extra: Default::default(),
amendments: Vec::new(),
};
assert!(c.sample().is_none()); let ns = c.numeric_sample().unwrap();
assert_eq!(
(ns.low, ns.high, ns.level, ns.value),
(10.0, 20.0, 0.8, 13.0)
);
}
#[test]
fn current_is_latest_forecast() {
let c = claim("c", &[0.6, 0.8, 0.3], None);
assert_eq!(c.first_prob(), Some(0.6));
assert_eq!(c.current_prob(), Some(0.3));
assert!(c.was_revised());
}
#[test]
fn index_of_handles_prefix_and_ambiguity() {
let ledger = Ledger {
claims: vec![
claim("ab12cd", &[0.5], None),
claim("ab99ff", &[0.5], None),
claim("ff0000", &[0.5], None),
],
..Default::default()
};
assert_eq!(ledger.index_of("ff0000").unwrap(), 2);
assert_eq!(ledger.index_of("ff").unwrap(), 2);
assert!(ledger.index_of("ab").is_err());
assert!(ledger.index_of("zz").is_err());
}
#[test]
fn exact_id_beats_prefix_collision() {
let ledger = Ledger {
claims: vec![claim("ab", &[0.5], None), claim("ab12cd", &[0.5], None)],
..Default::default()
};
assert_eq!(ledger.index_of("ab").unwrap(), 0);
}
#[test]
fn tags_normalised() {
let got = normalize_tags(&[
" Politics ".into(),
"politics".into(),
"".into(),
"TECH".into(),
]);
assert_eq!(got, vec!["politics".to_string(), "tech".to_string()]);
}
#[test]
fn due_logic() {
let mut c = claim("d", &[0.5], None);
c.resolve_by = Some(NaiveDate::from_ymd_opt(2025, 6, 1).unwrap());
assert!(c.is_due(NaiveDate::from_ymd_opt(2025, 7, 1).unwrap()));
assert!(!c.is_due(NaiveDate::from_ymd_opt(2025, 5, 1).unwrap()));
}
#[test]
fn legacy_binary_json_still_loads() {
let legacy = r#"{
"claims": [{
"id": "abc123",
"statement": "old belief",
"created_at": "2025-01-01T12:00:00Z",
"tags": ["legacy"],
"forecasts": [{ "at": "2025-01-01T12:00:00Z", "prob": 0.7, "because": "why" }],
"resolution": { "at": "2025-06-01T12:00:00Z", "outcome": "true", "note": "n" }
}]
}"#;
let ledger: Ledger = serde_json::from_str(legacy).unwrap();
let c = &ledger.claims[0];
assert_eq!(c.kind, ClaimKind::Binary);
assert_eq!(c.current_prob(), Some(0.7));
assert_eq!(c.outcome(), Some(Outcome::True));
assert_eq!(c.sample(), Some(Sample::new(0.7, true)));
assert_eq!(c.stake, 1.0);
assert!(!c.is_void());
assert!(c.amendments.is_empty());
let round = serde_json::to_string(&ledger).unwrap();
assert!(
!round.contains("void"),
"absent void must not be serialised"
);
assert!(
!round.contains("amendments"),
"an empty amendment list must not be serialised"
);
assert!(
!round.contains("stake"),
"default stake must not be serialised"
);
}
#[test]
fn compose_reasoning_weaves_the_elicitation_trail() {
let r = compose_reasoning(
Some("looks clean"),
Some("similar PRs pass 60%"),
Some((0.7, 0.5)),
)
.unwrap();
assert!(r.contains("outside view: similar PRs pass 60%"));
assert!(r.contains("dialectical 0.70 & 0.50 → 0.60"));
assert!(r.contains("looks clean"));
assert_eq!(compose_reasoning(Some("x"), None, None).unwrap(), "x");
assert!(compose_reasoning(None, None, None).is_none());
assert!(compose_reasoning(Some(" "), Some(""), None).is_none());
}
}