jevrs-core 0.1.1

Portable sans-I/O types, builders, and codecs for the Jev API
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
use alloc::{string::String, vec, vec::Vec};
use core::{
    fmt,
    marker::PhantomData,
    sync::atomic::{AtomicU64, Ordering},
};

use serde::{
    Serialize, Serializer,
    ser::{SerializeMap, SerializeStruct},
};

use crate::{
    ChoiceQ, DynChoiceQ, DynLevels, DynOptions, DynScoreQ, Error, Instructions, Levels, Model,
    NoulQ, Options, Question, ScoreQ,
    response::{
        AnswerSlot, Decoder, WireAnswer, decode_dynamic_choice, decode_dynamic_score, decode_noul,
        decode_static_choice, decode_static_score,
    },
};

static NEXT_BATCH_ID: AtomicU64 = AtomicU64::new(1);

/// Identifies the question batch that created a typed handle.
///
/// It appears only in debug output or a mismatched handle panic; answer lookup
/// checks it automatically.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct BatchId(u64);

/// A typed reference to one question in a [`Questions`] batch.
///
/// Keep the handle returned by a builder method, then pass it to
/// [`Answers::get`](crate::Answers::get) after evaluation. The marker `Q`
/// selects the answer type at compile time. Passing a handle from another
/// batch is a caller error and panics when the answer is retrieved.
pub struct Handle<Q: Question> {
    pub(crate) idx: u32,
    pub(crate) batch: BatchId,
    _q: PhantomData<Q>,
}

impl<Q: Question> Copy for Handle<Q> {}

impl<Q: Question> Clone for Handle<Q> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Q: Question> fmt::Debug for Handle<Q> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Handle")
            .field("idx", &self.idx)
            .field("batch", &self.batch)
            .finish()
    }
}

/// An insertion-ordered collection of questions sent in one Jev request.
///
/// Use the returned handles to retrieve typed answers after decoding. Dynamic
/// methods validate raw criteria and fill the question ID in
/// [`Error::InvalidCriteria`]; use [`DynOptions`] or [`DynLevels`] to validate
/// once up front and reuse them.
///
/// ```
/// use jevrs_core::Questions;
///
/// let mut questions = Questions::new();
/// let urgent = questions.noul_with(
///     "is_urgent",
///     "Does this convey urgency?",
///     "Explicitly time-sensitive",
///     "No urgency expressed",
/// )?;
/// let department = questions.choice_dyn(
///     "department",
///     "Which team should handle this?",
///     [
///         ("billing", Some("Payments, invoicing, refunds")),
///         ("technical", Some("Bugs, outages, integrations")),
///         ("sales", None),
///     ],
/// )?;
/// let frustration = questions.score_dyn(
///     "frustration",
///     "How frustrated is the customer?",
///     ["Calm", "Frustrated", "Very angry"],
/// )?;
///
/// assert_eq!(questions.len(), 3);
/// let _ = (urgent, department, frustration);
/// # Ok::<(), jevrs_core::Error>(())
/// ```
pub struct Questions {
    pub(crate) entries: Vec<QuestionEntry>,
    pub(crate) batch: BatchId,
}

