system2 0.1.0

An (unofficial) idiomatic Rust SDK for TypeSafe's System One model, Jev.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
use super::table::Table;
use crate::ask::wire::{RawAnswerSet, RawQuestionSet, Sealed, validate_range};
use crate::json::Json;
use crate::{InvalidAnswer, InvalidJson, QuestionSet, Tagged, json};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize, Serializer};
use serde_json::value::RawValue;
use std::borrow::Cow;
use std::collections::HashMap;
use system2_shared::score::{self, MAX_LEVELS};

/// A question with an answer on a scale of levels.
///
/// The levels go from the lowest to the highest, and each one has a value of the type `L`. The API
/// knows a level only by its text. The answer is a [`ScoreAnswer`], with the probability of each
/// level, and it gives the values back. [`score!`](crate::score) makes a Score that the compiler
/// checks. The constructors make one from data. A Score has 1 to 10 levels, and each level is
/// different.
///
/// # Examples
///
/// The smallest Score has a list of levels, from the lowest to the highest. The answer gives a
/// level back:
///
/// ```
/// use system2::Score;
///
/// let urgency = Score::new(
///     "How urgent is the ticket?",
///     ["It can wait.", "It needs an answer today.", "It needs an answer now."],
/// )?;
/// # Ok::<(), system2::Error>(())
/// ```
///
/// A level can be a value of the caller. A closure gives its text, and the answer gives the
/// value back:
///
/// ```
/// # use system2::Score;
/// struct Deadline {
///     level: String,
///     hours: u32,
/// }
///
/// let deadlines = vec![
///     Deadline { level: "It can wait.".to_string(), hours: 72 },
///     Deadline { level: "It needs an answer now.".to_string(), hours: 1 },
/// ];
/// let urgency = Score::with_values("How urgent is the ticket?", &deadlines, |deadline| {
///     &deadline.level
/// })?;
/// # Ok::<(), system2::Error>(())
/// ```
///
/// An enum that derives [`Levels`] gives its variants as the levels:
///
/// ```
/// use system2::Levels;
/// # use system2::Score;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Levels)]
/// enum Urgency {
///     Low,
///     Medium,
///     High,
/// }
///
/// let instructions = "How urgent is the ticket?".to_string();
/// let urgency = Score::<Urgency>::of(instructions)?;
/// # Ok::<(), system2::Error>(())
/// ```
///
/// [`score!`](crate::score) takes the same forms, and the compiler checks them. A question with
/// no variable can be a constant:
///
/// ```no_run
/// use system2::prelude::*;
/// use system2::Score;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Levels)]
/// enum Urgency {
///     Low,
///     Medium,
///     High,
/// }
///
/// const URGENCY: Score<Urgency> = score!("How urgent is the ticket?", Urgency);
/// const SIZE: Score<&str> = score!("How big is the fix?", ["A line.", "A file.", "A module."]);
/// const DAYS: Score<u32> = score!("How long does the fix take?", [("A day.", 1), ("A week.", 5)]);
///
/// # async fn run() -> system2::Result<()> {
/// let urgency = URGENCY.ask("The site is down.").await?;
/// if *urgency.most_likely() == Urgency::High || urgency.score() > 1.5 { /* … */ }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Score<L> {
    instructions: Json,
    levels: Table<MacroLevel<L>, Entry<L>>,
}

const EACH_LEVEL: &str = "must give a probability for each level of the Score, and no other";

// a level as a macro writes it: the text of the level, and the value
type MacroLevel<L> = (&'static str, L);

#[derive(Debug, Clone)]
struct Entry<L> {
    level: Json,
    value: L,
}

/// The levels of a [`Score`], from an enum.
///
/// Only [`derive(Levels)`](macro@crate::Levels) implements it. A caller names the trait in a
/// bound, as in `L: Levels`. For levels that are not an enum, use [`Score::with_values`].
#[diagnostic::on_unimplemented(
    message = "`{Self}` must derive `Levels` to give the levels of a Score",
    label = "does not derive `Levels`",
    note = "add `#[derive(Levels)]` to an enum, or use `Score::with_values` for other types"
)]
pub trait Levels: Sized + 'static {
    // only the derive writes the table, so its shape can change
    #[doc(hidden)]
    const LEVELS: &'static [ScoreLevel<Self>];

    // `score!` names the type in a path to this, where rustc refuses a variable as not a type
    #[doc(hidden)]
    const MACRO_LEVELS: fn() -> Vec<MacroLevel<Self>> = levels_of::<Self>;
}

