seshat-storage 0.7.0

SQLite storage, migrations, and repository implementations for Seshat
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
//! SQLite implementation of [`BranchRepository`].

use std::sync::{Arc, Mutex};

use rusqlite::{Connection, params};
use seshat_core::BranchId;

use super::{BranchRepository, lock_conn};
use crate::StorageError;

/// Key used in the `metadata` table to store the current branch.
const CURRENT_BRANCH_KEY: &str = "current_branch";

/// Default branch name when none has been set.
const DEFAULT_BRANCH: &str = "main";

/// SQLite-backed branch repository.
#[derive(Debug, Clone)]
pub struct SqliteBranchRepository {
    conn: Arc<Mutex<Connection>>,
}

impl SqliteBranchRepository {
    /// Create a new repository backed by the given connection.
    pub fn new(conn: Arc<Mutex<Connection>>) -> Self {
        Self { conn }
    }
}

impl BranchRepository for SqliteBranchRepository {
    fn create_snapshot(
        &self,
        source_branch: &BranchId,
        new_branch: &BranchId,
    ) -> Result<(), StorageError> {
        let conn = lock_conn(&self.conn)?;

        let tx = conn.unchecked_transaction()?;

        // Ensure the source branch is registered in the `branches` table so
        // it shows up in `list_branches` even if no scan has happened yet.
        tx.execute(
            "INSERT OR IGNORE INTO branches (branch_id) VALUES (?1)",
            params![source_branch.0],
        )?;

        // Register the new (target) branch with `snapshot_source` set so we
        // can later trace where the snapshot came from.
        tx.execute(
            "INSERT INTO branches (branch_id, snapshot_source) VALUES (?1, ?2)
             ON CONFLICT(branch_id) DO UPDATE SET snapshot_source = excluded.snapshot_source",
            params![new_branch.0, source_branch.0],
        )?;

        // Copy nodes
        tx.execute(
            "INSERT INTO nodes (branch_id, nature, weight, confidence, adoption_count, total_count, description, ext_data)
             SELECT ?1, nature, weight, confidence, adoption_count, total_count, description, ext_data
             FROM nodes WHERE branch_id = ?2",
            params![new_branch.0, source_branch.0],
        )?;

        // Copy edges — only edges that belong to the source branch
        tx.execute(
            "INSERT INTO edges (source_id, target_id, edge_type, branch_id, weight, metadata)
             SELECT source_id, target_id, edge_type, ?1, weight, metadata
             FROM edges WHERE branch_id = ?2",
            params![new_branch.0, source_branch.0],
        )?;

        // Copy files_ir
        tx.execute(
            "INSERT INTO files_ir (branch_id, file_path, language, content_hash, ir_data, updated_at)
             SELECT ?1, file_path, language, content_hash, ir_data, updated_at
             FROM files_ir WHERE branch_id = ?2",
            params![new_branch.0, source_branch.0],
        )?;

        // Copy symbol-index rows too. Without this, the new branch would
        // start with an empty index even though its files_ir matches the
        // source — and `incremental_sync_blocking` only rebuilds rows for
        // files that differ between branch HEADs, leaving unchanged files
        // unindexed for the lifetime of the snapshot.
        tx.execute(
            "INSERT INTO symbol_definitions (branch_id, symbol_name, file_path, line, end_line, kind, is_public, snippet)
             SELECT ?1, symbol_name, file_path, line, end_line, kind, is_public, snippet
             FROM symbol_definitions WHERE branch_id = ?2",
            params![new_branch.0, source_branch.0],
        )?;
        tx.execute(
            "INSERT INTO symbol_imports (branch_id, imported_name, importer_file)
             SELECT ?1, imported_name, importer_file
             FROM symbol_imports WHERE branch_id = ?2",
            params![new_branch.0, source_branch.0],
        )?;

        // Copy per-branch metadata (e.g. `workspace_crates`). Without this,
        // queries on a freshly-snapshotted branch would regress to an empty
        // internal-name set until the next full scan refreshes it.
        tx.execute(
            "INSERT INTO branch_metadata (branch_id, key, value, updated_at)
             SELECT ?1, key, value, updated_at
             FROM branch_metadata WHERE branch_id = ?2",
            params![new_branch.0, source_branch.0],
        )?;

        tx.commit()?;

        Ok(())
    }

