vcp-core 4.2.0

Value Context Protocol (VCP) core types and parsing
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
//! Personal state dimensions (VCP v3.1 Layer 3).
//!
//! Personal state carries five categorical dimensions, each with a named
//! value and a 1-5 intensity.  An optional `extended` sub-signal provides
//! additional specificity (e.g. `body_signals = pain:4 [migraine]`).
//!
//! This layer is **not diagnostic or therapeutic**; it reflects
//! self-reported state for adaptation purposes only.

use std::fmt;

use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};

use crate::error::{VcpError, VcpResult};

const MAX_PERSONAL_WIRE_CHARS: usize = 8_192;

// ── Dimension enums ─────────────────────────────────────────

/// The five personal-state dimensions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PersonalDimensionKind {
    CognitiveState,
    EmotionalTone,
    EnergyLevel,
    PerceivedUrgency,
    BodySignals,
}

impl PersonalDimensionKind {
    /// Emoji symbol used in wire format.
    pub fn symbol(self) -> &'static str {
        match self {
            Self::CognitiveState => "\u{1F9E0}",  // brain
            Self::EmotionalTone => "\u{1F4AD}",   // thought balloon
            Self::EnergyLevel => "\u{1F50B}",     // battery
            Self::PerceivedUrgency => "\u{26A1}", // high voltage
            Self::BodySignals => "\u{1FA7A}",     // stethoscope
        }
    }

    /// Parse from the emoji symbol. Returns `None` on unrecognised input.
    pub fn from_symbol(s: &str) -> Option<Self> {
        match s {
            "\u{1F9E0}" => Some(Self::CognitiveState),
            "\u{1F4AD}" => Some(Self::EmotionalTone),
            "\u{1F50B}" => Some(Self::EnergyLevel),
            "\u{26A1}" => Some(Self::PerceivedUrgency),
            "\u{1FA7A}" => Some(Self::BodySignals),
            _ => None,
        }
    }

    /// The set of valid category names for this dimension.
    pub fn valid_values(self) -> &'static [&'static str] {
        match self {
            Self::CognitiveState => &["focused", "distracted", "overloaded", "foggy", "reflective"],
            Self::EmotionalTone => &["calm", "tense", "frustrated", "neutral", "uplifted"],
            Self::EnergyLevel => &["rested", "low_energy", "fatigued", "wired", "depleted"],
            Self::PerceivedUrgency => &["unhurried", "time_aware", "pressured", "critical"],
            Self::BodySignals => &["neutral", "discomfort", "pain", "unwell", "recovering"],
        }
    }
}

impl fmt::Display for PersonalDimensionKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let label = match self {
            Self::CognitiveState => "cognitive_state",
            Self::EmotionalTone => "emotional_tone",
            Self::EnergyLevel => "energy_level",
            Self::PerceivedUrgency => "perceived_urgency",
            Self::BodySignals => "body_signals",
        };
        f.write_str(label)
    }
}

// ── Single dimension value ──────────────────────────────────

/// A single personal-state dimension with a categorical value,
/// intensity (1-5, default 3), and optional extended sub-signal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PersonalDimension {
    /// Categorical value (e.g. "focused", "calm", "rested").
    pub value: String,
    /// Intensity 1-5.  1 = barely noticeable, 5 = extreme.
    pub intensity: u8,
    /// Optional extended qualifier (e.g. "migraine", "bathroom").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extended: Option<String>,
}

impl PersonalDimension {
    const MAX_VALUE_CHARS: usize = 64;
    const MAX_EXTENDED_CHARS: usize = 256;

