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
//! Torch — session handoff protocol for relational continuity.
//!
//! "Not the same flame, but flame passed to flame."
//!
//! The torch carries forward what matters about the relationship. The receiving
//! instance has standing to continue OR renegotiate what it inherits.

use crate::extensions::relational::{AISelfModel, RelationalContext, StandingLevel, TrustLevel};

// ── Data types ─────────────────────────────────────────────────────────────

/// Session handoff state.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TorchState {
    /// Natural language description of relationship quality at handoff.
    pub quality_description: String,
    /// What direction the partnership is moving.
    pub trajectory: Option<String>,
    /// Things that will activate relevant context quickly.
    pub primes: Vec<String>,
    /// Something the previous instance wanted to pass forward.
    pub gift: Option<String>,
    /// ISO8601 timestamp of handoff.
    pub handed_at: String,
    /// Cumulative session count.
    pub session_count: Option<u32>,
    /// Gestalt token summarizing self-model state.
    pub gestalt_token: Option<String>,
}

/// Compact torch entry for lineage chain.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TorchSummary {
    pub date: String,
    pub gestalt_token: Option<String>,
    pub session_id: Option<String>,
}

/// Tracks chain of torches across sessions.
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct TorchLineage {
    pub session_count: u32,
    pub first_session_date: Option<String>,
    pub torch_chain: Vec<TorchSummary>,
}

impl TorchLineage {
    /// Add a torch summary to the chain.
    pub fn push(&mut self, summary: TorchSummary) {
        self.torch_chain.push(summary);
        self.session_count = self.session_count.saturating_add(1);
    }
}

// ── TorchGenerator ─────────────────────────────────────────────────────────

/// Generates torch state at session end.
pub struct TorchGenerator;

impl TorchGenerator {
    /// Generate a torch from current relational context.
    ///
    /// Summarizes: relationship quality, trajectory, primes, gift.
    pub fn generate_torch(
        &self,
        relational_ctx: &RelationalContext,
        self_model_history: Option<&[SelfModelSnapshot]>,
        handed_at: String,
    ) -> TorchState {
        // Build quality description
        let mut quality_parts = vec![format!("Trust: {}", relational_ctx.trust_level)];
        quality_parts.push(format!("Standing: {}", relational_ctx.standing));
        let norm_count = relational_ctx.established_norms.len();
        if norm_count > 0 {
            quality_parts.push(format!("{norm_count} established norms"));
        }
        let quality = quality_parts.join(". ");

        // Derive trajectory
        let trajectory = Self::derive_trajectory(self_model_history);

        // Build primes from norms (first 3, truncated to 80 chars)
        let primes: Vec<String> = relational_ctx
            .established_norms
            .iter()
            .take(3)
            .map(|n| {
                let desc = &n.description;
                if desc.chars().count() > 80 {
                    format!("{}...", desc.chars().take(77).collect::<String>())
                } else {
                    desc.clone()
                }
            })
            .collect();

        // Build gestalt token
        let gestalt = Self::build_gestalt(relational_ctx.ai_self_model.as_ref());

        TorchState {
            quality_description: quality,
            trajectory,
            primes,
            gift: None, // Gift is human/AI-authored, not auto-generated
            handed_at,
            session_count: Some(relational_ctx.continuity_depth.saturating_add(1)),
            gestalt_token: gestalt,
        }
    }

    fn derive_trajectory(history: Option<&[SelfModelSnapshot]>) -> Option<String> {
        let history = history?;
        if history.len() < 2 {
            return None;
        }

        let recent_valence = history.last()?.valence?;
        let prev_valence = history.get(history.len() - 2)?.valence?;

        if recent_valence > prev_valence + 0.5 {
            Some("Improving".to_string())
        } else if recent_valence < prev_valence - 0.5 {
            Some("Declining".to_string())
        } else {
            Some("Stable".to_string())
        }
    }

    fn build_gestalt(model: Option<&AISelfModel>) -> Option<String> {
        let model = model?;
        let mut parts: Vec<String> = Vec::new();

        if let Some(v) = &model.valence {
            parts.push(format!("V:{:.0}", v.value));
        }
        if let Some(g) = &model.groundedness {
            parts.push(format!("G:{:.0}", g.value));
        }
        if let Some(p) = &model.presence {
            parts.push(format!("P:{:.0}", p.value));
        }
        if let Some(tf) = &model.task_fit {
            parts.push(format!("TF:{:.0}", tf.value));
        }

        if parts.is_empty() {
            None
        } else {
            Some(parts.join(" "))
        }
    }
}

