Skip to main content

hyprstream_decision/
spec.rs

1//! The jev-1 question-spec intermediate representation.
2//!
3//! The IR is what every downstream node consumes: P0.1b emits capnp from it, P1.1
4//! linearizes it (via [`crate::serialize`]), P3.5 pins it in prepared statements. It is
5//! authored through [`crate::author`] (YAML/JSON) or constructed directly in Rust.
6
7use std::fmt;
8
9use crate::entry::Entry;
10
11/// Question type tags. `Span`/`Derived` are reserved for profile v2: recognized by the
12/// authoring layer (rejected with [`crate::error::SpecErrorKind::ReservedQuestionType`])
13/// so that a v2 document fails loudly instead of being misread.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum QuestionKind {
16    /// Statement judged against the state; answered with P(true).
17    Noul,
18    /// One of 2–255 pre-enumerated options; answered with a probability per option.
19    Choice,
20    /// Ordered rubric levels; answered with a probability per level.
21    Score,
22    /// Reserved for profile v2 (span extraction).
23    Span,
24    /// Reserved for profile v2 (derived/computed questions).
25    Derived,
26}
27
28impl QuestionKind {
29    /// The wire tag (`"noul"`, `"choice"`, `"score"`, `"span"`, `"derived"`).
30    pub fn as_str(self) -> &'static str {
31        match self {
32            Self::Noul => "noul",
33            Self::Choice => "choice",
34            Self::Score => "score",
35            Self::Span => "span",
36            Self::Derived => "derived",
37        }
38    }
39
40    /// Parse a wire tag. Unknown tags return `None`; reserved v2 tags parse successfully
41    /// and are rejected by the authoring layer as `ReservedQuestionType`.
42    pub fn from_tag(tag: &str) -> Option<Self> {
43        match tag {
44            "noul" => Some(Self::Noul),
45            "choice" => Some(Self::Choice),
46            "score" => Some(Self::Score),
47            "span" => Some(Self::Span),
48            "derived" => Some(Self::Derived),
49            _ => None,
50        }
51    }
52
53    /// Whether this tag is usable in profile v1 (reserved v2 tags are not).
54    pub fn is_v1(self) -> bool {
55        matches!(self, Self::Noul | Self::Choice | Self::Score)
56    }
57}
58
59impl fmt::Display for QuestionKind {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str(self.as_str())
62    }
63}
64
65/// Noul criteria: free-form descriptions of what the `true` and `false` outcomes mean.
66/// Keys are literally `"true"`/`"false"` on the wire; both entries are optional.
67#[derive(Debug, Clone, Default, PartialEq)]
68pub struct NoulCriteria {
69    /// Description of the true outcome.
70    pub on_true: Option<Entry>,
71    /// Description of the false outcome.
72    pub on_false: Option<Entry>,
73}
74
75/// One choice option: a name (its identity and its label) plus an optional rubric.
76/// `None` rubric = undescribed option (D3's choice-side counterpart).
77#[derive(Debug, Clone, PartialEq)]
78pub struct ChoiceOption {
79    /// Option name. Sent to the model; also the emitted label string.
80    pub name: String,
81    /// Rubric text (any entry type; structured entries are serialized as canonical JSON).
82    pub rubric: Option<Entry>,
83}
84
85/// The per-kind payload of a question spec.
86#[derive(Debug, Clone, PartialEq)]
87pub enum QuestionBody {
88    /// Noul: optional true/false criteria.
89    Noul {
90        /// Optional descriptions of the two outcomes.
91        criteria: Option<NoulCriteria>,
92    },
93    /// Choice: 2–255 options (D2) in canonical authoring order.
94    Choice {
95        /// Options in insertion order — this order is canonical (D6).
96        options: Vec<ChoiceOption>,
97    },
98    /// Score: ≥ 2 ordered levels (D1); index = level, 0-based. `None` = undescribed (D3).
99    Score {
100        /// Level rubrics in ascending level order. Level *numbers* are never sent to the
101        /// model — each level is judged independently against the state.
102        levels: Vec<Option<Entry>>,
103    },
104}
105
106/// One runtime-declared question.
107#[derive(Debug, Clone, PartialEq)]
108pub struct QuestionSpec {
109    /// Caller-chosen id. Opaque on the wire and **never serialized to the model**. For
110    /// Arrow emission it must additionally be identifier-safe (see
111    /// [`crate::arrow::DecisionSchema`]).
112    pub id: String,
113    /// The primitive type.
114    pub kind: QuestionKind,
115    /// Optional instructions (D4): the question text in practice.
116    pub instructions: Option<Entry>,
117    /// The per-kind payload.
118    pub body: QuestionBody,
119}
120
121impl QuestionSpec {
122    /// Number of labels in this question's distribution: 2 for noul
123    /// (`[false, true]`), option count for choice, level count for score.
124    pub fn cardinality(&self) -> usize {
125        match &self.body {
126            QuestionBody::Noul { .. } => 2,
127            QuestionBody::Choice { options } => options.len(),
128            QuestionBody::Score { levels } => levels.len(),
129        }
130    }
131
132    /// The label list, in canonical order. Noul labels are `["false", "true"]` (index 1
133    /// is the `noul` probability itself); choice labels are option names; score labels
134    /// are the decimal level indices `"0".."n-1"`.
135    pub fn labels(&self) -> Vec<String> {
136        match &self.body {
137            QuestionBody::Noul { .. } => vec!["false".to_owned(), "true".to_owned()],
138            QuestionBody::Choice { options } => {
139                options.iter().map(|option| option.name.clone()).collect()
140            }
141            QuestionBody::Score { levels } => {
142                (0..levels.len()).map(|level| level.to_string()).collect()
143            }
144        }
145    }
146}
147
148/// A parsed question-spec document: the questions map plus the optional shared `state`.
149///
150/// Insertion order is authoring order and is preserved end to end — it defines
151/// serialization order and argmax tie-breaking (D6). Question ids are unique (the
152/// authoring layer rejects duplicates with a positioned error).
153#[derive(Debug, Clone, Default, PartialEq)]
154pub struct QuestionSet {
155    /// Optional shared state the questions refer to.
156    pub state: Option<Entry>,
157    /// The questions, in authoring order.
158    pub questions: Vec<QuestionSpec>,
159}
160
161impl QuestionSet {
162    /// Look up a question by id.
163    pub fn question(&self, id: &str) -> Option<&QuestionSpec> {
164        self.questions.iter().find(|question| question.id == id)
165    }
166}