seshat-cli 0.5.0

CLI commands and TUI 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
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
//! Implementation of the `seshat serve` command.
//!
//! Discovers the project database via smart resolution (explicit repo argument,
//! current working directory, git root walk-up, or single-DB fallback), displays
//! startup information, and starts the MCP server on stdio transport with
//! graceful Ctrl+C shutdown.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;

use seshat_core::{BranchId, Language, ScanConfig};
use seshat_mcp::{ProjectConnection, ScanState};
use seshat_scanner::{read_and_parse_file, record_branch_scan_complete, scan_project};
use seshat_storage::{
    BranchRepository, Database, FileIRRepository, SqliteBranchRepository, SqliteFileIRRepository,
    SqliteSubmoduleRepository, SubmoduleRepository, SubmoduleRow,
};
use seshat_watcher::{WatcherError, WatcherParams, start_watcher};
use tokio::sync::oneshot;

use crate::config::AppConfig;
use crate::db::{ServeTarget, detect_branch, gc_branch_snapshots};
use crate::error::CliError;

/// Handle for the GC background task.
///
/// Call [`GcHandle::shutdown`] (or simply drop) to stop the periodic GC task.
pub struct GcHandle {
    shutdown_tx: oneshot::Sender<()>,
    task: tokio::task::JoinHandle<()>,
}

impl GcHandle {
    /// Signal the GC task to stop and await its completion.
    pub async fn shutdown(self) {
        let _ = self.shutdown_tx.send(());
        let _ = tokio::time::timeout(std::time::Duration::from_secs(5), self.task).await;
    }
}

/// Metadata about a discovered scanned project database.
struct RepoInfo {
    /// Human-readable project name (derived from DB filename).
    name: String,
    /// Path to the `.db` file.
    db_path: PathBuf,
    /// Current branch stored in the database.
    branch: BranchId,
    /// Number of indexed files.
    file_count: usize,
    /// Number of convention nodes.
    convention_count: usize,
}

/// Resolve the call log path from CLI flag and config.
///
/// Priority: CLI flag > config value > disabled.
/// - `Some("")` (bare `--call-log`) → default path `$XDG_DATA_HOME/seshat/call-log.jsonl`
/// - `Some("/path")` → explicit path
/// - `None` + `Some(config)` → config value
/// - `None` + `None` config → disabled
fn resolve_call_log_path(cli_flag: Option<PathBuf>, config_value: Option<&str>) -> Option<PathBuf> {
    match cli_flag {
        Some(p) if p.as_os_str().is_empty() => {
            // Bare --call-log with no value → use default path
            let data_dir = dirs::data_dir().unwrap_or_else(|| PathBuf::from("."));
            Some(data_dir.join("seshat").join("call-log.jsonl"))
        }
        Some(p) => Some(p),
        None => config_value.map(PathBuf::from),
    }
}

/// Decide whether the file watcher should start for this `serve` invocation.
///
/// Watcher is gated on **both**:
/// - The user has not disabled it via `[watcher] enabled = false` (`enabled`
///   parameter), AND
/// - The auto-scan (if any) did not fail. A failed scan means the project
///   is in an indeterminate state (e.g. too many files, scan timeout); we
///   refuse to walk the filesystem with `notify-debouncer-full` because
///   that is exactly what blew up to 91.8 GB in the original bug report.
///
/// `state.error_message()` returns `None` when the scan was not needed,
/// is in progress, or completed successfully — so this gate proceeds in
/// all the normal paths and only blocks the explicit failure case.
fn watcher_should_start(enabled: bool, state: &ScanState) -> bool {
    enabled && state.error_message().is_none()
}

/// Handle branch switching and snapshot logic for the serve flow.
///
/// For ExistingDb: if detected branch differs from DB's current branch,
/// switch to it (creating a snapshot from source if target has no data).
/// For AutoScan: if detected branch differs from "main" and "main" has data,
/// create a snapshot from "main" to the detected branch.
///
/// Returns the final branch ID after any switch.
fn handle_branch_switch(
    db: &Database,
    detected_branch: &str,
    current_branch: &BranchId,
    _is_auto_scan: bool,
) -> Result<BranchId, CliError> {
    let branch_repo = SqliteBranchRepository::new(db.connection().clone());

    // Check if we need to switch branches.
    if detected_branch == current_branch.0 {
        return Ok(current_branch.clone());
    }

    let detected_id = BranchId::from(detected_branch);

    // Check if target branch already has data.
    let branches = branch_repo
        .list_branches()
        .map_err(|e| CliError::CommandFailed {
            command: "serve".to_owned(),
            reason: format!("failed to list branches: {e}"),
        })?;

    let target_has_data = branches.iter().any(|b| b.0 == detected_branch);

    if !target_has_data {
        // Target branch has no data — check if source has data to snapshot.
        let source_branch = current_branch.clone();

        // Check source has actual data (not just registered).
        let source_branches = branch_repo
            .list_branches()
            .map_err(|e| CliError::CommandFailed {
                command: "serve".to_owned(),
                reason: format!("failed to list branches: {e}"),
            })?;
        let source_has_data = source_branches.iter().any(|b| b.0 == source_branch.0);

        if !source_has_data {
            tracing::info!(
                source_branch = %source_branch.0,
                target_branch = %detected_branch,
                "Source branch has no data — switching without snapshot"
            );
        } else {
            tracing::info!(
                source_branch = %source_branch.0,
                target_branch = %detected_branch,
                "Target branch has no data — creating snapshot from source"
            );
            branch_repo
                .create_snapshot(&source_branch, &detected_id)
                .map_err(|e| CliError::CommandFailed {
                    command: "serve".to_owned(),
                    reason: format!("failed to create snapshot: {e}"),
                })?;
        }
    }

    // Switch to the detected branch.
    tracing::info!(
        from = %current_branch.0,
        to = %detected_branch,
        "Switching branch"
    );
    branch_repo
        .switch_branch(&detected_id)
        .map_err(|e| CliError::CommandFailed {
            command: "serve".to_owned(),
            reason: format!("failed to switch branch: {e}"),
        })?;

    Ok(detected_id)
}

/// Handle branch snapshot for AutoScan path.
///
/// If detected branch differs from "main" and "main" has data,
/// create a snapshot from "main" to the detected branch.
///
/// Returns the final branch ID after any switch.
fn handle_auto_scan_snapshot(db: &Database, detected_branch: &str) -> Result<BranchId, CliError> {
    let branch_repo = SqliteBranchRepository::new(db.connection().clone());

    if detected_branch == "main" {
        return Ok(BranchId::from(detected_branch));
    }

    let detected_id = BranchId::from(detected_branch);

    // Check if "main" has data.
    let branches = branch_repo
        .list_branches()
        .map_err(|e| CliError::CommandFailed {
            command: "serve".to_owned(),
            reason: format!("failed to list branches: {e}"),
        })?;

    let main_has_data = branches.iter().any(|b| b.0 == "main");

    if !main_has_data {
        return Ok(detected_id);
    }

    // Create snapshot from "main" to detected branch.
    let main_branch = BranchId::from("main");
    tracing::info!(
        source_branch = "main",
        target_branch = %detected_branch,
        "Auto-scan on non-main branch — creating snapshot from main"
    );
    branch_repo
        .create_snapshot(&main_branch, &detected_id)
        .map_err(|e| CliError::CommandFailed {
            command: "serve".to_owned(),
            reason: format!("failed to create snapshot: {e}"),
        })?;

    // Switch to the detected branch.
    branch_repo
        .switch_branch(&detected_id)
        .map_err(|e| CliError::CommandFailed {
            command: "serve".to_owned(),
            reason: format!("failed to switch branch: {e}"),
        })?;

    Ok(detected_id)
}