#[doc(hidden)]
#[derive(Debug)]
pub struct ScoreLevel<L> {
    pub level: &'static str,
    pub value: fn() -> L,
}

impl<L> Score<L> {
    /// Makes a Score from levels that come from data, from the lowest to the highest.
    ///
    /// Each level is any `Serialize` value, and it follows the rules of the instructions. The
    /// answer gives the level back.
    ///
    /// # Errors
    ///
    /// - [`InvalidScore::Instructions`] if the instructions do not serialize, are empty, or are a
    ///   bare number or `bool`.
    /// - [`InvalidScore::Level`] if a level breaks a rule of the instructions.
    /// - [`InvalidScore::Count`] if there are no levels, or more than 10.
    /// - [`InvalidScore::Duplicate`] if two levels are the same.
    pub fn new(
        instructions: impl Serialize,
        levels: impl IntoIterator<Item = L>,
    ) -> Result<Self, InvalidScore>
    where
        L: Serialize,
    {
        let levels = levels
            .into_iter()
            .map(|level| (json::validate(&level), level));
        Self::validated(instructions, levels)
    }

    /// Makes a Score from the values of the caller, with a closure that gives their levels.
    ///
    /// The values go from the lowest level to the highest. Each level is any `Serialize` value, and
    /// it follows the rules of the instructions. The values need no `Clone`, and the answer gives
    /// a value back.
    ///
    /// # Errors
    ///
    /// - [`InvalidScore::Instructions`] if the instructions do not serialize, are empty, or are a
    ///   bare number or `bool`.
    /// - [`InvalidScore::Level`] if a level breaks a rule of the instructions.
    /// - [`InvalidScore::Count`] if there are no values, or more than 10.
    /// - [`InvalidScore::Duplicate`] if two levels are the same.
    pub fn with_values<D: Serialize>(
        instructions: impl Serialize,
        values: impl IntoIterator<Item = L>,
        mut level: impl FnMut(&L) -> D,
    ) -> Result<Self, InvalidScore> {
        let levels = values
            .into_iter()
            .map(|value| (json::validate(level(&value)), value));
        Self::validated(instructions, levels)
    }

    /// Makes a Score from instructions that come from data, with the levels of the type `L`.
    ///
    /// It validates the levels of `L` again, as [`Score::with_values`] does.
    ///
    /// # Errors
    ///
    /// [`InvalidScore::Instructions`] if the instructions do not serialize, are empty, or are a
    /// bare number or `bool`. The derive of [`Levels`] validates the levels, so another variant
    /// does not occur.
    pub fn of(instructions: impl Serialize) -> Result<Self, InvalidScore>
    where
        L: Levels,
    {
        let levels = L::LEVELS
            .iter()
            .map(|level| (json::validate(level.level), (level.value)()));
        Self::validated(instructions, levels)
    }

    /// Puts a tag next to the question, so that the answer comes back next to it.
    ///
    /// It is the same as [`Ask::tag`](crate::Ask::tag), but it is a `const fn`, so a constant can
    /// hold a tagged question.
    pub const fn tag<T>(self, tag: T) -> Tagged<Self, T> {
        Tagged::new(self, tag)
    }

    /// Builds the answer that a response with these values would give.
    ///
    /// `score` is the mean level, from 0 to the index of the last level, `confidence` is the
    /// confidence of the API, and `probabilities` has one probability for each level, lowest
    /// first. It's for tests of your own decision code, and it goes through the same checks as a
    /// response from the API.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidAnswer`] if the score is not from 0 to the index of the last level, if
    /// there is not one probability for each level, or if another value is not from 0 to 1.
    pub fn answer(
        self,
        score: f64,
        confidence: f64,
        probabilities: impl IntoIterator<Item = f64>,
    ) -> Result<ScoreAnswer<L>, InvalidAnswer> {
        let probabilities = probabilities.into_iter().collect();
        self.validated_answer(score, confidence, probabilities)
            .map_err(InvalidAnswer::new)
    }

