hitchmark-core 0.5.0

Core library for hook:// URI links, stable bookmark IDs, and purple-number paragraph addressing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! SQLite-backed link storage.
//!
//! Manages bidirectional links, bookmarks, and purple-number mappings.
//!
//! # Robustness
//!
//! - **WAL mode**: enables concurrent reads and one writer without lock errors.
//! - **busy_timeout**: retries on lock contention for up to 5 seconds.
//! - **Schema versioning**: the `schema_version` table lets future migrations
//!   detect and reject incompatible databases gracefully.
//! - **Duplicate links**: `create_link` returns `Error::LinkAlreadyExists`
//!   instead of exposing a raw UNIQUE constraint violation.

use crate::error::{Error, Result};
use rusqlite::Connection;
use std::path::Path;

/// Current schema version. Increment when making breaking schema changes.
const SCHEMA_VERSION: u32 = 2;

/// A bidirectional link between two resources
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Link {
    /// Source URI
    pub source: String,
    /// Target URI
    pub target: String,
    /// Optional note
    pub note: Option<String>,
    /// Created timestamp (RFC 3339)
    pub created_at: String,
}

/// A stored bookmark — a stable UUID mapping to a file path.
///
/// Bookmark URIs (`hook://bookmark/<uuid>`) remain valid even if the file is
/// renamed or moved, as long as the user updates the bookmark afterward.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Bookmark {
    /// UUID identifier (the UUID portion of `hook://bookmark/<uuid>`)
    pub id: String,
    /// Absolute path to the file at time of last update
    pub file_path: String,
    /// Created timestamp (RFC 3339)
    pub created_at: String,
}

/// SQLite-backed store for links and metadata
pub struct LinkStore {
    conn: Connection,
}

impl LinkStore {
    /// Open or create a LinkStore at the given path.
    ///
    /// Applies WAL journal mode, busy_timeout, and runs schema migrations.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let conn = Connection::open(path)?;

        // Retry on lock for up to 5 seconds instead of failing immediately
        conn.busy_timeout(std::time::Duration::from_secs(5))?;

        // WAL mode: allows concurrent reads + one writer without lock errors
        conn.pragma_update(None, "journal_mode", "WAL")?;

        // Enforce foreign key constraints
        conn.pragma_update(None, "foreign_keys", "ON")?;

