1use 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#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
20#[serde(rename_all = "lowercase")]
21pub enum ClaimKind {
22 #[default]
24 Binary,
25 Numeric,
27}
28
29#[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#[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#[derive(Serialize, Deserialize, Clone, Debug)]
89pub struct Forecast {
90 pub at: DateTime<Utc>,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub prob: Option<f64>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub interval: Option<NumericForecast>,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub because: Option<String>,
100}
101
102#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub resolved_by: Option<ResolvedBy>,
122}
123
124#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)]
126#[serde(rename_all = "lowercase")]
127pub enum ResolvedBy {
128 #[default]
130 #[serde(rename = "self")]
131 Zelf,
132 Auto,
134 Human,
136}
137
138#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub horizon_days: Option<i64>,
153 #[serde(default)]
154 pub tags: Vec<String>,
155 #[serde(default)]
157 pub kind: ClaimKind,
158 #[serde(default = "default_stake", skip_serializing_if = "is_default_stake")]
162 pub stake: f64,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub check: Option<String>,
173 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
175 pub extra: Extra,
176 pub forecasts: Vec<Forecast>,
179 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub resolution: Option<Resolution>,
181 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub void: Option<Void>,
191 #[serde(default, skip_serializing_if = "Vec::is_empty")]
196 pub amendments: Vec<Amendment>,
197}
198
199#[derive(Serialize, Deserialize, Clone, Debug)]
201pub struct Void {
202 pub at: DateTime<Utc>,
203 pub reason: String,
204}
205
206#[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
228pub 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 pub fn is_void(&self) -> bool {
277 self.void.is_some()
278 }
279
280 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 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 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 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 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 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 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 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 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 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
474pub fn collapse_spaces(s: &str) -> String {
476 s.split_whitespace().collect::<Vec<_>>().join(" ")
477}
478
479pub type Extra = serde_json::Map<String, serde_json::Value>;
487
488#[derive(Serialize, Deserialize, Clone, Debug, Default)]
490pub struct Ledger {
491 #[serde(default)]
492 pub claims: Vec<Claim>,
493 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
495 pub extra: Extra,
496}
497
498impl Ledger {
499 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
527pub 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
535pub 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()); 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 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 assert_eq!(c.stake, 1.0);
712 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 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}