impl Questions {
    /// Starts a batch when questions will be added individually at runtime.
    ///
    /// Use [`QuestionSet`](crate::QuestionSet) instead when the whole batch is
    /// fixed at compile time.
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            batch: BatchId(NEXT_BATCH_ID.fetch_add(1, Ordering::Relaxed)),
        }
    }

    /// Adds a yes/no question when the instruction alone defines both outcomes.
    ///
    /// Use [`Self::noul_with`] when explicit yes and no criteria improve the
    /// decision boundary.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DuplicateId`] if `id` is already in this batch.
    pub fn noul(
        &mut self,
        id: impl Into<String>,
        instructions: impl Into<Instructions>,
    ) -> Result<Handle<NoulQ>, Error> {
        self.insert(id.into(), instructions.into(), "noul", None, decode_noul)
    }

    /// Adds a yes/no question when both outcomes need explicit descriptions.
    ///
    /// Use [`Self::noul`] for a simpler instruction-only question.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DuplicateId`] if `id` is already in this batch.
    pub fn noul_with(
        &mut self,
        id: impl Into<String>,
        instructions: impl Into<Instructions>,
        yes: &str,
        no: &str,
    ) -> Result<Handle<NoulQ>, Error> {
        let criteria = ChoiceCriteria(vec![
            ("true".into(), Some(yes.into())),
            ("false".into(), Some(no.into())),
        ]);
        self.insert(
            id.into(),
            instructions.into(),
            "noul",
            Some(Criteria::Map(criteria)),
            decode_noul,
        )
    }

    /// Adds a choice question whose [`Options`] are known at compile time.
    ///
    /// Use [`Self::choice_dyn`] when option keys come from configuration or a
    /// database.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DuplicateId`] if `id` is already in this batch.
    pub fn choice<O: Options>(
        &mut self,
        id: impl Into<String>,
        instructions: impl Into<Instructions>,
    ) -> Result<Handle<ChoiceQ<O>>, Error> {
        let () = O::COUNT_OK;
        let criteria = ChoiceCriteria(
            O::all()
                .iter()
                .map(|option| (option.key().into(), option.description().map(String::from)))
                .collect(),
        );
        self.insert(
            id.into(),
            instructions.into(),
            "choice",
            Some(Criteria::Map(criteria)),
            decode_static_choice::<O>,
        )
    }

    /// Adds a score question whose ordered [`Levels`] are known at compile time.
    ///
    /// Use [`Self::score_dyn`] when level descriptions are runtime data.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DuplicateId`] if `id` is already in this batch.
    pub fn score<L: Levels>(
        &mut self,
        id: impl Into<String>,
        instructions: impl Into<Instructions>,
    ) -> Result<Handle<ScoreQ<L>>, Error> {
        let () = L::COUNT_OK;
        let criteria = L::all()
            .iter()
            .map(|level| level.description().into())
            .collect();
        self.insert(
            id.into(),
            instructions.into(),
            "score",
            Some(Criteria::Levels(criteria)),
            decode_static_score::<L>,
        )
    }

    /// Adds a choice question backed by runtime-defined [`DynOptions`].
    ///
    /// Use this for options loaded from configuration or a database. Prefer
    /// [`Self::choice`] when an enum can represent the choices.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidCriteria`] when the options are invalid, with
    /// its `id` set to this question's ID. Returns [`Error::DuplicateId`] if
    /// `id` is already in this batch.
    pub fn choice_dyn<K, D, I>(
        &mut self,
        id: impl Into<String>,
        instructions: impl Into<Instructions>,
        options: I,
    ) -> Result<Handle<DynChoiceQ>, Error>
    where
        K: Into<String>,
        D: Into<String>,
        I: IntoIterator<Item = (K, Option<D>)>,
    {
        let id = id.into();
        let options = criteria_for_question(DynOptions::new(options), &id)?;
        let criteria = ChoiceCriteria(options.into_iter().collect());
        self.insert(
            id,
            instructions.into(),
            "choice",
            Some(Criteria::Map(criteria)),
            decode_dynamic_choice,
        )
    }

    /// Adds a score question backed by runtime-defined [`DynLevels`].
    ///
    /// Use this for a scale loaded at runtime. Prefer [`Self::score`] when an
    /// enum can represent the ordered levels.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidCriteria`] when the levels are invalid, with its
    /// `id` set to this question's ID. Returns [`Error::DuplicateId`] if `id`
    /// is already in this batch.
    pub fn score_dyn<S: Into<String>>(
        &mut self,
        id: impl Into<String>,
        instructions: impl Into<Instructions>,
        levels: impl IntoIterator<Item = S>,
    ) -> Result<Handle<DynScoreQ>, Error> {
        let id = id.into();
        let levels = criteria_for_question(DynLevels::new(levels), &id)?;
        self.insert(
            id,
            instructions.into(),
            "score",
            Some(Criteria::Levels(levels.into_iter().collect())),
            decode_dynamic_score,
        )
    }

    /// Returns the number of questions, for validating or reporting a batch.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Reports whether [`encode`] would reject this batch as empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    #[allow(clippy::cast_possible_truncation)]
    fn insert<Q: Question>(
        &mut self,
        id: String,
        instructions: Instructions,
        question_type: &'static str,
        criteria: Option<Criteria>,
        decoder: Decoder,
    ) -> Result<Handle<Q>, Error> {
        if self.entries.iter().any(|entry| entry.id == id) {
            return Err(Error::DuplicateId(id));
        }
        let handle = Handle {
            idx: self.entries.len() as u32,
            batch: self.batch,
            _q: PhantomData,
        };
        self.entries.push(QuestionEntry {
            id,
            instructions,
            question_type,
            criteria,
            decoder,
        });
        Ok(handle)
    }
}

fn criteria_for_question<T>(criteria: Result<T, Error>, id: &str) -> Result<T, Error> {
    criteria.map_err(|error| match error {
        Error::InvalidCriteria { reason, .. } => Error::InvalidCriteria {
            id: Some(id.into()),
            reason,
        },
        other => other,
    })
}