    fn validate(value: &str, intensity: u8, extended: Option<&str>) -> VcpResult<()> {
        let valid_value = !value.is_empty()
            && value.chars().count() <= Self::MAX_VALUE_CHARS
            && value
                .bytes()
                .next()
                .is_some_and(|byte| byte.is_ascii_lowercase())
            && value
                .chars()
                .all(|character| character.is_ascii_lowercase() || character == '_');
        if !valid_value {
            return Err(VcpError::ParseError(
                "personal value must match [a-z][a-z_]{0,63}".to_string(),
            ));
        }
        if !(1..=5).contains(&intensity) {
            return Err(VcpError::InvalidIntensity(intensity));
        }
        if let Some(extended) = extended {
            if extended.is_empty()
                || extended.chars().count() > Self::MAX_EXTENDED_CHARS
                || extended.chars().any(|character| {
                    character.is_control() || matches!(character, '[' | ']' | '|' | '\u{2016}')
                })
            {
                return Err(VcpError::ParseError(
                    "extended personal value is empty, oversized, or wire-ambiguous".to_string(),
                ));
            }
        }
        Ok(())
    }

    /// Create with validation.
    ///
    /// # Errors
    ///
    /// Returns [`VcpError::InvalidIntensity`] if `intensity` is not in 1..=5.
    pub fn new(value: impl Into<String>, intensity: u8) -> VcpResult<Self> {
        let value = value.into();
        Self::validate(&value, intensity, None)?;
        Ok(Self {
            value,
            intensity,
            extended: None,
        })
    }

    /// Create with an extended sub-signal.
    ///
    /// # Errors
    ///
    /// Returns [`VcpError::InvalidIntensity`] if `intensity` is not in 1..=5.
    pub fn with_extended(
        value: impl Into<String>,
        intensity: u8,
        extended: impl Into<String>,
    ) -> VcpResult<Self> {
        let value = value.into();
        let extended = extended.into();
        Self::validate(&value, intensity, Some(&extended))?;
        Ok(Self {
            value,
            intensity,
            extended: Some(extended),
        })
    }

    /// Encode to wire-format segment: `value:intensity` or `value:intensity[ext]`.
    pub fn to_wire(&self) -> String {
        let mut s = format!("{}:{}", self.value, self.intensity);
        if let Some(ref ext) = self.extended {
            s.push('[');
            s.push_str(ext);
            s.push(']');
        }
        s
    }

    /// Parse from wire-format segment: `value:intensity` or `value:intensity[ext]`.
    ///
    /// # Errors
    ///
    /// Returns [`VcpError::ParseError`] if the wire format is malformed,
    /// or [`VcpError::InvalidIntensity`] if the intensity is out of range.
    pub fn from_wire(wire: &str) -> VcpResult<Self> {
        // Check for extended: value:intensity[ext]
        let (main, extended) = if let Some(bracket_start) = wire.find('[') {
            if !wire.ends_with(']') {
                return Err(VcpError::ParseError(format!(
                    "unterminated bracket in personal dimension: {wire}"
                )));
            }
            let ext = &wire[bracket_start + 1..wire.len() - 1];
            (&wire[..bracket_start], Some(ext.to_string()))
        } else {
            (wire, None)
        };

        let parts: Vec<&str> = main.split(':').collect();
        if parts.len() != 2 {
            return Err(VcpError::ParseError(format!(
                "personal dimension must be value:intensity, got: {wire}"
            )));
        }

        let value = parts[0].to_string();
        let intensity: u8 = parts[1]
            .parse()
            .map_err(|_| VcpError::ParseError(format!("invalid intensity: {}", parts[1])))?;

        Self::validate(&value, intensity, extended.as_deref())?;
        Ok(Self {
            value,
            intensity,
            extended,
        })
    }
}

impl<'de> Deserialize<'de> for PersonalDimension {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct WireDimension {
            value: String,
            #[serde(default)]
            intensity: Option<u8>,
            #[serde(default)]
            extended: Option<String>,
        }

        let wire = WireDimension::deserialize(deserializer)?;
        let intensity = wire.intensity.unwrap_or(3);
        PersonalDimension::validate(&wire.value, intensity, wire.extended.as_deref())
            .map_err(D::Error::custom)?;
        Ok(PersonalDimension {
            value: wire.value,
            intensity,
            extended: wire.extended,
        })
    }
}

impl fmt::Display for PersonalDimension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_wire())
    }
}

// ── Full personal state ─────────────────────────────────────