/// Background sync after a branch switch.
///
/// Thin wrapper around [`incremental_sync_blocking`] for the serve-startup
/// path: runs in a `std::thread::spawn`, no progress callback, and lets the
/// caller's `sync_in_progress` flag track completion.
#[allow(clippy::too_many_arguments)]
fn background_sync(
    project_root: &Path,
    sync_root: &Path,
    old_branch: Option<&str>,
    new_branch: &str,
    db: &Database,
    branch_id: &BranchId,
    scan_config: &ScanConfig,
    detection_config: &seshat_core::DetectionConfig,
) {
    incremental_sync_blocking(
        project_root,
        sync_root,
        old_branch,
        new_branch,
        db,
        branch_id,
        scan_config,
        detection_config,
        None,
    );
}

/// Synchronous incremental sync of a branch's `files_ir` to match `new_branch`'s
/// HEAD commit, with an optional 1-arg progress callback `(processed, total)`.
///
/// Collects file trees from the old and new branch HEAD commits via `gix`,
/// then diffs at the path level: new/changed files are re-parsed and upserted,
/// removed files are deleted from the new branch's `files_ir`. On `gix` failures,
/// falls back to a full rescan. Runs the detection cycle on completion to rebuild
/// conventions for the new branch, and records HEAD as `last_scanned_commit`.
///
/// The progress callback (if provided) fires on every iteration of the upsert
/// loop with `(processed_so_far, new_paths_total)` and once more with
/// `(total, total)` after the loop. Callers are responsible for any throttling
/// they need (e.g. the `seshat review` blocking sync emits at 1 Hz to stderr).
///
/// Used by:
/// - [`background_sync`] (no callback) — serve startup, runs in a spawned thread.
/// - `run_review` — runs synchronously before opening the TUI so the user sees
///   fresh data (US-011).
///
/// `project_root` is the actual working directory of the project (the
/// worktree path for git worktrees; the repo root otherwise). All file reads
/// and HEAD-commit recording happen against this path.
///
/// `sync_root` is the path used for ref/tree lookups via gix. For plain
/// repos this is identical to `project_root`. For worktrees both paths
/// resolve to the same shared common-dir refs under the hood, but keeping
/// the parameters separate makes the contract explicit: never read source
/// files through `sync_root` (it can point at a sibling worktree).
#[allow(clippy::too_many_arguments)]
pub(crate) fn incremental_sync_blocking(
    project_root: &Path,
    sync_root: &Path,
    old_branch: Option<&str>,
    new_branch: &str,
    db: &Database,
    branch_id: &BranchId,
    scan_config: &ScanConfig,
    detection_config: &seshat_core::DetectionConfig,
    progress: Option<&dyn Fn(usize, usize)>,
) {
    let new_paths = match resolve_branch_tree_paths(sync_root, new_branch) {
        Some(p) => p,
        None => {
            tracing::warn!(
                "incremental_sync_blocking: could not resolve new branch tree, falling back to full rescan"
            );
            fallback_rescan(project_root, db, branch_id, scan_config, detection_config);
            return;
        }
    };

    let old_paths = old_branch.and_then(|b| resolve_branch_tree_paths(sync_root, b));

    let file_ir_repo = SqliteFileIRRepository::new(db.connection().clone());

    let exclude_set = if scan_config.exclude_paths.is_empty() {
        None
    } else {
        let mut builder = globset::GlobSetBuilder::new();
        for p in &scan_config.exclude_paths {
            match globset::Glob::new(p) {
                Ok(g) => {
                    builder.add(g);
                }
                Err(e) => {
                    tracing::warn!(pattern = %p, error = %e, "incremental_sync_blocking: invalid exclude pattern");
                }
            }
        }
        match builder.build() {
            Ok(set) => Some(set),
            Err(e) => {
                tracing::warn!(error = %e, "incremental_sync_blocking: failed to build exclude globset");
                None
            }
        }
    };

    let total = new_paths.len();
    let mut synced = 0usize;
    let mut removed = 0usize;
    // Build a full source_map covering EVERY file in the new tree, not just
    // the diff. The detection cycle below DELETEs all auto-detected nodes
    // and re-emits them — feeding it an empty map (the previous bug) would
    // drop snippets for all unchanged files. Reading the unchanged files
    // costs a few hundred milliseconds even on large repos and matches the
    // semantics of a full scan, where `scan_project` retains source for
    // every file it touches.
    let mut source_map: HashMap<PathBuf, String> = HashMap::with_capacity(total);

    for (idx, (rel_path, oid)) in new_paths.iter().enumerate() {
        // Fire progress at the top of each iteration so `continue` paths still
        // advance the counter — otherwise large skipped runs would stall the UI.
        if let Some(cb) = progress {
            cb(idx, total);
        }

        let path_str = rel_path.as_str();
        // Absolute path is rooted at `project_root` (the worktree), NOT
        // `sync_root` — for a git worktree the latter points at a sibling
        // checkout where these files do not exist.
        let abs_path = project_root.join(rel_path);
        // Store paths relative to the worktree root, matching the
        // full-scan orchestrator. gix tree-walk already yields relative paths
        // here, so PathBuf::from(rel_path) is the canonical IR key.
        let stored_path = PathBuf::from(rel_path);

        let ext = match abs_path.extension().and_then(|e| e.to_str()) {
            Some(e) => e,
            None => continue,
        };
        let language = match Language::from_extension(ext) {
            Some(l) => l,
            None => continue,
        };

        if let Some(ref exclude_set) = exclude_set {
            if exclude_set.is_match(&abs_path) {
                continue;
            }
        }

        let max_bytes = scan_config.max_file_size_kb * 1024;
        if max_bytes > 0 {
            if let Ok(meta) = std::fs::metadata(&abs_path) {
                if meta.len() > max_bytes {
                    continue;
                }
            }
        }

        // Read every file (changed or not) so the detection cycle below has
        // source available for snippet construction. The IR upsert is still
        // skipped for unchanged files (oid match) — we only need source, not
        // a fresh parse, for detectors to attach snippets.
        let oid_unchanged = old_paths
            .as_ref()
            .is_some_and(|old| old.get(path_str) == Some(oid));

        let (project_file, source) = match read_and_parse_file(
            &abs_path,
            &stored_path,
            language,
            &scan_config.local_packages,
        ) {
            Ok(pair) => pair,
            Err(e) => {
                tracing::warn!(path = %abs_path.display(), error = %e, "incremental_sync_blocking: cannot read file");
                continue;
            }
        };

        if !oid_unchanged {
            // Write IR + symbol-index together so the new branch's HEAD
            // index includes every file whose oid changed.  Failure here
            // leaves the symbol-index inconsistent with files_ir for this
            // path — log at error so the user sees it in default log
            // configurations, not just `--verbose`.
            if let Err(e) = file_ir_repo.upsert_with_symbol_index(branch_id, &project_file, None) {
                tracing::error!(
                    path = %path_str,
                    error = %e,
                    "incremental_sync_blocking: upsert failed — symbol-index may be inconsistent for this file until next save",
                );
            }
            synced += 1;
        }
        // source_map keyed by relative path so it lines up with
        // ProjectFile.path that detectors look up against.
        source_map.insert(stored_path, source);
    }

    // Final tick so the UI snaps to "X / X" instead of stalling at "(X-1) / X".
    if let Some(cb) = progress {
        cb(total, total);
    }

    if let Some(ref old) = old_paths {
        for rel_path in old.keys() {
            if !new_paths.contains_key(rel_path.as_str()) {
                let path_str = rel_path.as_str();
                // Drop files_ir AND matching symbol-index rows in a single
                // transaction so the new branch's index can't observe one
                // half gone while the other half lingers.
                if let Err(e) = file_ir_repo.delete_with_symbol_index(branch_id, path_str) {
                    match &e {
                        seshat_storage::StorageError::NotFound { .. } => {}
                        _ => {
                            tracing::error!(
                                path = %path_str,
                                error = %e,
                                "incremental_sync_blocking: delete failed — orphan symbol-index rows may remain",
                            );
                        }
                    }
                }
                removed += 1;
            }
        }
    }

    tracing::info!(
        synced = synced,
        removed = removed,
        new_total = new_paths.len(),
        old_branch = ?old_branch,
        new_branch = %new_branch,
        "incremental_sync_blocking: completed diff-based sync"
    );

    // P24: skip the detection cycle when nothing actually changed in IR.
    // Detection re-aggregates findings across the whole project IR — that's
    // expensive on large codebases and the existing nodes are still valid
    // when no file changed.
    if synced > 0 || removed > 0 {
        let conn = db.connection().clone();
        let file_dates = SqliteFileIRRepository::new(conn.clone())
            .get_file_dates_by_branch(branch_id)
            .unwrap_or_default()
            .into_iter()
            .collect::<HashMap<_, _>>();
        match seshat_graph::run_detection_cycle(
            &conn,
            branch_id,
            detection_config,
            &file_dates,
            &source_map,
        ) {
            Ok(_) => tracing::info!("incremental_sync_blocking: detection cycle complete"),
            Err(e) => {
                tracing::warn!(error = %e, "incremental_sync_blocking: detection cycle failed")
            }
        }
    } else {
        tracing::debug!("incremental_sync_blocking: no IR changes; skipping detection cycle");
    }

    // Record the WORKTREE's HEAD (not the main repo's) so the next startup's
    // freshness check compares against the correct sentinel for this branch.
    let branch_repo = SqliteBranchRepository::new(db.connection().clone());
    record_branch_scan_complete(&branch_repo, project_root, branch_id);
}