impl Default for Questions {
    fn default() -> Self {
        Self::new()
    }
}

/// Encodes a Jev request body without performing network I/O.
///
/// Use this at the boundary to a custom HTTP implementation. Pair it with
/// [`crate::decode`] for successful responses and [`crate::classify`] for
/// unsuccessful statuses.
///
/// ```
/// use jevrs_core::{Model, Questions, encode};
///
/// let mut questions = Questions::new();
/// questions.noul("is_urgent", "Does this convey urgency?")?;
/// let body = encode(
///     &Model::LATEST,
///     &"Help! My payouts have been failing for 3 days.",
///     &questions,
/// )?;
/// assert!(!body.is_empty());
/// # Ok::<(), jevrs_core::Error>(())
/// ```
///
/// # Errors
///
/// Returns [`Error::NoQuestions`] for an empty builder or [`Error::Json`] if
/// `state` cannot be serialized.
pub fn encode(
    model: &Model,
    state: &impl Serialize,
    questions: &Questions,
) -> Result<Vec<u8>, Error> {
    if questions.is_empty() {
        return Err(Error::NoQuestions);
    }
    serde_json::to_vec(&WireRequest {
        state,
        model,
        questions: WireQuestions(questions),
    })
    .map_err(Error::from)
}

pub(crate) struct WireRequest<'a, S> {
    state: &'a S,
    model: &'a Model,
    questions: WireQuestions<'a>,
}

impl<S: Serialize> Serialize for WireRequest<'_, S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: Serializer,
    {
        let mut request = serializer.serialize_struct("Request", 3)?;
        request.serialize_field("state", self.state)?;
        request.serialize_field("model", self.model)?;
        request.serialize_field("questions", &self.questions)?;
        request.end()
    }
}

pub(crate) struct WireQuestions<'a>(&'a Questions);

impl Serialize for WireQuestions<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut questions = serializer.serialize_map(Some(self.0.entries.len()))?;
        for entry in &self.0.entries {
            questions.serialize_entry(&entry.id, &WireQuestion(entry))?;
        }
        questions.end()
    }
}

pub(crate) struct WireQuestion<'a>(&'a QuestionEntry);

impl Serialize for WireQuestion<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let field_count = if self.0.criteria.is_some() { 3 } else { 2 };
        let mut question = serializer.serialize_struct("Question", field_count)?;
        question.serialize_field("type", self.0.question_type)?;
        question.serialize_field("instructions", &self.0.instructions)?;
        if let Some(criteria) = &self.0.criteria {
            question.serialize_field("criteria", criteria)?;
        }
        question.end()
    }
}

pub(crate) struct QuestionEntry {
    pub(crate) id: String,
    instructions: Instructions,
    question_type: &'static str,
    criteria: Option<Criteria>,
    decoder: Decoder,
}

impl QuestionEntry {
    pub(crate) fn decode(&self, answer: WireAnswer) -> Result<AnswerSlot, Error> {
        (self.decoder)(&self.id, self.criteria.as_ref(), answer)
    }
}

pub(crate) enum Criteria {
    Map(ChoiceCriteria),
    Levels(Vec<String>),
}

impl Serialize for Criteria {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Map(criteria) => criteria.serialize(serializer),
            Self::Levels(criteria) => criteria.serialize(serializer),
        }
    }
}

pub(crate) struct ChoiceCriteria(pub(crate) Vec<(String, Option<String>)>);

impl Serialize for ChoiceCriteria {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut criteria = serializer.serialize_map(Some(self.0.len()))?;
        for (key, description) in &self.0 {
            criteria.serialize_entry(key, description)?;
        }
        criteria.end()
    }
}

#[cfg(test)]
mod tests {
    use alloc::{
        format,
        string::{String, ToString},
        vec,
        vec::Vec,
    };

    use serde_json::{Value, json};

    use super::{Handle, Questions, encode};
    use crate::{
        DynLevels, DynOptions, Error, Model, NoulQ, Question,
        options::{
            LEVELS_TOO_FEW, LEVELS_TOO_MANY, OPTION_KEY_DUPLICATE, OPTION_KEY_EMPTY,
            OPTIONS_TOO_FEW, OPTIONS_TOO_MANY,
        },
        test_support::{Dept, Frustration},
    };

    struct NotDebugQ;

    impl Question for NotDebugQ {
        type Answer = ();
    }

    fn encoded_value(state: &impl serde::Serialize, questions: &Questions) -> Value {
        serde_json::from_slice(&encode(&Model::LATEST, state, questions).unwrap()).unwrap()
    }

