ragrig 0.9.8

RAG framework for research and prototyping. Zero dependencies, hot-swap any agent at runtime, hybrid BM25+vector retrieval. Default build compiles with cargo build --release and nothing else.
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
//! Session persistence and cross-session history diffusion.
//!
//! Two trait-based extension points:
//!
//! | Trait | Role |
//! |---|---|
//! | [`SessionStore`] | Persist / load full chat sessions to disk |
//! | [`HistoryStrategy`] | Blend past session content into the current chat prompt |
//!
//! Both operate on the same [`Turn`] atom — no duplicate data model.

use std::path::PathBuf;
use std::time::{Duration, SystemTime};

use anyhow::Result;
use async_trait::async_trait;

use crate::agents::Generator;

// ── Shared atom ────────────────────────────────────────────────────────────

/// A single conversation turn.  Used by both the in‑session memory layer
/// (last N turns for context windows) and the persistence layer (all turns
/// saved to disk).
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct Turn {
    /// Who spoke this turn.
    pub role: TurnRole,
    /// The full text content of the turn.
    pub text: String,
    /// Per‑turn diagnostics captured during generation.
    #[serde(default)]
    pub perf: Option<TurnPerf>,
}

/// The speaker of a conversation turn.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
pub enum TurnRole {
    /// The human user.
    #[default]
    User,
    /// The AI assistant.
    Assistant,
}

impl TurnRole {
    /// Return `"User"` or `"Assistant"` as a static string.
    pub fn as_str(&self) -> &'static str {
        match self {
            TurnRole::User => "User",
            TurnRole::Assistant => "Assistant",
        }
    }
}

/// Convenience conversion from turns to role/text pairs.
pub struct TurnPairs<'a>(pub Vec<(&'a str, &'a str)>);

impl<'a> From<&'a [Turn]> for TurnPairs<'a> {
    fn from(turns: &'a [Turn]) -> Self {
        TurnPairs(
            turns
                .iter()
                .map(|t| (t.role.as_str(), t.text.as_str()))
                .collect(),
        )
    }
}

/// Performance data for a single assistant turn.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TurnPerf {
    /// Prompt token count (input).
    pub prompt_tokens: usize,
    /// Completion token count (output).
    pub completion_tokens: usize,
    /// Wall‑clock latency for the generation call.
    pub latency: Duration,
}

impl Default for TurnPerf {
    fn default() -> Self {
        Self {
            prompt_tokens: 0,
            completion_tokens: 0,
            latency: Duration::ZERO,
        }
    }
}

// ── Memory strategy kind ────────────────────────────────────────────────────

/// Memory strategy used during a session.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MemoryStrategyKind {
    /// Query rewriting via a second LLM call before vector search.
    Rewrite,
    /// Raw transcript replay (deprecated alias for no rewriting).
    Transcript,
    /// No query rewriting — raw user query is used directly.
    Off,
}

// ── Session data ───────────────────────────────────────────────────────────

/// Unique identifier for a session.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct SessionId(pub String);

/// Snapshot of every hot‑swappable setting at the moment a turn was recorded.
///
/// Stored once per session so the loaded session knows exactly which models,
/// strategies, and thresholds were active.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SessionConfig {
    /// Chat provider backend name (e.g. `"ollama"`, `"deepseek"`).
    pub chat_backend: String,
    /// Chat model identifier.
    pub chat_model: String,
    /// Embedding provider backend name.
    pub embed_backend: String,
    /// Embedding model identifier.
    pub embed_model: String,
    /// Memory rewriting strategy.
    pub memory_strategy: MemoryStrategyKind,
    /// Memory-provider backend name.
    pub memory_backend: String,
    /// Memory-provider model identifier.
    pub memory_model: String,
    /// Number of chunks retrieved per search.
    pub top_k: usize,
    /// Minimum cosine similarity threshold.
    pub similarity_threshold: f64,
    /// Context window size of the chat model in tokens.
    pub model_ctx_tokens: usize,
}

/// The full serialisable payload for one session.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SessionData {
    /// Unique session identifier.
    pub id: SessionId,
    /// When the session was first created.
    pub created: SystemTime,
    /// When the session was last modified.
    pub updated: SystemTime,
    /// Snapshot of the active configuration.
    pub config: SessionConfig,
    /// All conversation turns in order.
    pub turns: Vec<Turn>,
}

/// Lightweight metadata for listing sessions (no turn payload).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SessionManifest {
    /// Unique session identifier.
    pub id: SessionId,
    /// When the session was first created.
    pub created: SystemTime,
    /// When the session was last modified.
    pub updated: SystemTime,
    /// Number of turns in this session.
    pub turn_count: usize,
    /// Optional one‑line summary produced by a summarisation strategy.
    pub summary: Option<String>,
    /// Path to the on‑disk file (for filesystem‑backed stores).
    pub path: PathBuf,
}

// ── Persistence trait ──────────────────────────────────────────────────────

