clausura-core 1.0.6

Core library for Clausura — a CI-native agent for deterministic pipeline gating
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
use crate::types::{CheckpointError, Message, SnapshotMeta};
use rusqlite::{params, Connection};
use std::path::PathBuf;

/// SQLite-backed checkpoint store for agent state persistence.
pub struct CheckpointStore {
    conn: Connection,
    db_path: PathBuf,
}

impl CheckpointStore {
    /// Open or create the database at `~/.clausura/checkpoints.db`
    pub fn new() -> Result<Self, CheckpointError> {
        let clausura_dir = dirs::home_dir()
            .ok_or_else(|| CheckpointError::DbError("Could not find home directory".into()))?
            .join(".clausura");
        std::fs::create_dir_all(&clausura_dir)
            .map_err(|e| CheckpointError::DbError(format!("Failed to create dir: {}", e)))?;
        let db_path = clausura_dir.join("checkpoints.db");
        Self::open_at(db_path)
    }

    /// Open or create the database at a specific path
    pub fn open_at(db_path: PathBuf) -> Result<Self, CheckpointError> {
        let conn = Connection::open(&db_path)
            .map_err(|e| CheckpointError::DbError(format!("Failed to open DB: {}", e)))?;

        // Enable WAL mode for concurrent read performance
        conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;")
            .map_err(|e| CheckpointError::DbError(format!("Failed pragma: {}", e)))?;

        // Create the schema if it doesn't exist
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS checkpoints (
                thread_id    TEXT NOT NULL,
                checkpoint_id TEXT NOT NULL PRIMARY KEY,
                created_at   TEXT NOT NULL DEFAULT (datetime('now')),
                version      INTEGER NOT NULL DEFAULT 1,
                truncated    INTEGER NOT NULL DEFAULT 0,
                state        BLOB NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_thread_time
                ON checkpoints(thread_id, created_at DESC);",
        )
        .map_err(|e| CheckpointError::DbError(format!("Failed schema: {}", e)))?;

        Ok(Self { conn, db_path })
    }

    /// Save messages as a new checkpoint for the given thread.
    pub fn save(
        &self,
        thread_id: &str,
        messages: &[Message],
        truncated: bool,
    ) -> Result<uuid::Uuid, CheckpointError> {
        let checkpoint_id = uuid::Uuid::new_v4();
        let state = rmp_serde::to_vec(messages)
            .map_err(|e| CheckpointError::SerializationError(e.to_string()))?;

        self.conn
            .execute(
                "INSERT INTO checkpoints (thread_id, checkpoint_id, state, version, truncated)
                 VALUES (?1, ?2, ?3, 1, ?4)",
                params![
                    thread_id,
                    checkpoint_id.to_string(),
                    state,
                    truncated as i32
                ],
            )
            .map_err(|e| CheckpointError::DbError(format!("Insert failed: {}", e)))?;

        Ok(checkpoint_id)
    }