    #[test]
    fn triage_request_matches_the_spec() {
        let mut questions = Questions::new();
        questions
            .noul_with(
                "is_urgent",
                "Does this convey urgency?",
                "Explicitly time-sensitive",
                "No urgency expressed",
            )
            .unwrap();
        questions
            .choice::<Dept>("department", "Which team should handle this?")
            .unwrap();
        questions
            .score::<Frustration>("frustration", "How frustrated is the customer?")
            .unwrap();

        assert_eq!(
            encoded_value(
                &"Help! My payouts have been failing for 3 days.",
                &questions
            ),
            json!({
                "state": "Help! My payouts have been failing for 3 days.",
                "model": "jev-latest",
                "questions": {
                    "is_urgent": {
                        "type": "noul",
                        "instructions": "Does this convey urgency?",
                        "criteria": {
                            "true": "Explicitly time-sensitive",
                            "false": "No urgency expressed"
                        }
                    },
                    "department": {
                        "type": "choice",
                        "instructions": "Which team should handle this?",
                        "criteria": {
                            "billing": "Payments, invoicing, refunds",
                            "technical": "Bugs, outages, integrations",
                            "sales": null
                        }
                    },
                    "frustration": {
                        "type": "score",
                        "instructions": "How frustrated is the customer?",
                        "criteria": ["Calm", "Frustrated", "Very angry"]
                    }
                }
            })
        );
    }

    #[test]
    fn noul_omits_or_emits_criteria_as_requested() {
        let mut plain = Questions::new();
        plain.noul("urgent", "Is this urgent?").unwrap();
        assert_eq!(
            encoded_value(&"state", &plain)["questions"]["urgent"],
            json!({"type": "noul", "instructions": "Is this urgent?"})
        );

        let mut described = Questions::new();
        described
            .noul_with("urgent", "Is this urgent?", "Urgent", "Not urgent")
            .unwrap();
        assert_eq!(
            encoded_value(&"state", &described)["questions"]["urgent"]["criteria"],
            json!({"true": "Urgent", "false": "Not urgent"})
        );
    }

    #[test]
    fn structured_instructions_encode_verbatim() {
        let object = json!({"task": "Assess urgency", "signals": ["deadline"]});
        let array = json!(["Choose a team", {"prefer": "billing"}]);
        let mut questions = Questions::new();
        questions.noul("urgent", object.clone()).unwrap();
        questions
            .choice_dyn(
                "department",
                array.clone(),
                DynOptions::new([("billing", None::<&str>), ("sales", None)]).unwrap(),
            )
            .unwrap();

        let encoded = encoded_value(&"state", &questions);
        assert_eq!(encoded["questions"]["urgent"]["instructions"], object);
        assert_eq!(encoded["questions"]["department"]["instructions"], array);
    }

    #[test]
    fn dynamic_questions_encode_their_criteria() {
        let mut questions = Questions::new();
        questions
            .choice_dyn(
                "department",
                "Choose a team",
                [("billing", Some("Payments")), ("sales", None)],
            )
            .unwrap();
        questions
            .score_dyn("frustration", "Rate frustration", ["Calm", "Angry"])
            .unwrap();

        let value = encoded_value(&"state", &questions);
        assert_eq!(
            value["questions"]["department"]["criteria"],
            json!({"billing": "Payments", "sales": null})
        );
        assert_eq!(
            value["questions"]["frustration"]["criteria"],
            json!(["Calm", "Angry"])
        );
    }

    #[test]
    fn dynamic_questions_accept_owned_and_prevalidated_criteria() {
        let mut questions = Questions::new();
        let owned: Vec<(String, Option<String>)> = vec![
            (String::from("billing"), Some(String::from("Payments"))),
            (String::from("sales"), None),
        ];
        questions
            .choice_dyn("owned", "Choose a team", owned)
            .unwrap();

        let options = DynOptions::new([("technical", Some("Bugs"))]).unwrap();
        questions
            .choice_dyn("prevalidated_choice", "Choose a team", options)
            .unwrap();
        let levels = DynLevels::new(["Calm", "Angry"]).unwrap();
        questions
            .score_dyn("prevalidated_score", "Rate frustration", levels)
            .unwrap();

        assert_eq!(questions.len(), 3);
    }

    fn assert_invalid_criteria(error: Error, expected_id: &str, expected_reason: &'static str) {
        match error {
            Error::InvalidCriteria { id, reason } => {
                assert_eq!(id.as_deref(), Some(expected_id));
                assert_eq!(reason, expected_reason);
            }
            other => panic!("unexpected error: {other}"),
        }
    }

