Skip to main content

aidaemon_memory/store/
migrations.rs

1//! Versioned, embedded schema migrations for [`super::SqliteMemoryStore`].
2//!
3//! Versions are recorded in `memory_schema_migrations` (not the generic
4//! `schema_migrations`) so this store can share a database file with
5//! `aidaemon-store-sqlite` without the two version sequences colliding.
6//! Each migration runs in one transaction with its version row. Migrations
7//! are append-only.
8
9use sqlx::SqlitePool;
10
11use crate::error::{MemoryError, Result};
12
13/// One schema step.
14#[derive(Debug, Clone, Copy)]
15pub struct Migration {
16    /// Strictly increasing, starting at 1.
17    pub version: i64,
18    pub name: &'static str,
19    pub sql: &'static str,
20}
21
22/// Every migration this build knows, in order.
23pub const MIGRATIONS: &[Migration] = &[
24    Migration {
25        version: 1,
26        name: "facts_episodes_fts",
27        sql: r#"
28CREATE TABLE memory_facts (
29    id                TEXT PRIMARY KEY NOT NULL,
30    scope             TEXT NOT NULL,
31    category          TEXT NOT NULL,
32    key               TEXT NOT NULL,
33    value             TEXT NOT NULL,
34    confidence        REAL NOT NULL,
35    source_run_id     TEXT,
36    source_session_id TEXT,
37    source_excerpt    TEXT,
38    created_at        TEXT NOT NULL,
39    updated_at        TEXT NOT NULL,
40    superseded_at     TEXT,
41    recall_count      INTEGER NOT NULL DEFAULT 0,
42    last_recalled_at  TEXT,
43    embedding         BLOB,
44    embedding_model   TEXT
45);
46
47-- At most one active row per key; superseded rows are history.
48CREATE UNIQUE INDEX idx_memory_facts_active
49    ON memory_facts (scope, category, key) WHERE superseded_at IS NULL;
50CREATE INDEX idx_memory_facts_history ON memory_facts (scope, category, key, created_at);
51CREATE INDEX idx_memory_facts_superseded ON memory_facts (superseded_at)
52    WHERE superseded_at IS NOT NULL;
53
54-- Lexical index over ACTIVE facts only, maintained in the same transaction
55-- as every write.
56CREATE VIRTUAL TABLE memory_facts_fts USING fts5(
57    fact_id UNINDEXED,
58    scope UNINDEXED,
59    content,
60    tokenize = 'unicode61'
61);
62
63CREATE TABLE memory_episodes (
64    id               TEXT PRIMARY KEY NOT NULL,
65    scope            TEXT NOT NULL,
66    session_id       TEXT NOT NULL,
67    summary          TEXT NOT NULL,
68    topics           TEXT NOT NULL CHECK (json_valid(topics)),
69    importance       REAL NOT NULL,
70    created_at       TEXT NOT NULL,
71    recall_count     INTEGER NOT NULL DEFAULT 0,
72    last_recalled_at TEXT,
73    embedding        BLOB,
74    embedding_model  TEXT
75);
76
77CREATE INDEX idx_memory_episodes_scope ON memory_episodes (scope, created_at);
78
79CREATE VIRTUAL TABLE memory_episodes_fts USING fts5(
80    episode_id UNINDEXED,
81    scope UNINDEXED,
82    content,
83    tokenize = 'unicode61'
84);
85"#,
86    },
87    Migration {
88        version: 2,
89        name: "record_access",
90        // Rows from before this version were never classified, so they read
91        // as private: the owner keeps seeing them and shared channels do not.
92        sql: r#"
93ALTER TABLE memory_facts ADD COLUMN privacy TEXT NOT NULL DEFAULT 'private';
94ALTER TABLE memory_facts ADD COLUMN channel_id TEXT;
95ALTER TABLE memory_episodes ADD COLUMN privacy TEXT NOT NULL DEFAULT 'private';
96ALTER TABLE memory_episodes ADD COLUMN channel_id TEXT;
97"#,
98    },
99];
100
101/// The newest schema version this build understands.
102pub fn latest_version() -> i64 {
103    MIGRATIONS.last().map(|m| m.version).unwrap_or(0)
104}
105
106pub(crate) async fn current_version(pool: &SqlitePool) -> Result<i64> {
107    let version: Option<i64> =
108        sqlx::query_scalar("SELECT MAX(version) FROM memory_schema_migrations")
109            .fetch_one(pool)
110            .await?;
111    Ok(version.unwrap_or(0))
112}
113
114/// Bring the schema up to date. Idempotent and refuses newer databases.
115pub(crate) async fn run(pool: &SqlitePool) -> Result<()> {
116    debug_assert!(
117        MIGRATIONS
118            .windows(2)
119            .all(|w| w[1].version == w[0].version + 1)
120    );
121
122    sqlx::query(
123        "CREATE TABLE IF NOT EXISTS memory_schema_migrations (
124            version    INTEGER PRIMARY KEY,
125            applied_at TEXT NOT NULL
126        )",
127    )
128    .execute(pool)
129    .await?;
130
131    let found = current_version(pool).await?;
132    let supported = latest_version();
133    if found > supported {
134        return Err(MemoryError::SchemaTooNew { found, supported });
135    }
136
137    for migration in MIGRATIONS.iter().filter(|m| m.version > found) {
138        let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
139        let claimed = sqlx::query(
140            "INSERT OR IGNORE INTO memory_schema_migrations (version, applied_at)
141             VALUES (?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))",
142        )
143        .bind(migration.version)
144        .execute(&mut *tx)
145        .await?
146        .rows_affected();
147        if claimed == 0 {
148            tx.rollback().await?;
149            continue;
150        }
151        sqlx::Executor::execute(&mut *tx, migration.sql)
152            .await
153            .map_err(|source| MemoryError::Migration {
154                version: migration.version,
155                name: migration.name,
156                source,
157            })?;
158        tx.commit().await?;
159    }
160    Ok(())
161}