    fn switch_branch(&self, branch_id: &BranchId) -> Result<(), StorageError> {
        let conn = lock_conn(&self.conn)?;

        let tx = conn.unchecked_transaction()?;

        // Make the branch known to the `branches` table so subsequent
        // `list_branches` / freshness queries can find it.
        tx.execute(
            "INSERT OR IGNORE INTO branches (branch_id) VALUES (?1)",
            params![branch_id.0],
        )?;

        tx.execute(
            "INSERT INTO metadata (key, value) VALUES (?1, ?2)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            params![CURRENT_BRANCH_KEY, branch_id.0],
        )?;

        tx.commit()?;

        Ok(())
    }

    fn delete_branch(&self, branch_id: &BranchId) -> Result<(), StorageError> {
        let conn = lock_conn(&self.conn)?;

        let tx = conn.unchecked_transaction()?;

        // Delete edges first (they reference nodes via FK)
        tx.execute(
            "DELETE FROM edges WHERE branch_id = ?1",
            params![branch_id.0],
        )?;

        tx.execute(
            "DELETE FROM nodes WHERE branch_id = ?1",
            params![branch_id.0],
        )?;

        tx.execute(
            "DELETE FROM files_ir WHERE branch_id = ?1",
            params![branch_id.0],
        )?;

        // Keep symbol-index tables in sync with files_ir lifecycle.  Without
        // this, a deleted branch would leave orphan rows that match no
        // files_ir record — they'd never be served (queries filter by current
        // branch) but would accumulate across delete/recreate cycles.
        tx.execute(
            "DELETE FROM symbol_definitions WHERE branch_id = ?1",
            params![branch_id.0],
        )?;
        tx.execute(
            "DELETE FROM symbol_imports WHERE branch_id = ?1",
            params![branch_id.0],
        )?;

        // Drop the registry row last so failures above don't orphan the
        // branch metadata.
        tx.execute(
            "DELETE FROM branches WHERE branch_id = ?1",
            params![branch_id.0],
        )?;

        tx.commit()?;

        Ok(())
    }

    fn list_branches(&self) -> Result<Vec<BranchId>, StorageError> {
        let conn = lock_conn(&self.conn)?;

        let mut stmt = conn.prepare("SELECT branch_id FROM branches ORDER BY branch_id")?;

        let rows = stmt.query_map([], |row| {
            let id: String = row.get(0)?;
            Ok(BranchId(id))
        })?;

        rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
    }

    fn get_current_branch(&self) -> Result<BranchId, StorageError> {
        let conn = lock_conn(&self.conn)?;

        let result: Result<String, _> = conn.query_row(
            "SELECT value FROM metadata WHERE key = ?1",
            params![CURRENT_BRANCH_KEY],
            |row| row.get(0),
        );

        match result {
            Ok(branch) => Ok(BranchId(branch)),
            Err(rusqlite::Error::QueryReturnedNoRows) => {
                tracing::debug!("No current_branch in metadata, defaulting to 'main'");
                Ok(BranchId(DEFAULT_BRANCH.to_string()))
            }
            Err(e) => Err(e.into()),
        }
    }