    #[test]
    fn dynamic_questions_report_invalid_criteria_without_adding_entries() {
        let mut questions = Questions::new();
        questions.noul("existing", "Existing question").unwrap();

        let empty: Vec<(&str, Option<&str>)> = Vec::new();
        let error = questions
            .choice_dyn("empty_options", "Choose", empty)
            .unwrap_err();
        assert_invalid_criteria(error, "empty_options", OPTIONS_TOO_FEW);
        assert_eq!(questions.len(), 1);

        let error = questions
            .choice_dyn("empty_key", "Choose", [("", None::<&str>)])
            .unwrap_err();
        assert_invalid_criteria(error, "empty_key", OPTION_KEY_EMPTY);
        assert_eq!(questions.len(), 1);

        let error = questions
            .choice_dyn(
                "duplicate_key",
                "Choose",
                [("billing", None::<&str>), ("billing", None)],
            )
            .unwrap_err();
        assert_invalid_criteria(error, "duplicate_key", OPTION_KEY_DUPLICATE);
        assert_eq!(questions.len(), 1);

        let too_many = (0_u16..256)
            .map(|index| (index.to_string(), None::<String>))
            .collect::<Vec<_>>();
        let error = questions
            .choice_dyn("too_many_options", "Choose", too_many)
            .unwrap_err();
        assert_invalid_criteria(error, "too_many_options", OPTIONS_TOO_MANY);
        assert_eq!(questions.len(), 1);

        let error = questions
            .score_dyn("one_level", "Rate", ["only"])
            .unwrap_err();
        assert_invalid_criteria(error, "one_level", LEVELS_TOO_FEW);
        assert_eq!(questions.len(), 1);

        let error = questions
            .score_dyn("eleven_levels", "Rate", ["level"; 11])
            .unwrap_err();
        assert_invalid_criteria(error, "eleven_levels", LEVELS_TOO_MANY);
        assert_eq!(questions.len(), 1);
    }

    #[test]
    fn state_accepts_string_object_and_array() {
        let mut questions = Questions::new();
        questions.noul("urgent", "Is this urgent?").unwrap();

        assert_eq!(encoded_value(&"text", &questions)["state"], json!("text"));
        assert_eq!(
            encoded_value(&json!({"message": "text"}), &questions)["state"],
            json!({"message": "text"})
        );
        assert_eq!(
            encoded_value(&json!(["first", "second"]), &questions)["state"],
            json!(["first", "second"])
        );
    }

    #[test]
    fn duplicate_ids_are_rejected_without_adding_an_entry() {
        let mut questions = Questions::new();
        questions.noul("urgent", "First").unwrap();
        let error = questions.noul("urgent", "Second").err().unwrap();
        assert!(matches!(error, Error::DuplicateId(id) if id == "urgent"));
        assert_eq!(questions.len(), 1);
    }

    #[test]
    fn empty_batches_are_rejected_at_encode_time() {
        assert!(matches!(
            encode(&Model::LATEST, &"state", &Questions::new()),
            Err(Error::NoQuestions)
        ));
    }

    #[test]
    fn builders_have_distinct_batch_ids() {
        let mut first = Questions::new();
        let first_handle = first.noul("first", "First").unwrap();
        let mut second = Questions::new();
        let second_handle = second.noul("second", "Second").unwrap();
        assert_ne!(first_handle.batch, second_handle.batch);
    }

    #[test]
    fn handles_are_copy_and_debug_without_marker_bounds() {
        fn assert_copy<T: Copy>() {}
        fn assert_debug<T: core::fmt::Debug>() {}

        assert_copy::<Handle<NoulQ>>();
        assert_debug::<Handle<NotDebugQ>>();

        let mut questions = Questions::new();
        let handle = questions.noul("urgent", "Is this urgent?").unwrap();
        let debug = format!("{handle:?}");
        assert!(debug.contains("idx: 0"));
        assert!(debug.contains("batch: BatchId("));
    }

    #[test]
    fn choice_criteria_keep_option_order_on_the_wire() {
        let mut questions = Questions::new();
        questions
            .choice::<Dept>("department", "Choose a team")
            .unwrap();
        let json =
            String::from_utf8(encode(&Model::LATEST, &"state", &questions).unwrap()).unwrap();
        let billing = json.find("billing").unwrap();
        let technical = json.find("technical").unwrap();
        let sales = json.find("sales").unwrap();
        assert!(billing < technical && technical < sales);
    }
}