/// Pluggable persistence for chat sessions.
///
/// Built‑in backends: filesystem (one JSON file per session), SQLite.
/// Implement this trait to add cloud storage, encrypted archives, etc.
#[async_trait]
pub trait SessionStore: Send + Sync {
    /// Persist a session (create or overwrite).
    async fn save(&self, session: &SessionData) -> Result<()>;

    /// Load a full session by id.  Returns `None` if not found.
    async fn load(&self, id: &SessionId) -> Result<Option<SessionData>>;

    /// List all saved sessions (lightweight manifests only).
    async fn list(&self) -> Result<Vec<SessionManifest>>;

    /// Delete a session from the store.
    async fn delete(&self, id: &SessionId) -> Result<()>;

    /// Human‑readable label, e.g. "filesystem", "sqlite".
    fn name(&self) -> &'static str;
}

// ── History diffusion trait ────────────────────────────────────────────────

/// Controls how past session content influences the current chat prompt.
///
/// Called before the final prompt is assembled.  The strategy receives the
/// list of previous sessions and returns a string that gets prepended to the
/// system prompt (or appended as a `<|user|>` preamble).
///
/// # Built‑in strategies
///
/// | Strategy | Behaviour |
/// |---|---|
/// | `LogHistory` | Concatenate the raw transcript of the most recent session |
/// | `SummaryHistory` | Run an LLM summarisation over past sessions, cache the result |
/// | `None` | No diffusion — only the current session's memory is used |
///
/// Methods use `#[async_trait]` which expands to `Pin<Box<dyn Future>>` in
/// the rendered docs — just call them with `.await` as normal.
///
/// # Example
///
/// ```rust,no_run
/// use ragrig::longterm_memory::{HistoryStrategy, LogHistory};
/// use ragrig::FsSessionStore;
/// use std::path::Path;
///
/// # async fn example() -> anyhow::Result<()> {
/// let store = FsSessionStore::new(Path::new("./sessions").to_path_buf())?;
/// let strategy = LogHistory;
/// let context = strategy.build_context(&store, "current query").await?;
/// if !context.is_empty() {
///     println!("Injected previous-session context.");
/// }
/// # Ok(())
/// # }
/// ```
#[async_trait]
pub trait HistoryStrategy: Send + Sync {
    /// Build a context string from past sessions.
    ///
    /// The returned string is injected into the chat prompt by the session
    /// loop.  Return an empty string to skip diffusion.
    async fn build_context(&self, store: &dyn SessionStore, current_query: &str) -> Result<String>;

    /// Human‑readable label, e.g. "log", "summary".
    fn name(&self) -> &'static str;
}

// ── Built-in: raw transcript ───────────────────────────────────────────────

/// Concatenates the most recent session's turns into a plain transcript block.
///
/// Example output:
///
/// ```text
/// [Previous session — 2026-06-14]
/// User: What is a vector database?
/// Assistant: A vector database stores embeddings…
/// User: Can you explain RAG?
/// Assistant: Retrieval-Augmented Generation combines…
/// ```
pub struct LogHistory;

#[async_trait]
impl HistoryStrategy for LogHistory {
    async fn build_context(
        &self,
        store: &dyn SessionStore,
        _current_query: &str,
    ) -> Result<String> {
        let manifests = store.list().await?;
        let Some(latest) = manifests.last() else {
            return Ok(String::new());
        };
        let Some(session) = store.load(&latest.id).await? else {
            return Ok(String::new());
        };
        let mut out = format!("[Previous session — {:?}]\n", session.created);
        for turn in &session.turns {
            out.push_str(match turn.role {
                TurnRole::User => "User: ",
                TurnRole::Assistant => "Assistant: ",
            });
            out.push_str(&turn.text);
            out.push('\n');
        }
        Ok(out)
    }

    fn name(&self) -> &'static str {
        "log"
    }
}

// ── Built-in: LLM summarisation ────────────────────────────────────────────

/// Summarises past sessions via an LLM agent ([`Generator`]).
///
/// The summary is cached in the session manifest so it's only generated once.
#[derive(Clone, Debug)]
pub struct SummaryHistory {
    agent: Box<dyn Generator>,
}

impl SummaryHistory {
    /// Create a summary-history strategy backed by the given generator.
    pub fn new(agent: Box<dyn Generator>) -> Self {
        Self { agent }
    }
}

