claw-core 0.1.1

Embedded local database engine for ClawDB — an agent-native cognitive database
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
//! Memory record store for claw-core.
//!
//! The `memories` table is the primary store for persistent AI agent memories.
//! Records are classified by [`MemoryType`], can carry arbitrary tags for
//! keyword search, and optionally expire after a configurable TTL.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::SqlitePool;
use uuid::Uuid;

use crate::error::{ClawError, ClawResult};

// ── ListOptions ──────────────────────────────────────────────────────────────

/// Options controlling pagination for list queries.
///
/// Use with [`crate::ClawEngine::list_memories_paginated`] and
/// [`crate::ClawEngine::list_sessions_paginated`].
///
/// # Example
///
/// ```rust
/// use claw_core::ListOptions;
/// // First page — 50 results.
/// let opts = ListOptions { limit: 50, cursor: None };
/// // Subsequent page — pass the cursor returned from the previous call.
/// let opts2 = ListOptions { limit: 50, cursor: Some("some-uuid".to_string()) };
/// ```
#[derive(Debug, Clone, Default)]
pub struct ListOptions {
    /// Maximum number of items to return. `0` is treated as "no limit".
    pub limit: usize,
    /// Opaque cursor returned by the previous call.  `None` starts from the
    /// beginning.  The cursor value is the `id` of the last record on the
    /// previous page.
    pub cursor: Option<String>,
}

/// The logical classification of a memory record.
///
/// # Example
///
/// ```rust
/// use claw_core::MemoryType;
/// let mt = MemoryType::Semantic;
/// assert_eq!(mt.as_str(), "semantic");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MemoryType {
    /// Factual world knowledge (e.g. "Paris is the capital of France").
    Semantic,
    /// Event-based memories tied to specific experiences.
    Episodic,
    /// Short-lived working memory for active reasoning.
    Working,
    /// Skill or procedure memory.
    Procedural,
}

impl MemoryType {
    /// Return the string representation stored in the database.
    pub fn as_str(&self) -> &'static str {
        match self {
            MemoryType::Semantic => "semantic",
            MemoryType::Episodic => "episodic",
            MemoryType::Working => "working",
            MemoryType::Procedural => "procedural",
        }
    }
}

impl std::fmt::Display for MemoryType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for MemoryType {
    type Err = ClawError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "semantic" => Ok(MemoryType::Semantic),
            "episodic" => Ok(MemoryType::Episodic),
            "working" => Ok(MemoryType::Working),
            "procedural" => Ok(MemoryType::Procedural),
            other => Err(ClawError::InvalidInput(format!(
                "unknown memory type: {other}"
            ))),
        }
    }
}

/// A persistent memory record stored in the `memories` table.
///
/// Create new records with [`MemoryRecord::new`], which auto-generates a UUID
/// and timestamps. Persist them with [`crate::ClawEngine::insert_memory`].
///
/// # Example
///
/// ```rust
/// use claw_core::{MemoryRecord, MemoryType};
/// let r = MemoryRecord::new(
///     "Paris is the capital of France",
///     MemoryType::Semantic,
///     vec!["geography".to_string()],
///     None,
/// );
/// assert_eq!(r.memory_type, MemoryType::Semantic);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryRecord {
    /// Unique record identifier.
    pub id: Uuid,
    /// Natural-language content of the memory.
    pub content: String,
    /// The logical type of this memory.
    pub memory_type: MemoryType,
    /// Searchable tags attached to this record.
    pub tags: Vec<String>,
    /// Optional TTL in seconds from `created_at`. `None` means no expiry.
    pub ttl_seconds: Option<u64>,
    /// Timestamp when this record was first created.
    pub created_at: DateTime<Utc>,
    /// Timestamp when this record was last modified.
    pub updated_at: DateTime<Utc>,
}

impl MemoryRecord {
    /// Create a new [`MemoryRecord`] with a freshly generated UUID and current
    /// UTC timestamps.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claw_core::{MemoryRecord, MemoryType};
    /// let r = MemoryRecord::new("hello", MemoryType::Working, vec![], None);
    /// assert_eq!(r.content, "hello");
    /// assert!(r.ttl_seconds.is_none());
    /// ```
    pub fn new(
        content: impl Into<String>,
        memory_type: MemoryType,
        tags: Vec<String>,
        ttl_seconds: Option<u64>,
    ) -> Self {
        let now = Utc::now();
        MemoryRecord {
            id: Uuid::new_v4(),
            content: content.into(),
            memory_type,
            tags,
            ttl_seconds,
            created_at: now,
            updated_at: now,
        }
    }
}