    fn validated_answer(
        mut self,
        score: f64,
        confidence: f64,
        probabilities: Vec<f64>,
    ) -> Result<ScoreAnswer<L>, String> {
        let levels = self.levels.entries();
        #[expect(clippy::cast_precision_loss, reason = "a Score has at most 10 levels")]
        let last_position = (levels.len() - 1) as f64;
        validate_range("score", score, last_position)?;
        validate_range("confidence", confidence, 1.0)?;
        if probabilities.len() != levels.len() {
            return Err(EACH_LEVEL.to_owned());
        }
        for &probability in &probabilities {
            validate_range("probability", probability, 1.0)?;
        }

        // of two equal probabilities, the lower level is the more likely
        let most_likely = (0..probabilities.len())
            .max_by(|&a, &b| {
                probabilities[a]
                    .total_cmp(&probabilities[b])
                    .then(b.cmp(&a))
            })
            .unwrap_or_default();
        let question = self;
        Ok(ScoreAnswer {
            question,
            score,
            confidence,
            probabilities,
            most_likely,
        })
    }

    fn validated(
        instructions: impl Serialize,
        levels: impl IntoIterator<Item = (Result<Box<RawValue>, InvalidJson>, L)>,
    ) -> Result<Self, InvalidScore> {
        let instructions = json::validate(instructions).map_err(InvalidScore::Instructions)?;
        let levels: Vec<_> = levels
            .into_iter()
            .enumerate()
            .map(|(index, (level, value))| match level {
                Ok(level) => Ok((level, value)),
                Err(error) => Err(InvalidScore::Level { index, error }),
            })
            .collect::<Result<_, _>>()?;
        if !(1..=MAX_LEVELS).contains(&levels.len()) {
            return Err(InvalidScore::Count(levels.len()));
        }
        let mut indexes = HashMap::new();
        for (second, (level, _)) in levels.iter().enumerate() {
            if let Some(first) = indexes.insert(level.get(), second) {
                return Err(InvalidScore::Duplicate { first, second });
            }
        }
        let instructions = Json::from(instructions);
        let levels = levels
            .into_iter()
            .map(|(level, value)| Entry {
                level: Json::from(level),
                value,
            })
            .collect();
        let levels = Table::Owned(levels);
        Ok(Score {
            instructions,
            levels,
        })
    }
}

#[doc(hidden)]
#[must_use]
pub const fn score<L>(instructions: Json, levels: fn() -> Vec<MacroLevel<L>>) -> Score<L> {
    let levels = Table::Deferred(levels);
    Score {
        instructions,
        levels,
    }
}

// the derive has validated the table, so only `of` validates it again
fn levels_of<L: Levels>() -> Vec<MacroLevel<L>> {
    L::LEVELS
        .iter()
        .map(|level| (level.level, (level.value)()))
        .collect()
}

impl<L> From<MacroLevel<L>> for Entry<L> {
    fn from((level, value): MacroLevel<L>) -> Self {
        let level = Json::String(Cow::Borrowed(level));
        Entry { level, value }
    }
}

impl<L> QuestionSet for Score<L> {
    type AnswerSet = ScoreAnswer<L>;
}

/// An error of a constructor of [`Score`].
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum InvalidScore {
    /// The instructions are not valid.
    #[error("the instructions {0}")]
    Instructions(InvalidJson),
    /// A level is not valid.
    #[error("the level at index {index} {error}")]
    Level {
        /// The index of the level, from 0.
        index: usize,
        /// The rule that the level breaks.
        error: InvalidJson,
    },
    /// The Score has no levels, or more than 10. The value is the number of levels.
    #[error("{}", score::count_message(*.0))]
    Count(usize),
    /// Two levels are the same.
    #[error("{}", score::duplicate_message(*.first, *.second))]
    Duplicate {
        /// The index of the first level, from 0.
        first: usize,
        /// The index of the second level, from 0.
        second: usize,
    },
}

/// The answer to a [`Score`]: the score, and the probability of each level.
///
/// Each method that gives probabilities gives pairs of a value and its probability. A method
/// that borrows gives `(&L, f64)`, and a method that consumes the answer gives `(L, f64)`. It
/// serializes as `{"score": s, "most_likely": level, "confidence": c, "levels": [level, …],
/// "probabilities": [p, …]}`, so a value needs no `Serialize`.
#[derive(Debug, Clone)]
pub struct ScoreAnswer<L> {
    question: Score<L>,
    score: f64,
    confidence: f64,
    probabilities: Vec<f64>,
    most_likely: usize,
}

impl<L> ScoreAnswer<L> {
    /// Returns the question of the answer.
    #[must_use]
    pub fn question(&self) -> &Score<L> {
        &self.question
    }

    /// Returns the question of the answer, with its values, so that code can ask it again.
    #[must_use]
    pub fn into_question(self) -> Score<L> {
        self.question
    }

    /// Returns the mean level, from 0 for the lowest level, as the API gives it.
    #[must_use]
    pub fn score(&self) -> f64 {
        self.score
    }

