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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! Personal state signals for VCP v3.1.
//!
//! Provides categorical personal dimensions (cognitive state, emotional tone,
//! energy level, perceived urgency, body signals) with 1-5 intensity and
//! exponential/linear/step decay over time.

use std::fmt;
use std::time::SystemTime;

// ── Enums ──────────────────────────────────────────────────────────────────

/// The 5 personal state dimensions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum PersonalDimension {
    CognitiveState,
    EmotionalTone,
    EnergyLevel,
    PerceivedUrgency,
    BodySignals,
}

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

/// Source of a personal signal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum SignalSource {
    Declared,
    Inferred,
    InferredLocal,
    Preset,
    Decayed,
}

/// Lifecycle state for a personal dimension signal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LifecycleState {
    /// Just declared (t=0).
    Set,
    /// Within fresh window, minimal decay.
    Active,
    /// Intensity actively declining.
    Decaying,
    /// Below usefulness threshold but above baseline.
    Stale,
    /// At baseline, effectively cleared.
    Expired,
}

/// Decay curve shapes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum DecayCurve {
    Exponential,
    Linear,
    Step,
}

// ── Structs ────────────────────────────────────────────────────────────────

/// A single personal state signal with category + intensity.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PersonalSignal {
    /// Categorical value (e.g., "focused", "calm").
    pub category: String,
    /// Signal intensity 1-5 (1=minimal, 5=strong).
    pub intensity: u8,
    /// How this signal was obtained.
    pub source: SignalSource,
    /// Confidence in this signal (0.0-1.0).
    pub confidence: f64,
    /// When signal was declared (for decay). Uses `SystemTime`.
    pub declared_at: Option<SystemTime>,
}

impl PersonalSignal {
    /// Create a new personal signal. Intensity is clamped to [1, 5].
    pub fn new(category: impl Into<String>, intensity: u8) -> Self {
        Self {
            category: category.into(),
            intensity: intensity.clamp(1, 5),
            source: SignalSource::Declared,
            confidence: 1.0,
            declared_at: None,
        }
    }

    /// Set the source of this signal.
    #[must_use]
    pub fn with_source(mut self, source: SignalSource) -> Self {
        self.source = source;
        self
    }

    /// Set the confidence of this signal.
    #[must_use]
    pub fn with_confidence(mut self, confidence: f64) -> Self {
        self.confidence = confidence.clamp(0.0, 1.0);
        self
    }

    /// Set the declaration time for decay.
    #[must_use]
    pub fn with_declared_at(mut self, at: SystemTime) -> Self {
        self.declared_at = Some(at);
        self
    }
}

/// Personal state context (5 dimensions).
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct PersonalContext {
    pub cognitive_state: Option<PersonalSignal>,
    pub emotional_tone: Option<PersonalSignal>,
    pub energy_level: Option<PersonalSignal>,
    pub perceived_urgency: Option<PersonalSignal>,
    pub body_signals: Option<PersonalSignal>,
}

impl PersonalContext {
    /// Check if any personal signal is set.
    pub fn has_any_signal(&self) -> bool {
        self.cognitive_state.is_some()
            || self.emotional_tone.is_some()
            || self.energy_level.is_some()
            || self.perceived_urgency.is_some()
            || self.body_signals.is_some()
    }
}

/// A discrete intensity step for step-curve decay.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct StepThreshold {
    /// Time after declaration when this step activates.
    pub after_seconds: f64,
    /// The intensity value for this step.
    pub intensity: u8,
}

/// Configuration for signal decay behavior.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DecayConfig {
    /// Half-life in seconds (for exponential decay).
    pub half_life_seconds: f64,
    /// Integer baseline (1 = signal clears).
    pub baseline: u8,
    /// Whether engagement resets the decay timer.
    pub reset_on_engagement: bool,
    /// Decay curve shape.
    pub curve: DecayCurve,
    /// Fraction of declared intensity marking staleness.
    pub stale_threshold: f64,
    /// Seconds in ACTIVE before DECAYING.
    pub fresh_window_seconds: f64,
    /// Whether this signal is pinned (never decays).
    pub pinned: bool,
    /// For linear curve: total seconds until fully decayed.
    pub full_decay_seconds: Option<f64>,
    /// For step curve: discrete intensity thresholds.
    pub step_thresholds: Vec<StepThreshold>,
}

