echo_state 0.1.4

State management for echo-agent framework (memory, compression, audit)
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
//! SQLite conversation persistence implementation
//!
//! Production-grade conversation storage backed by SQLite, with cascading deletes and efficient queries.

use crate::util::{expand_tilde, memory_io_error};
use echo_core::error::Result;
pub use echo_core::memory::conversation::{
    Conversation, ConversationFilter, ConversationMeta, ConversationStore, NewConversation,
    StoredMessage,
};
use futures::future::BoxFuture;
use rusqlite::{Connection, params};
use std::path::{Path, PathBuf};
use tokio::sync::Mutex;
use tracing::info;

// ── SqliteConversationStore ─────────────────────────────────────────────────

/// SQLite conversation persistence Store
pub struct SqliteConversationStore {
    conn: Mutex<Connection>,
    #[allow(dead_code)]
    path: PathBuf,
}

impl SqliteConversationStore {
    /// Open or create the SQLite database, auto-creating tables
    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
        let path = expand_tilde(path.as_ref());
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| memory_io_error("failed to create directory", e))?;
        }

        let conn = Connection::open(&path)
            .map_err(|e| memory_io_error("failed to open SQLite database", e))?;

        conn.execute_batch(
            "PRAGMA journal_mode=WAL;
             PRAGMA synchronous=NORMAL;
             PRAGMA cache_size=5000;
             PRAGMA temp_store=MEMORY;
             PRAGMA foreign_keys=ON;",
        )
        .map_err(|e| memory_io_error("SQLite PRAGMA configuration failed", e))?;

        Self::init_tables(&conn)?;

        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM conversation", [], |row| row.get(0))
            .unwrap_or(0);

        info!(
            path = %path.display(),
            conversations = count,
            "SqliteConversationStore initialized"
        );

        Ok(Self {
            conn: Mutex::new(conn),
            path,
        })
    }

    fn init_tables(conn: &Connection) -> Result<()> {
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS conversation (
                id                  INTEGER PRIMARY KEY AUTOINCREMENT,
                conversation_id     TEXT NOT NULL UNIQUE,
                user_id             TEXT NOT NULL DEFAULT 'default',
                agent_type          TEXT,
                title               TEXT,
                summary             TEXT,
                compressed_before_id INTEGER,
                created_at          TEXT NOT NULL DEFAULT (datetime('now')),
                updated_at          TEXT NOT NULL DEFAULT (datetime('now'))
            );
            CREATE INDEX IF NOT EXISTS idx_conv_user ON conversation(user_id);
            CREATE INDEX IF NOT EXISTS idx_conv_updated ON conversation(updated_at DESC);

            CREATE TABLE IF NOT EXISTS message (
                id                  INTEGER PRIMARY KEY AUTOINCREMENT,
                conversation_id     TEXT NOT NULL REFERENCES conversation(conversation_id) ON DELETE CASCADE,
                role                TEXT NOT NULL,
                content             TEXT,
                attachments_json    TEXT,
                tool_calls_json     TEXT,
                tool_result_json    TEXT,
                created_at          TEXT NOT NULL DEFAULT (datetime('now'))
            );
            CREATE INDEX IF NOT EXISTS idx_msg_conv ON message(conversation_id);",
        )
        .map_err(|e| memory_io_error("failed to create tables", e))?;
        Ok(())
    }
}

// ── Trait implementation ───────────────────────────────────────────────────