    /// Returns the value of the level with the highest probability.
    ///
    /// If two levels have equal probabilities, it is the lower level.
    #[must_use]
    pub fn most_likely(&self) -> &L {
        &self.question.levels.as_entries()[self.most_likely].value
    }

    /// Returns the value of the level with the highest probability, owned.
    ///
    /// If two levels have equal probabilities, it is the lower level.
    #[must_use]
    pub fn into_most_likely(self) -> L {
        let mut levels = self.question.levels.into_entries();
        levels.swap_remove(self.most_likely).value
    }

    /// Returns the confidence of the API in the score, from 0 to 1.
    #[must_use]
    pub fn confidence(&self) -> f64 {
        self.confidence
    }

    /// Returns each level and its probability, from the lowest level.
    pub fn probabilities(&self) -> impl ExactSizeIterator<Item = (&L, f64)> {
        self.question
            .levels
            .as_entries()
            .iter()
            .zip(&self.probabilities)
            .map(|(level, &probability)| (&level.value, probability))
    }

    /// Returns each level and its probability, owned, from the lowest level.
    #[must_use]
    pub fn into_probabilities(self) -> Vec<(L, f64)> {
        self.question
            .levels
            .into_entries()
            .into_iter()
            .zip(self.probabilities)
            .map(|(level, probability)| (level.value, probability))
            .collect()
    }
}

impl<L> Serialize for ScoreAnswer<L> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        // the levels as sent, so a value needs no `Serialize`
        let levels = self.question.levels.as_entries();
        let levels: Vec<_> = levels.iter().map(|l| &l.level).collect();
        let mut answer = serializer.serialize_struct("ScoreAnswer", 5)?;
        answer.serialize_field("score", &self.score)?;
        answer.serialize_field("most_likely", levels[self.most_likely])?;
        answer.serialize_field("confidence", &self.confidence)?;
        answer.serialize_field("levels", &levels)?;
        answer.serialize_field("probabilities", &self.probabilities)?;
        answer.end()
    }
}

#[derive(Serialize)]
#[serde(tag = "type", rename = "score")]
struct Question<'a, L> {
    instructions: &'a Json,
    #[serde(serialize_with = "criteria")]
    criteria: &'a [Entry<L>],
}

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
enum Answer {
    Score {
        score: f64,
        confidence: f64,
        probabilities: HashMap<String, f64>,
    },
}

impl<L> Sealed for Score<L> {
    fn write(&mut self, raw_question_set: &mut RawQuestionSet) {
        let instructions = &self.instructions;
        let criteria = self.levels.entries();
        raw_question_set.push(&Question {
            instructions,
            criteria,
        });
    }

    fn read(
        mut self,
        raw_answer_set: &mut RawAnswerSet,
    ) -> Result<<Self as QuestionSet>::AnswerSet, String> {
        let Answer::Score {
            score,
            confidence,
            mut probabilities,
        } = raw_answer_set.next()?;
        let levels = self.levels.entries();
        let count = probabilities.len();
        let probabilities = (0..levels.len())
            .map(|index| probabilities.remove(&index.to_string()))
            .collect::<Option<Vec<_>>>()
            .filter(|_| count == levels.len())
            .ok_or(EACH_LEVEL)?;
        self.validated_answer(score, confidence, probabilities)
    }
}

fn criteria<L, S: Serializer>(levels: &&[Entry<L>], serializer: S) -> Result<S::Ok, S::Error> {
    serializer.collect_seq(levels.iter().map(|l| &l.level))
}

#[cfg(test)]
mod tests {
    use super::{InvalidScore, Levels, Score, ScoreAnswer, ScoreLevel};
    use crate::InvalidJson;
    use crate::ask::wire::{RawAnswerSet, RawQuestionSet, Sealed};
    use serde::Serialize;
    use serde_json::{Value, json};

    fn serialized<L>(mut score: Score<L>) -> String {
        let mut raw_question_set = RawQuestionSet::default();
        score.write(&mut raw_question_set);
        raw_question_set.texts()[0].to_owned()
    }

    fn read<L>(score: Score<L>, answer: Value) -> Result<ScoreAnswer<L>, String> {
        score.read(&mut RawAnswerSet::of(vec![answer]))
    }

    fn answer(probabilities: &Value) -> Value {
        json!({
            "type": "score",
            "score": 1.3,
            "confidence": 0.4,
            "probabilities": probabilities,
            "legend": { "0": "A line.", "1": "A function.", "2": "A module." },
        })
    }