fn resolve_branch_tree_paths(
    root: &Path,
    branch_name: &str,
) -> Option<HashMap<String, gix::ObjectId>> {
    let git_root = crate::db::find_git_root(root)?;
    let repo = gix::open(git_root).ok()?;

    let object = {
        let ref_name = format!("refs/heads/{branch_name}");
        if let Some(id) = repo
            .try_find_reference(&ref_name)
            .ok()
            .flatten()
            .and_then(|r| r.into_fully_peeled_id().ok())
        {
            repo.find_object(id.detach()).ok()
        } else {
            gix::ObjectId::from_hex(branch_name.as_bytes())
                .ok()
                .and_then(|oid| repo.find_object(oid).ok())
        }?
    };

    let tree = object.into_commit().tree().ok()?;

    let mut recorder = gix::traverse::tree::Recorder::default();
    tree.traverse().breadthfirst(&mut recorder).ok()?;

    let mut paths = HashMap::new();
    for entry in recorder.records {
        if entry.mode.is_blob() {
            paths.insert(entry.filepath.to_string(), entry.oid);
        }
    }
    Some(paths)
}

/// `project_root` must be the actual working directory of the project (the
/// worktree path for git worktrees) — `scan_project` walks the filesystem
/// from this root, so passing a sibling worktree here would scan the wrong
/// tree.
fn fallback_rescan(
    project_root: &Path,
    db: &Database,
    branch_id: &BranchId,
    scan_config: &ScanConfig,
    _detection_config: &seshat_core::DetectionConfig,
) {
    tracing::info!(root = %project_root.display(), "background_sync: falling back to full rescan");
    // `scan_project` already runs the full detection cycle with the
    // populated source_map — running it again with an empty source_map
    // (the pre-fix behaviour) wiped every snippet. So we only need the
    // scan call here.
    if let Err(e) = scan_project(project_root, scan_config, db, branch_id.clone()) {
        tracing::warn!(error = %e, "background_sync: full rescan scan_project failed");
    }

    // Record the worktree's HEAD as the last scanned commit so the next
    // freshness check compares against the right sentinel.
    let branch_repo = SqliteBranchRepository::new(db.connection().clone());
    record_branch_scan_complete(&branch_repo, project_root, branch_id);
}