    /// Load the most recent checkpoint for a thread.
    #[allow(clippy::type_complexity)]
    pub fn load(
        &self,
        thread_id: &str,
    ) -> Result<Option<(uuid::Uuid, Vec<Message>, bool, u32)>, CheckpointError> {
        let mut stmt = self
            .conn
            .prepare(
                "SELECT checkpoint_id, state, truncated, version FROM checkpoints
                 WHERE thread_id = ?1
                 ORDER BY created_at DESC, rowid DESC
                 LIMIT 1",
            )
            .map_err(|e| CheckpointError::DbError(e.to_string()))?;

        let result = stmt.query_row(params![thread_id], |row| {
            let id_str: String = row.get(0)?;
            let state_blob: Vec<u8> = row.get(1)?;
            let truncated: i32 = row.get(2)?;
            let version: i32 = row.get(3)?;
            let checkpoint_id = uuid::Uuid::parse_str(&id_str)
                .map_err(|_| rusqlite::Error::InvalidParameterName("Invalid UUID".into()))?;
            let messages: Vec<Message> = rmp_serde::from_slice(&state_blob).map_err(|e| {
                rusqlite::Error::InvalidParameterName(format!("Deserialize failed: {}", e))
            })?;
            Ok((checkpoint_id, messages, truncated != 0, version as u32))
        });

        match result {
            Ok(val) => Ok(Some(val)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(CheckpointError::DbError(e.to_string())),
        }
    }

    /// Load a specific checkpoint by ID.
    #[allow(clippy::type_complexity)]
    pub fn load_at(
        &self,
        thread_id: &str,
        checkpoint_id: &uuid::Uuid,
    ) -> Result<Option<(Vec<Message>, bool, u32)>, CheckpointError> {
        let mut stmt = self
            .conn
            .prepare(
                "SELECT state, truncated, version FROM checkpoints
                 WHERE thread_id = ?1 AND checkpoint_id = ?2",
            )
            .map_err(|e| CheckpointError::DbError(e.to_string()))?;

        let result = stmt.query_row(params![thread_id, checkpoint_id.to_string()], |row| {
            let state_blob: Vec<u8> = row.get(0)?;
            let truncated: i32 = row.get(1)?;
            let version: i32 = row.get(2)?;
            let messages: Vec<Message> = rmp_serde::from_slice(&state_blob).map_err(|e| {
                rusqlite::Error::InvalidParameterName(format!("Deserialize failed: {}", e))
            })?;
            Ok((messages, truncated != 0, version as u32))
        });

        match result {
            Ok(val) => Ok(Some(val)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(CheckpointError::DbError(e.to_string())),
        }
    }

    /// List checkpoints for a thread (most recent first).
    pub fn list(&self, thread_id: &str, limit: u32) -> Result<Vec<SnapshotMeta>, CheckpointError> {
        let mut stmt = self
            .conn
            .prepare(
                "SELECT checkpoint_id, created_at, version, truncated FROM checkpoints
                 WHERE thread_id = ?1
                 ORDER BY created_at DESC, rowid DESC
                 LIMIT ?2",
            )
            .map_err(|e| CheckpointError::DbError(e.to_string()))?;

        let metas = stmt
            .query_map(params![thread_id, limit], |row| {
                let id_str: String = row.get(0)?;
                let created_str: String = row.get(1)?;
                let version: i32 = row.get(2)?;
                let truncated: i32 = row.get(3)?;

                let checkpoint_id = uuid::Uuid::parse_str(&id_str).unwrap_or(uuid::Uuid::nil());
                // SQLite datetime('now') returns UTC in format "YYYY-MM-DD HH:MM:SS"
                let created_at =
                    chrono::NaiveDateTime::parse_from_str(&created_str, "%Y-%m-%d %H:%M:%S")
                        .map(|naive| {
                            chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
                                naive,
                                chrono::Utc,
                            )
                        })
                        .unwrap_or_else(|_| chrono::Utc::now());

                Ok(SnapshotMeta {
                    thread_id: thread_id.to_string(),
                    checkpoint_id,
                    created_at,
                    version: version as u32,
                    truncated: truncated != 0,
                })
            })
            .map_err(|e| CheckpointError::DbError(e.to_string()))?;

        let mut result = Vec::new();
        for meta in metas {
            result.push(meta.map_err(|e| CheckpointError::DbError(e.to_string()))?);
        }
        Ok(result)
    }

    /// List all checkpoints across all threads (most recent first).
    pub fn list_all(&self, limit: u32) -> Result<Vec<SnapshotMeta>, CheckpointError> {
        let mut stmt = self
            .conn
            .prepare(
                "SELECT checkpoint_id, thread_id, created_at, version, truncated FROM checkpoints
                  ORDER BY created_at DESC, rowid DESC
                  LIMIT ?1",
            )
            .map_err(|e| CheckpointError::DbError(e.to_string()))?;

        let metas = stmt
            .query_map(params![limit], |row| {
                let id_str: String = row.get(0)?;
                let thread_str: String = row.get(1)?;
                let created_str: String = row.get(2)?;
                let version: i32 = row.get(3)?;
                let truncated: i32 = row.get(4)?;

                let checkpoint_id = uuid::Uuid::parse_str(&id_str).unwrap_or(uuid::Uuid::nil());
                let created_at =
                    chrono::NaiveDateTime::parse_from_str(&created_str, "%Y-%m-%d %H:%M:%S")
                        .map(|naive| {
                            chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
                                naive,
                                chrono::Utc,
                            )
                        })
                        .unwrap_or_else(|_| chrono::Utc::now());

                Ok(SnapshotMeta {
                    thread_id: thread_str,
                    checkpoint_id,
                    created_at,
                    version: version as u32,
                    truncated: truncated != 0,
                })
            })
            .map_err(|e| CheckpointError::DbError(e.to_string()))?;

        let mut result = Vec::new();
        for meta in metas {
            result.push(meta.map_err(|e| CheckpointError::DbError(e.to_string()))?);
        }
        Ok(result)
    }

    /// Delete a specific checkpoint by ID.
    pub fn delete_checkpoint(&self, checkpoint_id: &uuid::Uuid) -> Result<(), CheckpointError> {
        self.conn
            .execute(
                "DELETE FROM checkpoints WHERE checkpoint_id = ?1",
                params![checkpoint_id.to_string()],
            )
            .map_err(|e| CheckpointError::DbError(e.to_string()))?;
        Ok(())
    }

    /// Delete all checkpoints for a thread.
    pub fn delete_thread(&self, thread_id: &str) -> Result<(), CheckpointError> {
        self.conn
            .execute(
                "DELETE FROM checkpoints WHERE thread_id = ?1",
                params![thread_id],
            )
            .map_err(|e| CheckpointError::DbError(e.to_string()))?;
        Ok(())
    }