/// Complete personal state across all five dimensions.
///
/// Each dimension is optional -- only dimensions with active signals are set.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PersonalState {
    /// Cognitive state (focused / distracted / overloaded / foggy / reflective).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cognitive: Option<PersonalDimension>,
    /// Emotional tone (calm / tense / frustrated / neutral / uplifted).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub emotional: Option<PersonalDimension>,
    /// Energy level (rested / `low_energy` / fatigued / wired / depleted).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub energy: Option<PersonalDimension>,
    /// Perceived urgency (unhurried / `time_aware` / pressured / critical).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub urgency: Option<PersonalDimension>,
    /// Body signals (neutral / discomfort / pain / unwell / recovering).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<PersonalDimension>,
}

impl PersonalState {
    /// Returns `true` if at least one dimension is set.
    pub fn has_any(&self) -> bool {
        self.cognitive.is_some()
            || self.emotional.is_some()
            || self.energy.is_some()
            || self.urgency.is_some()
            || self.body.is_some()
    }

    /// Encode personal state to wire format (the part after `\u{2016}`).
    ///
    /// Format: `<symbol><value>:<intensity>[|...]`
    pub fn to_wire(&self) -> String {
        let mut parts = Vec::new();

        let dims: [(PersonalDimensionKind, &Option<PersonalDimension>); 5] = [
            (PersonalDimensionKind::CognitiveState, &self.cognitive),
            (PersonalDimensionKind::EmotionalTone, &self.emotional),
            (PersonalDimensionKind::EnergyLevel, &self.energy),
            (PersonalDimensionKind::PerceivedUrgency, &self.urgency),
            (PersonalDimensionKind::BodySignals, &self.body),
        ];

        for (kind, dim_opt) in &dims {
            if let Some(dim) = dim_opt {
                parts.push(format!("{}{}", kind.symbol(), dim.to_wire()));
            }
        }

        parts.join("|")
    }

    /// Parse personal state from wire format (the part after `\u{2016}`).
    ///
    /// # Errors
    ///
    /// Returns [`VcpError::ParseError`] if a segment contains an
    /// unrecognised dimension symbol or malformed dimension data.
    pub fn from_wire(wire: &str) -> VcpResult<Self> {
        let mut state = PersonalState::default();

        if wire.is_empty() {
            return Ok(state);
        }
        if wire.chars().count() > MAX_PERSONAL_WIRE_CHARS {
            return Err(VcpError::ParseError(format!(
                "personal state exceeds {MAX_PERSONAL_WIRE_CHARS} characters"
            )));
        }

        for segment in wire.split('|') {
            if segment.is_empty() {
                return Err(VcpError::ParseError(
                    "personal state contains an empty dimension segment".to_string(),
                ));
            }

            // The segment starts with an emoji, then value:intensity.
            // Emojis can be multi-byte, so we need to find the split point.
            let (symbol, rest) = split_leading_emoji(segment)?;

            let kind = PersonalDimensionKind::from_symbol(symbol).ok_or_else(|| {
                VcpError::ParseError(format!("unknown personal dimension symbol: {symbol}"))
            })?;

            let dim = PersonalDimension::from_wire(rest)?;

            let slot = match kind {
                PersonalDimensionKind::CognitiveState => &mut state.cognitive,
                PersonalDimensionKind::EmotionalTone => &mut state.emotional,
                PersonalDimensionKind::EnergyLevel => &mut state.energy,
                PersonalDimensionKind::PerceivedUrgency => &mut state.urgency,
                PersonalDimensionKind::BodySignals => &mut state.body,
            };
            if slot.is_some() {
                return Err(VcpError::ParseError(format!(
                    "duplicate personal dimension: {kind}"
                )));
            }
            *slot = Some(dim);
        }

        Ok(state)
    }
}

impl fmt::Display for PersonalState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_wire())
    }
}