/// Run the serve command.
///
/// Discovers the project database (from explicit repo arg, cwd, git root, or
/// single-DB fallback), loads it, displays startup information, and starts the
/// MCP server on stdio transport.
pub fn run_serve(
    repo: Option<&Path>,
    host: Option<String>,
    port: Option<u16>,
    call_log: Option<PathBuf>,
) -> Result<(), CliError> {
    // -- Load config --------------------------------------------------
    let mut config = AppConfig::load().map_err(|e| CliError::CommandFailed {
        command: "serve".to_owned(),
        reason: format!("failed to load config: {e}"),
    })?;

    // CLI flags override config values.
    if let Some(h) = host {
        config.server.host = h;
    }
    if let Some(p) = port {
        config.server.port = p;
    }

    // -- Discover databases or project root --------------------------
    let target =
        crate::db::resolve_serve_db_or_project_root(repo, &config.scan.additional_denylist_paths)?;

    let (db_path, db, mut repo_info, scan_state, auto_scan_project_root, detected_branch) =
        match target {
            ServeTarget::ExistingDb {
                db_path,
                project_root,
            } => {
                let db = Database::open(&db_path).map_err(|e| CliError::CommandFailed {
                    command: "serve".to_owned(),
                    reason: format!("failed to open database: {e}"),
                })?;
                let detected = detect_branch(&project_root);
                let repo_info = load_repo_info(&db, &db_path)?;
                (
                    db_path,
                    db,
                    repo_info,
                    ScanState::not_needed(),
                    None,
                    detected,
                )
            }
            ServeTarget::AutoScan {
                project_root,
                db_path,
            } => {
                // Detect git branch before creating DB.
                let detected = detect_branch(&project_root);

                // Create empty DB (migrations auto-apply).
                let db = Database::open(&db_path).map_err(|e| CliError::CommandFailed {
                    command: "serve".to_owned(),
                    reason: format!("failed to create database: {e}"),
                })?;
                tracing::info!(
                    project_root = %project_root.display(),
                    db_path = %db_path.display(),
                    detected_branch = %detected,
                    "No existing DB found — starting auto-scan"
                );

                // Create scan state before the discovery check so that any early
                // error paths can still transition it to Failed.
                let scan_state = ScanState::in_progress();

                // File count pre-check: abort auto-scan if project is too large.
                let scan_config = config.scan.clone();
                let auto_scan_limit = scan_config.auto_scan_limit;
                match seshat_scanner::discover_files(&project_root, &scan_config) {
                    Ok(discovery_result) => {
                        let file_count = discovery_result.files.len();

                        if file_count > auto_scan_limit {
                            scan_state.mark_failed(format!(
                            "Project too large for auto-scan ({} files). Run: seshat scan --verbose",
                            file_count
                        ));
                            let repo_info = load_repo_info(&db, &db_path)?;
                            (db_path, db, repo_info, scan_state, None, detected)
                        } else {
                            let repo_info = load_repo_info(&db, &db_path)?;
                            (
                                db_path,
                                db,
                                repo_info,
                                scan_state,
                                Some(project_root),
                                detected,
                            )
                        }
                    }
                    Err(e) => {
                        // Discovery failed — continue with empty DB.
                        // MCP calls will get AUTO_SCAN_FAILED error.
                        scan_state.mark_failed(format!("auto-scan discovery failed: {e}"));
                        let repo_info = load_repo_info(&db, &db_path)?;
                        (db_path, db, repo_info, scan_state, None, detected)
                    }
                }
            }
        };

    // -- Handle branch switching / snapshots --------------------------
    let is_auto_scan = auto_scan_project_root.is_some();
    let old_branch_for_sync = if is_auto_scan {
        None
    } else {
        Some(repo_info.branch.0.clone())
    };

    let final_branch = if is_auto_scan {
        handle_auto_scan_snapshot(&db, &detected_branch)?
    } else {
        handle_branch_switch(&db, &detected_branch, &repo_info.branch, is_auto_scan)?
    };

    // Update repo_info.branch to reflect the actual branch after any switch.
    repo_info.branch = final_branch.clone();

    // -- Resolve the project root used for git operations and sync --------
    // Auto-scan owns its own root; otherwise use the shared sync_root_for
    // helper from cwd. This routes through the same fallback semantics as
    // ResolvedProject::sync_root (git common-dir, else cwd verbatim).
    let sync_root = match &auto_scan_project_root {
        Some(root) => root.clone(),
        None => crate::db::sync_root_for(&std::env::current_dir().unwrap_or_default()),
    };
    // For git worktrees `sync_root` points at the main repo (so we can read
    // shared refs), while the actual files live under the worktree checkout
    // dir — which is what `current_dir()` returns and what `scan_project`
    // walks. `project_root` therefore stays cwd-rooted for the no-auto-scan
    // case, matching the watcher path below.
    let sync_project_root: PathBuf = match &auto_scan_project_root {
        Some(root) => root.clone(),
        None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
    };

    // -- Detect HEAD change since last scan (US-010) ----------------------
    // For the auto-scan path, scan_project below is the scan; running an
    // additional sync on top would race with it. For the existing-DB path,
    // compare branches.last_scanned_commit against git rev-parse HEAD;
    // git-unavailable is treated as "no change" per AC#2.
    let head_change_hint: Option<String> = if is_auto_scan {
        None
    } else {
        let branch_repo = SqliteBranchRepository::new(db.connection().clone());
        match seshat_scanner::check_branch_freshness(
            &branch_repo,
            &sync_project_root,
            &final_branch,
        ) {
            seshat_scanner::FreshnessCheck::UpToDate
            | seshat_scanner::FreshnessCheck::GitUnavailable => None,
            seshat_scanner::FreshnessCheck::Stale {
                old_commit,
                new_commit,
            } => {
                let old_short = old_commit
                    .as_deref()
                    .map(|c| c.chars().take(7).collect::<String>())
                    .unwrap_or_else(|| "(none)".to_owned());
                let new_short: String = new_commit.chars().take(7).collect();
                tracing::info!(
                    branch = %final_branch.0,
                    old_head = %old_short,
                    new_head = %new_short,
                    "serve: detected HEAD change since last scan — triggering background sync"
                );
                old_commit
            }
        }
    };

    // -- Shared sync flag for MCP metadata ---------------------------------
    let sync_in_progress = Arc::new(AtomicBool::new(false));
    // -- Concurrent switch guard (prevents multiple parallel branch switches) --
    let switch_in_progress = Arc::new(AtomicBool::new(false));

    // -- Background diff-based sync (branch switch and/or HEAD change) ----
    let sync_old_branch = old_branch_for_sync.filter(|b| *b != final_branch.0);
    let needs_sync = sync_old_branch.is_some() || head_change_hint.is_some();
    // Resolve the old-side hint for tree-diff. Branch-switch wins (it carries
    // a refs/heads/<name> that gix resolves directly); on a same-branch HEAD
    // change the last_scanned_commit hash works as a commit-ish via the
    // ObjectId fallback in `resolve_branch_tree_paths`. None on the HEAD-change
    // path means there was no recorded sentinel — background_sync will fall
    // through to a full rescan when the new-branch tree itself is unresolvable.
    let sync_old_hint: Option<String> =
        sync_old_branch.clone().or_else(|| head_change_hint.clone());

    if needs_sync {
        let sync_root_clone = sync_root.clone();
        let project_root_clone = sync_project_root.clone();
        let sync_db_path = db_path.clone();
        let sync_branch = final_branch.clone();
        let sync_scan_config = config.scan.clone();
        let sync_detection_config = config.detection.clone();
        let sync_flag = sync_in_progress.clone();
        std::thread::spawn(move || {
            struct ClearOnDrop(Arc<AtomicBool>);
            impl Drop for ClearOnDrop {
                fn drop(&mut self) {
                    self.0.store(false, Ordering::Relaxed);
                }
            }
            sync_flag.store(true, Ordering::Relaxed);
            let _guard = ClearOnDrop(sync_flag);
            let sync_db = match Database::open(&sync_db_path) {
                Ok(d) => d,
                Err(e) => {
                    tracing::error!(error = %e, "background_sync: failed to open DB");
                    return;
                }
            };
            background_sync(
                &project_root_clone,
                &sync_root_clone,
                sync_old_hint.as_deref(),
                &sync_branch.0,
                &sync_db,
                &sync_branch,
                &sync_scan_config,
                &sync_detection_config,
            );
        });
    }

    // -- Run branch snapshot garbage collection -----------------------
    // Same resolution as `sync_root` above — branch GC reads git refs to
    // decide which DB-side branches no longer exist on disk.
    let gc_repo_path = match &auto_scan_project_root {
        Some(root) => root.clone(),
        None => crate::db::sync_root_for(&std::env::current_dir().unwrap_or_default()),
    };
    if let Ok(deleted) = gc_branch_snapshots(&db, &gc_repo_path) {
        if !deleted.is_empty() {
            tracing::info!(
                deleted_count = deleted.len(),
                deleted_branches = ?deleted,
                "Garbage collected orphan branch snapshots on startup"
            );
        }
    }

    // -- Load submodule connections -----------------------------------
    let submodule_rows = load_submodule_rows(&db);
    let submodules = open_submodule_connections(&submodule_rows, &repo_info.name);

    // -- Resolve call log path ----------------------------------------
    let call_log_path = resolve_call_log_path(call_log, config.server.call_log.as_deref());

    // -- Create embedding provider (optional) -------------------------
    let embedding_provider: Option<Arc<dyn seshat_embedding::EmbeddingProvider>> =
        config.embedding.as_ref().and_then(|emb_config| {
            match seshat_embedding::create_provider(emb_config) {
                Ok(provider) => {
                    tracing::info!("Embedding provider enabled: {emb_config}");
                    Some(Arc::from(provider))
                }
                Err(e) => {
                    tracing::warn!("Failed to create embedding provider: {e}");
                    eprintln!("  Warning: embedding provider unavailable: {e}");
                    None
                }
            }
        });

    // -- Start MCP server (async via tokio) ---------------------------
    let server_config = config.server.clone();
    let _start = Instant::now();

    let runtime = tokio::runtime::Runtime::new().map_err(|e| CliError::CommandFailed {
        command: "serve".to_owned(),
        reason: format!("failed to create tokio runtime: {e}"),
    })?;

    let root = ProjectConnection::new(
        db.connection().clone(),
        repo_info.name.clone(),
        detected_branch.clone(),
    );

    // Derive project root: use the auto-scan root if available.
    // Otherwise use the current working directory — for git worktrees, cwd is
    // the worktree checkout directory, which is what we need for file diffing.
    // find_git_root would walk up to the main repo root, which is wrong for
    // worktrees (they live under a different path than the main .git dir).
    let project_root = match &auto_scan_project_root {
        Some(root) => root.clone(),
        None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
    };

    let watcher_enabled = config.watcher.enabled;
    let watcher_params = WatcherParams {
        enabled: watcher_enabled,
        debounce_ms: config.watcher.debounce_ms,
        ignore_patterns: config.watcher.ignore_patterns.clone(),
        warm_tier_interval_seconds: config.watcher.warm_tier_interval_seconds,
        bulk_change_threshold: config.watcher.bulk_change_threshold,
    };
    let watcher_scan_config = config.scan.clone();
    let watcher_detection_config = config.detection.clone();

    let has_auto_scan = auto_scan_project_root.is_some();
    let auto_scan_root = auto_scan_project_root.clone();

    runtime
        .block_on(async {
            let scan_state_clone = scan_state.clone();

            // -- Launch background scan (if auto-scan) ------------------
            if let Some(scan_root) = auto_scan_root.clone() {
                let scan_config = config.scan.clone();
                let scan_db = db.clone();
                let scan_branch = detected_branch.clone();
                tokio::spawn(async move {
                    let branch = seshat_core::BranchId::from(scan_branch);
                    let result = tokio::task::spawn_blocking(move || {
                        scan_project(&scan_root, &scan_config, &scan_db, branch)
                    })
                    .await;
                    match result {
                        Ok(Ok(_scan_result)) => {
                            tracing::info!("Auto-scan completed successfully");
                            scan_state_clone.mark_complete();
                        }
                        Ok(Err(scan_err)) => {
                            tracing::error!("Auto-scan failed: {scan_err}");
                            scan_state_clone.mark_failed(scan_err.to_string());
                        }
                        Err(join_err) => {
                            tracing::error!("Auto-scan task panicked: {join_err}");
                            scan_state_clone.mark_failed(join_err.to_string());
                        }
                    }
                });
            }

            // -- Launch periodic GC background task -------------------
            let gc_db = db.clone();
            let gc_repo_path = gc_repo_path.clone();
            let (gc_shutdown_tx, mut gc_shutdown_rx) = oneshot::channel();
            let gc_task = tokio::spawn(async move {
                let mut interval = tokio::time::interval(std::time::Duration::from_secs(3600));
                loop {
                    tokio::select! {
                        _ = interval.tick() => {
                            let db_clone = gc_db.clone();
                            let path_clone = gc_repo_path.clone();
                            match tokio::task::spawn_blocking(move || {
                                gc_branch_snapshots(&db_clone, &path_clone)
                            })
                            .await
                            {
                                Ok(Ok(deleted_list)) => {
                                    if !deleted_list.is_empty() {
                                        tracing::info!(
                                            deleted_count = deleted_list.len(),
                                            deleted_branches = ?deleted_list,
                                            "Periodic branch snapshot garbage collection"
                                        );
                                    }
                                }
                                Ok(Err(e)) => {
                                    tracing::error!(error = %e, "Periodic GC failed");
                                }
                                Err(join_err) => {
                                    tracing::error!(error = %join_err, "Periodic GC task panicked");
                                }
                            }
                        }
                        _ = &mut gc_shutdown_rx => {
                            tracing::debug!("GC background task shutting down");
                            break;
                        }
                    }
                }
            });
            let gc_handle = GcHandle {
                shutdown_tx: gc_shutdown_tx,
                task: gc_task,
            };

            // -- Start watcher (delayed if auto-scan) ------------------
            // When auto-scan is in progress, watcher must wait for scan to
            // complete before starting (it needs a populated DB).
            //
            // P0 guardrail (see PRD US-004): refuse to spawn the watcher
            // task when the auto-scan has already failed. `notify-debouncer-full`
            // recursively walks the project root on init, which is what
            // blew up to 91.8 GB on a dangerous cwd in the original report.
            let watcher_rx = if watcher_should_start(watcher_enabled, &scan_state) {
                let (watcher_tx, watcher_rx) = tokio::sync::oneshot::channel();
                let params = watcher_params;
                let root = project_root.clone();
                let db_p = db_path.clone();
                let conn = db.connection().clone();
                let branch = BranchId::from(detected_branch.as_str());
                let wait_scan = scan_state.clone();

                let on_branch_switch: Arc<dyn Fn() + Send + Sync + 'static> = {
                    let root_clone = project_root.clone();
                    let sync_root_clone = sync_root.clone();
                    let db_path_clone = db_path.clone();
                    let scan_cfg_clone = watcher_scan_config.clone();
                    let detect_cfg_clone = watcher_detection_config.clone();
                    let sync_flag = sync_in_progress.clone();
                    let switch_guard = switch_in_progress.clone();
                    Arc::new(move || {
                        // CAS guard: skip if another switch is already in progress.
                        if switch_guard
                            .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
                            .is_err()
                        {
                            tracing::debug!("Branch switch already in progress — skipping duplicate event");
                            return;
                        }
                        let root = root_clone.clone();
                        let sync_root = sync_root_clone.clone();
                        let db_path = db_path_clone.clone();
                        let scan_cfg = scan_cfg_clone.clone();
                        let detect_cfg = detect_cfg_clone.clone();
                        let sync_flag = sync_flag.clone();
                        let switch_guard = switch_guard.clone();
                        std::thread::spawn(move || {
                            struct ClearOnDrop(Arc<AtomicBool>);
                            impl Drop for ClearOnDrop {
                                fn drop(&mut self) {
                                    self.0.store(false, Ordering::Relaxed);
                                }
                            }
                            let _guard = ClearOnDrop(switch_guard);
                            sync_flag.store(true, Ordering::Relaxed);
                            let _flag_guard = ClearOnDrop(sync_flag);
                            let start = Instant::now();
                            let new_branch = detect_branch(&root);
                            let db = match Database::open(&db_path) {
                                Ok(d) => d,
                                Err(e) => {
                                    tracing::error!(error = %e, "Failed to open DB for branch switch");
                                    return;
                                }
                            };
                            let branch_repo = SqliteBranchRepository::new(db.connection().clone());
                            let current_branch = branch_repo
                                .get_current_branch()
                                .map(|b| b.0.clone())
                                .unwrap_or_else(|e| {
                                    tracing::debug!(error = %e, "Could not read current branch from DB, defaulting to 'main'");
                                    "main".to_string()
                                });

                            tracing::info!(
                                old_branch = %current_branch,
                                new_branch = %new_branch,
                                "Branch switch detected by watcher"
                            );
                            if new_branch == current_branch {
                                tracing::debug!("Branch unchanged, no switch needed");
                                return;
                            }
                            let new_id = BranchId::from(new_branch.as_str());
                            let old_id = BranchId::from(current_branch.as_str());

                            let branches = match branch_repo.list_branches() {
                                Ok(b) => b,
                                Err(e) => {
                                    tracing::error!(error = %e, "Failed to list branches for switch");
                                    return;
                                }
                            };
                            let snapshot_exists = branches.iter().any(|b| b.0 == new_branch);
                            if snapshot_exists {
                                match branch_repo.switch_branch(&new_id) {
                                    Ok(()) => {
                                        let elapsed = start.elapsed();
                                        tracing::info!(
                                            to = %new_branch,
                                            elapsed_ms = elapsed.as_millis(),
                                            "Branch switch completed (instant, snapshot existed)"
                                        );
                                    }
                                    Err(e) => {
                                        tracing::error!(error = %e, "Failed to switch branch");
                                        return;
                                    }
                                }
                            } else {
                                tracing::info!(
                                    source = %current_branch,
                                    target = %new_branch,
                                    "No snapshot for target — creating"
                                );
                                match branch_repo.create_snapshot(&old_id, &new_id) {
                                    Ok(()) => {
                                        match branch_repo.switch_branch(&new_id) {
                                            Ok(()) => {
                                                let elapsed = start.elapsed();
                                                tracing::info!(
                                                    to = %new_branch,
                                                    elapsed_ms = elapsed.as_millis(),
                                                    "Branch switch completed (snapshot created)"
                                                );
                                            }
                                            Err(e) => {
                                                tracing::error!(error = %e, "Failed to switch after snapshot");
                                                return;
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        tracing::error!(error = %e, "Failed to create snapshot");
                                        return;
                                    }
                                }
                            }

                            let old_b = current_branch;
                            background_sync(
                                &root,
                                &sync_root,
                                Some(&old_b),
                                &new_branch,
                                &db,
                                &new_id,
                                &scan_cfg,
                                &detect_cfg,
                            );
                        });
                    })
                };

                tokio::spawn(async move {
                    // If auto-scan is in progress, wait for it to complete
                    // before starting the watcher.
                    wait_scan.wait_for_scan();

                    // Race guard: at the time of the outer `watcher_should_start`
                    // check, the auto-scan was still running. It may have
                    // failed during the wait; re-check before constructing
                    // the OS watcher (which recursively walks the tree).
                    if let Some(msg) = wait_scan.error_message() {
                        tracing::info!(
                            error_message = %msg,
                            "Auto-scan failed during watcher wait; not starting file watcher",
                        );
                        let _ = watcher_tx.send(Err(WatcherError::ScanFailed(msg)));
                        return;
                    }

                    let result = start_watcher(
                        params,
                        root,
                        db_p,
                        conn,
                        branch,
                        watcher_scan_config,
                        watcher_detection_config,
                        on_branch_switch,
                    )
                    .await;
                    if let Err(ref e) = result {
                        tracing::warn!(
                            "File watcher failed to start: {e}. \
                             Serving without incremental updates."
                        );
                    }
                    let _ = watcher_tx.send(result);
                });
                Some(watcher_rx)
            } else {
                None
            };

            // -- Print startup banner ------------------------------------
            // Branch order (guards against confusing messaging when a user
            // disables the watcher in config AND auto-scan also fails):
            //
            //   1. `!watcher_enabled` → "disabled" (config says so)
            //   2. scan failed         → "disabled (auto-scan failed: …)"
            //   3. scan still running  → "starting (after scan)"
            //   4. otherwise           → "starting"
            //
            // The scan-failure branch matches on `scan_error.is_some()`
            // alone (without requiring `has_auto_scan`) because the
            // AutoScan failure path sets `auto_scan_project_root = None`,
            // i.e. `has_auto_scan` flips to `false` precisely on failure.
            // `error_message().is_some()` only ever becomes true on the
            // AutoScan failure path — encoded as a `debug_assert!` below
            // so the invariant breaks loudly in tests if anything in
            // `ScanState` evolves to violate it.
            let watcher_status: std::borrow::Cow<'_, str> = if !watcher_enabled {
                std::borrow::Cow::Borrowed("disabled")
            } else if let Some(msg) = scan_state.error_message() {
                debug_assert!(
                    !has_auto_scan,
                    "scan_state.error_message().is_some() should imply has_auto_scan=false \
                     (the AutoScan failure branch sets auto_scan_project_root=None)"
                );
                std::borrow::Cow::Owned(format!("disabled (auto-scan failed: {msg})"))
            } else if has_auto_scan && !scan_state.auto_scanned() {
                std::borrow::Cow::Borrowed("starting (after scan)")
            } else {
                std::borrow::Cow::Borrowed("starting")
            };
            print_startup(
                &repo_info,
                &submodules,
                &config,
                call_log_path.as_deref(),
                &watcher_status,
                is_auto_scan,
                &detected_branch,
            );

            // -- Run MCP server -----------------------------------------
            let detached_head = final_branch.0.len() >= 7
                && final_branch.0.chars().all(|c| c.is_ascii_hexdigit());

            let shutdown = async {
                tokio::signal::ctrl_c()
                    .await
                    .expect("failed to listen for Ctrl+C");
                eprintln!();
                eprintln!("Shutting down...");
            };

            let result = seshat_mcp::start_stdio_with_shutdown(
                server_config,
                root,
                submodules,
                call_log_path,
                embedding_provider,
                scan_state,
                sync_in_progress.clone(),
                true,
                detached_head,
                project_root.clone(),
                shutdown,
                std::time::Duration::from_secs(5),
            )
            .await;

            // -- Shutdown GC background task ------------------------------
            drop(gc_handle);

            // -- Shutdown watcher ---------------------------------------
            if let Some(mut rx) = watcher_rx {
                if let Ok(Ok(handle)) = rx.try_recv() {
                    handle.shutdown().await;
                }
            }

            result
        })
        .map_err(|e| CliError::CommandFailed {
            command: "serve".to_owned(),
            reason: format!("MCP server error: {e}"),
        })
}