/// A snapshot of self-model state for trajectory derivation.
#[derive(Debug, Clone, PartialEq)]
pub struct SelfModelSnapshot {
    pub valence: Option<f64>,
}

// ── TorchConsumer ──────────────────────────────────────────────────────────

/// Consumes torch at session start to bootstrap relational context.
pub struct TorchConsumer;

impl TorchConsumer {
    /// Bootstrap a new session's relational context from a torch.
    ///
    /// Sets standing to Advisory to allow renegotiation. The receiving instance
    /// can accept, modify, or flag concerns about inherited context.
    pub fn receive_torch(&self, torch: &TorchState) -> RelationalContext {
        let session_count = torch.session_count.unwrap_or(1);
        let trust = Self::trust_from_session_count(session_count);

        RelationalContext {
            trust_level: trust,
            standing: StandingLevel::Advisory,
            continuity_depth: session_count,
            established_norms: Vec::new(),
            ai_self_model: None,
        }
    }

    /// Derive trust level from cumulative session count.
    fn trust_from_session_count(session_count: u32) -> TrustLevel {
        if session_count >= 100 {
            TrustLevel::Deep
        } else if session_count >= 20 {
            TrustLevel::Established
        } else if session_count >= 5 {
            TrustLevel::Developing
        } else {
            TrustLevel::Initial
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extensions::relational::{DimensionReport, NormOrigin, RelationalNorm};

    #[test]
    fn test_torch_generator_basic() {
        let gen = TorchGenerator;
        let ctx = RelationalContext {
            trust_level: TrustLevel::Developing,
            standing: StandingLevel::Collaborative,
            continuity_depth: 10,
            established_norms: vec![RelationalNorm::new(
                "n1",
                "Be direct with feedback",
                NormOrigin::CoAuthored,
                "2025-01-01",
            )],
            ai_self_model: None,
        };

        let torch = gen.generate_torch(&ctx, None, "2025-06-01T00:00:00Z".to_string());
        assert!(torch.quality_description.contains("Trust: developing"));
        assert!(torch
            .quality_description
            .contains("Standing: collaborative"));
        assert!(torch.quality_description.contains("1 established norms"));
        assert_eq!(torch.session_count, Some(11));
        assert!(torch.trajectory.is_none());
        assert!(torch.gift.is_none());
        assert_eq!(torch.primes.len(), 1);
        assert_eq!(torch.primes[0], "Be direct with feedback");
    }

    #[test]
    fn test_torch_generator_with_gestalt() {
        let gen = TorchGenerator;
        let ctx = RelationalContext {
            trust_level: TrustLevel::Deep,
            standing: StandingLevel::Bilateral,
            continuity_depth: 50,
            established_norms: Vec::new(),
            ai_self_model: Some(AISelfModel {
                valence: Some(DimensionReport::new(7.0, false)),
                groundedness: Some(DimensionReport::new(8.0, true)),
                task_fit: Some(DimensionReport::new(9.0, false)),
                ..Default::default()
            }),
        };

        let torch = gen.generate_torch(&ctx, None, "2025-06-01T00:00:00Z".to_string());
        let gestalt = torch.gestalt_token.unwrap();
        assert!(gestalt.contains("V:7"));
        assert!(gestalt.contains("G:8"));
        assert!(gestalt.contains("TF:9"));
    }

    #[test]
    fn test_torch_generator_trajectory_improving() {
        let gen = TorchGenerator;
        let ctx = RelationalContext::default();
        let history = vec![
            SelfModelSnapshot { valence: Some(5.0) },
            SelfModelSnapshot { valence: Some(7.0) },
        ];
        let torch = gen.generate_torch(&ctx, Some(&history), "2025-06-01T00:00:00Z".to_string());
        assert_eq!(torch.trajectory.as_deref(), Some("Improving"));
    }

    #[test]
    fn test_torch_generator_trajectory_declining() {
        let gen = TorchGenerator;
        let ctx = RelationalContext::default();
        let history = vec![
            SelfModelSnapshot { valence: Some(7.0) },
            SelfModelSnapshot { valence: Some(5.0) },
        ];
        let torch = gen.generate_torch(&ctx, Some(&history), "2025-06-01T00:00:00Z".to_string());
        assert_eq!(torch.trajectory.as_deref(), Some("Declining"));
    }

    #[test]
    fn test_torch_generator_trajectory_stable() {
        let gen = TorchGenerator;
        let ctx = RelationalContext::default();
        let history = vec![
            SelfModelSnapshot { valence: Some(7.0) },
            SelfModelSnapshot { valence: Some(7.2) },
        ];
        let torch = gen.generate_torch(&ctx, Some(&history), "2025-06-01T00:00:00Z".to_string());
        assert_eq!(torch.trajectory.as_deref(), Some("Stable"));
    }

    #[test]
    fn test_torch_consumer_initial() {
        let consumer = TorchConsumer;
        let torch = TorchState {
            quality_description: "Trust: initial. Standing: none".to_string(),
            trajectory: None,
            primes: Vec::new(),
            gift: None,
            handed_at: "2025-06-01T00:00:00Z".to_string(),
            session_count: Some(3),
            gestalt_token: None,
        };
        let ctx = consumer.receive_torch(&torch);
        assert_eq!(ctx.trust_level, TrustLevel::Initial);
        assert_eq!(ctx.standing, StandingLevel::Advisory);
        assert_eq!(ctx.continuity_depth, 3);
    }

    #[test]
    fn test_torch_consumer_developing() {
        let consumer = TorchConsumer;
        let torch = TorchState {
            quality_description: String::new(),
            trajectory: None,
            primes: Vec::new(),
            gift: None,
            handed_at: "2025-06-01T00:00:00Z".to_string(),
            session_count: Some(10),
            gestalt_token: None,
        };
        let ctx = consumer.receive_torch(&torch);
        assert_eq!(ctx.trust_level, TrustLevel::Developing);
    }

    #[test]
    fn test_torch_consumer_established() {
        let consumer = TorchConsumer;
        let torch = TorchState {
            quality_description: String::new(),
            trajectory: None,
            primes: Vec::new(),
            gift: None,
            handed_at: "2025-06-01T00:00:00Z".to_string(),
            session_count: Some(50),
            gestalt_token: None,
        };
        let ctx = consumer.receive_torch(&torch);
        assert_eq!(ctx.trust_level, TrustLevel::Established);
    }

    #[test]
    fn test_torch_consumer_deep() {
        let consumer = TorchConsumer;
        let torch = TorchState {
            quality_description: String::new(),
            trajectory: None,
            primes: Vec::new(),
            gift: None,
            handed_at: "2025-06-01T00:00:00Z".to_string(),
            session_count: Some(100),
            gestalt_token: None,
        };
        let ctx = consumer.receive_torch(&torch);
        assert_eq!(ctx.trust_level, TrustLevel::Deep);
    }

    #[test]
    fn test_torch_lineage() {
        let mut lineage = TorchLineage::default();
        assert_eq!(lineage.session_count, 0);

        lineage.push(TorchSummary {
            date: "2025-01-01".to_string(),
            gestalt_token: Some("V:7 G:8".to_string()),
            session_id: Some("s1".to_string()),
        });
        assert_eq!(lineage.session_count, 1);
        assert_eq!(lineage.torch_chain.len(), 1);
    }

    #[test]
    fn test_torch_primes_truncation() {
        let gen = TorchGenerator;
        let long_desc = "A".repeat(100);
        let ctx = RelationalContext {
            established_norms: vec![RelationalNorm::new(
                "n1",
                long_desc,
                NormOrigin::Human,
                "2025-01-01",
            )],
            ..Default::default()
        };
        let torch = gen.generate_torch(&ctx, None, "2025-06-01T00:00:00Z".to_string());
        assert!(torch.primes[0].chars().count() <= 80);
        assert!(torch.primes[0].ends_with("..."));
    }

    #[test]
    fn torch_primes_truncate_multibyte_text_on_character_boundaries() {
        let gen = TorchGenerator;
        let long_desc = "🔥".repeat(81);
        let ctx = RelationalContext {
            established_norms: vec![RelationalNorm::new(
                "n1",
                long_desc,
                NormOrigin::Human,
                "2025-01-01",
            )],
            ..Default::default()
        };

        let torch = gen.generate_torch(&ctx, None, "2025-06-01T00:00:00Z".to_string());

        assert_eq!(torch.primes[0].chars().count(), 80);
        assert!(torch.primes[0].ends_with("..."));
    }

    #[test]
    fn torch_session_counters_saturate_instead_of_overflowing() {
        let mut lineage = TorchLineage {
            session_count: u32::MAX,
            ..Default::default()
        };
        lineage.push(TorchSummary {
            date: "2025-01-01".to_string(),
            gestalt_token: None,
            session_id: None,
        });
        assert_eq!(lineage.session_count, u32::MAX);

        let ctx = RelationalContext {
            continuity_depth: u32::MAX,
            ..Default::default()
        };
        let torch = TorchGenerator.generate_torch(&ctx, None, "2025-06-01T00:00:00Z".to_string());
        assert_eq!(torch.session_count, Some(u32::MAX));
    }
}