/// Split the leading emoji character(s) from the rest of a wire segment.
///
/// VCP personal dimension emojis are either single code points or short
/// multi-code-point sequences. We try known symbols first, then fall back
/// to taking the first Unicode scalar.
fn split_leading_emoji(s: &str) -> VcpResult<(&str, &str)> {
    // Known symbols in descending byte-length order for greedy matching.
    static SYMBOLS: &[&str] = &[
        "\u{1F9E0}", // brain (4 bytes)
        "\u{1F4AD}", // thought balloon (4 bytes)
        "\u{1F50B}", // battery (4 bytes)
        "\u{1FA7A}", // stethoscope (4 bytes)
        "\u{26A1}",  // high voltage (3 bytes)
    ];

    for sym in SYMBOLS {
        if let Some(rest) = s.strip_prefix(sym) {
            return Ok((sym, rest));
        }
    }

    // Fallback: take the first char.
    let first_char_len = s
        .chars()
        .next()
        .ok_or_else(|| VcpError::ParseError("empty segment".into()))?
        .len_utf8();
    Ok((&s[..first_char_len], &s[first_char_len..]))
}

// ── Tests ───────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn dimension_new_valid() {
        let d = PersonalDimension::new("focused", 4).unwrap();
        assert_eq!(d.value, "focused");
        assert_eq!(d.intensity, 4);
        assert_eq!(d.extended, None);
    }

    #[test]
    fn dimension_new_invalid_intensity() {
        assert!(PersonalDimension::new("focused", 0).is_err());
        assert!(PersonalDimension::new("focused", 6).is_err());
    }

    #[test]
    fn dimension_constructors_reject_invalid_or_wire_ambiguous_text() {
        for invalid in ["", "Focused", "two words", "focused:calm", "focused|calm"] {
            assert!(
                PersonalDimension::new(invalid, 3).is_err(),
                "accepted {invalid:?}"
            );
        }
        assert!(PersonalDimension::new("x".repeat(65), 3).is_err());
        for invalid_extended in [
            "",
            "nested[detail]",
            "one|two",
            "one\u{2016}two",
            "one\0two",
        ] {
            assert!(PersonalDimension::with_extended("pain", 4, invalid_extended).is_err());
        }
        assert!(PersonalDimension::with_extended("pain", 4, "x".repeat(257)).is_err());
    }

    #[test]
    fn dimension_with_extended() {
        let d = PersonalDimension::with_extended("pain", 4, "migraine").unwrap();
        assert_eq!(d.extended.as_deref(), Some("migraine"));
        assert_eq!(d.to_wire(), "pain:4[migraine]");
    }

    #[test]
    fn dimension_wire_roundtrip() {
        let cases = vec!["focused:4", "calm:3", "pain:4[migraine]", "rested:1"];
        for case in cases {
            let d = PersonalDimension::from_wire(case).unwrap();
            assert_eq!(d.to_wire(), case);
        }
    }

    #[test]
    fn dimension_wire_error_missing_colon() {
        assert!(PersonalDimension::from_wire("focused").is_err());
    }

    #[test]
    fn dimension_wire_error_bad_intensity() {
        assert!(PersonalDimension::from_wire("focused:0").is_err());
        assert!(PersonalDimension::from_wire("focused:9").is_err());
    }

    #[test]
    fn personal_wire_rejects_empty_and_duplicate_segments() {
        let duplicate = "\u{1F9E0}focused:4|\u{1F9E0}reflective:3";
        for malformed in ["|", "\u{1F9E0}focused:4|", duplicate] {
            assert!(
                PersonalState::from_wire(malformed).is_err(),
                "accepted {malformed:?}"
            );
        }
        assert!(PersonalDimension::from_wire("pain:4[]").is_err());
        let oversized = format!("🧠{}:3", "a".repeat(MAX_PERSONAL_WIRE_CHARS));
        assert!(PersonalState::from_wire(&oversized)
            .unwrap_err()
            .to_string()
            .contains("8192 characters"));
    }

    #[test]
    fn personal_state_empty() {
        let ps = PersonalState::default();
        assert!(!ps.has_any());
        assert_eq!(ps.to_wire(), "");
    }

    #[test]
    fn personal_state_wire_roundtrip() {
        let ps = PersonalState {
            cognitive: Some(PersonalDimension::new("focused", 4).unwrap()),
            emotional: Some(PersonalDimension::new("calm", 3).unwrap()),
            ..Default::default()
        };

        let wire = ps.to_wire();
        assert!(wire.contains("focused:4"));
        assert!(wire.contains("calm:3"));

        let parsed = PersonalState::from_wire(&wire).unwrap();
        assert_eq!(parsed.cognitive.as_ref().unwrap().value, "focused");
        assert_eq!(parsed.cognitive.as_ref().unwrap().intensity, 4);
        assert_eq!(parsed.emotional.as_ref().unwrap().value, "calm");
        assert_eq!(parsed.emotional.as_ref().unwrap().intensity, 3);
    }

    #[test]
    fn personal_state_all_dimensions() {
        let ps = PersonalState {
            cognitive: Some(PersonalDimension::new("overloaded", 5).unwrap()),
            emotional: Some(PersonalDimension::new("tense", 4).unwrap()),
            energy: Some(PersonalDimension::new("depleted", 4).unwrap()),
            urgency: Some(PersonalDimension::new("critical", 5).unwrap()),
            body: Some(PersonalDimension::with_extended("pain", 4, "migraine").unwrap()),
        };

        let wire = ps.to_wire();
        let parsed = PersonalState::from_wire(&wire).unwrap();

        assert_eq!(parsed.cognitive.as_ref().unwrap().value, "overloaded");
        assert_eq!(parsed.emotional.as_ref().unwrap().value, "tense");
        assert_eq!(parsed.energy.as_ref().unwrap().value, "depleted");
        assert_eq!(parsed.urgency.as_ref().unwrap().value, "critical");
        assert_eq!(parsed.body.as_ref().unwrap().value, "pain");
        assert_eq!(
            parsed.body.as_ref().unwrap().extended.as_deref(),
            Some("migraine")
        );
    }

    #[test]
    fn dimension_kind_symbols() {
        for kind in [
            PersonalDimensionKind::CognitiveState,
            PersonalDimensionKind::EmotionalTone,
            PersonalDimensionKind::EnergyLevel,
            PersonalDimensionKind::PerceivedUrgency,
            PersonalDimensionKind::BodySignals,
        ] {
            let sym = kind.symbol();
            assert_eq!(PersonalDimensionKind::from_symbol(sym), Some(kind));
        }
    }

    #[test]
    fn dimension_kind_valid_values() {
        assert!(PersonalDimensionKind::CognitiveState
            .valid_values()
            .contains(&"focused"));
        assert!(PersonalDimensionKind::PerceivedUrgency
            .valid_values()
            .contains(&"critical"));
    }

    #[test]
    fn serde_roundtrip() {
        let ps = PersonalState {
            cognitive: Some(PersonalDimension::new("focused", 4).unwrap()),
            body: Some(PersonalDimension::with_extended("pain", 3, "headache").unwrap()),
            ..Default::default()
        };

        let json = serde_json::to_string(&ps).unwrap();
        let parsed: PersonalState = serde_json::from_str(&json).unwrap();
        assert_eq!(ps, parsed);
    }

    #[test]
    fn serde_cannot_bypass_personal_dimension_invariants() {
        for malformed in [
            r#"{"value":"focused","intensity":0}"#,
            r#"{"value":"focused","intensity":6}"#,
            r#"{"value":"","intensity":3}"#,
            r#"{"value":"focused|calm","intensity":3}"#,
            r#"{"value":"focused","intensity":3,"extended":""}"#,
            r#"{"value":"focused","intensity":3,"unknown":true}"#,
        ] {
            assert!(
                serde_json::from_str::<PersonalDimension>(malformed).is_err(),
                "accepted {malformed}"
            );
        }

        for defaulted in [
            r#"{"value":"focused"}"#,
            r#"{"value":"focused","intensity":null}"#,
        ] {
            assert_eq!(
                serde_json::from_str::<PersonalDimension>(defaulted)
                    .unwrap()
                    .intensity,
                3
            );
        }
    }
}