codive-core 0.1.0

Core types, traits, and utilities for Codive
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
//! Session management for the Agent system
//!
//! This module defines types for managing conversation sessions.
//! A session represents an ongoing conversation between a user and the agent.
//!
//! # Architecture
//!
//! ```text
//! Session
//!    ├── id (unique identifier)
//!    ├── title (display name)
//!    ├── messages[] (conversation history)
//!    ├── status (active/completed/error)
//!    └── timestamps (created/updated)
//! ```
//!
//! # Example
//!
//! ```rust
//! use codive_core::session::Session;
//! use codive_core::Message;
//!
//! let mut session = Session::new();
//! session.add_message(Message::user("Hello!"));
//! session.add_message(Message::assistant_text("Hi there!"));
//!
//! assert_eq!(session.message_count(), 2);
//! ```

use crate::message::Message;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU64, Ordering};

// ============================================================================
// SessionId
// ============================================================================

/// A unique identifier for a session
pub type SessionId = String;

/// Generate a unique session ID
fn generate_session_id() -> SessionId {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let timestamp = Utc::now().timestamp_millis() as u64;
    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("sess_{}_{}", timestamp, counter)
}

// ============================================================================
// SessionStatus
// ============================================================================

/// The current status of a session
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionStatus {
    /// Session is active and can accept messages
    Active,
    /// Session is currently processing a request
    Processing,
    /// Session completed normally
    Completed,
    /// Session ended due to an error
    Error,
}

impl Default for SessionStatus {
    fn default() -> Self {
        Self::Active
    }
}

impl SessionStatus {
    /// Check if the session can accept new messages
    pub fn can_accept_messages(&self) -> bool {
        matches!(self, Self::Active)
    }

    /// Check if the session is in a terminal state
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Completed | Self::Error)
    }
}

// ============================================================================
// Session
// ============================================================================

/// A conversation session between user and agent
///
/// Sessions track the full conversation history and metadata.
/// They are the primary unit of state in the agent system.
///
/// # Ownership
///
/// The session owns its messages (`Vec<Message>`). When you add a message,
/// ownership transfers to the session. This is Rust's ownership model in action.
///
/// # Mutability
///
/// Methods that modify the session take `&mut self`:
/// - `add_message()` - adds to the messages vec
/// - `set_title()` - changes the title
///
/// Methods that only read take `&self`:
/// - `last_message()` - returns a reference
/// - `message_count()` - returns a count
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    /// Unique identifier for this session
    pub id: SessionId,

    /// Human-readable title (can be auto-generated)
    pub title: String,

    /// Current status of the session
    pub status: SessionStatus,

    /// The conversation messages
    pub messages: Vec<Message>,

    /// When the session was created
    pub created_at: DateTime<Utc>,

    /// When the session was last modified
    pub updated_at: DateTime<Utc>,

    /// Optional metadata (for extensions)
    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub metadata: serde_json::Map<String, serde_json::Value>,
}

impl Session {
    /// Create a new empty session
    pub fn new() -> Self {
        let now = Utc::now();
        Self {
            id: generate_session_id(),
            title: "New Session".to_string(),
            status: SessionStatus::Active,
            messages: Vec::new(),
            created_at: now,
            updated_at: now,
            metadata: serde_json::Map::new(),
        }
    }