    /// Get the database path
    pub fn db_path(&self) -> &PathBuf {
        &self.db_path
    }
}

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

    fn create_test_store() -> (CheckpointStore, TempDir) {
        let tmp = TempDir::new().unwrap();
        let db_path = tmp.path().join("test.db");
        let store = CheckpointStore::open_at(db_path).unwrap();
        (store, tmp)
    }

    fn make_messages() -> Vec<Message> {
        vec![
            Message::new(Role::System, "You are a code reviewer."),
            Message::new(Role::User, "Review this code."),
            Message::new(Role::Assistant, "I found 3 issues."),
        ]
    }

    #[test]
    fn test_save_and_load() {
        let (store, _tmp) = create_test_store();
        let msgs = make_messages();
        let cid = store.save("test-thread", &msgs, false).unwrap();
        let loaded = store.load("test-thread").unwrap();
        assert!(loaded.is_some());
        let (loaded_cid, loaded_msgs, truncated, version) = loaded.unwrap();
        assert_eq!(version, 1);
        assert_eq!(cid, loaded_cid);
        assert_eq!(msgs, loaded_msgs);
        assert!(!truncated);
    }

    #[test]
    fn test_load_nonexistent_thread() {
        let (store, _tmp) = create_test_store();
        let loaded = store.load("ghost").unwrap();
        assert!(loaded.is_none());
    }

    #[test]
    fn test_load_at() {
        let (store, _tmp) = create_test_store();
        let msgs = make_messages();
        let cid = store.save("test", &msgs, false).unwrap();
        let loaded = store.load_at("test", &cid).unwrap();
        assert!(loaded.is_some());
        let (loaded_msgs, _, version) = loaded.unwrap();
        assert_eq!(version, 1);
        assert_eq!(msgs, loaded_msgs);
    }

    #[test]
    fn test_list() {
        let (store, _tmp) = create_test_store();
        store.save("test", &make_messages(), false).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        store.save("test", &make_messages(), true).unwrap();

        let list = store.list("test", 10).unwrap();
        assert_eq!(list.len(), 2);
        assert!(list[0].created_at >= list[1].created_at);
        assert!(list[0].truncated);
        assert!(!list[1].truncated);
    }

    #[test]
    fn test_delete_thread() {
        let (store, _tmp) = create_test_store();
        store.save("test", &make_messages(), false).unwrap();
        store.delete_thread("test").unwrap();
        let loaded = store.load("test").unwrap();
        assert!(loaded.is_none());
    }

    #[test]
    fn test_message_pack_round_trip() {
        let msgs = make_messages();
        let encoded = rmp_serde::to_vec(&msgs).unwrap();
        let decoded: Vec<Message> = rmp_serde::from_slice(&encoded).unwrap();
        assert_eq!(msgs, decoded);
    }

    #[test]
    fn test_delete_checkpoint() {
        let (store, _tmp) = create_test_store();
        let cid = store.save("del-test", &make_messages(), false).unwrap();
        store.delete_checkpoint(&cid).unwrap();
        // Checkpoint should no longer exist
        let loaded = store.load_at("del-test", &cid).unwrap();
        assert!(loaded.is_none());
        // Thread should still have no checkpoints
        let list = store.list("del-test", 10).unwrap();
        assert!(list.is_empty());
    }

    #[test]
    fn test_delete_checkpoint_does_not_affect_other_threads() {
        let (store, _tmp) = create_test_store();
        let cid_a = store.save("thread-a", &make_messages(), false).unwrap();
        store.save("thread-b", &make_messages(), false).unwrap();
        store.delete_checkpoint(&cid_a).unwrap();
        // thread-a should be empty
        let list_a = store.list("thread-a", 10).unwrap();
        assert!(list_a.is_empty());
        // thread-b should still have its checkpoint
        let list_b = store.list("thread-b", 10).unwrap();
        assert_eq!(list_b.len(), 1);
    }

    #[test]
    fn test_list_all() {
        let (store, _tmp) = create_test_store();
        store.save("alpha", &make_messages(), false).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        store.save("beta", &make_messages(), true).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        store.save("alpha", &make_messages(), false).unwrap();

        let all = store.list_all(10).unwrap();
        assert_eq!(all.len(), 3);
        // Most recent first
        assert_eq!(all[0].thread_id, "alpha");
        assert_eq!(all[1].thread_id, "beta");
        assert_eq!(all[2].thread_id, "alpha");
    }

    #[test]
    fn test_list_all_respects_limit() {
        let (store, _tmp) = create_test_store();
        for i in 0..5 {
            store
                .save(&format!("t{}", i), &make_messages(), false)
                .unwrap();
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        let all = store.list_all(3).unwrap();
        assert_eq!(all.len(), 3);
    }

    #[test]
    fn test_version_round_trip() {
        let (store, _tmp) = create_test_store();
        let cid = store.save("ver-test", &make_messages(), false).unwrap();
        let loaded = store.load("ver-test").unwrap().unwrap();
        assert_eq!(loaded.3, 1); // version field
        let loaded_at = store.load_at("ver-test", &cid).unwrap().unwrap();
        assert_eq!(loaded_at.2, 1); // version field from load_at
    }
}