impl DecayConfig {
    /// Create a new exponential decay config with the given half-life.
    pub fn exponential(half_life_seconds: f64) -> Self {
        Self {
            half_life_seconds,
            baseline: 1,
            reset_on_engagement: false,
            curve: DecayCurve::Exponential,
            stale_threshold: 0.3,
            fresh_window_seconds: 60.0,
            pinned: false,
            full_decay_seconds: None,
            step_thresholds: Vec::new(),
        }
    }

    /// Create a linear decay config.
    pub fn linear(full_decay_seconds: f64) -> Self {
        Self {
            half_life_seconds: 0.0,
            baseline: 1,
            reset_on_engagement: false,
            curve: DecayCurve::Linear,
            stale_threshold: 0.3,
            fresh_window_seconds: 60.0,
            pinned: false,
            full_decay_seconds: Some(full_decay_seconds),
            step_thresholds: Vec::new(),
        }
    }

    /// Set the baseline intensity.
    #[must_use]
    pub fn with_baseline(mut self, baseline: u8) -> Self {
        self.baseline = baseline;
        self
    }

    /// Set the reset-on-engagement flag.
    #[must_use]
    pub fn with_reset_on_engagement(mut self, reset: bool) -> Self {
        self.reset_on_engagement = reset;
        self
    }

    /// Set the pinned flag.
    #[must_use]
    pub fn with_pinned(mut self, pinned: bool) -> Self {
        self.pinned = pinned;
        self
    }

    /// Set the stale threshold (fraction of the declared range above baseline).
    #[must_use]
    pub fn with_stale_threshold(mut self, stale_threshold: f64) -> Self {
        self.stale_threshold = stale_threshold;
        self
    }

    /// Set the fresh window (seconds in ACTIVE before DECAYING).
    #[must_use]
    pub fn with_fresh_window_seconds(mut self, fresh_window_seconds: f64) -> Self {
        self.fresh_window_seconds = fresh_window_seconds;
        self
    }
}

// ── Default decay configs per dimension ────────────────────────────────────

/// Returns the default decay configuration for a given personal dimension
/// (VCP-X-Personal §3.3).
pub fn default_decay_config(dim: PersonalDimension) -> DecayConfig {
    match dim {
        PersonalDimension::PerceivedUrgency => DecayConfig::exponential(900.0) // 15 min
            .with_stale_threshold(0.35)
            .with_fresh_window_seconds(60.0),
        PersonalDimension::BodySignals => DecayConfig::exponential(14400.0) // 4 hours
            .with_stale_threshold(0.15)
            .with_fresh_window_seconds(600.0),
        PersonalDimension::CognitiveState => DecayConfig::exponential(720.0) // 12 min
            .with_reset_on_engagement(true)
            .with_stale_threshold(0.3)
            .with_fresh_window_seconds(60.0),
        PersonalDimension::EmotionalTone => DecayConfig::exponential(1800.0) // 30 min
            .with_stale_threshold(0.25)
            .with_fresh_window_seconds(60.0),
        PersonalDimension::EnergyLevel => DecayConfig::exponential(7200.0) // 2 hours
            .with_stale_threshold(0.2)
            .with_fresh_window_seconds(300.0),
    }
}

// ── Decay computation ──────────────────────────────────────────────────────