/// Load repository metadata from the database for startup display.
fn load_repo_info(db: &Database, db_path: &Path) -> Result<RepoInfo, CliError> {
    let name = db_path
        .file_stem()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| "unknown".to_owned());

    let info = crate::db::load_project_info(db);

    Ok(RepoInfo {
        name,
        db_path: db_path.to_path_buf(),
        branch: info.branch,
        file_count: info.file_count,
        convention_count: info.convention_count,
    })
}

/// Load the list of submodule rows from the root database.
///
/// Returns an empty `Vec` if the query fails (e.g. empty DB, no submodules
/// table data).
fn load_submodule_rows(db: &Database) -> Vec<SubmoduleRow> {
    let sub_repo = SqliteSubmoduleRepository::new(db.connection().clone());
    match sub_repo.list() {
        Ok(rows) => rows,
        Err(e) => {
            eprintln!(
                "  Warning: could not read submodules table: {e}. Continuing without submodules."
            );
            Vec::new()
        }
    }
}

/// Open database connections for each submodule and build the `ProjectConnection` map.
///
/// For each submodule row, resolves the DB path, opens the database, reads its
/// branch, and wraps it in a `ProjectConnection`. If a submodule DB is missing
/// or fails to open, a warning is logged and that submodule is skipped.
fn open_submodule_connections(
    rows: &[SubmoduleRow],
    root_project_name: &str,
) -> HashMap<String, ProjectConnection> {
    let mut submodules = HashMap::new();

    for row in rows {
        let db_path =
            match crate::db::resolve_submodule_db_path(root_project_name, &row.relative_path) {
                Ok(p) => p,
                Err(e) => {
                    eprintln!(
                        "  Warning: could not resolve DB path for submodule '{}': {e}. Skipping.",
                        row.relative_path
                    );
                    continue;
                }
            };

        if !db_path.exists() {
            eprintln!(
                "  Warning: submodule DB not found at '{}'. Skipping '{}'.",
                db_path.display(),
                row.relative_path
            );
            continue;
        }

        let db = match Database::open(&db_path) {
            Ok(d) => d,
            Err(e) => {
                eprintln!(
                    "  Warning: failed to open submodule DB '{}': {e}. Skipping '{}'.",
                    db_path.display(),
                    row.relative_path
                );
                continue;
            }
        };

        // Read the submodule's branch (default to "main" if not set).
        let branch_repo = SqliteBranchRepository::new(db.connection().clone());
        let branch = branch_repo.get_current_branch().unwrap_or_else(|_| {
            tracing::debug!("Could not detect submodule branch from DB, defaulting to 'main'");
            BranchId::from("main")
        });

        let pc = ProjectConnection::new(
            db.connection().clone(),
            row.relative_path.clone(),
            branch.to_string(),
        );

        submodules.insert(row.relative_path.clone(), pc);
    }

    submodules
}