    fn get_last_scanned_commit(
        &self,
        branch_id: &BranchId,
    ) -> Result<Option<String>, StorageError> {
        let conn = lock_conn(&self.conn)?;

        let result: Result<Option<String>, _> = conn.query_row(
            "SELECT last_scanned_commit FROM branches WHERE branch_id = ?1",
            params![branch_id.0],
            |row| row.get(0),
        );

        match result {
            Ok(commit) => Ok(commit),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    fn set_last_scanned_commit(
        &self,
        branch_id: &BranchId,
        commit: &str,
    ) -> Result<(), StorageError> {
        let conn = lock_conn(&self.conn)?;

        conn.execute(
            "INSERT INTO branches (branch_id, last_scanned_commit, last_scanned_at)
             VALUES (?1, ?2, unixepoch())
             ON CONFLICT(branch_id) DO UPDATE SET
                 last_scanned_commit = excluded.last_scanned_commit,
                 last_scanned_at     = excluded.last_scanned_at",
            params![branch_id.0, commit],
        )?;

        Ok(())
    }

    fn ensure_branch_exists(&self, branch_id: &BranchId) -> Result<(), StorageError> {
        let conn = lock_conn(&self.conn)?;

        conn.execute(
            "INSERT OR IGNORE INTO branches (branch_id) VALUES (?1)",
            params![branch_id.0],
        )?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Database;
    use crate::repository::file_ir_repository::SqliteFileIRRepository;
    use crate::repository::node_repository::SqliteNodeRepository;
    use crate::repository::{FileIRRepository, NodeRepository};
    use seshat_core::test_helpers::{make_knowledge_node, make_project_file};
    use seshat_core::{KnowledgeNature, Language};

    /// Helper: create an in-memory DB and return repos for testing.
    fn test_repos() -> (
        SqliteBranchRepository,
        SqliteNodeRepository,
        SqliteFileIRRepository,
    ) {
        let db = Database::open(":memory:").expect("in-memory DB");
        let conn = db.connection().clone();
        (
            SqliteBranchRepository::new(conn.clone()),
            SqliteNodeRepository::new(conn.clone()),
            SqliteFileIRRepository::new(conn),
        )
    }

    #[test]
    fn get_current_branch_default() {
        let (branch_repo, _, _) = test_repos();
        let current = branch_repo.get_current_branch().unwrap();
        assert_eq!(current, BranchId::from("main"));
    }

    #[test]
    fn switch_and_get_current_branch() {
        let (branch_repo, _, _) = test_repos();
        let feature = BranchId::from("feature-x");

        branch_repo.switch_branch(&feature).unwrap();
        let current = branch_repo.get_current_branch().unwrap();
        assert_eq!(current, feature);
    }

    #[test]
    fn switch_branch_overwrites() {
        let (branch_repo, _, _) = test_repos();

        branch_repo
            .switch_branch(&BranchId::from("branch-a"))
            .unwrap();
        branch_repo
            .switch_branch(&BranchId::from("branch-b"))
            .unwrap();

        let current = branch_repo.get_current_branch().unwrap();
        assert_eq!(current, BranchId::from("branch-b"));
    }

    #[test]
    fn create_snapshot_copies_nodes_and_files() {
        let (branch_repo, node_repo, file_repo) = test_repos();
        let main_branch = BranchId::from("main");

        // Insert nodes on main
        let mut n1 = make_knowledge_node(KnowledgeNature::Convention, 0.9);
        n1.branch_id = main_branch.clone();
        node_repo.insert(&n1).unwrap();

        let mut n2 = make_knowledge_node(KnowledgeNature::Fact, 0.7);
        n2.branch_id = main_branch.clone();
        node_repo.insert(&n2).unwrap();

        // Insert a file IR on main
        let mut file = make_project_file(Language::Rust);
        file.path = "src/lib.rs".into();
        file.content_hash = "snap_hash".to_string();
        file_repo.upsert(&main_branch, &file, None).unwrap();

        // Create snapshot
        let feature = BranchId::from("feature-snap");
        branch_repo.create_snapshot(&main_branch, &feature).unwrap();

        // Verify nodes were copied
        let main_nodes = node_repo.find_by_branch(&main_branch).unwrap();
        let feature_nodes = node_repo.find_by_branch(&feature).unwrap();
        assert_eq!(main_nodes.len(), 2);
        assert_eq!(feature_nodes.len(), 2);

        // Verify file IR was copied
        let feature_files = file_repo.get_by_branch(&feature).unwrap();
        assert_eq!(feature_files.len(), 1);
        assert_eq!(feature_files[0].content_hash, "snap_hash");
    }

    #[test]
    fn create_snapshot_empty_branch() {
        let (branch_repo, node_repo, _) = test_repos();
        let empty = BranchId::from("empty");
        let target = BranchId::from("copy-of-empty");

        // Snapshot of a branch with no data should succeed
        branch_repo.create_snapshot(&empty, &target).unwrap();

        let nodes = node_repo.find_by_branch(&target).unwrap();
        assert!(nodes.is_empty());
    }

    // A snapshot must carry the source branch's `branch_metadata`
    // (e.g. `workspace_crates`) so queries on the freshly snapshotted
    // branch don't regress to an empty internal-name set until the next
    // full scan refreshes it.
    #[test]
    fn create_snapshot_copies_branch_metadata() {
        use crate::repository::{BranchMetadataRepository, SqliteBranchMetadataRepository};

        let (branch_repo, _, _) = test_repos();
        let branch_meta = SqliteBranchMetadataRepository::new(branch_repo.conn.clone());

        let main_branch = BranchId::from("main");
        let feature = BranchId::from("feature-meta-snap");

        // `branch_metadata.branch_id` FKs to `branches(branch_id)` with FK
        // enforcement on (PRAGMA foreign_keys=ON in Database::open), so the
        // parent row must exist before `set` can INSERT.
        branch_repo.ensure_branch_exists(&main_branch).unwrap();

        branch_meta
            .set("main", "workspace_crates", r#"["crate_a","crate_b"]"#)
            .unwrap();
        branch_meta.set("main", "other_key", "other_value").unwrap();

        // Capture every column on the source side — `updated_at` is the one
        // the PRD AC requires to survive verbatim, so it must be compared
        // directly (the public `list` API only exposes key/value).
        let source_rows: Vec<(String, String, i64)> = {
            let conn = branch_repo.conn.lock().unwrap();
            let mut stmt = conn
                .prepare(
                    "SELECT key, value, updated_at FROM branch_metadata \
                     WHERE branch_id = ?1 ORDER BY key",
                )
                .unwrap();
            stmt.query_map(params!["main"], |row| {
                Ok((row.get(0)?, row.get(1)?, row.get(2)?))
            })
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap()
        };
        assert_eq!(source_rows.len(), 2, "test setup must seed two rows");

        branch_repo.create_snapshot(&main_branch, &feature).unwrap();

        // key/value parity via the public API.
        let snapshot_kv = branch_meta.list(&feature.0).unwrap();
        assert_eq!(
            snapshot_kv,
            vec![
                ("other_key".to_string(), "other_value".to_string()),
                (
                    "workspace_crates".to_string(),
                    r#"["crate_a","crate_b"]"#.to_string()
                ),
            ]
        );

        // Full-row parity — including `updated_at`.
        let snapshot_rows: Vec<(String, String, i64)> = {
            let conn = branch_repo.conn.lock().unwrap();
            let mut stmt = conn
                .prepare(
                    "SELECT key, value, updated_at FROM branch_metadata \
                     WHERE branch_id = ?1 ORDER BY key",
                )
                .unwrap();
            stmt.query_map(params![feature.0], |row| {
                Ok((row.get(0)?, row.get(1)?, row.get(2)?))
            })
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap()
        };
        assert_eq!(
            snapshot_rows, source_rows,
            "snapshotted branch_metadata must match source row-for-row"
        );

        // Source rows must be untouched by the copy.
        let source_kv = branch_meta.list("main").unwrap();
        assert_eq!(source_kv.len(), 2);
    }

    #[test]
    fn list_branches_empty() {
        let (branch_repo, _, _) = test_repos();
        let branches = branch_repo.list_branches().unwrap();
        assert!(branches.is_empty());
    }

    #[test]
    fn list_branches_with_data() {
        let (branch_repo, node_repo, file_repo) = test_repos();
        let main_branch = BranchId::from("main");
        let feature = BranchId::from("feature");

        // Branches must be explicitly registered now — `list_branches`
        // reads from the `branches` table, not from `nodes` / `files_ir`.
        branch_repo.ensure_branch_exists(&main_branch).unwrap();
        branch_repo.ensure_branch_exists(&feature).unwrap();

        // Insert data afterwards so the rest of the assertions on
        // node/file presence still exercise the snapshot/list interplay.
        let mut n = make_knowledge_node(KnowledgeNature::Fact, 0.5);
        n.branch_id = main_branch.clone();
        node_repo.insert(&n).unwrap();

        let mut f = make_project_file(Language::Python);
        f.path = "app.py".into();
        f.content_hash = "h".to_string();
        file_repo.upsert(&feature, &f, None).unwrap();

        let branches = branch_repo.list_branches().unwrap();
        assert_eq!(branches.len(), 2);
        assert!(branches.contains(&main_branch));
        assert!(branches.contains(&feature));
    }

    /// Regression guard for US-003: `list_branches` must not fall back to
    /// `SELECT DISTINCT branch_id FROM nodes` (the old behaviour). A branch
    /// with raw `nodes`/`edges`/`files_ir` rows but no entry in `branches`
    /// must NOT appear in the listing — we want explicit registration.
    #[test]
    fn list_branches_reads_from_branches_table_not_nodes() {
        let (branch_repo, node_repo, file_repo) = test_repos();
        let ghost = BranchId::from("ghost-branch");

        // Insert raw rows for a branch that was never registered. With the
        // old `UNION` query this branch would be returned by `list_branches`.
        let mut n = make_knowledge_node(KnowledgeNature::Fact, 0.4);
        n.branch_id = ghost.clone();
        node_repo.insert(&n).unwrap();

        let mut f = make_project_file(Language::Rust);
        f.path = "ghost.rs".into();
        f.content_hash = "ghost_hash".to_string();
        file_repo.upsert(&ghost, &f, None).unwrap();

        let branches = branch_repo.list_branches().unwrap();
        assert!(
            branches.is_empty(),
            "list_branches should ignore raw rows in nodes/files_ir, got {branches:?}"
        );
    }

    #[test]
    fn delete_branch() {
        let (branch_repo, node_repo, file_repo) = test_repos();
        let branch = BranchId::from("to-delete");

        // Insert node and file
        let mut n = make_knowledge_node(KnowledgeNature::Observation, 0.6);
        n.branch_id = branch.clone();
        node_repo.insert(&n).unwrap();

        let mut f = make_project_file(Language::TypeScript);
        f.path = "index.ts".into();
        f.content_hash = "del_hash".to_string();
        file_repo.upsert(&branch, &f, None).unwrap();

        // Verify data exists
        assert_eq!(node_repo.find_by_branch(&branch).unwrap().len(), 1);
        assert_eq!(file_repo.get_by_branch(&branch).unwrap().len(), 1);

        // Delete branch
        branch_repo.delete_branch(&branch).unwrap();

        // Verify data was removed
        assert!(node_repo.find_by_branch(&branch).unwrap().is_empty());
        assert!(file_repo.get_by_branch(&branch).unwrap().is_empty());
    }

    #[test]
    fn delete_branch_no_data_succeeds() {
        let (branch_repo, _, _) = test_repos();
        // Deleting a branch with no data should not error
        branch_repo.delete_branch(&BranchId::from("ghost")).unwrap();
    }

    #[test]
    fn snapshot_and_delete_isolation() {
        let (branch_repo, node_repo, file_repo) = test_repos();
        let main_branch = BranchId::from("main");

        // Set up main data
        let mut n = make_knowledge_node(KnowledgeNature::Decision, 0.95);
        n.branch_id = main_branch.clone();
        node_repo.insert(&n).unwrap();

        let mut f = make_project_file(Language::Rust);
        f.path = "src/main.rs".into();
        f.content_hash = "iso_hash".to_string();
        file_repo.upsert(&main_branch, &f, None).unwrap();

        // Create snapshot
        let snapshot = BranchId::from("snapshot");
        branch_repo
            .create_snapshot(&main_branch, &snapshot)
            .unwrap();

        // Delete snapshot — main should be unaffected
        branch_repo.delete_branch(&snapshot).unwrap();

        assert_eq!(node_repo.find_by_branch(&main_branch).unwrap().len(), 1);
        assert_eq!(file_repo.get_by_branch(&main_branch).unwrap().len(), 1);
        assert!(node_repo.find_by_branch(&snapshot).unwrap().is_empty());
    }

    // ── US-003: BranchRepository extensions ────────────────────────────

    #[test]
    fn ensure_branch_exists_is_idempotent() {
        let (branch_repo, _, _) = test_repos();
        let b = BranchId::from("idem");

        branch_repo.ensure_branch_exists(&b).unwrap();
        branch_repo.ensure_branch_exists(&b).unwrap();
        branch_repo.ensure_branch_exists(&b).unwrap();

        let branches = branch_repo.list_branches().unwrap();
        assert_eq!(branches, vec![b]);
    }

    #[test]
    fn ensure_branch_exists_does_not_overwrite_existing_metadata() {
        let (branch_repo, _, _) = test_repos();
        let b = BranchId::from("preserve-me");

        branch_repo.set_last_scanned_commit(&b, "abc1234").unwrap();
        // Calling ensure_branch_exists must not clobber `last_scanned_commit`.
        branch_repo.ensure_branch_exists(&b).unwrap();

        let commit = branch_repo.get_last_scanned_commit(&b).unwrap();
        assert_eq!(commit.as_deref(), Some("abc1234"));
    }

    #[test]
    fn get_last_scanned_commit_returns_none_for_unknown_branch() {
        let (branch_repo, _, _) = test_repos();
        let result = branch_repo
            .get_last_scanned_commit(&BranchId::from("never-scanned"))
            .unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn get_last_scanned_commit_returns_none_when_branch_exists_but_not_scanned() {
        let (branch_repo, _, _) = test_repos();
        let b = BranchId::from("registered-only");

        // Branch exists in the registry but never scanned — column is NULL.
        branch_repo.ensure_branch_exists(&b).unwrap();

        let result = branch_repo.get_last_scanned_commit(&b).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn set_last_scanned_commit_round_trip() {
        let (branch_repo, _, _) = test_repos();
        let b = BranchId::from("round-trip");

        branch_repo.set_last_scanned_commit(&b, "deadbeef").unwrap();
        let read = branch_repo.get_last_scanned_commit(&b).unwrap();
        assert_eq!(read.as_deref(), Some("deadbeef"));
    }

    #[test]
    fn set_last_scanned_commit_upsert_overwrites_previous_value() {
        let (branch_repo, _, _) = test_repos();
        let b = BranchId::from("overwrite-me");

        branch_repo.set_last_scanned_commit(&b, "first00").unwrap();
        branch_repo.set_last_scanned_commit(&b, "secondf0").unwrap();

        let read = branch_repo.get_last_scanned_commit(&b).unwrap();
        assert_eq!(read.as_deref(), Some("secondf0"));

        // Still exactly one row in `branches` for this id.
        let branches = branch_repo.list_branches().unwrap();
        assert_eq!(
            branches.iter().filter(|x| **x == b).count(),
            1,
            "UPSERT must not duplicate rows"
        );
    }

    #[test]
    fn set_last_scanned_commit_bumps_last_scanned_at() {
        // Deterministic version: instead of sleeping for `unixepoch()` to
        // tick (1100 ms × N CI runs adds up, and the assertion was `>=`
        // which doesn't actually prove forward motion), manually rewind
        // `last_scanned_at` to a fixed past value, then call
        // set_last_scanned_commit and assert it overwrote that value
        // with the current time.
        let (branch_repo, _, _) = test_repos();
        let b = BranchId::from("bump");

        branch_repo.set_last_scanned_commit(&b, "h1").unwrap();

        // Force last_scanned_at into the past so the next call has a
        // deterministic earlier timestamp to advance from. 0 is the
        // minimum valid Unix time, well before any real `unixepoch()`.
        const PAST_TS: i64 = 0;
        {
            let conn = branch_repo.conn.lock().unwrap();
            conn.execute(
                "UPDATE branches SET last_scanned_at = ?1 WHERE branch_id = ?2",
                params![PAST_TS, b.0],
            )
            .unwrap();
        }

        branch_repo.set_last_scanned_commit(&b, "h2").unwrap();

        let conn = branch_repo.conn.lock().unwrap();
        let ts2: i64 = conn
            .query_row(
                "SELECT last_scanned_at FROM branches WHERE branch_id = ?1",
                params![b.0],
                |row| row.get(0),
            )
            .unwrap();
        assert!(
            ts2 > PAST_TS,
            "last_scanned_at must advance forward of any stored prior value; \
             got ts2={ts2}, PAST_TS={PAST_TS}"
        );
    }

    #[test]
    fn create_snapshot_registers_target_branch_with_snapshot_source() {
        let (branch_repo, _, _) = test_repos();
        let main_branch = BranchId::from("main");
        let snap = BranchId::from("snap-1");

        // Source isn't pre-registered — create_snapshot must register both.
        branch_repo.create_snapshot(&main_branch, &snap).unwrap();

        let listed = branch_repo.list_branches().unwrap();
        assert!(listed.contains(&main_branch), "source must be registered");
        assert!(listed.contains(&snap), "target must be registered");

        // `snapshot_source` must be set on the target row.
        let conn = branch_repo.conn.lock().unwrap();
        let source: Option<String> = conn
            .query_row(
                "SELECT snapshot_source FROM branches WHERE branch_id = ?1",
                params![snap.0],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(source.as_deref(), Some("main"));
    }

    #[test]
    fn delete_branch_removes_branches_row() {
        let (branch_repo, _, _) = test_repos();
        let b = BranchId::from("doomed");

        branch_repo.set_last_scanned_commit(&b, "abc").unwrap();
        assert!(branch_repo.list_branches().unwrap().contains(&b));

        branch_repo.delete_branch(&b).unwrap();
        assert!(
            !branch_repo.list_branches().unwrap().contains(&b),
            "delete_branch must drop the registry row"
        );
    }

    #[test]
    fn switch_branch_registers_branch_implicitly() {
        let (branch_repo, _, _) = test_repos();
        let b = BranchId::from("switched-only");

        // No prior ensure / set / snapshot — the act of switching must
        // be enough to surface the branch in `list_branches`.
        branch_repo.switch_branch(&b).unwrap();

        assert!(branch_repo.list_branches().unwrap().contains(&b));
    }
}