/// Compute decayed intensity using exponential decay.
///
/// result = max(baseline, floor(baseline + (declared - baseline) * exp(-lambda * t)))
///
/// When intensity decays to baseline (1), the signal effectively clears.
///
pub fn compute_decayed_intensity(
    declared_intensity: u8,
    declared_at: SystemTime,
    config: &DecayConfig,
    now: SystemTime,
) -> u8 {
    if config.pinned {
        return declared_intensity;
    }

    let elapsed = match now.duration_since(declared_at) {
        Ok(d) => d.as_secs_f64(),
        Err(_) => return declared_intensity, // now is before declared_at
    };

    if elapsed <= 0.0 {
        return declared_intensity;
    }

    match config.curve {
        DecayCurve::Exponential => {
            if !config.half_life_seconds.is_finite() || config.half_life_seconds <= 0.0 {
                return declared_intensity;
            }
            if declared_intensity <= config.baseline {
                return config.baseline;
            }
            let lambda = (2.0_f64).ln() / config.half_life_seconds;
            let decayed = f64::from(config.baseline)
                + f64::from(declared_intensity.saturating_sub(config.baseline))
                    * (-lambda * elapsed).exp();
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let floored = decayed.clamp(0.0, 255.0).floor() as u8;
            floored.max(config.baseline)
        }
        DecayCurve::Linear => {
            let full_decay = match config.full_decay_seconds {
                Some(fd) if fd.is_finite() && fd > 0.0 => fd,
                _ => return declared_intensity,
            };
            if declared_intensity <= config.baseline {
                return config.baseline;
            }
            let fraction = (elapsed / full_decay).min(1.0);
            let decayed = f64::from(declared_intensity)
                - f64::from(declared_intensity.saturating_sub(config.baseline)) * fraction;
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let floored = decayed.clamp(0.0, 255.0).floor() as u8;
            floored.max(config.baseline)
        }
        DecayCurve::Step => {
            if config.step_thresholds.is_empty() {
                return declared_intensity;
            }
            // Sort thresholds descending by after_seconds, pick the first that applies.
            let mut sorted: Vec<&StepThreshold> = config
                .step_thresholds
                .iter()
                .filter(|threshold| {
                    threshold.after_seconds.is_finite() && threshold.after_seconds >= 0.0
                })
                .collect();
            sorted.sort_by(|a, b| b.after_seconds.total_cmp(&a.after_seconds));
            for threshold in &sorted {
                if elapsed >= threshold.after_seconds {
                    return threshold.intensity.max(config.baseline);
                }
            }
            declared_intensity
        }
    }
}

