Skip to main content

jev/
question.rs

1//! `Question`, `Questions`, and the validating builder.
2
3use indexmap::IndexMap;
4use serde::Serialize;
5
6use crate::{error::Error, guidance::Guidance};
7
8/// Minimum number of questions in a request.
9pub const MIN_QUESTIONS: usize = 1;
10/// Maximum number of questions in a request.
11pub const MAX_QUESTIONS: usize = 64;
12/// Maximum length, in bytes, of a question or option key.
13pub const MAX_KEY_BYTES: usize = 64;
14/// Maximum length, in bytes, of a single guidance string (`instructions` or one
15/// criterion).
16pub const MAX_GUIDANCE_BYTES: usize = 4096;
17/// Minimum number of options in a `choice` question.
18pub const MIN_CHOICE_OPTIONS: usize = 2;
19/// Maximum number of options in a `choice` question.
20pub const MAX_CHOICE_OPTIONS: usize = 64;
21/// Minimum number of levels in a `score` question.
22pub const MIN_SCORE_LEVELS: usize = 2;
23/// Maximum number of levels in a `score` question.
24pub const MAX_SCORE_LEVELS: usize = 32;
25
26/// One question sent to the model: `noul`, `choice`, or `score`.
27///
28/// See the crate-level documentation for the three primitives. Construct these
29/// through [`Questions::builder`] (validated) or `#[derive(Decision)]` (validated at
30/// compile time); there is no public unchecked constructor.
31#[derive(Debug, Clone, PartialEq, Serialize)]
32#[serde(tag = "type", rename_all = "snake_case")]
33pub enum Question {
34    /// A yes/no question. `criteria` is optional: the schema requires only `type` and
35    /// `instructions`.
36    Noul {
37        /// What to ask the model.
38        instructions: Guidance,
39        /// Optional per-branch criteria clarifying what counts as "true" or "false".
40        #[serde(skip_serializing_if = "Option::is_none")]
41        criteria: Option<NoulCriteria>,
42    },
43    /// A single-select question over a fixed, ordered option set.
44    Choice {
45        /// What to ask the model.
46        instructions: Guidance,
47        /// Wire key -> criteria, in declaration order.
48        criteria: IndexMap<String, Guidance>,
49    },
50    /// A question that places the state on an ordered scale.
51    Score {
52        /// What to ask the model.
53        instructions: Guidance,
54        /// One criterion per level, lowest first.
55        criteria: Vec<Guidance>,
56    },
57}
58
59impl Question {
60    /// The question's `instructions` guidance, common to all three primitives.
61    #[must_use]
62    pub fn instructions(&self) -> &Guidance {
63        match self {
64            Question::Noul { instructions, .. }
65            | Question::Choice { instructions, .. }
66            | Question::Score { instructions, .. } => instructions,
67        }
68    }
69
70    /// The wire name of this question's primitive: `"noul"`, `"choice"`, or `"score"`.
71    #[must_use]
72    pub fn kind(&self) -> &'static str {
73        match self {
74            Question::Noul { .. } => "noul",
75            Question::Choice { .. } => "choice",
76            Question::Score { .. } => "score",
77        }
78    }
79}
80
81/// The `"true"`/`"false"` criteria pair for a [`Question::Noul`].
82#[derive(Debug, Clone, PartialEq, Serialize)]
83pub struct NoulCriteria {
84    /// Criterion describing what counts as "yes".
85    #[serde(rename = "true")]
86    pub r#true: Guidance,
87    /// Criterion describing what counts as "no".
88    #[serde(rename = "false")]
89    pub r#false: Guidance,
90}
91
92/// An ordered map of question key to [`Question`].
93///
94/// Ordering is preserved (backed by [`indexmap::IndexMap`]) so request payloads are
95/// stable and byte-comparable in tests, and so score legends and probabilities read
96/// back in their natural order.
97///
98/// # Examples
99///
100/// ```
101/// use jev::Questions;
102///
103/// let questions = Questions::builder()
104///     .noul("refund", "Is the customer asking for money back?")
105///     .build()
106///     .unwrap();
107/// assert_eq!(questions.len(), 1);
108/// ```
109#[derive(Debug, Clone, Default, Serialize, PartialEq)]
110pub struct Questions(IndexMap<String, Question>);
111
112impl Questions {
113    /// Starts a validating builder.
114    #[must_use]
115    pub fn builder() -> QuestionsBuilder {
116        QuestionsBuilder::default()
117    }
118
119    /// The number of questions.
120    #[must_use]
121    pub fn len(&self) -> usize {
122        self.0.len()
123    }
124
125    /// Whether there are no questions.
126    #[must_use]
127    pub fn is_empty(&self) -> bool {
128        self.0.is_empty()
129    }
130
131    /// Looks up a question by key.
132    #[must_use]
133    pub fn get(&self, key: &str) -> Option<&Question> {
134        self.0.get(key)
135    }
136
137    /// Iterates questions in declaration order.
138    #[must_use]
139    pub fn iter(&self) -> indexmap::map::Iter<'_, String, Question> {
140        self.0.iter()
141    }
142
143    /// Builds a `Questions` from already-validated entries without re-running the
144    /// [`QuestionsBuilder::build`] checks.
145    ///
146    /// This exists solely for `#[derive(Decision)]`, which performs the equivalent
147    /// validation at compile time (key charset, guidance non-emptiness, duplicate
148    /// keys) using `syn`/`quote` over literal strings, so re-validating at runtime
149    /// on every process start would be pure overhead. It is not part of the public
150    /// API surface for hand-written callers, who should use [`Questions::builder`].
151    #[doc(hidden)]
152    #[must_use]
153    pub fn from_validated_entries(entries: Vec<(String, Question)>) -> Self {
154        Questions(entries.into_iter().collect())
155    }
156}
157
158impl<'a> IntoIterator for &'a Questions {
159    type Item = (&'a String, &'a Question);
160    type IntoIter = indexmap::map::Iter<'a, String, Question>;
161
162    fn into_iter(self) -> Self::IntoIter {
163        self.0.iter()
164    }
165}
166
167/// Validating builder for [`Questions`], the config-driven / dynamic-question path.
168///
169/// Every terminal invariant documented on [`Questions`] is enforced in [`Self::build`],
170/// not on each call, so calls can be chained freely before the single fallible step.
171///
172/// # Examples
173///
174/// ```
175/// use jev::Questions;
176///
177/// let questions = Questions::builder()
178///     .noul("refund", "Is the customer asking for money back?")
179///     .noul_with(
180///         "is_bug",
181///         "Is the customer reporting a defect?",
182///         "Describes broken behavior.",
183///         "Asks a question or requests a feature.",
184///     )
185///     .choice(
186///         "team",
187///         "Which team should own this?",
188///         [
189///             ("payments", "Checkout, billing, or payments."),
190///             ("frontend", "Rendering or browser issues."),
191///         ],
192///     )
193///     .score("urgency", "How urgent is this?", ["Can wait", "This week", "Blocking revenue"])
194///     .build()
195///     .unwrap();
196/// assert_eq!(questions.len(), 4);
197/// ```
198#[derive(Debug, Default)]
199pub struct QuestionsBuilder {
200    entries: Vec<(String, Question)>,
201}
202
203impl QuestionsBuilder {
204    /// Adds a `noul` question with no explicit branch criteria.
205    #[must_use]
206    pub fn noul(mut self, key: impl Into<String>, instructions: impl Into<Guidance>) -> Self {
207        self.entries.push((
208            key.into(),
209            Question::Noul {
210                instructions: instructions.into(),
211                criteria: None,
212            },
213        ));
214        self
215    }
216
217    /// Adds a `noul` question with explicit "yes" and "no" criteria.
218    #[must_use]
219    pub fn noul_with(
220        mut self,
221        key: impl Into<String>,
222        instructions: impl Into<Guidance>,
223        yes: impl Into<Guidance>,
224        no: impl Into<Guidance>,
225    ) -> Self {
226        self.entries.push((
227            key.into(),
228            Question::Noul {
229                instructions: instructions.into(),
230                criteria: Some(NoulCriteria {
231                    r#true: yes.into(),
232                    r#false: no.into(),
233                }),
234            },
235        ));
236        self
237    }
238
239    /// Adds a `choice` question over the given `(option_key, criteria)` pairs, in order.
240    #[must_use]
241    pub fn choice<K, G>(
242        mut self,
243        key: impl Into<String>,
244        instructions: impl Into<Guidance>,
245        options: impl IntoIterator<Item = (K, G)>,
246    ) -> Self
247    where
248        K: Into<String>,
249        G: Into<Guidance>,
250    {
251        let criteria: IndexMap<String, Guidance> = options
252            .into_iter()
253            .map(|(k, g)| (k.into(), g.into()))
254            .collect();
255        self.entries.push((
256            key.into(),
257            Question::Choice {
258                instructions: instructions.into(),
259                criteria,
260            },
261        ));
262        self
263    }
264
265    /// Adds a `score` question over the given levels, lowest first.
266    #[must_use]
267    pub fn score<G: Into<Guidance>>(
268        mut self,
269        key: impl Into<String>,
270        instructions: impl Into<Guidance>,
271        levels: impl IntoIterator<Item = G>,
272    ) -> Self {
273        let criteria: Vec<Guidance> = levels.into_iter().map(Into::into).collect();
274        self.entries.push((
275            key.into(),
276            Question::Score {
277                instructions: instructions.into(),
278                criteria,
279            },
280        ));
281        self
282    }
283
284    /// Validates every accumulated question and produces a [`Questions`].
285    ///
286    /// # Errors
287    ///
288    /// Returns [`Error::Invalid`] on the first invariant violated, in declaration
289    /// order: question count, duplicate keys, key charset, guidance length/emptiness,
290    /// `choice` option count/charset, and `score` level count.
291    pub fn build(self) -> Result<Questions, Error> {
292        let count = self.entries.len();
293        if !(MIN_QUESTIONS..=MAX_QUESTIONS).contains(&count) {
294            return Err(Error::Invalid {
295                field: "questions".to_string(),
296                reason: format!(
297                    "expected {MIN_QUESTIONS}..={MAX_QUESTIONS} questions, got {count}"
298                ),
299            });
300        }
301
302        let mut map: IndexMap<String, Question> = IndexMap::with_capacity(count);
303        for (key, question) in self.entries {
304            validate_key("question key", &key, false)?;
305            validate_question(&key, &question)?;
306            if map.insert(key.clone(), question).is_some() {
307                return Err(Error::Invalid {
308                    field: "questions".to_string(),
309                    reason: format!("duplicate question key `{key}`"),
310                });
311            }
312        }
313
314        Ok(Questions(map))
315    }
316}
317
318/// Validates one question's instructions and, for `choice`/`score`, its criteria set.
319fn validate_question(key: &str, question: &Question) -> Result<(), Error> {
320    validate_guidance(
321        &format!("questions.{key}.instructions"),
322        question.instructions(),
323    )?;
324
325    match question {
326        Question::Noul { criteria, .. } => {
327            if let Some(NoulCriteria { r#true, r#false }) = criteria {
328                validate_guidance(&format!("questions.{key}.criteria.true"), r#true)?;
329                validate_guidance(&format!("questions.{key}.criteria.false"), r#false)?;
330            }
331            Ok(())
332        }
333        Question::Choice { criteria, .. } => {
334            let count = criteria.len();
335            if !(MIN_CHOICE_OPTIONS..=MAX_CHOICE_OPTIONS).contains(&count) {
336                return Err(Error::Invalid {
337                    field: format!("questions.{key}.criteria"),
338                    reason: format!(
339                        "expected {MIN_CHOICE_OPTIONS}..={MAX_CHOICE_OPTIONS} choice options, got \
340                         {count}"
341                    ),
342                });
343            }
344            for (option_key, guidance) in criteria {
345                validate_key(
346                    &format!("questions.{key}.criteria option key"),
347                    option_key,
348                    true,
349                )?;
350                validate_guidance(&format!("questions.{key}.criteria.{option_key}"), guidance)?;
351            }
352            Ok(())
353        }
354        Question::Score { criteria, .. } => {
355            let count = criteria.len();
356            if !(MIN_SCORE_LEVELS..=MAX_SCORE_LEVELS).contains(&count) {
357                return Err(Error::Invalid {
358                    field: format!("questions.{key}.criteria"),
359                    reason: format!(
360                        "expected {MIN_SCORE_LEVELS}..={MAX_SCORE_LEVELS} score levels, got \
361                         {count}"
362                    ),
363                });
364            }
365            for (i, guidance) in criteria.iter().enumerate() {
366                validate_guidance(&format!("questions.{key}.criteria[{i}]"), guidance)?;
367            }
368            Ok(())
369        }
370    }
371}
372
373/// Validates a key against the allowlisted charset and length bound.
374///
375/// Question keys allow `[a-z0-9_]`; `choice` option keys additionally allow `-`.
376fn validate_key(field: &str, key: &str, allow_hyphen: bool) -> Result<(), Error> {
377    if key.is_empty() || key.len() > MAX_KEY_BYTES {
378        return Err(Error::Invalid {
379            field: field.to_string(),
380            reason: format!(
381                "length must be 1..={MAX_KEY_BYTES} bytes, got {}",
382                key.len()
383            ),
384        });
385    }
386    let valid = key.bytes().all(|b| {
387        b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || (allow_hyphen && b == b'-')
388    });
389    if !valid {
390        let charset = if allow_hyphen {
391            "[a-z0-9_-]"
392        } else {
393            "[a-z0-9_]"
394        };
395        return Err(Error::Invalid {
396            field: field.to_string(),
397            reason: format!("`{key}` must match `^{charset}{{1,{MAX_KEY_BYTES}}}$`"),
398        });
399    }
400    Ok(())
401}
402
403/// Validates that a guidance string is non-empty and within the byte-length bound.
404fn validate_guidance(field: &str, guidance: &Guidance) -> Result<(), Error> {
405    if guidance.is_empty() {
406        return Err(Error::Invalid {
407            field: field.to_string(),
408            reason: "must not be empty".to_string(),
409        });
410    }
411    let len = guidance.byte_len();
412    if len > MAX_GUIDANCE_BYTES {
413        return Err(Error::Invalid {
414            field: field.to_string(),
415            reason: format!("length must be <= {MAX_GUIDANCE_BYTES} bytes, got {len}"),
416        });
417    }
418    Ok(())
419}
420
421#[cfg(test)]
422mod tests {
423    use proptest::prelude::*;
424    use serde_json::json;
425
426    use super::*;
427
428    #[test]
429    fn test_should_build_minimal_valid_questions() {
430        let questions = Questions::builder()
431            .noul("refund", "Is this a refund request?")
432            .build()
433            .unwrap();
434        assert_eq!(questions.len(), 1);
435        assert!(questions.get("refund").is_some());
436    }
437
438    #[test]
439    fn test_should_build_noul_with_explicit_criteria() {
440        let questions = Questions::builder()
441            .noul_with(
442                "is_bug",
443                "Is this a bug?",
444                "Describes broken behavior.",
445                "Asks a question.",
446            )
447            .build()
448            .unwrap();
449        match questions.get("is_bug").unwrap() {
450            Question::Noul {
451                criteria: Some(c), ..
452            } => {
453                assert_eq!(c.r#true.as_str(), Some("Describes broken behavior."));
454            }
455            other => panic!("expected Noul with criteria, got {other:?}"),
456        }
457    }
458
459    #[test]
460    fn test_should_build_choice_and_score_questions() {
461        let questions = Questions::builder()
462            .choice(
463                "team",
464                "Which team?",
465                [("payments", "Billing."), ("frontend", "UI.")],
466            )
467            .score("urgency", "How urgent?", ["Low", "High"])
468            .build()
469            .unwrap();
470        assert_eq!(questions.len(), 2);
471        assert_eq!(questions.get("team").unwrap().kind(), "choice");
472        assert_eq!(questions.get("urgency").unwrap().kind(), "score");
473    }
474
475    #[test]
476    fn test_should_reject_zero_questions() {
477        let err = Questions::builder().build().unwrap_err();
478        assert!(matches!(err, Error::Invalid { .. }));
479    }
480
481    #[test]
482    fn test_should_reject_too_many_questions() {
483        let mut builder = Questions::builder();
484        for i in 0..=MAX_QUESTIONS {
485            builder = builder.noul(format!("q{i}"), "Some instructions here.");
486        }
487        assert!(builder.build().is_err());
488    }
489
490    #[test]
491    fn test_should_accept_max_questions() {
492        let mut builder = Questions::builder();
493        for i in 0..MAX_QUESTIONS {
494            builder = builder.noul(format!("q{i}"), "Some instructions here.");
495        }
496        assert_eq!(builder.build().unwrap().len(), MAX_QUESTIONS);
497    }
498
499    #[test]
500    fn test_should_reject_duplicate_question_keys() {
501        let err = Questions::builder()
502            .noul("dup", "First.")
503            .noul("dup", "Second.")
504            .build()
505            .unwrap_err();
506        assert!(matches!(err, Error::Invalid { .. }));
507    }
508
509    #[test]
510    fn test_should_reject_uppercase_or_symbol_in_question_key() {
511        assert!(
512            Questions::builder()
513                .noul("Refund", "Is this a refund?")
514                .build()
515                .is_err()
516        );
517        assert!(
518            Questions::builder()
519                .noul("refund!", "Is this a refund?")
520                .build()
521                .is_err()
522        );
523        assert!(
524            Questions::builder()
525                .noul("refund-request", "Is this a refund?")
526                .build()
527                .is_err()
528        );
529    }
530
531    #[test]
532    fn test_should_reject_empty_instructions() {
533        assert!(Questions::builder().noul("refund", "").build().is_err());
534        assert!(Questions::builder().noul("refund", "   ").build().is_err());
535    }
536
537    #[test]
538    fn test_should_reject_oversized_instructions() {
539        let huge = "x".repeat(MAX_GUIDANCE_BYTES + 1);
540        assert!(Questions::builder().noul("refund", huge).build().is_err());
541    }
542
543    #[test]
544    fn test_should_accept_max_length_instructions() {
545        let max = "x".repeat(MAX_GUIDANCE_BYTES);
546        assert!(Questions::builder().noul("refund", max).build().is_ok());
547    }
548
549    #[test]
550    fn test_should_reject_choice_with_one_option() {
551        let err = Questions::builder()
552            .choice("team", "Which?", [("only", "One.")])
553            .build()
554            .unwrap_err();
555        assert!(matches!(err, Error::Invalid { .. }));
556    }
557
558    #[test]
559    fn test_should_reject_choice_option_key_with_uppercase() {
560        let err = Questions::builder()
561            .choice(
562                "team",
563                "Which?",
564                [("Payments", "Billing."), ("frontend", "UI.")],
565            )
566            .build()
567            .unwrap_err();
568        assert!(matches!(err, Error::Invalid { .. }));
569    }
570
571    #[test]
572    fn test_should_allow_hyphen_in_choice_option_key_only() {
573        assert!(
574            Questions::builder()
575                .choice(
576                    "team",
577                    "Which?",
578                    [("front-end", "UI."), ("back-end", "Server.")]
579                )
580                .build()
581                .is_ok()
582        );
583    }
584
585    #[test]
586    fn test_should_reject_score_with_one_level() {
587        let err = Questions::builder()
588            .score("urgency", "How urgent?", ["Only"])
589            .build()
590            .unwrap_err();
591        assert!(matches!(err, Error::Invalid { .. }));
592    }
593
594    #[test]
595    fn test_should_reject_score_with_too_many_levels() {
596        let levels: Vec<String> = (0..=MAX_SCORE_LEVELS)
597            .map(|i| format!("Level {i}"))
598            .collect();
599        assert!(
600            Questions::builder()
601                .score("urgency", "How urgent?", levels)
602                .build()
603                .is_err()
604        );
605    }
606
607    #[test]
608    fn test_should_accept_structured_guidance_via_json_value() {
609        let g = json!({"note": "structured"});
610        assert!(Questions::builder().noul("refund", g).build().is_ok());
611    }
612
613    #[test]
614    fn test_should_serialize_choice_question_with_type_tag() {
615        let questions = Questions::builder()
616            .choice("team", "Which?", [("a", "A."), ("b", "B.")])
617            .build()
618            .unwrap();
619        let json = serde_json::to_value(&questions).unwrap();
620        assert_eq!(json["team"]["type"], "choice");
621        assert_eq!(json["team"]["instructions"], "Which?");
622        assert_eq!(json["team"]["criteria"]["a"], "A.");
623    }
624
625    #[test]
626    fn test_should_serialize_noul_without_criteria_key_when_absent() {
627        let questions = Questions::builder()
628            .noul("refund", "Is this a refund?")
629            .build()
630            .unwrap();
631        let json = serde_json::to_value(&questions).unwrap();
632        assert!(json["refund"].get("criteria").is_none());
633    }
634
635    #[test]
636    fn test_should_serialize_noul_criteria_as_true_false_keys() {
637        let questions = Questions::builder()
638            .noul_with("is_bug", "Is this a bug?", "Yes text.", "No text.")
639            .build()
640            .unwrap();
641        let json = serde_json::to_value(&questions).unwrap();
642        assert_eq!(json["is_bug"]["criteria"]["true"], "Yes text.");
643        assert_eq!(json["is_bug"]["criteria"]["false"], "No text.");
644    }
645
646    proptest! {
647        #[test]
648        fn test_should_never_accept_key_outside_allowlist(key in "[A-Za-z !@#$%^&*()]{1,20}") {
649            // Any key containing an uppercase letter or a disallowed symbol must be rejected.
650            let has_invalid_char = key.bytes().any(|b| !(b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'));
651            if has_invalid_char {
652                let result = Questions::builder().noul(key, "Some instructions.").build();
653                prop_assert!(result.is_err());
654            }
655        }
656    }
657}