/// Data-access object for the `memories` and `memories_fts` tables.
///
/// Obtain an instance via [`MemoryStore::new`], passing a shared [`SqlitePool`].
#[derive(Debug)]
pub struct MemoryStore<'a> {
    pool: &'a SqlitePool,
}

impl<'a> MemoryStore<'a> {
    /// Create a new [`MemoryStore`] bound to `pool`.
    pub fn new(pool: &'a SqlitePool) -> Self {
        MemoryStore { pool }
    }

    /// Insert a new [`MemoryRecord`] into the database.
    ///
    /// Both the `memories` table and the `memories_fts` FTS5 index are updated
    /// together.
    ///
    /// # Errors
    ///
    /// Returns a [`ClawError`] if the SQL execution or serialization fails.
    pub async fn insert(&self, record: &MemoryRecord) -> ClawResult<()> {
        let tags = serde_json::to_string(&record.tags)?;
        sqlx::query(
            "INSERT INTO memories \
             (id, content, memory_type, tags, ttl_seconds, created_at, updated_at) \
             VALUES (?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(record.id.to_string())
        .bind(&record.content)
        .bind(record.memory_type.as_str())
        .bind(&tags)
        .bind(record.ttl_seconds.map(|s| s as i64))
        .bind(record.created_at.to_rfc3339())
        .bind(record.updated_at.to_rfc3339())
        .execute(self.pool)
        .await?;

        sqlx::query("INSERT INTO memories_fts(id, content) VALUES (?, ?)")
            .bind(record.id.to_string())
            .bind(&record.content)
            .execute(self.pool)
            .await?;

        // Populate the normalised tag index (migration 0003).
        for tag in &record.tags {
            sqlx::query("INSERT OR IGNORE INTO memory_tags(memory_id, tag) VALUES (?, ?)")
                .bind(record.id.to_string())
                .bind(tag)
                .execute(self.pool)
                .await?;
        }

        Ok(())
    }

    /// Fetch a [`MemoryRecord`] by its `id`.
    ///
    /// # Errors
    ///
    /// Returns [`ClawError::NotFound`] if no record with the given `id` exists.
    pub async fn get(&self, id: Uuid) -> ClawResult<MemoryRecord> {
        let row =
            sqlx::query_as::<_, (String, String, String, String, Option<i64>, String, String)>(
                "SELECT id, content, memory_type, tags, ttl_seconds, created_at, updated_at \
             FROM memories WHERE id = ?",
            )
            .bind(id.to_string())
            .fetch_optional(self.pool)
            .await?;

        let row = row.ok_or_else(|| ClawError::NotFound {
            entity: "MemoryRecord".to_string(),
            id: id.to_string(),
        })?;

        Self::row_to_record(row)
    }

    /// Update the `content` and `updated_at` of a [`MemoryRecord`].
    ///
    /// # Errors
    ///
    /// Returns [`ClawError::NotFound`] if no record with the given `id` exists.
    pub async fn update_content(
        &self,
        id: Uuid,
        content: &str,
        updated_at: DateTime<Utc>,
    ) -> ClawResult<()> {
        let affected = sqlx::query("UPDATE memories SET content = ?, updated_at = ? WHERE id = ?")
            .bind(content)
            .bind(updated_at.to_rfc3339())
            .bind(id.to_string())
            .execute(self.pool)
            .await?
            .rows_affected();

        if affected == 0 {
            return Err(ClawError::NotFound {
                entity: "MemoryRecord".to_string(),
                id: id.to_string(),
            });
        }

        sqlx::query("UPDATE memories_fts SET content = ? WHERE id = ?")
            .bind(content)
            .bind(id.to_string())
            .execute(self.pool)
            .await?;

        Ok(())
    }

    /// Delete a [`MemoryRecord`] by its `id`.
    ///
    /// # Errors
    ///
    /// Returns [`ClawError::NotFound`] if no record with the given `id` exists.
    pub async fn delete(&self, id: Uuid) -> ClawResult<()> {
        let affected = sqlx::query("DELETE FROM memories WHERE id = ?")
            .bind(id.to_string())
            .execute(self.pool)
            .await?
            .rows_affected();

        if affected == 0 {
            return Err(ClawError::NotFound {
                entity: "MemoryRecord".to_string(),
                id: id.to_string(),
            });
        }

        sqlx::query("DELETE FROM memory_tags WHERE memory_id = ?")
            .bind(id.to_string())
            .execute(self.pool)
            .await?;

        sqlx::query("DELETE FROM memories_fts WHERE id = ?")
            .bind(id.to_string())
            .execute(self.pool)
            .await?;

        Ok(())
    }

    /// List all [`MemoryRecord`]s, optionally filtered by [`MemoryType`].
    ///
    /// Results are ordered by `created_at` ascending.
    ///
    /// # Errors
    ///
    /// Returns a [`ClawError`] if the query fails.
    pub async fn list(&self, type_filter: Option<&MemoryType>) -> ClawResult<Vec<MemoryRecord>> {
        #[allow(clippy::type_complexity)]
        let rows: Vec<(String, String, String, String, Option<i64>, String, String)> =
            match type_filter {
                Some(mt) => sqlx::query_as(
                    "SELECT id, content, memory_type, tags, ttl_seconds, created_at, updated_at \
                     FROM memories WHERE memory_type = ? ORDER BY created_at ASC",
                )
                .bind(mt.as_str())
                .fetch_all(self.pool)
                .await?,
                None => sqlx::query_as(
                    "SELECT id, content, memory_type, tags, ttl_seconds, created_at, updated_at \
                     FROM memories ORDER BY created_at ASC",
                )
                .fetch_all(self.pool)
                .await?,
            };

        rows.into_iter().map(Self::row_to_record).collect()
    }

    /// Search for records whose tag list contains `tag`.
    ///
    /// Uses the normalised `memory_tags` index (O(log n)) rather than a
    /// full-table LIKE scan.
    ///
    /// # Errors
    ///
    /// Returns a [`ClawError`] if the query fails.
    pub async fn search_by_tag(&self, tag: &str) -> ClawResult<Vec<MemoryRecord>> {
        #[allow(clippy::type_complexity)]
        let rows: Vec<(String, String, String, String, Option<i64>, String, String)> =
            sqlx::query_as(
                "SELECT m.id, m.content, m.memory_type, m.tags, m.ttl_seconds, \
                        m.created_at, m.updated_at \
                 FROM memories m \
                 JOIN memory_tags mt ON mt.memory_id = m.id \
                 WHERE mt.tag = ? \
                 ORDER BY m.created_at ASC",
            )
            .bind(tag)
            .fetch_all(self.pool)
            .await?;

        rows.into_iter().map(Self::row_to_record).collect()
    }

    /// List memories with keyset pagination.
    ///
    /// Returns up to `opts.limit` records (or all if `limit == 0`) plus an
    /// optional cursor for the next page.  The cursor is the `id` of the last
    /// returned record; pass it back as `opts.cursor` to continue iterating.
    ///
    /// # Errors
    ///
    /// Returns a [`ClawError`] if the query fails.
    pub async fn list_paginated(
        &self,
        type_filter: Option<&MemoryType>,
        opts: &ListOptions,
    ) -> ClawResult<(Vec<MemoryRecord>, Option<String>)> {
        let limit = if opts.limit == 0 {
            i64::MAX
        } else {
            opts.limit as i64
        };
        // Fetch one extra row to detect whether a next page exists.
        let fetch = limit.saturating_add(1);

        #[allow(clippy::type_complexity)]
        let rows: Vec<(String, String, String, String, Option<i64>, String, String)> =
            match (&opts.cursor, type_filter) {
                (None, None) => {
                    sqlx::query_as(
                        "SELECT id, content, memory_type, tags, ttl_seconds, \
                            created_at, updated_at \
                     FROM memories \
                     ORDER BY created_at ASC, id ASC \
                     LIMIT ?",
                    )
                    .bind(fetch)
                    .fetch_all(self.pool)
                    .await?
                }
                (None, Some(mt)) => {
                    sqlx::query_as(
                        "SELECT id, content, memory_type, tags, ttl_seconds, \
                            created_at, updated_at \
                     FROM memories \
                     WHERE memory_type = ? \
                     ORDER BY created_at ASC, id ASC \
                     LIMIT ?",
                    )
                    .bind(mt.as_str())
                    .bind(fetch)
                    .fetch_all(self.pool)
                    .await?
                }
                (Some(cursor), None) => {
                    sqlx::query_as(
                        "SELECT id, content, memory_type, tags, ttl_seconds, \
                            created_at, updated_at \
                     FROM memories \
                     WHERE (created_at, id) > \
                         (SELECT created_at, id FROM memories WHERE id = ?) \
                     ORDER BY created_at ASC, id ASC \
                     LIMIT ?",
                    )
                    .bind(cursor)
                    .bind(fetch)
                    .fetch_all(self.pool)
                    .await?
                }
                (Some(cursor), Some(mt)) => {
                    sqlx::query_as(
                        "SELECT id, content, memory_type, tags, ttl_seconds, \
                            created_at, updated_at \
                     FROM memories \
                     WHERE memory_type = ? \
                       AND (created_at, id) > \
                           (SELECT created_at, id FROM memories WHERE id = ?) \
                     ORDER BY created_at ASC, id ASC \
                     LIMIT ?",
                    )
                    .bind(mt.as_str())
                    .bind(cursor)
                    .bind(fetch)
                    .fetch_all(self.pool)
                    .await?
                }
            };

        let has_more = rows.len() as i64 > limit;
        let page = if has_more {
            &rows[..limit as usize]
        } else {
            rows.as_slice()
        };

        let records: Vec<MemoryRecord> = page
            .iter()
            .cloned()
            .map(Self::row_to_record)
            .collect::<ClawResult<_>>()?;
        let next_cursor = if has_more {
            records.last().map(|r| r.id.to_string())
        } else {
            None
        };
        Ok((records, next_cursor))
    }

    /// Full-text search over the `memories_fts` index.
    ///
    /// The `query` follows FTS5 query syntax.
    ///
    /// # Errors
    ///
    /// Returns a [`ClawError`] if the query fails.
    pub async fn fts_search(&self, query: &str) -> ClawResult<Vec<MemoryRecord>> {
        let ids: Vec<(String,)> =
            sqlx::query_as("SELECT id FROM memories_fts WHERE content MATCH ? ORDER BY rank")
                .bind(query)
                .fetch_all(self.pool)
                .await?;

        let mut records = Vec::with_capacity(ids.len());
        for (id_str,) in ids {
            #[allow(clippy::type_complexity)]
            let row: Option<(
                String,
                String,
                String,
                String,
                Option<i64>,
                String,
                String,
            )> = sqlx::query_as(
                "SELECT id, content, memory_type, tags, ttl_seconds, created_at, updated_at \
                     FROM memories WHERE id = ?",
            )
            .bind(&id_str)
            .fetch_optional(self.pool)
            .await?;
            if let Some(r) = row {
                records.push(Self::row_to_record(r)?);
            }
        }
        Ok(records)
    }

    /// Delete all records whose TTL has expired.
    ///
    /// Returns the number of records deleted.
    ///
    /// # Errors
    ///
    /// Returns a [`ClawError`] if any deletion fails.
    pub async fn expire_ttl(&self) -> ClawResult<u64> {
        let rows: Vec<(String, Option<i64>, String)> = sqlx::query_as(
            "SELECT id, ttl_seconds, created_at FROM memories WHERE ttl_seconds IS NOT NULL",
        )
        .fetch_all(self.pool)
        .await?;

        let now = Utc::now();
        let mut deleted = 0u64;

        for (id_str, ttl_secs, created_at_str) in rows {
            if let Some(ttl) = ttl_secs {
                let created_at = DateTime::parse_from_rfc3339(&created_at_str)
                    .map_err(|e| ClawError::Store(e.to_string()))?
                    .with_timezone(&Utc);
                let expiry = created_at + chrono::Duration::seconds(ttl);
                if now >= expiry {
                    sqlx::query("DELETE FROM memories WHERE id = ?")
                        .bind(&id_str)
                        .execute(self.pool)
                        .await?;
                    sqlx::query("DELETE FROM memories_fts WHERE id = ?")
                        .bind(&id_str)
                        .execute(self.pool)
                        .await?;
                    deleted += 1;
                }
            }
        }

        Ok(deleted)
    }

    fn row_to_record(
        row: (String, String, String, String, Option<i64>, String, String),
    ) -> ClawResult<MemoryRecord> {
        let (id_str, content, memory_type_str, tags_str, ttl_secs, created_at_str, updated_at_str) =
            row;
        Ok(MemoryRecord {
            id: Uuid::parse_str(&id_str).map_err(|e| ClawError::Store(e.to_string()))?,
            content,
            memory_type: memory_type_str.parse()?,
            tags: serde_json::from_str(&tags_str)?,
            ttl_seconds: ttl_secs.map(|s| s as u64),
            created_at: DateTime::parse_from_rfc3339(&created_at_str)
                .map_err(|e| ClawError::Store(e.to_string()))?
                .with_timezone(&Utc),
            updated_at: DateTime::parse_from_rfc3339(&updated_at_str)
                .map_err(|e| ClawError::Store(e.to_string()))?
                .with_timezone(&Utc),
        })
    }
}