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