Skip to main content

vcp_core/
context.rs

1//! Context wire format: combined situational + personal encoding (VCP v3.2).
2//!
3//! The full wire format joins the situational and personal halves with
4//! a double-pipe separator (`\u{2016}`):
5//!
6//! ```text
7//! <situational-wire>\u{2016}<personal-wire>
8//! ```
9//!
10//! For example:
11//! ```text
12//! \u{23F0}\u{1F305}|\u{1F4CD}\u{1F3E1}\u{2016}\u{1F9E0}focused:4|\u{1F4AD}calm:3
13//! ```
14//!
15//! ## Conformance levels (VCP v3.2)
16//!
17//! | level          | shape                                                 |
18//! |----------------|-------------------------------------------------------|
19//! | VCP-Minimal    | situational only, core 9 dims (positions 1-9)         |
20//! | VCP-Standard   | Minimal + any personal-state dim                      |
21//! | VCP-Extended   | Standard (or Minimal) + any VEP-0004 dim (pos 10-13)  |
22
23use serde::{Deserialize, Serialize};
24
25use crate::error::{VcpError, VcpResult};
26use crate::personal::PersonalState;
27use crate::situational::SituationalContext;
28
29/// VCP v3.2 conformance classification for a [`FullContext`].
30///
31/// Serializes as the canonical labels `VCP-Minimal`, `VCP-Standard`,
32/// or `VCP-Extended` — matching the schema at
33/// `schemas/vcp-adaptation-context.schema.json`.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
35pub enum ConformanceLevel {
36    /// Situational only, core 9 dims (positions 1-9). No personal,
37    /// no VEP-0004.
38    #[serde(rename = "VCP-Minimal")]
39    Minimal,
40    /// Core 9 situational + at least one personal-state dim.
41    #[serde(rename = "VCP-Standard")]
42    Standard,
43    /// Any VEP-0004 dimension present (positions 10-13). Takes
44    /// precedence over Standard.
45    #[serde(rename = "VCP-Extended")]
46    Extended,
47}
48
49impl ConformanceLevel {
50    /// Canonical kebab-case label: `VCP-Minimal` / `VCP-Standard` / `VCP-Extended`.
51    pub fn label(self) -> &'static str {
52        match self {
53            Self::Minimal => "VCP-Minimal",
54            Self::Standard => "VCP-Standard",
55            Self::Extended => "VCP-Extended",
56        }
57    }
58}
59
60/// The separator between the situational and personal halves of the
61/// full context wire format.
62pub const WIRE_SEPARATOR: char = '\u{2016}'; // double vertical line
63
64/// Maximum Unicode scalar values accepted for a context wire string.
65pub const MAX_CONTEXT_WIRE_CHARS: usize = 8_192;
66
67/// Backward-compatible alias for the historical, inaccurately named limit.
68pub const MAX_CONTEXT_WIRE_BYTES: usize = MAX_CONTEXT_WIRE_CHARS;
69
70/// Full VCP context combining situational and personal state (VCP v3.2).
71///
72/// Situational carries 13 dimensions (9 core + 4 VEP-0004).
73/// Personal carries 5 dimensions.
74#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
75pub struct FullContext {
76    /// Situational context (13 dimensions, VCP v3.2).
77    pub situational: SituationalContext,
78    /// Personal state (5 dimensions).
79    pub personal: PersonalState,
80}
81
82impl FullContext {
83    /// Create from its parts.
84    pub fn new(situational: SituationalContext, personal: PersonalState) -> Self {
85        Self {
86            situational,
87            personal,
88        }
89    }
90
91    /// Returns `true` if either half has data.
92    pub fn has_any(&self) -> bool {
93        self.situational.has_any() || self.personal.has_any()
94    }
95
96    /// Classify this context against the VCP v3.2 conformance levels.
97    ///
98    /// Extended (any VEP-0004 dim) wins over Standard. A context with no
99    /// personal data and no VEP-0004 dims is classified as Minimal — even
100    /// if it is empty.
101    pub fn conformance_level(&self) -> ConformanceLevel {
102        if self.situational.has_vep_0004() {
103            ConformanceLevel::Extended
104        } else if self.personal.has_any() {
105            ConformanceLevel::Standard
106        } else {
107            ConformanceLevel::Minimal
108        }
109    }
110
111    /// Encode to the full wire format.
112    ///
113    /// If only one half has data, the separator is still included
114    /// to make the format unambiguous. If neither has data,
115    /// returns an empty string.
116    pub fn to_wire(&self) -> String {
117        let sit = self.situational.to_wire();
118        let per = self.personal.to_wire();
119
120        if sit.is_empty() && per.is_empty() {
121            return String::new();
122        }
123
124        if per.is_empty() {
125            return sit;
126        }
127
128        if sit.is_empty() {
129            return format!("{WIRE_SEPARATOR}{per}");
130        }
131
132        format!("{sit}{WIRE_SEPARATOR}{per}")
133    }
134
135    /// Parse from the full wire format.
136    ///
137    /// # Errors
138    ///
139    /// Returns [`crate::error::VcpError::ParseError`] if the situational or personal
140    /// portion of the wire format is malformed.
141    pub fn from_wire(wire: &str) -> VcpResult<Self> {
142        if wire.is_empty() {
143            return Ok(Self::default());
144        }
145        if wire.chars().count() > MAX_CONTEXT_WIRE_CHARS {
146            return Err(VcpError::ParseError(format!(
147                "context exceeds {MAX_CONTEXT_WIRE_CHARS} characters"
148            )));
149        }
150        if wire
151            .chars()
152            .any(|character| character.is_whitespace() || character.is_control())
153        {
154            return Err(VcpError::ParseError(
155                "context contains whitespace or control characters".to_string(),
156            ));
157        }
158        if wire.matches(WIRE_SEPARATOR).count() > 1 {
159            return Err(VcpError::ParseError(
160                "context contains multiple personal-state separators".to_string(),
161            ));
162        }
163
164        if let Some(sep_idx) = wire.find(WIRE_SEPARATOR) {
165            let sit_part = &wire[..sep_idx];
166            let per_part = &wire[sep_idx + WIRE_SEPARATOR.len_utf8()..];
167            if per_part.is_empty() {
168                return Err(VcpError::ParseError(
169                    "personal-state separator must be followed by a dimension".to_string(),
170                ));
171            }
172
173            let situational = SituationalContext::from_wire(sit_part)?;
174            let personal = PersonalState::from_wire(per_part)?;
175
176            Ok(Self {
177                situational,
178                personal,
179            })
180        } else {
181            // No separator -- treat the entire string as situational only.
182            let situational = SituationalContext::from_wire(wire)?;
183            Ok(Self {
184                situational,
185                personal: PersonalState::default(),
186            })
187        }
188    }
189}
190
191impl std::fmt::Display for FullContext {
192    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        f.write_str(&self.to_wire())
194    }
195}
196
197// ── Tests ───────────────────────────────────────────────────
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use crate::personal::PersonalDimension;
203
204    #[test]
205    fn empty_context() {
206        let ctx = FullContext::default();
207        assert!(!ctx.has_any());
208        assert_eq!(ctx.to_wire(), "");
209    }
210
211    #[test]
212    fn situational_only() {
213        let mut ctx = FullContext::default();
214        ctx.situational.time = Some(vec!["\u{1F305}".to_string()]);
215
216        let wire = ctx.to_wire();
217        assert!(!wire.contains(WIRE_SEPARATOR));
218        assert!(wire.contains("\u{23F0}"));
219
220        let parsed = FullContext::from_wire(&wire).unwrap();
221        assert!(parsed.situational.time.is_some());
222        assert!(!parsed.personal.has_any());
223    }
224
225    #[test]
226    fn personal_only() {
227        let mut ctx = FullContext::default();
228        ctx.personal.cognitive = Some(PersonalDimension::new("focused", 4).unwrap());
229
230        let wire = ctx.to_wire();
231        assert!(wire.starts_with(WIRE_SEPARATOR));
232
233        let parsed = FullContext::from_wire(&wire).unwrap();
234        assert!(!parsed.situational.has_any());
235        assert_eq!(parsed.personal.cognitive.as_ref().unwrap().value, "focused");
236    }
237
238    #[test]
239    fn full_roundtrip() {
240        let mut ctx = FullContext::default();
241        ctx.situational.time = Some(vec!["\u{1F305}".to_string()]);
242        ctx.situational.space = Some(vec!["\u{1F3E1}".to_string()]);
243        ctx.personal.cognitive = Some(PersonalDimension::new("focused", 4).unwrap());
244        ctx.personal.emotional = Some(PersonalDimension::new("calm", 3).unwrap());
245
246        let wire = ctx.to_wire();
247        assert!(wire.contains(WIRE_SEPARATOR));
248
249        let parsed = FullContext::from_wire(&wire).unwrap();
250        assert!(parsed.situational.time.is_some());
251        assert!(parsed.situational.space.is_some());
252        assert_eq!(parsed.personal.cognitive.as_ref().unwrap().value, "focused");
253        assert_eq!(parsed.personal.emotional.as_ref().unwrap().value, "calm");
254    }
255
256    #[test]
257    fn from_wire_empty() {
258        let ctx = FullContext::from_wire("").unwrap();
259        assert!(!ctx.has_any());
260    }
261
262    #[test]
263    fn from_wire_rejects_noncanonical_separators_and_whitespace() {
264        for malformed in [
265            "\u{2016}",
266            "\u{23F0}\u{1F305}\u{2016}",
267            "\u{2016}\u{1F9E0}focused:4\u{2016}\u{1F4AD}calm:3",
268            "\u{23F0}\u{1F305} \u{2016}\u{1F9E0}focused:4",
269        ] {
270            assert!(
271                FullContext::from_wire(malformed).is_err(),
272                "accepted {malformed:?}"
273            );
274        }
275    }
276
277    #[test]
278    fn from_wire_enforces_encoded_size_boundary() {
279        let prefix = crate::situational::SituationalDimension::Time.symbol();
280        let maximum = format!(
281            "{prefix}{}",
282            "😀".repeat(MAX_CONTEXT_WIRE_CHARS - prefix.chars().count())
283        );
284        assert_eq!(maximum.chars().count(), MAX_CONTEXT_WIRE_CHARS);
285        assert!(FullContext::from_wire(&maximum).is_ok());
286
287        let excessive = format!("{maximum}😀");
288        assert!(FullContext::from_wire(&excessive).is_err());
289    }
290
291    #[test]
292    fn serde_roundtrip() {
293        let mut ctx = FullContext::default();
294        ctx.situational.company = Some(vec!["team".to_string()]);
295        ctx.personal.urgency = Some(PersonalDimension::new("pressured", 4).unwrap());
296
297        let json = serde_json::to_string(&ctx).unwrap();
298        let parsed: FullContext = serde_json::from_str(&json).unwrap();
299        assert_eq!(ctx, parsed);
300    }
301
302    // ── VEP-0004 / v3.2 ─────────────────────────────────────
303
304    #[test]
305    fn full_eighteen_dim_roundtrip() {
306        let mut ctx = FullContext::default();
307        // Situational core
308        ctx.situational.time = Some(vec!["\u{1F305}".to_string()]);
309        ctx.situational.space = Some(vec!["\u{1F3E2}".to_string()]);
310        ctx.situational.company = Some(vec!["\u{1F454}".to_string()]);
311        ctx.situational.occasion = Some(vec!["\u{1F4BC}".to_string()]);
312        // VEP-0004
313        ctx.situational.embodiment = Some(vec!["\u{270B}".to_string()]);
314        ctx.situational.proximity = Some(vec!["\u{1F90F}".to_string()]);
315        ctx.situational.relationship = Some(vec!["colleague:professional".to_string()]);
316        ctx.situational.formality = Some(vec!["\u{1F4BC}".to_string()]);
317        // Personal
318        ctx.personal.cognitive = Some(PersonalDimension::new("focused", 4).unwrap());
319        ctx.personal.emotional = Some(PersonalDimension::new("calm", 5).unwrap());
320
321        let wire = ctx.to_wire();
322        assert!(wire.contains(WIRE_SEPARATOR));
323        assert!(wire.contains("\u{1FAA2}colleague:professional"));
324
325        let parsed = FullContext::from_wire(&wire).unwrap();
326        assert_eq!(
327            parsed.situational.relationship.as_deref(),
328            Some(&["colleague:professional".to_string()][..])
329        );
330        assert_eq!(parsed.personal.cognitive.as_ref().unwrap().value, "focused");
331        assert_eq!(parsed.personal.emotional.as_ref().unwrap().intensity, 5);
332    }
333
334    #[test]
335    fn conformance_minimal_empty() {
336        let ctx = FullContext::default();
337        assert_eq!(ctx.conformance_level(), ConformanceLevel::Minimal);
338        assert_eq!(ctx.conformance_level().label(), "VCP-Minimal");
339    }
340
341    #[test]
342    fn conformance_minimal_core_only() {
343        let mut ctx = FullContext::default();
344        ctx.situational.time = Some(vec!["\u{1F305}".to_string()]);
345        assert_eq!(ctx.conformance_level(), ConformanceLevel::Minimal);
346    }
347
348    #[test]
349    fn conformance_standard_with_personal() {
350        let mut ctx = FullContext::default();
351        ctx.situational.time = Some(vec!["\u{1F305}".to_string()]);
352        ctx.personal.cognitive = Some(PersonalDimension::new("focused", 4).unwrap());
353        assert_eq!(ctx.conformance_level(), ConformanceLevel::Standard);
354    }
355
356    #[test]
357    fn conformance_extended_with_vep_0004() {
358        let mut ctx = FullContext::default();
359        ctx.situational.embodiment = Some(vec!["\u{270B}".to_string()]);
360        assert_eq!(ctx.conformance_level(), ConformanceLevel::Extended);
361    }
362
363    #[test]
364    fn conformance_extended_wins_over_standard() {
365        let mut ctx = FullContext::default();
366        ctx.situational.formality = Some(vec!["\u{1F4BC}".to_string()]);
367        ctx.personal.cognitive = Some(PersonalDimension::new("focused", 4).unwrap());
368        assert_eq!(ctx.conformance_level(), ConformanceLevel::Extended);
369    }
370}