vex_core/
context.rs

1//! Context packets for VEX agents
2//!
3//! A [`ContextPacket`] is the unit of information passed between agents,
4//! with temporal metadata and cryptographic hashing.
5
6use crate::merkle::Hash;
7use chrono::{DateTime, Duration, Utc};
8use serde::{Deserialize, Serialize};
9use sha2::{Digest, Sha256};
10use uuid::Uuid;
11
12/// Compression level for context packets
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14pub enum CompressionLevel {
15    /// Full fidelity - no compression
16    Full,
17    /// Summary - moderate compression
18    Summary,
19    /// Abstract - high compression, key points only
20    Abstract,
21    /// Minimal - extreme compression
22    Minimal,
23}
24
25impl CompressionLevel {
26    /// Get the numeric compression ratio (0.0 = full, 1.0 = minimal)
27    pub fn ratio(&self) -> f64 {
28        match self {
29            Self::Full => 0.0,
30            Self::Summary => 0.3,
31            Self::Abstract => 0.6,
32            Self::Minimal => 0.9,
33        }
34    }
35}
36
37/// A context packet - the unit of information in VEX
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct ContextPacket {
40    /// Unique identifier for this packet
41    pub id: Uuid,
42    /// The actual content
43    pub content: String,
44    /// When this context was created
45    pub created_at: DateTime<Utc>,
46    /// When this context expires (if applicable)
47    pub expires_at: Option<DateTime<Utc>>,
48    /// Compression level applied
49    pub compression: CompressionLevel,
50    /// SHA-256 hash of the content
51    pub hash: Hash,
52    /// Hash of the parent packet (for chaining)
53    pub parent_hash: Option<Hash>,
54    /// Source agent ID
55    pub source_agent: Option<Uuid>,
56    /// Importance score (0.0 - 1.0)
57    pub importance: f64,
58}
59
60/// Maximum allowed context content size in bytes (50KB)
61pub const MAX_CONTENT_SIZE: usize = 50 * 1024;
62
63impl ContextPacket {
64    /// Create a new context packet with the given content
65    /// Content is truncated if it exceeds MAX_CONTENT_SIZE
66    pub fn new(content: &str) -> Self {
67        // Truncate content if too large to prevent memory exhaustion
68        let content = if content.len() > MAX_CONTENT_SIZE {
69            tracing::warn!(
70                size = content.len(),
71                max = MAX_CONTENT_SIZE,
72                "Context content truncated"
73            );
74            &content[..MAX_CONTENT_SIZE]
75        } else {
76            content
77        };
78
79        let hash = Self::compute_hash(content);
80        Self {
81            id: Uuid::new_v4(),
82            content: content.to_string(),
83            created_at: Utc::now(),
84            expires_at: None,
85            compression: CompressionLevel::Full,
86            hash,
87            parent_hash: None,
88            source_agent: None,
89            importance: 0.5,
90        }
91    }
92
93    /// Create a context packet with a TTL (time-to-live)
94    pub fn with_ttl(content: &str, ttl: Duration) -> Self {
95        let mut packet = Self::new(content);
96        packet.expires_at = Some(Utc::now() + ttl);
97        packet
98    }
99
100    /// Compute SHA-256 hash of content
101    pub fn compute_hash(content: &str) -> Hash {
102        let mut hasher = Sha256::new();
103        hasher.update(content.as_bytes());
104        Hash(hasher.finalize().into())
105    }
106
107    /// Check if this packet has expired
108    pub fn is_expired(&self) -> bool {
109        self.expires_at.is_some_and(|exp| Utc::now() > exp)
110    }
111
112    /// Get the age of this packet
113    pub fn age(&self) -> Duration {
114        Utc::now().signed_duration_since(self.created_at)
115    }
116
117    /// Create a compressed version of this packet
118    pub fn compress(&self, level: CompressionLevel) -> Self {
119        // In a real implementation, this would use an LLM to summarize
120        // For now, we just truncate based on compression ratio
121        let max_len = ((1.0 - level.ratio()) * self.content.len() as f64) as usize;
122        let compressed_content = if max_len < self.content.len() {
123            format!("{}...", &self.content[..max_len.max(10)])
124        } else {
125            self.content.clone()
126        };
127
128        let mut packet = Self::new(&compressed_content);
129        packet.compression = level;
130        packet.parent_hash = Some(self.hash.clone());
131        packet.source_agent = self.source_agent;
132        packet.importance = self.importance;
133        packet
134    }
135
136    /// Chain this packet to a parent
137    pub fn chain_to(&mut self, parent: &ContextPacket) {
138        self.parent_hash = Some(parent.hash.clone());
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn test_create_packet() {
148        let packet = ContextPacket::new("Hello, world!");
149        assert_eq!(packet.content, "Hello, world!");
150        assert_eq!(packet.compression, CompressionLevel::Full);
151        assert!(!packet.is_expired());
152    }
153
154    #[test]
155    fn test_packet_with_ttl() {
156        let packet = ContextPacket::with_ttl("Temporary data", Duration::hours(1));
157        assert!(packet.expires_at.is_some());
158        assert!(!packet.is_expired());
159    }
160
161    #[test]
162    fn test_compress_packet() {
163        let packet = ContextPacket::new(
164            "This is a long piece of content that should be compressed when needed.",
165        );
166        let compressed = packet.compress(CompressionLevel::Summary);
167        assert_eq!(compressed.compression, CompressionLevel::Summary);
168        assert!(compressed.content.len() <= packet.content.len());
169    }
170}