    /// Create a session with a specific ID (for restoration)
    pub fn with_id(id: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            id: id.into(),
            title: "New Session".to_string(),
            status: SessionStatus::Active,
            messages: Vec::new(),
            created_at: now,
            updated_at: now,
            metadata: serde_json::Map::new(),
        }
    }

    /// Set the session title
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Add a message to the session
    ///
    /// This transfers ownership of the message to the session.
    /// The session's `updated_at` timestamp is also updated.
    pub fn add_message(&mut self, message: Message) {
        self.messages.push(message);
        self.updated_at = Utc::now();
    }

    /// Add multiple messages at once
    pub fn add_messages(&mut self, messages: impl IntoIterator<Item = Message>) {
        self.messages.extend(messages);
        self.updated_at = Utc::now();
    }

    /// Get the last message, if any
    pub fn last_message(&self) -> Option<&Message> {
        self.messages.last()
    }

    /// Get the last N messages
    pub fn last_n_messages(&self, n: usize) -> &[Message] {
        let len = self.messages.len();
        if n >= len {
            &self.messages
        } else {
            &self.messages[len - n..]
        }
    }

    /// Get all messages from a specific role
    pub fn messages_by_role(&self, role: crate::message::Role) -> Vec<&Message> {
        self.messages.iter().filter(|m| m.role == role).collect()
    }

    /// Get the number of messages
    pub fn message_count(&self) -> usize {
        self.messages.len()
    }

    /// Check if the session is empty (no messages)
    pub fn is_empty(&self) -> bool {
        self.messages.is_empty()
    }

    /// Set the session title
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = title.into();
        self.updated_at = Utc::now();
    }

    /// Set the session status
    pub fn set_status(&mut self, status: SessionStatus) {
        self.status = status;
        self.updated_at = Utc::now();
    }

    /// Mark session as processing
    pub fn start_processing(&mut self) {
        self.set_status(SessionStatus::Processing);
    }

    /// Mark session as active (done processing)
    pub fn finish_processing(&mut self) {
        self.set_status(SessionStatus::Active);
    }

    /// Mark session as completed
    pub fn complete(&mut self) {
        self.set_status(SessionStatus::Completed);
    }

    /// Mark session as errored
    pub fn mark_error(&mut self) {
        self.set_status(SessionStatus::Error);
    }

    /// Check if the session can accept new messages
    pub fn can_accept_messages(&self) -> bool {
        self.status.can_accept_messages()
    }

    /// Add metadata to the session
    pub fn set_metadata(&mut self, key: impl Into<String>, value: serde_json::Value) {
        self.metadata.insert(key.into(), value);
        self.updated_at = Utc::now();
    }

    /// Get metadata value
    pub fn get_metadata(&self, key: &str) -> Option<&serde_json::Value> {
        self.metadata.get(key)
    }

    /// Generate a title from the first user message
    ///
    /// Useful for auto-generating session titles from conversation content.
    pub fn auto_title(&mut self) {
        if let Some(first_user_msg) = self.messages.iter().find(|m| m.is_user()) {
            let text = first_user_msg.text_content();
            // Take first 50 chars, trim to word boundary
            let title: String = text.chars().take(50).collect();
            let title = title
                .rsplit_once(' ')
                .map(|(s, _)| s)
                .unwrap_or(&title)
                .trim();
            if !title.is_empty() {
                self.title = if title.len() < text.len() {
                    format!("{}...", title)
                } else {
                    title.to_string()
                };
                self.updated_at = Utc::now();
            }
        }
    }

    /// Get conversation duration
    pub fn duration(&self) -> chrono::Duration {
        self.updated_at - self.created_at
    }
}

impl Default for Session {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// SessionSummary
// ============================================================================

/// A lightweight summary of a session (for listings)
///
/// Used when you need to display a list of sessions without
/// loading all messages.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionSummary {
    /// Session ID
    pub id: SessionId,
    /// Session title
    pub title: String,
    /// Current status
    pub status: SessionStatus,
    /// Number of messages
    pub message_count: usize,
    /// When created
    pub created_at: DateTime<Utc>,
    /// When last updated
    pub updated_at: DateTime<Utc>,
}

impl From<&Session> for SessionSummary {
    fn from(session: &Session) -> Self {
        Self {
            id: session.id.clone(),
            title: session.title.clone(),
            status: session.status,
            message_count: session.message_count(),
            created_at: session.created_at,
            updated_at: session.updated_at,
        }
    }
}