#[async_trait]
impl HistoryStrategy for SummaryHistory {
    async fn build_context(&self, store: &dyn SessionStore, current_query: &str) -> Result<String> {
        let manifests = store.list().await?;
        if manifests.is_empty() {
            return Ok(String::new());
        }
        // Build a prompt that summarises all past sessions.
        let mut prompt =
            String::from("Summarise the following past research sessions in one paragraph.  ");
        prompt.push_str("Focus on topics discussed and conclusions reached.\n\n");
        for m in &manifests {
            let Some(session) = store.load(&m.id).await? else {
                continue;
            };
            prompt.push_str(&format!("## Session {}\n", m.id.0));
            for turn in &session.turns {
                prompt.push_str(match turn.role {
                    TurnRole::User => "User: ",
                    TurnRole::Assistant => "Assistant: ",
                });
                prompt.push_str(&turn.text);
                prompt.push('\n');
            }
            prompt.push('\n');
        }
        prompt.push_str(&format!("Current query: {}\n\nSummary:", current_query));
        let summary = self.agent.generate(&prompt).await?;
        Ok(format!(
            "[Summary of {} previous session(s)]\n{}\n",
            manifests.len(),
            summary.trim()
        ))
    }

    fn name(&self) -> &'static str {
        "summary"
    }
}

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

    #[test]
    fn turn_role_as_str() {
        assert_eq!(TurnRole::User.as_str(), "User");
        assert_eq!(TurnRole::Assistant.as_str(), "Assistant");
    }

    #[test]
    fn turn_serialization_roundtrip() {
        let turn = Turn {
            role: TurnRole::User,
            text: "What is RAG?".into(),
            perf: None,
        };
        let json = serde_json::to_string(&turn).unwrap();
        let back: Turn = serde_json::from_str(&json).unwrap();
        assert_eq!(back.role, TurnRole::User);
        assert_eq!(back.text, "What is RAG?");
        assert!(back.perf.is_none());
    }

    #[test]
    fn turn_with_perf_roundtrip() {
        let turn = Turn {
            role: TurnRole::Assistant,
            text: "RAG stands for...".into(),
            perf: Some(TurnPerf {
                prompt_tokens: 150,
                completion_tokens: 80,
                latency: std::time::Duration::from_millis(1200),
            }),
        };
        let json = serde_json::to_string(&turn).unwrap();
        let back: Turn = serde_json::from_str(&json).unwrap();
        assert_eq!(back.perf.unwrap().prompt_tokens, 150);
    }

    #[test]
    fn session_id_equality() {
        let a = SessionId("abc".into());
        let b = SessionId("abc".into());
        let c = SessionId("def".into());
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn session_config_serialization() {
        let cfg = SessionConfig {
            chat_backend: "ollama".into(),
            chat_model: "gemma2".into(),
            embed_backend: "ollama".into(),
            embed_model: "nomic".into(),
            memory_strategy: MemoryStrategyKind::Rewrite,
            memory_backend: String::new(),
            memory_model: String::new(),
            top_k: 5,
            similarity_threshold: 0.0,
            model_ctx_tokens: 4096,
        };
        let json = serde_json::to_string(&cfg).unwrap();
        let back: SessionConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(back.chat_model, "gemma2");
        assert_eq!(back.top_k, 5);
    }

    // ── TurnPairs ────────────────────────────────────────────────────

    #[test]
    fn turn_pairs_from_empty_slice() {
        let turns: Vec<Turn> = vec![];
        let pairs = TurnPairs::from(&turns[..]);
        assert!(pairs.0.is_empty());
    }

    #[test]
    fn turn_pairs_from_single_user_turn() {
        let turns = [Turn {
            role: TurnRole::User,
            text: "What is RAG?".into(),
            perf: None,
        }];
        let pairs = TurnPairs::from(&turns[..]);
        assert_eq!(pairs.0.len(), 1);
        assert_eq!(pairs.0[0], ("User", "What is RAG?"));
    }

    #[test]
    fn turn_pairs_from_single_assistant_turn() {
        let turns = [Turn {
            role: TurnRole::Assistant,
            text: "RAG stands for...".into(),
            perf: None,
        }];
        let pairs = TurnPairs::from(&turns[..]);
        assert_eq!(pairs.0.len(), 1);
        assert_eq!(pairs.0[0], ("Assistant", "RAG stands for..."));
    }

    #[test]
    fn turn_pairs_from_mixed_turns_preserves_order() {
        let turns = [
            Turn {
                role: TurnRole::User,
                text: "Hello".into(),
                perf: None,
            },
            Turn {
                role: TurnRole::Assistant,
                text: "Hi there!".into(),
                perf: None,
            },
            Turn {
                role: TurnRole::User,
                text: "Explain RAG".into(),
                perf: None,
            },
            Turn {
                role: TurnRole::Assistant,
                text: "Retrieval-Augmented...".into(),
                perf: Some(TurnPerf {
                    prompt_tokens: 100,
                    completion_tokens: 50,
                    latency: std::time::Duration::from_millis(500),
                }),
            },
        ];
        let pairs = TurnPairs::from(&turns[..]);
        assert_eq!(pairs.0.len(), 4);
        assert_eq!(pairs.0[0], ("User", "Hello"));
        assert_eq!(pairs.0[1], ("Assistant", "Hi there!"));
        assert_eq!(pairs.0[2], ("User", "Explain RAG"));
        assert_eq!(pairs.0[3], ("Assistant", "Retrieval-Augmented..."));
    }
}