        let store = LinkStore { conn };
        store.run_migrations()?;
        Ok(store)
    }

    fn run_migrations(&self) -> Result<()> {
        // Ensure the version table exists before reading it
        self.conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS schema_version (
                version INTEGER NOT NULL
            );",
        )?;

        let current_version: Option<u32> = self
            .conn
            .query_row(
                "SELECT version FROM schema_version LIMIT 1",
                [],
                |row| row.get(0),
            )
            .ok();

        match current_version {
            None => {
                // Fresh database — apply all schema migrations and record current version
                self.apply_v1_schema()?;
                self.apply_v2_schema()?;
                self.conn.execute(
                    "INSERT INTO schema_version (version) VALUES (?)",
                    [SCHEMA_VERSION],
                )?;
            }
            Some(1) => {
                // Upgrade from v1 → v2: add bookmarks table
                self.apply_v2_schema()?;
                self.conn
                    .execute("UPDATE schema_version SET version = ?", [SCHEMA_VERSION])?;
            }
            Some(v) if v == SCHEMA_VERSION => {
                // Up to date — nothing to do
            }
            Some(v) if v < SCHEMA_VERSION => {
                // Gap between known versions — shouldn't happen with current code
                let _ = v;
            }
            Some(v) => {
                // Database was written by a newer version of hitchmark
                return Err(Error::SchemaTooNew {
                    found: v,
                    supported: SCHEMA_VERSION,
                });
            }
        }

        Ok(())
    }

    fn apply_v1_schema(&self) -> Result<()> {
        self.conn.execute_batch(
            r#"
            CREATE TABLE IF NOT EXISTS links (
                id INTEGER PRIMARY KEY,
                source TEXT NOT NULL,
                target TEXT NOT NULL,
                note TEXT,
                created_at TEXT NOT NULL,
                UNIQUE(source, target)
            );

            CREATE TABLE IF NOT EXISTS purple_numbers (
                id INTEGER PRIMARY KEY,
                doc_path TEXT NOT NULL,
                para_id TEXT NOT NULL,
                content_hash TEXT NOT NULL,
                UNIQUE(doc_path, para_id)
            );

            CREATE INDEX IF NOT EXISTS idx_links_source ON links(source);
            CREATE INDEX IF NOT EXISTS idx_links_target ON links(target);
            CREATE INDEX IF NOT EXISTS idx_purple_doc ON purple_numbers(doc_path);
            "#,
        )?;
        Ok(())
    }

    fn apply_v2_schema(&self) -> Result<()> {
        self.conn.execute_batch(
            r#"
            CREATE TABLE IF NOT EXISTS bookmarks (
                id TEXT PRIMARY KEY,
                file_path TEXT NOT NULL,
                created_at TEXT NOT NULL
            );

            CREATE INDEX IF NOT EXISTS idx_bookmarks_path ON bookmarks(file_path);
            "#,
        )?;
        Ok(())
    }

    /// Create a bidirectional link.
    ///
    /// Returns `Error::LinkAlreadyExists` if the pair is already linked.
    pub fn create_link(&self, source: &str, target: &str, note: Option<&str>) -> Result<()> {
        let now = chrono::Utc::now().to_rfc3339();
        let result = self.conn.execute(
            "INSERT INTO links (source, target, note, created_at) VALUES (?, ?, ?, ?)",
            rusqlite::params![source, target, note, now],
        );

        match result {
            Ok(_) => Ok(()),
            Err(rusqlite::Error::SqliteFailure(e, _))
                if e.code == rusqlite::ErrorCode::ConstraintViolation =>
            {
                Err(Error::LinkAlreadyExists {
                    uri_a: source.to_string(),
                    uri_b: target.to_string(),
                })
            }
            Err(e) => Err(Error::DatabaseError(e)),
        }
    }

    /// List all links for a URI (bidirectional).
    pub fn list_links(&self, uri: &str) -> Result<Vec<Link>> {
        let mut stmt = self.conn.prepare(
            "SELECT source, target, note, created_at FROM links WHERE source = ? OR target = ?",
        )?;
        let links = stmt.query_map(rusqlite::params![uri, uri], |row| {
            Ok(Link {
                source: row.get(0)?,
                target: row.get(1)?,
                note: row.get(2)?,
                created_at: row.get(3)?,
            })
        })?;

        let mut result = Vec::new();
        for link in links {
            result.push(link?);
        }
        Ok(result)
    }

    /// List every link in the store (used for export).
    pub fn list_all_links(&self) -> Result<Vec<Link>> {
        let mut stmt = self
            .conn
            .prepare("SELECT source, target, note, created_at FROM links ORDER BY created_at")?;
        let rows = stmt.query_map([], |row| {
            Ok(Link {
                source: row.get(0)?,
                target: row.get(1)?,
                note: row.get(2)?,
                created_at: row.get(3)?,
            })
        })?;
        rows.map(|r| r.map_err(Error::DatabaseError)).collect()
    }

    /// Delete a link (removes regardless of which end is source/target).
    pub fn delete_link(&self, source: &str, target: &str) -> Result<()> {
        self.conn.execute(
            "DELETE FROM links WHERE (source = ? AND target = ?) OR (source = ? AND target = ?)",
            rusqlite::params![source, target, target, source],
        )?;
        Ok(())
    }

    /// Return the number of links in the store (useful for diagnostics).
    pub fn link_count(&self) -> Result<u64> {
        let count: i64 =
            self.conn
                .query_row("SELECT COUNT(*) FROM links", [], |row| row.get(0))?;
        Ok(count as u64)
    }

    /// Scan for links that reference file URIs pointing to non-existent files.
    ///
    /// Returns `(stale_links, total_checked)`. Only `hook://file/` URIs are
    /// checked — bookmark and x-callback-url URIs are skipped.
    pub fn scan_stale_links(&self) -> Result<(Vec<Link>, usize)> {
        let all_links: Vec<Link> = {
            let mut stmt = self
                .conn
                .prepare("SELECT source, target, note, created_at FROM links")?;
            let rows = stmt.query_map([], |row| {
                Ok(Link {
                    source: row.get(0)?,
                    target: row.get(1)?,
                    note: row.get(2)?,
                    created_at: row.get(3)?,
                })
            })?;
            rows.filter_map(|r| r.ok()).collect()
        };
        let total = all_links.len();
        let stale = all_links
            .into_iter()
            .filter(|link| uri_file_missing(&link.source) || uri_file_missing(&link.target))
            .collect();
        Ok((stale, total))
    }

    /// Scan for bookmarks whose `file_path` no longer exists on disk.
    pub fn scan_stale_bookmarks(&self) -> Result<(Vec<Bookmark>, usize)> {
        let all = self.list_bookmarks()?;
        let total = all.len();
        let stale = all
            .into_iter()
            .filter(|b| !std::path::Path::new(&b.file_path).exists())
            .collect();
        Ok((stale, total))
    }

    /// Delete links whose source **or** target URI exactly matches any entry in `uris`.
    pub fn delete_links_involving(&self, uris: &[String]) -> Result<usize> {
        let mut removed = 0;
        for uri in uris {
            removed += self.conn.execute(
                "DELETE FROM links WHERE source = ? OR target = ?",
                rusqlite::params![uri, uri],
            )?;
        }
        Ok(removed)
    }

    /// Delete bookmarks by UUID.
    pub fn delete_bookmarks_by_ids(&self, ids: &[String]) -> Result<usize> {
        let mut removed = 0;
        for id in ids {
            removed += self
                .conn
                .execute("DELETE FROM bookmarks WHERE id = ?", rusqlite::params![id])?;
        }
        Ok(removed)
    }

    /// Store a stable bookmark for a file path and return its UUID.
    ///
    /// If a bookmark for this path already exists, the existing UUID is returned.
    /// This makes `hk file --bookmark` idempotent.
    pub fn store_bookmark(&self, file_path: &str) -> Result<String> {
        // Check for an existing bookmark for this path
        let existing: Option<String> = self
            .conn
            .query_row(
                "SELECT id FROM bookmarks WHERE file_path = ? LIMIT 1",
                rusqlite::params![file_path],
                |row| row.get(0),
            )
            .ok();

        if let Some(id) = existing {
            return Ok(id);
        }

        // Generate a new UUID v4
        let id = new_uuid_v4();
        let now = chrono::Utc::now().to_rfc3339();
        self.conn.execute(
            "INSERT INTO bookmarks (id, file_path, created_at) VALUES (?, ?, ?)",
            rusqlite::params![id, file_path, now],
        )?;
        Ok(id)
    }

    /// Import a bookmark with a specific UUID (used by `hk import`).
    ///
    /// Returns `Error::BookmarkAlreadyExists` if the UUID is already present,
    /// allowing callers to silently skip duplicates.
    pub fn import_bookmark(&self, id: &str, file_path: &str) -> Result<()> {
        let exists: bool = self
            .conn
            .query_row(
                "SELECT 1 FROM bookmarks WHERE id = ?",
                rusqlite::params![id],
                |_| Ok(true),
            )
            .unwrap_or(false);

        if exists {
            return Err(Error::BookmarkAlreadyExists { id: id.to_string() });
        }

        let now = chrono::Utc::now().to_rfc3339();
        self.conn.execute(
            "INSERT INTO bookmarks (id, file_path, created_at) VALUES (?, ?, ?)",
            rusqlite::params![id, file_path, now],
        )?;
        Ok(())
    }

    /// Look up the file path for a bookmark UUID.
    ///
    /// Returns `None` when the UUID is not found (bookmark was never created or
    /// the database has been reset).
    pub fn lookup_bookmark(&self, id: &str) -> Result<Option<String>> {
        let path: Option<String> = self
            .conn
            .query_row(
                "SELECT file_path FROM bookmarks WHERE id = ?",
                rusqlite::params![id],
                |row| row.get(0),
            )
            .ok();
        Ok(path)
    }

    /// Update the file path for an existing bookmark.
    ///
    /// Returns `false` when `id` is not found.
    pub fn update_bookmark_path(&self, id: &str, new_path: &str) -> Result<bool> {
        let rows = self.conn.execute(
            "UPDATE bookmarks SET file_path = ? WHERE id = ?",
            rusqlite::params![new_path, id],
        )?;
        Ok(rows > 0)
    }

    /// List all stored bookmarks.
    pub fn list_bookmarks(&self) -> Result<Vec<Bookmark>> {
        let mut stmt = self
            .conn
            .prepare("SELECT id, file_path, created_at FROM bookmarks ORDER BY created_at")?;
        let bookmarks = stmt.query_map([], |row| {
            Ok(Bookmark {
                id: row.get(0)?,
                file_path: row.get(1)?,
                created_at: row.get(2)?,
            })
        })?;
        let mut result = Vec::new();
        for b in bookmarks {
            result.push(b?);
        }
        Ok(result)
    }
}

