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    // Reversible archival (hides from active recall while staying restorable)
341    // and optional typed expiry timestamp (auto-archived on maintenance passes).
342    aidaemon_tools::sqlite_schema::add_column_if_missing(
343        pool,
344        "ALTER TABLE facts ADD COLUMN archived_at TEXT",
345    )
346    .await?;
347    aidaemon_tools::sqlite_schema::add_column_if_missing(
348        pool,
349        "ALTER TABLE facts ADD COLUMN expires_at TEXT",
350    )
351    .await?;
352    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_facts_archived ON facts(archived_at)")
353        .execute(pool)
354        .await;
355
356    // Durable tombstones for deleted/folded facts. Retention can physically
357    // purge old superseded rows from `facts` without erasing the resurrection
358    // barrier that prevents background extractors from bringing back knowledge
359    // the owner explicitly forgot or folded away.
360    sqlx::query(
361        "CREATE TABLE IF NOT EXISTS memory_fact_tombstones (
362            id INTEGER PRIMARY KEY AUTOINCREMENT,
363            category TEXT NOT NULL,
364            canonical_key TEXT NOT NULL,
365            normalized_value TEXT NOT NULL,
366            reason TEXT NOT NULL,
367            retired_at TEXT NOT NULL
368        )",
369    )
370    .execute(pool)
371    .await?;
372    let _ = sqlx::query(
373        "CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_fact_tombstones_unique
374         ON memory_fact_tombstones(category, canonical_key, normalized_value, reason)",
375    )
376    .execute(pool)
377    .await;
378    let _ = sqlx::query(
379        "CREATE INDEX IF NOT EXISTS idx_memory_fact_tombstones_key
380         ON memory_fact_tombstones(canonical_key)",
381    )
382    .execute(pool)
383    .await;
384
385    // Migration: deduplicate people entries and add unique index on LOWER(name).
386    // Keeps the row with the lowest id for each name, merging interaction counts.
387    let _ = sqlx::query(
388        "DELETE FROM people WHERE id NOT IN (
389            SELECT MIN(id) FROM people GROUP BY LOWER(name)
390        )",
391    )
392    .execute(pool)
393    .await;
394    let _ = sqlx::query(
395        "CREATE UNIQUE INDEX IF NOT EXISTS idx_people_name_unique ON people(LOWER(name))",
396    )
397    .execute(pool)
398    .await;
399
400    // Migration: allow multiple episodes per session (for mid-session episode
401    // creation in long-running conversations). The non-unique index on session_id
402    // (idx_episodes_session) already exists for lookups.
403    let _ = sqlx::query("DROP INDEX IF EXISTS idx_episodes_session_unique")
404        .execute(pool)
405        .await;
406
407    // Canonical long-term memory. Domain tables remain authoritative during
408    // the rolling migration; these tables are durable projections with explicit
409    // provenance, validity, and replaceable search indexes.
410    sqlx::query(
411        "CREATE TABLE IF NOT EXISTS memory_spans (
412            id INTEGER PRIMARY KEY AUTOINCREMENT,
413            span_kind TEXT NOT NULL,
414            source_event_id INTEGER,
415            source_episode_id INTEGER UNIQUE,
416            session_id TEXT,
417            channel_id TEXT,
418            role TEXT,
419            content TEXT NOT NULL,
420            content_hash TEXT NOT NULL,
421            privacy TEXT NOT NULL DEFAULT 'global',
422            observed_from TEXT,
423            observed_to TEXT,
424            valid_from TEXT NOT NULL,
425            valid_to TEXT,
426            deleted_at TEXT,
427            created_at TEXT NOT NULL DEFAULT (datetime('now'))
428        )",
429    )
430    .execute(pool)
431    .await?;
432    aidaemon_tools::sqlite_schema::add_column_if_missing(
433        pool,
434        "ALTER TABLE memory_spans ADD COLUMN observed_from TEXT",
435    )
436    .await?;
437    aidaemon_tools::sqlite_schema::add_column_if_missing(
438        pool,
439        "ALTER TABLE memory_spans ADD COLUMN observed_to TEXT",
440    )
441    .await?;
442
443    sqlx::query(
444        "CREATE TABLE IF NOT EXISTS memory_claims (
445            id INTEGER PRIMARY KEY AUTOINCREMENT,
446            subject TEXT NOT NULL,
447            predicate TEXT NOT NULL,
448            object TEXT NOT NULL,
449            claim_text TEXT NOT NULL,
450            source_fact_id INTEGER UNIQUE,
451            source_span_id INTEGER,
452            source_event_id INTEGER,
453            provenance TEXT NOT NULL,
454            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
455            channel_id TEXT,
456            privacy TEXT NOT NULL DEFAULT 'global',
457            valid_from TEXT NOT NULL,
458            valid_to TEXT,
459            superseded_by_claim_id INTEGER,
460            deleted_at TEXT,
461            created_at TEXT NOT NULL DEFAULT (datetime('now')),
462            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
463            FOREIGN KEY(source_span_id) REFERENCES memory_spans(id),
464            FOREIGN KEY(superseded_by_claim_id) REFERENCES memory_claims(id)
465        )",
466    )
467    .execute(pool)
468    .await?;
469
470    sqlx::query(
471        "CREATE TABLE IF NOT EXISTS memory_entities (
472            id INTEGER PRIMARY KEY AUTOINCREMENT,
473            entity_type TEXT NOT NULL,
474            canonical_name TEXT NOT NULL,
475            display_name TEXT NOT NULL,
476            aliases_json TEXT NOT NULL DEFAULT '[]',
477            channel_id TEXT,
478            privacy TEXT NOT NULL DEFAULT 'global',
479            deleted_at TEXT,
480            created_at TEXT NOT NULL DEFAULT (datetime('now')),
481            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
482            UNIQUE(entity_type, canonical_name)
483        )",
484    )
485    .execute(pool)
486    .await?;
487    for statement in [
488        "ALTER TABLE memory_entities ADD COLUMN status TEXT NOT NULL DEFAULT 'active'",
489        "ALTER TABLE memory_entities ADD COLUMN merged_into_entity_id INTEGER",
490        "ALTER TABLE memory_entities ADD COLUMN is_owner INTEGER NOT NULL DEFAULT 0",
491    ] {
492        aidaemon_tools::sqlite_schema::add_column_if_missing(pool, statement).await?;
493    }
494
495    // Entity-aware personal memory. These tables extend the rolling canonical
496    // projection without changing or deleting the legacy facts/people tables.
497    sqlx::query(
498        "CREATE TABLE IF NOT EXISTS memory_aliases (
499            id INTEGER PRIMARY KEY AUTOINCREMENT,
500            entity_id INTEGER NOT NULL,
501            alias_type TEXT NOT NULL,
502            value TEXT NOT NULL,
503            normalized_value TEXT NOT NULL,
504            status TEXT NOT NULL DEFAULT 'active',
505            source TEXT NOT NULL,
506            provenance TEXT,
507            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
508            channel_id TEXT,
509            privacy TEXT NOT NULL DEFAULT 'private',
510            asserted_at TEXT NOT NULL,
511            confirmed_at TEXT,
512            last_confirmed_at TEXT,
513            valid_from TEXT,
514            valid_to TEXT,
515            created_at TEXT NOT NULL,
516            updated_at TEXT NOT NULL,
517            FOREIGN KEY(entity_id) REFERENCES memory_entities(id),
518            UNIQUE(entity_id, alias_type, normalized_value)
519        )",
520    )
521    .execute(pool)
522    .await?;
523
524    sqlx::query(
525        "CREATE TABLE IF NOT EXISTS memory_entity_facts (
526            id INTEGER PRIMARY KEY AUTOINCREMENT,
527            subject_entity_id INTEGER NOT NULL,
528            predicate TEXT NOT NULL,
529            value_type TEXT NOT NULL DEFAULT 'text',
530            value TEXT NOT NULL,
531            normalized_value TEXT NOT NULL,
532            display_value TEXT,
533            status TEXT NOT NULL DEFAULT 'active',
534            source TEXT NOT NULL,
535            provenance TEXT,
536            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
537            source_fact_id INTEGER,
538            channel_id TEXT,
539            privacy TEXT NOT NULL DEFAULT 'private',
540            asserted_at TEXT NOT NULL,
541            confirmed_at TEXT,
542            last_confirmed_at TEXT,
543            valid_from TEXT,
544            valid_to TEXT,
545            supersedes_fact_id INTEGER,
546            created_at TEXT NOT NULL,
547            updated_at TEXT NOT NULL,
548            FOREIGN KEY(subject_entity_id) REFERENCES memory_entities(id),
549            FOREIGN KEY(source_fact_id) REFERENCES facts(id),
550            FOREIGN KEY(supersedes_fact_id) REFERENCES memory_entity_facts(id)
551        )",
552    )
553    .execute(pool)
554    .await?;
555
556    sqlx::query(
557        "CREATE TABLE IF NOT EXISTS memory_relationships (
558            id INTEGER PRIMARY KEY AUTOINCREMENT,
559            source_entity_id INTEGER NOT NULL,
560            relationship_type TEXT NOT NULL,
561            target_entity_id INTEGER NOT NULL,
562            inverse_relationship_id INTEGER,
563            status TEXT NOT NULL DEFAULT 'active',
564            source TEXT NOT NULL,
565            provenance TEXT,
566            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
567            source_fact_id INTEGER,
568            channel_id TEXT,
569            privacy TEXT NOT NULL DEFAULT 'private',
570            asserted_at TEXT NOT NULL,
571            confirmed_at TEXT,
572            last_confirmed_at TEXT,
573            valid_from TEXT,
574            valid_to TEXT,
575            created_at TEXT NOT NULL,
576            updated_at TEXT NOT NULL,
577            FOREIGN KEY(source_entity_id) REFERENCES memory_entities(id),
578            FOREIGN KEY(target_entity_id) REFERENCES memory_entities(id),
579            FOREIGN KEY(inverse_relationship_id) REFERENCES memory_relationships(id),
580            FOREIGN KEY(source_fact_id) REFERENCES facts(id)
581        )",
582    )
583    .execute(pool)
584    .await?;
585
586    sqlx::query(
587        "CREATE TABLE IF NOT EXISTS memory_resolution_reviews (
588            id INTEGER PRIMARY KEY AUTOINCREMENT,
589            review_kind TEXT NOT NULL,
590            normalized_reference TEXT,
591            candidate_entity_ids_json TEXT NOT NULL DEFAULT '[]',
592            payload_json TEXT NOT NULL,
593            source TEXT NOT NULL,
594            source_fact_id INTEGER,
595            status TEXT NOT NULL DEFAULT 'pending',
596            created_at TEXT NOT NULL,
597            updated_at TEXT NOT NULL,
598            resolved_at TEXT,
599            UNIQUE(review_kind, normalized_reference, payload_json, status)
600        )",
601    )
602    .execute(pool)
603    .await?;
604
605    sqlx::query(
606        "CREATE TABLE IF NOT EXISTS memory_write_audit (
607            id INTEGER PRIMARY KEY AUTOINCREMENT,
608            operation TEXT NOT NULL,
609            entity_id INTEGER,
610            record_type TEXT NOT NULL,
611            record_id INTEGER,
612            prior_state_json TEXT,
613            new_state_json TEXT,
614            source TEXT NOT NULL,
615            source_fact_id INTEGER,
616            provenance TEXT,
617            created_at TEXT NOT NULL,
618            FOREIGN KEY(entity_id) REFERENCES memory_entities(id)
619        )",
620    )
621    .execute(pool)
622    .await?;
623
624    sqlx::query(
625        "CREATE TABLE IF NOT EXISTS memory_edges (
626            id INTEGER PRIMARY KEY AUTOINCREMENT,
627            source_entity_id INTEGER NOT NULL,
628            target_entity_id INTEGER NOT NULL,
629            relation TEXT NOT NULL,
630            source_claim_id INTEGER,
631            confidence REAL NOT NULL DEFAULT 1.0 CHECK(confidence >= 0.0 AND confidence <= 1.0),
632            channel_id TEXT,
633            privacy TEXT NOT NULL DEFAULT 'global',
634            valid_from TEXT NOT NULL,
635            valid_to TEXT,
636            deleted_at TEXT,
637            created_at TEXT NOT NULL DEFAULT (datetime('now')),
638            FOREIGN KEY(source_entity_id) REFERENCES memory_entities(id),
639            FOREIGN KEY(target_entity_id) REFERENCES memory_entities(id),
640            FOREIGN KEY(source_claim_id) REFERENCES memory_claims(id),
641            UNIQUE(source_entity_id, target_entity_id, relation, source_claim_id)
642        )",
643    )
644    .execute(pool)
645    .await?;
646
647    sqlx::query(
648        "CREATE TABLE IF NOT EXISTS memory_embeddings (
649            id INTEGER PRIMARY KEY AUTOINCREMENT,
650            owner_type TEXT NOT NULL,
651            owner_id TEXT NOT NULL,
652            embedding_purpose TEXT NOT NULL,
653            embedding_model TEXT NOT NULL,
654            embedding_dim INTEGER NOT NULL CHECK(embedding_dim > 0),
655            content_hash TEXT NOT NULL,
656            embedding BLOB NOT NULL,
657            stale_at TEXT,
658            created_at TEXT NOT NULL,
659            updated_at TEXT NOT NULL,
660            UNIQUE(owner_type, owner_id, embedding_purpose, embedding_model, content_hash)
661        )",
662    )
663    .execute(pool)
664    .await?;
665
666    // A change counter for `memory_embeddings`, so the in-memory vector
667    // cache in `SqliteEmbeddingIndex` knows when to reload. Triggers keep it
668    // exact whichever code (or process) writes the table.
669    for statement in [
670        "CREATE TABLE IF NOT EXISTS memory_embedding_generation (
671            id INTEGER PRIMARY KEY CHECK(id = 1),
672            generation INTEGER NOT NULL
673        )",
674        "INSERT OR IGNORE INTO memory_embedding_generation (id, generation) VALUES (1, 0)",
675        "CREATE TRIGGER IF NOT EXISTS memory_embeddings_generation_insert
676         AFTER INSERT ON memory_embeddings BEGIN
677            UPDATE memory_embedding_generation SET generation = generation + 1 WHERE id = 1;
678         END",
679        "CREATE TRIGGER IF NOT EXISTS memory_embeddings_generation_update
680         AFTER UPDATE ON memory_embeddings BEGIN
681            UPDATE memory_embedding_generation SET generation = generation + 1 WHERE id = 1;
682         END",
683        "CREATE TRIGGER IF NOT EXISTS memory_embeddings_generation_delete
684         AFTER DELETE ON memory_embeddings BEGIN
685            UPDATE memory_embedding_generation SET generation = generation + 1 WHERE id = 1;
686         END",
687    ] {
688        sqlx::query(statement).execute(pool).await?;
689    }
690
691    for statement in [
692        "CREATE INDEX IF NOT EXISTS idx_memory_claims_active ON memory_claims(privacy, channel_id, valid_to, deleted_at)",
693        "CREATE INDEX IF NOT EXISTS idx_memory_spans_active ON memory_spans(privacy, channel_id, valid_to, deleted_at)",
694        "CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_spans_source_event ON memory_spans(source_event_id) WHERE source_event_id IS NOT NULL",
695        "CREATE INDEX IF NOT EXISTS idx_memory_edges_source ON memory_edges(source_entity_id, valid_to, deleted_at)",
696        "CREATE INDEX IF NOT EXISTS idx_memory_edges_target ON memory_edges(target_entity_id, valid_to, deleted_at)",
697        "CREATE INDEX IF NOT EXISTS idx_memory_embeddings_lookup ON memory_embeddings(embedding_model, embedding_purpose, owner_type, stale_at)",
698        "CREATE INDEX IF NOT EXISTS idx_memory_embeddings_owner ON memory_embeddings(owner_type, owner_id, stale_at)",
699        "CREATE INDEX IF NOT EXISTS idx_memory_entities_status ON memory_entities(entity_type, status, canonical_name)",
700        "CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_entities_one_owner ON memory_entities(is_owner) WHERE is_owner = 1 AND status = 'active'",
701        "CREATE INDEX IF NOT EXISTS idx_memory_aliases_lookup ON memory_aliases(normalized_value, alias_type, status)",
702        "CREATE INDEX IF NOT EXISTS idx_memory_aliases_entity ON memory_aliases(entity_id, status)",
703        "CREATE INDEX IF NOT EXISTS idx_memory_entity_facts_subject ON memory_entity_facts(subject_entity_id, predicate, status)",
704        "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",
705        "CREATE INDEX IF NOT EXISTS idx_memory_relationships_source ON memory_relationships(source_entity_id, relationship_type, status)",
706        "CREATE INDEX IF NOT EXISTS idx_memory_relationships_target ON memory_relationships(target_entity_id, relationship_type, status)",
707        "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",
708        "CREATE INDEX IF NOT EXISTS idx_memory_reviews_status ON memory_resolution_reviews(status, review_kind)",
709        "CREATE INDEX IF NOT EXISTS idx_memory_audit_entity ON memory_write_audit(entity_id, created_at)",
710    ] {
711        sqlx::query(statement).execute(pool).await?;
712    }
713
714    repair_blank_validity_bounds(pool).await?;
715    convert_legacy_person_dates(pool).await?;
716
717    // FTS5 is present in standard SQLite and bundled SQLCipher builds. Keep the
718    // daemon usable on custom SQLite builds without it; semantic and lexical
719    // fallback retrieval remain available.
720    if let Err(error) = create_memory_fts(pool).await {
721        tracing::warn!(%error, "SQLite FTS5 unavailable; memory full-text index disabled");
722    }
723
724    Ok(())
725}
726
727/// Canonical rows written with a blank validity bound (`""` from extraction,
728/// meaning "no bound") were invisible to every `valid_to IS NULL` read: the
729/// prompt never showed them and the next identical write inserted a
730/// duplicate. Ends the later duplicate of each such row, then stores the
731/// remaining blank bounds as NULL. Idempotent: a clean database matches
732/// nothing.
733async fn repair_blank_validity_bounds(pool: &SqlitePool) -> anyhow::Result<()> {
734    // A twin that already has a NULL bound wins whatever its id; between two
735    // blank twins the older one does.
736    let twin = |alias: &str, row: &str| {
737        format!(
738            "({alias}.valid_to IS NULL OR (TRIM({alias}.valid_to) = '' AND {alias}.id < {row}.id))"
739        )
740    };
741    let statements = [
742        format!(
743            "UPDATE memory_entity_facts AS f SET status = 'superseded', valid_to = f.updated_at
744             WHERE f.status = 'active' AND TRIM(f.valid_to) = ''
745               AND EXISTS (SELECT 1 FROM memory_entity_facts o
746                           WHERE o.subject_entity_id = f.subject_entity_id
747                             AND o.predicate = f.predicate
748                             AND o.normalized_value = f.normalized_value
749                             AND o.status = 'active' AND o.id <> f.id AND {})",
750            twin("o", "f")
751        ),
752        format!(
753            "UPDATE memory_relationships AS r SET status = 'superseded', valid_to = r.updated_at
754             WHERE r.status = 'active' AND TRIM(r.valid_to) = ''
755               AND EXISTS (SELECT 1 FROM memory_relationships o
756                           WHERE o.source_entity_id = r.source_entity_id
757                             AND o.relationship_type = r.relationship_type
758                             AND o.target_entity_id = r.target_entity_id
759                             AND o.status = 'active' AND o.id <> r.id AND {})",
760            twin("o", "r")
761        ),
762    ];
763    for statement in &statements {
764        sqlx::query(sqlx::AssertSqlSafe(statement.as_str()))
765            .execute(pool)
766            .await?;
767    }
768    for table in [
769        "memory_entity_facts",
770        "memory_relationships",
771        "memory_aliases",
772    ] {
773        for column in ["valid_from", "valid_to"] {
774            sqlx::query(sqlx::AssertSqlSafe(format!(
775                "UPDATE {table} SET {column} = NULL WHERE TRIM({column}) = ''"
776            )))
777            .execute(pool)
778            .await?;
779        }
780    }
781    Ok(())
782}
783
784/// Birthdays and important dates stored before dates were ISO only
785/// ("March 15", "03-15", "3/15") are read by nothing now: rewrites each one
786/// the old reader understood as ISO, read the way it read them
787/// ([`crate::dates::legacy_date_to_iso`]). A value it could not read stays
788/// as written. Idempotent: an ISO value is never touched, so a second run
789/// changes nothing.
790async fn convert_legacy_person_dates(pool: &SqlitePool) -> anyhow::Result<()> {
791    let placeholders = vec!["?"; crate::dates::DATE_FACT_CATEGORIES.len()].join(", ");
792    let select = format!(
793        "SELECT id, value FROM person_facts WHERE LOWER(TRIM(category)) IN ({placeholders})"
794    );
795    let mut query = sqlx::query_as::<_, (i64, String)>(sqlx::AssertSqlSafe(select));
796    for category in crate::dates::DATE_FACT_CATEGORIES {
797        query = query.bind(*category);
798    }
799    let rows = query.fetch_all(pool).await?;
800    let mut converted = 0usize;
801    for (id, value) in rows {
802        let Some(iso) = crate::dates::legacy_date_to_iso(&value) else {
803            continue;
804        };
805        sqlx::query("UPDATE person_facts SET value = ? WHERE id = ? AND value = ?")
806            .bind(&iso)
807            .bind(id)
808            .bind(&value)
809            .execute(pool)
810            .await?;
811        converted += 1;
812    }
813    if converted > 0 {
814        tracing::info!(converted, "Rewrote legacy person dates as ISO dates");
815    }
816    Ok(())
817}
818
819/// Migrate facts schema to allow supersession history.
820///
821/// Legacy databases used a table-level `UNIQUE(category, key)` constraint which prevents
822/// inserting a new version after marking the old one superseded. We rebuild the table once
823/// to remove that constraint, then enforce at most one *active* fact per key via a partial
824/// unique index: `UNIQUE(category, key) WHERE superseded_at IS NULL`.
825async fn migrate_facts_history_schema(pool: &SqlitePool) -> anyhow::Result<()> {
826    let table_row = sqlx::query(
827        "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'facts' LIMIT 1",
828    )
829    .fetch_optional(pool)
830    .await?;
831
832    let Some(row) = table_row else {
833        // No facts table yet.
834        return Ok(());
835    };
836
837    let create_sql: Option<String> = row.try_get("sql").unwrap_or(None);
838    let create_sql = create_sql.unwrap_or_default();
839    let create_l = create_sql.to_lowercase();
840    let has_legacy_unique = create_l.contains("unique(category, key)")
841        || create_l.contains("unique(category,key)")
842        || create_l.contains("unique (category, key)")
843        || create_l.contains("unique (category,key)");
844
845    if has_legacy_unique {
846        let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
847
848        // Defensive: clean up a prior failed attempt.
849        let _ = sqlx::query("DROP TABLE IF EXISTS facts_new")
850            .execute(&mut *tx)
851            .await;
852
853        sqlx::query(
854            "CREATE TABLE facts_new (
855                id INTEGER PRIMARY KEY AUTOINCREMENT,
856                category TEXT NOT NULL,
857                key TEXT NOT NULL,
858                value TEXT NOT NULL,
859                source TEXT NOT NULL DEFAULT '',
860                created_at TEXT NOT NULL,
861                updated_at TEXT NOT NULL,
862                superseded_at TEXT,
863                recall_count INTEGER DEFAULT 0,
864                last_recalled_at TEXT,
865                channel_id TEXT,
866                privacy TEXT DEFAULT 'global',
867                embedding BLOB
868            )",
869        )
870        .execute(&mut *tx)
871        .await?;
872
873        // Copy all existing columns. These columns should exist after migrations, but
874        // keeping this in a single statement makes the rebuild fast.
875        sqlx::query(
876            "INSERT INTO facts_new
877                (id, category, key, value, source, created_at, updated_at, superseded_at,
878                 recall_count, last_recalled_at, channel_id, privacy, embedding)
879             SELECT
880                id, category, key, value, source, created_at, updated_at, superseded_at,
881                recall_count, last_recalled_at, channel_id, privacy, embedding
882             FROM facts",
883        )
884        .execute(&mut *tx)
885        .await?;
886
887        sqlx::query("DROP TABLE facts").execute(&mut *tx).await?;
888        sqlx::query("ALTER TABLE facts_new RENAME TO facts")
889            .execute(&mut *tx)
890            .await?;
891
892        tx.commit().await?;
893    }
894
895    // (Re)create indexes. If the table was rebuilt, previous indexes were dropped.
896    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_facts_channel ON facts(channel_id)")
897        .execute(pool)
898        .await;
899    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_facts_privacy ON facts(privacy)")
900        .execute(pool)
901        .await;
902    if let Err(e) = sqlx::query(
903        "CREATE UNIQUE INDEX IF NOT EXISTS idx_facts_active_unique
904         ON facts(category, key) WHERE superseded_at IS NULL",
905    )
906    .execute(pool)
907    .await
908    {
909        tracing::warn!(
910            "Failed to create idx_facts_active_unique (active fact dedupe not enforced): {}",
911            e
912        );
913    }
914
915    Ok(())
916}
917
918async fn create_memory_fts(pool: &SqlitePool) -> anyhow::Result<()> {
919    let claims_fts_existed = sqlx::query_scalar::<_, i64>(
920        "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memory_claims_fts'",
921    )
922    .fetch_optional(pool)
923    .await?
924    .is_some();
925    let spans_fts_existed = sqlx::query_scalar::<_, i64>(
926        "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memory_spans_fts'",
927    )
928    .fetch_optional(pool)
929    .await?
930    .is_some();
931    sqlx::query(
932        "CREATE VIRTUAL TABLE IF NOT EXISTS memory_claims_fts USING fts5(
933            claim_text, content='memory_claims', content_rowid='id', tokenize='unicode61'
934        )",
935    )
936    .execute(pool)
937    .await?;
938    sqlx::query(
939        "CREATE VIRTUAL TABLE IF NOT EXISTS memory_spans_fts USING fts5(
940            content, content='memory_spans', content_rowid='id', tokenize='unicode61'
941        )",
942    )
943    .execute(pool)
944    .await?;
945    // FTS5 secure-delete corrupts external-content indexes under the
946    // multi-connection SQLCipher 3.51.2 workload used by the daemon (the same
947    // update sequence is healthy through a single connection). Keep the FTS
948    // projection in compatibility mode. The database remains encrypted and
949    // `PRAGMA secure_delete=ON` still scrubs ordinary SQLite pages; deleted FTS
950    // terms are made unqueryable by the standard tombstone/merge mechanism.
951    for table in ["memory_claims_fts", "memory_spans_fts"] {
952        sqlx::query(sqlx::AssertSqlSafe(format!(
953            "INSERT INTO {table}({table}, rank) VALUES('secure-delete', 0)"
954        )))
955        .execute(pool)
956        .await?;
957    }
958
959    // `UPDATE OF column` fires even when an UPSERT assigns the existing value.
960    // Repeated delete/reinsert churn of an unchanged row can corrupt FTS5
961    // secure-delete segments on SQLCipher's SQLite build. Replace legacy
962    // update triggers and suppress true no-op text updates.
963    for trigger in ["memory_claims_au", "memory_spans_au"] {
964        sqlx::query(sqlx::AssertSqlSafe(format!(
965            "DROP TRIGGER IF EXISTS {trigger}"
966        )))
967        .execute(pool)
968        .await?;
969    }
970
971    for statement in [
972        "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",
973        "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",
974        "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",
975        "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",
976        "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",
977        "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",
978    ] {
979        sqlx::query(statement).execute(pool).await?;
980    }
981
982    if !claims_fts_existed {
983        sqlx::query("INSERT INTO memory_claims_fts(memory_claims_fts) VALUES ('rebuild')")
984            .execute(pool)
985            .await?;
986    }
987    if !spans_fts_existed {
988        sqlx::query("INSERT INTO memory_spans_fts(memory_spans_fts) VALUES ('rebuild')")
989            .execute(pool)
990            .await?;
991    }
992    Ok(())
993}
994
995/// Recreate the memory search indexes from their authoritative source tables.
996///
997/// These FTS tables are replaceable projections. Rebuilding both together keeps
998/// their trigger and secure-delete configuration consistent after either index
999/// is reported corrupt during startup integrity verification.
1000pub async fn rebuild_memory_fts_projections(pool: &SqlitePool) -> anyhow::Result<()> {
1001    sqlx::query("DROP TABLE IF EXISTS memory_claims_fts")
1002        .execute(pool)
1003        .await?;
1004    sqlx::query("DROP TABLE IF EXISTS memory_spans_fts")
1005        .execute(pool)
1006        .await?;
1007    create_memory_fts(pool).await
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use super::*;
1013    use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
1014
1015    #[tokio::test]
1016    async fn legacy_person_dates_become_iso_once_and_unreadable_ones_stay() {
1017        let pool = SqlitePoolOptions::new()
1018            .max_connections(1)
1019            .connect("sqlite::memory:")
1020            .await
1021            .unwrap();
1022        sqlx::query(
1023            "CREATE TABLE person_facts (
1024                id INTEGER PRIMARY KEY,
1025                person_id INTEGER NOT NULL,
1026                category TEXT NOT NULL,
1027                key TEXT NOT NULL,
1028                value TEXT NOT NULL
1029             )",
1030        )
1031        .execute(&pool)
1032        .await
1033        .unwrap();
1034        for (id, category, value) in [
1035            (1, "birthday", "March 15"),
1036            (2, "important_date", "3/15"),
1037            (3, "birthday", "--07-04"),
1038            (4, "birthday", "15 March"),
1039            (5, "preference", "03-15"),
1040            (6, "Birthday", "2019-4-2"),
1041        ] {
1042            sqlx::query(
1043                "INSERT INTO person_facts (id, person_id, category, key, value) VALUES (?, 1, ?, 'synthetic', ?)",
1044            )
1045            .bind(id)
1046            .bind(category)
1047            .bind(value)
1048            .execute(&pool)
1049            .await
1050            .unwrap();
1051        }
1052        convert_legacy_person_dates(&pool).await.unwrap();
1053        convert_legacy_person_dates(&pool).await.unwrap();
1054        let values: Vec<String> = sqlx::query_scalar("SELECT value FROM person_facts ORDER BY id")
1055            .fetch_all(&pool)
1056            .await
1057            .unwrap();
1058        assert_eq!(
1059            values,
1060            [
1061                "--03-15",
1062                "--03-15",
1063                "--07-04",
1064                // The old reader could not read it: left as written.
1065                "15 March",
1066                // Not a date category.
1067                "03-15",
1068                "2019-04-02",
1069            ]
1070        );
1071    }
1072
1073    #[tokio::test]
1074    async fn no_op_content_updates_do_not_churn_or_corrupt_secure_delete_indexes() {
1075        let database = tempfile::NamedTempFile::new().unwrap();
1076        let options = SqliteConnectOptions::new()
1077            .filename(database.path())
1078            .create_if_missing(true);
1079        let pool = SqlitePoolOptions::new()
1080            .max_connections(2)
1081            .connect_with(options)
1082            .await
1083            .unwrap();
1084        sqlx::query(
1085            "CREATE TABLE memory_claims (
1086                id INTEGER PRIMARY KEY,
1087                claim_text TEXT NOT NULL
1088             );
1089             CREATE TABLE memory_spans (
1090                id INTEGER PRIMARY KEY,
1091                content TEXT NOT NULL
1092             )",
1093        )
1094        .execute(&pool)
1095        .await
1096        .unwrap();
1097
1098        create_memory_fts(&pool).await.unwrap();
1099        for table in ["memory_claims_fts_config", "memory_spans_fts_config"] {
1100            let secure_delete: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
1101                "SELECT v FROM {table} WHERE k = 'secure-delete'"
1102            )))
1103            .fetch_one(&pool)
1104            .await
1105            .unwrap();
1106            assert_eq!(secure_delete, 0);
1107        }
1108        sqlx::query("INSERT INTO memory_claims(id, claim_text) VALUES (1, 'alpha claim')")
1109            .execute(&pool)
1110            .await
1111            .unwrap();
1112        sqlx::query("INSERT INTO memory_spans(id, content) VALUES (1, 'alpha span')")
1113            .execute(&pool)
1114            .await
1115            .unwrap();
1116        let claim_shadow_before: (i64, i64) = sqlx::query_as(
1117            "SELECT COUNT(*), COALESCE(SUM(length(block)), 0) FROM memory_claims_fts_data",
1118        )
1119        .fetch_one(&pool)
1120        .await
1121        .unwrap();
1122        let span_shadow_before: (i64, i64) = sqlx::query_as(
1123            "SELECT COUNT(*), COALESCE(SUM(length(block)), 0) FROM memory_spans_fts_data",
1124        )
1125        .fetch_one(&pool)
1126        .await
1127        .unwrap();
1128
1129        for _ in 0..64 {
1130            sqlx::query("UPDATE memory_claims SET claim_text = claim_text WHERE id = 1")
1131                .execute(&pool)
1132                .await
1133                .unwrap();
1134            sqlx::query("UPDATE memory_spans SET content = content WHERE id = 1")
1135                .execute(&pool)
1136                .await
1137                .unwrap();
1138        }
1139
1140        let claim_shadow_after: (i64, i64) = sqlx::query_as(
1141            "SELECT COUNT(*), COALESCE(SUM(length(block)), 0) FROM memory_claims_fts_data",
1142        )
1143        .fetch_one(&pool)
1144        .await
1145        .unwrap();
1146        let span_shadow_after: (i64, i64) = sqlx::query_as(
1147            "SELECT COUNT(*), COALESCE(SUM(length(block)), 0) FROM memory_spans_fts_data",
1148        )
1149        .fetch_one(&pool)
1150        .await
1151        .unwrap();
1152        assert_eq!(claim_shadow_after, claim_shadow_before);
1153        assert_eq!(span_shadow_after, span_shadow_before);
1154
1155        sqlx::query("UPDATE memory_claims SET claim_text = 'beta claim' WHERE id = 1")
1156            .execute(&pool)
1157            .await
1158            .unwrap();
1159        sqlx::query("UPDATE memory_spans SET content = 'beta span' WHERE id = 1")
1160            .execute(&pool)
1161            .await
1162            .unwrap();
1163        sqlx::query("INSERT INTO memory_claims_fts(memory_claims_fts) VALUES('integrity-check')")
1164            .execute(&pool)
1165            .await
1166            .unwrap();
1167        sqlx::query("INSERT INTO memory_spans_fts(memory_spans_fts) VALUES('integrity-check')")
1168            .execute(&pool)
1169            .await
1170            .unwrap();
1171        let beta_claims: i64 = sqlx::query_scalar(
1172            "SELECT COUNT(*) FROM memory_claims_fts WHERE memory_claims_fts MATCH 'beta'",
1173        )
1174        .fetch_one(&pool)
1175        .await
1176        .unwrap();
1177        let beta_spans: i64 = sqlx::query_scalar(
1178            "SELECT COUNT(*) FROM memory_spans_fts WHERE memory_spans_fts MATCH 'beta'",
1179        )
1180        .fetch_one(&pool)
1181        .await
1182        .unwrap();
1183        assert_eq!((beta_claims, beta_spans), (1, 1));
1184
1185        for trigger in ["memory_claims_au", "memory_spans_au"] {
1186            let sql: String =
1187                sqlx::query_scalar("SELECT sql FROM sqlite_master WHERE type='trigger' AND name=?")
1188                    .bind(trigger)
1189                    .fetch_one(&pool)
1190                    .await
1191                    .unwrap();
1192            assert!(sql.contains("WHEN old."), "trigger SQL: {sql}");
1193            assert!(sql.contains(" IS NOT new."), "trigger SQL: {sql}");
1194        }
1195    }
1196
1197    async fn database() -> (tempfile::NamedTempFile, SqlitePool) {
1198        let file = tempfile::NamedTempFile::new().unwrap();
1199        let pool = SqlitePoolOptions::new()
1200            .max_connections(2)
1201            .connect_with(SqliteConnectOptions::new().filename(file.path()))
1202            .await
1203            .unwrap();
1204        (file, pool)
1205    }
1206
1207    async fn count(pool: &SqlitePool, sql: &str) -> i64 {
1208        sqlx::query_scalar(sqlx::AssertSqlSafe(sql))
1209            .fetch_one(pool)
1210            .await
1211            .unwrap()
1212    }
1213
1214    /// A database from before channels, privacy, supersession history and
1215    /// the claim graph existed, as a long-running install still has.
1216    async fn old_install(pool: &SqlitePool) {
1217        for statement in [
1218            "CREATE TABLE facts (
1219                id INTEGER PRIMARY KEY AUTOINCREMENT,
1220                category TEXT NOT NULL,
1221                key TEXT NOT NULL,
1222                value TEXT NOT NULL,
1223                source TEXT NOT NULL DEFAULT '',
1224                created_at TEXT NOT NULL,
1225                updated_at TEXT NOT NULL,
1226                UNIQUE(category, key)
1227            )",
1228            "INSERT INTO facts (category, key, value, source, created_at, updated_at) VALUES
1229                ('personal', 'favorite_color', 'teal', 'user', '2025-01-01T00:00:00Z', '2025-01-01T00:00:00Z'),
1230                ('project', 'acme_stack', 'Rust', 'agent', '2025-01-02T00:00:00Z', '2025-01-02T00:00:00Z')",
1231            "CREATE TABLE people (
1232                id INTEGER PRIMARY KEY AUTOINCREMENT,
1233                name TEXT NOT NULL,
1234                created_at TEXT NOT NULL DEFAULT (datetime('now')),
1235                updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1236            )",
1237            "INSERT INTO people (name) VALUES ('Alice Rivera'), ('Jordan Lee')",
1238        ] {
1239            sqlx::query(statement).execute(pool).await.unwrap();
1240        }
1241    }
1242
1243    #[tokio::test]
1244    async fn upgrading_an_old_install_keeps_what_it_remembers() {
1245        let (_file, pool) = database().await;
1246        old_install(&pool).await;
1247
1248        migrate(&pool).await.unwrap();
1249
1250        assert_eq!(count(&pool, "SELECT COUNT(*) FROM facts").await, 2);
1251        assert_eq!(count(&pool, "SELECT COUNT(*) FROM people").await, 2);
1252        let value: String =
1253            sqlx::query_scalar("SELECT value FROM facts WHERE key = 'favorite_color'")
1254                .fetch_one(&pool)
1255                .await
1256                .unwrap();
1257        assert_eq!(value, "teal");
1258        assert_eq!(
1259            count(&pool, "SELECT COUNT(*) FROM facts WHERE privacy = 'global'").await,
1260            2,
1261            "existing facts stay visible as they were"
1262        );
1263        // The old one-row-per-key constraint is gone: a key can keep history.
1264        sqlx::query(
1265            "UPDATE facts SET superseded_at = '2026-01-01T00:00:00Z' WHERE key = 'favorite_color'",
1266        )
1267        .execute(&pool)
1268        .await
1269        .unwrap();
1270        sqlx::query(
1271            "INSERT INTO facts (category, key, value, source, created_at, updated_at)
1272             VALUES ('personal', 'favorite_color', 'navy', 'user', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')",
1273        )
1274        .execute(&pool)
1275        .await
1276        .unwrap();
1277    }
1278
1279    #[tokio::test]
1280    async fn every_start_leaves_existing_memory_alone() {
1281        let (_file, pool) = database().await;
1282        migrate(&pool).await.unwrap();
1283        sqlx::query(
1284            "INSERT INTO facts (category, key, value, source, created_at, updated_at)
1285             VALUES ('personal', 'favorite_color', 'teal', 'agent', '2025-01-01T00:00:00Z', '2025-01-01T00:00:00Z')",
1286        )
1287        .execute(&pool)
1288        .await
1289        .unwrap();
1290
1291        migrate(&pool).await.unwrap();
1292        migrate(&pool).await.unwrap();
1293
1294        let (value, source): (String, String) =
1295            sqlx::query_as("SELECT value, source FROM facts WHERE key = 'favorite_color'")
1296                .fetch_one(&pool)
1297                .await
1298                .unwrap();
1299        assert_eq!((value.as_str(), source.as_str()), ("teal", "agent"));
1300    }
1301}