1use alloc::{string::String, vec, vec::Vec};
2use core::{
3 fmt,
4 marker::PhantomData,
5 sync::atomic::{AtomicU64, Ordering},
6};
7
8use serde::{
9 Serialize, Serializer,
10 ser::{SerializeMap, SerializeStruct},
11};
12
13use crate::{
14 ChoiceQ, DynChoiceQ, DynLevels, DynOptions, DynScoreQ, Error, Instructions, Levels, Model,
15 NoulQ, Options, Question, ScoreQ,
16 response::{
17 AnswerSlot, Decoder, WireAnswer, decode_dynamic_choice, decode_dynamic_score, decode_noul,
18 decode_static_choice, decode_static_score,
19 },
20};
21
22static NEXT_BATCH_ID: AtomicU64 = AtomicU64::new(1);
23
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub(crate) struct BatchId(u64);
30
31pub struct Handle<Q: Question> {
38 pub(crate) idx: u32,
39 pub(crate) batch: BatchId,
40 _q: PhantomData<Q>,
41}
42
43impl<Q: Question> Copy for Handle<Q> {}
44
45impl<Q: Question> Clone for Handle<Q> {
46 fn clone(&self) -> Self {
47 *self
48 }
49}
50
51impl<Q: Question> fmt::Debug for Handle<Q> {
52 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
53 formatter
54 .debug_struct("Handle")
55 .field("idx", &self.idx)
56 .field("batch", &self.batch)
57 .finish()
58 }
59}
60
61pub struct Questions {
98 pub(crate) entries: Vec<QuestionEntry>,
99 pub(crate) batch: BatchId,
100}
101
102impl Questions {
103 #[must_use]
108 pub fn new() -> Self {
109 Self {
110 entries: Vec::new(),
111 batch: BatchId(NEXT_BATCH_ID.fetch_add(1, Ordering::Relaxed)),
112 }
113 }
114
115 pub fn noul(
124 &mut self,
125 id: impl Into<String>,
126 instructions: impl Into<Instructions>,
127 ) -> Result<Handle<NoulQ>, Error> {
128 self.insert(id.into(), instructions.into(), "noul", None, decode_noul)
129 }
130
131 pub fn noul_with(
139 &mut self,
140 id: impl Into<String>,
141 instructions: impl Into<Instructions>,
142 yes: &str,
143 no: &str,
144 ) -> Result<Handle<NoulQ>, Error> {
145 let criteria = ChoiceCriteria(vec![
146 ("true".into(), Some(yes.into())),
147 ("false".into(), Some(no.into())),
148 ]);
149 self.insert(
150 id.into(),
151 instructions.into(),
152 "noul",
153 Some(Criteria::Map(criteria)),
154 decode_noul,
155 )
156 }
157
158 pub fn choice<O: Options>(
167 &mut self,
168 id: impl Into<String>,
169 instructions: impl Into<Instructions>,
170 ) -> Result<Handle<ChoiceQ<O>>, Error> {
171 let () = O::COUNT_OK;
172 let criteria = ChoiceCriteria(
173 O::all()
174 .iter()
175 .map(|option| (option.key().into(), option.description().map(String::from)))
176 .collect(),
177 );
178 self.insert(
179 id.into(),
180 instructions.into(),
181 "choice",
182 Some(Criteria::Map(criteria)),
183 decode_static_choice::<O>,
184 )
185 }
186
187 pub fn score<L: Levels>(
195 &mut self,
196 id: impl Into<String>,
197 instructions: impl Into<Instructions>,
198 ) -> Result<Handle<ScoreQ<L>>, Error> {
199 let () = L::COUNT_OK;
200 let criteria = L::all()
201 .iter()
202 .map(|level| level.description().into())
203 .collect();
204 self.insert(
205 id.into(),
206 instructions.into(),
207 "score",
208 Some(Criteria::Levels(criteria)),
209 decode_static_score::<L>,
210 )
211 }
212
213 pub fn choice_dyn<K, D, I>(
224 &mut self,
225 id: impl Into<String>,
226 instructions: impl Into<Instructions>,
227 options: I,
228 ) -> Result<Handle<DynChoiceQ>, Error>
229 where
230 K: Into<String>,
231 D: Into<String>,
232 I: IntoIterator<Item = (K, Option<D>)>,
233 {
234 let id = id.into();
235 let options = criteria_for_question(DynOptions::new(options), &id)?;
236 let criteria = ChoiceCriteria(options.into_iter().collect());
237 self.insert(
238 id,
239 instructions.into(),
240 "choice",
241 Some(Criteria::Map(criteria)),
242 decode_dynamic_choice,
243 )
244 }
245
246 pub fn score_dyn<S: Into<String>>(
257 &mut self,
258 id: impl Into<String>,
259 instructions: impl Into<Instructions>,
260 levels: impl IntoIterator<Item = S>,
261 ) -> Result<Handle<DynScoreQ>, Error> {
262 let id = id.into();
263 let levels = criteria_for_question(DynLevels::new(levels), &id)?;
264 self.insert(
265 id,
266 instructions.into(),
267 "score",
268 Some(Criteria::Levels(levels.into_iter().collect())),
269 decode_dynamic_score,
270 )
271 }
272
273 #[must_use]
275 pub fn len(&self) -> usize {
276 self.entries.len()
277 }
278
279 #[must_use]
281 pub fn is_empty(&self) -> bool {
282 self.entries.is_empty()
283 }
284
285 #[allow(clippy::cast_possible_truncation)]
286 fn insert<Q: Question>(
287 &mut self,
288 id: String,
289 instructions: Instructions,
290 question_type: &'static str,
291 criteria: Option<Criteria>,
292 decoder: Decoder,
293 ) -> Result<Handle<Q>, Error> {
294 if self.entries.iter().any(|entry| entry.id == id) {
295 return Err(Error::DuplicateId(id));
296 }
297 let handle = Handle {
298 idx: self.entries.len() as u32,
299 batch: self.batch,
300 _q: PhantomData,
301 };
302 self.entries.push(QuestionEntry {
303 id,
304 instructions,
305 question_type,
306 criteria,
307 decoder,
308 });
309 Ok(handle)
310 }
311}
312
313fn criteria_for_question<T>(criteria: Result<T, Error>, id: &str) -> Result<T, Error> {
314 criteria.map_err(|error| match error {
315 Error::InvalidCriteria { reason, .. } => Error::InvalidCriteria {
316 id: Some(id.into()),
317 reason,
318 },
319 other => other,
320 })
321}
322
323impl Default for Questions {
324 fn default() -> Self {
325 Self::new()
326 }
327}
328
329pub fn encode(
354 model: &Model,
355 state: &impl Serialize,
356 questions: &Questions,
357) -> Result<Vec<u8>, Error> {
358 if questions.is_empty() {
359 return Err(Error::NoQuestions);
360 }
361 serde_json::to_vec(&WireRequest {
362 state,
363 model,
364 questions: WireQuestions(questions),
365 })
366 .map_err(Error::from)
367}
368
369pub(crate) struct WireRequest<'a, S> {
370 state: &'a S,
371 model: &'a Model,
372 questions: WireQuestions<'a>,
373}
374
375impl<S: Serialize> Serialize for WireRequest<'_, S> {
376 fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
377 where
378 Ser: Serializer,
379 {
380 let mut request = serializer.serialize_struct("Request", 3)?;
381 request.serialize_field("state", self.state)?;
382 request.serialize_field("model", self.model)?;
383 request.serialize_field("questions", &self.questions)?;
384 request.end()
385 }
386}
387
388pub(crate) struct WireQuestions<'a>(&'a Questions);
389
390impl Serialize for WireQuestions<'_> {
391 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
392 where
393 S: Serializer,
394 {
395 let mut questions = serializer.serialize_map(Some(self.0.entries.len()))?;
396 for entry in &self.0.entries {
397 questions.serialize_entry(&entry.id, &WireQuestion(entry))?;
398 }
399 questions.end()
400 }
401}
402
403pub(crate) struct WireQuestion<'a>(&'a QuestionEntry);
404
405impl Serialize for WireQuestion<'_> {
406 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
407 where
408 S: Serializer,
409 {
410 let field_count = if self.0.criteria.is_some() { 3 } else { 2 };
411 let mut question = serializer.serialize_struct("Question", field_count)?;
412 question.serialize_field("type", self.0.question_type)?;
413 question.serialize_field("instructions", &self.0.instructions)?;
414 if let Some(criteria) = &self.0.criteria {
415 question.serialize_field("criteria", criteria)?;
416 }
417 question.end()
418 }
419}
420
421pub(crate) struct QuestionEntry {
422 pub(crate) id: String,
423 instructions: Instructions,
424 question_type: &'static str,
425 criteria: Option<Criteria>,
426 decoder: Decoder,
427}
428
429impl QuestionEntry {
430 pub(crate) fn decode(&self, answer: WireAnswer) -> Result<AnswerSlot, Error> {
431 (self.decoder)(&self.id, self.criteria.as_ref(), answer)
432 }
433}
434
435pub(crate) enum Criteria {
436 Map(ChoiceCriteria),
437 Levels(Vec<String>),
438}
439
440impl Serialize for Criteria {
441 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
442 where
443 S: Serializer,
444 {
445 match self {
446 Self::Map(criteria) => criteria.serialize(serializer),
447 Self::Levels(criteria) => criteria.serialize(serializer),
448 }
449 }
450}
451
452pub(crate) struct ChoiceCriteria(pub(crate) Vec<(String, Option<String>)>);
453
454impl Serialize for ChoiceCriteria {
455 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
456 where
457 S: Serializer,
458 {
459 let mut criteria = serializer.serialize_map(Some(self.0.len()))?;
460 for (key, description) in &self.0 {
461 criteria.serialize_entry(key, description)?;
462 }
463 criteria.end()
464 }
465}
466
467#[cfg(test)]
468mod tests {
469 use alloc::{
470 format,
471 string::{String, ToString},
472 vec,
473 vec::Vec,
474 };
475
476 use serde_json::{Value, json};
477
478 use super::{Handle, Questions, encode};
479 use crate::{
480 DynLevels, DynOptions, Error, Model, NoulQ, Question,
481 options::{
482 LEVELS_TOO_FEW, LEVELS_TOO_MANY, OPTION_KEY_DUPLICATE, OPTION_KEY_EMPTY,
483 OPTIONS_TOO_FEW, OPTIONS_TOO_MANY,
484 },
485 test_support::{Dept, Frustration},
486 };
487
488 struct NotDebugQ;
489
490 impl Question for NotDebugQ {
491 type Answer = ();
492 }
493
494 fn encoded_value(state: &impl serde::Serialize, questions: &Questions) -> Value {
495 serde_json::from_slice(&encode(&Model::LATEST, state, questions).unwrap()).unwrap()
496 }
497
498 #[test]
499 fn triage_request_matches_the_spec() {
500 let mut questions = Questions::new();
501 questions
502 .noul_with(
503 "is_urgent",
504 "Does this convey urgency?",
505 "Explicitly time-sensitive",
506 "No urgency expressed",
507 )
508 .unwrap();
509 questions
510 .choice::<Dept>("department", "Which team should handle this?")
511 .unwrap();
512 questions
513 .score::<Frustration>("frustration", "How frustrated is the customer?")
514 .unwrap();
515
516 assert_eq!(
517 encoded_value(
518 &"Help! My payouts have been failing for 3 days.",
519 &questions
520 ),
521 json!({
522 "state": "Help! My payouts have been failing for 3 days.",
523 "model": "jev-latest",
524 "questions": {
525 "is_urgent": {
526 "type": "noul",
527 "instructions": "Does this convey urgency?",
528 "criteria": {
529 "true": "Explicitly time-sensitive",
530 "false": "No urgency expressed"
531 }
532 },
533 "department": {
534 "type": "choice",
535 "instructions": "Which team should handle this?",
536 "criteria": {
537 "billing": "Payments, invoicing, refunds",
538 "technical": "Bugs, outages, integrations",
539 "sales": null
540 }
541 },
542 "frustration": {
543 "type": "score",
544 "instructions": "How frustrated is the customer?",
545 "criteria": ["Calm", "Frustrated", "Very angry"]
546 }
547 }
548 })
549 );
550 }
551
552 #[test]
553 fn noul_omits_or_emits_criteria_as_requested() {
554 let mut plain = Questions::new();
555 plain.noul("urgent", "Is this urgent?").unwrap();
556 assert_eq!(
557 encoded_value(&"state", &plain)["questions"]["urgent"],
558 json!({"type": "noul", "instructions": "Is this urgent?"})
559 );
560
561 let mut described = Questions::new();
562 described
563 .noul_with("urgent", "Is this urgent?", "Urgent", "Not urgent")
564 .unwrap();
565 assert_eq!(
566 encoded_value(&"state", &described)["questions"]["urgent"]["criteria"],
567 json!({"true": "Urgent", "false": "Not urgent"})
568 );
569 }
570
571 #[test]
572 fn structured_instructions_encode_verbatim() {
573 let object = json!({"task": "Assess urgency", "signals": ["deadline"]});
574 let array = json!(["Choose a team", {"prefer": "billing"}]);
575 let mut questions = Questions::new();
576 questions.noul("urgent", object.clone()).unwrap();
577 questions
578 .choice_dyn(
579 "department",
580 array.clone(),
581 DynOptions::new([("billing", None::<&str>), ("sales", None)]).unwrap(),
582 )
583 .unwrap();
584
585 let encoded = encoded_value(&"state", &questions);
586 assert_eq!(encoded["questions"]["urgent"]["instructions"], object);
587 assert_eq!(encoded["questions"]["department"]["instructions"], array);
588 }
589
590 #[test]
591 fn dynamic_questions_encode_their_criteria() {
592 let mut questions = Questions::new();
593 questions
594 .choice_dyn(
595 "department",
596 "Choose a team",
597 [("billing", Some("Payments")), ("sales", None)],
598 )
599 .unwrap();
600 questions
601 .score_dyn("frustration", "Rate frustration", ["Calm", "Angry"])
602 .unwrap();
603
604 let value = encoded_value(&"state", &questions);
605 assert_eq!(
606 value["questions"]["department"]["criteria"],
607 json!({"billing": "Payments", "sales": null})
608 );
609 assert_eq!(
610 value["questions"]["frustration"]["criteria"],
611 json!(["Calm", "Angry"])
612 );
613 }
614
615 #[test]
616 fn dynamic_questions_accept_owned_and_prevalidated_criteria() {
617 let mut questions = Questions::new();
618 let owned: Vec<(String, Option<String>)> = vec![
619 (String::from("billing"), Some(String::from("Payments"))),
620 (String::from("sales"), None),
621 ];
622 questions
623 .choice_dyn("owned", "Choose a team", owned)
624 .unwrap();
625
626 let options = DynOptions::new([("technical", Some("Bugs"))]).unwrap();
627 questions
628 .choice_dyn("prevalidated_choice", "Choose a team", options)
629 .unwrap();
630 let levels = DynLevels::new(["Calm", "Angry"]).unwrap();
631 questions
632 .score_dyn("prevalidated_score", "Rate frustration", levels)
633 .unwrap();
634
635 assert_eq!(questions.len(), 3);
636 }
637
638 fn assert_invalid_criteria(error: Error, expected_id: &str, expected_reason: &'static str) {
639 match error {
640 Error::InvalidCriteria { id, reason } => {
641 assert_eq!(id.as_deref(), Some(expected_id));
642 assert_eq!(reason, expected_reason);
643 }
644 other => panic!("unexpected error: {other}"),
645 }
646 }
647
648 #[test]
649 fn dynamic_questions_report_invalid_criteria_without_adding_entries() {
650 let mut questions = Questions::new();
651 questions.noul("existing", "Existing question").unwrap();
652
653 let empty: Vec<(&str, Option<&str>)> = Vec::new();
654 let error = questions
655 .choice_dyn("empty_options", "Choose", empty)
656 .unwrap_err();
657 assert_invalid_criteria(error, "empty_options", OPTIONS_TOO_FEW);
658 assert_eq!(questions.len(), 1);
659
660 let error = questions
661 .choice_dyn("empty_key", "Choose", [("", None::<&str>)])
662 .unwrap_err();
663 assert_invalid_criteria(error, "empty_key", OPTION_KEY_EMPTY);
664 assert_eq!(questions.len(), 1);
665
666 let error = questions
667 .choice_dyn(
668 "duplicate_key",
669 "Choose",
670 [("billing", None::<&str>), ("billing", None)],
671 )
672 .unwrap_err();
673 assert_invalid_criteria(error, "duplicate_key", OPTION_KEY_DUPLICATE);
674 assert_eq!(questions.len(), 1);
675
676 let too_many = (0_u16..256)
677 .map(|index| (index.to_string(), None::<String>))
678 .collect::<Vec<_>>();
679 let error = questions
680 .choice_dyn("too_many_options", "Choose", too_many)
681 .unwrap_err();
682 assert_invalid_criteria(error, "too_many_options", OPTIONS_TOO_MANY);
683 assert_eq!(questions.len(), 1);
684
685 let error = questions
686 .score_dyn("one_level", "Rate", ["only"])
687 .unwrap_err();
688 assert_invalid_criteria(error, "one_level", LEVELS_TOO_FEW);
689 assert_eq!(questions.len(), 1);
690
691 let error = questions
692 .score_dyn("eleven_levels", "Rate", ["level"; 11])
693 .unwrap_err();
694 assert_invalid_criteria(error, "eleven_levels", LEVELS_TOO_MANY);
695 assert_eq!(questions.len(), 1);
696 }
697
698 #[test]
699 fn state_accepts_string_object_and_array() {
700 let mut questions = Questions::new();
701 questions.noul("urgent", "Is this urgent?").unwrap();
702
703 assert_eq!(encoded_value(&"text", &questions)["state"], json!("text"));
704 assert_eq!(
705 encoded_value(&json!({"message": "text"}), &questions)["state"],
706 json!({"message": "text"})
707 );
708 assert_eq!(
709 encoded_value(&json!(["first", "second"]), &questions)["state"],
710 json!(["first", "second"])
711 );
712 }
713
714 #[test]
715 fn duplicate_ids_are_rejected_without_adding_an_entry() {
716 let mut questions = Questions::new();
717 questions.noul("urgent", "First").unwrap();
718 let error = questions.noul("urgent", "Second").err().unwrap();
719 assert!(matches!(error, Error::DuplicateId(id) if id == "urgent"));
720 assert_eq!(questions.len(), 1);
721 }
722
723 #[test]
724 fn empty_batches_are_rejected_at_encode_time() {
725 assert!(matches!(
726 encode(&Model::LATEST, &"state", &Questions::new()),
727 Err(Error::NoQuestions)
728 ));
729 }
730
731 #[test]
732 fn builders_have_distinct_batch_ids() {
733 let mut first = Questions::new();
734 let first_handle = first.noul("first", "First").unwrap();
735 let mut second = Questions::new();
736 let second_handle = second.noul("second", "Second").unwrap();
737 assert_ne!(first_handle.batch, second_handle.batch);
738 }
739
740 #[test]
741 fn handles_are_copy_and_debug_without_marker_bounds() {
742 fn assert_copy<T: Copy>() {}
743 fn assert_debug<T: core::fmt::Debug>() {}
744
745 assert_copy::<Handle<NoulQ>>();
746 assert_debug::<Handle<NotDebugQ>>();
747
748 let mut questions = Questions::new();
749 let handle = questions.noul("urgent", "Is this urgent?").unwrap();
750 let debug = format!("{handle:?}");
751 assert!(debug.contains("idx: 0"));
752 assert!(debug.contains("batch: BatchId("));
753 }
754
755 #[test]
756 fn choice_criteria_keep_option_order_on_the_wire() {
757 let mut questions = Questions::new();
758 questions
759 .choice::<Dept>("department", "Choose a team")
760 .unwrap();
761 let json =
762 String::from_utf8(encode(&Model::LATEST, &"state", &questions).unwrap()).unwrap();
763 let billing = json.find("billing").unwrap();
764 let technical = json.find("technical").unwrap();
765 let sales = json.find("sales").unwrap();
766 assert!(billing < technical && technical < sales);
767 }
768}