Skip to main content

anamnesis/
model.rs

1//! The domain model: claims, the forecasts layered onto them over time, and
2//! their eventual resolution. A [`Claim`] is deliberately a *palimpsest* — each
3//! revision is appended, never overwritten, so the history of your own
4//! mind-changing survives intact.
5//!
6//! A claim is either **binary** (a yes/no proposition scored with a probability)
7//! or **numeric** (a quantity scored with a credible interval). Both live in the
8//! same struct; the [`ClaimKind`] tag and the `Option` fields keep older,
9//! binary-only ledgers loading unchanged (see the serde defaults below).
10
11use chrono::{DateTime, NaiveDate, Utc};
12use serde::{Deserialize, Serialize};
13use std::collections::hash_map::DefaultHasher;
14use std::hash::{Hash, Hasher};
15
16use crate::scoring::{NumericSample, Sample};
17
18/// Whether a claim is scored as a yes/no proposition or as a quantity.
19#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
20#[serde(rename_all = "lowercase")]
21pub enum ClaimKind {
22    /// A proposition resolved true/false, forecast with a probability.
23    #[default]
24    Binary,
25    /// A quantity resolved to a number, forecast with a credible interval.
26    Numeric,
27}
28
29/// What actually happened for a *binary* claim.
30///
31/// Written as `"true"` or `"false"`. Read more loosely: `yes`/`no`, `y`/`n`, any case, a JSON
32/// boolean, or `1`/`0`. The documented format's own example said `"no"` and the reader
33/// refused it, in the one file meant to be readable without this program.
34#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
35#[serde(rename_all = "lowercase")]
36pub enum Outcome {
37    True,
38    False,
39}
40
41impl<'de> Deserialize<'de> for Outcome {
42    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
43        struct Words;
44        impl serde::de::Visitor<'_> for Words {
45            type Value = Outcome;
46            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
47                f.write_str("an outcome: \"true\" or \"false\" (yes/no and booleans are read too)")
48            }
49            fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<Outcome, E> {
50                Ok(if v { Outcome::True } else { Outcome::False })
51            }
52            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Outcome, E> {
53                match v {
54                    1 => Ok(Outcome::True),
55                    0 => Ok(Outcome::False),
56                    _ => Err(E::custom(format!("an outcome of {v}: use true or false"))),
57                }
58            }
59            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Outcome, E> {
60                match v.trim().to_ascii_lowercase().as_str() {
61                    "true" | "yes" | "y" | "1" => Ok(Outcome::True),
62                    "false" | "no" | "n" | "0" => Ok(Outcome::False),
63                    _ => Err(E::custom(format!("an outcome of {v:?}: use true or false"))),
64                }
65            }
66        }
67        d.deserialize_any(Words)
68    }
69}
70
71impl Outcome {
72    pub fn happened(self) -> bool {
73        matches!(self, Outcome::True)
74    }
75}
76
77/// A central credible interval `[low, high]` stated at confidence `level`
78/// (e.g. `0.80` for an 80% interval). The stored form of a numeric forecast.
79#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
80pub struct NumericForecast {
81    pub low: f64,
82    pub high: f64,
83    pub level: f64,
84}
85
86/// A single dated forecast, with the reasoning that produced it. Exactly one of
87/// `prob` (binary) or `interval` (numeric) is set.
88#[derive(Serialize, Deserialize, Clone, Debug)]
89pub struct Forecast {
90    pub at: DateTime<Utc>,
91    /// Probability the claim is true, in `[0, 1]` — for binary claims.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub prob: Option<f64>,
94    /// Credible interval — for numeric claims.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub interval: Option<NumericForecast>,
97    /// The reasoning — the part hindsight will try to erase.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub because: Option<String>,
100}
101
102/// The verdict of reality. Exactly one of `outcome` (binary) or `value`
103/// (numeric) is set.
104#[derive(Serialize, Deserialize, Clone, Debug)]
105pub struct Resolution {
106    pub at: DateTime<Utc>,
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub outcome: Option<Outcome>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub value: Option<f64>,
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub note: Option<String>,
113    /// Who graded this claim: `self` (the forecaster said so), `auto` (a machine
114    /// observed it — a test run's exit status, say), or `human`.
115    ///
116    /// "Why would I trust a self-graded ledger?" is the first fair objection to
117    /// this whole idea, and the honest answer is to record which claims did not
118    /// depend on the forecaster's word. Absent in older ledgers, and not written
119    /// when it is the default, so existing files stay byte-identical.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub resolved_by: Option<ResolvedBy>,
122}
123
124/// Provenance of a resolution. See [`Resolution::resolved_by`].
125#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
126#[serde(rename_all = "lowercase")]
127pub enum ResolvedBy {
128    /// The forecaster graded their own prediction.
129    #[default]
130    #[serde(rename = "self")]
131    Zelf,
132    /// Graded from an observed fact, with no human in the loop.
133    Auto,
134    /// Graded by someone other than the forecaster.
135    Human,
136}
137
138/// One belief tracked over its lifetime.
139#[derive(Serialize, Deserialize, Clone, Debug)]
140pub struct Claim {
141    pub id: String,
142    pub statement: String,
143    pub created_at: DateTime<Utc>,
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub resolve_by: Option<NaiveDate>,
146    /// How many days after creation this claim becomes answerable, when it has no
147    /// `resolve_by` date. **Stored at creation** rather than computed at read time
148    /// from a global, so the evidence order is auditable from the file itself and
149    /// cannot silently shift when a default changes. Absent in older ledgers ⇒ the
150    /// current global default, and not serialised when absent.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub horizon_days: Option<i64>,
153    #[serde(default)]
154    pub tags: Vec<String>,
155    /// Binary or numeric. Absent in older ledgers ⇒ defaults to binary.
156    #[serde(default)]
157    pub kind: ClaimKind,
158    /// How much this call *matters* (≥ 0; default 1) — weights the Brier toward
159    /// your consequential predictions. Absent in older ledgers ⇒ 1, and a
160    /// default stake is not serialised, so existing ledgers stay byte-identical.
161    #[serde(default = "default_stake", skip_serializing_if = "is_default_stake")]
162    pub stake: f64,
163    /// The exact command that settles this claim, pinned when it was logged, before the
164    /// outcome could be known: `cargo test`, `make ci`.
165    ///
166    /// `ana run` runs the command it is *given* and grades the claim only if that
167    /// matches this text. It never executes this text: a ledger holds words anyone can
168    /// have written. Pinning is what stops an agent that logged "the tests pass" from
169    /// settling it with one narrow test it chose afterwards. Absent unless set, and not
170    /// serialised when absent, so existing ledgers stay byte-identical.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub check: Option<String>,
173    /// Fields written by a newer version, kept so a save does not erase them.
174    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
175    pub extra: Extra,
176    /// Every forecast you ever made, oldest first. The last is your current
177    /// belief; the first is where you started.
178    pub forecasts: Vec<Forecast>,
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub resolution: Option<Resolution>,
181    /// Annulled: the question turned out to be ambiguous, or to be about
182    /// something that never became knowable.
183    ///
184    /// A voided claim keeps its place in the history — nothing is ever deleted —
185    /// but it is excluded from every score, exactly as a forecasting platform
186    /// annuls a question rather than grading it. The alternative, hand-editing
187    /// the JSON, is worse: it removes the evidence that the question was ever
188    /// asked. Absent in older ledgers, and not serialised when absent.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub void: Option<Void>,
191    /// Corrections to the wording or tags, oldest first. Probabilities and
192    /// timestamps are never amendable — that immutability is the entire point of
193    /// the instrument — so only the parts that carry no forecast can change, and
194    /// even those leave a record of what they were.
195    #[serde(default, skip_serializing_if = "Vec::is_empty")]
196    pub amendments: Vec<Amendment>,
197}
198
199/// Why a claim was annulled, and when.
200#[derive(Serialize, Deserialize, Clone, Debug)]
201pub struct Void {
202    pub at: DateTime<Utc>,
203    pub reason: String,
204}
205
206/// One correction to a claim's wording or tags.
207#[derive(Serialize, Deserialize, Clone, Debug)]
208pub struct Amendment {
209    pub at: DateTime<Utc>,
210    #[serde(default, skip_serializing_if = "Option::is_none")]
211    pub old_statement: Option<String>,
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub new_statement: Option<String>,
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub old_tags: Option<Vec<String>>,
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub new_tags: Option<Vec<String>>,
218}
219
220fn default_stake() -> f64 {
221    1.0
222}
223
224fn is_default_stake(s: &f64) -> bool {
225    (*s - 1.0).abs() < f64::EPSILON
226}
227
228/// Weave the elicitation trail into the stored reasoning: the outside-view
229/// *reference class*, the two *dialectical* estimates that produced the forecast,
230/// and the free-text rationale — joined into one `because`. Empty pieces drop out;
231/// returns `None` only when there is nothing at all to record. This keeps the CLI
232/// and the MCP server recording provenance identically.
233pub fn compose_reasoning(
234    because: Option<&str>,
235    reference_class: Option<&str>,
236    estimates: Option<(f64, f64)>,
237) -> Option<String> {
238    let mut parts: Vec<String> = Vec::new();
239    if let Some(rc) = reference_class.map(str::trim).filter(|s| !s.is_empty()) {
240        parts.push(format!("outside view: {rc}"));
241    }
242    if let Some((p1, p2)) = estimates {
243        parts.push(format!(
244            "dialectical {p1:.2} & {p2:.2} → {:.2}",
245            crate::scoring::dialectical_mean(p1, p2)
246        ));
247    }
248    if let Some(b) = because.map(str::trim).filter(|s| !s.is_empty()) {
249        parts.push(b.to_string());
250    }
251    (!parts.is_empty()).then(|| parts.join(" · "))
252}
253
254impl Claim {
255    pub fn current(&self) -> Option<&Forecast> {
256        self.forecasts.last()
257    }
258
259    pub fn current_prob(&self) -> Option<f64> {
260        self.forecasts.last().and_then(|f| f.prob)
261    }
262
263    pub fn first_prob(&self) -> Option<f64> {
264        self.forecasts.first().and_then(|f| f.prob)
265    }
266
267    pub fn current_interval(&self) -> Option<NumericForecast> {
268        self.forecasts.last().and_then(|f| f.interval)
269    }
270
271    pub fn is_resolved(&self) -> bool {
272        self.resolution.is_some()
273    }
274
275    /// Annulled, and therefore excluded from every score.
276    pub fn is_void(&self) -> bool {
277        self.void.is_some()
278    }
279
280    /// Voided before the answer was known.
281    ///
282    /// This is the honest case, and the only one the sequential evidence test
283    /// honours: a claim with no outcome carries no evidence, so removing it
284    /// cannot move the e-value in any direction.
285    pub fn voided_before_resolution(&self) -> bool {
286        match (&self.void, &self.resolution) {
287            (Some(v), Some(r)) => v.at <= r.at,
288            (Some(_), None) => true,
289            _ => false,
290        }
291    }
292
293    /// Voided *after* it had already resolved — an outcome deleted from the
294    /// record after being seen.
295    ///
296    /// Sometimes legitimate (the question really was ambiguous, and you only
297    /// noticed once it resolved), but it retroactively edits a sequence whose
298    /// whole guarantee rests on being fixed in advance, and the direction of
299    /// abuse is self-flattery: you void the ones that went badly, and the e-value
300    /// falls. Kept in the evidence sequence, and counted out loud.
301    pub fn voided_after_resolution(&self) -> bool {
302        match (&self.void, &self.resolution) {
303            (Some(v), Some(r)) => v.at > r.at,
304            _ => false,
305        }
306    }
307
308    pub fn is_open(&self) -> bool {
309        self.resolution.is_none()
310    }
311
312    /// Whether `argv` is the command this claim is pinned to: the pinned line, split into
313    /// words as a shell would, equals the words given. This is a guard on honesty, not a
314    /// security boundary: nothing is executed on the strength of it.
315    pub fn check_matches(&self, argv: &[String]) -> bool {
316        match &self.check {
317            Some(check) => crate::check::split_command(check).is_ok_and(|words| words == argv),
318            None => false,
319        }
320    }
321
322    pub fn is_due(&self, today: NaiveDate) -> bool {
323        self.is_open() && self.resolve_by.map(|d| d <= today).unwrap_or(false)
324    }
325
326    pub fn outcome(&self) -> Option<Outcome> {
327        self.resolution.as_ref().and_then(|r| r.outcome)
328    }
329
330    pub fn value(&self) -> Option<f64> {
331        self.resolution.as_ref().and_then(|r| r.value)
332    }
333
334    /// The scoreable binary sample: current probability paired with the resolved
335    /// outcome. `None` unless this is a resolved binary claim.
336    pub fn sample(&self) -> Option<Sample> {
337        if self.kind != ClaimKind::Binary || self.is_void() {
338            return None;
339        }
340        match (self.first_prob(), self.outcome()) {
341            (Some(p), Some(o)) => Some(Sample::new(p, o.happened())),
342            _ => None,
343        }
344    }
345
346    /// The sample as the **sequential evidence test** sees it.
347    ///
348    /// Differs from [`Claim::sample`] in exactly one way: a claim voided *after*
349    /// it resolved still counts here. Void annuls a question, and for every score
350    /// in the report that is the right thing — but the evidence sequence's whole
351    /// guarantee rests on being fixed before the outcomes are known, and dropping
352    /// an outcome you have already seen edits it retroactively. So the scores
353    /// forget it and the evidence test does not, and the report says how often
354    /// that has happened.
355    pub fn evidence_sample(&self) -> Option<Sample> {
356        if self.kind != ClaimKind::Binary || self.voided_before_resolution() {
357            return None;
358        }
359        match (self.first_prob(), self.outcome()) {
360            (Some(p), Some(o)) => Some(Sample::new(p, o.happened())),
361            _ => None,
362        }
363    }
364
365    /// The same sample scored on the **final** forecast instead of the first.
366    ///
367    /// Shown, never graded. Scoring the final forecast is what let ten claims
368    /// logged at 0.5, updated to 0.99 and then resolved YES earn a Brier score
369    /// of 0.000 and the compliment "your updates moved you TOWARD the truth" —
370    /// the exact self-deception this tool exists to prevent. The first forecast
371    /// is the one made before the answer was known, so it is the one that counts.
372    pub fn sample_final(&self) -> Option<Sample> {
373        if self.kind != ClaimKind::Binary || self.is_void() {
374            return None;
375        }
376        match (self.current_prob(), self.outcome()) {
377            (Some(p), Some(o)) => Some(Sample::new(p, o.happened())),
378            _ => None,
379        }
380    }
381
382    /// Whether any forecast after the first landed too close to the answer to be
383    /// an honest update: after the resolve-by date, within 24 hours of the
384    /// resolution, or in the last 10% of the claim's window.
385    ///
386    /// This is a neutral flag, not an accusation — a genuine late update is
387    /// perfectly legitimate. It exists so the report can say which forecasts are
388    /// not being graded, instead of silently rewarding them.
389    pub fn has_late_update(&self) -> bool {
390        if self.forecasts.len() < 2 {
391            return false;
392        }
393        let Some(res) = self.resolution.as_ref() else {
394            return false;
395        };
396        let deadline = self
397            .resolve_by
398            .and_then(|d| d.and_hms_opt(23, 59, 59))
399            .map(|dt| dt.and_utc());
400        let window = (res.at - self.created_at).num_seconds().max(0) as f64;
401        self.forecasts.iter().skip(1).any(|f| {
402            if deadline.is_some_and(|d| f.at > d) {
403                return true;
404            }
405            if (res.at - f.at).num_seconds() <= 86_400 {
406                return true;
407            }
408            window > 0.0 && (f.at - self.created_at).num_seconds() as f64 > 0.9 * window
409        })
410    }
411
412    /// Brier weighted by **how long each forecast stood**, the way Metaculus
413    /// time-averages a question.
414    ///
415    /// The window runs from `created_at` to the earlier of the resolution and the
416    /// end of the resolve-by day, so a revision made after the deadline carries
417    /// no weight at all. Secondary, never the headline: someone who learns the
418    /// answer early can still farm it by updating the moment they know.
419    pub fn brier_time_averaged(&self) -> Option<f64> {
420        if self.kind != ClaimKind::Binary || self.is_void() {
421            return None;
422        }
423        let y = if self.outcome()?.happened() { 1.0 } else { 0.0 };
424        let first = self.first_prob()?;
425        let start = self.created_at;
426        let mut end = self.resolution.as_ref()?.at;
427        if let Some(d) = self.resolve_by {
428            end = end.min(d.and_hms_opt(23, 59, 59)?.and_utc());
429        }
430        let total = (end - start).num_seconds();
431        if total < 60 {
432            // Degenerate or inverted window: nothing to weight by.
433            return Some((first - y).powi(2));
434        }
435        let mut acc = 0.0;
436        for (k, f) in self.forecasts.iter().enumerate() {
437            let p = f.prob?;
438            let from = if k == 0 {
439                start
440            } else {
441                f.at.clamp(start, end)
442            };
443            let to = self
444                .forecasts
445                .get(k + 1)
446                .map_or(end, |next| next.at)
447                .clamp(from, end);
448            acc += (p - y).powi(2) * (to - from).num_seconds() as f64;
449        }
450        Some(acc / total as f64)
451    }
452
453    /// The scoreable numeric sample: current interval paired with the resolved
454    /// value. `None` unless this is a resolved numeric claim.
455    pub fn numeric_sample(&self) -> Option<NumericSample> {
456        if self.kind != ClaimKind::Numeric || self.is_void() {
457            return None;
458        }
459        let iv = self.current_interval()?;
460        let value = self.value()?;
461        Some(NumericSample {
462            low: iv.low,
463            high: iv.high,
464            level: iv.level,
465            value,
466        })
467    }
468
469    pub fn was_revised(&self) -> bool {
470        self.forecasts.len() > 1
471    }
472}
473
474/// `s` with every run of whitespace collapsed to one space and the ends trimmed.
475pub fn collapse_spaces(s: &str) -> String {
476    s.split_whitespace().collect::<Vec<_>>().join(" ")
477}
478
479/// Fields a newer version wrote that this one does not know.
480///
481/// Kept on the claim and on the ledger so that loading and saving does not erase
482/// them. Without this, an older `ana` earlier on `PATH` silently dropped every field
483/// it did not recognise on the next `add`: a ledger written with `check` pins came
484/// back with none. Only the claim and the ledger keep unknown fields; one nested
485/// inside a forecast or a resolution is still dropped.
486pub type Extra = serde_json::Map<String, serde_json::Value>;
487
488/// The whole ledger.
489#[derive(Serialize, Deserialize, Clone, Debug, Default)]
490pub struct Ledger {
491    #[serde(default)]
492    pub claims: Vec<Claim>,
493    /// Anything else at the top level of the file, kept as it was read.
494    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
495    pub extra: Extra,
496}
497
498impl Ledger {
499    /// Resolve a (possibly abbreviated) id to a single claim index.
500    pub fn index_of(&self, id_prefix: &str) -> Result<usize, String> {
501        if let Some(i) = self.claims.iter().position(|c| c.id == id_prefix) {
502            return Ok(i);
503        }
504        let hits: Vec<usize> = self
505            .claims
506            .iter()
507            .enumerate()
508            .filter(|(_, c)| c.id.starts_with(id_prefix))
509            .map(|(i, _)| i)
510            .collect();
511        match hits.len() {
512            0 => Err(format!("no claim matches id '{id_prefix}'")),
513            1 => Ok(hits[0]),
514            n => Err(format!("ambiguous id '{id_prefix}' matches {n} claims")),
515        }
516    }
517
518    pub fn has_id(&self, id: &str) -> bool {
519        self.claims.iter().any(|c| c.id == id)
520    }
521
522    pub fn resolved_samples(&self) -> Vec<Sample> {
523        self.claims.iter().filter_map(|c| c.sample()).collect()
524    }
525}
526
527/// Derive a short, stable, dependency-free id from a statement and a salt.
528pub fn gen_id(statement: &str, salt: u64) -> String {
529    let mut h = DefaultHasher::new();
530    statement.hash(&mut h);
531    salt.hash(&mut h);
532    format!("{:06x}", h.finish() & 0xff_ffff)
533}
534
535/// Normalise tags: trim, lower-case, drop empties, de-duplicate (order kept).
536pub fn normalize_tags(tags: &[String]) -> Vec<String> {
537    let mut out: Vec<String> = Vec::new();
538    for t in tags {
539        let t = t.trim().to_lowercase();
540        if !t.is_empty() && !out.contains(&t) {
541            out.push(t);
542        }
543    }
544    out
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550    use chrono::TimeZone;
551
552    fn ts(y: i32, m: u32, d: u32) -> DateTime<Utc> {
553        Utc.with_ymd_and_hms(y, m, d, 12, 0, 0).unwrap()
554    }
555
556    fn binary_forecast(p: f64) -> Forecast {
557        Forecast {
558            at: ts(2025, 1, 1),
559            prob: Some(p),
560            interval: None,
561            because: None,
562        }
563    }
564
565    fn claim(id: &str, probs: &[f64], outcome: Option<Outcome>) -> Claim {
566        Claim {
567            id: id.to_string(),
568            statement: format!("claim {id}"),
569            created_at: ts(2025, 1, 1),
570            horizon_days: None,
571            resolve_by: None,
572            tags: vec![],
573            kind: ClaimKind::Binary,
574            stake: 1.0,
575            forecasts: probs.iter().map(|&p| binary_forecast(p)).collect(),
576            resolution: outcome.map(|o| Resolution {
577                at: ts(2025, 6, 1),
578                outcome: Some(o),
579                value: None,
580                note: None,
581                resolved_by: None,
582            }),
583            void: None,
584            check: None,
585            extra: Default::default(),
586            amendments: Vec::new(),
587        }
588    }
589
590    #[test]
591    fn sample_only_when_resolved_binary() {
592        assert!(claim("a", &[0.7], None).sample().is_none());
593        let s = claim("b", &[0.7], Some(Outcome::True)).sample().unwrap();
594        assert_eq!(s, Sample::new(0.7, true));
595    }
596
597    #[test]
598    fn numeric_sample_round_trips() {
599        let c = Claim {
600            id: "n".into(),
601            statement: "how many".into(),
602            created_at: ts(2025, 1, 1),
603            horizon_days: None,
604            resolve_by: None,
605            tags: vec![],
606            kind: ClaimKind::Numeric,
607            stake: 1.0,
608            forecasts: vec![Forecast {
609                at: ts(2025, 1, 1),
610                prob: None,
611                interval: Some(NumericForecast {
612                    low: 10.0,
613                    high: 20.0,
614                    level: 0.8,
615                }),
616                because: None,
617            }],
618            resolution: Some(Resolution {
619                at: ts(2025, 6, 1),
620                outcome: None,
621                value: Some(13.0),
622                note: None,
623                resolved_by: None,
624            }),
625            void: None,
626            check: None,
627            extra: Default::default(),
628            amendments: Vec::new(),
629        };
630        assert!(c.sample().is_none()); // not a binary sample
631        let ns = c.numeric_sample().unwrap();
632        assert_eq!(
633            (ns.low, ns.high, ns.level, ns.value),
634            (10.0, 20.0, 0.8, 13.0)
635        );
636    }
637
638    #[test]
639    fn current_is_latest_forecast() {
640        let c = claim("c", &[0.6, 0.8, 0.3], None);
641        assert_eq!(c.first_prob(), Some(0.6));
642        assert_eq!(c.current_prob(), Some(0.3));
643        assert!(c.was_revised());
644    }
645
646    #[test]
647    fn index_of_handles_prefix_and_ambiguity() {
648        let ledger = Ledger {
649            claims: vec![
650                claim("ab12cd", &[0.5], None),
651                claim("ab99ff", &[0.5], None),
652                claim("ff0000", &[0.5], None),
653            ],
654            ..Default::default()
655        };
656        assert_eq!(ledger.index_of("ff0000").unwrap(), 2);
657        assert_eq!(ledger.index_of("ff").unwrap(), 2);
658        assert!(ledger.index_of("ab").is_err());
659        assert!(ledger.index_of("zz").is_err());
660    }
661
662    #[test]
663    fn exact_id_beats_prefix_collision() {
664        let ledger = Ledger {
665            claims: vec![claim("ab", &[0.5], None), claim("ab12cd", &[0.5], None)],
666            ..Default::default()
667        };
668        assert_eq!(ledger.index_of("ab").unwrap(), 0);
669    }
670
671    #[test]
672    fn tags_normalised() {
673        let got = normalize_tags(&[
674            " Politics ".into(),
675            "politics".into(),
676            "".into(),
677            "TECH".into(),
678        ]);
679        assert_eq!(got, vec!["politics".to_string(), "tech".to_string()]);
680    }
681
682    #[test]
683    fn due_logic() {
684        let mut c = claim("d", &[0.5], None);
685        c.resolve_by = Some(NaiveDate::from_ymd_opt(2025, 6, 1).unwrap());
686        assert!(c.is_due(NaiveDate::from_ymd_opt(2025, 7, 1).unwrap()));
687        assert!(!c.is_due(NaiveDate::from_ymd_opt(2025, 5, 1).unwrap()));
688    }
689
690    #[test]
691    fn legacy_binary_json_still_loads() {
692        // A ledger written before numeric claims existed: no `kind`, bare `prob`,
693        // string `outcome`. It must load as a binary claim, unchanged.
694        let legacy = r#"{
695            "claims": [{
696                "id": "abc123",
697                "statement": "old belief",
698                "created_at": "2025-01-01T12:00:00Z",
699                "tags": ["legacy"],
700                "forecasts": [{ "at": "2025-01-01T12:00:00Z", "prob": 0.7, "because": "why" }],
701                "resolution": { "at": "2025-06-01T12:00:00Z", "outcome": "true", "note": "n" }
702            }]
703        }"#;
704        let ledger: Ledger = serde_json::from_str(legacy).unwrap();
705        let c = &ledger.claims[0];
706        assert_eq!(c.kind, ClaimKind::Binary);
707        assert_eq!(c.current_prob(), Some(0.7));
708        assert_eq!(c.outcome(), Some(Outcome::True));
709        assert_eq!(c.sample(), Some(Sample::new(0.7, true)));
710        // A ledger predating stakes loads with the default stake of 1.0…
711        assert_eq!(c.stake, 1.0);
712        // …and a default-stake claim does not re-introduce the field on save.
713        // Neither void nor amendments existed either, and a claim that has
714        // neither must not grow the fields on save — an old ledger stays
715        // byte-identical through a load/save round trip.
716        assert!(!c.is_void());
717        assert!(c.amendments.is_empty());
718        let round = serde_json::to_string(&ledger).unwrap();
719        assert!(
720            !round.contains("void"),
721            "absent void must not be serialised"
722        );
723        assert!(
724            !round.contains("amendments"),
725            "an empty amendment list must not be serialised"
726        );
727        assert!(
728            !round.contains("stake"),
729            "default stake must not be serialised"
730        );
731    }
732
733    #[test]
734    fn compose_reasoning_weaves_the_elicitation_trail() {
735        let r = compose_reasoning(
736            Some("looks clean"),
737            Some("similar PRs pass 60%"),
738            Some((0.7, 0.5)),
739        )
740        .unwrap();
741        assert!(r.contains("outside view: similar PRs pass 60%"));
742        assert!(r.contains("dialectical 0.70 & 0.50 → 0.60"));
743        assert!(r.contains("looks clean"));
744        // A single piece comes back bare; nothing-to-record is None.
745        assert_eq!(compose_reasoning(Some("x"), None, None).unwrap(), "x");
746        assert!(compose_reasoning(None, None, None).is_none());
747        assert!(compose_reasoning(Some("  "), Some(""), None).is_none());
748    }
749}