/// Print the startup information block to stderr.
fn print_startup(
    info: &RepoInfo,
    submodules: &HashMap<String, ProjectConnection>,
    config: &AppConfig,
    call_log_path: Option<&Path>,
    watcher_status: &str,
    auto_scanning: bool,
    detected_branch: &str,
) {
    eprintln!("seshat v{}", env!("CARGO_PKG_VERSION"));
    eprintln!();
    eprintln!("  Repo:         {}", info.name);
    eprintln!("  Branch:       {}", detected_branch);
    if auto_scanning {
        eprintln!("  Files:        0 (auto-scanning...)");
    } else {
        eprintln!("  Files:        {}", info.file_count);
    }
    eprintln!("  Conventions:  {}", info.convention_count);
    eprintln!("  Database:     {}", info.db_path.display());
    eprintln!("  Watcher:      {watcher_status}");

    if submodules.is_empty() {
        eprintln!("  Submodules:   none");
    } else {
        eprintln!("  Submodules:   {}", submodules.len());
        let mut names: Vec<&String> = submodules.keys().collect();
        names.sort();
        for name in names {
            eprintln!("    - {name}");
        }
    }

    if let Some(path) = call_log_path {
        eprintln!("  Call log:     {}", path.display());
    }

    eprintln!();
    eprintln!(
        "  Transport:    stdio ({}:{})",
        config.server.host, config.server.port
    );
    eprintln!();
    eprintln!("Ready. Waiting for MCP client connection...");
}

#[cfg(test)]
mod tests {
    use super::*;
    use seshat_core::DetectionConfig;
    use std::collections::HashMap;

    #[test]
    fn load_repo_info_empty_db() {
        // Verify that load_repo_info works with an empty in-memory DB.
        let db = Database::open(":memory:").expect("in-memory db");
        let path = PathBuf::from("/tmp/test-seshat-project.db");
        let info = load_repo_info(&db, &path).expect("should succeed with empty db");
        assert_eq!(info.name, "test-seshat-project");
        assert_eq!(info.file_count, 0);
        assert_eq!(info.convention_count, 0);
        assert_eq!(info.branch, BranchId::from("main"));
    }

