Skip to main content

vector_core/db/
schema.rs

1//! Database schema and migrations.
2
3pub const SQL_SCHEMA: &str = r#"
4-- Profiles table (plaintext - public data)
5CREATE TABLE IF NOT EXISTS profiles (
6    id INTEGER PRIMARY KEY AUTOINCREMENT,
7    npub TEXT UNIQUE NOT NULL,
8    name TEXT NOT NULL DEFAULT '',
9    display_name TEXT NOT NULL DEFAULT '',
10    nickname TEXT NOT NULL DEFAULT '',
11    lud06 TEXT NOT NULL DEFAULT '',
12    lud16 TEXT NOT NULL DEFAULT '',
13    banner TEXT NOT NULL DEFAULT '',
14    avatar TEXT NOT NULL DEFAULT '',
15    about TEXT NOT NULL DEFAULT '',
16    website TEXT NOT NULL DEFAULT '',
17    nip05 TEXT NOT NULL DEFAULT '',
18    status_content TEXT NOT NULL DEFAULT '',
19    status_url TEXT NOT NULL DEFAULT '',
20    muted INTEGER NOT NULL DEFAULT 0,
21    bot INTEGER NOT NULL DEFAULT 0,
22    avatar_cached TEXT NOT NULL DEFAULT '',
23    banner_cached TEXT NOT NULL DEFAULT ''
24);
25CREATE INDEX IF NOT EXISTS idx_profiles_npub ON profiles(npub);
26CREATE INDEX IF NOT EXISTS idx_profiles_name ON profiles(name);
27
28-- Chats table (plaintext - metadata)
29CREATE TABLE IF NOT EXISTS chats (
30    id INTEGER PRIMARY KEY AUTOINCREMENT,
31    chat_identifier TEXT UNIQUE NOT NULL,
32    chat_type INTEGER NOT NULL,
33    participants TEXT NOT NULL,
34    last_read TEXT NOT NULL DEFAULT '',
35    created_at INTEGER NOT NULL,
36    metadata TEXT NOT NULL DEFAULT '{}',
37    muted INTEGER NOT NULL DEFAULT 0
38);
39CREATE INDEX IF NOT EXISTS idx_chats_identifier ON chats(chat_identifier);
40CREATE INDEX IF NOT EXISTS idx_chats_created ON chats(created_at DESC);
41
42
43-- Settings table (key-value pairs)
44CREATE TABLE IF NOT EXISTS settings (
45    key TEXT PRIMARY KEY,
46    value TEXT NOT NULL
47);
48
49-- Events table: flat, protocol-aligned storage for all Nostr events
50CREATE TABLE IF NOT EXISTS events (
51    id TEXT PRIMARY KEY,
52    kind INTEGER NOT NULL,
53    chat_id INTEGER NOT NULL,
54    user_id INTEGER,
55    content TEXT NOT NULL,
56    tags TEXT NOT NULL DEFAULT '[]',
57    reference_id TEXT,
58    created_at INTEGER NOT NULL,
59    received_at INTEGER NOT NULL,
60    mine INTEGER NOT NULL DEFAULT 0,
61    pending INTEGER NOT NULL DEFAULT 0,
62    failed INTEGER NOT NULL DEFAULT 0,
63    wrapper_event_id TEXT,
64    npub TEXT,
65    preview_metadata TEXT,
66    FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE,
67    FOREIGN KEY (user_id) REFERENCES profiles(id) ON DELETE SET NULL
68);
69-- Pages a chat newest-first with no sort step, rejecting other kinds without reading the row.
70CREATE INDEX IF NOT EXISTS idx_events_chat_page ON events(chat_id, created_at DESC, received_at DESC, kind);
71CREATE INDEX IF NOT EXISTS idx_events_kind ON events(kind);
72-- Covers the community member fold (authors + newest activity per channel) without touching rows.
73CREATE INDEX IF NOT EXISTS idx_events_chat_kind_npub ON events(chat_id, kind, npub, created_at);
74CREATE INDEX IF NOT EXISTS idx_events_reference ON events(reference_id) WHERE reference_id IS NOT NULL;
75CREATE INDEX IF NOT EXISTS idx_events_wrapper ON events(wrapper_event_id) WHERE wrapper_event_id IS NOT NULL;
76
77-- PIVX Promos table
78CREATE TABLE IF NOT EXISTS pivx_promos (
79    id INTEGER PRIMARY KEY AUTOINCREMENT,
80    gift_code TEXT NOT NULL UNIQUE,
81    address TEXT NOT NULL,
82    privkey_encrypted TEXT NOT NULL,
83    created_at INTEGER NOT NULL,
84    claimed_at INTEGER,
85    amount_piv REAL,
86    status TEXT NOT NULL DEFAULT 'active'
87);
88CREATE INDEX IF NOT EXISTS idx_pivx_promos_code ON pivx_promos(gift_code);
89CREATE INDEX IF NOT EXISTS idx_pivx_promos_address ON pivx_promos(address);
90CREATE INDEX IF NOT EXISTS idx_pivx_promos_status ON pivx_promos(status);
91
92-- Mini Apps history table
93CREATE TABLE IF NOT EXISTS miniapps_history (
94    id INTEGER PRIMARY KEY AUTOINCREMENT,
95    name TEXT NOT NULL UNIQUE,
96    src_url TEXT NOT NULL,
97    attachment_ref TEXT,
98    open_count INTEGER DEFAULT 1,
99    last_opened_at INTEGER NOT NULL,
100    is_favorite INTEGER NOT NULL DEFAULT 0,
101    categories TEXT NOT NULL DEFAULT '',
102    marketplace_id TEXT DEFAULT NULL,
103    installed_version TEXT DEFAULT NULL
104);
105
106-- Mini App permissions table
107CREATE TABLE IF NOT EXISTS miniapp_permissions (
108    id INTEGER PRIMARY KEY AUTOINCREMENT,
109    file_hash TEXT NOT NULL,
110    permission TEXT NOT NULL,
111    granted INTEGER NOT NULL DEFAULT 0,
112    granted_at INTEGER,
113    UNIQUE(file_hash, permission)
114);
115CREATE INDEX IF NOT EXISTS idx_miniapp_permissions_hash ON miniapp_permissions(file_hash);
116
117-- Processed wrappers table (NIP-59 gift wrap dedup + NIP-77 negentropy)
118-- Universal outer-event ledger across transports. The `transport` discriminator
119-- (0 = nip17 gift-wrap, 1 = concord channel envelope, …) is added by migration 42 so the
120-- dedup is shared but NIP-77 negentropy only fingerprints the nip17 (0) subset.
121CREATE TABLE IF NOT EXISTS processed_wrappers (
122    wrapper_id BLOB PRIMARY KEY,
123    wrapper_created_at INTEGER NOT NULL DEFAULT 0
124);
125
126-- The nip17_wrap_keys vault is introduced by migration 21. The legacy MLS
127-- tables (mls_wrap_keys / mls_pending_events from migrations 22/23) are dropped
128-- by migration 41, so on a fresh DB they're created in order and then removed.
129
130-- Schema migrations tracking table
131CREATE TABLE IF NOT EXISTS schema_migrations (
132    id INTEGER PRIMARY KEY,
133    applied_at INTEGER NOT NULL
134);
135"#;
136
137/// Highest migration id this build knows how to apply.
138///
139/// **Bump this whenever you add a migration below.** A DB carrying anything
140/// above it was written by a newer Vector, so its schema holds changes this
141/// build cannot see and opening it corrupts data.
142///
143/// Leaving it behind is the one way the guard misfires: the new migration
144/// applies on first run, then this build reads its own database as newer and
145/// refuses to open it. The `debug_assert` in `run_atomic_migration` and
146/// `highest_migration_id_matches_the_runner` both catch that before release.
147pub const HIGHEST_MIGRATION_ID: u32 = 127;
148
149/// Highest migration id recorded in this DB; 0 for a fresh or pre-tracking one.
150///
151/// Nothing else reads the high-water mark: `schema_migrations` is a *set* of
152/// applied ids and every migration probes its own id, which is exactly why an
153/// older build slides past newer schema without noticing it exists.
154pub fn applied_migration_high_water(conn: &rusqlite::Connection) -> u32 {
155    conn.query_row("SELECT MAX(id) FROM schema_migrations", [], |row| {
156        row.get::<_, Option<u32>>(0)
157    })
158    .ok()
159    .flatten()
160    .unwrap_or(0)
161}
162
163/// Check if a specific migration has already been applied
164pub fn migration_applied(conn: &rusqlite::Connection, migration_id: u32) -> bool {
165    conn.query_row(
166        "SELECT 1 FROM schema_migrations WHERE id = ?1",
167        rusqlite::params![migration_id],
168        |_| Ok(())
169    ).is_ok()
170}
171
172/// Mark a migration as applied (within a transaction)
173pub fn mark_migration_applied(tx: &rusqlite::Transaction, migration_id: u32) -> Result<(), String> {
174    let now = crate::clock::now_secs() as i64;
175
176    tx.execute(
177        "INSERT INTO schema_migrations (id, applied_at) VALUES (?1, ?2)",
178        rusqlite::params![migration_id, now],
179    ).map_err(|e| format!("[DB] Migration {}: Failed to record: {}", migration_id, e))?;
180
181    Ok(())
182}
183
184/// Run a single migration atomically within a transaction.
185///
186/// GUARANTEES:
187/// - If the migration succeeds: all changes are committed, migration is marked as applied
188/// - If the migration fails: ALL changes are rolled back, database is unchanged
189/// - No partial state is ever possible
190///
191/// This is the ONLY way migrations should be run.
192fn run_atomic_migration<F>(
193    conn: &mut rusqlite::Connection,
194    id: u32,
195    name: &str,
196    migrate: F,
197) -> Result<(), String>
198where
199    F: FnOnce(&rusqlite::Transaction) -> Result<(), String>,
200{
201    // A migration above the constant would apply fine on first run, then be
202    // read as a downgrade on the next one and lock the user out of their own
203    // account. Fires on any debug run, so it lands long before a release even
204    // if nobody ran the test suite.
205    debug_assert!(
206        id <= HIGHEST_MIGRATION_ID,
207        "migration {id} exceeds HIGHEST_MIGRATION_ID ({HIGHEST_MIGRATION_ID}); bump the constant \
208         or this build will refuse the database it just wrote"
209    );
210
211    // Check if this specific migration was already applied.
212    if migration_applied(conn, id) {
213        return Ok(());
214    }
215
216    crate::log_info!("[DB] Migration {}: {}...", id, name);
217
218    // Start transaction - this is the atomicity boundary
219    let tx = conn.transaction()
220        .map_err(|e| format!("[DB] Migration {}: Failed to start transaction: {}", id, e))?;
221
222    // Run the migration within the transaction
223    match migrate(&tx) {
224        Ok(()) => {
225            // Mark as applied WITHIN the same transaction
226            mark_migration_applied(&tx, id)?;
227
228            // Commit - if this fails, everything rolls back
229            tx.commit()
230                .map_err(|e| format!("[DB] Migration {}: Failed to commit: {}", id, e))?;
231
232            crate::log_info!("[DB] Migration {} complete", id);
233            Ok(())
234        }
235        Err(e) => {
236            // Transaction automatically rolls back on drop
237            eprintln!("[DB] Migration {} FAILED: {} - rolling back", id, e);
238            Err(e)
239        }
240    }
241}
242
243/// Ensure a column exists on a table, adding it if missing.
244/// This is a safety net for cases where ALTER TABLE inside a WAL-mode
245/// transaction silently fails (e.g., other connections hold read locks).
246#[allow(dead_code)]
247fn ensure_column_exists(
248    conn: &mut rusqlite::Connection,
249    table: &str,
250    column: &str,
251    col_type: &str,
252) -> Result<(), String> {
253    let exists: bool = conn.query_row(
254        &format!("SELECT COUNT(*) FROM pragma_table_info('{}') WHERE name='{}'", table, column),
255        [],
256        |row| row.get::<_, i32>(0),
257    ).map(|c| c > 0).unwrap_or(false);
258
259    if !exists {
260        crate::log_warn!("[DB] Safety net: adding missing column {}.{}", table, column);
261        conn.execute(
262            &format!("ALTER TABLE {} ADD COLUMN {} {}", table, column, col_type),
263            [],
264        ).map_err(|e| format!("[DB] Failed to add column {}.{}: {}", table, column, e))?;
265    }
266    Ok(())
267}
268
269/// Run database migrations for schema updates
270///
271/// GUARANTEES:
272/// - Each migration runs in a transaction (atomic - all or nothing)
273/// - If any migration fails, changes are rolled back - no partial state
274/// - Migrations are tracked in schema_migrations table (idempotent - safe to re-run)
275/// - All errors are logged with `[DB]` prefix and propagated (no silent failures)
276pub fn run_migrations(conn: &mut rusqlite::Connection) -> Result<(), String> {
277    // Ensure schema_migrations table exists (bootstrap - must succeed before any migrations)
278    conn.execute(
279        "CREATE TABLE IF NOT EXISTS schema_migrations (
280            id INTEGER PRIMARY KEY,
281            applied_at INTEGER NOT NULL
282        )",
283        [],
284    ).map_err(|e| format!("[DB] Failed to create schema_migrations table: {}", e))?;
285
286    // =========================================================================
287    // Migration 19: Create marketplace_cache table for persistent Nexus cache
288    // =========================================================================
289    // Caches marketplace app listings in SQLite so they survive restarts.
290    // On login, the cache is loaded into MARKETPLACE_STATE immediately (so
291    // permission checks work before the user visits the Nexus tab), then a
292    // background network fetch refreshes the data.
293    run_atomic_migration(conn, 19, "Create marketplace_cache table", |tx| {
294        tx.execute_batch(
295            "CREATE TABLE IF NOT EXISTS marketplace_cache (
296                id TEXT PRIMARY KEY,
297                data TEXT NOT NULL,
298                fetched_at INTEGER NOT NULL
299            );"
300        ).map_err(|e| format!("Failed to create marketplace_cache table: {}", e))?;
301        Ok(())
302    })?;
303
304    // =========================================================================
305    // Migration 20: Add is_blocked column to profiles table
306    // =========================================================================
307    // Supports user blocking: blocked profiles have DM events dropped after
308    // decrypt (wrapper kept for negentropy), group messages filtered in UI.
309    run_atomic_migration(conn, 20, "Add is_blocked column to profiles", |tx| {
310        tx.execute_batch(
311            "ALTER TABLE profiles ADD COLUMN is_blocked INTEGER NOT NULL DEFAULT 0;"
312        ).map_err(|e| format!("Failed to add is_blocked column: {}", e))?;
313        Ok(())
314    })?;
315
316    // =========================================================================
317    // Migration 21: NIP-17 ephemeral wrap-key vault for deletable DMs
318    // =========================================================================
319    // Stores the ephemeral secp256k1 secret used to sign each kind-1059
320    // gift-wrap so the user can later publish a NIP-09 deletion against
321    // the wrap event ID — actually removing the message from inbox relays.
322    // Encryption-at-rest is handled by Vector's per-account database
323    // envelope (ChaCha20 if the account has a password; plaintext otherwise).
324    // One row per published wrap; deletion uses (wrap_event_id, secret,
325    // relay_urls) to issue an author-signed NIP-09 to the same relay set.
326    run_atomic_migration(conn, 21, "Create nip17_wrap_keys table", |tx| {
327        tx.execute_batch(
328            "CREATE TABLE IF NOT EXISTS nip17_wrap_keys (
329                wrap_event_id    TEXT PRIMARY KEY,
330                rumor_id         TEXT NOT NULL,
331                recipient_pubkey TEXT NOT NULL,
332                role             INTEGER NOT NULL,
333                secret           BLOB NOT NULL,
334                relay_urls       TEXT NOT NULL,
335                created_at       INTEGER NOT NULL
336            );
337            CREATE INDEX IF NOT EXISTS idx_nip17_wrap_keys_rumor ON nip17_wrap_keys(rumor_id);"
338        ).map_err(|e| format!("Failed to create nip17_wrap_keys table: {}", e))?;
339        Ok(())
340    })?;
341
342    // =========================================================================
343    // Migration 22: MLS ephemeral wrap-key vault for deletable group messages
344    // =========================================================================
345    // Sibling of nip17_wrap_keys: every kind-445 MLS wrapper is signed by an
346    // ephemeral keypair that MDK normally discards. With our `create_message_retained`
347    // patch the sender retains the secret so a later NIP-09 deletion against
348    // the kind-445 event id is valid (NIP-09 requires `event.pubkey ==
349    // deletion.pubkey`). One row per published wrapper; retries write new rows.
350    run_atomic_migration(conn, 22, "Create mls_wrap_keys table", |tx| {
351        tx.execute_batch(
352            "CREATE TABLE IF NOT EXISTS mls_wrap_keys (
353                wrap_event_id TEXT PRIMARY KEY,
354                message_id    TEXT NOT NULL,
355                group_id      TEXT NOT NULL,
356                secret        BLOB NOT NULL,
357                relay_urls    TEXT NOT NULL,
358                created_at    INTEGER NOT NULL
359            );
360            CREATE INDEX IF NOT EXISTS idx_mls_wrap_keys_message ON mls_wrap_keys(message_id);
361            CREATE INDEX IF NOT EXISTS idx_mls_wrap_keys_group ON mls_wrap_keys(group_id);"
362        ).map_err(|e| format!("Failed to create mls_wrap_keys table: {}", e))?;
363        Ok(())
364    })?;
365
366    // =========================================================================
367    // Migration 23: MLS pending event queue for cross-sync retry
368    // =========================================================================
369    // When MDK can't process an MLS event because its prerequisite commit
370    // hasn't arrived, we previously marked it "processed" and advanced the
371    // cursor past it — losing it forever. This table persists such events
372    // so subsequent syncs can retry once the prerequisite shows up (possibly
373    // from a different relay, days or weeks later). Pruned at 90 days.
374    run_atomic_migration(conn, 23, "Create mls_pending_events table", |tx| {
375        tx.execute_batch(
376            "CREATE TABLE IF NOT EXISTS mls_pending_events (
377                event_id      TEXT PRIMARY KEY,
378                group_id      TEXT NOT NULL,
379                event_json    TEXT NOT NULL,
380                first_seen_at INTEGER NOT NULL,
381                last_retry_at INTEGER NOT NULL,
382                retry_count   INTEGER NOT NULL DEFAULT 0
383            );
384            CREATE INDEX IF NOT EXISTS idx_mls_pending_events_group ON mls_pending_events(group_id);
385            CREATE INDEX IF NOT EXISTS idx_mls_pending_events_first_seen ON mls_pending_events(first_seen_at);"
386        ).map_err(|e| format!("Failed to create mls_pending_events table: {}", e))?;
387        Ok(())
388    })?;
389
390    // =========================================================================
391    // Migration 24: Blossom capability cache — drives smart upload routing.
392    // =========================================================================
393    run_atomic_migration(conn, 24, "Create blossom_server_capabilities table", |tx| {
394        tx.execute_batch(
395            "CREATE TABLE IF NOT EXISTS blossom_server_capabilities (
396                server_url        TEXT    NOT NULL,
397                mime_type         TEXT    NOT NULL,
398                outcome           INTEGER NOT NULL,
399                max_accepted_size INTEGER NOT NULL DEFAULT 0,
400                updated_at        INTEGER NOT NULL,
401                PRIMARY KEY (server_url, mime_type)
402            );"
403        ).map_err(|e| format!("Failed to create blossom_server_capabilities table: {}", e))?;
404        Ok(())
405    })?;
406
407    // =========================================================================
408    // Migration 25: Add `min_rejected_size` (smallest observed 413).
409    // =========================================================================
410    run_atomic_migration(conn, 25, "Add min_rejected_size to blossom_server_capabilities", |tx| {
411        tx.execute_batch(
412            "ALTER TABLE blossom_server_capabilities ADD COLUMN min_rejected_size INTEGER;"
413        ).map_err(|e| format!("Failed to add min_rejected_size column: {}", e))?;
414        Ok(())
415    })?;
416
417    // =========================================================================
418    // Migration 26: Split capability rows by encrypted vs plaintext context.
419    // Same wire MIME means different things for ciphertext vs real bytes;
420    // pre-migration rows didn't track the distinction so they're dropped.
421    // =========================================================================
422    run_atomic_migration(conn, 26, "Add is_encrypted to capability cache PK", |tx| {
423        tx.execute_batch(
424            "DROP TABLE IF EXISTS blossom_server_capabilities;
425             CREATE TABLE blossom_server_capabilities (
426                server_url        TEXT    NOT NULL,
427                mime_type         TEXT    NOT NULL,
428                is_encrypted      INTEGER NOT NULL DEFAULT 0,
429                outcome           INTEGER NOT NULL,
430                max_accepted_size INTEGER NOT NULL DEFAULT 0,
431                min_rejected_size INTEGER,
432                updated_at        INTEGER NOT NULL,
433                PRIMARY KEY (server_url, mime_type, is_encrypted)
434             );"
435        ).map_err(|e| format!("Failed to recreate blossom_server_capabilities: {}", e))?;
436        Ok(())
437    })?;
438
439    // =========================================================================
440    // Migration 27: Mark NIP-46 remote-signer support landed.
441    //
442    // Settings is a KV — no schema change needed for the three new keys
443    // (`signer_type`, `bunker_url`, `bunker_remote_pubkey`). Pre-bunker
444    // accounts have no `signer_type` row at all; the loader treats missing
445    // as `local`. We backfill an explicit `signer_type='local'` row so every
446    // account has a discriminator on disk after this point — makes the
447    // discriminator query a clean `=` instead of a NULL-coalesce.
448    // =========================================================================
449    run_atomic_migration(conn, 27, "Backfill signer_type=local for pre-NIP-46 accounts", |tx| {
450        tx.execute(
451            "INSERT OR IGNORE INTO settings (key, value) VALUES ('signer_type', 'local')",
452            [],
453        ).map_err(|e| format!("Failed to backfill signer_type: {}", e))?;
454        Ok(())
455    })?;
456
457    // =========================================================================
458    // Migration 28: NIP-30 / NIP-51 custom emoji packs
459    // =========================================================================
460    // `emoji_packs`           — kind 30030 sets (own + subscribed), one row per addr.
461    // `emoji_pack_items`      — flattened emoji rows per pack; CASCADE deletes follow.
462    // `emoji_pack_subscriptions` — local mirror of kind 10030 `a` tags; fast startup
463    //                              read without re-fetching from relays.
464    run_atomic_migration(conn, 28, "Create emoji pack tables", |tx| {
465        tx.execute_batch(
466            "CREATE TABLE IF NOT EXISTS emoji_packs (
467                addr        TEXT PRIMARY KEY,
468                pubkey      TEXT NOT NULL,
469                identifier  TEXT NOT NULL,
470                title       TEXT NOT NULL DEFAULT '',
471                image_url   TEXT NOT NULL DEFAULT '',
472                description TEXT NOT NULL DEFAULT '',
473                is_own      INTEGER NOT NULL DEFAULT 0,
474                updated_at  INTEGER NOT NULL,
475                raw_event   TEXT NOT NULL DEFAULT ''
476            );
477            CREATE INDEX IF NOT EXISTS idx_emoji_packs_pubkey ON emoji_packs(pubkey);
478            CREATE INDEX IF NOT EXISTS idx_emoji_packs_is_own ON emoji_packs(is_own);
479
480            CREATE TABLE IF NOT EXISTS emoji_pack_items (
481                pack_addr  TEXT NOT NULL,
482                shortcode  TEXT NOT NULL,
483                url        TEXT NOT NULL,
484                sha256     TEXT,
485                position   INTEGER NOT NULL DEFAULT 0,
486                PRIMARY KEY (pack_addr, shortcode),
487                FOREIGN KEY (pack_addr) REFERENCES emoji_packs(addr) ON DELETE CASCADE
488            );
489            CREATE INDEX IF NOT EXISTS idx_emoji_pack_items_pack ON emoji_pack_items(pack_addr, position);
490
491            CREATE TABLE IF NOT EXISTS emoji_pack_subscriptions (
492                addr           TEXT PRIMARY KEY,
493                subscribed_at  INTEGER NOT NULL
494            );"
495        ).map_err(|e| format!("Failed to create emoji pack tables: {}", e))?;
496        Ok(())
497    })?;
498
499    // =========================================================================
500    // Migration 29: Add per-DM wallpaper columns to chats
501    // =========================================================================
502    // Wallpaper is the local cached file path (decrypted from the Blossom
503    // attachment carried by the most recent kind-30078 d=vector-wallpaper rumor
504    // for this chat). wallpaper_ts is the rumor created_at that produced it,
505    // used for latest-write-wins on concurrent sets.
506    run_atomic_migration(conn, 29, "Add wallpaper columns to chats", |tx| {
507        tx.execute_batch(
508            "ALTER TABLE chats ADD COLUMN wallpaper_path TEXT NOT NULL DEFAULT '';
509             ALTER TABLE chats ADD COLUMN wallpaper_ts INTEGER NOT NULL DEFAULT 0;"
510        ).map_err(|e| format!("Failed to add wallpaper columns: {}", e))?;
511        Ok(())
512    })?;
513
514    // =========================================================================
515    // Migration 30: Wallpaper customisation knobs (blur + brightness)
516    // =========================================================================
517    // blur: integer pixels, 0..=30 (0 = no blur).
518    // dim:  integer percent, 0..=100 (100 = no darkening, 0 = fully black).
519    // Defaults match the values applied when a rumor arrives without the
520    // optional tags — keeps older clients interoperable.
521    run_atomic_migration(conn, 30, "Add wallpaper blur/dim columns to chats", |tx| {
522        tx.execute_batch(
523            "ALTER TABLE chats ADD COLUMN wallpaper_blur INTEGER NOT NULL DEFAULT 0;
524             ALTER TABLE chats ADD COLUMN wallpaper_dim INTEGER NOT NULL DEFAULT 50;"
525        ).map_err(|e| format!("Failed to add wallpaper blur/dim columns: {}", e))?;
526        Ok(())
527    })?;
528
529    // =========================================================================
530    // Migration 31: Track wallpaper Blossom URL + uploader pubkey
531    // =========================================================================
532    // wallpaper_url is the Blossom blob URL of the current wallpaper.
533    // wallpaper_uploader is the npub (bech32) of whoever uploaded it. Together
534    // they let us DELETE the previous blob from Blossom when we (or another
535    // device of ours) replace the wallpaper — only the original uploader's
536    // signature satisfies the server's auth challenge.
537    run_atomic_migration(conn, 31, "Add wallpaper url/uploader columns to chats", |tx| {
538        tx.execute_batch(
539            "ALTER TABLE chats ADD COLUMN wallpaper_url TEXT NOT NULL DEFAULT '';
540             ALTER TABLE chats ADD COLUMN wallpaper_uploader TEXT NOT NULL DEFAULT '';"
541        ).map_err(|e| format!("Failed to add wallpaper url/uploader columns: {}", e))?;
542        Ok(())
543    })?;
544
545    // =========================================================================
546    // Migration 32: Drop mls_event_cursors — superseded by Total Negentropy
547    // =========================================================================
548    // MLS sync no longer tracks a per-group cursor. Possession of an event
549    // (mls_processed_events ∪ mls_pending_events) is the negentropy fingerprint
550    // set, and reconciliation derives the missing set directly. The cursor was
551    // a pre-negentropy resume mechanism that could only disagree with it.
552    run_atomic_migration(conn, 32, "Drop mls_event_cursors table", |tx| {
553        tx.execute_batch("DROP TABLE IF EXISTS mls_event_cursors;")
554            .map_err(|e| format!("Failed to drop mls_event_cursors: {}", e))?;
555        Ok(())
556    })?;
557
558    // =========================================================================
559    // GAP: migration ids 33-39 are PERMANENTLY BURNED — do not reuse.
560    // =========================================================================
561    // The distributed v0.4.0 "MLS edition" shipped MLS migrations in the 33-39 range that
562    // never made it into committed history (its release branch was later squashed to max 32).
563    // Migrations are tracked per-id (`schema_migrations`), not by a monotonic counter, so an
564    // MLS-edition DB has 33-39 recorded and would SKIP any new migration reusing those ids,
565    // silently never creating the table. Community state therefore starts at 40. Never fill
566    // the 33-39 gap, even though it looks tidy — those ids are spent forever.
567    //
568    // Migration 40: Community (Concord) protocol local state
569    // =========================================================================
570    // Per-account (the DB itself is account-scoped via account_dir(npub)). Holds the
571    // owner/member's held secrets (server-root key, epoch-tagged channel keys), the folded
572    // control-plane state, and local invite/dedup bookkeeping. Ids are hex. Authority is
573    // keyless: real-npub control editions + the owner attestation, never a shared secret.
574    run_atomic_migration(conn, 40, "Create community tables", |tx| {
575        tx.execute_batch(
576            "CREATE TABLE IF NOT EXISTS communities (
577                community_id          TEXT PRIMARY KEY,
578                server_root_key       BLOB NOT NULL,
579                name                  TEXT NOT NULL,
580                relays                TEXT NOT NULL,
581                created_at            INTEGER NOT NULL,
582                description           TEXT,
583                icon                  TEXT,
584                banner                TEXT,
585                banlist               TEXT NOT NULL DEFAULT '[]',
586                banlist_at            INTEGER NOT NULL DEFAULT 0,
587                owner_attestation     TEXT,
588                roles                 TEXT NOT NULL DEFAULT '{}',
589                roles_at              INTEGER NOT NULL DEFAULT 0,
590                server_root_epoch     INTEGER NOT NULL DEFAULT 0,
591                invite_registry       TEXT NOT NULL DEFAULT '[]',
592                read_cut_pending      INTEGER NOT NULL DEFAULT 0,
593                read_cut_target_epoch INTEGER NOT NULL DEFAULT 0,
594                dissolved             INTEGER NOT NULL DEFAULT 0
595            );
596            CREATE TABLE IF NOT EXISTS community_channels (
597                channel_id              TEXT PRIMARY KEY,
598                community_id            TEXT NOT NULL,
599                channel_key             BLOB NOT NULL,
600                epoch                   INTEGER NOT NULL,
601                name                    TEXT NOT NULL,
602                created_at              INTEGER NOT NULL,
603                rekeyed_at_server_epoch INTEGER NOT NULL DEFAULT 0
604            );
605            CREATE INDEX IF NOT EXISTS idx_community_channels_community
606                ON community_channels(community_id);
607            CREATE TABLE IF NOT EXISTS community_message_keys (
608                outer_event_id   TEXT PRIMARY KEY,
609                ephemeral_secret BLOB NOT NULL,
610                relays           TEXT NOT NULL,
611                created_at       INTEGER NOT NULL,
612                message_id       TEXT
613            );
614            CREATE INDEX IF NOT EXISTS idx_cmk_message_id
615                ON community_message_keys(message_id);
616            CREATE TABLE IF NOT EXISTS pending_community_invites (
617                community_id TEXT PRIMARY KEY,
618                bundle_json  TEXT NOT NULL,
619                inviter_npub TEXT NOT NULL,
620                received_at  INTEGER NOT NULL
621            );
622            CREATE TABLE IF NOT EXISTS community_public_invites (
623                token        TEXT PRIMARY KEY,
624                community_id TEXT NOT NULL,
625                url          TEXT NOT NULL,
626                expires_at   INTEGER,
627                created_at   INTEGER NOT NULL
628            );
629            CREATE INDEX IF NOT EXISTS idx_public_invites_community
630                ON community_public_invites(community_id);
631            CREATE TABLE IF NOT EXISTS community_edition_heads (
632                community_id TEXT NOT NULL,
633                entity_id    TEXT NOT NULL,
634                version      INTEGER NOT NULL,
635                self_hash    BLOB NOT NULL,
636                inner_id     BLOB,
637                epoch        INTEGER NOT NULL DEFAULT 0,
638                PRIMARY KEY (community_id, entity_id)
639            );
640            CREATE TABLE IF NOT EXISTS community_epoch_keys (
641                community_id TEXT NOT NULL,
642                scope_id     TEXT NOT NULL,
643                epoch        INTEGER NOT NULL,
644                key          BLOB NOT NULL,
645                created_at   INTEGER NOT NULL,
646                PRIMARY KEY (community_id, scope_id, epoch)
647            );
648            CREATE TABLE IF NOT EXISTS community_invite_link_sets (
649                community_id TEXT NOT NULL,
650                creator      TEXT NOT NULL,
651                locators     TEXT NOT NULL DEFAULT '[]',
652                version      INTEGER NOT NULL DEFAULT 0,
653                PRIMARY KEY (community_id, creator)
654            );",
655        )
656        .map_err(|e| format!("Failed to create community tables: {}", e))?;
657        Ok(())
658    })?;
659
660    // =========================================================================
661    // Migration 41: Purge legacy MLS data (MLS is fully removed)
662    // =========================================================================
663    // Drop the retired chat_type=1 (MlsGroup) chats + their events, then the MLS-only
664    // storage tables. chat_type 2 (Community) is untouched. Runs for accounts upgrading
665    // from an MLS build; a no-op on a fresh DB.
666    run_atomic_migration(conn, 41, "Purge legacy MLS data", |tx| {
667        tx.execute_batch(
668            "DELETE FROM events WHERE chat_id IN (SELECT id FROM chats WHERE chat_type = 1);
669             DELETE FROM chats WHERE chat_type = 1;
670             DROP TABLE IF EXISTS mls_groups;
671             DROP TABLE IF EXISTS mls_keypackages;
672             DROP TABLE IF EXISTS mls_processed_events;
673             DROP TABLE IF EXISTS mls_wrap_keys;
674             DROP TABLE IF EXISTS mls_pending_events;",
675        )
676        .map_err(|e| format!("Failed to purge legacy MLS data: {}", e))?;
677        Ok(())
678    })?;
679
680    // =========================================================================
681    // Migration 42: Make processed_wrappers a cross-transport dedup ledger
682    // =========================================================================
683    // A `transport` discriminator so every transport (NIP-17 DMs, Concord) shares ONE
684    // outer-event dedup store, while NIP-77 negentropy keeps fingerprinting only the 'nip17'
685    // subset. Existing rows are gift-wraps, so the default 0 ('nip17') is correct.
686    run_atomic_migration(conn, 42, "Add transport discriminator to processed_wrappers", |tx| {
687        tx.execute_batch("ALTER TABLE processed_wrappers ADD COLUMN transport INTEGER NOT NULL DEFAULT 0;")
688            .map_err(|e| format!("Failed to add transport column: {}", e))?;
689        Ok(())
690    })?;
691
692    // =========================================================================
693    // Migration 43: Persist the optional label on a minted public invite
694    // =========================================================================
695    // The label set at mint time rides in the relay-published bundle (join attribution) but wasn't
696    // stored locally, so the owner's invite-links list had no label to show. Encrypted-at-rest like
697    // the sibling columns; NULL when no label was set.
698    run_atomic_migration(conn, 43, "Add label to community_public_invites", |tx| {
699        tx.execute_batch("ALTER TABLE community_public_invites ADD COLUMN label TEXT;")
700            .map_err(|e| format!("Failed to add label column: {}", e))?;
701        Ok(())
702    })?;
703
704    // Migration 44: Per-account emoji "frecency" (most-used) table.
705    // =========================================================================
706    // `score` is a time-weighted log-space value: each use adds
707    // 2^((t-EPOCH)/half_life), so ranking is a plain `ORDER BY score DESC` (the
708    // uniform decay factor cancels) — no per-row decay math at read time. `kind`:
709    // 0=unicode, 1=custom. WITHOUT ROWID + (kind,id) PK so a reuse is an in-place
710    // upsert (one row per emoji), not an append.
711    run_atomic_migration(conn, 44, "Create emoji_usage table", |tx| {
712        tx.execute_batch(
713            "CREATE TABLE IF NOT EXISTS emoji_usage (
714                kind      INTEGER NOT NULL,
715                id        TEXT    NOT NULL,
716                url       TEXT,
717                score     REAL    NOT NULL,
718                last_used INTEGER NOT NULL,
719                PRIMARY KEY (kind, id)
720            ) WITHOUT ROWID;
721            CREATE INDEX IF NOT EXISTS idx_emoji_usage_score
722                ON emoji_usage(score DESC);",
723        )
724        .map_err(|e| format!("Failed to create emoji_usage table: {}", e))?;
725        Ok(())
726    })?;
727
728    // Migration 62: Repair — guarantee `label` exists on community_public_invites. Id 43 (which adds it)
729    // was burned on DBs created from an older baseline: recorded as applied without the ALTER ever landing,
730    // so `label` is silently absent and list_all_public_invites errors. Use a fresh id past every recorded
731    // one (DBs already hold up to 61) and add the column only if missing, so it's a no-op where 43 worked.
732    run_atomic_migration(conn, 62, "Repair: ensure label column on community_public_invites", |tx| {
733        let has_label: i64 = tx
734            .query_row(
735                "SELECT COUNT(*) FROM pragma_table_info('community_public_invites') WHERE name = 'label'",
736                [],
737                |r| r.get(0),
738            )
739            .map_err(|e| format!("Failed to inspect community_public_invites columns: {}", e))?;
740        if has_label == 0 {
741            tx.execute_batch("ALTER TABLE community_public_invites ADD COLUMN label TEXT;")
742                .map_err(|e| format!("Failed to add label column: {}", e))?;
743        }
744        Ok(())
745    })?;
746
747    // =========================================================================
748    // Migration 63: Emoji pack health (revocation / durable-absence tracking)
749    // =========================================================================
750    // `status`: 0 = active, 1 = revoked (a deterministic tombstone was seen: an
751    // empty kind-30030 replacement, or an author-signed kind-5 deletion),
752    // 2 = missing (absent across enough clean relay sweeps). The miss columns
753    // drive the promotion gauntlet in `emoji_packs::apply_pack_health`; a live
754    // fetch resets everything back to active.
755    run_atomic_migration(conn, 63, "Add health columns to emoji_packs", |tx| {
756        tx.execute_batch(
757            "ALTER TABLE emoji_packs ADD COLUMN status INTEGER NOT NULL DEFAULT 0;
758             ALTER TABLE emoji_packs ADD COLUMN miss_count INTEGER NOT NULL DEFAULT 0;
759             ALTER TABLE emoji_packs ADD COLUMN first_missed_at INTEGER NOT NULL DEFAULT 0;
760             ALTER TABLE emoji_packs ADD COLUMN last_miss_counted_at INTEGER NOT NULL DEFAULT 0;
761             ALTER TABLE emoji_packs ADD COLUMN status_changed_at INTEGER NOT NULL DEFAULT 0;",
762        )
763        .map_err(|e| format!("Failed to add emoji pack health columns: {}", e))?;
764        Ok(())
765    })?;
766
767    // =========================================================================
768    // Migration 64: Drop orphaned pending-id event rows
769    // =========================================================================
770    // Mid-flight persists could land a row under a message's optimistic
771    // "pending-…" id; the finalized message then saved under its REAL id,
772    // orphaning the pending-keyed row as a ghost duplicate that renders on
773    // reload. Rows still flagged pending/failed are live send-state (the
774    // retry UI needs them) and stay.
775    run_atomic_migration(conn, 64, "Drop orphaned pending-id event rows", |tx| {
776        tx.execute(
777            "DELETE FROM events WHERE id LIKE 'pending-%' AND pending = 0 AND failed = 0",
778            [],
779        )
780        .map_err(|e| format!("Failed to drop orphaned pending rows: {}", e))?;
781        Ok(())
782    })?;
783
784    // =========================================================================
785    // Migration 65: Add position to emoji pack subscriptions
786    // =========================================================================
787    // `subscribed_at` alone can't hold a user-defined order — save_subscriptions
788    // rewrites every row with the same `now`, so ties are unordered. `position`
789    // is the authoritative display order (cross-device synced via kind 10030).
790    // Backfill preserves the current rowid order so existing installs don't
791    // reshuffle on first launch.
792    run_atomic_migration(conn, 65, "Add position to emoji pack subscriptions", |tx| {
793        tx.execute_batch(
794            "ALTER TABLE emoji_pack_subscriptions ADD COLUMN position INTEGER NOT NULL DEFAULT 0;
795             UPDATE emoji_pack_subscriptions SET position = (
796                 SELECT COUNT(*) FROM emoji_pack_subscriptions s2
797                 WHERE s2.rowid < emoji_pack_subscriptions.rowid
798             );",
799        )
800        .map_err(|e| format!("Failed to add position column: {}", e))?;
801        Ok(())
802    })?;
803
804    // Migration 66: Concord v2 dual-stack columns. A community is v1 (the shipped
805    // protocol) or v2 (the self-certifying-id CORD stack); the two coexist per
806    // account. Existing rows default to v1. v2 stores the owner commitment inputs
807    // (owner_pubkey + owner_salt reproduce the community_id) in place of v1's
808    // owner_attestation; server_root_key/server_root_epoch carry the v2
809    // community_root/root_epoch (same base-key role, reused columns). A channel's
810    // `private` flag selects v2 keying: public channels derive from the root (no
811    // stored key), private ones carry an independent key.
812    run_atomic_migration(conn, 66, "Concord v2 dual-stack columns", |tx| {
813        for (table, col, ddl) in [
814            ("communities", "protocol", "INTEGER NOT NULL DEFAULT 1"),
815            ("communities", "owner_pubkey", "TEXT"),
816            ("communities", "owner_salt", "TEXT"),
817            ("community_channels", "private", "INTEGER NOT NULL DEFAULT 0"),
818        ] {
819            // ADD COLUMN is not idempotent; tolerate a re-run (duplicate column).
820            let sql = format!("ALTER TABLE {table} ADD COLUMN {col} {ddl}");
821            if let Err(e) = tx.execute(&sql, []) {
822                let msg = e.to_string();
823                if !msg.contains("duplicate column name") {
824                    return Err(format!("add {table}.{col}: {msg}"));
825                }
826            }
827        }
828        Ok(())
829    })?;
830
831    // Migration 67: the persisted v2 Guestbook — the RAW membership events (one
832    // encrypted JSON blob per community; kick/snapshot validity is judged at fold
833    // time against CURRENT authority, so raw events are the correct stored form)
834    // plus the newest-seen cursor, so boot catches the plane up incrementally and
835    // the memberlist becomes a local read.
836    run_atomic_migration(conn, 67, "v2 guestbook store", |tx| {
837        tx.execute(
838            "CREATE TABLE IF NOT EXISTS community_guestbook (
839                community_id TEXT PRIMARY KEY,
840                events TEXT NOT NULL,
841                cursor_secs INTEGER NOT NULL DEFAULT 0
842            )",
843            [],
844        )
845        .map_err(|e| format!("create community_guestbook: {e}"))?;
846        Ok(())
847    })?;
848
849    // Migration 68: the CORD-02 §6 preservation stash — vsk fields Vector doesn't
850    // drive (voice, client `custom`, unknown `extra`) persist beside the entity so
851    // our own editions republish the FULL document instead of wiping them.
852    run_atomic_migration(conn, 68, "v2 metadata preservation stash", |tx| {
853        for (table, col) in [("communities", "meta_extra"), ("community_channels", "meta_extra")] {
854            let sql = format!("ALTER TABLE {table} ADD COLUMN {col} TEXT");
855            if let Err(e) = tx.execute(&sql, []) {
856                let msg = e.to_string();
857                if !msg.contains("duplicate column name") {
858                    return Err(format!("add {table}.{col}: {msg}"));
859                }
860            }
861        }
862        Ok(())
863    })?;
864
865    // Migration 69: last-known bot manifests (kind 10304) so the `/` command
866    // picker serves instantly from boot; a background refetch replaces a row
867    // only with a newer edition. Manifests are PUBLIC replaceable events, so
868    // rows are plaintext (unlike membership/community state).
869    run_atomic_migration(conn, 69, "bot manifest store", |tx| {
870        tx.execute(
871            "CREATE TABLE IF NOT EXISTS bot_manifests (
872                pubkey TEXT PRIMARY KEY,
873                manifest TEXT NOT NULL,
874                event_created_at INTEGER NOT NULL,
875                fetched_at INTEGER NOT NULL
876            )",
877            [],
878        )
879        .map_err(|e| format!("create bot_manifests: {e}"))?;
880        Ok(())
881    })?;
882
883    // =========================================================================
884    // Migration 70: Retained gift-wrap body for idempotent manual retry
885    // =========================================================================
886    // A failed (red) DM whose wrap silently landed would double-post on manual
887    // Retry, because Retry rebuilt a fresh wrap with a new outer id. Retaining
888    // the exact recipient wrap event (+ its rumor, + the local pending id to
889    // look it up by) lets Retry republish the byte-identical event: relays
890    // no-op the duplicate, so duplication is impossible regardless of client.
891    // The body columns are nulled the instant the send is confirmed (a relay
892    // OK), so steady-state they are NULL — only unsent messages carry a body.
893    run_atomic_migration(conn, 70, "Retained gift-wrap body for idempotent retry", |tx| {
894        tx.execute_batch(
895            "ALTER TABLE nip17_wrap_keys ADD COLUMN wrap_json  TEXT;
896             ALTER TABLE nip17_wrap_keys ADD COLUMN rumor_json TEXT;
897             ALTER TABLE nip17_wrap_keys ADD COLUMN pending_id TEXT;
898             CREATE INDEX IF NOT EXISTS idx_nip17_wrap_keys_pending ON nip17_wrap_keys(pending_id);"
899        ).map_err(|e| format!("Failed to add resend-payload columns: {}", e))?;
900        Ok(())
901    })?;
902
903    // =========================================================================
904    // Migration 71: Covering index for the unread-count query
905    // =========================================================================
906    // Column order = (chat_id, mine, kind) equality then a created_at range; the four columns
907    // cover both the per-chat anchor MAX and the count, so neither touches the table.
908    run_atomic_migration(conn, 71, "Covering index for unread counts", |tx| {
909        tx.execute_batch(
910            "CREATE INDEX IF NOT EXISTS idx_events_unread ON events(chat_id, mine, kind, created_at);"
911        ).map_err(|e| format!("Failed to create unread covering index: {}", e))?;
912        Ok(())
913    })?;
914
915    // =========================================================================
916    // Migration 72: Drop the unused events(user_id) index
917    // =========================================================================
918    // No query filters, joins, or orders by events.user_id, so the index only
919    // cost a b-tree write on every event insert. Authors resolve via the
920    // denormalized npub column instead.
921    run_atomic_migration(conn, 72, "Drop unused events user_id index", |tx| {
922        tx.execute_batch("DROP INDEX IF EXISTS idx_events_user;")
923            .map_err(|e| format!("Failed to drop idx_events_user: {}", e))?;
924        Ok(())
925    })?;
926
927    // =========================================================================
928    // Migration 73: Drop the legacy `messages` table
929    // =========================================================================
930    // Superseded by `events` at v0.3.1 (its data + attachment metadata were
931    // copied over then). The public app has shipped on `events` since v0.4.0,
932    // so no live account writes or reads `messages`. DROP takes its indexes too.
933    run_atomic_migration(conn, 73, "Drop legacy messages table", |tx| {
934        tx.execute_batch("DROP TABLE IF EXISTS messages;")
935            .map_err(|e| format!("Failed to drop legacy messages table: {}", e))?;
936        Ok(())
937    })?;
938
939    // =========================================================================
940    // Migration 74: Dedicated attachments table + backfill from event tags
941    // =========================================================================
942    // Attachments lived as a `["attachments", <json>]` entry inside events.tags,
943    // making dedup a LIKE scan, the integrity check a per-event JSON parse, and
944    // every download flip a read-modify-write of the whole tags blob. Normalize
945    // into one row per attachment, keyed to its event (cascade on delete) and
946    // indexed by content hash. Backfill from the existing tags in this same
947    // transaction; the original tag is LEFT IN PLACE as a safety net (the table
948    // is authoritative, but no data is destroyed) until a later release strips it.
949    // Tags are plaintext at rest (only content is encrypted), so no decrypt here.
950    run_atomic_migration(conn, 74, "Attachments table + backfill", |tx| {
951        tx.execute_batch(
952            "CREATE TABLE IF NOT EXISTS attachments (
953                id           INTEGER PRIMARY KEY,
954                event_id     TEXT NOT NULL,
955                att_index    INTEGER NOT NULL,
956                hash         TEXT NOT NULL,
957                key          TEXT NOT NULL DEFAULT '',
958                nonce        TEXT NOT NULL DEFAULT '',
959                extension    TEXT NOT NULL DEFAULT '',
960                name         TEXT NOT NULL DEFAULT '',
961                url          TEXT NOT NULL DEFAULT '',
962                path         TEXT NOT NULL DEFAULT '',
963                size         INTEGER NOT NULL DEFAULT 0,
964                img_meta     TEXT,
965                downloaded   INTEGER NOT NULL DEFAULT 0,
966                webxdc_topic TEXT, group_id TEXT, original_hash TEXT, scheme_version TEXT, mls_filename TEXT,
967                UNIQUE(event_id, att_index),
968                FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE CASCADE
969            );
970            CREATE INDEX IF NOT EXISTS idx_attachments_hash       ON attachments(hash);
971            CREATE INDEX IF NOT EXISTS idx_attachments_downloaded ON attachments(downloaded) WHERE downloaded = 1;"
972        ).map_err(|e| format!("Failed to create attachments table: {}", e))?;
973
974        // Backfill: parse each event's attachments tag and insert one row per attachment.
975        let events: Vec<(String, String)> = {
976            let mut stmt = tx.prepare("SELECT id, tags FROM events WHERE tags LIKE '%attachments%'")
977                .map_err(|e| format!("prepare attachment backfill: {}", e))?;
978            let mapped = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
979                .map_err(|e| format!("query attachment backfill: {}", e))?;
980            mapped.filter_map(|r| r.ok()).collect()
981        };
982        for (event_id, tags_json) in events {
983            let tags: Vec<Vec<String>> = match serde_json::from_str(&tags_json) {
984                Ok(t) => t,
985                Err(_) => continue,
986            };
987            let att_json = tags.iter()
988                .find(|t| t.first().map(|s| s.as_str()) == Some("attachments"))
989                .and_then(|t| t.get(1));
990            let Some(att_json) = att_json else { continue };
991            let atts: Vec<crate::types::Attachment> = match serde_json::from_str(att_json) {
992                Ok(a) => a,
993                Err(_) => continue,
994            };
995            for (i, a) in atts.iter().enumerate() {
996                let img_meta_json = a.img_meta.as_ref().and_then(|m| serde_json::to_string(m).ok());
997                tx.execute(
998                    "INSERT INTO attachments (event_id, att_index, hash, key, nonce, extension, name, url, \
999                     path, size, img_meta, downloaded, webxdc_topic, group_id, original_hash) \
1000                     VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15)",
1001                    rusqlite::params![
1002                        event_id, i as i64, a.id, a.key, a.nonce, a.extension, a.name, a.url,
1003                        a.path, a.size as i64, img_meta_json, a.downloaded as i64,
1004                        a.webxdc_topic, a.group_id, a.original_hash,
1005                    ],
1006                ).map_err(|e| format!("insert backfilled attachment: {}", e))?;
1007            }
1008        }
1009        Ok(())
1010    })?;
1011
1012    // =========================================================================
1013    // Migration 75: Strip the vestigial `attachments` tag from backfilled events
1014    // =========================================================================
1015    // Migration 74 copied the attachments into the table but left the source tag
1016    // in place as a fallback. Now reclaim that dead JSON from every event whose
1017    // attachments are PROVABLY in the table — 74's backfill is all-or-nothing per
1018    // event, so a matching table row means the whole vec was copied. A tag that 74
1019    // could not parse (no row) keeps its raw bytes, so this is lossless. Smaller
1020    // event rows also mean the message-load queries (which read `tags`) touch fewer
1021    // bytes. The read fallback stays for any un-backfilled remnants.
1022    run_atomic_migration(conn, 75, "Strip backfilled attachment tags", |tx| {
1023        let events: Vec<(String, String)> = {
1024            let mut stmt = tx.prepare(
1025                "SELECT id, tags FROM events WHERE tags LIKE '%attachments%' \
1026                 AND id IN (SELECT DISTINCT event_id FROM attachments)"
1027            ).map_err(|e| format!("prepare tag strip: {}", e))?;
1028            let mapped = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
1029                .map_err(|e| format!("query tag strip: {}", e))?;
1030            mapped.flatten().collect()
1031        };
1032        for (id, tags_json) in events {
1033            let Ok(mut tags) = serde_json::from_str::<Vec<Vec<String>>>(&tags_json) else { continue };
1034            let before = tags.len();
1035            tags.retain(|t| t.first().map(|s| s.as_str()) != Some("attachments"));
1036            if tags.len() == before {
1037                continue; // false-positive LIKE match; no actual attachments tag
1038            }
1039            let new_tags = serde_json::to_string(&tags).unwrap_or(tags_json);
1040            tx.execute("UPDATE events SET tags=?1 WHERE id=?2", rusqlite::params![new_tags, id])
1041                .map_err(|e| format!("strip attachments tag: {}", e))?;
1042        }
1043        Ok(())
1044    })?;
1045
1046    // Drop the two attachment columns that never carried production data: `mls_filename`
1047    // (a vestige of the removed MLS feature) and `scheme_version` (unused MIP-04 plumbing).
1048    // Neither is read anywhere; both were always NULL.
1049    run_atomic_migration(conn, 76, "Drop dead attachment columns (mls_filename, scheme_version)", |tx| {
1050        tx.execute("ALTER TABLE attachments DROP COLUMN scheme_version", [])
1051            .map_err(|e| format!("drop scheme_version: {}", e))?;
1052        tx.execute("ALTER TABLE attachments DROP COLUMN mls_filename", [])
1053            .map_err(|e| format!("drop mls_filename: {}", e))?;
1054        Ok(())
1055    })?;
1056
1057    // v1→v2 community migration (task #10). `migrated_to` is the terminal per-community
1058    // fence: set inside the flip transaction, checked by every v1 write path. `migration_pointer`
1059    // persists the extracted dissolution payload (signpost + sealed key material) so the flip
1060    // survives restarts; `migration_checked` stops the boot sweep re-probing a community whose
1061    // tombstone turned out to be a plain payload-less dissolution. `community_migrations` is the
1062    // owner wizard's resumable ledger — `twin` carries the created channel key material because
1063    // the pre-flip v2 twin has zero channel rows locally (the hijack guard skips v1-owned rows).
1064    run_atomic_migration(conn, 77, "v1->v2 migration: pointer columns + wizard ledger", |tx| {
1065        tx.execute_batch(
1066            "ALTER TABLE communities ADD COLUMN migrated_to TEXT;
1067             ALTER TABLE communities ADD COLUMN migration_pointer TEXT;
1068             ALTER TABLE communities ADD COLUMN migration_checked INTEGER NOT NULL DEFAULT 0;
1069             CREATE TABLE IF NOT EXISTS community_migrations (
1070                 community_id    TEXT PRIMARY KEY,
1071                 v2_community_id TEXT NOT NULL,
1072                 phase           INTEGER NOT NULL DEFAULT 0,
1073                 twin            TEXT NOT NULL DEFAULT '',
1074                 updated_at      INTEGER NOT NULL DEFAULT 0
1075             );",
1076        )
1077        .map_err(|e| format!("migration 77: {}", e))?;
1078        Ok(())
1079    })?;
1080
1081    // Direct Invites carry a NIP-40 24h expiry. Relay support for NIP-40 is optional, so the
1082    // recipient enforces it locally too: the sender's declared expiry is persisted per parked
1083    // invite and filtered on read. 0 = no expiry declared (a pre-expiry sender), which stays
1084    // permanent — an invite whose sender never promised a deadline isn't ours to revoke.
1085    run_atomic_migration(conn, 78, "Pending invite expiry (NIP-40)", |tx| {
1086        tx.execute(
1087            "ALTER TABLE pending_community_invites ADD COLUMN expires_at INTEGER NOT NULL DEFAULT 0",
1088            [],
1089        )
1090        .map_err(|e| format!("migration 78: {}", e))?;
1091        Ok(())
1092    })?;
1093
1094    // =========================================================================
1095    // Migration 79: Per-npub ban history for phantom-member suppression
1096    // =========================================================================
1097    // CORD-02 §5 counts observation FORWARD of a member's latest Leave, Kick OR
1098    // BAN. The banlist alone is a timeless set, so lifting it let a pre-ban Join
1099    // (or old message) resurrect the npub as a member of a community they hold no
1100    // key to. Armada folds this from live control history; Vector caches the
1101    // banlist, so the per-npub mark has to persist alongside it.
1102    run_atomic_migration(conn, 79, "Per-npub ban marks (phantom-member suppression)", |tx| {
1103        // Presence-checked, not blind: a build that briefly carried this column in the
1104        // CREATE TABLE too would leave a DB holding the column with the migration rolled
1105        // back, and a bare ALTER then fails on every boot forever with no way out.
1106        let present: i32 = tx
1107            .query_row("SELECT COUNT(*) FROM pragma_table_info('communities') WHERE name='banlist_marks'", [], |r| r.get(0))
1108            .map_err(|e| format!("migration 79: {}", e))?;
1109        if present == 0 {
1110            tx.execute(
1111                "ALTER TABLE communities ADD COLUMN banlist_marks TEXT NOT NULL DEFAULT '{}'",
1112                [],
1113            )
1114            .map_err(|e| format!("migration 79: {}", e))?;
1115        }
1116        Ok(())
1117    })?;
1118
1119    // =========================================================================
1120    // Migration 80: Attachment mirror URLs (BUD-04 fallbacks)
1121    // =========================================================================
1122    // NIP-17 / imeta `fallback` sources: the same ciphertext mirrored on other
1123    // Blossom servers, tried in order when the primary URL dies. Space-joined
1124    // (URLs cannot contain spaces); empty = no mirrors.
1125    run_atomic_migration(conn, 80, "Attachment fallback URLs (Blossom mirrors)", |tx| {
1126        tx.execute(
1127            "ALTER TABLE attachments ADD COLUMN fallback_urls TEXT NOT NULL DEFAULT ''",
1128            [],
1129        )
1130        .map_err(|e| format!("migration 80: {}", e))?;
1131        Ok(())
1132    })?;
1133
1134    // =========================================================================
1135    // Migration 81: window index for the dedup-cache preload
1136    // =========================================================================
1137    // The preload reads processed_wrappers bounded by the reconcile cursors;
1138    // without this index the bounded query still scans the full ledger.
1139    run_atomic_migration(conn, 81, "processed_wrappers window index", |tx| {
1140        tx.execute(
1141            "CREATE INDEX IF NOT EXISTS idx_processed_wrappers_window \
1142             ON processed_wrappers(transport, wrapper_created_at)",
1143            [],
1144        )
1145        .map_err(|e| format!("migration 81: {}", e))?;
1146        Ok(())
1147    })?;
1148
1149    // =========================================================================
1150    // Migration 82: parked Private-Channel key vends (CORD-03/05 §6)
1151    // =========================================================================
1152    // A grant's key vend can arrive before the control fold that proves the
1153    // grant, so it parks here and is re-judged after every control follow.
1154    // Durable rather than in-RAM by necessity: the vend rides a 24h NIP-40 wrap
1155    // that relays delete, so a restart before the fold catches up would lose the
1156    // only copy. One row per (community, channel) — the newest epoch wins, and a
1157    // vend at or below the held epoch is superseded.
1158    run_atomic_migration(conn, 82, "Parked private-channel key vends", |tx| {
1159        tx.execute(
1160            "CREATE TABLE IF NOT EXISTS pending_channel_keys (
1161                community_id TEXT NOT NULL,
1162                channel_id   TEXT NOT NULL,
1163                epoch        INTEGER NOT NULL,
1164                channel_key  BLOB NOT NULL,
1165                sender       TEXT NOT NULL,
1166                received_at  INTEGER NOT NULL,
1167                PRIMARY KEY (community_id, channel_id)
1168            )",
1169            [],
1170        )
1171        .map_err(|e| format!("migration 82: {}", e))?;
1172        Ok(())
1173    })?;
1174
1175    // =========================================================================
1176    // Migration 83: parked vends become CANDIDATES, not a single slot
1177    // =========================================================================
1178    // 82 keyed the table on (community, channel) and only replaced on a higher
1179    // epoch. Parking is reachable by any npub that can gift-wrap us (the bundle
1180    // self-certifies, and its inputs are public for a public community), so a
1181    // stranger could pre-park a high-epoch row and make the genuine vend a silent
1182    // no-op — the member simply stays keyless with no retry.
1183    //
1184    // Now every vend is its own row and the judge tries them all, so an
1185    // unprovable row can never displace a provable one. Caps bound what an
1186    // arbitrary sender can make us store (and decrypt on every follow pass).
1187    run_atomic_migration(conn, 83, "Parked channel-key vends as candidates", |tx| {
1188        tx.execute("DROP TABLE IF EXISTS pending_channel_keys", [])
1189            .map_err(|e| format!("migration 83: {}", e))?;
1190        tx.execute(
1191            "CREATE TABLE pending_channel_keys (
1192                id           INTEGER PRIMARY KEY AUTOINCREMENT,
1193                community_id TEXT NOT NULL,
1194                channel_id   TEXT NOT NULL,
1195                epoch        INTEGER NOT NULL,
1196                channel_key  BLOB NOT NULL,
1197                sender       TEXT NOT NULL,
1198                received_at  INTEGER NOT NULL
1199            )",
1200            [],
1201        )
1202        .map_err(|e| format!("migration 83: {}", e))?;
1203        tx.execute(
1204            "CREATE INDEX IF NOT EXISTS idx_pending_channel_keys_scope \
1205             ON pending_channel_keys(community_id, channel_id)",
1206            [],
1207        )
1208        .map_err(|e| format!("migration 83: {}", e))?;
1209        Ok(())
1210    })?;
1211
1212    // CORD-04 §7: one Pin List per channel — the folded head's RAW content
1213    // (both self-describing forms), never a re-serialization, so republishing
1214    // carries the exact bytes and the byte cap judges what the wire carried.
1215    run_atomic_migration(conn, 84, "Per-channel pin lists", |tx| {
1216        tx.execute(
1217            "CREATE TABLE IF NOT EXISTS community_pins (
1218                community_id TEXT NOT NULL,
1219                channel_id   TEXT NOT NULL,
1220                content      TEXT NOT NULL,
1221                version      INTEGER NOT NULL,
1222                PRIMARY KEY (community_id, channel_id)
1223            )",
1224            [],
1225        )
1226        .map_err(|e| format!("migration 84: {}", e))?;
1227        Ok(())
1228    })?;
1229
1230    // Durable delete tombstones: a deleted message's row is GONE, so the ingest
1231    // dedup can't refuse a wrap a relay re-serves after ignoring our NIP-09 —
1232    // across a restart the in-session tombstone set is empty and the message
1233    // resurrects. One row per deleted message id, forever.
1234    run_atomic_migration(conn, 85, "Deleted-message tombstones", |tx| {
1235        tx.execute(
1236            "CREATE TABLE IF NOT EXISTS deleted_messages (
1237                event_id   TEXT PRIMARY KEY,
1238                deleted_at INTEGER NOT NULL
1239            )",
1240            [],
1241        )
1242        .map_err(|e| format!("migration 85: {}", e))?;
1243        Ok(())
1244    })?;
1245
1246    // CORD-02 §2 control_root split: the Control Plane's held address
1247    // (control_pk, encrypted hex) and the staff write secret (control_root,
1248    // encrypted blob) per v2 community. Nullable — a legacy epoch has neither,
1249    // a non-staff member holds only the address, and the v1 writer never
1250    // names these columns.
1251    run_atomic_migration(conn, 86, "Concord v2 control_root split columns", |tx| {
1252        for (col, ddl) in [("control_pk", "TEXT"), ("control_root", "BLOB")] {
1253            // ADD COLUMN is not idempotent; tolerate a re-run (duplicate column).
1254            let sql = format!("ALTER TABLE communities ADD COLUMN {col} {ddl}");
1255            if let Err(e) = tx.execute(&sql, []) {
1256                let msg = e.to_string();
1257                if !msg.contains("duplicate column name") {
1258                    return Err(format!("add communities.{col}: {msg}"));
1259                }
1260            }
1261        }
1262        Ok(())
1263    })?;
1264
1265    // The NIP-77 fingerprint read selects `wrapper_id` for a whole transport,
1266    // which `idx_processed_wrappers_window` can locate but not supply — so every
1267    // row costs a table lookup, and asking for sorted rows costs a temp B-tree
1268    // on top. Carrying `wrapper_id` in the index makes the read a covering scan
1269    // that arrives in negentropy's own sort order, which is most of the cost of
1270    // sealing a storage on a device that isn't a desktop.
1271    run_atomic_migration(conn, 87, "Covering index for negentropy fingerprints", |tx| {
1272        tx.execute(
1273            "CREATE INDEX IF NOT EXISTS idx_processed_wrappers_neg \
1274             ON processed_wrappers(transport, wrapper_created_at, wrapper_id)",
1275            [],
1276        )
1277        .map_err(|e| format!("migration 87: {}", e))?;
1278
1279        // `idx_processed_wrappers_window` is a strict prefix of the index above,
1280        // and every reader of this table also wants `wrapper_id` — the one
1281        // column it lacks. Keeping it would cost a second b-tree write per
1282        // ingested wrapper to serve queries the wider index already covers.
1283        tx.execute("DROP INDEX IF EXISTS idx_processed_wrappers_window", [])
1284            .map_err(|e| format!("migration 87 (drop superseded index): {}", e))?;
1285        Ok(())
1286    })?;
1287
1288    run_atomic_migration(conn, 88, "Persist status custom-emoji tags", |tx| {
1289        // Without this column the shortcode->URL pairs live only in memory,
1290        // so every boot renders raw :shortcodes: until a relay answers the
1291        // next status fetch — even when the emoji is cached on disk.
1292        tx.execute(
1293            "ALTER TABLE profiles ADD COLUMN status_emoji_tags TEXT NOT NULL DEFAULT ''",
1294            [],
1295        )
1296        .map_err(|e| format!("migration 88: {}", e))?;
1297        Ok(())
1298    })?;
1299
1300    // Migration 89: the policy store. Bytes, not columns — a policy is hashed
1301    // over the EXACT bytes it arrived as, and one day those same bytes ride a
1302    // control-plane edition to every device and client. Normalising it into
1303    // columns would mean re-serialising to evaluate, which changes the hash and
1304    // breaks the only identity the wire has.
1305    run_atomic_migration(conn, 89, "Community policy store", |tx| {
1306        tx.execute(
1307            "CREATE TABLE IF NOT EXISTS community_policies (
1308                community_id TEXT NOT NULL,
1309                policy_id    TEXT NOT NULL,
1310                bytes        TEXT NOT NULL,
1311                hash         TEXT NOT NULL,
1312                enabled      INTEGER NOT NULL DEFAULT 1,
1313                updated_at   INTEGER NOT NULL DEFAULT 0,
1314                PRIMARY KEY (community_id, policy_id)
1315            )",
1316            [],
1317        )
1318        .map_err(|e| format!("create community_policies: {e}"))?;
1319        Ok(())
1320    })?;
1321
1322    // The banlist's queryable home. It lived only as an encrypted blob on the
1323    // communities row, which SQL cannot compare against — so a banned author's
1324    // messages could not be excluded before LIMIT, and filtering them after it
1325    // returned short pages and broke backscroll.
1326    //
1327    // Plaintext by necessity: `events.npub` is plaintext, and a join needs both
1328    // sides in the same form. Deliberate — every message author is already stored
1329    // in the clear, so the list mainly hides members who never posted, and the
1330    // column it retires is one fewer for the at-rest sweep to forget.
1331    run_atomic_migration(conn, 90, "Queryable community banlist", |tx| {
1332        tx.execute(
1333            "CREATE TABLE IF NOT EXISTS community_bans (
1334                community_id TEXT NOT NULL,
1335                npub         TEXT NOT NULL,
1336                PRIMARY KEY (community_id, npub)
1337            )",
1338            [],
1339        )
1340        .map_err(|e| format!("create community_bans: {e}"))?;
1341        // The hot path is 'is THIS author banned in THIS community', which the
1342        // primary key already serves; this one serves 'list the bans' cheaply.
1343        tx.execute(
1344            "CREATE INDEX IF NOT EXISTS idx_community_bans_community ON community_bans(community_id)",
1345            [],
1346        )
1347        .map_err(|e| format!("index community_bans: {e}"))?;
1348        Ok(())
1349    })?;
1350
1351    // A chat row needs an identifier to ever be opened; one without is a phantom
1352    // that loads into the list and can never be addressed or removed.
1353    run_atomic_migration(conn, 91, "Drop chats with an empty identifier", |tx| {
1354        tx.execute(
1355            "DELETE FROM events WHERE chat_id IN (SELECT id FROM chats WHERE chat_identifier = '')",
1356            [],
1357        )
1358        .map_err(|e| format!("drop phantom chat events: {e}"))?;
1359        tx.execute("DELETE FROM chats WHERE chat_identifier = ''", [])
1360            .map_err(|e| format!("drop phantom chats: {e}"))?;
1361        Ok(())
1362    })?;
1363
1364    run_atomic_migration(conn, 92, "Create blossom_server_stats table", |tx| {
1365        crate::blossom_stats::migrate(tx)
1366    })?;
1367
1368    // Keyed by scope id rather than hung off a chat row: a community has no chat
1369    // row of its own, only its primary channel's, and storing it there is what
1370    // made "Mute Community" silence one channel.
1371    run_atomic_migration(conn, 93, "Per-scope notification preferences", |tx| {
1372        tx.execute(
1373            "CREATE TABLE IF NOT EXISTS notify_prefs (
1374                scope_id          TEXT PRIMARY KEY,
1375                level             INTEGER,
1376                mute_until        INTEGER NOT NULL DEFAULT 0,
1377                suppress_everyone INTEGER
1378            )",
1379            [],
1380        )
1381        .map_err(|e| format!("create notify_prefs: {e}"))?;
1382        // Existing mutes carry over as indefinite ones, so nobody's rooms get
1383        // loud on upgrade.
1384        tx.execute(
1385            "INSERT OR REPLACE INTO notify_prefs (scope_id, level, mute_until, suppress_everyone)
1386             SELECT chat_identifier, NULL, -1, NULL FROM chats WHERE muted = 1 AND chat_identifier != ''",
1387            [],
1388        )
1389        .map_err(|e| format!("seed notify_prefs from mutes: {e}"))?;
1390        Ok(())
1391    })?;
1392
1393    // The page query skipped rows by reading each one for its kind, then sorted ties on
1394    // received_at; the wider index answers both from the index alone.
1395    run_atomic_migration(conn, 94, "Chat page index covers received_at and kind", |tx| {
1396        tx.execute_batch(
1397            "DROP INDEX IF EXISTS idx_events_chat_time;
1398             CREATE INDEX IF NOT EXISTS idx_events_chat_page ON events(chat_id, created_at DESC, received_at DESC, kind);",
1399        )
1400        .map_err(|e| format!("rebuild chat page index: {e}"))
1401    })?;
1402
1403    // A fence, no schema change: from here an encrypted account may carry a per-account salt
1404    // (the `kdf` settings row), which an older build would ignore and then reject the right PIN.
1405    // The downgrade guard refuses such a build cleanly instead.
1406    run_atomic_migration(conn, 95, "Per-account key derivation salt", |_tx| Ok(()))?;
1407
1408    // DM wraps recorded only on their events row (written before the ledger) join the ledger, so
1409    // the ledger alone answers gift-wrap dedup. Timestamp 0 is the ledger's "unknown": the next
1410    // reconcile that re-serves the wrap backfills it, as for pre-timestamp rows.
1411    run_atomic_migration(conn, 96, "Ledger DM wrappers held only on events rows", |tx| {
1412        backfill_dm_wrapper_ledger(tx).map(|_| ())
1413    })?;
1414
1415    // Zero for every cached row, so a profile fetched before the flag existed stays hidden on
1416    // stream until its next fetch says otherwise.
1417    run_atomic_migration(conn, 97, "Profile stream consent", |tx| {
1418        tx.execute("ALTER TABLE profiles ADD COLUMN stream_consent INTEGER NOT NULL DEFAULT 0", [])
1419            .map_err(|e| format!("add profiles.stream_consent: {e}"))?;
1420        Ok(())
1421    })?;
1422
1423    // "Mark as Unread" from a chosen message: counts from that message, past own replies.
1424    run_atomic_migration(conn, 98, "Chat unread_from marker", |tx| {
1425        tx.execute("ALTER TABLE chats ADD COLUMN unread_from TEXT NOT NULL DEFAULT ''", [])
1426            .map_err(|e| format!("add chats.unread_from: {e}"))?;
1427        Ok(())
1428    })?;
1429
1430    run_atomic_migration(conn, 99, "Persisted inbox relay lists", |tx| crate::inbox_relays::migrate(tx))?;
1431
1432    run_atomic_migration(conn, 100, "Inbox relay list revisions", |tx| crate::inbox_relays::migrate_event_at(tx))?;
1433
1434    // When the relays were last asked for each profile, so an on-screen refresh survives a restart.
1435    run_atomic_migration(conn, 101, "Profile checked_at", |tx| {
1436        tx.execute("ALTER TABLE profiles ADD COLUMN checked_at INTEGER NOT NULL DEFAULT 0", [])
1437            .map_err(|e| format!("add profiles.checked_at: {e}"))?;
1438        Ok(())
1439    })?;
1440
1441    // What one read of a Mini App package found, by content hash, and which hash each file on
1442    // disk holds: a package is unzipped once, not on every listing and open.
1443    run_atomic_migration(conn, 102, "Mini App package metadata", |tx| {
1444        tx.execute_batch(
1445            "CREATE TABLE IF NOT EXISTS miniapp_meta (
1446                file_hash BLOB PRIMARY KEY,
1447                data TEXT NOT NULL
1448            );
1449            CREATE TABLE IF NOT EXISTS miniapp_files (
1450                path TEXT PRIMARY KEY,
1451                size INTEGER NOT NULL,
1452                modified INTEGER NOT NULL,
1453                file_hash BLOB NOT NULL
1454            );",
1455        )
1456        .map_err(|e| format!("create miniapp_meta: {e}"))
1457    })?;
1458
1459    // Concord v1's removal: finish each held flip, then drop every v1 community and its rooms.
1460    run_atomic_migration(conn, 103, "Remove Concord v1", |tx| {
1461        let plan = super::v1_purge::plan_v1_purge(tx)?;
1462        super::v1_purge::apply_v1_purge(tx, &plan)
1463    })?;
1464
1465    // Separate from 103 so a database is never left without the columns the purge reads.
1466    run_atomic_migration(conn, 104, "Drop Concord v1 columns", |tx| super::v1_purge::drop_v1_columns(tx))?;
1467
1468    // A held floor's author, so a same-version fork against it is judged authority first
1469    // (CORD-04 §1) even when the held edition itself is no longer served.
1470    run_atomic_migration(conn, 105, "Edition head author", |tx| {
1471        tx.execute("ALTER TABLE community_edition_heads ADD COLUMN author BLOB", [])
1472            .map_err(|e| format!("add community_edition_heads.author: {e}"))?;
1473        Ok(())
1474    })?;
1475
1476    // Which fold a floor belongs to, so an edition of one kind squatting another kind's
1477    // coordinate can't hold that entity to a version it never had.
1478    run_atomic_migration(conn, 106, "Edition head family", |tx| {
1479        tx.execute("ALTER TABLE community_edition_heads ADD COLUMN family TEXT", [])
1480            .map_err(|e| format!("add community_edition_heads.family: {e}"))?;
1481        Ok(())
1482    })?;
1483
1484    // CORD-03 §1: a restricted Channel's Writers ledger, the folded head's raw content.
1485    run_atomic_migration(conn, 107, "Writers ledgers", |tx| {
1486        tx.execute(
1487            "CREATE TABLE IF NOT EXISTS community_writers (
1488                community_id TEXT NOT NULL,
1489                channel_id   TEXT NOT NULL,
1490                content      TEXT NOT NULL,
1491                version      INTEGER NOT NULL,
1492                PRIMARY KEY (community_id, channel_id)
1493            )",
1494            [],
1495        )
1496        .map_err(|e| format!("migration 107: {e}"))?;
1497        Ok(())
1498    })?;
1499
1500    // CORD-03 §1: posts a restricted Channel's rules didn't stand behind on arrival, kept as the
1501    // wraps they came in so a later Roster or ledger can judge them again.
1502    run_atomic_migration(conn, 108, "Held community wraps", |tx| {
1503        tx.execute_batch(
1504            "CREATE TABLE IF NOT EXISTS community_held_wraps (
1505                wrap_id      TEXT PRIMARY KEY,
1506                community_id TEXT NOT NULL,
1507                channel_id   TEXT NOT NULL,
1508                wrap         TEXT NOT NULL,
1509                at_ms        INTEGER NOT NULL
1510            );
1511            CREATE INDEX IF NOT EXISTS idx_held_wraps_channel ON community_held_wraps(community_id, channel_id, at_ms);",
1512        )
1513        .map_err(|e| format!("migration 108: {e}"))?;
1514        Ok(())
1515    })?;
1516
1517    // Who wrote each held post, so no one author's flood holds a Channel's whole share.
1518    run_atomic_migration(conn, 109, "Held wrap authors", |tx| {
1519        tx.execute("ALTER TABLE community_held_wraps ADD COLUMN author TEXT NOT NULL DEFAULT ''", [])
1520            .map_err(|e| format!("migration 109: {e}"))?;
1521        Ok(())
1522    })?;
1523
1524    // Each held wrap's size, so the caps never read the wraps back to weigh them.
1525    run_atomic_migration(conn, 110, "Held wrap sizes", |tx| {
1526        tx.execute_batch(
1527            "ALTER TABLE community_held_wraps ADD COLUMN bytes INTEGER NOT NULL DEFAULT 0;
1528             UPDATE community_held_wraps SET bytes = length(wrap);",
1529        )
1530        .map_err(|e| format!("migration 110: {e}"))?;
1531        Ok(())
1532    })?;
1533
1534    // The Audit Log's moderation acts that leave no Control edition behind, as this device saw them.
1535    run_atomic_migration(conn, 111, "Community audit log", |tx| {
1536        tx.execute_batch(
1537            "CREATE TABLE IF NOT EXISTS community_audit_local (
1538                id           TEXT PRIMARY KEY,
1539                community_id TEXT NOT NULL,
1540                at_ms        INTEGER NOT NULL,
1541                entry        TEXT NOT NULL
1542            );
1543            CREATE INDEX IF NOT EXISTS idx_audit_local_community ON community_audit_local(community_id, at_ms);",
1544        )
1545        .map_err(|e| format!("migration 111: {e}"))?;
1546        Ok(())
1547    })?;
1548
1549    // A hide request for a message this device hasn't met yet: gift wraps are backdated, so a
1550    // sync can bring it before the message it names. Held until that message arrives.
1551    run_atomic_migration(conn, 112, "Pending DM deletions", |tx| {
1552        tx.execute_batch(
1553            "CREATE TABLE IF NOT EXISTS pending_deletions (
1554                target     TEXT PRIMARY KEY,
1555                requester  TEXT NOT NULL,
1556                expires_at INTEGER NOT NULL
1557            );",
1558        )
1559        .map_err(|e| format!("migration 112: {e}"))?;
1560        Ok(())
1561    })?;
1562
1563    run_atomic_migration(conn, 113, "Community wrap owner keys", |tx| {
1564        tx.execute_batch(
1565            "CREATE TABLE IF NOT EXISTS community_wrap_owners (
1566                outer_event_id TEXT PRIMARY KEY,
1567                message_id     TEXT NOT NULL,
1568                owner_secret   BLOB NOT NULL,
1569                relays         TEXT NOT NULL,
1570                created_at     INTEGER NOT NULL
1571            );
1572            CREATE INDEX IF NOT EXISTS idx_cwo_message_id
1573                ON community_wrap_owners(message_id);",
1574        )
1575        .map_err(|e| format!("migration 113: {e}"))?;
1576        Ok(())
1577    })?;
1578
1579    run_atomic_migration(conn, 114, "Community wrap scrub queue", |tx| {
1580        tx.execute_batch(
1581            "CREATE TABLE IF NOT EXISTS community_wrap_scrubs (
1582                message_id   TEXT PRIMARY KEY,
1583                community_id TEXT NOT NULL,
1584                queued_at    INTEGER NOT NULL
1585            );",
1586        )
1587        .map_err(|e| format!("migration 114: {e}"))?;
1588        Ok(())
1589    })?;
1590
1591    // A wallpaper from someone whose DM request waits: kept, unfetched, until it's accepted.
1592    run_atomic_migration(conn, 115, "Held DM wallpapers", |tx| {
1593        tx.execute_batch(
1594            "CREATE TABLE IF NOT EXISTS dm_held_wallpapers (
1595                chat_id    TEXT PRIMARY KEY,
1596                created_at INTEGER NOT NULL,
1597                payload    TEXT NOT NULL
1598            );",
1599        )
1600        .map_err(|e| format!("migration 115: {e}"))?;
1601        Ok(())
1602    })?;
1603
1604    // `downloaded` only says a local file matches the row's claimed hash, which a sender can
1605    // claim for a file they never sent. Reuse needs the row's own blob and key proven, so every
1606    // existing row starts unproven: an old file's next forward uploads it once more.
1607    run_atomic_migration(conn, 116, "Attachment blobs proven to open", |tx| {
1608        tx.execute(
1609            "ALTER TABLE attachments ADD COLUMN verified INTEGER NOT NULL DEFAULT 0",
1610            [],
1611        )
1612        .map_err(|e| format!("migration 116: {e}"))?;
1613        Ok(())
1614    })?;
1615
1616    // Files this account keeps, as the ciphertext they arrived as, under `media/`. Each row holds
1617    // the key and nonce that open its file (sealed under Local Encryption); `chunk_size` and
1618    // `have` are for media that streams in parts.
1619    run_atomic_migration(conn, 117, "Media store", |tx| {
1620        tx.execute_batch(
1621            "CREATE TABLE IF NOT EXISTS media_store (
1622                hash        TEXT PRIMARY KEY,
1623                file        TEXT NOT NULL,
1624                format      TEXT NOT NULL,
1625                key         TEXT NOT NULL,
1626                nonce       TEXT NOT NULL,
1627                blob_sha256 TEXT NOT NULL,
1628                pt_len      INTEGER NOT NULL,
1629                mime        TEXT NOT NULL DEFAULT '',
1630                origin      TEXT NOT NULL,
1631                created_at  INTEGER NOT NULL,
1632                used_at     INTEGER NOT NULL,
1633                missing_at  INTEGER,
1634                chunk_size  INTEGER,
1635                have        BLOB
1636            );",
1637        )
1638        .map_err(|e| format!("migration 117: {e}"))?;
1639        Ok(())
1640    })?;
1641
1642    // Files the user saved into one of Vector's folders: theirs, so nothing Vector clears takes them.
1643    run_atomic_migration(conn, 118, "Saved files", |tx| {
1644        tx.execute_batch("CREATE TABLE IF NOT EXISTS saved_files (path TEXT PRIMARY KEY);")
1645            .map_err(|e| format!("migration 118: {e}"))?;
1646        Ok(())
1647    })?;
1648
1649    // A Guestbook one row per event, so storing one is an insert rather than a rewrite of all of
1650    // them. `book` and `seq` are INTEGER PRIMARY KEYs because VACUUM keeps those. A community's
1651    // blob in `community_guestbook.events` moves in when it is next read (sealed blobs open only
1652    // once the account is unlocked); the cursor stays where it was.
1653    run_atomic_migration(conn, 119, "Guestbook events as rows", |tx| {
1654        tx.execute_batch(
1655            "CREATE TABLE IF NOT EXISTS community_guestbook_books (
1656                 book INTEGER PRIMARY KEY,
1657                 community_id TEXT NOT NULL UNIQUE
1658             );
1659             CREATE TABLE IF NOT EXISTS community_guestbook_events (
1660                 seq INTEGER PRIMARY KEY,
1661                 book INTEGER NOT NULL,
1662                 rumor_id BLOB NOT NULL,
1663                 body BLOB NOT NULL,
1664                 UNIQUE (book, rumor_id)
1665             );",
1666        )
1667        .map_err(|e| format!("migration 119: {e}"))?;
1668        Ok(())
1669    })?;
1670
1671    // The departures each member has been owed for, one sealed row per member, so a Leave writes
1672    // its member's row rather than every member's. A record still in `settings` moves in when next read.
1673    run_atomic_migration(conn, 120, "Owed departures as rows", |tx| {
1674        tx.execute_batch(
1675            "CREATE TABLE IF NOT EXISTS community_departures_seen (
1676                 seq INTEGER PRIMARY KEY,
1677                 book INTEGER NOT NULL,
1678                 body BLOB NOT NULL
1679             );
1680             CREATE INDEX IF NOT EXISTS community_departures_seen_book ON community_departures_seen (book);",
1681        )
1682        .map_err(|e| format!("migration 120: {e}"))?;
1683        Ok(())
1684    })?;
1685
1686    // Owed per-author take-backs, sealed: the settings rows they were kept in named the author in
1687    // the clear. Those move in when next read.
1688    run_atomic_migration(conn, 121, "Owed author take-backs sealed", |tx| {
1689        tx.execute_batch(
1690            "CREATE TABLE IF NOT EXISTS community_owed_authors (
1691                 seq INTEGER PRIMARY KEY,
1692                 book INTEGER NOT NULL,
1693                 channel_id TEXT NOT NULL,
1694                 body BLOB NOT NULL
1695             );
1696             CREATE INDEX IF NOT EXISTS community_owed_authors_book ON community_owed_authors (book, channel_id);",
1697        )
1698        .map_err(|e| format!("migration 121: {e}"))?;
1699        Ok(())
1700    })?;
1701
1702    // A member list reads which authors' posts are no sign of membership: a scan of every
1703    // post's tags without an index on each predicate.
1704    run_atomic_migration(conn, 122, "Index posts that are no sign of membership", |tx| {
1705        tx.execute_batch(
1706            "CREATE INDEX IF NOT EXISTS idx_events_unauthorized ON events(chat_id, npub) WHERE instr(tags, '[\"unauthorized\"]') > 0;
1707             CREATE INDEX IF NOT EXISTS idx_events_unauthorized_or_writer ON events(chat_id, npub) WHERE (instr(tags, '[\"unauthorized\"]') > 0 OR instr(tags, '[\"writer\"]') > 0);",
1708        )
1709        .map_err(|e| format!("migration 122: {e}"))?;
1710        Ok(())
1711    })?;
1712
1713    // One index per sign, each WHERE the very predicate the reader writes
1714    // (`db::community::HELD_POST`/`WRITER_POST`): the planner took the either-sign index for a
1715    // held-post read too, reading every writer post with it.
1716    run_atomic_migration(conn, 123, "Index each sign of a post that is no sign of membership", |tx| {
1717        tx.execute_batch(
1718            "DROP INDEX IF EXISTS idx_events_unauthorized_or_writer;
1719             CREATE INDEX IF NOT EXISTS idx_events_writer_post ON events(chat_id, npub) WHERE instr(tags, '[\"writer\"]') > 0;",
1720        )
1721        .map_err(|e| format!("migration 123: {e}"))?;
1722        Ok(())
1723    })?;
1724
1725    // The gift wraps that delivered a parked invite, space-separated hex ids: a decline asks
1726    // our relays to delete each, as the `p`-tagged recipient.
1727    run_atomic_migration(conn, 124, "Pending invite wrap ids", |tx| {
1728        tx.execute("ALTER TABLE pending_community_invites ADD COLUMN wrap_ids TEXT NOT NULL DEFAULT ''", [])
1729            .map_err(|e| format!("migration 124: {e}"))?;
1730        Ok(())
1731    })?;
1732
1733    // When a parked invite was sent (its rumor's time, unix secs; 0 = parked before this): its
1734    // lifetime runs from then, as the ingest rule's does.
1735    run_atomic_migration(conn, 125, "Pending invite send time", |tx| {
1736        tx.execute("ALTER TABLE pending_community_invites ADD COLUMN sent_at INTEGER NOT NULL DEFAULT 0", [])
1737            .map_err(|e| format!("migration 125: {e}"))?;
1738        Ok(())
1739    })?;
1740
1741    // Every Control wrap this device has read, per plane view, so a sync asks each relay only for
1742    // what it lacks. A NULL body is a wrap that was refused: held by id, so it isn't asked for again.
1743    run_atomic_migration(conn, 126, "Control wraps", |tx| {
1744        tx.execute_batch(
1745            "CREATE TABLE IF NOT EXISTS community_control_wraps (
1746                community_id TEXT NOT NULL,
1747                view         BLOB NOT NULL,
1748                wrap_id      BLOB NOT NULL,
1749                created_at   INTEGER NOT NULL,
1750                wrap         BLOB,
1751                rules        INTEGER NOT NULL,
1752                judged_at    INTEGER NOT NULL,
1753                PRIMARY KEY (community_id, view, wrap_id)
1754            );
1755            CREATE INDEX IF NOT EXISTS idx_control_wraps_page
1756                ON community_control_wraps(community_id, view, created_at DESC, wrap_id DESC) WHERE wrap IS NOT NULL;",
1757        )
1758        .map_err(|e| format!("migration 126: {e}"))?;
1759        Ok(())
1760    })?;
1761
1762    // The Guestbook wraps this device has read, by id: what a sync tells each relay it holds.
1763    // `rules` 0 is a wrap whose entry is in the Guestbook; any other is one refused under them.
1764    run_atomic_migration(conn, 127, "Guestbook wraps", |tx| {
1765        tx.execute_batch(
1766            "CREATE TABLE IF NOT EXISTS community_guestbook_wraps (
1767                community_id TEXT NOT NULL,
1768                plane        BLOB NOT NULL,
1769                wrap_id      BLOB NOT NULL,
1770                created_at   INTEGER NOT NULL,
1771                rules        INTEGER NOT NULL,
1772                judged_at    INTEGER NOT NULL,
1773                PRIMARY KEY (community_id, plane, wrap_id)
1774            ) WITHOUT ROWID;",
1775        )
1776        .map_err(|e| format!("migration 127: {e}"))?;
1777        Ok(())
1778    })?;
1779
1780    Ok(())
1781}
1782
1783/// Copies every DM events-row wrapper id into `processed_wrappers` (transport 0); returns how
1784/// many ledger rows it added. Community rows are left alone: Concord dedups messages by the
1785/// events column by design.
1786pub(crate) fn backfill_dm_wrapper_ledger(conn: &rusqlite::Connection) -> Result<usize, String> {
1787    let mut read = conn
1788        .prepare(
1789            "SELECT e.wrapper_event_id FROM events e LEFT JOIN chats c ON c.id = e.chat_id \
1790             WHERE e.wrapper_event_id IS NOT NULL AND length(e.wrapper_event_id) = 64 \
1791             AND c.chat_type IS NOT 2",
1792        )
1793        .map_err(|e| format!("prepare wrapper backfill read: {e}"))?;
1794    let mut write = conn
1795        .prepare(
1796            "INSERT OR IGNORE INTO processed_wrappers (wrapper_id, wrapper_created_at, transport) \
1797             VALUES (?1, 0, 0)",
1798        )
1799        .map_err(|e| format!("prepare wrapper backfill write: {e}"))?;
1800    let mut rows = read.query([]).map_err(|e| format!("read wrapper backfill: {e}"))?;
1801    let mut added = 0;
1802    while let Some(row) = rows.next().map_err(|e| format!("read wrapper backfill row: {e}"))? {
1803        let Ok(hex) = row.get_ref(0).and_then(|v| v.as_str().map_err(Into::into)) else {
1804            continue;
1805        };
1806        let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(hex) else {
1807            continue;
1808        };
1809        added += write
1810            .execute(rusqlite::params![&id[..]])
1811            .map_err(|e| format!("write wrapper backfill: {e}"))?;
1812    }
1813    Ok(added)
1814}
1815
1816#[cfg(test)]
1817mod tests {
1818    use super::HIGHEST_MIGRATION_ID;
1819
1820    fn migrated() -> rusqlite::Connection {
1821        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
1822        conn.execute_batch(super::SQL_SCHEMA).unwrap();
1823        super::run_migrations(&mut conn).unwrap();
1824        conn
1825    }
1826
1827    fn hex(b: u8) -> String {
1828        format!("{b:02x}").repeat(32)
1829    }
1830
1831    fn event(conn: &rusqlite::Connection, id: &str, chat: i64, wrapper: Option<&str>) {
1832        conn.execute(
1833            "INSERT INTO events (id, kind, chat_id, content, created_at, received_at, wrapper_event_id) \
1834             VALUES (?1, 14, ?2, '', 1, 1, ?3)",
1835            rusqlite::params![id, chat, wrapper],
1836        )
1837        .unwrap();
1838    }
1839
1840    fn ledger(conn: &rusqlite::Connection) -> Vec<(Vec<u8>, i64, i64)> {
1841        conn.prepare("SELECT wrapper_id, wrapper_created_at, transport FROM processed_wrappers ORDER BY wrapper_id")
1842            .unwrap()
1843            .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
1844            .unwrap()
1845            .map(Result::unwrap)
1846            .collect()
1847    }
1848
1849    /// Every shape of events row the backfill can meet, run through the real migration runner.
1850    #[test]
1851    fn the_wrapper_backfill_ledgers_exactly_the_dm_wrappers() {
1852        let mut conn = migrated();
1853        conn.execute_batch(
1854            "INSERT INTO chats (id, chat_identifier, chat_type, participants, created_at) VALUES
1855                (1, 'npub1dm', 0, '[]', 0), (2, 'channel', 2, '[]', 0);",
1856        )
1857        .unwrap();
1858        conn.execute_batch("PRAGMA foreign_keys = OFF;").unwrap();
1859        event(&conn, "m1", 1, Some(&hex(0x11)));                    // legacy DM: ledgered
1860        event(&conn, "m2", 1, Some(&hex(0xAB).to_uppercase()));     // uppercase hex: ledgered
1861        event(&conn, "m3", 1, Some(&hex(0x22)));                    // already ledgered: untouched
1862        event(&conn, "m4", 2, Some(&hex(0x33)));                    // community: Concord's, skipped
1863        event(&conn, "m5", 99, Some(&hex(0x44)));                   // orphan chat: treated as DM
1864        event(&conn, "m6", 1, Some("zz".repeat(32).as_str()));      // not hex: skipped
1865        event(&conn, "m7", 1, Some("abc"));                         // wrong length: skipped
1866        event(&conn, "m8", 1, Some(""));                            // empty: skipped
1867        event(&conn, "m9", 1, None);                                // no wrapper: skipped
1868        event(&conn, "m10", 1, Some(&hex(0x11)));                   // duplicate wrapper: one row
1869        conn.execute(
1870            "INSERT INTO processed_wrappers (wrapper_id, wrapper_created_at, transport) VALUES (?1, 777, 0)",
1871            [&[0x22u8; 32][..]],
1872        )
1873        .unwrap();
1874        conn.execute("DELETE FROM schema_migrations WHERE id = 96", []).unwrap();
1875
1876        super::run_migrations(&mut conn).unwrap();
1877
1878        assert_eq!(
1879            ledger(&conn),
1880            vec![
1881                (vec![0x11; 32], 0, 0),
1882                (vec![0x22; 32], 777, 0),
1883                (vec![0x44; 32], 0, 0),
1884                (vec![0xAB; 32], 0, 0),
1885            ],
1886        );
1887        assert!(super::migration_applied(&conn, 96));
1888
1889        // Applied once: a later run never re-reads events.
1890        event(&conn, "m11", 1, Some(&hex(0x55)));
1891        super::run_migrations(&mut conn).unwrap();
1892        assert_eq!(ledger(&conn).len(), 4);
1893    }
1894
1895    #[test]
1896    fn the_wrapper_backfill_is_a_no_op_on_a_fresh_database() {
1897        let conn = migrated();
1898        assert!(super::migration_applied(&conn, 96));
1899        assert!(ledger(&conn).is_empty());
1900        assert_eq!(super::backfill_dm_wrapper_ledger(&conn).unwrap(), 0);
1901    }
1902
1903    /// The backfill and the ledger's own writer agree on the id encoding, so the dedup lookup
1904    /// that replaces the events-column check finds a backfilled wrap.
1905    #[test]
1906    fn a_backfilled_wrapper_is_found_by_the_dedup_lookup() {
1907        let conn = migrated();
1908        conn.execute_batch(
1909            "INSERT INTO chats (id, chat_identifier, chat_type, participants, created_at) VALUES (1, 'npub1dm', 0, '[]', 0);",
1910        )
1911        .unwrap();
1912        let id = [0x5Au8; 32];
1913        event(&conn, "m1", 1, Some(&crate::simd::hex::bytes_to_hex_32(&id)));
1914        assert_eq!(super::backfill_dm_wrapper_ledger(&conn).unwrap(), 1);
1915        let found: bool = conn
1916            .query_row("SELECT EXISTS(SELECT 1 FROM processed_wrappers WHERE wrapper_id = ?1)", [&id[..]], |r| r.get(0))
1917            .unwrap();
1918        assert!(found);
1919        assert_eq!(super::backfill_dm_wrapper_ledger(&conn).unwrap(), 0, "idempotent");
1920    }
1921
1922    /// Parses this very file so the constant cannot drift from `run_migrations`.
1923    /// Without it, adding a migration and forgetting the bump would silently
1924    /// re-open the downgrade hole the constant exists to close.
1925    #[test]
1926    fn highest_migration_id_matches_the_runner() {
1927        let src = include_str!("schema.rs");
1928        let mut highest = 0u32;
1929        let mut seen = 0usize;
1930
1931        for (at, _) in src.match_indices("run_atomic_migration(") {
1932            let tail = src[at + "run_atomic_migration(".len()..].trim_start();
1933            // Skips this test's own mention of the name, which is not a call.
1934            let Some(args) = tail.strip_prefix("conn,") else {
1935                continue;
1936            };
1937            let id: String = args
1938                .trim_start()
1939                .chars()
1940                .take_while(char::is_ascii_digit)
1941                .collect();
1942            if let Ok(id) = id.parse::<u32>() {
1943                seen += 1;
1944                highest = highest.max(id);
1945            }
1946        }
1947
1948        assert!(seen > 0, "parsed no migrations; the call shape must have changed");
1949        assert_eq!(
1950            HIGHEST_MIGRATION_ID, highest,
1951            "bump HIGHEST_MIGRATION_ID to {highest} when adding a migration"
1952        );
1953    }
1954}