// ============================================================================
// RUST CONCEPTS EXPLAINED (for learning)
// ============================================================================
//
// 1. `Vec<T>` - Growable array
//    - Like ArrayList in Java or std::vector in C++
//    - Owns its elements (when Vec is dropped, elements are dropped)
//    - `push()` adds to end, `last()` gets last element
//
// 2. `&self` vs `&mut self`
//    - `&self` - immutable borrow, can only read
//    - `&mut self` - mutable borrow, can modify
//    - Rust enforces: many readers OR one writer (not both)
//
// 3. `Option<&Message>` return
//    - `last_message()` returns reference to message owned by session
//    - `Option` because the vec might be empty
//    - Caller cannot outlive the session (borrow checker ensures this)
//
// 4. `chrono::DateTime<Utc>`
//    - `DateTime` is generic over timezone
//    - `Utc` is the UTC timezone type
//    - `Utc::now()` gets current time
//    - Built-in serde support with `features = ["serde"]`
//
// 5. Ownership transfer in `add_message`
//    - Takes `message: Message` (not `&Message`)
//    - Ownership moves from caller to session
//    - Caller can't use the message after passing it
//
// 6. `impl Default`
//    - Allows `Session::default()` as alternative to `Session::new()`
//    - Required for some generic code
//    - Convention: `new()` and `default()` should be equivalent
//
// 7. `&[Message]` return type
//    - Slice - a view into a contiguous sequence
//    - Doesn't own the data, just references it
//    - More flexible than `&Vec<Message>`
//
// **📚 Read:**
// - [Rust Book Ch 4 - Ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html)
// - [Rust Book Ch 8.1 - Vectors](https://doc.rust-lang.org/book/ch08-01-vectors.html)

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::Role;

    #[test]
    fn test_session_new() {
        let session = Session::new();
        assert!(session.id.starts_with("sess_"));
        assert_eq!(session.title, "New Session");
        assert_eq!(session.status, SessionStatus::Active);
        assert!(session.messages.is_empty());
    }

    #[test]
    fn test_session_with_id() {
        let session = Session::with_id("custom_id");
        assert_eq!(session.id, "custom_id");
    }

    #[test]
    fn test_session_with_title() {
        let session = Session::new().with_title("My Chat");
        assert_eq!(session.title, "My Chat");
    }

    #[test]
    fn test_add_message() {
        let mut session = Session::new();
        let initial_updated = session.updated_at;

        // Small delay to ensure timestamp changes
        std::thread::sleep(std::time::Duration::from_millis(1));

        session.add_message(Message::user("Hello"));
        assert_eq!(session.message_count(), 1);
        assert!(session.updated_at > initial_updated);
    }

    #[test]
    fn test_add_messages() {
        let mut session = Session::new();
        session.add_messages(vec![
            Message::user("Hello"),
            Message::assistant_text("Hi!"),
            Message::user("How are you?"),
        ]);
        assert_eq!(session.message_count(), 3);
    }

    #[test]
    fn test_last_message() {
        let mut session = Session::new();
        assert!(session.last_message().is_none());

        session.add_message(Message::user("First"));
        session.add_message(Message::user("Second"));

        let last = session.last_message().unwrap();
        assert_eq!(last.text_content(), "Second");
    }

    #[test]
    fn test_last_n_messages() {
        let mut session = Session::new();
        session.add_messages(vec![
            Message::user("1"),
            Message::user("2"),
            Message::user("3"),
            Message::user("4"),
        ]);

        let last_2 = session.last_n_messages(2);
        assert_eq!(last_2.len(), 2);
        assert_eq!(last_2[0].text_content(), "3");
        assert_eq!(last_2[1].text_content(), "4");

        // Request more than available
        let all = session.last_n_messages(10);
        assert_eq!(all.len(), 4);
    }

    #[test]
    fn test_messages_by_role() {
        let mut session = Session::new();
        session.add_messages(vec![
            Message::user("User 1"),
            Message::assistant_text("Assistant 1"),
            Message::user("User 2"),
            Message::assistant_text("Assistant 2"),
        ]);

        let user_msgs = session.messages_by_role(Role::User);
        assert_eq!(user_msgs.len(), 2);

        let assistant_msgs = session.messages_by_role(Role::Assistant);
        assert_eq!(assistant_msgs.len(), 2);
    }

    #[test]
    fn test_session_status() {
        let mut session = Session::new();
        assert!(session.can_accept_messages());

        session.start_processing();
        assert_eq!(session.status, SessionStatus::Processing);
        assert!(!session.can_accept_messages());

        session.finish_processing();
        assert_eq!(session.status, SessionStatus::Active);
        assert!(session.can_accept_messages());

        session.complete();
        assert_eq!(session.status, SessionStatus::Completed);
        assert!(session.status.is_terminal());
    }

    #[test]
    fn test_auto_title() {
        let mut session = Session::new();
        session.add_message(Message::user("How do I write a Rust function?"));
        session.auto_title();
        assert!(session.title.contains("Rust"));
    }

    #[test]
    fn test_auto_title_long() {
        let mut session = Session::new();
        session.add_message(Message::user(
            "This is a very long message that should be truncated when used as a title",
        ));
        session.auto_title();
        assert!(session.title.len() <= 55); // 50 chars + "..."
        assert!(session.title.ends_with("..."));
    }

    #[test]
    fn test_metadata() {
        let mut session = Session::new();
        session.set_metadata("key", serde_json::json!("value"));
        assert_eq!(
            session.get_metadata("key"),
            Some(&serde_json::json!("value"))
        );
        assert!(session.get_metadata("nonexistent").is_none());
    }

    #[test]
    fn test_session_serialization() {
        let mut session = Session::new().with_title("Test Session");
        session.add_message(Message::user("Hello"));

        let json = serde_json::to_string(&session).unwrap();
        let restored: Session = serde_json::from_str(&json).unwrap();

        assert_eq!(session.id, restored.id);
        assert_eq!(session.title, restored.title);
        assert_eq!(session.message_count(), restored.message_count());
    }

    #[test]
    fn test_session_summary() {
        let mut session = Session::new().with_title("My Session");
        session.add_messages(vec![Message::user("1"), Message::user("2")]);

        let summary = SessionSummary::from(&session);
        assert_eq!(summary.id, session.id);
        assert_eq!(summary.title, "My Session");
        assert_eq!(summary.message_count, 2);
    }

    #[test]
    fn test_session_id_uniqueness() {
        let s1 = Session::new();
        let s2 = Session::new();
        assert_ne!(s1.id, s2.id);
    }

    #[test]
    fn test_session_status_serialization() {
        assert_eq!(
            serde_json::to_string(&SessionStatus::Active).unwrap(),
            "\"active\""
        );
        assert_eq!(
            serde_json::to_string(&SessionStatus::Processing).unwrap(),
            "\"processing\""
        );
    }
}