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