aidaemon-memory 0.28.0

Swappable long-term memory for aidaemon agents: the MemoryStore traits plus SQLite and embedding implementations
Documentation
//! Versioned, embedded schema migrations for [`super::SqliteMemoryStore`].
//!
//! Versions are recorded in `memory_schema_migrations` (not the generic
//! `schema_migrations`) so this store can share a database file with
//! `aidaemon-store-sqlite` without the two version sequences colliding.
//! Each migration runs in one transaction with its version row. Migrations
//! are append-only.

use sqlx::SqlitePool;

use crate::error::{MemoryError, Result};

/// One schema step (the shape `aidaemon-store-sqlite` applies).
pub use aidaemon_store_sqlite::Migration;

/// Every migration this build knows, in order.
pub const MIGRATIONS: &[Migration] = &[
    Migration {
        version: 1,
        name: "facts_episodes_fts",
        sql: r#"
CREATE TABLE memory_facts (
    id                TEXT PRIMARY KEY NOT NULL,
    scope             TEXT NOT NULL,
    category          TEXT NOT NULL,
    key               TEXT NOT NULL,
    value             TEXT NOT NULL,
    confidence        REAL NOT NULL,
    source_run_id     TEXT,
    source_session_id TEXT,
    source_excerpt    TEXT,
    created_at        TEXT NOT NULL,
    updated_at        TEXT NOT NULL,
    superseded_at     TEXT,
    recall_count      INTEGER NOT NULL DEFAULT 0,
    last_recalled_at  TEXT,
    embedding         BLOB,
    embedding_model   TEXT
);

-- At most one active row per key; superseded rows are history.
CREATE UNIQUE INDEX idx_memory_facts_active
    ON memory_facts (scope, category, key) WHERE superseded_at IS NULL;
CREATE INDEX idx_memory_facts_history ON memory_facts (scope, category, key, created_at);
CREATE INDEX idx_memory_facts_superseded ON memory_facts (superseded_at)
    WHERE superseded_at IS NOT NULL;

-- Lexical index over ACTIVE facts only, maintained in the same transaction
-- as every write.
CREATE VIRTUAL TABLE memory_facts_fts USING fts5(
    fact_id UNINDEXED,
    scope UNINDEXED,
    content,
    tokenize = 'unicode61'
);

CREATE TABLE memory_episodes (
    id               TEXT PRIMARY KEY NOT NULL,
    scope            TEXT NOT NULL,
    session_id       TEXT NOT NULL,
    summary          TEXT NOT NULL,
    topics           TEXT NOT NULL CHECK (json_valid(topics)),
    importance       REAL NOT NULL,
    created_at       TEXT NOT NULL,
    recall_count     INTEGER NOT NULL DEFAULT 0,
    last_recalled_at TEXT,
    embedding        BLOB,
    embedding_model  TEXT
);

CREATE INDEX idx_memory_episodes_scope ON memory_episodes (scope, created_at);

CREATE VIRTUAL TABLE memory_episodes_fts USING fts5(
    episode_id UNINDEXED,
    scope UNINDEXED,
    content,
    tokenize = 'unicode61'
);
"#,
    },
    Migration {
        version: 2,
        name: "record_access",
        // Rows from before this version were never classified, so they read
        // as private: the owner keeps seeing them and shared channels do not.
        sql: r#"
ALTER TABLE memory_facts ADD COLUMN privacy TEXT NOT NULL DEFAULT 'private';
ALTER TABLE memory_facts ADD COLUMN channel_id TEXT;
ALTER TABLE memory_episodes ADD COLUMN privacy TEXT NOT NULL DEFAULT 'private';
ALTER TABLE memory_episodes ADD COLUMN channel_id TEXT;
"#,
    },
];

/// The newest schema version this build understands.
pub fn latest_version() -> i64 {
    MIGRATIONS.last().map(|m| m.version).unwrap_or(0)
}

pub(crate) async fn current_version(pool: &SqlitePool) -> Result<i64> {
    Ok(aidaemon_store_sqlite::recorded_version(pool, VERSION_TABLE).await?)
}

/// The table this store records its versions in.
const VERSION_TABLE: &str = "memory_schema_migrations";

/// Bring the schema up to date. Idempotent and refuses newer databases.
pub(crate) async fn run(pool: &SqlitePool) -> Result<()> {
    aidaemon_store_sqlite::apply_migrations(pool, VERSION_TABLE, MIGRATIONS)
        .await
        .map_err(|error| match error {
            aidaemon_store_sqlite::MigrateError::Sqlx(error) => MemoryError::Sqlx(error),
            aidaemon_store_sqlite::MigrateError::SchemaTooNew { found, supported } => {
                MemoryError::SchemaTooNew { found, supported }
            }
            aidaemon_store_sqlite::MigrateError::Step {
                version,
                name,
                source,
            } => MemoryError::Migration {
                version,
                name,
                source,
            },
        })
}