claw-core 0.1.2

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
//! 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};

/// Options controlling pagination for list queries.
///
/// `limit` defaults to `50` and is clamped to a maximum of `1000`.
#[derive(Debug, Clone)]
pub struct ListOptions {
    /// Maximum number of items to return.
    pub limit: u32,
    /// Opaque cursor returned by the previous call.
    pub cursor: Option<String>,
}

impl Default for ListOptions {
    fn default() -> Self {
        Self {
            limit: 50,
            cursor: None,
        }
    }
}

impl ListOptions {
    /// Return the validated page size.
    pub fn validated_limit(&self) -> u32 {
        self.limit.clamp(1, 1000)
    }
}

/// A page of list results with an optional continuation cursor.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListPage<T> {
    /// Page items.
    pub items: Vec<T>,
    /// Cursor to request the next page, if any.
    pub next_cursor: Option<String>,
}

/// The logical classification of a memory record.
#[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.
#[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 fresh UUID and current UTC timestamps.
    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.
#[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.
    ///
    /// The write is atomic across `memories`, `memories_fts`, and `memory_tags`.
    pub async fn insert(&self, record: &MemoryRecord) -> ClawResult<()> {
        let tags = serde_json::to_string(&record.tags)?;
        let mut tx = self.pool.begin().await?;

        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(&mut *tx)
        .await?;

        sqlx::query(
            "INSERT INTO memories_fts(rowid, content) \
               VALUES (last_insert_rowid(), ?)",
        )
        .bind(&record.content)
        .execute(&mut *tx)
        .await?;

        for tag in &record.tags {
            sqlx::query("INSERT OR REPLACE INTO memory_tags(memory_id, tag) VALUES (?, ?)")
                .bind(record.id.to_string())
                .bind(tag)
                .execute(&mut *tx)
                .await?;
        }

        tx.commit().await?;
        Ok(())
    }

    /// Fetch a [`MemoryRecord`] by its `id`.
    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`].
    ///
    /// The write is atomic across `memories` and `memories_fts`.
    pub async fn update_content(
        &self,
        id: Uuid,
        content: &str,
        updated_at: DateTime<Utc>,
    ) -> ClawResult<()> {
        let mut tx = self.pool.begin().await?;

        let affected = sqlx::query("UPDATE memories SET content = ?, updated_at = ? WHERE id = ?")
            .bind(content)
            .bind(updated_at.to_rfc3339())
            .bind(id.to_string())
            .execute(&mut *tx)
            .await?
            .rows_affected();

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

        sqlx::query(
            "DELETE FROM memories_fts WHERE rowid = (SELECT rowid FROM memories WHERE id = ?)",
        )
        .bind(id.to_string())
        .execute(&mut *tx)
        .await?;

        sqlx::query(
            "INSERT INTO memories_fts(rowid, content) \
             VALUES ((SELECT rowid FROM memories WHERE id = ?), ?)",
        )
        .bind(id.to_string())
        .bind(content)
        .execute(&mut *tx)
        .await?;

        tx.commit().await?;
        Ok(())
    }

    /// Delete a [`MemoryRecord`] by its `id`.
    ///
    /// `memory_tags` rows are removed by `ON DELETE CASCADE`.
    pub async fn delete(&self, id: Uuid) -> ClawResult<()> {
        let mut tx = self.pool.begin().await?;

        sqlx::query(
            "DELETE FROM memories_fts WHERE rowid = (SELECT rowid FROM memories WHERE id = ?)",
        )
        .bind(id.to_string())
        .execute(&mut *tx)
        .await?;

        let affected = sqlx::query("DELETE FROM memories WHERE id = ?")
            .bind(id.to_string())
            .execute(&mut *tx)
            .await?
            .rows_affected();

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

        tx.commit().await?;
        Ok(())
    }

    /// List all [`MemoryRecord`]s, optionally filtered by [`MemoryType`].
    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 DESC, id DESC",
                )
                .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 DESC, id DESC",
                )
                .fetch_all(self.pool)
                .await?,
            };

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

    /// Search by exact tag using the indexed `memory_tags` table.
    pub async fn search_by_tag(
        &self,
        tag: &str,
        limit: u32,
        offset: u32,
    ) -> 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 t ON m.id = t.memory_id \
                 WHERE t.tag = ? \
                 ORDER BY m.created_at DESC LIMIT ? OFFSET ?",
            )
            .bind(tag)
            .bind(limit as i64)
            .bind(offset as i64)
            .fetch_all(self.pool)
            .await?;

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

    /// List memories with keyset pagination.
    pub async fn list_paginated(
        &self,
        type_filter: Option<&MemoryType>,
        opts: &ListOptions,
    ) -> ClawResult<ListPage<MemoryRecord>> {
        let limit = opts.validated_limit() as i64;
        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 DESC, id DESC 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 DESC, id DESC 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 DESC, id DESC 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 DESC, id DESC LIMIT ?",
                )
                .bind(mt.as_str())
                .bind(cursor)
                .bind(fetch)
                .fetch_all(self.pool)
                .await?,
            };

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

        let items = page_rows
            .iter()
            .cloned()
            .map(Self::row_to_record)
            .collect::<ClawResult<Vec<_>>>()?;

        let next_cursor = if has_more {
            items.last().map(|item| item.id.to_string())
        } else {
            None
        };

        Ok(ListPage { items, next_cursor })
    }

    /// Full-text search over the `memories_fts` index.
    pub async fn fts_search(&self, query: &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_fts f \
                 JOIN memories m ON m.rowid = f.rowid \
                 WHERE memories_fts MATCH ? \
                 ORDER BY m.created_at DESC, m.id DESC",
            )
            .bind(query)
            .fetch_all(self.pool)
            .await?;

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

    /// Delete all records whose TTL has expired.
    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_fts WHERE rowid = (SELECT rowid FROM memories WHERE id = ?)")
                        .bind(&id_str)
                        .execute(self.pool)
                        .await?;
                    sqlx::query("DELETE FROM memories 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),
        })
    }
}