Skip to main content

aidaemon_memory/sqlite/
schema.rs

1//! The memory tables: created on a new database, brought up to date on an
2//! existing one. Every step is idempotent and runs on each start, and none
3//! removes a user's data, so upgrading the host keeps what it remembers.
4
5use sqlx::{Row, SqlitePool};
6
7/// Create or upgrade the memory tables in `pool`.
8pub async fn migrate(pool: &SqlitePool) -> anyhow::Result<()> {
9    // Create tables
10    sqlx::query(
11        "CREATE TABLE IF NOT EXISTS facts (
12            id INTEGER PRIMARY KEY AUTOINCREMENT,
13            category TEXT NOT NULL,
14            key TEXT NOT NULL,
15            value TEXT NOT NULL,
16            source TEXT NOT NULL DEFAULT '',
17            created_at TEXT NOT NULL,
18            updated_at TEXT NOT NULL
19        )",
20    )
21    .execute(pool)
22    .await?;
23
24    // --- Human-Like Memory System Migrations ---
25    // 5. Add new columns to facts table for supersession and recall tracking
26    aidaemon_tools::sqlite_schema::add_column_if_missing(
27        pool,
28        "ALTER TABLE facts ADD COLUMN superseded_at TEXT",
29    )
30    .await?;
31    aidaemon_tools::sqlite_schema::add_column_if_missing(
32        pool,
33        "ALTER TABLE facts ADD COLUMN recall_count INTEGER DEFAULT 0",
34    )
35    .await?;
36    aidaemon_tools::sqlite_schema::add_column_if_missing(
37        pool,
38        "ALTER TABLE facts ADD COLUMN last_recalled_at TEXT",
39    )
40    .await?;
41
42    // 6. Create episodes table (episodic memory)
43    sqlx::query(
44        "CREATE TABLE IF NOT EXISTS episodes (
45            id INTEGER PRIMARY KEY AUTOINCREMENT,
46            session_id TEXT NOT NULL,
47            summary TEXT NOT NULL,
48            topics TEXT,
49            emotional_tone TEXT,
50            outcome TEXT,
51            embedding BLOB,
52            importance REAL DEFAULT 0.5,
53            recall_count INTEGER DEFAULT 0,
54            last_recalled_at TEXT,
55            message_count INTEGER,
56            start_time TEXT NOT NULL,
57            end_time TEXT NOT NULL,
58            created_at TEXT NOT NULL
59        )",
60    )
61    .execute(pool)
62    .await?;
63
64    sqlx::query("CREATE INDEX IF NOT EXISTS idx_episodes_session ON episodes(session_id)")
65        .execute(pool)
66        .await?;
67
68    // 8. Create user_profile table
69    sqlx::query(
70        "CREATE TABLE IF NOT EXISTS user_profile (
71            id INTEGER PRIMARY KEY AUTOINCREMENT,
72            verbosity_preference TEXT DEFAULT 'medium',
73            explanation_depth TEXT DEFAULT 'moderate',
74            tone_preference TEXT DEFAULT 'neutral',
75            emoji_preference TEXT DEFAULT 'none',
76            typical_session_length INTEGER,
77            active_hours TEXT,
78            common_workflows TEXT,
79            asks_before_acting INTEGER DEFAULT 0,
80            prefers_explanations INTEGER DEFAULT 1,
81            likes_suggestions INTEGER DEFAULT 0,
82            updated_at TEXT NOT NULL
83        )",
84    )
85    .execute(pool)
86    .await?;
87
88    // 9. Create behavior_patterns table
89    sqlx::query(
90        "CREATE TABLE IF NOT EXISTS behavior_patterns (
91            id INTEGER PRIMARY KEY AUTOINCREMENT,
92            pattern_type TEXT NOT NULL,
93            description TEXT NOT NULL,
94            trigger_context TEXT,
95            action TEXT,
96            confidence REAL DEFAULT 0.5,
97            occurrence_count INTEGER DEFAULT 1,
98            last_seen_at TEXT,
99            created_at TEXT NOT NULL
100        )",
101    )
102    .execute(pool)
103    .await?;
104
105    // 10. Create procedures table (procedural memory)
106    sqlx::query(
107        "CREATE TABLE IF NOT EXISTS procedures (
108            id INTEGER PRIMARY KEY AUTOINCREMENT,
109            name TEXT NOT NULL UNIQUE,
110            trigger_pattern TEXT NOT NULL,
111            trigger_embedding BLOB,
112            steps TEXT NOT NULL,
113            success_count INTEGER DEFAULT 1,
114            failure_count INTEGER DEFAULT 0,
115            avg_duration_secs REAL,
116            last_used_at TEXT,
117            created_at TEXT NOT NULL,
118            updated_at TEXT NOT NULL
119        )",
120    )
121    .execute(pool)
122    .await?;
123
124    // 11. Create expertise table
125    sqlx::query(
126        "CREATE TABLE IF NOT EXISTS expertise (
127            id INTEGER PRIMARY KEY AUTOINCREMENT,
128            domain TEXT NOT NULL UNIQUE,
129            tasks_attempted INTEGER DEFAULT 0,
130            tasks_succeeded INTEGER DEFAULT 0,
131            tasks_failed INTEGER DEFAULT 0,
132            current_level TEXT DEFAULT 'novice',
133            confidence_score REAL DEFAULT 0.0,
134            common_errors TEXT,
135            last_task_at TEXT,
136            created_at TEXT NOT NULL,
137            updated_at TEXT NOT NULL
138        )",
139    )
140    .execute(pool)
141    .await?;
142
143    // 12. Create error_solutions table
144    sqlx::query(
145        "CREATE TABLE IF NOT EXISTS error_solutions (
146            id INTEGER PRIMARY KEY AUTOINCREMENT,
147            error_pattern TEXT NOT NULL,
148            error_embedding BLOB,
149            domain TEXT,
150            solution_summary TEXT NOT NULL,
151            solution_steps TEXT,
152            success_count INTEGER DEFAULT 1,
153            failure_count INTEGER DEFAULT 0,
154            last_used_at TEXT,
155            created_at TEXT NOT NULL
156        )",
157    )
158    .execute(pool)
159    .await?;
160
161    // Normalize historical NULL domains to empty string so dedupe/unique keys are stable.
162    sqlx::query("UPDATE error_solutions SET domain = '' WHERE domain IS NULL")
163        .execute(pool)
164        .await?;
165
166    // Dedupe: allow multiple solutions per error pattern, but avoid identical repeats.
167    // Only do the (potentially expensive) cleanup once, before we install the unique index.
168    let has_unique: Option<i64> = sqlx::query_scalar::<_, i64>(
169        "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'idx_error_solutions_unique' LIMIT 1",
170    )
171    .fetch_optional(pool)
172    .await?;
173    if has_unique.is_none() {
174        // Remove exact duplicates before adding the unique index.
175        // Keep the smallest id (oldest row) for each (error_pattern, domain, solution_summary) triple.
176        sqlx::query(
177            r#"
178            DELETE FROM error_solutions
179            WHERE id NOT IN (
180                SELECT MIN(id)
181                FROM error_solutions
182                GROUP BY error_pattern, domain, solution_summary
183            )
184            "#,
185        )
186        .execute(pool)
187        .await?;
188
189        sqlx::query(
190            "CREATE UNIQUE INDEX IF NOT EXISTS idx_error_solutions_unique
191             ON error_solutions(error_pattern, domain, solution_summary)",
192        )
193        .execute(pool)
194        .await?;
195    }
196
197    // People tables - for tracking the owner's social circle
198    sqlx::query(
199        "CREATE TABLE IF NOT EXISTS people (
200            id INTEGER PRIMARY KEY AUTOINCREMENT,
201            name TEXT NOT NULL,
202            aliases_json TEXT NOT NULL DEFAULT '[]',
203            relationship TEXT,
204            platform_ids_json TEXT NOT NULL DEFAULT '{}',
205            notes TEXT,
206            communication_style TEXT,
207            language_preference TEXT,
208            last_interaction_at TEXT,
209            interaction_count INTEGER NOT NULL DEFAULT 0,
210            created_at TEXT NOT NULL DEFAULT (datetime('now')),
211            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
212        )",
213    )
214    .execute(pool)
215    .await?;
216
217    sqlx::query(
218        "CREATE TABLE IF NOT EXISTS person_facts (
219            id INTEGER PRIMARY KEY AUTOINCREMENT,
220            person_id INTEGER NOT NULL REFERENCES people(id) ON DELETE CASCADE,
221            category TEXT NOT NULL,
222            key TEXT NOT NULL,
223            value TEXT NOT NULL,
224            source TEXT NOT NULL DEFAULT 'agent',
225            confidence REAL NOT NULL DEFAULT 1.0,
226            created_at TEXT NOT NULL DEFAULT (datetime('now')),
227            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
228            UNIQUE(person_id, category, key)
229        )",
230    )
231    .execute(pool)
232    .await?;
233
234    sqlx::query("CREATE INDEX IF NOT EXISTS idx_people_name ON people(name)")
235        .execute(pool)
236        .await?;
237    sqlx::query("CREATE INDEX IF NOT EXISTS idx_person_facts_person ON person_facts(person_id)")
238        .execute(pool)
239        .await?;
240    sqlx::query("CREATE INDEX IF NOT EXISTS idx_person_facts_category ON person_facts(category)")
241        .execute(pool)
242        .await?;
243
244    // --- Channel-Scoped Memory Migrations ---
245    // Add channel_id and privacy columns to facts table
246    aidaemon_tools::sqlite_schema::add_column_if_missing(
247        pool,
248        "ALTER TABLE facts ADD COLUMN channel_id TEXT",
249    )
250    .await?;
251    aidaemon_tools::sqlite_schema::add_column_if_missing(
252        pool,
253        "ALTER TABLE facts ADD COLUMN privacy TEXT DEFAULT 'global'",
254    )
255    .await?;
256    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_facts_channel ON facts(channel_id)")
257        .execute(pool)
258        .await;
259    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_facts_privacy ON facts(privacy)")
260        .execute(pool)
261        .await;
262    // Add channel_id column to episodes table
263    aidaemon_tools::sqlite_schema::add_column_if_missing(
264        pool,
265        "ALTER TABLE episodes ADD COLUMN channel_id TEXT",
266    )
267    .await?;
268    // Stable canonical bounds avoid timestamp-tie duplication when creating
269    // multiple episodes for a long-running session.
270    aidaemon_tools::sqlite_schema::add_column_if_missing(
271        pool,
272        "ALTER TABLE episodes ADD COLUMN start_event_id INTEGER",
273    )
274    .await?;
275    aidaemon_tools::sqlite_schema::add_column_if_missing(
276        pool,
277        "ALTER TABLE episodes ADD COLUMN end_event_id INTEGER",
278    )
279    .await?;
280    let _ = sqlx::query(
281        "CREATE INDEX IF NOT EXISTS idx_episodes_session_end_event
282         ON episodes(session_id, end_event_id)",
283    )
284    .execute(pool)
285    .await;
286
287    // --- Binary Embedding Storage Migration ---
288    // Add embedding column to facts table for pre-computed embeddings
289    aidaemon_tools::sqlite_schema::add_column_if_missing(
290        pool,
291        "ALTER TABLE facts ADD COLUMN embedding BLOB",
292    )
293    .await?;
294
295    // --- Provenance Capture Migrations ---
296    // Add first_seen_at and source_excerpt to facts table
297    aidaemon_tools::sqlite_schema::add_column_if_missing(
298        pool,
299        "ALTER TABLE facts ADD COLUMN first_seen_at TEXT",
300    )
301    .await?;
302    aidaemon_tools::sqlite_schema::add_column_if_missing(
303        pool,
304        "ALTER TABLE facts ADD COLUMN source_excerpt TEXT",
305    )
306    .await?;
307
308    // Backfill legacy source values: facts with an unknown source are marked
309    // "inferred". The allowlist MUST contain every source value live writers
310    // stamp ('progressive' from progressive extraction, 'owner_quoted' from
311    // its quote-checked flat facts, 'agent' from
312    // remember_fact, 'task_learning' from task learning, 'consolidation' from
313    // memory consolidation, plus the stamped 'user_stated'/'derived'
314    // provenance values) — this runs on every startup, so anything missing
315    // here gets its provenance permanently scrubbed.
316    sqlx::query("UPDATE facts SET source = 'inferred' WHERE source NOT IN ('consolidation', 'user_stated', 'derived', 'inferred', 'progressive', 'owner_quoted', 'agent', 'task_learning')")
317        .execute(pool)
318        .await?;
319
320    // --- Facts History Migration ---
321    // Ensure facts can keep superseded history while enforcing a single active
322    // row per (category, key).
323    if let Err(e) = migrate_facts_history_schema(pool).await {
324        tracing::warn!("Failed to migrate facts schema for history: {}", e);
325    }
326    // Why a row stopped being active (`SupersededReason`), and for a fold
327    // or a copy the row that carries its knowledge on. Added after the
328    // legacy rebuild, which copies a fixed column list. NULL on rows retired
329    // before this column existed.
330    aidaemon_tools::sqlite_schema::add_column_if_missing(
331        pool,
332        "ALTER TABLE facts ADD COLUMN superseded_reason TEXT",
333    )
334    .await?;
335    aidaemon_tools::sqlite_schema::add_column_if_missing(
336        pool,
337        "ALTER TABLE facts ADD COLUMN folded_into INTEGER",
338    )
339    .await?;
340
341    // Migration: deduplicate people entries and add unique index on LOWER(name).
342    // Keeps the row with the lowest id for each name, merging interaction counts.
343    let _ = sqlx::query(
344        "DELETE FROM people WHERE id NOT IN (
345            SELECT MIN(id) FROM people GROUP BY LOWER(name)
346        )",
347    )
348    .execute(pool)
349    .await;
350    let _ = sqlx::query(
351        "CREATE UNIQUE INDEX IF NOT EXISTS idx_people_name_unique ON people(LOWER(name))",
352    )
353    .execute(pool)
354    .await;
355
356    // Migration: allow multiple episodes per session (for mid-session episode
357    // creation in long-running conversations). The non-unique index on session_id
358    // (idx_episodes_session) already exists for lookups.
359    let _ = sqlx::query("DROP INDEX IF EXISTS idx_episodes_session_unique")
360        .execute(pool)
361        .await;
362
363    // Canonical long-term memory. Domain tables remain authoritative during
364    // the rolling migration; these tables are durable projections with explicit
365    // provenance, validity, and replaceable search indexes.
366    sqlx::query(
367        "CREATE TABLE IF NOT EXISTS memory_spans (
368            id INTEGER PRIMARY KEY AUTOINCREMENT,
369            span_kind TEXT NOT NULL,
370            source_event_id INTEGER,
371            source_episode_id INTEGER UNIQUE,
372            session_id TEXT,
373            channel_id TEXT,
374            role TEXT,
375            content TEXT NOT NULL,
376            content_hash TEXT NOT NULL,
377            privacy TEXT NOT NULL DEFAULT 'global',
378            observed_from TEXT,
379            observed_to TEXT,
380            valid_from TEXT NOT NULL,
381            valid_to TEXT,
382            deleted_at TEXT,
383            created_at TEXT NOT NULL DEFAULT (datetime('now'))
384        )",
385    )
386    .execute(pool)
387    .await?;
388    aidaemon_tools::sqlite_schema::add_column_if_missing(
389        pool,
390        "ALTER TABLE memory_spans ADD COLUMN observed_from TEXT",
391    )
392    .await?;
393    aidaemon_tools::sqlite_schema::add_column_if_missing(
394        pool,
395        "ALTER TABLE memory_spans ADD COLUMN observed_to TEXT",
396    )
397    .await?;
398
399    sqlx::query(
400        "CREATE TABLE IF NOT EXISTS memory_claims (
401            id INTEGER PRIMARY KEY AUTOINCREMENT,
402            subject TEXT NOT NULL,
403            predicate TEXT NOT NULL,
404            object TEXT NOT NULL,
405            claim_text TEXT NOT NULL,
406            source_fact_id INTEGER UNIQUE,
407            source_span_id INTEGER,
408            source_event_id INTEGER,
409            provenance TEXT NOT NULL,
410            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
411            channel_id TEXT,
412            privacy TEXT NOT NULL DEFAULT 'global',
413            valid_from TEXT NOT NULL,
414            valid_to TEXT,
415            superseded_by_claim_id INTEGER,
416            deleted_at TEXT,
417            created_at TEXT NOT NULL DEFAULT (datetime('now')),
418            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
419            FOREIGN KEY(source_span_id) REFERENCES memory_spans(id),
420            FOREIGN KEY(superseded_by_claim_id) REFERENCES memory_claims(id)
421        )",
422    )
423    .execute(pool)
424    .await?;
425
426    sqlx::query(
427        "CREATE TABLE IF NOT EXISTS memory_entities (
428            id INTEGER PRIMARY KEY AUTOINCREMENT,
429            entity_type TEXT NOT NULL,
430            canonical_name TEXT NOT NULL,
431            display_name TEXT NOT NULL,
432            aliases_json TEXT NOT NULL DEFAULT '[]',
433            channel_id TEXT,
434            privacy TEXT NOT NULL DEFAULT 'global',
435            deleted_at TEXT,
436            created_at TEXT NOT NULL DEFAULT (datetime('now')),
437            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
438            UNIQUE(entity_type, canonical_name)
439        )",
440    )
441    .execute(pool)
442    .await?;
443    for statement in [
444        "ALTER TABLE memory_entities ADD COLUMN status TEXT NOT NULL DEFAULT 'active'",
445        "ALTER TABLE memory_entities ADD COLUMN merged_into_entity_id INTEGER",
446        "ALTER TABLE memory_entities ADD COLUMN is_owner INTEGER NOT NULL DEFAULT 0",
447    ] {
448        aidaemon_tools::sqlite_schema::add_column_if_missing(pool, statement).await?;
449    }
450
451    // Entity-aware personal memory. These tables extend the rolling canonical
452    // projection without changing or deleting the legacy facts/people tables.
453    sqlx::query(
454        "CREATE TABLE IF NOT EXISTS memory_aliases (
455            id INTEGER PRIMARY KEY AUTOINCREMENT,
456            entity_id INTEGER NOT NULL,
457            alias_type TEXT NOT NULL,
458            value TEXT NOT NULL,
459            normalized_value TEXT NOT NULL,
460            status TEXT NOT NULL DEFAULT 'active',
461            source TEXT NOT NULL,
462            provenance TEXT,
463            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
464            channel_id TEXT,
465            privacy TEXT NOT NULL DEFAULT 'private',
466            asserted_at TEXT NOT NULL,
467            confirmed_at TEXT,
468            last_confirmed_at TEXT,
469            valid_from TEXT,
470            valid_to TEXT,
471            created_at TEXT NOT NULL,
472            updated_at TEXT NOT NULL,
473            FOREIGN KEY(entity_id) REFERENCES memory_entities(id),
474            UNIQUE(entity_id, alias_type, normalized_value)
475        )",
476    )
477    .execute(pool)
478    .await?;
479
480    sqlx::query(
481        "CREATE TABLE IF NOT EXISTS memory_entity_facts (
482            id INTEGER PRIMARY KEY AUTOINCREMENT,
483            subject_entity_id INTEGER NOT NULL,
484            predicate TEXT NOT NULL,
485            value_type TEXT NOT NULL DEFAULT 'text',
486            value TEXT NOT NULL,
487            normalized_value TEXT NOT NULL,
488            display_value TEXT,
489            status TEXT NOT NULL DEFAULT 'active',
490            source TEXT NOT NULL,
491            provenance TEXT,
492            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
493            source_fact_id INTEGER,
494            channel_id TEXT,
495            privacy TEXT NOT NULL DEFAULT 'private',
496            asserted_at TEXT NOT NULL,
497            confirmed_at TEXT,
498            last_confirmed_at TEXT,
499            valid_from TEXT,
500            valid_to TEXT,
501            supersedes_fact_id INTEGER,
502            created_at TEXT NOT NULL,
503            updated_at TEXT NOT NULL,
504            FOREIGN KEY(subject_entity_id) REFERENCES memory_entities(id),
505            FOREIGN KEY(source_fact_id) REFERENCES facts(id),
506            FOREIGN KEY(supersedes_fact_id) REFERENCES memory_entity_facts(id)
507        )",
508    )
509    .execute(pool)
510    .await?;
511
512    sqlx::query(
513        "CREATE TABLE IF NOT EXISTS memory_relationships (
514            id INTEGER PRIMARY KEY AUTOINCREMENT,
515            source_entity_id INTEGER NOT NULL,
516            relationship_type TEXT NOT NULL,
517            target_entity_id INTEGER NOT NULL,
518            inverse_relationship_id INTEGER,
519            status TEXT NOT NULL DEFAULT 'active',
520            source TEXT NOT NULL,
521            provenance TEXT,
522            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
523            source_fact_id INTEGER,
524            channel_id TEXT,
525            privacy TEXT NOT NULL DEFAULT 'private',
526            asserted_at TEXT NOT NULL,
527            confirmed_at TEXT,
528            last_confirmed_at TEXT,
529            valid_from TEXT,
530            valid_to TEXT,
531            created_at TEXT NOT NULL,
532            updated_at TEXT NOT NULL,
533            FOREIGN KEY(source_entity_id) REFERENCES memory_entities(id),
534            FOREIGN KEY(target_entity_id) REFERENCES memory_entities(id),
535            FOREIGN KEY(inverse_relationship_id) REFERENCES memory_relationships(id),
536            FOREIGN KEY(source_fact_id) REFERENCES facts(id)
537        )",
538    )
539    .execute(pool)
540    .await?;
541
542    sqlx::query(
543        "CREATE TABLE IF NOT EXISTS memory_resolution_reviews (
544            id INTEGER PRIMARY KEY AUTOINCREMENT,
545            review_kind TEXT NOT NULL,
546            normalized_reference TEXT,
547            candidate_entity_ids_json TEXT NOT NULL DEFAULT '[]',
548            payload_json TEXT NOT NULL,
549            source TEXT NOT NULL,
550            source_fact_id INTEGER,
551            status TEXT NOT NULL DEFAULT 'pending',
552            created_at TEXT NOT NULL,
553            updated_at TEXT NOT NULL,
554            resolved_at TEXT,
555            UNIQUE(review_kind, normalized_reference, payload_json, status)
556        )",
557    )
558    .execute(pool)
559    .await?;
560
561    sqlx::query(
562        "CREATE TABLE IF NOT EXISTS memory_write_audit (
563            id INTEGER PRIMARY KEY AUTOINCREMENT,
564            operation TEXT NOT NULL,
565            entity_id INTEGER,
566            record_type TEXT NOT NULL,
567            record_id INTEGER,
568            prior_state_json TEXT,
569            new_state_json TEXT,
570            source TEXT NOT NULL,
571            source_fact_id INTEGER,
572            provenance TEXT,
573            created_at TEXT NOT NULL,
574            FOREIGN KEY(entity_id) REFERENCES memory_entities(id)
575        )",
576    )
577    .execute(pool)
578    .await?;
579
580    sqlx::query(
581        "CREATE TABLE IF NOT EXISTS memory_edges (
582            id INTEGER PRIMARY KEY AUTOINCREMENT,
583            source_entity_id INTEGER NOT NULL,
584            target_entity_id INTEGER NOT NULL,
585            relation TEXT NOT NULL,
586            source_claim_id INTEGER,
587            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
588            channel_id TEXT,
589            privacy TEXT NOT NULL DEFAULT 'global',
590            valid_from TEXT NOT NULL,
591            valid_to TEXT,
592            deleted_at TEXT,
593            created_at TEXT NOT NULL DEFAULT (datetime('now')),
594            FOREIGN KEY(source_entity_id) REFERENCES memory_entities(id),
595            FOREIGN KEY(target_entity_id) REFERENCES memory_entities(id),
596            FOREIGN KEY(source_claim_id) REFERENCES memory_claims(id),
597            UNIQUE(source_entity_id, target_entity_id, relation, source_claim_id)
598        )",
599    )
600    .execute(pool)
601    .await?;
602
603    sqlx::query(
604        "CREATE TABLE IF NOT EXISTS memory_embeddings (
605            id INTEGER PRIMARY KEY AUTOINCREMENT,
606            owner_type TEXT NOT NULL,
607            owner_id TEXT NOT NULL,
608            embedding_purpose TEXT NOT NULL,
609            embedding_model TEXT NOT NULL,
610            embedding_dim INTEGER NOT NULL CHECK(embedding_dim > 0),
611            content_hash TEXT NOT NULL,
612            embedding BLOB NOT NULL,
613            stale_at TEXT,
614            created_at TEXT NOT NULL,
615            updated_at TEXT NOT NULL,
616            UNIQUE(owner_type, owner_id, embedding_purpose, embedding_model, content_hash)
617        )",
618    )
619    .execute(pool)
620    .await?;
621
622    // A change counter for `memory_embeddings`, so the in-memory vector
623    // cache in `SqliteEmbeddingIndex` knows when to reload. Triggers keep it
624    // exact whichever code (or process) writes the table.
625    for statement in [
626        "CREATE TABLE IF NOT EXISTS memory_embedding_generation (
627            id INTEGER PRIMARY KEY CHECK(id = 1),
628            generation INTEGER NOT NULL
629        )",
630        "INSERT OR IGNORE INTO memory_embedding_generation (id, generation) VALUES (1, 0)",
631        "CREATE TRIGGER IF NOT EXISTS memory_embeddings_generation_insert
632         AFTER INSERT ON memory_embeddings BEGIN
633            UPDATE memory_embedding_generation SET generation = generation + 1 WHERE id = 1;
634         END",
635        "CREATE TRIGGER IF NOT EXISTS memory_embeddings_generation_update
636         AFTER UPDATE ON memory_embeddings BEGIN
637            UPDATE memory_embedding_generation SET generation = generation + 1 WHERE id = 1;
638         END",
639        "CREATE TRIGGER IF NOT EXISTS memory_embeddings_generation_delete
640         AFTER DELETE ON memory_embeddings BEGIN
641            UPDATE memory_embedding_generation SET generation = generation + 1 WHERE id = 1;
642         END",
643    ] {
644        sqlx::query(statement).execute(pool).await?;
645    }
646
647    for statement in [
648        "CREATE INDEX IF NOT EXISTS idx_memory_claims_active ON memory_claims(privacy, channel_id, valid_to, deleted_at)",
649        "CREATE INDEX IF NOT EXISTS idx_memory_spans_active ON memory_spans(privacy, channel_id, valid_to, deleted_at)",
650        "CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_spans_source_event ON memory_spans(source_event_id) WHERE source_event_id IS NOT NULL",
651        "CREATE INDEX IF NOT EXISTS idx_memory_edges_source ON memory_edges(source_entity_id, valid_to, deleted_at)",
652        "CREATE INDEX IF NOT EXISTS idx_memory_edges_target ON memory_edges(target_entity_id, valid_to, deleted_at)",
653        "CREATE INDEX IF NOT EXISTS idx_memory_embeddings_lookup ON memory_embeddings(embedding_model, embedding_purpose, owner_type, stale_at)",
654        "CREATE INDEX IF NOT EXISTS idx_memory_embeddings_owner ON memory_embeddings(owner_type, owner_id, stale_at)",
655        "CREATE INDEX IF NOT EXISTS idx_memory_entities_status ON memory_entities(entity_type, status, canonical_name)",
656        "CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_entities_one_owner ON memory_entities(is_owner) WHERE is_owner = 1 AND status = 'active'",
657        "CREATE INDEX IF NOT EXISTS idx_memory_aliases_lookup ON memory_aliases(normalized_value, alias_type, status)",
658        "CREATE INDEX IF NOT EXISTS idx_memory_aliases_entity ON memory_aliases(entity_id, status)",
659        "CREATE INDEX IF NOT EXISTS idx_memory_entity_facts_subject ON memory_entity_facts(subject_entity_id, predicate, status)",
660        "CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_entity_facts_active_exact ON memory_entity_facts(subject_entity_id, predicate, normalized_value) WHERE status = 'active' AND valid_to IS NULL",
661        "CREATE INDEX IF NOT EXISTS idx_memory_relationships_source ON memory_relationships(source_entity_id, relationship_type, status)",
662        "CREATE INDEX IF NOT EXISTS idx_memory_relationships_target ON memory_relationships(target_entity_id, relationship_type, status)",
663        "CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_relationships_active_exact ON memory_relationships(source_entity_id, relationship_type, target_entity_id) WHERE status = 'active' AND valid_to IS NULL",
664        "CREATE INDEX IF NOT EXISTS idx_memory_reviews_status ON memory_resolution_reviews(status, review_kind)",
665        "CREATE INDEX IF NOT EXISTS idx_memory_audit_entity ON memory_write_audit(entity_id, created_at)",
666    ] {
667        sqlx::query(statement).execute(pool).await?;
668    }
669
670    repair_blank_validity_bounds(pool).await?;
671    convert_legacy_person_dates(pool).await?;
672
673    // FTS5 is present in standard SQLite and bundled SQLCipher builds. Keep the
674    // daemon usable on custom SQLite builds without it; semantic and lexical
675    // fallback retrieval remain available.
676    if let Err(error) = create_memory_fts(pool).await {
677        tracing::warn!(%error, "SQLite FTS5 unavailable; memory full-text index disabled");
678    }
679
680    Ok(())
681}
682
683/// Canonical rows written with a blank validity bound (`""` from extraction,
684/// meaning "no bound") were invisible to every `valid_to IS NULL` read: the
685/// prompt never showed them and the next identical write inserted a
686/// duplicate. Ends the later duplicate of each such row, then stores the
687/// remaining blank bounds as NULL. Idempotent: a clean database matches
688/// nothing.
689async fn repair_blank_validity_bounds(pool: &SqlitePool) -> anyhow::Result<()> {
690    // A twin that already has a NULL bound wins whatever its id; between two
691    // blank twins the older one does.
692    let twin = |alias: &str, row: &str| {
693        format!(
694            "({alias}.valid_to IS NULL OR (TRIM({alias}.valid_to) = '' AND {alias}.id < {row}.id))"
695        )
696    };
697    let statements = [
698        format!(
699            "UPDATE memory_entity_facts AS f SET status = 'superseded', valid_to = f.updated_at
700             WHERE f.status = 'active' AND TRIM(f.valid_to) = ''
701               AND EXISTS (SELECT 1 FROM memory_entity_facts o
702                           WHERE o.subject_entity_id = f.subject_entity_id
703                             AND o.predicate = f.predicate
704                             AND o.normalized_value = f.normalized_value
705                             AND o.status = 'active' AND o.id <> f.id AND {})",
706            twin("o", "f")
707        ),
708        format!(
709            "UPDATE memory_relationships AS r SET status = 'superseded', valid_to = r.updated_at
710             WHERE r.status = 'active' AND TRIM(r.valid_to) = ''
711               AND EXISTS (SELECT 1 FROM memory_relationships o
712                           WHERE o.source_entity_id = r.source_entity_id
713                             AND o.relationship_type = r.relationship_type
714                             AND o.target_entity_id = r.target_entity_id
715                             AND o.status = 'active' AND o.id <> r.id AND {})",
716            twin("o", "r")
717        ),
718    ];
719    for statement in &statements {
720        sqlx::query(sqlx::AssertSqlSafe(statement.as_str()))
721            .execute(pool)
722            .await?;
723    }
724    for table in [
725        "memory_entity_facts",
726        "memory_relationships",
727        "memory_aliases",
728    ] {
729        for column in ["valid_from", "valid_to"] {
730            sqlx::query(sqlx::AssertSqlSafe(format!(
731                "UPDATE {table} SET {column} = NULL WHERE TRIM({column}) = ''"
732            )))
733            .execute(pool)
734            .await?;
735        }
736    }
737    Ok(())
738}
739
740/// Birthdays and important dates stored before dates were ISO only
741/// ("March 15", "03-15", "3/15") are read by nothing now: rewrites each one
742/// the old reader understood as ISO, read the way it read them
743/// ([`crate::dates::legacy_date_to_iso`]). A value it could not read stays
744/// as written. Idempotent: an ISO value is never touched, so a second run
745/// changes nothing.
746async fn convert_legacy_person_dates(pool: &SqlitePool) -> anyhow::Result<()> {
747    let placeholders = vec!["?"; crate::dates::DATE_FACT_CATEGORIES.len()].join(", ");
748    let select = format!(
749        "SELECT id, value FROM person_facts WHERE LOWER(TRIM(category)) IN ({placeholders})"
750    );
751    let mut query = sqlx::query_as::<_, (i64, String)>(sqlx::AssertSqlSafe(select));
752    for category in crate::dates::DATE_FACT_CATEGORIES {
753        query = query.bind(*category);
754    }
755    let rows = query.fetch_all(pool).await?;
756    let mut converted = 0usize;
757    for (id, value) in rows {
758        let Some(iso) = crate::dates::legacy_date_to_iso(&value) else {
759            continue;
760        };
761        sqlx::query("UPDATE person_facts SET value = ? WHERE id = ? AND value = ?")
762            .bind(&iso)
763            .bind(id)
764            .bind(&value)
765            .execute(pool)
766            .await?;
767        converted += 1;
768    }
769    if converted > 0 {
770        tracing::info!(converted, "Rewrote legacy person dates as ISO dates");
771    }
772    Ok(())
773}
774
775/// Migrate facts schema to allow supersession history.
776///
777/// Legacy databases used a table-level `UNIQUE(category, key)` constraint which prevents
778/// inserting a new version after marking the old one superseded. We rebuild the table once
779/// to remove that constraint, then enforce at most one *active* fact per key via a partial
780/// unique index: `UNIQUE(category, key) WHERE superseded_at IS NULL`.
781async fn migrate_facts_history_schema(pool: &SqlitePool) -> anyhow::Result<()> {
782    let table_row = sqlx::query(
783        "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'facts' LIMIT 1",
784    )
785    .fetch_optional(pool)
786    .await?;
787
788    let Some(row) = table_row else {
789        // No facts table yet.
790        return Ok(());
791    };
792
793    let create_sql: Option<String> = row.try_get("sql").unwrap_or(None);
794    let create_sql = create_sql.unwrap_or_default();
795    let create_l = create_sql.to_lowercase();
796    let has_legacy_unique = create_l.contains("unique(category, key)")
797        || create_l.contains("unique(category,key)")
798        || create_l.contains("unique (category, key)")
799        || create_l.contains("unique (category,key)");
800
801    if has_legacy_unique {
802        let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
803
804        // Defensive: clean up a prior failed attempt.
805        let _ = sqlx::query("DROP TABLE IF EXISTS facts_new")
806            .execute(&mut *tx)
807            .await;
808
809        sqlx::query(
810            "CREATE TABLE facts_new (
811                id INTEGER PRIMARY KEY AUTOINCREMENT,
812                category TEXT NOT NULL,
813                key TEXT NOT NULL,
814                value TEXT NOT NULL,
815                source TEXT NOT NULL DEFAULT '',
816                created_at TEXT NOT NULL,
817                updated_at TEXT NOT NULL,
818                superseded_at TEXT,
819                recall_count INTEGER DEFAULT 0,
820                last_recalled_at TEXT,
821                channel_id TEXT,
822                privacy TEXT DEFAULT 'global',
823                embedding BLOB
824            )",
825        )
826        .execute(&mut *tx)
827        .await?;
828
829        // Copy all existing columns. These columns should exist after migrations, but
830        // keeping this in a single statement makes the rebuild fast.
831        sqlx::query(
832            "INSERT INTO facts_new
833                (id, category, key, value, source, created_at, updated_at, superseded_at,
834                 recall_count, last_recalled_at, channel_id, privacy, embedding)
835             SELECT
836                id, category, key, value, source, created_at, updated_at, superseded_at,
837                recall_count, last_recalled_at, channel_id, privacy, embedding
838             FROM facts",
839        )
840        .execute(&mut *tx)
841        .await?;
842
843        sqlx::query("DROP TABLE facts").execute(&mut *tx).await?;
844        sqlx::query("ALTER TABLE facts_new RENAME TO facts")
845            .execute(&mut *tx)
846            .await?;
847
848        tx.commit().await?;
849    }
850
851    // (Re)create indexes. If the table was rebuilt, previous indexes were dropped.
852    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_facts_channel ON facts(channel_id)")
853        .execute(pool)
854        .await;
855    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_facts_privacy ON facts(privacy)")
856        .execute(pool)
857        .await;
858    if let Err(e) = sqlx::query(
859        "CREATE UNIQUE INDEX IF NOT EXISTS idx_facts_active_unique
860         ON facts(category, key) WHERE superseded_at IS NULL",
861    )
862    .execute(pool)
863    .await
864    {
865        tracing::warn!(
866            "Failed to create idx_facts_active_unique (active fact dedupe not enforced): {}",
867            e
868        );
869    }
870
871    Ok(())
872}
873
874async fn create_memory_fts(pool: &SqlitePool) -> anyhow::Result<()> {
875    let claims_fts_existed = sqlx::query_scalar::<_, i64>(
876        "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memory_claims_fts'",
877    )
878    .fetch_optional(pool)
879    .await?
880    .is_some();
881    let spans_fts_existed = sqlx::query_scalar::<_, i64>(
882        "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memory_spans_fts'",
883    )
884    .fetch_optional(pool)
885    .await?
886    .is_some();
887    sqlx::query(
888        "CREATE VIRTUAL TABLE IF NOT EXISTS memory_claims_fts USING fts5(
889            claim_text, content='memory_claims', content_rowid='id', tokenize='unicode61'
890        )",
891    )
892    .execute(pool)
893    .await?;
894    sqlx::query(
895        "CREATE VIRTUAL TABLE IF NOT EXISTS memory_spans_fts USING fts5(
896            content, content='memory_spans', content_rowid='id', tokenize='unicode61'
897        )",
898    )
899    .execute(pool)
900    .await?;
901    // FTS5 secure-delete corrupts external-content indexes under the
902    // multi-connection SQLCipher 3.51.2 workload used by the daemon (the same
903    // update sequence is healthy through a single connection). Keep the FTS
904    // projection in compatibility mode. The database remains encrypted and
905    // `PRAGMA secure_delete=ON` still scrubs ordinary SQLite pages; deleted FTS
906    // terms are made unqueryable by the standard tombstone/merge mechanism.
907    for table in ["memory_claims_fts", "memory_spans_fts"] {
908        sqlx::query(sqlx::AssertSqlSafe(format!(
909            "INSERT INTO {table}({table}, rank) VALUES('secure-delete', 0)"
910        )))
911        .execute(pool)
912        .await?;
913    }
914
915    // `UPDATE OF column` fires even when an UPSERT assigns the existing value.
916    // Repeated delete/reinsert churn of an unchanged row can corrupt FTS5
917    // secure-delete segments on SQLCipher's SQLite build. Replace legacy
918    // update triggers and suppress true no-op text updates.
919    for trigger in ["memory_claims_au", "memory_spans_au"] {
920        sqlx::query(sqlx::AssertSqlSafe(format!(
921            "DROP TRIGGER IF EXISTS {trigger}"
922        )))
923        .execute(pool)
924        .await?;
925    }
926
927    for statement in [
928        "CREATE TRIGGER IF NOT EXISTS memory_claims_ai AFTER INSERT ON memory_claims BEGIN INSERT INTO memory_claims_fts(rowid, claim_text) VALUES (new.id, new.claim_text); END",
929        "CREATE TRIGGER IF NOT EXISTS memory_claims_ad AFTER DELETE ON memory_claims BEGIN INSERT INTO memory_claims_fts(memory_claims_fts, rowid, claim_text) VALUES ('delete', old.id, old.claim_text); END",
930        "CREATE TRIGGER memory_claims_au AFTER UPDATE OF claim_text ON memory_claims WHEN old.claim_text IS NOT new.claim_text BEGIN INSERT INTO memory_claims_fts(memory_claims_fts, rowid, claim_text) VALUES ('delete', old.id, old.claim_text); INSERT INTO memory_claims_fts(rowid, claim_text) VALUES (new.id, new.claim_text); END",
931        "CREATE TRIGGER IF NOT EXISTS memory_spans_ai AFTER INSERT ON memory_spans BEGIN INSERT INTO memory_spans_fts(rowid, content) VALUES (new.id, new.content); END",
932        "CREATE TRIGGER IF NOT EXISTS memory_spans_ad AFTER DELETE ON memory_spans BEGIN INSERT INTO memory_spans_fts(memory_spans_fts, rowid, content) VALUES ('delete', old.id, old.content); END",
933        "CREATE TRIGGER memory_spans_au AFTER UPDATE OF content ON memory_spans WHEN old.content IS NOT new.content BEGIN INSERT INTO memory_spans_fts(memory_spans_fts, rowid, content) VALUES ('delete', old.id, old.content); INSERT INTO memory_spans_fts(rowid, content) VALUES (new.id, new.content); END",
934    ] {
935        sqlx::query(statement).execute(pool).await?;
936    }
937
938    if !claims_fts_existed {
939        sqlx::query("INSERT INTO memory_claims_fts(memory_claims_fts) VALUES ('rebuild')")
940            .execute(pool)
941            .await?;
942    }
943    if !spans_fts_existed {
944        sqlx::query("INSERT INTO memory_spans_fts(memory_spans_fts) VALUES ('rebuild')")
945            .execute(pool)
946            .await?;
947    }
948    Ok(())
949}
950
951/// Recreate the memory search indexes from their authoritative source tables.
952///
953/// These FTS tables are replaceable projections. Rebuilding both together keeps
954/// their trigger and secure-delete configuration consistent after either index
955/// is reported corrupt during startup integrity verification.
956pub async fn rebuild_memory_fts_projections(pool: &SqlitePool) -> anyhow::Result<()> {
957    sqlx::query("DROP TABLE IF EXISTS memory_claims_fts")
958        .execute(pool)
959        .await?;
960    sqlx::query("DROP TABLE IF EXISTS memory_spans_fts")
961        .execute(pool)
962        .await?;
963    create_memory_fts(pool).await
964}
965
966#[cfg(test)]
967mod tests {
968    use super::*;
969    use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
970
971    #[tokio::test]
972    async fn legacy_person_dates_become_iso_once_and_unreadable_ones_stay() {
973        let pool = SqlitePoolOptions::new()
974            .max_connections(1)
975            .connect("sqlite::memory:")
976            .await
977            .unwrap();
978        sqlx::query(
979            "CREATE TABLE person_facts (
980                id INTEGER PRIMARY KEY,
981                person_id INTEGER NOT NULL,
982                category TEXT NOT NULL,
983                key TEXT NOT NULL,
984                value TEXT NOT NULL
985             )",
986        )
987        .execute(&pool)
988        .await
989        .unwrap();
990        for (id, category, value) in [
991            (1, "birthday", "March 15"),
992            (2, "important_date", "3/15"),
993            (3, "birthday", "--07-04"),
994            (4, "birthday", "15 March"),
995            (5, "preference", "03-15"),
996            (6, "Birthday", "2019-4-2"),
997        ] {
998            sqlx::query(
999                "INSERT INTO person_facts (id, person_id, category, key, value) VALUES (?, 1, ?, 'synthetic', ?)",
1000            )
1001            .bind(id)
1002            .bind(category)
1003            .bind(value)
1004            .execute(&pool)
1005            .await
1006            .unwrap();
1007        }
1008        convert_legacy_person_dates(&pool).await.unwrap();
1009        convert_legacy_person_dates(&pool).await.unwrap();
1010        let values: Vec<String> = sqlx::query_scalar("SELECT value FROM person_facts ORDER BY id")
1011            .fetch_all(&pool)
1012            .await
1013            .unwrap();
1014        assert_eq!(
1015            values,
1016            [
1017                "--03-15",
1018                "--03-15",
1019                "--07-04",
1020                // The old reader could not read it: left as written.
1021                "15 March",
1022                // Not a date category.
1023                "03-15",
1024                "2019-04-02",
1025            ]
1026        );
1027    }
1028
1029    #[tokio::test]
1030    async fn no_op_content_updates_do_not_churn_or_corrupt_secure_delete_indexes() {
1031        let database = tempfile::NamedTempFile::new().unwrap();
1032        let options = SqliteConnectOptions::new()
1033            .filename(database.path())
1034            .create_if_missing(true);
1035        let pool = SqlitePoolOptions::new()
1036            .max_connections(2)
1037            .connect_with(options)
1038            .await
1039            .unwrap();
1040        sqlx::query(
1041            "CREATE TABLE memory_claims (
1042                id INTEGER PRIMARY KEY,
1043                claim_text TEXT NOT NULL
1044             );
1045             CREATE TABLE memory_spans (
1046                id INTEGER PRIMARY KEY,
1047                content TEXT NOT NULL
1048             )",
1049        )
1050        .execute(&pool)
1051        .await
1052        .unwrap();
1053
1054        create_memory_fts(&pool).await.unwrap();
1055        for table in ["memory_claims_fts_config", "memory_spans_fts_config"] {
1056            let secure_delete: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
1057                "SELECT v FROM {table} WHERE k = 'secure-delete'"
1058            )))
1059            .fetch_one(&pool)
1060            .await
1061            .unwrap();
1062            assert_eq!(secure_delete, 0);
1063        }
1064        sqlx::query("INSERT INTO memory_claims(id, claim_text) VALUES (1, 'alpha claim')")
1065            .execute(&pool)
1066            .await
1067            .unwrap();
1068        sqlx::query("INSERT INTO memory_spans(id, content) VALUES (1, 'alpha span')")
1069            .execute(&pool)
1070            .await
1071            .unwrap();
1072        let claim_shadow_before: (i64, i64) = sqlx::query_as(
1073            "SELECT COUNT(*), COALESCE(SUM(length(block)), 0) FROM memory_claims_fts_data",
1074        )
1075        .fetch_one(&pool)
1076        .await
1077        .unwrap();
1078        let span_shadow_before: (i64, i64) = sqlx::query_as(
1079            "SELECT COUNT(*), COALESCE(SUM(length(block)), 0) FROM memory_spans_fts_data",
1080        )
1081        .fetch_one(&pool)
1082        .await
1083        .unwrap();
1084
1085        for _ in 0..64 {
1086            sqlx::query("UPDATE memory_claims SET claim_text = claim_text WHERE id = 1")
1087                .execute(&pool)
1088                .await
1089                .unwrap();
1090            sqlx::query("UPDATE memory_spans SET content = content WHERE id = 1")
1091                .execute(&pool)
1092                .await
1093                .unwrap();
1094        }
1095
1096        let claim_shadow_after: (i64, i64) = sqlx::query_as(
1097            "SELECT COUNT(*), COALESCE(SUM(length(block)), 0) FROM memory_claims_fts_data",
1098        )
1099        .fetch_one(&pool)
1100        .await
1101        .unwrap();
1102        let span_shadow_after: (i64, i64) = sqlx::query_as(
1103            "SELECT COUNT(*), COALESCE(SUM(length(block)), 0) FROM memory_spans_fts_data",
1104        )
1105        .fetch_one(&pool)
1106        .await
1107        .unwrap();
1108        assert_eq!(claim_shadow_after, claim_shadow_before);
1109        assert_eq!(span_shadow_after, span_shadow_before);
1110
1111        sqlx::query("UPDATE memory_claims SET claim_text = 'beta claim' WHERE id = 1")
1112            .execute(&pool)
1113            .await
1114            .unwrap();
1115        sqlx::query("UPDATE memory_spans SET content = 'beta span' WHERE id = 1")
1116            .execute(&pool)
1117            .await
1118            .unwrap();
1119        sqlx::query("INSERT INTO memory_claims_fts(memory_claims_fts) VALUES('integrity-check')")
1120            .execute(&pool)
1121            .await
1122            .unwrap();
1123        sqlx::query("INSERT INTO memory_spans_fts(memory_spans_fts) VALUES('integrity-check')")
1124            .execute(&pool)
1125            .await
1126            .unwrap();
1127        let beta_claims: i64 = sqlx::query_scalar(
1128            "SELECT COUNT(*) FROM memory_claims_fts WHERE memory_claims_fts MATCH 'beta'",
1129        )
1130        .fetch_one(&pool)
1131        .await
1132        .unwrap();
1133        let beta_spans: i64 = sqlx::query_scalar(
1134            "SELECT COUNT(*) FROM memory_spans_fts WHERE memory_spans_fts MATCH 'beta'",
1135        )
1136        .fetch_one(&pool)
1137        .await
1138        .unwrap();
1139        assert_eq!((beta_claims, beta_spans), (1, 1));
1140
1141        for trigger in ["memory_claims_au", "memory_spans_au"] {
1142            let sql: String =
1143                sqlx::query_scalar("SELECT sql FROM sqlite_master WHERE type='trigger' AND name=?")
1144                    .bind(trigger)
1145                    .fetch_one(&pool)
1146                    .await
1147                    .unwrap();
1148            assert!(sql.contains("WHEN old."), "trigger SQL: {sql}");
1149            assert!(sql.contains(" IS NOT new."), "trigger SQL: {sql}");
1150        }
1151    }
1152
1153    async fn database() -> (tempfile::NamedTempFile, SqlitePool) {
1154        let file = tempfile::NamedTempFile::new().unwrap();
1155        let pool = SqlitePoolOptions::new()
1156            .max_connections(2)
1157            .connect_with(SqliteConnectOptions::new().filename(file.path()))
1158            .await
1159            .unwrap();
1160        (file, pool)
1161    }
1162
1163    async fn count(pool: &SqlitePool, sql: &str) -> i64 {
1164        sqlx::query_scalar(sqlx::AssertSqlSafe(sql))
1165            .fetch_one(pool)
1166            .await
1167            .unwrap()
1168    }
1169
1170    /// A database from before channels, privacy, supersession history and
1171    /// the claim graph existed, as a long-running install still has.
1172    async fn old_install(pool: &SqlitePool) {
1173        for statement in [
1174            "CREATE TABLE facts (
1175                id INTEGER PRIMARY KEY AUTOINCREMENT,
1176                category TEXT NOT NULL,
1177                key TEXT NOT NULL,
1178                value TEXT NOT NULL,
1179                source TEXT NOT NULL DEFAULT '',
1180                created_at TEXT NOT NULL,
1181                updated_at TEXT NOT NULL,
1182                UNIQUE(category, key)
1183            )",
1184            "INSERT INTO facts (category, key, value, source, created_at, updated_at) VALUES
1185                ('personal', 'favorite_color', 'teal', 'user', '2025-01-01T00:00:00Z', '2025-01-01T00:00:00Z'),
1186                ('project', 'acme_stack', 'Rust', 'agent', '2025-01-02T00:00:00Z', '2025-01-02T00:00:00Z')",
1187            "CREATE TABLE people (
1188                id INTEGER PRIMARY KEY AUTOINCREMENT,
1189                name TEXT NOT NULL,
1190                created_at TEXT NOT NULL DEFAULT (datetime('now')),
1191                updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1192            )",
1193            "INSERT INTO people (name) VALUES ('Alice Rivera'), ('Jordan Lee')",
1194        ] {
1195            sqlx::query(statement).execute(pool).await.unwrap();
1196        }
1197    }
1198
1199    #[tokio::test]
1200    async fn upgrading_an_old_install_keeps_what_it_remembers() {
1201        let (_file, pool) = database().await;
1202        old_install(&pool).await;
1203
1204        migrate(&pool).await.unwrap();
1205
1206        assert_eq!(count(&pool, "SELECT COUNT(*) FROM facts").await, 2);
1207        assert_eq!(count(&pool, "SELECT COUNT(*) FROM people").await, 2);
1208        let value: String =
1209            sqlx::query_scalar("SELECT value FROM facts WHERE key = 'favorite_color'")
1210                .fetch_one(&pool)
1211                .await
1212                .unwrap();
1213        assert_eq!(value, "teal");
1214        assert_eq!(
1215            count(&pool, "SELECT COUNT(*) FROM facts WHERE privacy = 'global'").await,
1216            2,
1217            "existing facts stay visible as they were"
1218        );
1219        // The old one-row-per-key constraint is gone: a key can keep history.
1220        sqlx::query(
1221            "UPDATE facts SET superseded_at = '2026-01-01T00:00:00Z' WHERE key = 'favorite_color'",
1222        )
1223        .execute(&pool)
1224        .await
1225        .unwrap();
1226        sqlx::query(
1227            "INSERT INTO facts (category, key, value, source, created_at, updated_at)
1228             VALUES ('personal', 'favorite_color', 'navy', 'user', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')",
1229        )
1230        .execute(&pool)
1231        .await
1232        .unwrap();
1233    }
1234
1235    #[tokio::test]
1236    async fn every_start_leaves_existing_memory_alone() {
1237        let (_file, pool) = database().await;
1238        migrate(&pool).await.unwrap();
1239        sqlx::query(
1240            "INSERT INTO facts (category, key, value, source, created_at, updated_at)
1241             VALUES ('personal', 'favorite_color', 'teal', 'agent', '2025-01-01T00:00:00Z', '2025-01-01T00:00:00Z')",
1242        )
1243        .execute(&pool)
1244        .await
1245        .unwrap();
1246
1247        migrate(&pool).await.unwrap();
1248        migrate(&pool).await.unwrap();
1249
1250        let (value, source): (String, String) =
1251            sqlx::query_as("SELECT value, source FROM facts WHERE key = 'favorite_color'")
1252                .fetch_one(&pool)
1253                .await
1254                .unwrap();
1255        assert_eq!((value.as_str(), source.as_str()), ("teal", "agent"));
1256    }
1257}