use std::collections::BTreeMap;
use std::fmt::Write as _;
use serde::Serialize;
use chrono::NaiveDate;
use crate::model::Ledger;
use crate::scoring::{self, NumericSample, Sample};
use crate::untrusted;
const LANE_W: usize = 34;
fn finite(x: f64) -> Option<f64> {
x.is_finite().then_some(x)
}
#[derive(Serialize, Clone, Debug)]
pub struct BinData {
pub lo: f64,
pub hi: f64,
pub count: usize,
pub mean_pred: Option<f64>,
pub observed: Option<f64>,
}
#[derive(Serialize, Clone, Debug)]
pub struct TagStat {
pub tag: String,
pub n: usize,
pub brier: Option<f64>,
pub confidence_gap: Option<f64>,
pub confidence_gap_shrunk: Option<f64>,
pub eprocess: Option<f64>,
}
#[derive(Serialize, Clone, Debug)]
pub struct MindChange {
pub revised: usize,
pub brier_first: f64,
pub brier_last: f64,
pub improvement: f64,
}
#[derive(Serialize, Clone, Debug)]
pub struct NumericData {
pub count: usize,
pub mean_winkler: f64,
pub mean_winkler_ratio: Option<f64>,
pub median_winkler_ratio: Option<f64>,
pub nominal_coverage: f64,
pub empirical_coverage: f64,
pub coverage_gap: f64,
pub mean_width: f64,
pub coverage_shrunk: f64,
pub coverage_eprocess: Option<f64>,
pub width_factor: Option<f64>,
}
pub(crate) const RECAL_RIDGE: f64 = 1.5;
pub(crate) use scoring::{RECAL_MIN_E, RECAL_MIN_N};
pub fn earned_recalibration(
ledger: &Ledger,
tag: Option<&str>,
today: NaiveDate,
) -> (Option<scoring::Recalibration>, bool, usize, Option<f64>) {
let evidence = crate::evidence::binary_evidence(&ledger.claims, today, tag);
let all: Vec<Sample> = ledger
.claims
.iter()
.filter(|c| tag.is_none_or(|t| c.tags.iter().any(|x| x == t)))
.filter_map(|c| c.sample())
.collect();
let n = evidence.samples.len();
let (recal, earned, e) = scoring::gate_recalibration_seq(&all, &evidence.steps, RECAL_RIDGE);
(recal, earned, n, e)
}
const BRIER_CI_RESAMPLES: usize = 2000;
const BRIER_CI_SEED: u64 = 0xA11A_5EED_C0FF_EE00;
const EWMA_HALF_LIFE: f64 = 5.0;
const TREND_MIN_N: usize = 10;
const SELECTION_ASMD_FLAG: f64 = 0.1;
const MCB_NULL_DRAWS: usize = 400;
const MCB_NULL_SEED: u64 = 0xA11C_E5EE_D000_0001;
pub const VERDICT_MIN_N: usize = 20;
pub const VERDICT_CONFIDENT_N: usize = 50;
pub const EVIDENCE_ALARM: f64 = 20.0;
pub const KIND_MIN_COVERAGE: f64 = 0.5;
pub const MCB_RATIO_NOTABLE: f64 = 1.5;
pub const GROUP_MIN_K: usize = 2;
pub const GROUP_MAX_K: usize = 12;
fn mcb_ratio(d: &ReportData) -> Option<f64> {
match (d.mcb, d.mcb_null_q95) {
(Some(m), Some(f)) if f > 0.0 => Some(m / f),
_ => None,
}
}
const BIAS_DOMINATES: f64 = 0.1;
const DIRECTION_MIN_GAP: f64 = 0.02;
const DSC_UNINFORMATIVE: f64 = 1e-9;
#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
InsufficientData,
Withheld,
NoEvidenceOfMiscalibration,
CalibratedButUninformative,
Overconfident,
Underconfident,
BiasedYes,
BiasedNo,
MiscalibratedBothWays,
}
impl Verdict {
pub fn is_miscalibrated(self) -> bool {
matches!(
self,
Verdict::Overconfident
| Verdict::Underconfident
| Verdict::BiasedYes
| Verdict::BiasedNo
| Verdict::MiscalibratedBothWays
)
}
pub fn slug(self) -> &'static str {
match self {
Verdict::InsufficientData => "insufficient_data",
Verdict::Withheld => "withheld",
Verdict::NoEvidenceOfMiscalibration => "no_evidence_of_miscalibration",
Verdict::CalibratedButUninformative => "calibrated_but_uninformative",
Verdict::Overconfident => "overconfident",
Verdict::Underconfident => "underconfident",
Verdict::BiasedYes => "biased_yes",
Verdict::BiasedNo => "biased_no",
Verdict::MiscalibratedBothWays => "miscalibrated_both_ways",
}
}
pub fn label(self) -> &'static str {
match self {
Verdict::InsufficientData => "not enough data",
Verdict::Withheld => "withheld",
Verdict::NoEvidenceOfMiscalibration => "no miscalibration found",
Verdict::CalibratedButUninformative => "uninformative",
Verdict::Overconfident => "overconfident",
Verdict::Underconfident => "underconfident",
Verdict::BiasedYes => "leans yes",
Verdict::BiasedNo => "leans no",
Verdict::MiscalibratedBothWays => "miscalibrated",
}
}
}
pub const TOPIC_NS: &str = "topic";
fn group_keys<'a>(c: &'a crate::model::Claim, ns: &'a str) -> impl Iterator<Item = &'a str> {
c.tags.iter().filter_map(move |t| {
if ns == TOPIC_NS {
(!t.contains(':')).then_some(t.as_str())
} else {
t.strip_prefix(ns).and_then(|r| r.strip_prefix(':'))
}
})
}
#[derive(Clone, Debug)]
struct Grouping {
ns: String,
coverage: f64,
groups: BTreeMap<String, Vec<Sample>>,
signature: Vec<Vec<usize>>,
}
impl Grouping {
fn k(&self) -> usize {
self.groups.len()
}
fn usable(&self) -> bool {
self.coverage >= KIND_MIN_COVERAGE && (GROUP_MIN_K..=GROUP_MAX_K).contains(&self.k())
}
}
fn materialise(graded: &[&crate::model::Claim], ns: &str) -> Option<Grouping> {
let mut groups: BTreeMap<String, Vec<Sample>> = BTreeMap::new();
let mut members: BTreeMap<String, Vec<usize>> = BTreeMap::new();
let mut covered = 0usize;
for (i, c) in graded.iter().enumerate() {
let Some(s) = c.evidence_sample() else {
continue;
};
let mut any = false;
for key in group_keys(c, ns) {
any = true;
groups.entry(key.to_string()).or_default().push(s);
members.entry(key.to_string()).or_default().push(i);
}
covered += usize::from(any);
}
if groups.is_empty() {
return None;
}
let mut signature: Vec<Vec<usize>> = members.into_values().collect();
for m in &mut signature {
m.sort_unstable();
m.dedup();
}
signature.sort();
Some(Grouping {
ns: ns.to_string(),
coverage: covered as f64 / graded.len() as f64,
groups,
signature,
})
}
#[derive(Clone, Debug, Default)]
struct GroupingChoice {
chosen: Option<Grouping>,
coverage: f64,
k: usize,
topic_signature: Option<Vec<Vec<usize>>>,
}
fn pick_grouping(
claims: &[crate::model::Claim],
today: NaiveDate,
tag: Option<&str>,
) -> GroupingChoice {
let graded = crate::evidence::binary_evidence_claims(claims, today, tag);
if graded.is_empty() {
return GroupingChoice::default();
}
let mut namespaces: Vec<String> = graded
.iter()
.flat_map(|c| c.tags.iter())
.map(|t| match t.split_once(':') {
Some((ns, _)) => ns.to_string(),
None => TOPIC_NS.to_string(),
})
.collect();
namespaces.sort_by(|a, b| {
(a.as_str() != "kind")
.cmp(&(b.as_str() != "kind"))
.then(a.cmp(b))
});
namespaces.dedup();
let mut candidates: Vec<Grouping> = Vec::new();
let mut topic_signature = None;
for ns in &namespaces {
let Some(g) = materialise(&graded, ns) else {
continue;
};
if ns.as_str() == TOPIC_NS {
topic_signature = Some(g.signature.clone());
}
if candidates.iter().all(|c| c.signature != g.signature) {
candidates.push(g);
}
}
let mut ranked: Vec<&Grouping> = candidates.iter().collect();
ranked.sort_by(|a, b| b.coverage.total_cmp(&a.coverage).then(a.ns.cmp(&b.ns)));
let chosen = candidates
.iter()
.find(|g| g.ns == "kind" && g.usable())
.or_else(|| ranked.iter().copied().find(|g| g.usable()))
.cloned();
match (chosen, ranked.first()) {
(Some(g), _) => GroupingChoice {
coverage: g.coverage,
k: g.k(),
chosen: Some(g),
topic_signature,
},
(None, Some(best)) => GroupingChoice {
chosen: None,
coverage: best.coverage,
k: best.k(),
topic_signature,
},
(None, None) => GroupingChoice {
topic_signature,
..GroupingChoice::default()
},
}
}
#[allow(clippy::too_many_arguments)]
pub fn verdict_from(
n: usize,
mcb: Option<f64>,
mcb_floor: Option<f64>,
dsc: Option<f64>,
eprocess: Option<f64>,
confidence_gap: Option<f64>,
directional_bias: Option<f64>,
distinct_forecasts: usize,
voids_withhold: bool,
) -> Verdict {
if voids_withhold {
return Verdict::Withheld;
}
if n < VERDICT_MIN_N {
return Verdict::InsufficientData;
}
let demonstrated = eprocess.is_some_and(|e| e >= EVIDENCE_ALARM);
let above_floor = match (mcb, mcb_floor) {
(Some(m), Some(f)) => m > f,
(Some(m), None) => m > 0.0,
_ => false,
};
if distinct_forecasts >= 2 && dsc.is_some_and(|d| d.abs() < DSC_UNINFORMATIVE) {
return Verdict::CalibratedButUninformative;
}
if demonstrated && above_floor {
let bias = directional_bias.unwrap_or(0.0);
if bias.abs() >= BIAS_DOMINATES && bias.abs() > confidence_gap.map_or(0.0, f64::abs) {
return if bias > 0.0 {
Verdict::BiasedYes
} else {
Verdict::BiasedNo
};
}
let gap = confidence_gap.unwrap_or(0.0);
if gap.abs() < DIRECTION_MIN_GAP {
return Verdict::MiscalibratedBothWays;
}
return if gap > 0.0 {
Verdict::Overconfident
} else {
Verdict::Underconfident
};
}
let level_off =
matches!((mcb, mcb_floor), (Some(m), Some(f)) if f > 0.0 && m / f >= MCB_RATIO_NOTABLE);
if !level_off && dsc.is_some_and(|d| d.abs() < DSC_UNINFORMATIVE) {
return Verdict::CalibratedButUninformative;
}
Verdict::NoEvidenceOfMiscalibration
}
#[derive(Serialize, Clone, Debug)]
pub struct RecalData {
pub a: f64,
pub b: f64,
pub n: usize,
pub examples: Vec<(f64, f64)>,
}
#[derive(Serialize, Clone, Debug)]
pub struct ResolutionDiscipline {
pub resolution_rate: f64,
pub resolved: usize,
pub open: usize,
pub overdue: usize,
pub resolved_boldness: Option<f64>,
pub open_boldness: Option<f64>,
pub auto_graded: usize,
pub auto_pinned: usize,
pub boldness_asmd: Option<f64>,
}
#[derive(Serialize, Clone, Debug)]
pub struct SelectiveData {
pub risk_full: f64,
pub risk_half: f64,
pub aurcc: f64,
}
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct GradedCall {
pub id: String,
pub prob: f64,
pub came_true: bool,
pub brier: f64,
}
pub const SO_FAR_MAX: usize = 8;
#[derive(Serialize, Clone, Debug)]
pub struct ReportData {
pub tag: Option<String>,
pub resolved: usize,
pub resolved_binary: usize,
pub resolved_numeric: usize,
pub open: usize,
pub total: usize,
pub first_recorded: Option<String>,
pub last_recorded: Option<String>,
pub brier: Option<f64>,
pub log_score: Option<f64>,
pub brier_skill: Option<f64>,
pub base_rate: Option<f64>,
pub base_rate_ci: Option<(f64, f64)>,
pub reliability: Option<f64>,
pub resolution: Option<f64>,
pub uncertainty: Option<f64>,
pub auc: Option<f64>,
pub confidence_gap: Option<f64>,
pub mean_confidence: Option<f64>,
pub accuracy: Option<f64>,
pub directional_bias: Option<f64>,
pub calibration: Vec<BinData>,
pub by_tag: Vec<TagStat>,
pub by_tag_merged_into_group: bool,
pub by_kind: Vec<TagStat>,
pub group_by: Option<String>,
pub group_coverage: f64,
pub group_k: usize,
pub mind_changing: Option<MindChange>,
pub numeric: Option<NumericData>,
pub eprocess: Option<f64>,
pub eprocess_pvalue: Option<f64>,
pub recalibration: Option<RecalData>,
pub brier_ci: Option<(f64, f64)>,
pub recent_brier: Option<f64>,
pub distinct_forecasts: usize,
pub selective: Option<SelectiveData>,
pub weighted_brier: Option<f64>,
pub resolution_discipline: Option<ResolutionDiscipline>,
pub score_basis: &'static str,
pub brier_first: Option<f64>,
pub brier_final: Option<f64>,
pub brier_time_avg: Option<f64>,
pub late_updates: usize,
pub mcb: Option<f64>,
pub dsc: Option<f64>,
pub unc: Option<f64>,
pub mcb_null_q95: Option<f64>,
pub evidence_n: usize,
pub evidence_oldest_gap: Option<String>,
pub evidence_gap_cost_log: Option<f64>,
pub evidence_gap_without_deadline: bool,
pub evidence_ungraded_due: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub evidence_pending: Option<(usize, NaiveDate, NaiveDate)>,
pub voided_after_resolution: usize,
pub voids: crate::evidence::VoidAccount,
pub eprocess_log: Option<f64>,
pub kind_alarm_threshold: Option<f64>,
pub verdict: Verdict,
#[serde(skip_serializing_if = "Option::is_none")]
pub sensitivity: Option<f64>,
pub easy_calls: usize,
pub so_far: Vec<GradedCall>,
#[serde(skip_serializing_if = "Option::is_none")]
pub brier_contested: Option<f64>,
}
pub const EASY_P: f64 = 0.95;
pub const CONTESTED_MIN_N: usize = 5;
pub const EASY_SHARE_NOTE: f64 = 0.3;
pub const SENSITIVITY_SHRINK: f64 = 0.3;
pub const DIALED_MIN_SENSITIVITY: f64 = 0.8;
impl ReportData {
pub fn compute(
ledger: &Ledger,
tag_filter: Option<&str>,
bins: usize,
today: NaiveDate,
) -> ReportData {
let tag_filter = tag_filter.map(|t| t.to_lowercase());
let matches_tag = |c: &&crate::model::Claim| match &tag_filter {
Some(t) => c.tags.iter().any(|x| x == t),
None => true,
};
let resolved_claims: Vec<&crate::model::Claim> = ledger
.claims
.iter()
.filter(|c| c.is_resolved() && !c.is_void())
.filter(matches_tag)
.collect();
let samples: Vec<Sample> = resolved_claims.iter().filter_map(|c| c.sample()).collect();
let so_far: Vec<GradedCall> = if samples.len() < VERDICT_MIN_N {
let mut graded: Vec<(&crate::model::Claim, Sample)> = resolved_claims
.iter()
.filter_map(|c| c.sample().map(|s| (*c, s)))
.collect();
graded.sort_by_key(|(c, _)| std::cmp::Reverse(c.resolution.as_ref().map(|r| r.at)));
graded
.into_iter()
.take(SO_FAR_MAX)
.map(|(c, s)| GradedCall {
id: c.id.clone(),
prob: s.prob,
came_true: s.outcome > 0.5,
brier: (s.prob - s.outcome).powi(2),
})
.collect()
} else {
Vec::new()
};
let is_easy = |s: &Sample| s.prob >= EASY_P || s.prob <= 1.0 - EASY_P;
let easy_calls = samples.iter().filter(|s| is_easy(s)).count();
let contested: Vec<Sample> = samples.iter().filter(|s| !is_easy(s)).cloned().collect();
let brier_contested = (contested.len() >= CONTESTED_MIN_N)
.then(|| scoring::brier(&contested))
.flatten();
let numeric_samples: Vec<NumericSample> = resolved_claims
.iter()
.filter_map(|c| c.numeric_sample())
.collect();
let open_claims: Vec<&crate::model::Claim> = ledger
.claims
.iter()
.filter(|c| c.is_open() && !c.is_void())
.filter(matches_tag)
.collect();
let open = open_claims.len();
let (first_recorded, last_recorded) = {
let dates: Vec<_> = resolved_claims
.iter()
.map(|c| c.created_at.date_naive())
.collect();
(
dates.iter().min().map(|d| d.to_string()),
dates.iter().max().map(|d| d.to_string()),
)
};
let evidence =
crate::evidence::binary_evidence(&ledger.claims, today, tag_filter.as_deref());
let chrono_samples: Vec<Sample> = evidence.samples.clone();
let voids = crate::evidence::void_account(&ledger.claims, today, tag_filter.as_deref());
let evidence_pending =
crate::evidence::pending_due(&ledger.claims, today, tag_filter.as_deref());
let mut chrono: Vec<&crate::model::Claim> = resolved_claims.clone();
chrono.sort_by_key(|c| c.resolution.as_ref().map(|r| r.at));
let recent_samples: Vec<Sample> = chrono.iter().filter_map(|c| c.sample()).collect();
let decomp = scoring::decompose(&samples);
let over = scoring::overconfidence(&samples);
let overall_acc = over.map(|o| o.accuracy);
let calibration = scoring::calibration_curve(&samples, bins)
.into_iter()
.map(|b| BinData {
lo: b.lo,
hi: b.hi,
count: b.count,
mean_pred: (b.count > 0).then_some(b.mean_pred),
observed: finite(b.observed),
})
.collect();
let by_tag = if tag_filter.is_some() {
Vec::new()
} else {
let mut map: BTreeMap<&str, Vec<Sample>> = BTreeMap::new();
for c in &chrono {
if let Some(s) = c.sample() {
for t in group_keys(c, TOPIC_NS) {
map.entry(t).or_default().push(s);
}
}
}
let mut rows: Vec<TagStat> = map
.into_iter()
.map(|(tag, s)| {
let oc = scoring::overconfidence(&s);
let gap_shrunk = match (oc, overall_acc) {
(Some(o), Some(pa)) => Some(
o.mean_confidence
- scoring::shrink_toward(
o.accuracy * s.len() as f64,
s.len(),
pa,
4.0,
),
),
_ => oc.map(|o| o.gap),
};
TagStat {
tag: tag.to_string(),
n: s.len(),
brier: scoring::brier(&s),
confidence_gap: oc.map(|o| o.gap),
confidence_gap_shrunk: gap_shrunk,
eprocess: None, }
})
.collect();
rows.sort_by(|a, b| b.n.cmp(&a.n).then(a.tag.cmp(&b.tag)));
rows
};
let choice = pick_grouping(&ledger.claims, today, tag_filter.as_deref());
let group_by = choice.chosen.as_ref().map(|g| g.ns.clone());
let group_coverage = choice.coverage;
let by_tag_merged_into_group = matches!(
(&choice.chosen, &choice.topic_signature),
(Some(g), Some(t)) if &g.signature == t
);
let by_tag = if by_tag_merged_into_group {
Vec::new()
} else {
by_tag
};
let by_kind = {
let map: BTreeMap<&str, Vec<Sample>> = choice
.chosen
.as_ref()
.map(|g| {
g.groups
.iter()
.map(|(k, s)| (k.as_str(), s.clone()))
.collect()
})
.unwrap_or_default();
let mut rows: Vec<TagStat> = map
.into_iter()
.map(|(tag, s)| {
let oc = scoring::overconfidence(&s);
let gap_shrunk = match (oc, overall_acc) {
(Some(o), Some(pa)) => Some(
o.mean_confidence
- scoring::shrink_toward(
o.accuracy * s.len() as f64,
s.len(),
pa,
4.0,
),
),
_ => oc.map(|o| o.gap),
};
TagStat {
tag: tag.to_string(),
n: s.len(),
brier: scoring::brier(&s),
confidence_gap: oc.map(|o| o.gap),
confidence_gap_shrunk: gap_shrunk,
eprocess: scoring::calibration_eprocess_v2(&s),
}
})
.collect();
rows.sort_by(|a, b| b.n.cmp(&a.n).then(a.tag.cmp(&b.tag)));
rows
};
let base_rate_ci = {
let k: f64 = samples.iter().map(|s| s.outcome).sum();
scoring::wilson_interval(k, samples.len(), 1.96)
};
let revised: Vec<&crate::model::Claim> = resolved_claims
.iter()
.copied()
.filter(|c| c.was_revised() && c.sample().is_some())
.collect();
let mind_changing = if revised.is_empty() {
None
} else {
let mut first = Vec::new();
let mut last = Vec::new();
for c in &revised {
let happened = c.outcome().unwrap().happened();
first.push(Sample::new(c.first_prob().unwrap(), happened));
last.push(Sample::new(c.current_prob().unwrap(), happened));
}
let bf = scoring::brier(&first).unwrap();
let bl = scoring::brier(&last).unwrap();
Some(MindChange {
revised: revised.len(),
brier_first: bf,
brier_last: bl,
improvement: bf - bl,
})
};
let numeric = if numeric_samples.is_empty() {
None
} else {
let n = numeric_samples.len() as f64;
let mean_winkler = numeric_samples.iter().map(scoring::winkler).sum::<f64>() / n;
let mut ratios: Vec<f64> = numeric_samples
.iter()
.filter_map(scoring::winkler_ratio)
.collect();
ratios.sort_by(f64::total_cmp);
let mean_winkler_ratio =
(!ratios.is_empty()).then(|| ratios.iter().sum::<f64>() / ratios.len() as f64);
let median_winkler_ratio = (!ratios.is_empty()).then(|| {
let m = ratios.len() / 2;
if ratios.len().is_multiple_of(2) {
(ratios[m - 1] + ratios[m]) / 2.0
} else {
ratios[m]
}
});
let nominal = numeric_samples.iter().map(|s| s.level).sum::<f64>() / n;
let cov = scoring::coverage(&numeric_samples).unwrap_or(f64::NAN);
let width = numeric_samples.iter().map(|s| s.width()).sum::<f64>() / n;
let contained = numeric_samples.iter().filter(|s| s.contains()).count() as f64;
let coverage_shrunk =
scoring::shrink_toward(contained, numeric_samples.len(), 0.5, 1.0);
let coverage_samples: Vec<Sample> = numeric_samples
.iter()
.map(|s| Sample::new(s.level, s.contains()))
.collect();
Some(NumericData {
count: numeric_samples.len(),
mean_winkler,
mean_winkler_ratio,
median_winkler_ratio,
nominal_coverage: nominal,
empirical_coverage: cov,
coverage_gap: cov - nominal,
mean_width: width,
coverage_shrunk,
coverage_eprocess: scoring::calibration_eprocess_v2(&coverage_samples),
width_factor: scoring::conformal_width_factor(&numeric_samples),
})
};
let eprocess = scoring::calibration_eprocess_seq(&evidence.steps);
let eprocess_log = scoring::calibration_log_eprocess_seq(&evidence.steps);
let gap_cost_log = match (
eprocess_log,
scoring::calibration_log_eprocess(&chrono_samples),
) {
(Some(with_gaps), Some(graded_only)) => Some(graded_only - with_gaps),
_ => None,
};
let eprocess_pvalue = eprocess.map(scoring::eprocess_pvalue);
let corp = scoring::corp_brier(&samples);
let mcb_null_q95 =
scoring::mcb_null_quantile(&samples, MCB_NULL_DRAWS, 0.95, MCB_NULL_SEED);
let final_samples: Vec<Sample> = resolved_claims
.iter()
.filter_map(|c| c.sample_final())
.collect();
let brier_final = scoring::brier(&final_samples);
let time_avg: Vec<f64> = resolved_claims
.iter()
.filter_map(|c| c.brier_time_averaged())
.collect();
let brier_time_avg =
(!time_avg.is_empty()).then(|| time_avg.iter().sum::<f64>() / time_avg.len() as f64);
let late_updates = resolved_claims
.iter()
.filter(|c| c.has_late_update())
.count();
let recalibration = scoring::fit_recalibration(&samples, RECAL_RIDGE).map(|r| RecalData {
a: r.a,
b: r.b,
n: r.n,
examples: [0.5, 0.6, 0.7, 0.8, 0.9]
.iter()
.map(|&p| (p, r.apply(p)))
.collect(),
});
let brier_ci =
scoring::brier_ci_bootstrap(&samples, 0.95, BRIER_CI_RESAMPLES, BRIER_CI_SEED);
let recent_brier = scoring::ewma_brier(&recent_samples, EWMA_HALF_LIFE);
let distinct_forecasts = scoring::distinct_forecasts(&samples);
let selective = scoring::risk_coverage(&samples).map(|rc| SelectiveData {
risk_full: rc.risk_at_full,
risk_half: rc.risk_at(0.5),
aurcc: rc.aurcc,
});
let stakes: Vec<f64> = resolved_claims
.iter()
.filter_map(|c| c.sample().map(|_| c.stake))
.collect();
let weighted_brier = if stakes.iter().any(|&w| (w - 1.0).abs() > 1e-9) {
scoring::brier_weighted(&samples, &stakes)
} else {
None
};
let resolution_discipline = {
let total = resolved_claims.len() + open_claims.len();
(total > 0).then(|| {
let overdue = open_claims
.iter()
.filter(|c| matches!(c.resolve_by, Some(d) if d <= today))
.count();
let resolved_probs: Vec<f64> = resolved_claims
.iter()
.filter_map(|c| c.current_prob())
.collect();
let open_probs: Vec<f64> = open_claims
.iter()
.filter_map(|c| c.current_prob())
.collect();
ResolutionDiscipline {
resolution_rate: resolved_claims.len() as f64 / total as f64,
resolved: resolved_claims.len(),
open: open_claims.len(),
overdue,
auto_graded: resolved_claims
.iter()
.filter(|c| {
c.resolution.as_ref().and_then(|r| r.resolved_by)
== Some(crate::model::ResolvedBy::Auto)
})
.count(),
auto_pinned: resolved_claims
.iter()
.filter(|c| {
c.check.is_some()
&& c.resolution.as_ref().and_then(|r| r.resolved_by)
== Some(crate::model::ResolvedBy::Auto)
})
.count(),
resolved_boldness: scoring::mean_boldness(&resolved_probs),
open_boldness: scoring::mean_boldness(&open_probs),
boldness_asmd: scoring::asmd(&resolved_probs, &open_probs),
}
})
};
let by_kind_len = by_kind.len();
let group_k = if choice.chosen.is_some() {
by_kind_len
} else {
choice.k
};
let by_kind_len_zero = by_kind_len == 0;
let verdict = verdict_from(
chrono_samples.len(),
corp.as_ref().map(|c| c.mcb),
mcb_null_q95,
corp.as_ref().map(|c| c.dsc),
eprocess,
over.map(|o| o.gap),
scoring::directional_bias(&samples),
distinct_forecasts,
voids.withholds_verdict(),
);
let sensitivity = (verdict == Verdict::NoEvidenceOfMiscalibration)
.then(|| {
let n = evidence.steps.len().max(1);
let sims = (400_000 / n).min(200);
(sims >= 40)
.then(|| {
scoring::detection_rate(
&evidence.steps,
SENSITIVITY_SHRINK,
EVIDENCE_ALARM,
sims,
0x5EED_0A4A,
)
})
.flatten()
})
.flatten();
ReportData {
tag: tag_filter,
resolved: resolved_claims.len(),
resolved_binary: samples.len(),
resolved_numeric: numeric_samples.len(),
open,
total: resolved_claims.len() + open,
first_recorded,
last_recorded,
brier: scoring::brier(&samples),
log_score: scoring::log_score(&samples, 1e-6),
brier_skill: scoring::skill_score(&samples),
base_rate: scoring::base_rate(&samples),
base_rate_ci,
reliability: decomp.map(|d| d.reliability),
resolution: decomp.map(|d| d.resolution),
uncertainty: decomp.map(|d| d.uncertainty),
auc: scoring::auc(&samples),
confidence_gap: over.map(|o| o.gap),
mean_confidence: over.map(|o| o.mean_confidence),
accuracy: over.map(|o| o.accuracy),
directional_bias: scoring::directional_bias(&samples),
calibration,
by_tag,
by_tag_merged_into_group,
by_kind,
group_by,
group_coverage,
group_k,
mind_changing,
numeric,
eprocess,
eprocess_pvalue,
recalibration,
brier_ci,
recent_brier,
distinct_forecasts,
selective,
weighted_brier,
resolution_discipline,
score_basis: "first",
brier_first: scoring::brier(&samples),
brier_final,
brier_time_avg,
late_updates,
mcb: corp.as_ref().map(|c| c.mcb),
dsc: corp.as_ref().map(|c| c.dsc),
unc: corp.as_ref().map(|c| c.unc),
mcb_null_q95,
evidence_n: evidence.samples.len(),
evidence_oldest_gap: evidence.oldest_gap.clone(),
evidence_gap_cost_log: gap_cost_log,
evidence_gap_without_deadline: evidence.oldest_gap_without_deadline,
evidence_ungraded_due: evidence.ungraded_due,
evidence_pending,
voided_after_resolution: evidence.voided_after_resolution,
voids,
eprocess_log,
kind_alarm_threshold: (!by_kind_len_zero)
.then_some(EVIDENCE_ALARM * by_kind_len as f64),
verdict,
sensitivity,
easy_calls,
so_far,
brier_contested,
}
}
fn is_empty(&self) -> bool {
self.resolved_binary == 0 && self.numeric.is_none()
}
}
pub fn render_json(
ledger: &Ledger,
tag_filter: Option<&str>,
bins: usize,
today: NaiveDate,
) -> String {
let data = ReportData::compute(ledger, tag_filter, bins, today);
serde_json::to_string_pretty(&data).unwrap_or_else(|e| format!("{{\"error\":\"{e}\"}}"))
}
fn lane(pred: f64, obs: Option<f64>) -> String {
let pos = |v: f64| -> usize { (v.clamp(0.0, 1.0) * (LANE_W as f64 - 1.0)).round() as usize };
let mut cells = vec![b'-'; LANE_W];
let pp = pos(pred);
match obs {
None => cells[pp] = b'P',
Some(o) => {
let op = pos(o);
if pp == op {
cells[pp] = b'X';
} else {
cells[pp] = b'P';
cells[op] = b'O';
}
}
}
String::from_utf8(cells).unwrap()
}
pub const DETAIL_MIN_N: usize = 10;
fn signed(x: f64) -> String {
if x.abs() < 0.0005 {
"0.000".to_string()
} else {
format!("{x:+.3}")
}
}
fn gap_gloss(gap: f64, v: Verdict) -> String {
let direction = if gap > 0.05 {
"bolder than you are right"
} else if gap < -0.05 {
"less sure than you turn out to be"
} else {
"boldness and accuracy match on average"
};
if v.is_miscalibrated() {
match () {
_ if gap > 0.05 => format!("OVERCONFIDENT — {direction}"),
_ if gap < -0.05 => format!("UNDERCONFIDENT — {direction}"),
_ => format!("{direction} (the errors cancel here — see the verdict above)"),
}
} else if v == Verdict::InsufficientData && gap.abs() > 0.05 {
format!(
"{direction}; whether that is more than luck is not tested yet — see the verdict above"
)
} else if gap.abs() > 0.05 {
format!("{direction}, but not by more than luck could manage at this sample size — see the verdict above")
} else {
format!("{direction} (an average: errors in opposite directions cancel here)")
}
}
pub fn render(ledger: &Ledger, tag_filter: Option<&str>, bins: usize, today: NaiveDate) -> String {
let d = ReportData::compute(ledger, tag_filter, bins, today);
let mut out = String::new();
let title = match &d.tag {
Some(t) => format!("ANAMNESIS — the shape of your judgement [tag: {t}]"),
None => "ANAMNESIS — the shape of your judgement".to_string(),
};
let _ = writeln!(out, "\n{title}");
let _ = writeln!(out, "{}", "=".repeat(title.len()));
if d.is_empty() {
let scope = d
.tag
.as_ref()
.map(|t| format!(" tagged '{t}'"))
.unwrap_or_default();
let _ = writeln!(
out,
"\nNo resolved claims yet{scope}. {} still open.\n\nRecord beliefs with `ana add`, and `ana resolve` them once reality speaks.\nThe mirror needs something to reflect.",
d.open
);
return out;
}
let split = if d.resolved_numeric > 0 && d.resolved_binary > 0 {
format!(
" ({} yes/no · {} numeric)",
d.resolved_binary, d.resolved_numeric
)
} else {
String::new()
};
let _ = writeln!(
out,
"\n{} of {} resolved{split} · {} open · first recorded {} · latest {}",
d.resolved,
d.total,
d.open,
d.first_recorded.as_deref().unwrap_or("—"),
d.last_recorded.as_deref().unwrap_or("—"),
);
if let Some(rd) = &d.resolution_discipline {
let overdue_tail = if rd.overdue > 0 {
format!(" · {} overdue", rd.overdue)
} else {
String::new()
};
let _ = writeln!(
out,
"\n Resolution discipline {:.0}% graded ({} of {}){overdue_tail}",
rd.resolution_rate * 100.0,
rd.resolved,
rd.resolved + rd.open,
);
if rd.overdue > 0 {
let _ = writeln!(
out,
" ⚠ {} claim(s) past due and ungraded — resolve them; until you do, the numbers below rest on a self-selected sample.",
rd.overdue
);
}
if d.voids.total > 0 {
let _ = writeln!(
out,
" Voided: {} of {} settled claim(s) ({}), {} of them after they came due or had resolved. A void can hide a miss whenever it was made; past one in ten, no verdict is read.",
d.voids.total, d.voids.settled, pct(d.voids.void_rate().unwrap_or(0.0)), d.voids.late
);
}
if d.voids.reworded > 0 {
let _ = writeln!(
out,
" Reworded: {} settled claim(s) had their statement changed after they were logged (`ana show <id>` lists each change). A reword can turn a miss into a hit; it counts toward the same one-in-ten line as a void.",
d.voids.reworded
);
}
if d.voided_after_resolution > 0 {
let _ = writeln!(
out,
" ⚠ {} claim(s) were voided AFTER they had already resolved — an outcome removed from the record after it was seen. They are still counted in the evidence test below; voiding a claim you did not like is how this instrument would be defeated.",
d.voided_after_resolution
);
}
if rd.auto_graded > 0 {
let _ = writeln!(
out,
" {} of them ({:.0}%) were graded from a test run's exit status: {} by the command pinned when they were logged, {} by the next plain test run the hook saw. The grade is not yours, though the choice of command was.",
rd.auto_graded,
100.0 * rd.auto_graded as f64 / rd.resolved.max(1) as f64,
rd.auto_pinned,
rd.auto_graded - rd.auto_pinned
);
}
if let (Some(rb), Some(ob), Some(asmd)) =
(rd.resolved_boldness, rd.open_boldness, rd.boldness_asmd)
{
if asmd > SELECTION_ASMD_FLAG {
let (dir, caveat) = if ob > rb {
(
"BOLDER",
"the confident end, where overconfidence hides, is under-graded — the gap above may understate it",
)
} else {
(
"more CAUTIOUS",
"your graded sample leans bold relative to what you actually predicted",
)
};
let _ = writeln!(
out,
" Your ungraded calls are {dir} than your graded ones (boldness {ob:.2} vs {rb:.2}, ASMD {asmd:.2}) — {caveat}.",
);
}
}
}
if d.resolved_binary > 0 {
let _ = writeln!(
out,
"\n VERDICT {}",
d.verdict.label().to_uppercase()
);
if let Some(note) = sensitivity_note(&d) {
let _ = writeln!(out, " {note}.");
}
if d.verdict == Verdict::InsufficientData {
if let Some(note) = pending_due_note(&d) {
let _ = writeln!(out, " {note}.");
}
}
if d.verdict == Verdict::Withheld {
let _ = writeln!(
out,
" {} of the {} settled claims {}. Every score here leaves voided claims out and scores a reworded one as reworded, and the misses are the ones that get edited, so none of them is read.",
d.voids.edited().0, d.voids.settled, d.voids.edited().1
);
}
if d.verdict != Verdict::Withheld {
let detail = d.resolved_binary >= DETAIL_MIN_N;
if let (Some(brier), Some(logs), Some(base)) = (d.brier, d.log_score, d.base_rate) {
let _ = writeln!(out, "\n Brier score {brier:.3} (0 = perfect · 0.25 = always 50/50 · lower better)");
let _ = writeln!(
out,
" scored on your FIRST forecast — the belief you recorded before the answer was known"
);
if let Some(bf) = d.brier_final {
if (bf - brier).abs() > 0.0005 {
let _ = writeln!(
out,
" on your final forecast it would be {bf:.3} (shown, not graded)"
);
}
}
if let (Some((lo, hi)), true) = (d.brier_ci, detail) {
let _ = writeln!(
out,
" 95% bootstrap band [{lo:.3}, {hi:.3}] — how far luck alone could move it"
);
}
if let Some(wb) = d.weighted_brier {
let cmp = if wb > brier + 0.01 {
"WORSE on the calls that matter"
} else if wb < brier - 0.01 {
"better on the calls that matter"
} else {
"about the same across stakes"
};
let _ = writeln!(
out,
" Stake-weighted {wb:.3} vs {brier:.3} flat → {cmp}"
);
}
let _ = writeln!(
out,
" Log score {logs:.3} (lower better; punishes confident misses)"
);
if let (Some(bss), true) = (d.brier_skill, detail) {
let tail = if bss > 0.0 {
"you beat always-guess-the-base-rate"
} else if bss < 0.0 {
"you did WORSE than always guessing the base rate"
} else {
"no better than guessing the base rate"
};
let _ = writeln!(out, " Brier skill {bss:+.3} ({tail})");
}
if let Some(recent) = d.recent_brier {
if d.resolved_binary >= TREND_MIN_N {
let delta = brier - recent; let lean = if delta > 0.02 {
"improving"
} else if delta < -0.02 {
"slipping"
} else {
"steady"
};
let _ = writeln!(
out,
" Lately {recent:.3} recent Brier vs {brier:.3} lifetime → {lean} (last ~5 weighted; directional, not significant)"
);
}
}
let ci = d
.base_rate_ci
.map(|(lo, hi)| format!(" 95% CI {lo:.2}–{hi:.2}"))
.unwrap_or_default();
let _ = writeln!(
out,
" Base rate {base:.3} (fraction of your claims that came true){ci}"
);
if let Some(note) = easy_note(&d) {
let _ = writeln!(out, " Easy calls {note}");
}
}
if !detail {
let _ = writeln!(
out,
"\n ({} graded call(s). Below {DETAIL_MIN_N}, the band, the decomposition, the confidence gap and the diagram would describe noise, so they are left out.)",
d.resolved_binary
);
}
if !d.so_far.is_empty() && d.verdict != Verdict::Withheld {
let _ = writeln!(
out,
"\n Graded so far (newest first; `ana show <id>` for the claim)"
);
for g in &d.so_far {
let _ = writeln!(
out,
" [{}] said {:>3.0}% → {:<16} Brier {:.3}{}",
g.id,
g.prob * 100.0,
if g.came_true {
"came true"
} else {
"did not happen"
},
g.brier,
if g.brier >= 0.64 {
" ← a sure call that missed costs the most"
} else {
""
}
);
}
}
if let (Some(mcb), Some(dsc), Some(unc), true) = (d.mcb, d.dsc, d.unc, detail) {
let _ = writeln!(
out,
"\n Decomposition (Brier = Miscalibration − Discrimination + Uncertainty)"
);
match d.mcb_null_q95 {
Some(floor) if floor > 0.0 => {
let _ = writeln!(
out,
" miscalibration {mcb:.3} calibration error ↓ lower is better\n {:.2}x the {floor:.3} that only 1 calibrated forecaster in 20 exceeds on these same calls",
mcb / floor
);
}
Some(_) => {
let _ = writeln!(
out,
" miscalibration {mcb:.3} calibration error ↓ lower is better\n too few graded calls for a meaningful noise floor yet"
);
}
None => {
let _ = writeln!(
out,
" miscalibration {mcb:.3} calibration error ↓ lower is better"
);
}
}
let dsc_note = if unc.abs() < 1e-12 {
" — n/a: every call resolved the same way, so there is nothing to sort"
} else if dsc.abs() < 1e-9 {
" — your confidence carries NO information about which calls come true"
} else {
""
};
let _ = writeln!(
out,
" discrimination {dsc:.3} sorting power ↑ higher is better{dsc_note}"
);
let _ = writeln!(
out,
" uncertainty {unc:.3} irreducible difficulty of your questions"
);
let _ = writeln!(out, " check {mcb:.3} − {dsc:.3} + {unc:.3} = {:.3} (= Brier, exactly — no bins, no tuning)", mcb - dsc + unc);
}
match d.auc {
Some(a) => {
let _ = writeln!(out, "\n Discrimination AUC {a:.3} (0.5 = can't tell true from false · 1.0 = perfect)");
}
None => {
let _ = writeln!(
out,
"\n Discrimination n/a (every claim resolved the same way)"
);
}
}
if let (Some(gap), Some(conf), Some(acc), true) =
(d.confidence_gap, d.mean_confidence, d.accuracy, detail)
{
let _ = writeln!(
out,
"\n Confidence gap {} {}",
signed(gap),
gap_gloss(gap, d.verdict)
);
let _ = writeln!(
out,
" mean boldness {conf:.3} vs accuracy {acc:.3}"
);
if let Some(bias) = d.directional_bias {
let dir = if bias >= 0.0005 {
" (toward YES)"
} else if bias <= -0.0005 {
" (toward NO)"
} else {
""
};
let _ = writeln!(
out,
" directional bias {}{dir}",
signed(bias)
);
}
}
if d.distinct_forecasts > 0 && detail {
let _ = writeln!(
out,
"\n Confidence vocab {:>4} distinct level(s) across {} call(s){}",
d.distinct_forecasts,
d.resolved_binary,
if d.distinct_forecasts <= 3 && d.resolved_binary >= 6 {
" — coarse; more gradations would sharpen you"
} else {
""
}
);
}
if let Some(sel) = &d.selective {
if d.resolved_binary >= 6 {
let verdict = if sel.risk_full < 0.005 {
"no misses to separate"
} else if sel.risk_half < sel.risk_full - 0.05 {
"your confidence ranks your calls — trust the bold ones"
} else if sel.risk_half > sel.risk_full + 0.05 {
"INVERTED — your most-confident calls are your worst"
} else {
"confidence barely separates winners from losers"
};
let _ = writeln!(
out,
"\n Selective act on all {:.0}% error · surest half {:.0}% → {verdict}",
sel.risk_full * 100.0,
sel.risk_half * 100.0
);
}
}
if let Some(e) = d.eprocess {
let p = d.eprocess_pvalue.unwrap_or(1.0);
let n = d.evidence_n;
let shown = if d
.eprocess_log
.is_some_and(|l| l >= scoring::EPROCESS_LOG_CAP)
{
"> 10^12".to_string()
} else if e < 0.1 {
format!("{e:.3}")
} else {
format!("{e:.1}")
};
let line = if e >= EVIDENCE_ALARM {
"miscalibration is REAL — significant even though you peek every session (α=.05)"
.to_string()
} else if n < VERDICT_MIN_N {
format!(
"not enough graded calls yet — {n} in the test, about {} more to reach a usable {VERDICT_MIN_N}",
VERDICT_MIN_N.saturating_sub(n)
)
} else if e >= RECAL_MIN_E {
"suggestive, not yet conclusive — keep logging".to_string()
} else {
"no evidence of miscalibration in {n} graded calls — the test can still miss patterns; read the calibration error above for the SIZE of any error"
.replace("{n}", &n.to_string())
};
let _ = writeln!(
out,
"\n Is it real? e-value {shown:>8} (anytime-valid p ≤ {p:.3})"
);
let _ = writeln!(out, " {line}");
} else if d.resolved_binary > 0 {
let _ = writeln!(out, "\n Is it real? no evidence sequence yet");
}
if d.resolved_binary > 0 && d.verdict == Verdict::NoEvidenceOfMiscalibration {
let notable = mcb_ratio(&d).is_some_and(|r| r >= MCB_RATIO_NOTABLE);
if notable {
let _ = writeln!(
out,
" but your calibration error is {:.2}x its noise floor. the two checks disagree, and they fail in opposite directions:",
mcb_ratio(&d).unwrap_or(1.0)
);
let _ = writeln!(
out,
" the e-process is strong on sharp patterns and weak on a gentle drift toward 50/50; the error above measures SIZE but one reading of it is a single look, not an anytime-valid test"
);
let _ = writeln!(
out,
" treat this as worth watching, not as settled either way — keep logging"
);
}
}
if d.resolved_binary > 0 && d.evidence_ungraded_due > 0 {
let _ = writeln!(
out,
" {} of {} graded calls counted, {} ungraded priced in at their worst case (`ana list --due`)",
d.evidence_n, d.resolved_binary, d.evidence_ungraded_due
);
if let Some(cost) = d.evidence_gap_cost_log {
if cost > 0.0 {
let _ = writeln!(
out,
" that backlog is costing you a factor of {:.3} on the evidence — grading it is how you get it back",
cost.min(scoring::EPROCESS_LOG_CAP).exp()
);
}
}
if let Some(id) = &d.evidence_oldest_gap {
let fix = if d.evidence_gap_without_deadline {
"resolve it, or give it a --by date"
} else {
"resolve it, or void it if it was never answerable"
};
let _ = writeln!(
out,
" oldest is [{id}] — {fix}. an ungraded bold call costs more than a cautious one",
);
}
}
if let Some(r) = &d.recalibration {
let has_evidence = d.eprocess.is_some_and(|e| e >= RECAL_MIN_E);
if has_evidence
&& r.n >= RECAL_MIN_N
&& ((r.b - 1.0).abs() > 0.10 || r.a.abs() > 0.10)
{
let shape = if r.b < 1.0 {
"you run too extreme"
} else {
"you are too timid"
};
let bias = if r.a > 0.10 {
"; under-stating on average"
} else if r.a < -0.10 {
"; over-stating on average"
} else {
""
};
let _ = writeln!(
out,
"\n Recalibration stated → what it should be (Cox slope b={:.2}: {shape}{bias})",
r.b
);
let cells: Vec<String> = r
.examples
.iter()
.map(|(p, q)| format!("{p:.2}→{q:.2}"))
.collect();
let _ = writeln!(out, " {}", cells.join(" "));
}
}
if detail {
let _ = writeln!(
out,
"\n Reliability diagram P = your avg forecast · O = what actually happened"
);
let _ = writeln!(
out,
" range n 0{}1",
" ".repeat(LANE_W.saturating_sub(2))
);
for b in &d.calibration {
if b.count == 0 {
continue;
}
let mean_pred = b.mean_pred.unwrap_or((b.lo + b.hi) / 2.0);
let tail = match b.observed {
None => String::new(),
Some(obs) => {
let gap = mean_pred - obs;
let mark = if gap.abs() < 0.05 {
"ok"
} else if gap > 0.0 {
"over"
} else {
"under"
};
format!(" pred {mean_pred:.2} → obs {obs:.2} {mark}")
}
};
let _ = writeln!(
out,
" {:.2}-{:.2} {:>4} |{}|{}",
b.lo,
b.hi,
b.count,
lane(mean_pred, b.observed),
tail
);
}
}
if !d.by_tag.is_empty() {
let _ = writeln!(out, "\n By domain");
let _ = writeln!(
out,
" {:<14} {:>4} {:>7} {:>9}",
"tag", "n", "brier", "conf-gap"
);
for t in &d.by_tag {
let br = t
.brier
.map(|x| format!("{x:.3}"))
.unwrap_or_else(|| " —".into());
let g = t
.confidence_gap
.map(|x| format!("{x:+.3}"))
.unwrap_or_else(|| " —".into());
let _ = writeln!(
out,
" {:<14} {:>4} {:>7} {:>9}",
untrusted::tag(&t.tag),
t.n,
br,
g
);
}
}
if d.group_by.is_none() && d.resolved_binary > 0 {
if d.group_coverage < KIND_MIN_COVERAGE {
let _ = writeln!(
out,
"\n By group hidden: your best-covered tag reaches only {:.0}% of your graded",
d.group_coverage * 100.0
);
let _ = writeln!(
out,
" calls, so a breakdown would describe a self-selected slice."
);
let _ = writeln!(
out,
" tag as you log — `--tags kind:<type>` (tests-pass, estimate,"
);
let _ = writeln!(
out,
" bug-hypothesis, approach, compat) or any topic tag — and this"
);
let _ = writeln!(
out,
" fills in at {:.0}% coverage.",
KIND_MIN_COVERAGE * 100.0
);
} else {
let _ = writeln!(
out,
"\n By group hidden: your tags cover the record but split it into {} group{}.",
d.group_k,
if d.group_k == 1 { "" } else { "s" }
);
let _ = writeln!(
out,
" every group pays a factor of K in its alarm, so {}-{} is the usable",
GROUP_MIN_K, GROUP_MAX_K
);
let _ = writeln!(
out,
" range — a per-session or per-user tag is bookkeeping, not a grouping."
);
let _ = writeln!(
out,
" add a `kind:` tag (tests-pass, estimate, bug-hypothesis, approach,"
);
let _ = writeln!(
out,
" compat) and the breakdown keys off that instead."
);
}
} else if !d.by_kind.is_empty() {
let _ = writeln!(
out,
"\n By {:<17}(K={} groups · {:.0}% covered · gap~ shrunk toward your overall rate)",
untrusted::tag(d.group_by.as_deref().unwrap_or("group")),
d.group_k,
d.group_coverage * 100.0
);
let _ = writeln!(
out,
" {:<16} {:>4} {:>7} {:>8} {:>8}",
untrusted::tag(d.group_by.as_deref().unwrap_or("group")),
"n",
"brier",
"gap",
"gap~"
);
for t in &d.by_kind {
let br = t
.brier
.map(|x| format!("{x:.3}"))
.unwrap_or_else(|| " —".into());
let g = t
.confidence_gap
.map(|x| format!("{x:+.3}"))
.unwrap_or_else(|| " —".into());
let gs = t
.confidence_gap_shrunk
.map(|x| format!("{x:+.3}"))
.unwrap_or_else(|| " —".into());
let _ = writeln!(
out,
" {:<16} {:>4} {:>7} {:>8} {:>8}",
untrusted::tag(&t.tag),
t.n,
br,
g,
gs
);
}
let k_threshold = d.kind_alarm_threshold.unwrap_or(EVIDENCE_ALARM);
if let Some((t, e)) = d
.by_kind
.iter()
.filter_map(|t| t.eprocess.map(|e| (t, e)))
.filter(|&(_, e)| e >= k_threshold)
.max_by(|a, b| a.1.total_cmp(&b.1))
{
let dir = match t.confidence_gap {
Some(g) if g > 0.0 => "overconfident",
Some(_) => "underconfident",
None => "miscalibrated",
};
let _ = writeln!(
out,
" → '{}' is really {dir} (e={:.0}) — trust your '{}' calls least.",
untrusted::tag(&t.tag),
e,
untrusted::tag(&t.tag)
);
}
}
if let Some(mc) = &d.mind_changing {
let _ = writeln!(
out,
"\n Mind-changing {} claim(s) you revised",
mc.revised
);
let _ = writeln!(
out,
" Brier of first guess {:.3} (GRADED) → Brier of final guess {:.3} (not graded) ({:+.3})",
mc.brier_first, mc.brier_last, mc.improvement
);
let _ = writeln!(
out,
" Only the first figure is scored. A revision may be genuine learning or may be hindsight; the ledger cannot tell, so it grades the belief you recorded before the answer was known."
);
if d.late_updates > 0 {
let _ = writeln!(
out,
" {} claim(s) were revised after their due date or within a day of the answer — those revisions carry no weight anywhere.",
d.late_updates
);
}
if let Some(ta) = d.brier_time_avg {
let _ = writeln!(
out,
" Time-averaged Brier {ta:.3} — each forecast weighted by how long it stood, the way Metaculus rewards updating early (secondary: it can still be farmed by updating the moment you know)."
);
}
}
} }
if let Some(num) = &d.numeric {
let _ = writeln!(
out,
"\n Numeric forecasts {} resolved interval(s)",
num.count
);
let _ = writeln!(
out,
" interval score {}\n (1.00 = the value landed inside; above that is the miss penalty, in multiples of your own stated width)",
match (num.mean_winkler_ratio, num.median_winkler_ratio) {
(Some(mean), Some(med)) => format!("mean {mean:.2} · median {med:.2}"),
_ => format!("{:.3} raw Winkler (units vary)", num.mean_winkler),
}
);
let _ = writeln!(out, " mean interval width {:.3}", num.mean_width);
let _ = writeln!(
out,
" coverage {:.0}% actual vs {:.0}% intended ({:+.0} pts)",
num.empirical_coverage * 100.0,
num.nominal_coverage * 100.0,
num.coverage_gap * 100.0
);
let line = if num.coverage_gap < -0.05 {
" Your intervals are TOO NARROW — overconfident about numbers, just like probabilities."
} else if num.coverage_gap > 0.05 {
" Your intervals are too WIDE — you could afford to be sharper."
} else {
" Your intervals are about the right width. Well judged."
};
let _ = writeln!(out, "{line}");
if let (Some(m), Some(e)) = (num.width_factor, num.coverage_eprocess) {
if e >= RECAL_MIN_E && (m - 1.0).abs() > 0.10 {
let verb = if m > 1.0 { "WIDEN" } else { "SHARPEN" };
let _ = writeln!(
out,
" Recalibration: {verb} — multiply your interval half-widths by {m:.2} (coverage e={e:.0})."
);
}
}
}
let _ = writeln!(
out,
"\n \"The first principle is that you must not fool yourself —\n and you are the easiest person to fool.\" — R. Feynman\n"
);
out
}
fn pct(x: f64) -> String {
format!("{:.0}%", (x * 100.0).round())
}
fn wrap(text: &str, width: usize, indent: &str) -> String {
let mut lines: Vec<String> = Vec::new();
let mut cur = String::new();
for word in text.split_whitespace() {
if !cur.is_empty() && cur.chars().count() + 1 + word.chars().count() > width {
lines.push(std::mem::take(&mut cur));
}
if !cur.is_empty() {
cur.push(' ');
}
cur.push_str(word);
}
if !cur.is_empty() {
lines.push(cur);
}
lines
.into_iter()
.map(|l| format!("{indent}{l}"))
.collect::<Vec<_>>()
.join("\n")
}
fn esc(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
}
struct Insight {
label: &'static str,
answer: String,
jargon: &'static str,
}
struct PlainSummary {
headline: String,
verdict_word: String,
verdict_class: &'static str,
insights: Vec<Insight>,
actions: Vec<String>,
footer: String,
}
fn easy_heavy(d: &ReportData) -> bool {
d.resolved_binary > 0 && d.easy_calls as f64 >= EASY_SHARE_NOTE * d.resolved_binary as f64
}
fn easy_note(d: &ReportData) -> Option<String> {
let n = d.resolved_binary;
if !easy_heavy(d) {
return None;
}
let rest = match d.brier_contested {
Some(b) => format!("; on the other {} it is {b:.3}", n - d.easy_calls),
None => format!("; too few others ({}) to score apart", n - d.easy_calls),
};
Some(format!(
"{} of your {n} graded calls ({:.0}%) were said at {:.0}% or more either way. Sure things lower a Brier score without showing much judgement{rest}",
d.easy_calls,
100.0 * d.easy_calls as f64 / n as f64,
EASY_P * 100.0
))
}
fn sensitivity_note(d: &ReportData) -> Option<String> {
let r = d.sensitivity?;
let (only, weight) = if r < 0.5 {
("only ", "so this silence says little")
} else if r < 0.8 {
("only ", "so this silence is moderate evidence at best")
} else {
("", "so an error that size would probably have shown")
};
Some(format!(
"At your {} calls, this test catches a forecaster {:.0}% too extreme {only}{:.0}% of the time, {weight}",
d.evidence_n,
SENSITIVITY_SHRINK * 100.0,
r * 100.0
))
}
fn pending_due_note(d: &ReportData) -> Option<String> {
let (k, first, last) = d.evidence_pending?;
let when = if first == last {
format!("on {first}")
} else {
format!("between {first} and {last}")
};
Some(format!(
"{k} resolved call(s) join the test {when}. It reads claims in due-date order, which is what keeps it valid however often you look, so a call counts once its due date has passed, however early it was resolved. Until then the numbers below describe your calls; they do not decide anything"
))
}
fn plain_summary(d: &ReportData) -> PlainSummary {
let n = d.resolved_binary;
let mut insights: Vec<Insight> = Vec::new();
if let Some(rd) = &d.resolution_discipline {
let mut a = if d.verdict == Verdict::Withheld {
format!(
"No. {} of your {} settled call(s) {}, and every number leaves a voided call out and scores a reworded one as reworded, so what remains may be the calls that went your way.",
d.voids.edited().0, d.voids.settled, d.voids.edited().1
)
} else if rd.open == 0 && d.voids.total == 0 {
format!("Yes — you've graded every one of your {} call(s). This isn't a picture cherry-picked from only the predictions that went your way.", rd.resolved)
} else if rd.open == 0 {
format!(
"You've graded every one of the {} call(s) still on the record.",
rd.resolved
)
} else {
format!(
"You've graded {} of {} call(s) ({}). The {} still open aren't in the numbers below.",
rd.resolved,
rd.resolved + rd.open,
pct(rd.resolution_rate),
rd.open
)
};
if d.voids.total > 0 && d.verdict != Verdict::Withheld {
a.push_str(&format!(" You voided {} call(s)", d.voids.total));
if d.voids.late > 0 {
a.push_str(&format!(
", {} of them after they came due, when you may already have known how they went.",
d.voids.late
));
} else {
a.push_str(". A void hides a miss whenever it is made, so past one in ten no verdict is read.");
}
}
if let Some(note) = easy_note(d) {
a.push_str(&format!(
" Also, {}{}.",
note[..1].to_lowercase(),
¬e[1..]
));
}
if rd.overdue > 0 {
a.push_str(&format!(" Watch out: {} of those are past their due date — resolve them, or these scores quietly flatter you.", rd.overdue));
}
if let (Some(rb), Some(ob), Some(asmd)) =
(rd.resolved_boldness, rd.open_boldness, rd.boldness_asmd)
{
if asmd > SELECTION_ASMD_FLAG {
let dir = if ob > rb { "bolder" } else { "more cautious" };
a.push_str(&format!(
" And the calls you left open are {dir} than the ones you graded, so the split isn't random."
));
}
}
insights.push(Insight {
label: "Is this an honest sample of your calls?",
answer: a,
jargon: "resolution discipline / selection bias",
});
}
let (verdict_word, verdict_class): (String, &'static str) = match d.verdict {
Verdict::InsufficientData => ("Not enough data".into(), "unknown"),
Verdict::Withheld => ("Withheld".into(), "unknown"),
Verdict::Overconfident => ("Overconfident".into(), "over"),
Verdict::Underconfident => ("Underconfident".into(), "under"),
Verdict::BiasedYes => ("Leans yes".into(), "over"),
Verdict::BiasedNo => ("Leans no".into(), "under"),
Verdict::CalibratedButUninformative => ("Uninformative".into(), "uninformative"),
Verdict::MiscalibratedBothWays => ("Miscalibrated".into(), "both"),
Verdict::NoEvidenceOfMiscalibration
if d.sensitivity.is_some_and(|r| r < DIALED_MIN_SENSITIVITY) =>
{
("Nothing found yet".into(), "unknown")
}
Verdict::NoEvidenceOfMiscalibration => ("No miscalibration found".into(), "good"),
};
if let (Some(conf), Some(acc)) = (d.mean_confidence, d.accuracy) {
let core = format!(
"On the calls you felt about {} sure of, you turned out right about {} of the time.",
pct(conf),
pct(acc)
);
let lesson = match d.verdict {
Verdict::Overconfident => "You OVERSELL yourself — you sound more certain than you turn out to be, so shade your confidence down.",
Verdict::Underconfident => "You UNDERSELL yourself — reality rewards you more than you claim, so when you feel fairly sure you can trust it more.",
Verdict::BiasedYes => "You lean toward YES — you say things will happen more often than they do.",
Verdict::BiasedNo => "You lean toward NO — you say things won't happen more often than turns out to be true.",
Verdict::CalibratedButUninformative => "Your confidence does not separate the calls that come true from the ones that don't — after correcting for level, every forecast you make carries the same information. That is the thing to fix first; how high or low you pitch the numbers barely matters until the ranking works.",
Verdict::InsufficientData => "Too few graded calls to say whether that's luck or judgement.",
Verdict::Withheld => "No reading is given. More than one in ten of the settled calls were voided, and the ones that get voided are the ones that went badly, so these numbers describe a record that has been tidied. Resolve a call when it answers, even when it went against you; a void is for a question that stopped making sense.",
Verdict::MiscalibratedBothWays => "Your errors run BOTH ways — too sure at one end of your range and not sure enough at the other. They cancel in the average, so there is no single direction to shade: look at the reliability diagram to see where each half goes wrong.",
Verdict::NoEvidenceOfMiscalibration => "Nothing in the record shows your confidence is off. That is not the same as proof it's right — the test can miss patterns, and a small record hides a lot.",
};
let answer = if d.verdict == Verdict::Withheld {
lesson.to_string()
} else {
format!("{core} {lesson}")
};
insights.push(Insight {
label: "When you say you're sure, should you be?",
answer,
jargon: "calibration verdict (CORP miscalibration + sequential evidence test)",
});
}
let disc = match d.auc {
None => "Everything you've logged so far turned out the same way, so there's nothing to sort yet.".to_string(),
Some(_) if n < 12 => format!("Can't tell from {n} call(s) yet — sorting your good calls from your bad ones needs more answers before it means anything."),
Some(a) if a >= 0.70 => "Yes — the calls you're more confident about come true noticeably more often than the ones you're unsure of.".to_string(),
Some(a) if a >= 0.55 => "Somewhat — your confidence points the right way, but not sharply.".to_string(),
Some(_) => "Not really — your confidence isn't tracking which calls actually come true. Of everything here, that's the one most worth fixing.".to_string(),
};
insights.push(Insight {
label: "Can you tell your right calls from your wrong ones?",
answer: disc,
jargon: "discrimination (AUC)",
});
if let Some(e) = d.eprocess {
let en = d.evidence_n;
let ev = if e >= EVIDENCE_ALARM {
"Yes, it's real. Even though you check this every session, the pattern above is statistically solid — you can act on it.".to_string()
} else if en < VERDICT_MIN_N {
format!(
"Not yet answerable. Only {en} of your calls are in the test, and about {} more are needed before it can say anything either way.{}",
VERDICT_MIN_N.saturating_sub(en),
pending_due_note(d).map(|s| format!(" Note: {s}.")).unwrap_or_default()
)
} else if e >= RECAL_MIN_E {
"Maybe — the signs are suggestive but not yet conclusive. Keep logging.".to_string()
} else {
format!("No. Across {en} graded calls the test found no miscalibration. That is not proof you are calibrated — the test can miss patterns it isn't looking for — but nothing here is demonstrably off.")
};
insights.push(Insight {
label: "Is any of this real, or a small-sample fluke?",
answer: ev,
jargon: "anytime-valid e-value",
});
}
if let Some(b) = d.brier {
let band = d
.brier_ci
.map(|(lo, hi)| {
format!(
" Luck alone could place the true figure anywhere between {lo:.2} and {hi:.2}."
)
})
.unwrap_or_default();
let quality = if b < 0.10 {
"That's sharp."
} else if b < 0.25 {
"Better than a coin flip."
} else {
"That's around coin-flip territory."
};
insights.push(Insight {
label: "How good are your predictions overall?",
answer: format!(
"{b:.2} on the forecasting \"golf score\": 0 is a perfect prophet, 0.25 is a coin flip, lower is better. {quality}{band}"
),
jargon: "Brier score",
});
}
if let Some(num) = &d.numeric {
let a = if num.coverage_gap < -0.05 {
format!("Your number ranges are TOO NARROW — meant to contain the true value {} of the time, they only did {} of the time. You're overconfident about numbers, just like probabilities.", pct(num.nominal_coverage), pct(num.empirical_coverage))
} else if num.coverage_gap > 0.05 {
format!("Your number ranges are too WIDE — they caught the value {} of the time versus the {} you aimed for, so you can afford to be sharper.", pct(num.empirical_coverage), pct(num.nominal_coverage))
} else {
"Your number ranges are about the right width — well judged.".to_string()
};
insights.push(Insight {
label: "And your number ranges?",
answer: a,
jargon: "interval coverage",
});
}
if d.verdict == Verdict::Withheld {
insights.retain(|i| {
i.jargon.starts_with("resolution discipline")
|| i.jargon.starts_with("calibration verdict")
});
}
let mut actions: Vec<String> = Vec::new();
if d.verdict == Verdict::Withheld {
actions.push("Resolve the calls that have come due instead of voiding them. A void is for a question that stopped making sense before you knew the answer.".into());
}
match verdict_class {
"under" => actions
.push("Lean in a little when you feel sure — you tend to undersell yourself.".into()),
"over" => {
actions.push("Add slack and shade your confidence down — you tend to oversell.".into())
}
"both" => actions.push(
"Your errors cancel: shading everything one way will not help. Compare your high-confidence and low-confidence calls separately — the reliability diagram shows which end is wrong.".into(),
),
"uninformative" => actions.push(
"Spread your probabilities out — right now they don't distinguish the calls that come true from the ones that don't.".into(),
),
"good" if n >= VERDICT_CONFIDENT_N => actions
.push("Nothing here needs correcting — keep logging so it stays that way.".into()),
"good" => actions.push(
"Nothing is demonstrably off yet. Keep logging: absence of evidence at this sample size is not evidence of calibration.".into(),
),
_ => {}
}
let earned = d.eprocess.is_some_and(|e| e >= RECAL_MIN_E)
&& d.recalibration
.as_ref()
.is_some_and(|r| r.n >= RECAL_MIN_N && ((r.b - 1.0).abs() > 0.10 || r.a.abs() > 0.10));
if earned {
if let Some((p, q)) = d
.recalibration
.as_ref()
.and_then(|r| r.examples.iter().find(|(p, _)| (*p - 0.7).abs() < 1e-9))
{
actions.push(format!(
"A correction has earned its place: when you'd say {}, log about {} instead.",
pct(*p),
pct(*q)
));
}
}
if n < 12 {
actions.push(format!(
"Don't over-read {n} prediction(s) — keep logging and the picture sharpens."
));
}
actions.push("Before a costly or irreversible call, run `ana decide` to turn your confidence into a clear proceed / verify / abstain.".into());
let headline = match d.verdict {
Verdict::Withheld => format!(
"No verdict: {} of your {} settled calls {}.",
d.voids.edited().0, d.voids.settled, d.voids.edited().1
),
Verdict::Underconfident => {
"You undersell yourself — trust your sure calls more.".to_string()
}
Verdict::Overconfident => "You oversell yourself — add slack and shade down.".to_string(),
Verdict::BiasedYes => {
"You lean toward yes — you predict things happen more than they do.".to_string()
}
Verdict::BiasedNo => {
"You lean toward no — you predict things don't happen more than holds up.".to_string()
}
Verdict::CalibratedButUninformative => {
"Right on average, but your confidence doesn't separate the good calls from the bad."
.to_string()
}
Verdict::MiscalibratedBothWays => {
"Miscalibrated in both directions at once — the errors cancel in the average."
.to_string()
}
Verdict::NoEvidenceOfMiscalibration
if n >= VERDICT_CONFIDENT_N
&& mcb_ratio(d).is_some_and(|r| r >= MCB_RATIO_NOTABLE) =>
{
format!(
"The 'is it real' test is quiet, but the SIZE of your calibration error is {:.1}x its noise floor. The two checks disagree — worth watching, not settled.",
mcb_ratio(d).unwrap_or(1.0)
)
}
Verdict::NoEvidenceOfMiscalibration if n >= VERDICT_CONFIDENT_N => format!(
"Neither check finds your confidence off — which is not the same as proof that it is right.{}",
sensitivity_note(d).map(|s| format!(" {s}.")).unwrap_or_default()
),
Verdict::NoEvidenceOfMiscalibration => format!(
"Nothing shows your confidence is off — but this is still a small record.{}",
sensitivity_note(d).map(|s| format!(" {s}.")).unwrap_or_default()
),
Verdict::InsufficientData => format!(
"Too few resolved calls to read your calibration yet.{}",
pending_due_note(d).map(|s| format!(" {s}.")).unwrap_or_default()
),
};
let evidence_tag = match d.eprocess {
_ if d.verdict == Verdict::Withheld => "verdict withheld",
Some(e) if e >= EVIDENCE_ALARM => "evidence: solid",
Some(e) if e >= RECAL_MIN_E => "evidence: suggestive",
_ if d.evidence_n < VERDICT_MIN_N => "evidence: too few to tell",
_ => "evidence: no miscalibration found",
};
let footer = format!(
"{} resolved · {} · offline & local — nothing left your machine",
d.resolved_binary, evidence_tag
);
PlainSummary {
headline,
verdict_word,
verdict_class,
insights,
actions,
footer,
}
}
const CAT_DIALED: &str = " /\\_/\\\n ( ^.^ ) <3\n > ^ <";
const CAT_CLOSE: &str = " /\\_/\\\n ( o.o )\n > . <";
const CAT_DRIFT: &str = " /\\_/\\\n ( ;_; )\n > _ <";
const CAT_OFF: &str = " /\\_/\\\n ( @_@ )\n >< ><";
const CAT_SLEEPY: &str = " /\\_/\\\n ( -.- ) zzz\n > ~ <";
struct Mood {
art: &'static str,
name: &'static str,
gloss: String,
}
const MOOD_WORST_EXCESS: f64 = 0.10;
fn mood(d: &ReportData) -> Mood {
let excess = match (d.mcb, d.mcb_null_q95) {
(Some(m), Some(f)) => Some((m - f).max(0.0)),
(Some(m), None) => Some(m.max(0.0)),
_ => None,
};
let score = if matches!(d.verdict, Verdict::InsufficientData | Verdict::Withheld) {
None
} else {
excess.map(|e| (100.0 * (1.0 - (e / MOOD_WORST_EXCESS).min(1.0))).round() as u32)
};
let dir = match d.verdict {
Verdict::InsufficientData => "not enough graded calls to judge yet",
Verdict::Withheld => "verdict withheld — more than one in ten settled calls were voided",
Verdict::Overconfident => "overconfident — you oversell",
Verdict::Underconfident => "underconfident — you undersell",
Verdict::BiasedYes => "leans yes — you over-predict that things happen",
Verdict::BiasedNo => "leans no — you over-predict that things don't",
Verdict::CalibratedButUninformative => "your confidence sorts nothing — fix that first",
Verdict::NoEvidenceOfMiscalibration => "no miscalibration found",
Verdict::MiscalibratedBothWays => {
"miscalibrated both ways — the errors cancel in the average"
}
};
let (art, band) = match score {
None => (CAT_SLEEPY, "WARMING UP"),
Some(s)
if s >= 75
&& d.evidence_n >= VERDICT_CONFIDENT_N
&& mcb_ratio(d).is_none_or(|r| r <= 1.0)
&& d.sensitivity.is_none_or(|r| r >= DIALED_MIN_SENSITIVITY)
&& !easy_heavy(d) =>
{
(CAT_DIALED, "DIALED IN")
}
Some(s) if s >= 75 => (CAT_CLOSE, "NOTHING OFF YET"),
Some(s) if s >= 50 => (CAT_CLOSE, "CLOSE"),
Some(s) if s >= 25 => (CAT_DRIFT, "DRIFTING"),
Some(_) => (CAT_OFF, "WAY OFF"),
};
let (art, name) = match d.verdict {
Verdict::InsufficientData => (CAT_SLEEPY, "WARMING UP"),
Verdict::Withheld => (CAT_SLEEPY, "WITHHELD"),
Verdict::CalibratedButUninformative => (art, "UNINFORMATIVE"),
_ => (art, band),
};
let blind = d.sensitivity.is_some_and(|r| r < 0.5);
let gloss = match score {
Some(_) if blind => {
format!("{dir}, but at this record the test would miss most errors of 30%")
}
Some(s) if easy_heavy(d) => format!(
"calibration {s}/100 · {dir} · {:.0}% of it near-certain calls",
100.0 * d.easy_calls as f64 / d.resolved_binary.max(1) as f64
),
Some(s) => format!("calibration {s}/100 · {dir}"),
None => dir.to_string(),
};
Mood { art, name, gloss }
}
pub fn render_plain(
ledger: &Ledger,
tag_filter: Option<&str>,
bins: usize,
today: NaiveDate,
) -> String {
let d = ReportData::compute(ledger, tag_filter, bins, today);
let mut out = String::new();
let scope = d
.tag
.as_deref()
.map(|t| format!(" [tag: {t}]"))
.unwrap_or_default();
let title = format!("ANAMNESIS — your judgement, in plain English{scope}");
let _ = writeln!(out, "\n{title}");
let _ = writeln!(out, "{}", "=".repeat(title.chars().count()));
if d.is_empty() {
let scope = d
.tag
.as_ref()
.map(|t| format!(" tagged '{t}'"))
.unwrap_or_default();
let _ = writeln!(
out,
"\nNothing to reflect yet{scope}. You have {} open prediction(s) but none resolved.\nLog a belief with `ana add`, then `ana resolve` it once you find out — the\nmirror needs something to reflect.\n",
d.open
);
return out;
}
let m = mood(&d);
let _ = writeln!(out, "\n{}", m.art);
let _ = writeln!(out, " [{}] {}", m.name, m.gloss);
let s = plain_summary(&d);
let _ = writeln!(out, "\n{}", s.headline);
let _ = writeln!(
out,
"Based on {} resolved prediction(s).",
d.resolved_binary
);
if !d.so_far.is_empty() && d.verdict != Verdict::Withheld {
let calls: Vec<String> = d
.so_far
.iter()
.map(|g| {
format!(
"[{}] {:.0}%, {}",
g.id,
g.prob * 100.0,
if g.came_true { "came true" } else { "didn't" }
)
})
.collect();
let _ = writeln!(
out,
"Your graded calls so far, newest first: {}.",
calls.join("; ")
);
}
for ins in &s.insights {
let _ = writeln!(out, "\n{}", ins.label);
let _ = writeln!(out, "{}", wrap(&ins.answer, 74, " "));
let _ = writeln!(out, " ↳ technical name: {}", ins.jargon);
}
let _ = writeln!(out, "\nSo what should you do?");
for act in &s.actions {
let _ = writeln!(out, "{}", wrap(act, 72, " ").replacen(" ", " • ", 1));
}
let _ = writeln!(out, "\n{}\n", s.footer);
out
}
const CARD_CSS: &str = r#" /* ============================================================
ANAMNESIS · CALIBRATION CARD
One file. Inline CSS only. No fonts, no scripts, no network.
Opens offline by double-click. A mirror, not a dashboard.
============================================================ */
:root {
color-scheme: light dark;
/* --- the one value driven by the verdict's severity --- */
--accent-seed: __ACCENT__; /* e.g. #1565c0 */
--accent: var(--accent-seed);
/* --- light palette (paper & ink) --- */
--paper: #efece4; /* page behind the card */
--card: #fbfaf6; /* the card surface */
--ink: #1d1b16; /* primary text */
--ink-soft: #3f3c34; /* answers, body */
--muted: #75716a; /* captions, labels */
--faint: #a39e93; /* technical terms */
--hairline: #e2ddd2; /* rules & ticks */
--shadow: 0 1px 2px rgba(40,34,20,.05), 0 18px 50px -28px rgba(40,34,20,.30);
/* --- type --- */
--serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, "Times New Roman", serif;
--sans: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, "Liberation Mono", monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--paper: #0f1012;
--card: #16181b;
--ink: #eae6dd;
--ink-soft: #c4c0b6;
--muted: #8f8b81;
--faint: #6a665e;
--hairline: #2a2c30;
--shadow: 0 1px 2px rgba(0,0,0,.4), 0 24px 60px -30px rgba(0,0,0,.7);
/* lift the accent off the dark ground so it reads as light */
--accent: color-mix(in oklab, var(--accent-seed), white 30%);
}
}
* { box-sizing: border-box; }
html, body { margin: 0; }
body {
background: var(--paper);
color: var(--ink);
font-family: var(--sans);
font-size: 16px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
min-height: 100vh;
display: flex;
align-items: flex-start;
justify-content: center;
padding: clamp(16px, 5vw, 64px);
}
.card {
width: 100%;
max-width: 660px;
background: var(--card);
border: 1px solid var(--hairline);
border-radius: 7px;
box-shadow: var(--shadow);
overflow: hidden;
position: relative;
}
/* the severity colour as a quiet spine across the top edge */
.card::before {
content: "";
position: absolute;
inset: 0 0 auto 0;
height: 3px;
background: var(--accent);
opacity: .9;
}
.inner {
padding: clamp(30px, 6.5vw, 60px) clamp(26px, 6vw, 60px) clamp(28px, 5vw, 48px);
}
/* ---------- masthead ---------- */
.masthead {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 16px;
margin-bottom: clamp(30px, 6vw, 52px);
}
.wordmark {
font-family: var(--serif);
font-size: 16px;
letter-spacing: .02em;
color: var(--ink);
}
.wordmark .dot { color: var(--accent); }
.kicker {
font-family: var(--sans);
font-size: 11px;
font-weight: 600;
letter-spacing: .22em;
text-transform: uppercase;
color: var(--muted);
}
/* ---------- verdict + headline ---------- */
.verdict {
font-family: var(--serif);
font-weight: 600;
color: var(--accent);
font-size: clamp(40px, 9.5vw, 66px);
line-height: .98;
letter-spacing: -.018em;
margin: 0;
}
.headline {
font-family: var(--serif);
font-weight: 400;
color: var(--ink);
font-size: clamp(20px, 4.1vw, 27px);
line-height: 1.34;
letter-spacing: -.005em;
max-width: 30ch;
text-wrap: balance;
margin: clamp(18px, 3.5vw, 26px) 0 0;
}
/* ---------- a hairline rule ---------- */
.rule {
height: 1px;
background: var(--hairline);
border: 0;
margin: clamp(30px, 6vw, 46px) 0;
}
/* ---------- brier stat ---------- */
.stat-label {
font-size: 11px;
font-weight: 600;
letter-spacing: .2em;
text-transform: uppercase;
color: var(--muted);
margin-bottom: 10px;
}
.brier {
display: flex;
align-items: baseline;
gap: 18px;
flex-wrap: wrap;
}
.brier-num {
font-family: var(--sans);
font-weight: 600;
font-size: clamp(46px, 11vw, 64px);
line-height: 1;
letter-spacing: -.03em;
color: var(--ink);
font-variant-numeric: tabular-nums lining-nums;
}
.brier-caption {
font-size: 13.5px;
line-height: 1.45;
color: var(--muted);
max-width: 30ch;
}
/* ---------- confidence gauge ---------- */
.gauge {
margin-top: clamp(26px, 5vw, 38px);
--pos: 50%;
}
.gauge-track {
position: relative;
height: 30px;
}
/* the baseline */
.gauge-track::before {
content: "";
position: absolute;
left: 0; right: 0; top: 50%;
height: 2px;
transform: translateY(-50%);
background: var(--hairline);
border-radius: 2px;
}
/* the "calibrated" reference at centre */
.gauge-center {
position: absolute;
left: 50%; top: 50%;
width: 1px; height: 22px;
transform: translate(-50%, -50%);
background: var(--faint);
}
/* the marker: a plumb line + dot, in the accent */
.gauge-marker {
position: absolute;
left: var(--pos); top: 50%;
transform: translate(-50%, -50%);
width: 2px; height: 26px;
background: var(--accent);
border-radius: 2px;
}
.gauge-marker::after {
content: "";
position: absolute;
left: 50%; top: 50%;
width: 13px; height: 13px;
transform: translate(-50%, -50%);
background: var(--accent);
border-radius: 50%;
box-shadow: 0 0 0 4px var(--card);
}
.gauge-labels {
display: grid;
grid-template-columns: 1fr auto 1fr;
margin-top: 12px;
font-size: 11px;
font-weight: 600;
letter-spacing: .14em;
text-transform: uppercase;
color: var(--muted);
}
.gauge-labels span:nth-child(1) { text-align: left; }
.gauge-labels span:nth-child(2) { text-align: center; color: var(--faint); }
.gauge-labels span:nth-child(3) { text-align: right; }
/* ---------- insight list ---------- */
.insights {
display: flex;
flex-direction: column;
}
.insight {
padding: clamp(22px, 4vw, 30px) 0;
border-top: 1px solid var(--hairline);
}
.insight:first-child { border-top: 0; padding-top: 0; }
.insight:last-child { padding-bottom: 0; }
.insight-q {
font-family: var(--serif);
font-size: clamp(18px, 3.4vw, 21px);
font-weight: 600;
line-height: 1.3;
letter-spacing: -.005em;
color: var(--ink);
margin: 0;
text-wrap: pretty;
}
.insight-a {
font-family: var(--sans);
font-size: 15.5px;
line-height: 1.6;
color: var(--ink-soft);
margin: 10px 0 0;
max-width: 56ch;
text-wrap: pretty;
}
.insight-term {
font-family: var(--mono);
font-size: 11.5px;
letter-spacing: .01em;
color: var(--faint);
margin: 12px 0 0;
}
/* ---------- what to do ---------- */
.todo-label {
font-size: 11px;
font-weight: 600;
letter-spacing: .2em;
text-transform: uppercase;
color: var(--muted);
margin-bottom: clamp(16px, 3vw, 22px);
}
.actions {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 14px;
}
.actions li {
position: relative;
padding-left: 26px;
font-size: 16.5px;
line-height: 1.5;
color: var(--ink);
max-width: 54ch;
text-wrap: pretty;
}
.actions li::before {
content: "";
position: absolute;
left: 4px; top: .62em;
width: 6px; height: 6px;
border-radius: 50%;
background: var(--accent);
}
/* ---------- footer ---------- */
.footer {
margin-top: clamp(30px, 6vw, 46px);
padding-top: clamp(20px, 4vw, 26px);
border-top: 1px solid var(--hairline);
font-size: 12.5px;
line-height: 1.6;
color: var(--muted);
letter-spacing: .005em;
}
@media (max-width: 480px) {
.masthead { flex-direction: column; gap: 6px; }
}
"#;
pub fn render_html(
ledger: &Ledger,
tag_filter: Option<&str>,
bins: usize,
today: NaiveDate,
) -> String {
let d = ReportData::compute(ledger, tag_filter, bins, today);
let summary = (!d.is_empty()).then(|| plain_summary(&d));
let (verdict_word, verdict_class): (String, &str) = match &summary {
Some(s) => (s.verdict_word.clone(), s.verdict_class),
None => ("Not enough data".to_string(), "unknown"),
};
let accent = match verdict_class {
"under" => "#1565c0",
"over" => "#c62828",
"uninformative" => "#ef6c00",
"both" => "#c62828",
"good" => "#2e7d32",
_ => "#757575",
};
let severity_class = match verdict_class {
"under" => "underconfident",
"over" => "overconfident",
"uninformative" => "uninformative",
"both" => "miscalibrated",
"good" => "no-miscalibration-found",
_ => "not-enough-data",
};
let mut b = String::new();
b.push_str(&format!(
"<main class=\"card\" data-severity=\"{severity_class}\">\n <div class=\"inner\">\n\
<header class=\"masthead\">\n <span class=\"wordmark\">Anamnesis<span class=\"dot\">.</span></span>\n <span class=\"kicker\">Calibration</span>\n </header>\n\
<h1 class=\"verdict\">{}</h1>\n",
esc(&verdict_word)
));
match &summary {
None => {
b.push_str(" <p class=\"headline\">Log a belief and resolve it once you know — the mirror needs something to reflect.</p>\n");
b.push_str(&format!(
" <p class=\"footer\">{} open · 0 resolved · offline & local — nothing left your machine</p>\n",
d.open
));
}
Some(s) => {
b.push_str(&format!(
" <p class=\"headline\">{}</p>\n <hr class=\"rule\" />\n",
esc(&s.headline)
));
if let Some(brier) = d.brier {
b.push_str(&format!(
" <div>\n <div class=\"stat-label\">Brier score</div>\n <div class=\"brier\">\n <span class=\"brier-num\">{brier:.2}</span>\n <span class=\"brier-caption\">forecasting golf score — 0 perfect, 0.25 coin-flip, lower better</span>\n </div>\n"
));
if let Some(gap) = d.confidence_gap {
let pos = (50.0 + gap * 100.0).clamp(3.0, 97.0);
b.push_str(&format!(
" <div class=\"gauge\" style=\"--pos: {pos:.0}%\">\n <div class=\"gauge-track\">\n <span class=\"gauge-center\"></span>\n <span class=\"gauge-marker\"></span>\n </div>\n <div class=\"gauge-labels\">\n <span>Undersell</span>\n <span>Calibrated</span>\n <span>Oversell</span>\n </div>\n </div>\n"
));
}
b.push_str(" </div>\n <hr class=\"rule\" />\n");
}
let items: Vec<&Insight> = s
.insights
.iter()
.filter(|i| i.jargon != "Brier score")
.collect();
if !items.is_empty() {
b.push_str(" <section class=\"insights\">\n");
for i in &items {
b.push_str(&format!(
" <article class=\"insight\">\n <p class=\"insight-q\">{}</p>\n <p class=\"insight-a\">{}</p>\n <p class=\"insight-term\">{}</p>\n </article>\n",
esc(i.label),
esc(&i.answer),
esc(i.jargon)
));
}
b.push_str(" </section>\n <hr class=\"rule\" />\n");
}
if !s.actions.is_empty() {
b.push_str(
" <div class=\"todo-label\">What to do</div>\n <ul class=\"actions\">\n",
);
for a in &s.actions {
b.push_str(&format!(" <li>{}</li>\n", esc(a)));
}
b.push_str(" </ul>\n");
}
b.push_str(&format!(
" <p class=\"footer\">{}</p>\n",
esc(&s.footer)
));
}
}
b.push_str(" </div>\n </main>");
let css = CARD_CSS.replace("__ACCENT__", accent);
format!(
"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>Anamnesis — Calibration Card</title>\n<style>\n{css}</style>\n</head>\n<body>\n {b}\n</body>\n</html>\n"
)
}
pub fn render_badge_svg(
ledger: &Ledger,
tag_filter: Option<&str>,
bins: usize,
today: NaiveDate,
) -> String {
let d = ReportData::compute(ledger, tag_filter, bins, today);
let summary = (!d.is_empty()).then(|| plain_summary(&d));
let (verdict_word, verdict_class): (String, &str) = match &summary {
Some(s) => (s.verdict_word.clone(), s.verdict_class),
None => ("Not enough data".to_string(), "unknown"),
};
let accent = match verdict_class {
"under" => "#1565c0",
"over" => "#c62828",
"good" => "#2e7d32",
_ => "#757575",
};
let brier = d
.brier
.map(|b| format!("{b:.2}"))
.unwrap_or_else(|| "—".into());
let pos = (50.0 + d.confidence_gap.unwrap_or(0.0) * 100.0).clamp(3.0, 97.0);
let gauge_x = 28.0 + 344.0 * pos / 100.0;
let v = esc(&verdict_word);
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="100" viewBox="0 0 400 100" role="img" aria-label="Anamnesis calibration: {v}, Brier {brier}">
<title>Anamnesis calibration — {v} · Brier {brier}</title>
<clipPath id="r"><rect x="1" y="1" width="398" height="98" rx="11"></rect></clipPath>
<rect class="card" x="1" y="1" width="398" height="98" rx="11" fill="#fbfaf6" stroke="#e2ddd2"></rect>
<g clip-path="url(#r)"><rect class="spine" x="0" y="0" width="5" height="100" fill="{accent}"></rect></g>
<text class="verdict" x="28" y="40" fill="{accent}" font-family="'Iowan Old Style',Palatino,Georgia,'Times New Roman',serif" font-size="25" font-weight="600">{v}</text>
<text class="lab" x="372" y="24" text-anchor="end" fill="#75716a" font-family="system-ui,-apple-system,'Segoe UI',Roboto,sans-serif" font-size="9.5" font-weight="600" letter-spacing="2">BRIER</text>
<text class="brier" x="372" y="45" text-anchor="end" fill="#1d1b16" font-family="system-ui,-apple-system,'Segoe UI',Roboto,sans-serif" font-size="26" font-weight="600" letter-spacing="-1">{brier}</text>
<line class="track" x1="28" y1="66" x2="372" y2="66" stroke="#e2ddd2" stroke-width="2" stroke-linecap="round"></line>
<line class="center" x1="200" y1="59" x2="200" y2="73" stroke="#a39e93" stroke-width="1"></line>
<line class="mark" x1="{gauge_x:.1}" y1="57" x2="{gauge_x:.1}" y2="75" stroke="{accent}" stroke-width="2" stroke-linecap="round"></line>
<circle class="dot" cx="{gauge_x:.1}" cy="66" r="5" fill="{accent}" stroke="#fbfaf6" stroke-width="3"></circle>
<text class="foot" x="28" y="90" fill="#75716a" font-family="system-ui,-apple-system,'Segoe UI',Roboto,sans-serif" font-size="11" letter-spacing="0.3">anamnesis · calibration · offline & local</text>
</svg>
"##
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{Claim, Forecast, NumericForecast, Outcome, Resolution};
use chrono::{TimeZone, Utc};
fn now() -> chrono::DateTime<Utc> {
Utc.with_ymd_and_hms(2025, 1, 1, 12, 0, 0).unwrap()
}
fn td() -> NaiveDate {
NaiveDate::from_ymd_opt(2026, 1, 1).unwrap()
}
fn binary(id: &str, prob: f64, happened: bool, tags: &[&str]) -> Claim {
Claim {
id: id.into(),
statement: format!("claim {id}"),
created_at: now(),
horizon_days: None,
resolve_by: Some(NaiveDate::from_ymd_opt(2025, 6, 1).unwrap()),
tags: tags.iter().map(|s| s.to_string()).collect(),
kind: crate::model::ClaimKind::Binary,
stake: 1.0,
forecasts: vec![Forecast {
at: now(),
prob: Some(prob),
interval: None,
because: None,
}],
resolution: Some(Resolution {
at: now(),
outcome: Some(if happened {
Outcome::True
} else {
Outcome::False
}),
value: None,
note: None,
resolved_by: None,
}),
void: None,
check: None,
extra: Default::default(),
amendments: Vec::new(),
}
}
fn numeric(id: &str, low: f64, high: f64, level: f64, value: f64) -> Claim {
Claim {
id: id.into(),
statement: format!("num {id}"),
created_at: now(),
horizon_days: None,
resolve_by: None,
tags: vec![],
kind: crate::model::ClaimKind::Numeric,
stake: 1.0,
forecasts: vec![Forecast {
at: now(),
prob: None,
interval: Some(NumericForecast { low, high, level }),
because: None,
}],
resolution: Some(Resolution {
at: now(),
outcome: None,
value: Some(value),
note: None,
resolved_by: None,
}),
void: None,
check: None,
extra: Default::default(),
amendments: Vec::new(),
}
}
#[test]
fn empty_ledger_renders_guidance() {
let r = render(&Ledger::default(), None, 10, td());
assert!(r.contains("No resolved claims yet"));
let j = render_json(&Ledger::default(), None, 10, td());
let v: serde_json::Value = serde_json::from_str(&j).unwrap();
assert_eq!(v["resolved"], 0);
assert!(v["brier"].is_null());
}
#[test]
fn json_has_no_nan_and_parses() {
let ledger = Ledger {
claims: vec![
binary("a", 0.9, true, &["tech"]),
binary("b", 0.9, false, &["tech"]),
binary("c", 0.2, false, &["world"]),
binary("d", 0.8, true, &["world"]),
],
..Default::default()
};
let j = render_json(&ledger, None, 10, td());
let v: serde_json::Value = serde_json::from_str(&j).unwrap();
assert!(!j.contains("NaN") && !j.contains("Infinity"));
assert_eq!(v["resolved"], 4);
assert!(v["brier"].as_f64().unwrap() > 0.0);
assert!(v["auc"].as_f64().is_some());
let cal = v["calibration"].as_array().unwrap();
assert!(cal.iter().any(|b| b["observed"].is_null()));
}
#[test]
fn text_and_json_agree_on_brier() {
let ledger = Ledger {
claims: vec![binary("a", 0.7, true, &[]), binary("b", 0.3, false, &[])],
..Default::default()
};
let data = ReportData::compute(&ledger, None, 10, td());
let v: serde_json::Value =
serde_json::from_str(&render_json(&ledger, None, 10, td())).unwrap();
assert_eq!(v["brier"].as_f64().unwrap(), data.brier.unwrap());
}
#[test]
fn numeric_section_appears_and_scores() {
let ledger = Ledger {
claims: vec![
numeric("n1", 10.0, 20.0, 0.8, 15.0), numeric("n2", 10.0, 20.0, 0.8, 40.0), ],
..Default::default()
};
let r = render(&ledger, None, 10, td());
assert!(r.contains("Numeric forecasts"));
assert!(r.contains("TOO NARROW"));
let v: serde_json::Value =
serde_json::from_str(&render_json(&ledger, None, 10, td())).unwrap();
assert_eq!(v["numeric"]["count"], 2);
assert_eq!(v["numeric"]["empirical_coverage"].as_f64().unwrap(), 0.5);
}
#[test]
fn tag_filter_limits_and_titles() {
let ledger = Ledger {
claims: vec![
binary("a", 0.9, true, &["tech"]),
binary("b", 0.2, false, &["world"]),
],
..Default::default()
};
let r = render(&ledger, Some("tech"), 10, td());
assert!(r.contains("[tag: tech]"));
assert!(!r.contains("By domain")); }
#[test]
fn plain_and_html_views_explain_and_render() {
let ledger = Ledger {
claims: (0..40)
.map(|i| binary(&format!("c{i}"), 0.9, i % 3 == 0, &[]))
.collect(),
..Default::default()
};
let p = render_plain(&ledger, None, 10, td());
assert!(p.contains("plain English"));
assert!(p.contains("golf score")); assert!(p.contains("technical name:")); assert!(p.contains("what should you do")); assert!(["DIALED IN", "CLOSE", "DRIFTING", "WAY OFF", "WARMING UP"]
.iter()
.any(|m| p.contains(m)));
let h = render_html(&ledger, None, 10, td());
assert!(h.contains("<!DOCTYPE html"));
assert!(h.contains("class=\"card\""));
assert!(h.contains("class=\"verdict\""));
assert!(h.contains("golf score")); assert!(!h.contains("__ACCENT__")); assert!(h.contains("#c62828")); assert!(!h.contains(">Brier score</p>"));
let tiny = Ledger {
claims: vec![
binary("a", 1.0, true, &[]),
binary("b", 1.0, true, &[]),
binary("c", 1.0, true, &[]),
binary("d", 0.0, false, &[]),
binary("e", 0.0, false, &[]),
],
..Default::default()
};
let td5 = ReportData::compute(&tiny, None, 10, td());
assert_eq!(td5.verdict, Verdict::InsufficientData);
assert!(
td5.log_score.unwrap().is_finite(),
"log score must not be inf"
);
let tp = render_plain(&tiny, None, 10, td());
assert!(
tp.contains("Too few resolved calls") && tp.contains("WARMING UP"),
"must say so plainly:\n{tp}"
);
for banned in ["DIALED IN", "Well calibrated", "confidence is honest"] {
assert!(!tp.contains(banned), "{banned:?} at n=5:\n{tp}");
}
assert!(render_badge_svg(&tiny, None, 10, td()).contains("Not enough data"));
assert!(render_plain(&Ledger::default(), None, 10, td()).contains("Nothing to reflect"));
assert!(render_html(&Ledger::default(), None, 10, td()).contains("<!DOCTYPE html"));
let svg = render_badge_svg(&ledger, None, 10, td());
assert!(svg.contains("<svg") && svg.contains("</svg>"));
assert!(svg.contains("Overconfident")); assert!(svg.contains("#c62828")); assert!(!svg.contains("{{")); assert!(render_badge_svg(&Ledger::default(), None, 10, td()).contains("Not enough data"));
}
#[test]
fn a_new_ledger_lists_its_graded_calls_and_a_full_one_does_not() {
let few = Ledger {
claims: vec![
binary("aa1", 0.9, false, &[]),
binary("bb2", 0.6, true, &[]),
],
..Default::default()
};
let d = ReportData::compute(&few, None, 10, td());
assert_eq!(d.so_far.len(), 2);
let miss = d.so_far.iter().find(|g| g.id == "aa1").unwrap();
assert!(!miss.came_true && (miss.brier - 0.81).abs() < 1e-12);
let text = render(&few, None, 10, td());
assert!(
text.contains("Graded so far")
&& text.contains("[aa1]")
&& text.contains("costs the most"),
"{text}"
);
assert!(render_plain(&few, None, 10, td()).contains("Your graded calls so far"));
assert!(
!render_json(&few, None, 10, td()).contains("claim aa1"),
"a statement leaked"
);
let many = Ledger {
claims: (0..30)
.map(|i| binary(&format!("m{i}"), 0.7, i % 10 < 7, &[]))
.collect(),
..Default::default()
};
assert!(ReportData::compute(&many, None, 10, td()).so_far.is_empty());
}
#[test]
fn a_weak_quiet_test_is_not_shown_in_green() {
let claims = (0..40)
.map(|i| {
let (p, hit) = if i < 20 {
(0.6, i % 10 < 6)
} else {
(0.8, i % 10 < 8)
};
binary(&format!("w{i}"), p, hit, &[])
})
.collect();
let ledger = Ledger {
claims,
..Default::default()
};
let d = ReportData::compute(&ledger, None, 10, td());
assert_eq!(d.verdict, Verdict::NoEvidenceOfMiscalibration);
assert!(
d.sensitivity.unwrap() < DIALED_MIN_SENSITIVITY,
"{:?}",
d.sensitivity
);
let svg = render_badge_svg(&ledger, None, 10, td());
assert!(svg.contains("Nothing found yet"), "{svg}");
assert!(!svg.contains("#2e7d32"), "green on a weak test:\n{svg}");
assert!(!svg.contains("No miscalibration found"));
}
#[test]
fn mood_tracks_the_size_of_the_calibration_error() {
let tiny = Ledger {
claims: vec![
binary("a", 1.0, true, &[]),
binary("b", 1.0, true, &[]),
binary("c", 0.0, false, &[]),
binary("d", 0.0, false, &[]),
],
..Default::default()
};
assert_eq!(
mood(&ReportData::compute(&tiny, None, 10, td())).name,
"WARMING UP",
"a four-claim ledger must not earn the best face in the program"
);
let bad = Ledger {
claims: (0..40)
.map(|i| {
binary(
&format!("c{i}"),
if i % 2 == 0 { 0.95 } else { 0.05 },
i % 2 != 0,
&[],
)
})
.collect(),
..Default::default()
};
let d = ReportData::compute(&bad, None, 10, td());
assert_eq!(d.verdict, Verdict::CalibratedButUninformative);
assert_eq!(mood(&d).name, "UNINFORMATIVE");
assert_eq!(
mood(&d).art,
CAT_OFF,
"an inverted forecaster must not look calm"
);
assert_eq!(
mood(&ReportData::compute(&Ledger::default(), None, 10, td())).name,
"WARMING UP"
);
}
#[test]
fn cancelling_errors_are_never_called_well_calibrated() {
let mut claims: Vec<Claim> = Vec::new();
for i in 0..50 {
claims.push(binary(&format!("f{i}"), 0.9, i % 2 == 0, &[]));
}
for i in 0..50 {
claims.push(binary(&format!("s{i}"), 0.6, true, &[]));
}
let ledger = Ledger {
claims,
..Default::default()
};
let d = ReportData::compute(&ledger, None, 10, td());
assert!(d.confidence_gap.unwrap().abs() < 1e-9);
assert_eq!(d.verdict, Verdict::CalibratedButUninformative);
assert!(d.mcb.unwrap() > d.mcb_null_q95.unwrap());
assert_eq!(d.dsc.unwrap(), 0.0, "the forecasts order nothing");
for view in [
render(&ledger, None, 10, td()),
render_plain(&ledger, None, 10, td()),
render_html(&ledger, None, 10, td()),
render_badge_svg(&ledger, None, 10, td()),
render_json(&ledger, None, 10, td()),
] {
for banned in [
"DIALED IN",
"Well calibrated",
"well calibrated",
"well-calibrated",
"confidence is honest",
"Keep doing what you're doing",
] {
assert!(!view.contains(banned), "{banned:?} appeared in:\n{view}");
}
}
}
}