/// Returns true if `uri` is a `hook://file/` URI pointing to a file that no longer exists.
/// Non-file URIs (bookmark, x-callback-url) always return false.
fn uri_file_missing(uri: &str) -> bool {
    use crate::uri::{HookUri, UriType};
    match HookUri::parse(uri) {
        Ok(h) => match h.uri_type {
            UriType::File(path) => !path.exists(),
            _ => false,
        },
        Err(_) => false,
    }
}

/// Generate a UUID v4 (random) without pulling in the `uuid` crate.
///
/// Uses `std::collections::hash_map::DefaultHasher` seeded from system time
/// plus a thread-local counter for reasonable uniqueness. For production use
/// that requires cryptographic UUIDs, add the `uuid` crate with the `v4` feature.
fn new_uuid_v4() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let t = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos() as u64;
    let c = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let a = t.wrapping_mul(6364136223846793005).wrapping_add(c ^ 0xdeadbeefcafe);
    let b = c.wrapping_mul(2862933555777941757).wrapping_add(t ^ 0x1234567890abcdef);

    // Standard UUID layout: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
    // p0: 8 hex (32 bits), p1: 4 hex (16 bits), p2: 4 hex (version nibble forced to 4)
    // p3: 4 hex (variant bits 10xx forced), p4: 12 hex (48 bits)
    let p0 = (a >> 32) as u32;
    let p1 = ((a >> 16) & 0xffff) as u16;
    let p2 = 0x4000u16 | ((a & 0x0fff) as u16);
    let p3 = 0x8000u16 | (((b >> 48) & 0x3fff) as u16);
    let p4 = b & 0x0000_ffff_ffff_ffff;
    format!("{p0:08x}-{p1:04x}-{p2:04x}-{p3:04x}-{p4:012x}")
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::Engine as _;
    use tempfile::TempDir;

    fn make_store() -> (TempDir, LinkStore) {
        let tmpdir = TempDir::new().unwrap();
        let store_path = tmpdir.path().join("test.db");
        let store = LinkStore::open(&store_path).unwrap();
        (tmpdir, store)
    }

    #[test]
    fn test_store_roundtrip() {
        let (_dir, store) = make_store();
        store
            .create_link("hook://file/a", "hook://file/b", Some("test note"))
            .unwrap();

        let links = store.list_links("hook://file/a").unwrap();
        assert_eq!(links.len(), 1);
        assert_eq!(links[0].note, Some("test note".to_string()));
    }

    #[test]
    fn test_bidirectional_query() {
        let (_dir, store) = make_store();
        store
            .create_link("hook://file/a", "hook://file/b", None)
            .unwrap();

        // Query from either end should find the link
        assert_eq!(store.list_links("hook://file/a").unwrap().len(), 1);
        assert_eq!(store.list_links("hook://file/b").unwrap().len(), 1);
        assert_eq!(store.list_links("hook://file/c").unwrap().len(), 0);
    }

    #[test]
    fn test_duplicate_link_returns_friendly_error() {
        let (_dir, store) = make_store();
        store
            .create_link("hook://file/a", "hook://file/b", None)
            .unwrap();

        let result = store.create_link("hook://file/a", "hook://file/b", None);
        assert!(matches!(result, Err(Error::LinkAlreadyExists { .. })));

        // The error message should be human-readable
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("already exists"));
    }

    #[test]
    fn test_delete_link() {
        let (_dir, store) = make_store();
        store
            .create_link("hook://file/a", "hook://file/b", None)
            .unwrap();
        assert_eq!(store.list_links("hook://file/a").unwrap().len(), 1);

        store
            .delete_link("hook://file/a", "hook://file/b")
            .unwrap();
        assert_eq!(store.list_links("hook://file/a").unwrap().len(), 0);
    }

    #[test]
    fn test_delete_link_symmetric() {
        // delete_link should work regardless of argument order
        let (_dir, store) = make_store();
        store
            .create_link("hook://file/a", "hook://file/b", None)
            .unwrap();

        store
            .delete_link("hook://file/b", "hook://file/a") // reversed
            .unwrap();
        assert_eq!(store.list_links("hook://file/a").unwrap().len(), 0);
    }

    #[test]
    fn test_link_count() {
        let (_dir, store) = make_store();
        assert_eq!(store.link_count().unwrap(), 0);
        store
            .create_link("hook://file/a", "hook://file/b", None)
            .unwrap();
        store
            .create_link("hook://file/a", "hook://file/c", None)
            .unwrap();
        assert_eq!(store.link_count().unwrap(), 2);
    }

    #[test]
    fn test_schema_version_persists() {
        let tmpdir = TempDir::new().unwrap();
        let store_path = tmpdir.path().join("versioned.db");

        // Open once — creates schema
        {
            let _store = LinkStore::open(&store_path).unwrap();
        }

        // Open again — should detect existing schema and not re-run migrations
        let store = LinkStore::open(&store_path).unwrap();
        assert_eq!(store.link_count().unwrap(), 0);
    }

    #[test]
    fn test_schema_too_new_rejected() {
        let tmpdir = TempDir::new().unwrap();
        let store_path = tmpdir.path().join("future.db");

        // Manually write a future schema version
        {
            let conn = Connection::open(&store_path).unwrap();
            conn.execute_batch(
                "CREATE TABLE schema_version (version INTEGER NOT NULL);
                 INSERT INTO schema_version VALUES (9999);",
            )
            .unwrap();
        }

        let result = LinkStore::open(&store_path);
        assert!(matches!(result, Err(Error::SchemaTooNew { .. })));
    }

    #[test]
    fn test_bookmark_create_and_lookup() {
        let (_dir, store) = make_store();
        let id = store.store_bookmark("/Users/alice/notes.md").unwrap();
        assert!(!id.is_empty());
        let path = store.lookup_bookmark(&id).unwrap();
        assert_eq!(path, Some("/Users/alice/notes.md".to_string()));
    }

    #[test]
    fn test_bookmark_create_is_idempotent() {
        let (_dir, store) = make_store();
        let id1 = store.store_bookmark("/Users/alice/notes.md").unwrap();
        let id2 = store.store_bookmark("/Users/alice/notes.md").unwrap();
        assert_eq!(id1, id2, "Same path should return same bookmark UUID");
    }

    #[test]
    fn test_bookmark_lookup_unknown_returns_none() {
        let (_dir, store) = make_store();
        let result = store
            .lookup_bookmark("00000000-0000-4000-8000-000000000000")
            .unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_bookmark_update_path() {
        let (_dir, store) = make_store();
        let id = store.store_bookmark("/old/path.md").unwrap();
        let updated = store.update_bookmark_path(&id, "/new/path.md").unwrap();
        assert!(updated);
        let path = store.lookup_bookmark(&id).unwrap();
        assert_eq!(path, Some("/new/path.md".to_string()));
    }

    #[test]
    fn test_bookmark_update_unknown_returns_false() {
        let (_dir, store) = make_store();
        let updated = store
            .update_bookmark_path("00000000-0000-4000-8000-000000000000", "/foo.md")
            .unwrap();
        assert!(!updated);
    }

    #[test]
    fn test_bookmark_list() {
        let (_dir, store) = make_store();
        store.store_bookmark("/file/a.md").unwrap();
        store.store_bookmark("/file/b.md").unwrap();
        let bookmarks = store.list_bookmarks().unwrap();
        assert_eq!(bookmarks.len(), 2);
    }

    #[test]
    fn test_bookmark_uuid_format() {
        let (_dir, store) = make_store();
        let id = store.store_bookmark("/any/path.md").unwrap();
        // Must match xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
        let parts: Vec<&str> = id.split('-').collect();
        assert_eq!(parts.len(), 5, "UUID must have 5 hyphen-separated parts");
        assert_eq!(parts[0].len(), 8);
        assert_eq!(parts[1].len(), 4);
        assert_eq!(parts[2].len(), 4);
        assert_eq!(parts[3].len(), 4);
        // parts[4] is the last segment: 4 chars + 8 chars = 12 hex chars
        assert_eq!(parts[4].len(), 12);
    }

    #[test]
    fn test_schema_v1_migrates_to_v2() {
        // Simulate an existing v1 database (no bookmarks table)
        let tmpdir = TempDir::new().unwrap();
        let store_path = tmpdir.path().join("v1.db");
        {
            let conn = Connection::open(&store_path).unwrap();
            conn.execute_batch(
                "CREATE TABLE schema_version (version INTEGER NOT NULL);
                 INSERT INTO schema_version VALUES (1);
                 CREATE TABLE links (
                     id INTEGER PRIMARY KEY,
                     source TEXT NOT NULL,
                     target TEXT NOT NULL,
                     note TEXT,
                     created_at TEXT NOT NULL,
                     UNIQUE(source, target)
                 );",
            )
            .unwrap();
        }
        // Opening should auto-migrate and add the bookmarks table
        let store = LinkStore::open(&store_path).unwrap();
        // Can now create a bookmark
        let id = store.store_bookmark("/migrated/file.md").unwrap();
        assert!(!id.is_empty());
    }

    #[test]
    fn test_scan_stale_links_all_live() {
        // All URIs are non-file (bookmark/x-callback-url) — nothing stale
        let (_dir, store) = make_store();
        store
            .create_link("hook://bookmark/abc-123", "hook://bookmark/def-456", None)
            .unwrap();
        let (stale, total) = store.scan_stale_links().unwrap();
        assert_eq!(total, 1);
        assert_eq!(stale.len(), 0, "non-file URIs should never be stale");
    }

    #[test]
    fn test_scan_stale_links_with_missing_file() {
        let tmpdir = TempDir::new().unwrap();
        let store_path = tmpdir.path().join("test.db");
        let store = LinkStore::open(&store_path).unwrap();

        // Create a real file and encode its URI
        let real_file = tmpdir.path().join("real.md");
        std::fs::write(&real_file, "# Real").unwrap();
        let real_uri = format!(
            "hook://file/{}",
            base64::engine::general_purpose::URL_SAFE_NO_PAD
                .encode(real_file.to_string_lossy().as_bytes())
        );

        // Ghost URI pointing to a file that does not exist
        let ghost_uri = "hook://file/L25vbmV4aXN0ZW50L2ZpbGUubWQ"; // /nonexistent/file.md

        store.create_link(&real_uri, ghost_uri, None).unwrap();

        let (stale, total) = store.scan_stale_links().unwrap();
        assert_eq!(total, 1);
        assert_eq!(stale.len(), 1, "link to missing file should be stale");
    }

    #[test]
    fn test_scan_stale_bookmarks() {
        let (_dir, store) = make_store();
        // Path that definitely does not exist
        store.store_bookmark("/absolutely/does/not/exist/file.md").unwrap();
        let (stale, total) = store.scan_stale_bookmarks().unwrap();
        assert_eq!(total, 1);
        assert_eq!(stale.len(), 1);
    }

    #[test]
    fn test_scan_stale_bookmarks_live_path() {
        let tmpdir = TempDir::new().unwrap();
        let store_path = tmpdir.path().join("test.db");
        let store = LinkStore::open(&store_path).unwrap();

        let real = tmpdir.path().join("exists.md");
        std::fs::write(&real, "hi").unwrap();
        store.store_bookmark(real.to_str().unwrap()).unwrap();

        let (stale, total) = store.scan_stale_bookmarks().unwrap();
        assert_eq!(total, 1);
        assert_eq!(stale.len(), 0, "live path should not be stale");
    }

    #[test]
    fn test_delete_links_involving() {
        let (_dir, store) = make_store();
        store
            .create_link("hook://file/a", "hook://file/b", None)
            .unwrap();
        store
            .create_link("hook://file/a", "hook://file/c", None)
            .unwrap();
        assert_eq!(store.link_count().unwrap(), 2);

        let removed = store
            .delete_links_involving(&["hook://file/a".to_string()])
            .unwrap();
        assert_eq!(removed, 2, "both links referencing 'a' should be deleted");
        assert_eq!(store.link_count().unwrap(), 0);
    }

    #[test]
    fn test_delete_bookmarks_by_ids() {
        let (_dir, store) = make_store();
        let id1 = store.store_bookmark("/file/one.md").unwrap();
        let id2 = store.store_bookmark("/file/two.md").unwrap();
        assert_eq!(store.list_bookmarks().unwrap().len(), 2);

        let removed = store.delete_bookmarks_by_ids(&[id1]).unwrap();
        assert_eq!(removed, 1);
        let remaining = store.list_bookmarks().unwrap();
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].id, id2);
    }

    #[test]
    fn test_list_all_links() {
        let (_dir, store) = make_store();
        store
            .create_link("hook://file/a", "hook://file/b", Some("note"))
            .unwrap();
        store
            .create_link("hook://file/c", "hook://file/d", None)
            .unwrap();
        let all = store.list_all_links().unwrap();
        assert_eq!(all.len(), 2);
    }

    #[test]
    fn test_import_bookmark_idempotent() {
        let (_dir, store) = make_store();
        store.import_bookmark("fixed-uuid-1234", "/path/to/file.md").unwrap();
        // Second import with same UUID should return BookmarkAlreadyExists
        let result = store.import_bookmark("fixed-uuid-1234", "/path/to/file.md");
        assert!(
            matches!(result, Err(Error::BookmarkAlreadyExists { .. })),
            "duplicate bookmark UUID should return BookmarkAlreadyExists"
        );
        // Store should still have exactly 1
        assert_eq!(store.list_bookmarks().unwrap().len(), 1);
    }

    #[test]
    fn test_import_bookmark_different_uuids() {
        let (_dir, store) = make_store();
        store.import_bookmark("uuid-aaa", "/file/a.md").unwrap();
        store.import_bookmark("uuid-bbb", "/file/b.md").unwrap();
        assert_eq!(store.list_bookmarks().unwrap().len(), 2);
    }
}