    #[test]
    fn load_submodule_rows_empty_db() {
        let db = Database::open(":memory:").expect("in-memory db");
        let rows = load_submodule_rows(&db);
        assert!(rows.is_empty());
    }

    #[test]
    fn load_submodule_rows_with_data() {
        use seshat_storage::{SqliteSubmoduleRepository, SubmoduleInput, SubmoduleRepository};

        let db = Database::open(":memory:").expect("in-memory db");
        let sub_repo = SqliteSubmoduleRepository::new(db.connection().clone());
        sub_repo
            .insert(&SubmoduleInput {
                relative_path: "vendor/libfoo".to_string(),
                name: "libfoo".to_string(),
                db_path: "/data/seshat/repos/proj/vendor/libfoo.db".to_string(),
                commit_hash: Some("abc123".to_string()),
            })
            .expect("insert");
        sub_repo
            .insert(&SubmoduleInput {
                relative_path: "libs/core".to_string(),
                name: "core".to_string(),
                db_path: "/data/seshat/repos/proj/libs/core.db".to_string(),
                commit_hash: Some("def456".to_string()),
            })
            .expect("insert");

        let rows = load_submodule_rows(&db);
        assert_eq!(rows.len(), 2);
        // list() returns sorted by relative_path
        assert_eq!(rows[0].relative_path, "libs/core");
        assert_eq!(rows[1].relative_path, "vendor/libfoo");
    }

    #[test]
    fn open_submodule_connections_empty_rows() {
        let submodules = open_submodule_connections(&[], "test-project");
        assert!(submodules.is_empty());
    }

    #[test]
    fn open_submodule_connections_missing_db_skipped() {
        let project_name = "serve-test-missing-db";

        let row = SubmoduleRow {
            id: 1,
            relative_path: "vendor/nonexistent".to_string(),
            name: "nonexistent".to_string(),
            db_path: "/no/such/path.db".to_string(),
            commit_hash: Some("abc123".to_string()),
            created_at: "2026-04-03T00:00:00".to_string(),
            updated_at: "2026-04-03T00:00:00".to_string(),
        };

        let submodules = open_submodule_connections(&[row], project_name);
        // Should be empty since the DB file doesn't exist.
        assert!(submodules.is_empty());

        // Clean up directories created as side effect of resolve_submodule_db_path.
        if let Ok(repos) = crate::db::xdg_repos_dir() {
            let _ = std::fs::remove_dir_all(repos.join(project_name));
        }
    }

    #[test]
    fn resolve_call_log_bare_flag_uses_default_path() {
        // --call-log with no value → default_missing_value="" → empty PathBuf
        let result = resolve_call_log_path(Some(PathBuf::from("")), None);
        let path = result.expect("should resolve to default path");
        // Normalize path separators so the assertion holds on Windows where
        // PathBuf renders as `…\seshat\call-log.jsonl`.
        let normalized = path.to_string_lossy().replace('\\', "/");
        assert!(
            normalized.ends_with("seshat/call-log.jsonl"),
            "expected default path to end with seshat/call-log.jsonl, got {normalized}"
        );
    }

    #[test]
    fn resolve_call_log_explicit_path() {
        let result = resolve_call_log_path(Some(PathBuf::from("/tmp/my-log.jsonl")), None);
        assert_eq!(result, Some(PathBuf::from("/tmp/my-log.jsonl")));
    }

    #[test]
    fn resolve_call_log_from_config() {
        let result = resolve_call_log_path(None, Some("/config/path.jsonl"));
        assert_eq!(result, Some(PathBuf::from("/config/path.jsonl")));
    }

    #[test]
    fn resolve_call_log_cli_overrides_config() {
        let result = resolve_call_log_path(
            Some(PathBuf::from("/cli/path.jsonl")),
            Some("/config/path.jsonl"),
        );
        assert_eq!(result, Some(PathBuf::from("/cli/path.jsonl")));
    }

    #[test]
    fn resolve_call_log_disabled_when_no_flag_and_no_config() {
        let result = resolve_call_log_path(None, None);
        assert!(result.is_none());
    }

    #[test]
    fn open_submodule_connections_with_real_dbs() {
        use std::fs;

        let project_name = "serve-test-submod";
        let mount_path = "vendor/testlib";

        // resolve_submodule_db_path creates the DB in the real XDG data dir
        // (required because open_submodule_connections resolves paths itself).
        let db_path =
            crate::db::resolve_submodule_db_path(project_name, mount_path).expect("resolve path");

        // RAII guard: clean up the XDG directory on drop (even on panic).
        struct Cleanup(PathBuf);
        impl Drop for Cleanup {
            fn drop(&mut self) {
                let _ = fs::remove_dir_all(&self.0);
            }
        }
        let repos_dir = crate::db::xdg_repos_dir().expect("xdg repos dir");
        let _guard = Cleanup(repos_dir.join(project_name));

        let db = Database::open(&db_path).expect("create submodule DB");
        drop(db);

        let row = SubmoduleRow {
            id: 1,
            relative_path: mount_path.to_string(),
            name: "testlib".to_string(),
            db_path: db_path.to_string_lossy().to_string(),
            commit_hash: Some("abc123".to_string()),
            created_at: "2026-04-03T00:00:00".to_string(),
            updated_at: "2026-04-03T00:00:00".to_string(),
        };

        let submodules = open_submodule_connections(&[row], project_name);
        assert_eq!(submodules.len(), 1);
        assert!(submodules.contains_key(mount_path));

        let pc = &submodules[mount_path];
        assert_eq!(pc.name, mount_path);
        assert_eq!(pc.branch, "main"); // default branch for empty DB
        // _guard drops here, cleaning up the project dir.
    }

    // ── handle_auto_scan_snapshot ─────────────────────────────────────

    #[test]
    fn handle_auto_scan_snapshot_main_branch_no_op() {
        let db = Database::open(":memory:").expect("in-memory db");
        let result = handle_auto_scan_snapshot(&db, "main").expect("should succeed");
        assert_eq!(result, BranchId::from("main"));
    }

    // ── print_startup ─────────────────────────────────────────────────

    #[test]
    fn print_startup_does_not_panic() {
        let repos_dir = crate::db::xdg_repos_dir().expect("xdg repos dir");
        let _ = std::fs::create_dir_all(&repos_dir);
        let info = RepoInfo {
            name: "test-project".to_string(),
            db_path: PathBuf::from("/tmp/test.db"),
            file_count: 5,
            convention_count: 42,
            branch: BranchId::from("main"),
        };
        let config = AppConfig::load().unwrap_or_default();
        print_startup(
            &info,
            &HashMap::new(),
            &config,
            None,
            "running",
            false,
            "main",
        );
    }

    // ── RepoInfo ──────────────────────────────────────────────────────

    #[test]
    fn repo_info_default_name_extraction() {
        let info = RepoInfo {
            name: "my-awesome-project".to_string(),
            db_path: PathBuf::from("/tmp/test.db"),
            file_count: 10,
            convention_count: 20,
            branch: BranchId::from("feat/bar"),
        };
        assert_eq!(info.name, "my-awesome-project");
        assert_eq!(info.file_count, 10);
        assert_eq!(info.convention_count, 20);
        assert_eq!(info.branch, BranchId::from("feat/bar"));
    }

    // ── fallback_rescan ───────────────────────────────────────────────

    #[test]
    fn fallback_rescan_empty_dir_handles_gracefully() {
        use tempfile::tempdir;
        let dir = tempdir().expect("tempdir");
        let db = Database::open(":memory:").expect("in-memory db");
        let branch = BranchId::from("main");
        // Empty dir — fallback_rescan should log warnings but not panic.
        fallback_rescan(
            dir.path(),
            &db,
            &branch,
            &ScanConfig::default(),
            &DetectionConfig::default(),
        );
    }

    // ── resolve_branch_tree_paths ─────────────────────────────────────

