Skip to main content

jev/
typed.rs

1//! The typed-decision layer: three traits, three wrapper types, built on top of
2//! [`crate::question::Questions`] / [`crate::answer::Answers`] so there is exactly
3//! one copy of the wire logic.
4
5use indexmap::IndexMap;
6
7use crate::{answer::Answers, error::Error, question::Questions};
8
9/// A set of questions about one state, answered as one struct.
10///
11/// Implemented by `#[derive(Decision)]`; see the crate-level docs for the derive's
12/// rules. `questions()` is built once per process (the derive caches it in a private
13/// `LazyLock`) and is infallible, because the derive validates the question shape at
14/// compile time.
15///
16/// # Examples
17///
18/// ```
19/// use jev::{Answers, Decision, Error, Noul, Questions};
20///
21/// struct Manual {
22///     is_bug: Noul,
23/// }
24///
25/// impl Decision for Manual {
26///     fn questions() -> &'static Questions {
27///         use std::sync::LazyLock;
28///         static QUESTIONS: LazyLock<Questions> = LazyLock::new(|| {
29///             Questions::builder().noul("is_bug", "Is this a defect?").build().unwrap()
30///         });
31///         &QUESTIONS
32///     }
33///
34///     fn from_answers(answers: &Answers) -> Result<Self, Error> {
35///         Ok(Manual { is_bug: Noul::try_new(answers.noul("is_bug")?)? })
36///     }
37/// }
38/// ```
39pub trait Decision: Sized {
40    /// The questions to send, built once and cached by the derive.
41    fn questions() -> &'static Questions;
42
43    /// Rebuilds the struct from the model's answers.
44    ///
45    /// # Errors
46    ///
47    /// Any [`Error`] naming the offending question: [`Error::MissingAnswer`],
48    /// [`Error::AnswerType`], [`Error::UnknownChoice`], or [`Error::ScoreRange`].
49    fn from_answers(answers: &Answers) -> Result<Self, Error>;
50}
51
52/// A fieldless enum usable as `choice` criteria.
53///
54/// Implemented by `#[derive(ChoiceOptions)]`. Wire keys and criteria come from the
55/// enum's variants and their doc comments; see the crate-level docs for the derive's
56/// rules.
57pub trait ChoiceOptions: Sized + 'static {
58    /// Wire keys in declaration order, paired with their criteria text.
59    fn options() -> &'static [(&'static str, &'static str)];
60
61    /// Looks up the variant for a wire key, or `None` if unrecognized.
62    fn from_key(key: &str) -> Option<Self>;
63
64    /// This variant's wire key.
65    fn key(&self) -> &'static str;
66}
67
68/// A fieldless enum usable as an ordered `score` scale, lowest level first.
69///
70/// Implemented by `#[derive(ScoreLevels)]`. **Declaration order is the scale**:
71/// reordering variants silently changes the meaning of every tuned threshold.
72pub trait ScoreLevels: Sized + 'static {
73    /// Level criteria text, in declaration order (index 0 is the lowest level).
74    fn levels() -> &'static [&'static str];
75
76    /// Looks up the variant at `index`, or `None` if out of range.
77    fn from_index(index: usize) -> Option<Self>;
78
79    /// This variant's declaration-order index.
80    fn index(&self) -> usize;
81}
82
83/// A `noul` answer: `P(yes)`, plus threshold arithmetic.
84///
85/// # Examples
86///
87/// ```
88/// use jev::Noul;
89///
90/// let noul = Noul::try_new(0.92).unwrap();
91/// assert!(noul.is_yes(0.9));
92/// assert_eq!(noul.decide(0.9, 0.1), Some(true));
93/// ```
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct Noul {
96    probability: f64,
97}
98
99impl Noul {
100    /// Builds a `Noul` from a raw probability.
101    ///
102    /// # Errors
103    ///
104    /// Returns [`Error::Parse`] if `probability` is not finite or not within
105    /// `0.0..=1.0`. In practice this cannot happen for a value that came from
106    /// [`Answers::noul`], which already validates the range; the check here guards
107    /// hand-built values from a dynamic caller.
108    pub fn try_new(probability: f64) -> Result<Self, Error> {
109        if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
110            return Err(Error::Parse(format!(
111                "noul probability must be finite and within 0.0..=1.0, got {probability}"
112            )));
113        }
114        Ok(Noul { probability })
115    }
116
117    /// `P(yes)`.
118    #[must_use]
119    pub fn probability(&self) -> f64 {
120        self.probability
121    }
122
123    /// `P(yes) >= threshold`.
124    #[must_use]
125    pub fn is_yes(&self, threshold: f64) -> bool {
126        self.probability >= threshold
127    }
128
129    /// `P(yes) <= 1 - threshold`, computed as `1 - P(yes) >= threshold` so common
130    /// thresholds like `0.9` do not fail from floating-point subtraction order
131    /// (`1.0 - 0.9` is not bit-exact, but `1.0 - 0.1 >= 0.9` is).
132    #[must_use]
133    pub fn is_no(&self, threshold: f64) -> bool {
134        1.0 - self.probability >= threshold
135    }
136
137    /// `Some(true)` when `P(yes) >= yes_at`, `Some(false)` when `P(yes) <= 1 - no_at`,
138    /// `None` inside the ambiguous band between the two — the caller's cue to escalate.
139    #[must_use]
140    pub fn decide(&self, yes_at: f64, no_at: f64) -> Option<bool> {
141        if self.is_yes(yes_at) {
142            Some(true)
143        } else if self.is_no(no_at) {
144            Some(false)
145        } else {
146            None
147        }
148    }
149
150    /// A one-threshold alternative to [`Noul::decide`]: reads `P(yes)` as a
151    /// [`Verdict`] against a single `certainty` threshold, measured as distance from
152    /// the coin flip rather than as a raw probability.
153    ///
154    /// Where `decide(yes_at, no_at)` takes two independent thresholds — useful when
155    /// the cost of a false yes and a false no differ — `decide_verdict` takes one
156    /// symmetric threshold: `certainty = 0.8` accepts [`Verdict::Yes`] from `P(yes) >=
157    /// 0.9` and [`Verdict::No`] from `P(yes) <= 0.1`, leaving everything between them
158    /// [`Verdict::Unsure`]. `certainty = 0.0` never returns `Unsure` and splits at
159    /// `0.5`, matching [`Verdict::from_probability`]'s own default.
160    ///
161    /// # Examples
162    ///
163    /// ```
164    /// use jev::{Noul, Verdict};
165    ///
166    /// let noul = Noul::try_new(0.94).unwrap();
167    /// assert_eq!(noul.decide_verdict(0.8), Verdict::Yes);
168    ///
169    /// let ambiguous = Noul::try_new(0.55).unwrap();
170    /// assert_eq!(ambiguous.decide_verdict(0.8), Verdict::Unsure);
171    /// ```
172    #[must_use]
173    pub fn decide_verdict(&self, certainty: f64) -> Verdict {
174        Verdict::from_probability(self.probability, certainty)
175    }
176}
177
178impl std::fmt::Display for Noul {
179    /// Renders as a verdict with its certainty, e.g. `"yes, 88% sure"` or
180    /// `"no, 70% sure"`. See [`Verdict::from_probability`] for what "sure" measures.
181    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        let certainty = certainty_from_probability(self.probability);
183        let word = if self.probability >= 0.5 { "yes" } else { "no" };
184        write!(f, "{word}, {} sure", format_percent(certainty))
185    }
186}
187
188/// A yes/no judgment that may also come out undecided.
189///
190/// Where [`Noul::is_yes`]/[`Noul::is_no`] each take their own threshold, and
191/// [`Noul::decide`] takes two independent thresholds for an asymmetric risk
192/// tolerance, `Verdict` is the result of [`Noul::decide_verdict`]'s single symmetric
193/// threshold: a caller that falls back to non-AI behavior on an uncertain answer
194/// branches on this instead of comparing probabilities by hand.
195///
196/// # Examples
197///
198/// ```
199/// use jev::Verdict;
200///
201/// assert_eq!(Verdict::from_probability(0.94, 0.8), Verdict::Yes);
202/// assert_eq!(Verdict::from_probability(0.55, 0.8), Verdict::Unsure);
203/// assert_eq!(Verdict::from_probability(0.05, 0.8), Verdict::No);
204/// ```
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum Verdict {
207    /// Yes, at least as certain as the threshold asked for.
208    Yes,
209    /// Too close to the coin flip to call either way.
210    Unsure,
211    /// No, at least as certain as the threshold asked for.
212    No,
213}
214
215impl Verdict {
216    /// Reads a `P(yes)` probability as a `Verdict`, [`Verdict::Unsure`] below
217    /// `certainty`.
218    ///
219    /// `certainty` measures distance from the coin flip (`0.0..=1.0`), not a raw
220    /// probability: `0.8` accepts a yes from `P(yes) >= 0.9` and a no from `P(yes) <=
221    /// 0.1`. Both arguments are clamped into `0.0..=1.0` first, so a `certainty` above
222    /// `1.0` is treated as exactly `1.0`: `Unsure` for every probability except the
223    /// exact extremes `0.0` and `1.0`, rather than for every probability.
224    #[must_use]
225    pub fn from_probability(yes: f64, certainty: f64) -> Self {
226        let yes = yes.clamp(0.0, 1.0);
227        let certainty = certainty.clamp(0.0, 1.0);
228        let actual_certainty = certainty_from_probability(yes);
229        if actual_certainty < certainty {
230            Verdict::Unsure
231        } else if yes >= 0.5 {
232            Verdict::Yes
233        } else {
234            Verdict::No
235        }
236    }
237}
238
239impl std::fmt::Display for Verdict {
240    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241        f.write_str(match self {
242            Verdict::Yes => "yes",
243            Verdict::Unsure => "unsure",
244            Verdict::No => "no",
245        })
246    }
247}
248
249/// The distance of `yes` from the coin flip (`0.5`), stretched to `0.0..=1.0`: `0.5`
250/// and `1.0` (or `0.0`) map to `0.0` and `1.0` respectively.
251fn certainty_from_probability(yes: f64) -> f64 {
252    2.0f64.mul_add(yes, -1.0).abs()
253}
254
255/// Renders a probability in `0.0..=1.0` as a whole-percent string, e.g. `"88%"`.
256fn format_percent(probability: f64) -> String {
257    format!("{:.0}%", probability * 100.0)
258}
259
260/// A `choice` answer, carrying the typed value alongside its raw probabilities.
261///
262/// # Examples
263///
264/// ```
265/// use jev::{Choice, ChoiceOptions};
266///
267/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
268/// enum Team {
269///     Payments,
270///     Frontend,
271/// }
272///
273/// impl ChoiceOptions for Team {
274///     fn options() -> &'static [(&'static str, &'static str)] {
275///         &[("payments", "Billing issues."), ("frontend", "UI issues.")]
276///     }
277///     fn from_key(key: &str) -> Option<Self> {
278///         match key {
279///             "payments" => Some(Team::Payments),
280///             "frontend" => Some(Team::Frontend),
281///             _ => None,
282///         }
283///     }
284///     fn key(&self) -> &'static str {
285///         match self {
286///             Team::Payments => "payments",
287///             Team::Frontend => "frontend",
288///         }
289///     }
290/// }
291///
292/// let choice = Choice::<Team>::try_new("team", "payments", Some(0.8), Default::default()).unwrap();
293/// assert_eq!(*choice.value(), Team::Payments);
294/// assert!(choice.confident(0.7));
295/// ```
296#[derive(Debug, Clone, PartialEq)]
297pub struct Choice<T: ChoiceOptions> {
298    value: T,
299    confidence: Option<f64>,
300    probabilities: IndexMap<String, f64>,
301}
302
303impl<T: ChoiceOptions> Choice<T> {
304    /// Builds a `Choice` from a wire choice key, confidence, and probability map.
305    ///
306    /// # Errors
307    ///
308    /// Returns [`Error::UnknownChoice`] when `choice` names an option outside `T`.
309    /// `key` names the question this answer came from, used only in the
310    /// [`Error::UnknownChoice`] message if `choice` is not one of `T::options()`.
311    pub fn try_new(
312        key: &str,
313        choice: &str,
314        confidence: Option<f64>,
315        probabilities: IndexMap<String, f64>,
316    ) -> Result<Self, Error> {
317        let value = T::from_key(choice).ok_or_else(|| Error::UnknownChoice {
318            key: key.to_string(),
319            choice: choice.to_string(),
320            expected: T::options()
321                .iter()
322                .map(|(k, _)| *k)
323                .collect::<Vec<_>>()
324                .join(", "),
325        })?;
326        Ok(Choice {
327            value,
328            confidence,
329            probabilities,
330        })
331    }
332
333    /// The selected option.
334    #[must_use]
335    pub fn value(&self) -> &T {
336        &self.value
337    }
338
339    /// Consumes the wrapper, returning the selected option.
340    #[must_use]
341    pub fn into_value(self) -> T {
342        self.value
343    }
344
345    /// The server's confidence in `value`, when reported.
346    #[must_use]
347    pub fn confidence(&self) -> Option<f64> {
348        self.confidence
349    }
350
351    /// The raw probability the server assigned to `option`, or `0.0` if absent.
352    #[must_use]
353    pub fn probability_of(&self, option: &T) -> f64 {
354        self.probabilities.get(option.key()).copied().unwrap_or(0.0)
355    }
356
357    /// Confidence is present and `>= threshold`.
358    #[must_use]
359    pub fn confident(&self, threshold: f64) -> bool {
360        self.confidence.is_some_and(|c| c >= threshold)
361    }
362
363    /// `Some(value)` when [`Self::accept`] confident, else `None` — the caller's cue to
364    /// escalate to a human or a fallback path.
365    #[must_use]
366    pub fn accept(&self, threshold: f64) -> Option<&T> {
367        self.confident(threshold).then(|| self.value())
368    }
369
370    /// Picks an option by its probability instead of by [`Self::value`]'s mode.
371    ///
372    /// Walks `T::options()` in declaration order, subtracting each option's
373    /// probability (`0.0` for an option [`Self::probability_of`] has no entry for)
374    /// from `roll`, and returns the option the roll lands in: an option the model
375    /// gave a fifth of the mass to comes up for a fifth of the rolls. This lets a
376    /// scene play out differently from one run to the next without ever picking an
377    /// option the model ruled out entirely.
378    ///
379    /// `roll` is a value in `0.0..=1.0` supplied by the caller, so the draw stays
380    /// reproducible (seeded from the caller's own RNG, a fixed test seed, or
381    /// anything else) and this crate stays free of a `rand` dependency. When `roll`
382    /// is outside `0.0..=1.0`, or the probabilities do not sum to at least `roll`
383    /// (for example because the server reported none), [`Self::value`] comes back.
384    ///
385    /// # Examples
386    ///
387    /// ```
388    /// use jev::{Choice, ChoiceOptions};
389    /// use indexmap::IndexMap;
390    ///
391    /// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
392    /// enum Team { Payments, Frontend }
393    /// impl ChoiceOptions for Team {
394    ///     fn options() -> &'static [(&'static str, &'static str)] {
395    ///         &[("payments", "Billing."), ("frontend", "UI.")]
396    ///     }
397    ///     fn from_key(key: &str) -> Option<Self> {
398    ///         match key { "payments" => Some(Team::Payments), "frontend" => Some(Team::Frontend), _ => None }
399    ///     }
400    ///     fn key(&self) -> &'static str {
401    ///         match self { Team::Payments => "payments", Team::Frontend => "frontend" }
402    ///     }
403    /// }
404    ///
405    /// let mut probabilities = IndexMap::new();
406    /// probabilities.insert("payments".to_string(), 0.7);
407    /// probabilities.insert("frontend".to_string(), 0.3);
408    /// let choice = Choice::<Team>::try_new("team", "payments", Some(0.7), probabilities).unwrap();
409    ///
410    /// assert_eq!(choice.sample(0.5), Team::Payments); // within the first 0.7
411    /// assert_eq!(choice.sample(0.9), Team::Frontend); // within the last 0.3
412    /// ```
413    /// # Panics
414    ///
415    /// Never panics for a `T` whose `ChoiceOptions` impl keeps `key()`/`from_key()`
416    /// consistent (guaranteed by `#[derive(ChoiceOptions)]`): `self.value.key()` is
417    /// always one of `T::options()`'s keys, so the fallback `T::from_key` always
418    /// succeeds. A hand-written `ChoiceOptions` impl that violates that contract is a
419    /// caller-side bug this method cannot recover from.
420    #[must_use]
421    pub fn sample(&self, roll: f64) -> T {
422        let mut remaining = roll;
423        for (key, _) in T::options() {
424            let probability = self.probabilities.get(*key).copied().unwrap_or(0.0);
425            remaining -= probability;
426            if remaining < 0.0 {
427                // `key` came from `T::options()`, so `from_key` always succeeds here.
428                if let Some(value) = T::from_key(key) {
429                    return value;
430                }
431            }
432        }
433        // Roll exceeded the total probability mass (or there was none reported):
434        // fall back to a value equivalent to the answer's own selection.
435        T::from_key(self.value.key()).unwrap_or_else(|| unreachable_choice_key(self.value.key()))
436    }
437}
438
439/// Panics: only reachable from a hand-written `ChoiceOptions` impl whose `key()` and
440/// `from_key()` disagree, which `#[derive(ChoiceOptions)]` never produces. See
441/// [`Choice::sample`]'s `# Panics` section.
442fn unreachable_choice_key<T>(key: &str) -> T {
443    panic!(
444        "ChoiceOptions::from_key({key:?}) must succeed: key() must return one of T::options()'s \
445         own keys"
446    )
447}
448
449impl<T: ChoiceOptions + std::fmt::Debug> std::fmt::Display for Choice<T> {
450    /// Renders as the selected option followed by the full distribution and
451    /// confidence, e.g. `"Payments (payments 88%, frontend 12%; confidence 82%)"`.
452    /// Probabilities are listed in `T::options()` declaration order.
453    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454        write!(f, "{:?} (", self.value)?;
455        for (index, (key, _)) in T::options().iter().enumerate() {
456            if index > 0 {
457                f.write_str(", ")?;
458            }
459            let probability = self.probabilities.get(*key).copied().unwrap_or(0.0);
460            write!(f, "{key} {}", format_percent(probability))?;
461        }
462        let confidence = self
463            .confidence
464            .map_or_else(|| "n/a".to_string(), format_percent);
465        write!(f, "; confidence {confidence})")
466    }
467}
468
469/// A `score` answer, carrying the raw continuous score alongside the typed nearest
470/// level.
471///
472/// # Examples
473///
474/// ```
475/// use jev::{Score, ScoreLevels};
476///
477/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
478/// enum Urgency {
479///     NextRelease,
480///     ThisWeek,
481///     BlockingRevenue,
482/// }
483///
484/// impl ScoreLevels for Urgency {
485///     fn levels() -> &'static [&'static str] {
486///         &["Can wait.", "This week.", "Blocking revenue."]
487///     }
488///     fn from_index(index: usize) -> Option<Self> {
489///         match index {
490///             0 => Some(Urgency::NextRelease),
491///             1 => Some(Urgency::ThisWeek),
492///             2 => Some(Urgency::BlockingRevenue),
493///             _ => None,
494///         }
495///     }
496///     fn index(&self) -> usize {
497///         match self {
498///             Urgency::NextRelease => 0,
499///             Urgency::ThisWeek => 1,
500///             Urgency::BlockingRevenue => 2,
501///         }
502///     }
503/// }
504///
505/// let score = Score::<Urgency>::try_new("urgency", 1.9, None, Default::default()).unwrap();
506/// assert_eq!(score.nearest(), Urgency::BlockingRevenue);
507/// ```
508#[derive(Debug, Clone, PartialEq)]
509pub struct Score<T: ScoreLevels> {
510    raw: f64,
511    confidence: Option<f64>,
512    probabilities: IndexMap<String, f64>,
513    _levels: std::marker::PhantomData<T>,
514}
515
516impl<T: ScoreLevels> Score<T> {
517    /// Builds a `Score` from a raw wire score, confidence, and probability map.
518    ///
519    /// `key` names the question this answer came from, used only in the
520    /// [`Error::ScoreRange`] message if `raw` is out of range for `T`.
521    ///
522    /// # Errors
523    ///
524    /// Returns [`Error::ScoreRange`] when `raw` falls outside `0.0..=(levels - 1)`
525    /// for `T::levels()`.
526    #[allow(clippy::cast_precision_loss)] // levels is bounded by MAX_SCORE_LEVELS (32)
527    pub fn try_new(
528        key: &str,
529        raw: f64,
530        confidence: Option<f64>,
531        probabilities: IndexMap<String, f64>,
532    ) -> Result<Self, Error> {
533        let levels = T::levels().len();
534        let max_index = (levels.saturating_sub(1)) as f64;
535        if !raw.is_finite() || !(0.0..=max_index).contains(&raw) {
536            return Err(Error::ScoreRange {
537                key: key.to_string(),
538                score: raw,
539                levels,
540            });
541        }
542        Ok(Score {
543            raw,
544            confidence,
545            probabilities,
546            _levels: std::marker::PhantomData,
547        })
548    }
549
550    /// The probability-weighted position on the scale, e.g. `1.99`.
551    #[must_use]
552    pub fn raw(&self) -> f64 {
553        self.raw
554    }
555
556    /// The nearest discrete level.
557    ///
558    /// Always returns a value: a `Score<T>` can only be constructed from a raw score
559    /// already validated against `T::levels()` by [`Self::try_new`], so rounding
560    /// `raw()` to the nearest integer always lands on a valid index.
561    ///
562    /// # Panics
563    ///
564    /// Never panics for a `T` whose `ScoreLevels` impl keeps `index()`/`from_index()`
565    /// consistent with `levels()` (guaranteed by `#[derive(ScoreLevels)]`). A
566    /// hand-written `ScoreLevels` impl that violates that contract — for example,
567    /// `from_index(0)` returning `None` — is a caller-side bug this method cannot
568    /// recover from.
569    #[must_use]
570    #[allow(clippy::cast_precision_loss)] // levels is bounded by MAX_SCORE_LEVELS (32)
571    pub fn nearest(&self) -> T {
572        let levels = T::levels().len();
573        let max_index = levels.saturating_sub(1);
574        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
575        let rounded = self.raw.round().clamp(0.0, max_index as f64) as usize;
576        T::from_index(rounded).unwrap_or_else(|| {
577            T::from_index(0).expect(
578                "ScoreLevels::from_index(0) must succeed: derive(ScoreLevels) guarantees at least \
579                 2 variants, so index 0 always exists",
580            )
581        })
582    }
583
584    /// `raw()` normalized to `0.0..=1.0`, handy for sorting across different scales.
585    ///
586    /// A single-level scale (`levels() == 1`) normalizes to `0.0`.
587    #[must_use]
588    #[allow(clippy::cast_precision_loss)] // levels is bounded by MAX_SCORE_LEVELS (32)
589    pub fn normalized(&self) -> f64 {
590        let max_index = T::levels().len().saturating_sub(1);
591        if max_index == 0 {
592            0.0
593        } else {
594            self.raw / max_index as f64
595        }
596    }
597
598    /// `raw() >= level.index()`.
599    #[must_use]
600    #[allow(clippy::cast_precision_loss)] // index() is bounded by MAX_SCORE_LEVELS (32)
601    pub fn at_least(&self, level: &T) -> bool {
602        self.raw >= level.index() as f64
603    }
604
605    /// The server's confidence in `score`, when reported.
606    #[must_use]
607    pub fn confidence(&self) -> Option<f64> {
608        self.confidence
609    }
610
611    /// Confidence is present and `>= threshold`.
612    #[must_use]
613    pub fn confident(&self, threshold: f64) -> bool {
614        self.confidence.is_some_and(|c| c >= threshold)
615    }
616}
617
618impl<T: ScoreLevels> std::fmt::Display for Score<T> {
619    /// Renders as the raw score followed by each level's probability and the
620    /// confidence, e.g. `"1.88 (harmless 0%, wary 12%, lethal 88%; confidence
621    /// 82%)"`. Levels are listed in `T::levels()` declaration order; a level with no
622    /// reported probability shows `0%`.
623    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
624        write!(f, "{:.2} (", self.raw)?;
625        for (index, level) in T::levels().iter().enumerate() {
626            if index > 0 {
627                f.write_str(", ")?;
628            }
629            let probability = self
630                .probabilities
631                .get(&index.to_string())
632                .copied()
633                .unwrap_or(0.0);
634            write!(f, "{level} {}", format_percent(probability))?;
635        }
636        let confidence = self
637            .confidence
638            .map_or_else(|| "n/a".to_string(), format_percent);
639        write!(f, "; confidence {confidence})")
640    }
641}
642
643#[cfg(test)]
644mod tests {
645    use proptest::prelude::*;
646
647    use super::*;
648
649    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
650    enum Team {
651        Payments,
652        Frontend,
653    }
654
655    impl ChoiceOptions for Team {
656        fn options() -> &'static [(&'static str, &'static str)] {
657            &[("payments", "Billing."), ("frontend", "UI.")]
658        }
659        fn from_key(key: &str) -> Option<Self> {
660            match key {
661                "payments" => Some(Team::Payments),
662                "frontend" => Some(Team::Frontend),
663                _ => None,
664            }
665        }
666        fn key(&self) -> &'static str {
667            match self {
668                Team::Payments => "payments",
669                Team::Frontend => "frontend",
670            }
671        }
672    }
673
674    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
675    enum Urgency {
676        Low,
677        Mid,
678        High,
679    }
680
681    impl ScoreLevels for Urgency {
682        fn levels() -> &'static [&'static str] {
683            &["Low.", "Mid.", "High."]
684        }
685        fn from_index(index: usize) -> Option<Self> {
686            match index {
687                0 => Some(Urgency::Low),
688                1 => Some(Urgency::Mid),
689                2 => Some(Urgency::High),
690                _ => None,
691            }
692        }
693        fn index(&self) -> usize {
694            match self {
695                Urgency::Low => 0,
696                Urgency::Mid => 1,
697                Urgency::High => 2,
698            }
699        }
700    }
701
702    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
703    enum TwoLevel {
704        Off,
705        On,
706    }
707
708    impl ScoreLevels for TwoLevel {
709        fn levels() -> &'static [&'static str] {
710            &["Off.", "On."]
711        }
712        fn from_index(index: usize) -> Option<Self> {
713            match index {
714                0 => Some(TwoLevel::Off),
715                1 => Some(TwoLevel::On),
716                _ => None,
717            }
718        }
719        fn index(&self) -> usize {
720            match self {
721                TwoLevel::Off => 0,
722                TwoLevel::On => 1,
723            }
724        }
725    }
726
727    #[test]
728    fn test_should_reject_out_of_range_noul_probability() {
729        assert!(Noul::try_new(1.5).is_err());
730        assert!(Noul::try_new(-0.1).is_err());
731        assert!(Noul::try_new(f64::NAN).is_err());
732    }
733
734    #[test]
735    fn test_should_evaluate_is_yes_and_is_no_at_boundaries() {
736        let noul = Noul::try_new(0.9).unwrap();
737        assert!(noul.is_yes(0.9));
738        assert!(!noul.is_yes(0.91));
739        let noul = Noul::try_new(0.1).unwrap();
740        assert!(noul.is_no(0.9));
741        assert!(!noul.is_no(0.91));
742    }
743
744    #[test]
745    fn test_should_return_none_from_decide_in_ambiguous_band() {
746        let noul = Noul::try_new(0.5).unwrap();
747        assert_eq!(noul.decide(0.9, 0.9), None);
748    }
749
750    #[test]
751    fn test_should_return_some_true_or_false_outside_ambiguous_band() {
752        assert_eq!(Noul::try_new(0.95).unwrap().decide(0.9, 0.9), Some(true));
753        assert_eq!(Noul::try_new(0.05).unwrap().decide(0.9, 0.9), Some(false));
754    }
755
756    #[test]
757    fn test_should_build_choice_and_reject_unknown_option() {
758        let choice =
759            Choice::<Team>::try_new("team", "payments", Some(0.9), IndexMap::new()).unwrap();
760        assert_eq!(*choice.value(), Team::Payments);
761
762        let err = Choice::<Team>::try_new("team", "legal", None, IndexMap::new()).unwrap_err();
763        assert!(matches!(err, Error::UnknownChoice { .. }));
764    }
765
766    #[test]
767    fn test_should_report_choice_confidence_and_accept_threshold() {
768        let choice =
769            Choice::<Team>::try_new("team", "payments", Some(0.9), IndexMap::new()).unwrap();
770        assert!(choice.confident(0.8));
771        assert_eq!(choice.accept(0.8), Some(&Team::Payments));
772        assert_eq!(choice.accept(0.95), None);
773    }
774
775    #[test]
776    fn test_should_treat_missing_confidence_as_not_confident() {
777        let choice = Choice::<Team>::try_new("team", "payments", None, IndexMap::new()).unwrap();
778        assert!(!choice.confident(0.0));
779        assert_eq!(choice.accept(0.0), None);
780    }
781
782    #[test]
783    fn test_should_return_zero_probability_for_option_without_entry() {
784        let choice = Choice::<Team>::try_new("team", "payments", None, IndexMap::new()).unwrap();
785        assert_eq!(choice.probability_of(&Team::Frontend), 0.0);
786    }
787
788    #[test]
789    fn test_should_build_score_and_report_nearest_level() {
790        let score = Score::<Urgency>::try_new("urgency", 1.9, Some(0.7), IndexMap::new()).unwrap();
791        assert_eq!(score.nearest(), Urgency::High);
792        assert_eq!(score.raw(), 1.9);
793        assert!(score.confident(0.5));
794    }
795
796    #[test]
797    fn test_should_reject_score_out_of_range() {
798        assert!(Score::<Urgency>::try_new("urgency", -0.1, None, IndexMap::new()).is_err());
799        assert!(Score::<Urgency>::try_new("urgency", 2.1, None, IndexMap::new()).is_err());
800        assert!(Score::<Urgency>::try_new("urgency", f64::NAN, None, IndexMap::new()).is_err());
801    }
802
803    #[test]
804    fn test_should_accept_score_at_boundaries() {
805        assert!(Score::<Urgency>::try_new("urgency", 0.0, None, IndexMap::new()).is_ok());
806        assert!(Score::<Urgency>::try_new("urgency", 2.0, None, IndexMap::new()).is_ok());
807    }
808
809    #[test]
810    fn test_should_evaluate_at_least() {
811        let score = Score::<Urgency>::try_new("urgency", 1.0, None, IndexMap::new()).unwrap();
812        assert!(score.at_least(&Urgency::Low));
813        assert!(score.at_least(&Urgency::Mid));
814        assert!(!score.at_least(&Urgency::High));
815    }
816
817    #[test]
818    fn test_should_normalize_two_level_scale_to_zero_or_one() {
819        let low = Score::<TwoLevel>::try_new("flag", 0.0, None, IndexMap::new()).unwrap();
820        let high = Score::<TwoLevel>::try_new("flag", 1.0, None, IndexMap::new()).unwrap();
821        assert_eq!(low.normalized(), 0.0);
822        assert_eq!(high.normalized(), 1.0);
823    }
824
825    #[test]
826    fn test_should_normalize_three_level_scale() {
827        let mid = Score::<Urgency>::try_new("urgency", 1.0, None, IndexMap::new()).unwrap();
828        assert_eq!(mid.normalized(), 0.5);
829    }
830
831    proptest! {
832        #[test]
833        fn test_should_keep_normalized_within_unit_interval(raw in 0.0f64..=2.0) {
834            let score = Score::<Urgency>::try_new("urgency", raw, None, IndexMap::new()).unwrap();
835            let normalized = score.normalized();
836            prop_assert!((0.0..=1.0).contains(&normalized));
837        }
838    }
839
840    #[test]
841    fn test_should_compute_verdict_from_probability() {
842        assert_eq!(Verdict::from_probability(0.94, 0.8), Verdict::Yes);
843        assert_eq!(Verdict::from_probability(0.55, 0.8), Verdict::Unsure);
844        assert_eq!(Verdict::from_probability(0.05, 0.8), Verdict::No);
845    }
846
847    #[test]
848    fn test_should_never_return_unsure_for_zero_certainty_threshold() {
849        assert_eq!(Verdict::from_probability(0.51, 0.0), Verdict::Yes);
850        assert_eq!(Verdict::from_probability(0.49, 0.0), Verdict::No);
851    }
852
853    #[test]
854    fn test_should_return_unsure_for_non_extreme_probability_at_certainty_above_one() {
855        // Clamped threshold of 1.0 requires certainty == 1.0, achievable only at the
856        // probability extremes (exactly 0.0 or 1.0); anything else is Unsure.
857        assert_eq!(Verdict::from_probability(0.99, 1.5), Verdict::Unsure);
858        assert_eq!(Verdict::from_probability(0.01, 1.5), Verdict::Unsure);
859    }
860
861    #[test]
862    fn test_should_clamp_out_of_range_probability_for_verdict() {
863        assert_eq!(Verdict::from_probability(1.5, 0.0), Verdict::Yes);
864        assert_eq!(Verdict::from_probability(-0.5, 0.0), Verdict::No);
865    }
866
867    #[test]
868    fn test_should_derive_verdict_from_noul() {
869        let noul = Noul::try_new(0.94).unwrap();
870        assert_eq!(noul.decide_verdict(0.8), Verdict::Yes);
871        let ambiguous = Noul::try_new(0.55).unwrap();
872        assert_eq!(ambiguous.decide_verdict(0.8), Verdict::Unsure);
873    }
874
875    #[test]
876    fn test_should_display_verdict_as_lowercase_word() {
877        assert_eq!(Verdict::Yes.to_string(), "yes");
878        assert_eq!(Verdict::Unsure.to_string(), "unsure");
879        assert_eq!(Verdict::No.to_string(), "no");
880    }
881
882    #[test]
883    fn test_should_display_noul_as_verdict_with_certainty() {
884        let noul = Noul::try_new(0.94).unwrap();
885        assert_eq!(noul.to_string(), "yes, 88% sure");
886        let noul = Noul::try_new(0.15).unwrap();
887        assert_eq!(noul.to_string(), "no, 70% sure");
888    }
889
890    #[test]
891    fn test_should_sample_choice_within_first_probability_band() {
892        let mut probabilities = IndexMap::new();
893        probabilities.insert("payments".to_string(), 0.7);
894        probabilities.insert("frontend".to_string(), 0.3);
895        let choice = Choice::<Team>::try_new("team", "payments", Some(0.7), probabilities).unwrap();
896
897        assert_eq!(choice.sample(0.0), Team::Payments);
898        assert_eq!(choice.sample(0.69), Team::Payments);
899        assert_eq!(choice.sample(0.71), Team::Frontend);
900        assert_eq!(choice.sample(0.99), Team::Frontend);
901    }
902
903    #[test]
904    fn test_should_sample_choice_deterministically_for_same_roll() {
905        let mut probabilities = IndexMap::new();
906        probabilities.insert("payments".to_string(), 0.5);
907        probabilities.insert("frontend".to_string(), 0.5);
908        let choice = Choice::<Team>::try_new("team", "payments", None, probabilities).unwrap();
909
910        assert_eq!(choice.sample(0.3), choice.sample(0.3));
911    }
912
913    #[test]
914    fn test_should_fall_back_to_value_when_sample_roll_exceeds_probability_mass() {
915        // No probabilities reported at all: any roll falls back to `value()`.
916        let choice = Choice::<Team>::try_new("team", "payments", None, IndexMap::new()).unwrap();
917        assert_eq!(choice.sample(0.5), Team::Payments);
918        assert_eq!(choice.sample(1.5), Team::Payments);
919    }
920
921    #[test]
922    fn test_should_display_choice_with_ranked_probabilities_and_confidence() {
923        let mut probabilities = IndexMap::new();
924        probabilities.insert("payments".to_string(), 0.88);
925        probabilities.insert("frontend".to_string(), 0.12);
926        let choice =
927            Choice::<Team>::try_new("team", "payments", Some(0.82), probabilities).unwrap();
928        assert_eq!(
929            choice.to_string(),
930            "Payments (payments 88%, frontend 12%; confidence 82%)"
931        );
932    }
933
934    #[test]
935    fn test_should_display_choice_without_confidence_as_not_applicable() {
936        let choice = Choice::<Team>::try_new("team", "payments", None, IndexMap::new()).unwrap();
937        assert_eq!(
938            choice.to_string(),
939            "Payments (payments 0%, frontend 0%; confidence n/a)"
940        );
941    }
942
943    #[test]
944    fn test_should_display_score_with_level_probabilities_and_confidence() {
945        let mut probabilities = IndexMap::new();
946        probabilities.insert("0".to_string(), 0.0);
947        probabilities.insert("1".to_string(), 0.12);
948        probabilities.insert("2".to_string(), 0.88);
949        let score = Score::<Urgency>::try_new("urgency", 1.88, Some(0.82), probabilities).unwrap();
950        assert_eq!(
951            score.to_string(),
952            "1.88 (Low. 0%, Mid. 12%, High. 88%; confidence 82%)"
953        );
954    }
955}