use chrono::NaiveDate;
use serde::Serialize;
use crate::model::Claim;
use crate::scoring::{Sample, Step};
#[derive(Clone, Debug, Default)]
pub struct Evidence {
pub samples: Vec<Sample>,
pub steps: Vec<Step>,
pub oldest_gap: Option<String>,
pub oldest_gap_without_deadline: bool,
pub voided_after_resolution: usize,
pub ungraded_due: usize,
}
pub const DEFAULT_HORIZON_DAYS: i64 = 7;
pub fn horizon_for(tags: &[String]) -> i64 {
tags.iter()
.find_map(|t| t.strip_prefix("kind:"))
.map(|kind| match kind {
"tests-pass" | "bug-hypothesis" | "measurement" => 1,
"estimate" | "approach" | "compat" | "refactor" => 3,
_ => horizon_days(),
})
.unwrap_or_else(horizon_days)
}
fn horizon_days() -> i64 {
std::env::var("ANAMNESIS_HORIZON_DAYS")
.ok()
.and_then(|v| v.parse::<i64>().ok())
.filter(|d| *d >= 0)
.unwrap_or(DEFAULT_HORIZON_DAYS)
}
fn due_key(c: &Claim) -> NaiveDate {
let written = c.created_at.date_naive();
c.resolve_by.map(|d| d.max(written)).unwrap_or_else(|| {
let days = c.horizon_days.unwrap_or_else(horizon_days);
c.created_at.date_naive() + chrono::Duration::days(days)
})
}
pub fn came_due(c: &Claim, today: NaiveDate) -> bool {
c.is_open() && !c.is_void() && due_key(c) < today
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
pub struct VoidAccount {
pub total: usize,
pub late: usize,
pub settled: usize,
#[serde(default)]
pub reworded: usize,
}
pub const VOID_WITHHOLD_RATE: f64 = 0.10;
pub const VOID_WITHHOLD_MIN: usize = 3;
impl VoidAccount {
pub fn void_rate(&self) -> Option<f64> {
(self.total > 0 && self.settled > 0).then(|| self.total as f64 / self.settled as f64)
}
pub fn edited(&self) -> (usize, &'static str) {
let verb = match (self.total, self.reworded) {
(_, 0) => "were voided",
(0, _) => "were reworded",
_ => "were voided or reworded",
};
(self.total + self.reworded, verb)
}
pub fn edit_rate(&self) -> Option<f64> {
let edited = self.total + self.reworded;
(edited > 0 && self.settled > 0).then(|| edited as f64 / self.settled as f64)
}
pub fn withholds_verdict(&self) -> bool {
self.total + self.reworded >= VOID_WITHHOLD_MIN
&& self.edit_rate().is_some_and(|r| r > VOID_WITHHOLD_RATE)
}
}
fn voided_late(c: &Claim) -> bool {
match &c.void {
None => false,
Some(v) => c.voided_after_resolution() || v.at.date_naive() > due_key(c),
}
}
pub fn void_account(claims: &[Claim], today: NaiveDate, tag: Option<&str>) -> VoidAccount {
let mut acct = VoidAccount::default();
for c in claims {
if let Some(t) = tag {
if !c.tags.iter().any(|x| x == t) {
continue;
}
}
if c.is_void() {
acct.total += 1;
}
if voided_late(c) {
acct.late += 1;
}
let settled = c.is_void() || c.resolution.is_some() || due_key(c) <= today;
if settled {
acct.settled += 1;
}
if settled && !c.is_void() && c.amendments.iter().any(|a| a.new_statement.is_some()) {
acct.reworded += 1;
}
}
acct
}
pub fn evidence_sequence(
claims: &[Claim],
today: NaiveDate,
include: impl Fn(&Claim) -> bool,
to_sample: impl Fn(&Claim) -> Option<Sample>,
) -> Evidence {
let include = |c: &Claim| include(c) && !c.voided_before_resolution();
let voided_after_resolution = claims
.iter()
.filter(|c| c.voided_after_resolution())
.count();
let mut due: Vec<&Claim> = claims
.iter()
.filter(|c| include(c) && due_key(c) <= today)
.collect();
due.sort_by(|a, b| {
due_key(a)
.cmp(&due_key(b))
.then(a.created_at.cmp(&b.created_at))
.then(a.id.cmp(&b.id))
});
let mut samples = Vec::with_capacity(due.len());
let mut steps = Vec::with_capacity(due.len());
let mut oldest_gap = None;
let mut oldest_gap_without_deadline = false;
let mut ungraded_due = 0;
for c in &due {
match to_sample(c) {
Some(s) => {
steps.push(Step::graded(s.prob, s.outcome));
samples.push(s);
}
None => {
if let Some(p) = c.first_prob() {
steps.push(Step::gap(p));
}
if oldest_gap.is_none() {
oldest_gap = Some(c.id.clone());
oldest_gap_without_deadline = c.resolve_by.is_none();
}
ungraded_due += 1;
}
}
}
Evidence {
samples,
steps,
oldest_gap,
oldest_gap_without_deadline,
voided_after_resolution,
ungraded_due,
}
}
pub fn pending_due(
claims: &[Claim],
today: NaiveDate,
tag: Option<&str>,
) -> Option<(usize, NaiveDate, NaiveDate)> {
let keys: Vec<NaiveDate> = claims
.iter()
.filter(|c| {
c.kind == crate::model::ClaimKind::Binary
&& tag.is_none_or(|t| c.tags.iter().any(|x| x == t))
&& !c.is_void()
&& c.evidence_sample().is_some()
})
.map(due_key)
.filter(|&d| d > today)
.collect();
Some((keys.len(), *keys.iter().min()?, *keys.iter().max()?))
}
fn binary_candidates<'a>(
claims: &'a [Claim],
today: NaiveDate,
tag: Option<&str>,
) -> Vec<&'a Claim> {
let mut due: Vec<&Claim> = claims
.iter()
.filter(|c| {
c.kind == crate::model::ClaimKind::Binary
&& tag.is_none_or(|t| c.tags.iter().any(|x| x == t))
&& !c.voided_before_resolution()
&& due_key(c) <= today
})
.collect();
due.sort_by(|a, b| {
due_key(a)
.cmp(&due_key(b))
.then(a.created_at.cmp(&b.created_at))
.then(a.id.cmp(&b.id))
});
due
}
pub fn binary_evidence_claims<'a>(
claims: &'a [Claim],
today: NaiveDate,
tag: Option<&str>,
) -> Vec<&'a Claim> {
binary_candidates(claims, today, tag)
.into_iter()
.filter(|c| c.evidence_sample().is_some())
.collect()
}
pub fn binary_evidence(claims: &[Claim], today: NaiveDate, tag: Option<&str>) -> Evidence {
evidence_sequence(
claims,
today,
|c| {
c.kind == crate::model::ClaimKind::Binary
&& tag.is_none_or(|t| c.tags.iter().any(|x| x == t))
},
|c| c.evidence_sample(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{ClaimKind, Forecast, Outcome, Resolution};
use chrono::{Duration, TimeZone, Utc};
fn claim(id: &str, day: u32, prob: f64, outcome: Option<Outcome>, resolved_day: u32) -> Claim {
let created =
Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap() + Duration::days(day as i64);
Claim {
id: id.into(),
statement: id.into(),
created_at: created,
horizon_days: None,
resolve_by: Some(
NaiveDate::from_ymd_opt(2025, 2, 1).unwrap() + Duration::days(day as i64),
),
tags: vec![],
kind: ClaimKind::Binary,
stake: 1.0,
forecasts: vec![Forecast {
at: created,
prob: Some(prob),
interval: None,
because: None,
}],
resolution: outcome.map(|o| Resolution {
at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap()
+ Duration::days(resolved_day as i64),
outcome: Some(o),
value: None,
note: None,
resolved_by: None,
}),
void: None,
check: None,
extra: Default::default(),
amendments: Vec::new(),
}
}
#[test]
fn order_ignores_when_the_answer_arrived() {
let claims = vec![
claim("a", 0, 0.9, Some(Outcome::True), 40),
claim("b", 1, 0.1, Some(Outcome::False), 5),
];
let today = NaiveDate::from_ymd_opt(2025, 6, 1).unwrap();
let ev = binary_evidence(&claims, today, None);
assert_eq!(ev.samples.len(), 2);
assert_eq!(
ev.samples[0].prob, 0.9,
"ordered by resolve_by, not by when it resolved"
);
assert_eq!(ev.samples[1].prob, 0.1);
}
#[test]
fn a_claim_not_yet_due_does_not_enter_the_sequence() {
let claims = vec![claim("a", 0, 0.9, Some(Outcome::True), 2)];
let before = NaiveDate::from_ymd_opt(2025, 1, 15).unwrap();
assert!(binary_evidence(&claims, before, None).samples.is_empty());
let after = NaiveDate::from_ymd_opt(2025, 3, 1).unwrap();
assert_eq!(binary_evidence(&claims, after, None).samples.len(), 1);
}
#[test]
fn an_overdue_unresolved_claim_is_priced_in_not_skipped() {
let claims = vec![
claim("a", 0, 0.9, Some(Outcome::True), 40),
claim("b", 1, 0.8, None, 0),
claim("c", 2, 0.7, Some(Outcome::True), 45),
];
let today = NaiveDate::from_ymd_opt(2025, 6, 1).unwrap();
let ev = binary_evidence(&claims, today, None);
assert_eq!(ev.samples.len(), 2, "both graded claims count now");
assert_eq!(ev.steps.len(), 3, "and the gap is in the sequence");
assert_eq!(ev.steps[1].outcome, None, "as a gap, in its fixed position");
assert_eq!(ev.oldest_gap.as_deref(), Some("b"));
assert_eq!(ev.ungraded_due, 1);
let mut graded = claims.clone();
graded[1] = claim("b", 1, 0.8, Some(Outcome::True), 41);
let with_gap = crate::scoring::calibration_log_eprocess_seq(&ev.steps).unwrap();
let full = crate::scoring::calibration_log_eprocess_seq(
&binary_evidence(&graded, today, None).steps,
)
.unwrap();
assert!(with_gap < full, "an ungraded claim must cost, not be free");
}
#[test]
fn claims_without_a_deadline_still_count_from_their_creation_date() {
let mut c = claim("a", 0, 0.9, Some(Outcome::True), 40);
c.resolve_by = None;
let ev = binary_evidence(&[c], NaiveDate::from_ymd_opt(2025, 6, 1).unwrap(), None);
assert_eq!(ev.samples.len(), 1);
assert!(ev.oldest_gap.is_none());
}
#[test]
fn an_ungraded_deadline_free_claim_is_named_and_says_how_to_clear_it() {
let mut open = claim("b", 1, 0.8, None, 0);
open.resolve_by = None;
let claims = vec![
claim("a", 0, 0.9, Some(Outcome::True), 40),
open,
claim("c", 2, 0.7, Some(Outcome::True), 45),
];
let ev = binary_evidence(&claims, NaiveDate::from_ymd_opt(2025, 6, 1).unwrap(), None);
assert_eq!(ev.samples.len(), 2, "the later graded claim still counts");
assert_eq!(ev.oldest_gap.as_deref(), Some("b"));
assert!(ev.oldest_gap_without_deadline);
assert_eq!(ev.ungraded_due, 1);
}
#[test]
fn a_fresh_deadline_free_claim_does_not_block_anything_yet() {
let mut fresh = claim("z", 0, 0.5, None, 0);
fresh.resolve_by = None;
fresh.created_at = Utc.with_ymd_and_hms(2025, 5, 28, 0, 0, 0).unwrap();
let claims = vec![
fresh,
claim("a", 0, 0.9, Some(Outcome::True), 40),
claim("b", 1, 0.7, Some(Outcome::False), 45),
];
let ev = binary_evidence(&claims, NaiveDate::from_ymd_opt(2025, 6, 1).unwrap(), None);
assert_eq!(ev.samples.len(), 2, "the graded claims still count");
assert!(
ev.oldest_gap.is_none(),
"a four-day-old claim is not yet overdue"
);
let later = binary_evidence(&claims, NaiveDate::from_ymd_opt(2025, 8, 1).unwrap(), None);
assert_eq!(later.oldest_gap.as_deref(), Some("z"));
assert_eq!(later.ungraded_due, 1);
}
#[test]
fn voiding_a_resolved_claim_does_not_remove_it_from_the_evidence() {
let mut resolved_then_voided = claim("a", 0, 0.9, Some(Outcome::False), 40);
resolved_then_voided.void = Some(crate::model::Void {
at: Utc.with_ymd_and_hms(2025, 5, 1, 0, 0, 0).unwrap(), reason: "on reflection I did not like this one".into(),
});
let mut never_resolved = claim("b", 1, 0.9, None, 0);
never_resolved.void = Some(crate::model::Void {
at: Utc.with_ymd_and_hms(2025, 5, 1, 0, 0, 0).unwrap(),
reason: "genuinely ambiguous, and never answered".into(),
});
assert!(resolved_then_voided.voided_after_resolution());
assert!(!resolved_then_voided.voided_before_resolution());
assert!(never_resolved.voided_before_resolution());
let claims = vec![resolved_then_voided, never_resolved];
let ev = binary_evidence(&claims, NaiveDate::from_ymd_opt(2025, 9, 1).unwrap(), None);
assert_eq!(
ev.samples.len(),
1,
"the seen outcome stays in the sequence"
);
assert_eq!(ev.voided_after_resolution, 1, "and is counted out loud");
assert!(
ev.oldest_gap.is_none(),
"the unresolved void leaves no gap to price — it is gone, not pending"
);
}
#[test]
fn a_long_horizon_open_claim_does_not_block_earlier_ones() {
let mut far = claim("a", 0, 0.5, None, 0);
far.resolve_by = Some(NaiveDate::from_ymd_opt(2030, 1, 1).unwrap());
let claims = vec![
far,
claim("b", 1, 0.9, Some(Outcome::True), 40),
claim("c", 2, 0.7, Some(Outcome::False), 45),
];
let ev = binary_evidence(&claims, NaiveDate::from_ymd_opt(2025, 6, 1).unwrap(), None);
assert_eq!(ev.samples.len(), 2);
assert!(ev.oldest_gap.is_none(), "not due yet, so not a gap yet");
}
#[test]
fn the_horizon_is_per_kind_and_stored_on_the_claim() {
assert_eq!(horizon_for(&["kind:tests-pass".into()]), 1);
assert_eq!(horizon_for(&["kind:approach".into()]), 3);
assert_eq!(horizon_for(&["who:claude".into()]), DEFAULT_HORIZON_DAYS);
assert_eq!(horizon_for(&[]), DEFAULT_HORIZON_DAYS);
let mut fast = claim("f", 0, 0.9, None, 0);
fast.resolve_by = None;
fast.horizon_days = Some(1);
let mut slow = claim("s", 0, 0.9, None, 0);
slow.resolve_by = None;
slow.horizon_days = Some(365);
let today = NaiveDate::from_ymd_opt(2025, 1, 3).unwrap();
let ev = binary_evidence(&[fast, slow], today, None);
assert_eq!(ev.ungraded_due, 1, "only the short-horizon claim is due");
assert_eq!(ev.oldest_gap.as_deref(), Some("f"));
}
#[test]
fn a_ledger_written_before_horizons_still_loads_and_orders() {
let mut old = claim("legacy", 0, 0.9, Some(Outcome::True), 1);
old.resolve_by = None;
old.horizon_days = None;
let before = binary_evidence(
&[old.clone()],
NaiveDate::from_ymd_opt(2025, 1, 2).unwrap(),
None,
);
assert!(before.samples.is_empty(), "not due one day in");
let after = binary_evidence(&[old], NaiveDate::from_ymd_opt(2025, 3, 1).unwrap(), None);
assert_eq!(
after.samples.len(),
1,
"due once the default horizon passes"
);
}
#[test]
fn a_backlog_shrinks_the_evidence_it_can_never_inflate_it() {
let today = NaiveDate::from_ymd_opt(2026, 6, 1).unwrap();
let mut all_graded = Vec::new();
for i in 0..40u32 {
let o = if i % 3 == 0 {
Outcome::False
} else {
Outcome::True
};
all_graded.push(claim(&format!("c{i:02}"), i, 0.8, Some(o), 40 + i));
}
let full = crate::scoring::calibration_log_eprocess_seq(
&binary_evidence(&all_graded, today, None).steps,
)
.unwrap();
let mut with_gaps = all_graded.clone();
for (i, c) in with_gaps.iter_mut().enumerate() {
if i % 4 == 3 {
c.resolution = None;
}
}
let ev = binary_evidence(&with_gaps, today, None);
let gapped = crate::scoring::calibration_log_eprocess_seq(&ev.steps).unwrap();
assert_eq!(ev.ungraded_due, 10);
assert!(
gapped <= full + 1e-12,
"gaps must not raise the e-value: {gapped} vs {full}"
);
}
fn void_at(mut c: Claim, y: i32, m: u32, d: u32) -> Claim {
c.void = Some(crate::model::Void {
at: Utc.with_ymd_and_hms(y, m, d, 0, 0, 0).unwrap(),
reason: "test".into(),
});
c
}
#[test]
fn a_void_is_late_when_it_followed_the_due_date_or_the_resolution() {
let today = NaiveDate::from_ymd_opt(2025, 9, 1).unwrap();
let a = void_at(claim("a", 0, 0.7, None, 0), 2025, 1, 20);
let b = void_at(claim("b", 1, 0.7, None, 0), 2025, 3, 1);
let c = void_at(claim("c", 2, 0.7, Some(Outcome::False), 10), 2025, 4, 1);
let d = claim("d", 3, 0.7, Some(Outcome::True), 20);
let e = claim("e", 300, 0.7, None, 0);
let acct = void_account(&[a, b, c, d, e], today, None);
assert_eq!(acct.total, 3);
assert_eq!(
acct.late, 2,
"b came due, c had resolved; a was before both"
);
assert_eq!(
acct.settled, 4,
"a, b, c and d are settled; e is open and not due"
);
assert_eq!(acct.void_rate(), Some(0.75));
assert!(acct.withholds_verdict());
}
#[test]
fn the_withholding_line_is_strictly_more_than_one_in_ten() {
let acct = |total, settled| VoidAccount {
total,
late: 0,
settled,
reworded: 0,
};
assert!(!acct(0, 30).withholds_verdict());
assert!(!acct(2, 30).withholds_verdict());
assert!(
!acct(3, 30).withholds_verdict(),
"exactly 10% is not more than 10%"
);
assert!(acct(4, 30).withholds_verdict());
assert!(
!acct(2, 5).withholds_verdict(),
"two voids are never a pattern, whatever the share"
);
assert!(acct(3, 5).withholds_verdict());
assert!(!VoidAccount::default().withholds_verdict());
let mixed = VoidAccount {
total: 2,
late: 0,
settled: 30,
reworded: 2,
};
assert!(
mixed.withholds_verdict(),
"2 voids + 2 rewords of 30 is 13%"
);
}
#[test]
fn voids_are_counted_only_within_the_tag_in_scope() {
let today = NaiveDate::from_ymd_opt(2025, 9, 1).unwrap();
let mut mine = void_at(claim("m", 1, 0.7, None, 0), 2025, 3, 1);
mine.tags = vec!["who:claude".into()];
let theirs = void_at(claim("t", 2, 0.7, None, 0), 2025, 3, 1);
let acct = void_account(&[mine, theirs], today, Some("who:claude"));
assert_eq!((acct.total, acct.late, acct.settled), (1, 1, 1));
}
#[test]
fn voiding_the_misses_before_they_come_due_withholds_the_verdict() {
let today = NaiveDate::from_ymd_opt(2025, 1, 15).unwrap();
let mut claims = Vec::new();
for i in 0..20 {
claims.push(claim(&format!("w{i}"), 300, 0.9, Some(Outcome::True), 1));
}
for i in 0..20 {
claims.push(void_at(
claim(&format!("l{i}"), 300, 0.9, None, 0),
2025,
1,
12,
));
}
let acct = void_account(&claims, today, None);
assert_eq!((acct.total, acct.late, acct.settled), (20, 0, 40));
assert!(
acct.withholds_verdict(),
"none was late, and it is still half the record"
);
}
}