/// Compute the lifecycle state for a personal dimension signal.
pub fn compute_lifecycle_state(
    declared_intensity: u8,
    declared_at: SystemTime,
    config: &DecayConfig,
    now: SystemTime,
) -> LifecycleState {
    if config.pinned {
        return LifecycleState::Active;
    }

    let elapsed = match now.duration_since(declared_at) {
        Ok(d) => d.as_secs_f64(),
        Err(_) => return LifecycleState::Set,
    };

    if elapsed <= 0.0 {
        return LifecycleState::Set;
    }

    if elapsed < config.fresh_window_seconds {
        return LifecycleState::Active;
    }

    let effective = compute_decayed_intensity(declared_intensity, declared_at, config, now);

    if effective <= config.baseline {
        return LifecycleState::Expired;
    }

    let stale_level = f64::from(config.baseline)
        + f64::from(declared_intensity - config.baseline) * config.stale_threshold;

    if f64::from(effective) <= stale_level {
        LifecycleState::Stale
    } else {
        LifecycleState::Decaying
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    fn time_plus_secs(base: SystemTime, secs: f64) -> SystemTime {
        base + Duration::from_secs_f64(secs)
    }

    #[test]
    fn test_personal_signal_clamps_intensity() {
        let sig = PersonalSignal::new("focused", 0);
        assert_eq!(sig.intensity, 1);
        let sig = PersonalSignal::new("focused", 10);
        assert_eq!(sig.intensity, 5);
        let sig = PersonalSignal::new("focused", 3);
        assert_eq!(sig.intensity, 3);
    }

    #[test]
    fn test_personal_context_has_any_signal() {
        let ctx = PersonalContext::default();
        assert!(!ctx.has_any_signal());

        let ctx = PersonalContext {
            cognitive_state: Some(PersonalSignal::new("focused", 3)),
            ..Default::default()
        };
        assert!(ctx.has_any_signal());
    }

    #[test]
    fn test_exponential_decay_no_elapsed() {
        let config = DecayConfig::exponential(900.0);
        let now = SystemTime::now();
        let result = compute_decayed_intensity(5, now, &config, now);
        assert_eq!(result, 5);
    }

    #[test]
    fn test_exponential_decay_one_half_life() {
        let config = DecayConfig::exponential(900.0);
        let base = SystemTime::now();
        let now = time_plus_secs(base, 900.0);
        // declared=5, baseline=1, after 1 half-life:
        // 1 + (5-1) * 0.5 = 1 + 2.0 = 3.0 -> floor = 3
        let result = compute_decayed_intensity(5, base, &config, now);
        assert_eq!(result, 3);
    }

    #[test]
    fn test_exponential_decay_many_half_lives() {
        let config = DecayConfig::exponential(900.0);
        let base = SystemTime::now();
        let now = time_plus_secs(base, 9000.0); // 10 half-lives
        let result = compute_decayed_intensity(5, base, &config, now);
        assert_eq!(result, 1); // should be at baseline
    }

    #[test]
    fn test_pinned_never_decays() {
        let config = DecayConfig::exponential(900.0).with_pinned(true);
        let base = SystemTime::now();
        let now = time_plus_secs(base, 99999.0);
        let result = compute_decayed_intensity(5, base, &config, now);
        assert_eq!(result, 5);
    }

    #[test]
    fn test_linear_decay() {
        let config = DecayConfig::linear(100.0);
        let base = SystemTime::now();
        // At 50% through: 5 - (5-1)*0.5 = 5 - 2 = 3
        let now = time_plus_secs(base, 50.0);
        let result = compute_decayed_intensity(5, base, &config, now);
        assert_eq!(result, 3);
    }

    #[test]
    fn test_linear_decay_fully_elapsed() {
        let config = DecayConfig::linear(100.0);
        let base = SystemTime::now();
        let now = time_plus_secs(base, 200.0);
        let result = compute_decayed_intensity(5, base, &config, now);
        assert_eq!(result, 1);
    }

    #[test]
    fn test_step_decay() {
        let config = DecayConfig {
            half_life_seconds: 0.0,
            baseline: 1,
            reset_on_engagement: false,
            curve: DecayCurve::Step,
            stale_threshold: 0.3,
            fresh_window_seconds: 60.0,
            pinned: false,
            full_decay_seconds: None,
            step_thresholds: vec![
                StepThreshold {
                    after_seconds: 60.0,
                    intensity: 4,
                },
                StepThreshold {
                    after_seconds: 120.0,
                    intensity: 3,
                },
                StepThreshold {
                    after_seconds: 300.0,
                    intensity: 1,
                },
            ],
        };
        let base = SystemTime::now();

        // Before first threshold
        assert_eq!(
            compute_decayed_intensity(5, base, &config, time_plus_secs(base, 30.0)),
            5
        );
        // After first threshold
        assert_eq!(
            compute_decayed_intensity(5, base, &config, time_plus_secs(base, 90.0)),
            4
        );
        // After second threshold
        assert_eq!(
            compute_decayed_intensity(5, base, &config, time_plus_secs(base, 200.0)),
            3
        );
        // After third threshold
        assert_eq!(
            compute_decayed_intensity(5, base, &config, time_plus_secs(base, 500.0)),
            1
        );
    }

    #[test]
    fn invalid_decay_parameters_are_ignored_without_panicking() {
        let base = SystemTime::now();
        let now = time_plus_secs(base, 120.0);

        for half_life in [0.0, -1.0, f64::NAN, f64::INFINITY] {
            let config = DecayConfig::exponential(half_life);
            assert_eq!(compute_decayed_intensity(5, base, &config, now), 5);
        }

        let mut config = DecayConfig::linear(f64::INFINITY);
        assert_eq!(compute_decayed_intensity(5, base, &config, now), 5);

        config.curve = DecayCurve::Step;
        config.step_thresholds = vec![
            StepThreshold {
                after_seconds: f64::NAN,
                intensity: 1,
            },
            StepThreshold {
                after_seconds: -1.0,
                intensity: 2,
            },
            StepThreshold {
                after_seconds: 60.0,
                intensity: 3,
            },
        ];
        assert_eq!(compute_decayed_intensity(5, base, &config, now), 3);
    }

    #[test]
    fn test_lifecycle_state_set() {
        let config = DecayConfig::exponential(900.0);
        let now = SystemTime::now();
        let state = compute_lifecycle_state(5, now, &config, now);
        assert_eq!(state, LifecycleState::Set);
    }

    #[test]
    fn test_lifecycle_state_active() {
        let config = DecayConfig::exponential(900.0);
        let base = SystemTime::now();
        let now = time_plus_secs(base, 30.0); // within 60s fresh window
        let state = compute_lifecycle_state(5, base, &config, now);
        assert_eq!(state, LifecycleState::Active);
    }

    #[test]
    fn test_lifecycle_state_expired() {
        let config = DecayConfig::exponential(900.0);
        let base = SystemTime::now();
        let now = time_plus_secs(base, 99999.0);
        let state = compute_lifecycle_state(5, base, &config, now);
        assert_eq!(state, LifecycleState::Expired);
    }

    #[test]
    fn test_lifecycle_state_pinned() {
        let config = DecayConfig::exponential(900.0).with_pinned(true);
        let base = SystemTime::now();
        let now = time_plus_secs(base, 99999.0);
        let state = compute_lifecycle_state(5, base, &config, now);
        assert_eq!(state, LifecycleState::Active);
    }

    #[test]
    fn test_default_decay_configs() {
        // Values per VCP-X-Personal §3.3.
        let urg = default_decay_config(PersonalDimension::PerceivedUrgency);
        assert!((urg.half_life_seconds - 900.0).abs() < f64::EPSILON);
        assert!(!urg.reset_on_engagement);
        assert!((urg.stale_threshold - 0.35).abs() < f64::EPSILON);
        assert!((urg.fresh_window_seconds - 60.0).abs() < f64::EPSILON);

        let cog = default_decay_config(PersonalDimension::CognitiveState);
        assert!((cog.half_life_seconds - 720.0).abs() < f64::EPSILON);
        assert!(cog.reset_on_engagement);
        assert!((cog.stale_threshold - 0.3).abs() < f64::EPSILON);
        assert!((cog.fresh_window_seconds - 60.0).abs() < f64::EPSILON);

        let emo = default_decay_config(PersonalDimension::EmotionalTone);
        assert!((emo.half_life_seconds - 1800.0).abs() < f64::EPSILON);
        assert!((emo.stale_threshold - 0.25).abs() < f64::EPSILON);
        assert!((emo.fresh_window_seconds - 60.0).abs() < f64::EPSILON);

        let energy = default_decay_config(PersonalDimension::EnergyLevel);
        assert!((energy.half_life_seconds - 7200.0).abs() < f64::EPSILON);
        assert!((energy.stale_threshold - 0.2).abs() < f64::EPSILON);
        assert!((energy.fresh_window_seconds - 300.0).abs() < f64::EPSILON);

        let body = default_decay_config(PersonalDimension::BodySignals);
        assert!((body.half_life_seconds - 14400.0).abs() < f64::EPSILON);
        assert!((body.stale_threshold - 0.15).abs() < f64::EPSILON);
        assert!((body.fresh_window_seconds - 600.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_personal_dimension_display() {
        assert_eq!(
            PersonalDimension::CognitiveState.to_string(),
            "cognitive_state"
        );
        assert_eq!(PersonalDimension::BodySignals.to_string(), "body_signals");
    }
}