impl ConversationStore for SqliteConversationStore {
    fn create_conversation<'a>(
        &'a self,
        conv: NewConversation,
    ) -> BoxFuture<'a, Result<Conversation>> {
        Box::pin(async move {
            let conn = self.conn.lock().await;
            conn.execute(
                "INSERT INTO conversation (conversation_id, user_id, agent_type, title)
                 VALUES (?1, ?2, ?3, ?4)",
                params![
                    conv.conversation_id,
                    conv.user_id,
                    conv.agent_type,
                    conv.title
                ],
            )
            .map_err(|e| memory_io_error("failed to insert conversation", e))?;

            let id = conn.last_insert_rowid();
            let row = conn
                .query_row(
                    "SELECT id, conversation_id, user_id, agent_type, title, summary,
                        compressed_before_id, created_at, updated_at
                 FROM conversation WHERE id = ?1",
                    params![id],
                    |row| {
                        Ok(Conversation {
                            id: row.get(0)?,
                            conversation_id: row.get(1)?,
                            user_id: row.get(2)?,
                            agent_type: row.get(3)?,
                            title: row.get(4)?,
                            summary: row.get(5)?,
                            compressed_before_id: row.get(6)?,
                            created_at: row.get(7)?,
                            updated_at: row.get(8)?,
                        })
                    },
                )
                .map_err(|e| memory_io_error("failed to query new conversation", e))?;

            Ok(row)
        })
    }

    fn get_conversation<'a>(
        &'a self,
        conversation_id: &'a str,
    ) -> BoxFuture<'a, Result<Option<Conversation>>> {
        Box::pin(async move {
            let conn = self.conn.lock().await;
            let result = conn.query_row(
                "SELECT id, conversation_id, user_id, agent_type, title, summary,
                        compressed_before_id, created_at, updated_at
                 FROM conversation WHERE conversation_id = ?1",
                params![conversation_id],
                |row| {
                    Ok(Conversation {
                        id: row.get(0)?,
                        conversation_id: row.get(1)?,
                        user_id: row.get(2)?,
                        agent_type: row.get(3)?,
                        title: row.get(4)?,
                        summary: row.get(5)?,
                        compressed_before_id: row.get(6)?,
                        created_at: row.get(7)?,
                        updated_at: row.get(8)?,
                    })
                },
            );

            match result {
                Ok(conv) => Ok(Some(conv)),
                Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
                Err(e) => Err(memory_io_error("failed to query conversation", e).into()),
            }
        })
    }

    fn list_conversations<'a>(
        &'a self,
        filter: ConversationFilter,
    ) -> BoxFuture<'a, Result<Vec<ConversationMeta>>> {
        Box::pin(async move {
            let conn = self.conn.lock().await;

            let mut sql = String::from(
                "SELECT c.id, c.conversation_id, c.user_id, c.title, c.created_at, c.updated_at,
                        (SELECT COUNT(*) FROM message m WHERE m.conversation_id = c.conversation_id) AS msg_count
                 FROM conversation c WHERE 1=1",
            );
            let mut param_values: Vec<Box<dyn rusqlite::types::ToSql>> = Vec::new();
            let mut param_idx = 1;

            if let Some(user_id) = filter.user_id {
                sql.push_str(&format!(" AND c.user_id = ?{param_idx}"));
                param_values.push(Box::new(user_id));
                param_idx += 1;
            }
            if let Some(agent_type) = filter.agent_type {
                sql.push_str(&format!(" AND c.agent_type = ?{param_idx}"));
                param_values.push(Box::new(agent_type));
                param_idx += 1;
            }

            sql.push_str(" ORDER BY c.updated_at DESC");

            if let Some(limit) = filter.limit {
                sql.push_str(&format!(" LIMIT ?{param_idx}"));
                param_values.push(Box::new(limit as i64));
                param_idx += 1;
            }
            if let Some(offset) = filter.offset {
                sql.push_str(&format!(" OFFSET ?{param_idx}"));
                param_values.push(Box::new(offset as i64));
            }

            let params_refs: Vec<&dyn rusqlite::types::ToSql> =
                param_values.iter().map(|p| p.as_ref()).collect();

            let mut stmt = conn
                .prepare(&sql)
                .map_err(|e| memory_io_error("failed to prepare query", e))?;

            let rows = stmt
                .query_map(params_refs.as_slice(), |row| {
                    Ok(ConversationMeta {
                        id: row.get(0)?,
                        conversation_id: row.get(1)?,
                        user_id: row.get(2)?,
                        title: row.get(3)?,
                        created_at: row.get(4)?,
                        updated_at: row.get(5)?,
                        message_count: row.get::<_, i64>(6).unwrap_or(0) as usize,
                    })
                })
                .map_err(|e| memory_io_error("failed to query conversation list", e))?;

            let mut result = Vec::new();
            for row in rows {
                let meta = row.map_err(|e| memory_io_error("failed to read row", e))?;
                result.push(meta);
            }
            Ok(result)
        })
    }

    fn update_conversation<'a>(
        &'a self,
        conversation_id: &'a str,
        title: Option<&'a str>,
        summary: Option<&'a str>,
        compressed_before_id: Option<i64>,
    ) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let conn = self.conn.lock().await;

            // Build dynamic UPDATE — only update fields that are Some
            let mut sets = Vec::new();
            let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = Vec::new();

            if let Some(t) = title {
                sets.push(format!("title = ?{}", params.len() + 1));
                params.push(Box::new(t.to_string()));
            }
            if let Some(s) = summary {
                sets.push(format!("summary = ?{}", params.len() + 1));
                params.push(Box::new(s.to_string()));
            }
            if let Some(cbid) = compressed_before_id {
                sets.push(format!("compressed_before_id = ?{}", params.len() + 1));
                params.push(Box::new(cbid));
            }

            if sets.is_empty() {
                return Ok(());
            }

            sets.push("updated_at = datetime('now')".to_string());
            params.push(Box::new(conversation_id.to_string()));

            let sql = format!(
                "UPDATE conversation SET {} WHERE conversation_id = ?{}",
                sets.join(", "),
                params.len()
            );

            let params_refs: Vec<&dyn rusqlite::types::ToSql> =
                params.iter().map(|p| p.as_ref()).collect();

            conn.execute(&sql, params_refs.as_slice())
                .map_err(|e| memory_io_error("failed to update conversation", e))?;

            Ok(())
        })
    }

    fn delete_conversation<'a>(&'a self, conversation_id: &'a str) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let conn = self.conn.lock().await;
            conn.execute(
                "DELETE FROM conversation WHERE conversation_id = ?1",
                params![conversation_id],
            )
            .map_err(|e| memory_io_error("failed to delete conversation", e))?;
            Ok(())
        })
    }

    fn save_messages<'a>(
        &'a self,
        conversation_id: &'a str,
        messages: &'a [StoredMessage],
    ) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let conn = self.conn.lock().await;

            // Delete existing messages (upsert pattern: replace all)
            conn.execute(
                "DELETE FROM message WHERE conversation_id = ?1",
                params![conversation_id],
            )
            .map_err(|e| memory_io_error("failed to clear old messages", e))?;

            // Insert new messages
            for msg in messages {
                conn.execute(
                    "INSERT INTO message (conversation_id, role, content, attachments_json, tool_calls_json, tool_result_json, created_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                    params![
                        conversation_id,
                        msg.role,
                        msg.content,
                        msg.attachments_json,
                        msg.tool_calls_json,
                        msg.tool_result_json,
                        msg.created_at,
                    ],
                )
                .map_err(|e| memory_io_error("failed to insert message", e))?;
            }

            // Update conversation timestamp
            conn.execute(
                "UPDATE conversation SET updated_at = datetime('now') WHERE conversation_id = ?1",
                params![conversation_id],
            )
            .map_err(|e| memory_io_error("failed to update conversation timestamp", e))?;

            Ok(())
        })
    }

    fn get_messages<'a>(
        &'a self,
        conversation_id: &'a str,
    ) -> BoxFuture<'a, Result<Vec<StoredMessage>>> {
        Box::pin(async move {
            let conn = self.conn.lock().await;
            let mut stmt = conn
                .prepare(
                    "SELECT id, conversation_id, role, content, attachments_json,
                            tool_calls_json, tool_result_json, created_at
                     FROM message WHERE conversation_id = ?1 ORDER BY id ASC",
                )
                .map_err(|e| memory_io_error("failed to prepare query", e))?;

            let rows = stmt
                .query_map(params![conversation_id], |row| {
                    Ok(StoredMessage {
                        id: Some(row.get(0)?),
                        conversation_id: row.get(1)?,
                        role: row.get(2)?,
                        content: row.get(3)?,
                        attachments_json: row.get(4)?,
                        tool_calls_json: row.get(5)?,
                        tool_result_json: row.get(6)?,
                        created_at: row.get(7)?,
                    })
                })
                .map_err(|e| memory_io_error("failed to query messages", e))?;

            let mut result = Vec::new();
            for row in rows {
                result.push(row.map_err(|e| memory_io_error("failed to read message", e))?);
            }
            Ok(result)
        })
    }

    fn count_messages<'a>(&'a self, conversation_id: &'a str) -> BoxFuture<'a, Result<usize>> {
        Box::pin(async move {
            let conn = self.conn.lock().await;
            let count: i64 = conn
                .query_row(
                    "SELECT COUNT(*) FROM message WHERE conversation_id = ?1",
                    params![conversation_id],
                    |row| row.get(0),
                )
                .map_err(|e| memory_io_error("failed to count messages", e))?;
            Ok(count as usize)
        })
    }
}