    #[test]
    fn resolve_branch_tree_paths_not_a_git_repo_returns_none() {
        use tempfile::tempdir;
        let dir = tempdir().expect("tempdir");
        let result = resolve_branch_tree_paths(dir.path(), "main");
        assert!(result.is_none());
    }

    // ── handle_branch_switch ───────────────────────────────────────────

    fn seed_branch(db: &Database, branch_name: &str) -> BranchId {
        let branch = BranchId::from(branch_name);
        let br = SqliteBranchRepository::new(db.connection().clone());
        br.switch_branch(&branch).unwrap();
        // Insert a node so list_branches returns this branch.
        let c = db.connection().lock().unwrap();
        c.execute(
            "INSERT INTO nodes (branch_id, nature, weight, confidence, adoption_count, total_count, description, ext_data)
             VALUES (?1, 'convention', 'strong', 0.9, 5, 10, 'test', '{\"source\":\"auto_detected\"}')",
            rusqlite::params![branch_name],
        ).unwrap();
        branch
    }

    #[test]
    fn handle_branch_switch_same_branch_returns_current() {
        let db = Database::open(":memory:").expect("in-memory db");
        let current = BranchId::from("main");
        let result = handle_branch_switch(&db, "main", &current, false).unwrap();
        assert_eq!(result, current);
    }

    #[test]
    fn handle_branch_switch_target_has_data_no_snapshot() {
        let db = Database::open(":memory:").expect("in-memory db");
        let current = BranchId::from("main");
        seed_branch(&db, "feat/test");
        let result = handle_branch_switch(&db, "feat/test", &current, false).unwrap();
        assert_eq!(result, BranchId::from("feat/test"));
    }

    #[test]
    fn handle_branch_switch_source_no_data_still_switches() {
        let db = Database::open(":memory:").expect("in-memory db");
        let current = BranchId::from("main");
        let result = handle_branch_switch(&db, "feat/empty", &current, false).unwrap();
        assert_eq!(result, BranchId::from("feat/empty"));
    }

    #[test]
    fn handle_branch_switch_source_has_data_creates_snapshot() {
        let db = Database::open(":memory:").expect("in-memory db");
        let current = BranchId::from("main");
        seed_branch(&db, "main");
        let result = handle_branch_switch(&db, "feat/snap", &current, false).unwrap();
        assert_eq!(result, BranchId::from("feat/snap"));
        // Snapshot created — verify feat/snap now has nodes.
        let br = SqliteBranchRepository::new(db.connection().clone());
        let branches = br.list_branches().unwrap();
        assert!(branches.iter().any(|b| b.0 == "feat/snap"));
    }

    // ── handle_auto_scan_snapshot ───────────────────────────────────────

    #[test]
    fn auto_scan_snapshot_non_main_no_main_data_still_switches() {
        let db = Database::open(":memory:").expect("in-memory db");
        let result = handle_auto_scan_snapshot(&db, "feat/bar").unwrap();
        assert_eq!(result, BranchId::from("feat/bar"));
    }

    #[test]
    fn auto_scan_snapshot_non_main_with_main_data_creates_snapshot() {
        let db = Database::open(":memory:").expect("in-memory db");
        seed_branch(&db, "main");
        let result = handle_auto_scan_snapshot(&db, "feat/baz").unwrap();
        assert_eq!(result, BranchId::from("feat/baz"));
        let br = SqliteBranchRepository::new(db.connection().clone());
        let branches = br.list_branches().unwrap();
        assert!(branches.iter().any(|b| b.0 == "feat/baz"));
    }

    // ── watcher_should_start (P0 guardrail, US-004) ───────────────────

    #[test]
    fn watcher_should_start_disabled_returns_false_regardless_of_scan_state() {
        // Even with a healthy scan_state, a disabled config blocks the watcher.
        let state_ok = ScanState::not_needed();
        assert!(!watcher_should_start(false, &state_ok));

        let state_complete = ScanState::in_progress();
        state_complete.mark_complete();
        assert!(!watcher_should_start(false, &state_complete));
    }

    #[test]
    fn watcher_should_start_enabled_with_no_scan_returns_true() {
        // ExistingDb path: ScanState::not_needed() — no auto-scan ran,
        // watcher should start as before this guardrail existed.
        let state = ScanState::not_needed();
        assert!(watcher_should_start(true, &state));
    }

    #[test]
    fn watcher_should_start_enabled_with_completed_scan_returns_true() {
        // AutoScan happy path: scan finished successfully → watcher starts.
        let state = ScanState::in_progress();
        state.mark_complete();
        assert!(watcher_should_start(true, &state));
    }

    #[test]
    fn watcher_should_start_enabled_with_in_progress_scan_returns_true() {
        // AutoScan in-progress path: outer gate decides to spawn the
        // watcher task NOW; the spawned task waits for completion via
        // wait_for_scan() and re-checks error_message() before walking.
        let state = ScanState::in_progress();
        assert!(watcher_should_start(true, &state));
    }

    #[test]
    fn watcher_should_start_enabled_with_failed_scan_returns_false() {
        // P0: this is the bug class US-004 closes. A failed auto-scan
        // means we must NOT construct notify-debouncer-full / walk the tree.
        let state = ScanState::in_progress();
        state.mark_failed("project too large".to_owned());
        assert!(!watcher_should_start(true, &state));
    }

    #[test]
    fn watcher_should_start_disabled_with_failed_scan_returns_false() {
        // Belt-and-suspenders: both gates closed.
        let state = ScanState::in_progress();
        state.mark_failed("scan timeout".to_owned());
        assert!(!watcher_should_start(false, &state));
    }

    // ── Race-guard re-check inside spawned watcher task (FR-5) ─────────
    //
    // The outer `watcher_should_start` gate may pass while scan is still
    // `InProgress` — the spawned task then `wait_for_scan()`s. If the scan
    // transitions to `Failed` during that wait, the inner re-check
    // (`error_message().is_some()`) must catch it BEFORE `start_watcher`
    // gets to construct `notify-debouncer-full` and walk the tree.
    //
    // We can't drive the actual `tokio::spawn` block from here without
    // standing up the full serve flow, so we exercise the underlying
    // `ScanState` synchronisation pattern directly.

    #[test]
    fn race_guard_pattern_detects_pre_wait_failure() {
        // Failure was set BEFORE wait_for_scan returns: the post-wait
        // error_message() check must surface it.
        let state = ScanState::in_progress();
        state.mark_failed("simulated pre-wait failure".to_owned());
        state.wait_for_scan(); // returns immediately — not InProgress anymore
        assert_eq!(
            state.error_message(),
            Some("simulated pre-wait failure".to_owned())
        );
    }

    #[test]
    fn race_guard_pattern_returns_none_for_normal_completion() {
        let state = ScanState::in_progress();
        state.mark_complete();
        state.wait_for_scan();
        assert_eq!(state.error_message(), None);
    }

    #[test]
    fn race_guard_pattern_observes_failure_set_during_wait() {
        // Honest race test: thread A enters wait_for_scan while state is
        // InProgress; thread B then mark_fails. A must wake up, observe
        // the failure via error_message(), and return Some(reason).
        use std::sync::Arc;
        use std::thread;
        use std::time::Duration;

        let state = ScanState::in_progress();
        let waiter_state = state.clone();
        let observed: Arc<std::sync::Mutex<Option<String>>> = Arc::new(std::sync::Mutex::new(None));
        let observed_for_thread = Arc::clone(&observed);
        let waiter = thread::spawn(move || {
            waiter_state.wait_for_scan();
            *observed_for_thread.lock().expect("lock") = waiter_state.error_message();
        });

        // Give the waiter time to enter `wait_for_scan` and park on the
        // condvar. A short sleep is fine because the waiter blocks until
        // we notify via mark_failed.
        thread::sleep(Duration::from_millis(50));
        state.mark_failed("simulated late failure".to_owned());

        waiter.join().expect("waiter thread join");
        let captured = observed.lock().expect("lock").clone();
        assert_eq!(captured, Some("simulated late failure".to_owned()));
    }
}