    // one type of level, so coverage sees each failure of `validated` and its success together
    fn numbered(count: usize) -> Vec<Value> {
        (0..count).map(|i| json!(format!("Level {i}."))).collect()
    }

    #[derive(Debug)]
    struct Severity;

    impl Levels for Severity {
        const LEVELS: &'static [ScoreLevel<Self>] = &[
            ScoreLevel {
                level: "Nothing breaks.",
                value: || Severity,
            },
            ScoreLevel {
                level: "Data is lost.",
                value: || Severity,
            },
        ];
    }

    fn sizes(probabilities: &Value) -> ScoreAnswer<&'static str> {
        let score = Score::new("How big?", ["A line.", "A function.", "A module."]).unwrap();
        read(score, answer(probabilities)).unwrap()
    }

    #[test]
    fn new_sends_the_levels_in_order() {
        let score = Score::new("How big?", ["A line.", "A function.", "A module."]).unwrap();

        assert_eq!(
            serialized(score),
            r#"{"type":"score","instructions":"How big?","criteria":["A line.","A function.","A module."]}"#
        );
    }

    #[test]
    fn with_values_sends_the_level_of_each_value() {
        #[derive(Serialize)]
        struct Span {
            unit: &'static str,
            count: u32,
        }

        let score =
            Score::with_values("How long?", [1, 5], |&count| Span { unit: "day", count }).unwrap();

        assert_eq!(
            serialized(score),
            r#"{"type":"score","instructions":"How long?","criteria":[{"unit":"day","count":1},{"unit":"day","count":5}]}"#
        );
    }

    #[test]
    fn of_sends_the_levels_of_the_type() {
        let score = Score::<Severity>::of("How severe?").unwrap();

        assert_eq!(
            serialized(score),
            r#"{"type":"score","instructions":"How severe?","criteria":["Nothing breaks.","Data is lost."]}"#
        );
    }

    #[test]
    fn of_refuses_a_bad_table() {
        #[derive(Debug)]
        struct Twice;
        impl Levels for Twice {
            const LEVELS: &'static [ScoreLevel<Self>] = &[
                ScoreLevel {
                    level: "Some.",
                    value: || Twice,
                },
                ScoreLevel {
                    level: "Some.",
                    value: || Twice,
                },
            ];
        }
        #[derive(Debug)]
        struct Blank;
        impl Levels for Blank {
            const LEVELS: &'static [ScoreLevel<Self>] = &[ScoreLevel {
                level: "",
                value: || Blank,
            }];
        }

        let cases = [
            (
                Score::<Twice>::of("How much?").unwrap_err(),
                "each level must be different, but the levels at index 0 and 1 are the same",
            ),
            (
                Score::<Blank>::of("How much?").unwrap_err(),
                "the level at index 0 must not be empty",
            ),
        ];
        for (error, message) in cases {
            assert_eq!(error.to_string(), message);
        }
    }

    #[test]
    fn new_refuses_bad_levels() {
        let cases = [
            (vec![], "a Score must have 1 to 10 levels, not 0"),
            (numbered(11), "a Score must have 1 to 10 levels, not 11"),
            (
                vec![json!("Some."), json!(" ")],
                "the level at index 1 must not be empty",
            ),
            (
                vec![json!("Some."), json!(null)],
                "the level at index 1 must not be empty",
            ),
            (
                vec![json!(1)],
                "the level at index 0 must be text, an object, or an array",
            ),
            (
                vec![json!("Some."), json!("More."), json!("Some.")],
                "each level must be different, but the levels at index 0 and 2 are the same",
            ),
            (
                vec![json!({ "at_least": 1 }), json!({ "at_least": 1 })],
                "each level must be different, but the levels at index 0 and 1 are the same",
            ),
        ];
        for (levels, message) in cases {
            let error = Score::new("How much?", levels).unwrap_err();
            assert_eq!(error.to_string(), message);
        }
    }

    #[test]
    fn new_takes_1_to_10_levels() {
        for count in [1, 10] {
            let score = Score::new("How much?", numbered(count));
            assert!(score.is_ok(), "{count}");
        }
    }

    #[test]
    fn constructors_refuse_bad_instructions() {
        let errors = [
            Score::new("", ["Some."]).unwrap_err(),
            Score::with_values(json!({}), [1], |_| "Some.").unwrap_err(),
            Score::<Severity>::of(json!([])).unwrap_err(),
        ];
        for error in errors {
            assert!(matches!(
                error,
                InvalidScore::Instructions(InvalidJson::Empty)
            ));
            assert_eq!(error.to_string(), "the instructions must not be empty");
        }
    }

    #[test]
    fn read_keeps_the_values_of_the_api() {
        let answer = sizes(&json!({ "0": 0.1, "1": 0.5, "2": 0.4 }));

        assert_eq!(answer.score(), 1.3);
        assert_eq!(answer.confidence(), 0.4);
        let probabilities: Vec<_> = answer.probabilities().collect();
        assert_eq!(
            probabilities,
            [
                (&"A line.", 0.1),
                (&"A function.", 0.5),
                (&"A module.", 0.4)
            ]
        );
        assert_eq!(answer.probabilities().len(), 3);
    }

    #[test]
    fn read_refuses_an_answer_that_does_not_fit() {
        let cases = [
            (
                json!({ "type": "noul", "noul": 0.5 }),
                "must answer each question: unknown variant `noul`, expected `score`",
            ),
            (
                answer(&json!({ "0": 0.5, "1": 0.5 })),
                "must give a probability for each level of the Score, and no other",
            ),
            (
                answer(&json!({ "0": 0.2, "1": 0.4, "3": 0.4 })),
                "must give a probability for each level of the Score, and no other",
            ),
            (
                answer(&json!({ "0": 0.2, "1": 0.4, "2": 0.2, "3": 0.2 })),
                "must give a probability for each level of the Score, and no other",
            ),
            (
                json!({
                    "type": "score",
                    "score": 2.5,
                    "confidence": 0.4,
                    "probabilities": { "0": 0.2, "1": 0.4, "2": 0.4 },
                }),
                "must give a score from 0 to 2, not 2.5",
            ),
            (
                json!({
                    "type": "score",
                    "score": 1.3,
                    "confidence": -0.4,
                    "probabilities": { "0": 0.2, "1": 0.4, "2": 0.4 },
                }),
                "must give a confidence from 0 to 1, not -0.4",
            ),
            (
                answer(&json!({ "2": -0.4, "1": 1.2, "0": 0.2 })),
                "must give a probability from 0 to 1, not 1.2",
            ),
        ];
        for (json, message) in cases {
            let score = Score::new("How big?", ["A line.", "A function.", "A module."]).unwrap();
            assert_eq!(read(score, json).unwrap_err(), message);
        }
    }

    #[test]
    fn most_likely_takes_the_highest_probability_then_the_lower_level() {
        let cases = [
            (json!({ "0": 0.0, "1": 0.0, "2": 1.0 }), "A module."),
            (json!({ "0": 0.0, "1": 0.5, "2": 0.5 }), "A function."),
            (json!({ "0": 0.4, "1": 0.2, "2": 0.4 }), "A line."),
        ];
        for (probabilities, level) in cases {
            assert_eq!(
                *sizes(&probabilities).most_likely(),
                level,
                "{probabilities}"
            );
        }
    }

    #[test]
    fn serialize_gives_the_levels_and_the_probabilities_in_order() {
        // not `Serialize`, so the answer writes the levels as they were sent
        struct Days(u32);
        #[derive(Serialize)]
        struct Span {
            unit: &'static str,
            count: u32,
        }
        let days = [Days(1), Days(5), Days(20)];
        let score = Score::with_values("How long?", days, |d| Span {
            unit: "day",
            count: d.0,
        })
        .unwrap();
        let probabilities = json!({ "0": 0.1, "1": 0.5, "2": 0.4 });
        let answer = read(score, answer(&probabilities)).unwrap();

        assert_eq!(
            serde_json::to_string(&answer).unwrap(),
            concat!(
                r#"{"score":1.3,"most_likely":{"unit":"day","count":5},"confidence":0.4,"#,
                r#""levels":[{"unit":"day","count":1},{"unit":"day","count":5},"#,
                r#"{"unit":"day","count":20}],"probabilities":[0.1,0.5,0.4]}"#,
            )
        );
    }

    #[test]
    fn into_methods_give_the_values_back() {
        let probabilities = json!({ "0": 0.1, "1": 0.5, "2": 0.4 });

        assert_eq!(sizes(&probabilities).into_most_likely(), "A function.");
        assert_eq!(
            sizes(&probabilities).into_probabilities(),
            [("A line.", 0.1), ("A function.", 0.5), ("A module.", 0.4)]
        );

        let question = serialized(sizes(&probabilities).into_question());
        assert_eq!(
            serialized(sizes(&probabilities).question().clone()),
            question
        );
        assert!(question.contains(r#""instructions":"How big?""#));
    }
}