semantex-core 1.1.0

Core library for semantex semantic code search (indexing, embeddings, search)
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
//! Storage layout v13 — per-branch index directories under
//! `<project>/.semantex/indexes/<branch_key>/`, plus the top-level project
//! meta, `history.db` / `memory.db` schema creation, and legacy-layout
//! migration.
//!
//! # Design notes (read before touching this file)
//!
//! Pre-v13, `<project>/.semantex/` WAS the index directory: `chunks.db`,
//! `meta.json`, `sparse/`, `dense/<backend>/` all lived directly at that root,
//! and dozens of call sites across three crates (`semantex-cli`,
//! `semantex-mcp`, and non-owned modules within this crate) resolve "the
//! index dir" as `SemantexConfig::project_index_dir(project)` and then read
//! those files straight from it. Wave 1 (this file) owns the storage schema
//! but does NOT own those call sites, and the quality gate requires the
//! entire existing test suite to keep passing unmodified.
//!
//! So: **the container root (`<project>/.semantex/`) stays the live,
//! authoritative location for the currently-open branch** — exactly as
//! today, byte-for-byte, so every existing reader keeps working with zero
//! changes. On top of that, this module builds the v13 `indexes/<branch_key>/`
//! structure the contract specifies, mirroring the root's current content
//! into the branch directory after every successful build/update.
//!
//! The mirror is a **snapshot, not an alias**. Root artifacts that mutate
//! in place after a later build (SQLite writes pages inside `chunks.db`;
//! `fs::write` truncates-and-rewrites `dense/**` and `meta.json` through the
//! same inode) are **copied** — `chunks.db` via SQLite `VACUUM INTO` (which
//! also folds in any not-yet-checkpointed WAL content), the rest byte-copies.
//! Hard-linking those would silently morph an old branch's mirror into the
//! new branch's data on the next incremental build. Only `sparse/` (tantivy)
//! is hard-linked: tantivy segment files are write-once and its own
//! `meta.json` is replaced by atomic rename, both of which are hard-link-safe
//! — and they're the bulk of the index, so the snapshot stays near-free on
//! disk. A `hard_link` failure (e.g. cross-device) falls back to a real copy.
//!
//! The top-level `meta.json` gains the v13 fields (`layout_version`,
//! `project_id`, `default_branch`) via [`ProjectMeta`], which
//! `#[serde(flatten)]`s the existing [`IndexMeta`] so legacy readers that
//! `serde_json::from_str::<IndexMeta>()` the same file (unknown fields are
//! ignored by serde) keep working unmodified — this is how
//! `semantex-mcp`'s warm-state fast path and every other non-owned consumer
//! stays green without being touched.
//!
//! `indexes/<branch_key>/meta.json` is a snapshot of whatever the root
//! `meta.json` was at mirror time — plain [`IndexMeta`] on the very first
//! migration of a legacy index, the flattened [`ProjectMeta`] superset on
//! every sync after that. Either way it parses as `IndexMeta` (flattening
//! exists precisely for that compatibility). The contract also asks for
//! "branch name, head_commit" on the per-index meta; rather than adding
//! fields to the shared `IndexMeta` struct (which nine files across the
//! workspace construct via struct literals with no `..Default::default()`,
//! several outside spine's ownership), that data is written to a small
//! sidecar, `indexes/<branch_key>/branch.json` ([`BranchMeta`]).

use crate::types::IndexMeta;
use anyhow::{Context as _, Result};
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Current storage layout version (contract §A).
pub const LAYOUT_VERSION: u32 = 13;

/// Branch key used when the branch cannot be resolved (detached HEAD, or the
/// project directory is not a git repository at all).
pub const DEFAULT_BRANCH_KEY: &str = "default";

/// Top-level `<project>/.semantex/meta.json` under v13.
///
/// Deliberately a superset of [`IndexMeta`] (via `#[serde(flatten)]`) so that
/// any code still doing `serde_json::from_str::<IndexMeta>(&meta_json)` on
/// this exact file keeps parsing successfully — see the module doc for why
/// that compatibility matters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectMeta {
    pub layout_version: u32,
    pub project_id: String,
    pub default_branch: String,
    #[serde(flatten)]
    pub active_index_meta: IndexMeta,
}

/// Sidecar next to `indexes/<branch_key>/meta.json` carrying the branch
/// identity that the contract asks for on the per-index meta, without
/// widening the shared [`IndexMeta`] struct (see module doc).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BranchMeta {
    pub branch: String,
    pub branch_key: String,
    #[serde(default)]
    pub head_commit: Option<String>,
}

// Root-level sidecar (Wave 2, `<project>/.semantex/branch.json`) recording
// which branch the container root's LIVE content currently belongs to —
// as opposed to the (possibly stale) snapshots sitting in
// `indexes/<branch_key>/`. This is the source of truth
// `crate::index::branches::detect_and_handle_branch_switch` compares
// against `current_branch_key` to notice a `git switch`/`checkout` since
// the root was last synced. Written by `mirror_into_branch_dir` (same
// `BranchMeta` shape/content as the per-branch sidecar, just also kept at
// the root) so the two never disagree. See `root_branch_meta_path` /
// `read_root_branch_meta` below.

// ── Path helpers ───────────────────────────────────────────────────────────

/// `<project>/.semantex/` — the top-level container. Unchanged from
/// pre-v13; still the live/authoritative dir for the active branch.
pub fn container_dir(project_root: &Path) -> PathBuf {
    project_root.join(".semantex")
}

/// `<project>/.semantex/indexes/`
pub fn indexes_root(project_root: &Path) -> PathBuf {
    container_dir(project_root).join("indexes")
}

/// `<project>/.semantex/indexes/<branch_key>/`
pub fn branch_index_dir(project_root: &Path, branch_key: &str) -> PathBuf {
    indexes_root(project_root).join(branch_key)
}

/// `<project>/.semantex/history.db`
pub fn history_db_path(project_root: &Path) -> PathBuf {
    container_dir(project_root).join("history.db")
}

/// `<project>/.semantex/memory.db`
pub fn memory_db_path(project_root: &Path) -> PathBuf {
    container_dir(project_root).join("memory.db")
}

/// `<project>/.semantex/meta.json` (top-level, v13 [`ProjectMeta`] shape).
pub fn project_meta_path(project_root: &Path) -> PathBuf {
    container_dir(project_root).join("meta.json")
}

/// `<project>/.semantex/branch.json` — see [`BranchMeta`]'s root-sidecar doc.
pub fn root_branch_meta_path(project_root: &Path) -> PathBuf {
    container_dir(project_root).join("branch.json")
}

/// Read the root's recorded branch identity, if any. `None` means either a
/// brand-new project (nothing synced yet) or a pre-Wave-2 `.semantex/` that
/// predates this sidecar — either way, callers should treat that as "no
/// switch to reconcile" rather than an error.
pub fn read_root_branch_meta(project_root: &Path) -> Option<BranchMeta> {
    let content = std::fs::read_to_string(root_branch_meta_path(project_root)).ok()?;
    serde_json::from_str(&content).ok()
}

/// Read the branch identity sidecar of a saved snapshot
/// (`indexes/<branch_key>/branch.json`), if present. Used by the
/// branch-switch handling to decide whether an outgoing branch's snapshot is
/// already current (same `head_commit` as the root's sidecar) and must NOT
/// be overwritten by a possibly-contaminated root (a build for the NEW
/// branch that failed midway leaves hybrid root content with the OLD
/// branch's sidecar still in place).
pub fn read_branch_dir_meta(project_root: &Path, branch_key: &str) -> Option<BranchMeta> {
    let path = branch_index_dir(project_root, branch_key).join("branch.json");
    let content = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&content).ok()
}

// ── branch_key derivation ───────────────────────────────────────────────────

/// Longest sanitized-name prefix kept in a branch_key. The 8-hex ref-name
/// hash carries the identity; the name prefix is only for human readability,
/// so capping it keeps `indexes/<branch_key>/...` paths clear of filesystem
/// name-length limits (ENAMETOOLONG) for pathological branch names.
const BRANCH_KEY_NAME_MAX: usize = 64;

/// Replace every non-alphanumeric (ASCII) byte with `-`, capped at
/// [`BRANCH_KEY_NAME_MAX`] chars. Applied to the branch name before
/// appending the ref-name hash. Output is pure ASCII (non-ASCII chars are
/// not alphanumeric-ASCII, so they map to `-`).
fn sanitize_branch_name(name: &str) -> String {
    name.chars()
        .take(BRANCH_KEY_NAME_MAX)
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect()
}

/// First 8 hex chars of SHA256(ref_name).
fn ref_name_hash8(ref_name: &str) -> String {
    use sha2::{Digest, Sha256};
    use std::fmt::Write as _;
    let mut hasher = Sha256::new();
    hasher.update(ref_name.as_bytes());
    let digest = hasher.finalize();
    digest[..4].iter().fold(String::new(), |mut out, b| {
        let _ = write!(out, "{b:02x}");
        out
    })
}

/// branch_key = sanitized branch name (non-alnum → `-`) + `-` + first 8 hex
/// of SHA256(ref name). Exposed standalone (rather than folded into
/// `current_branch_key`) so callers that already have a branch name (e.g.
/// the registry, or a federated target from another project) can compute the
/// same key without touching the filesystem.
pub fn branch_key_for_branch(branch_name: &str) -> String {
    format!(
        "{}-{}",
        sanitize_branch_name(branch_name),
        ref_name_hash8(branch_name)
    )
}

/// Resolve the `.git` directory for `project_root`, following the `gitdir:`
/// pointer file used by worktrees and submodules. Returns `None` if
/// `project_root` is not a git repository.
fn resolve_git_dir(project_root: &Path) -> Option<PathBuf> {
    let dot_git = project_root.join(".git");
    if dot_git.is_dir() {
        return Some(dot_git);
    }
    if dot_git.is_file() {
        let content = std::fs::read_to_string(&dot_git).ok()?;
        let pointer = content
            .lines()
            .find_map(|l| l.trim().strip_prefix("gitdir:"))?;
        let p = PathBuf::from(pointer.trim());
        return Some(if p.is_absolute() {
            p
        } else {
            project_root.join(p)
        });
    }
    None
}

/// The actual `HEAD` file to watch for branch-switch detection (Wave 2's
/// `semantex watch`). NOT necessarily `<project_root>/.git/HEAD` — for a
/// linked worktree, `.git` is a `gitdir:` pointer file and the real `HEAD`
/// lives in the main repo's `.git/worktrees/<name>/HEAD`, which is OUTSIDE
/// `project_root` entirely and would never be seen by a recursive watch of
/// the project directory. `None` for a non-git directory (nothing to
/// watch).
pub fn git_head_file(project_root: &Path) -> Option<PathBuf> {
    resolve_git_dir(project_root).map(|d| d.join("HEAD"))
}

/// Resolve the branch name HEAD currently points to. Returns `None` for a
/// detached HEAD (raw commit hash), an unreadable HEAD, or a non-git
/// directory — all of which map to the `"default"` branch_key.
pub fn resolve_git_head_branch(project_root: &Path) -> Option<String> {
    let git_dir = resolve_git_dir(project_root)?;
    let head = std::fs::read_to_string(git_dir.join("HEAD")).ok()?;
    head.trim()
        .strip_prefix("ref: refs/heads/")
        .map(str::to_string)
}

/// Look up `ref_name` (e.g. `refs/heads/main`) in `git_dir`: loose ref file
/// first, then `packed-refs`.
fn resolve_ref_in(git_dir: &Path, ref_name: &str) -> Option<String> {
    if let Ok(hash) = std::fs::read_to_string(git_dir.join(ref_name)) {
        return Some(hash.trim().to_string());
    }
    let packed = std::fs::read_to_string(git_dir.join("packed-refs")).ok()?;
    packed.lines().find_map(|line| {
        let line = line.trim();
        if line.starts_with('#') {
            return None;
        }
        let mut parts = line.split_whitespace();
        let hash = parts.next()?;
        let name = parts.next()?;
        (name == ref_name).then(|| hash.to_string())
    })
}

/// Resolve HEAD's commit hash on a best-effort basis (loose ref file, with
/// `packed-refs` and worktree-`commondir` fallbacks) rather than shelling out
/// to `git`, matching the rest of this module's no-git2-dependency approach.
pub fn resolve_git_head_commit(project_root: &Path) -> Option<String> {
    let git_dir = resolve_git_dir(project_root)?;
    let head = std::fs::read_to_string(git_dir.join("HEAD")).ok()?;
    let head = head.trim();
    if let Some(rest) = head.strip_prefix("ref: ") {
        if let Some(hash) = resolve_ref_in(&git_dir, rest) {
            return Some(hash);
        }
        // Linked worktree: its private gitdir (`.git/worktrees/<name>/`) holds
        // HEAD but NOT the shared refs/packed-refs — those live in the main
        // repo's git dir, pointed to by the `commondir` file (a path relative
        // to the worktree gitdir, usually `../..`).
        if let Ok(common) = std::fs::read_to_string(git_dir.join("commondir")) {
            let common = PathBuf::from(common.trim());
            let common_dir = if common.is_absolute() {
                common
            } else {
                git_dir.join(common)
            };
            return resolve_ref_in(&common_dir, rest);
        }
        return None;
    }
    // Detached HEAD: the file content IS the commit hash.
    Some(head.to_string())
}

/// branch_key for the branch currently checked out at `project_root`.
/// `"default"` for detached HEAD or a non-git directory (contract §A).
pub fn current_branch_key(project_root: &Path) -> String {
    match resolve_git_head_branch(project_root) {
        Some(branch) => branch_key_for_branch(&branch),
        None => DEFAULT_BRANCH_KEY.to_string(),
    }
}

/// The branch name to record alongside `current_branch_key` — mirrors its
/// git-resolution fallback so the two always agree on what "default" means.
pub fn current_branch_name(project_root: &Path) -> String {
    resolve_git_head_branch(project_root).unwrap_or_else(|| DEFAULT_BRANCH_KEY.to_string())
}

// ── history.db / memory.db schema (Wave 2 populates; spine creates) ────────

/// Open (creating if absent) `history.db` at `path`, ensuring the schema
/// from contract §A exists. Returns the raw connection — Wave 2 owns all
/// read/write access beyond schema creation.
pub fn open_history_db(path: &Path) -> Result<Connection> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let conn = Connection::open(path)?;
    conn.execute_batch(
        "
        CREATE TABLE IF NOT EXISTS commits (
            hash    TEXT PRIMARY KEY,
            author  TEXT NOT NULL,
            ts      INTEGER NOT NULL,
            message TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS file_commits (
            path TEXT NOT NULL,
            hash TEXT NOT NULL,
            PRIMARY KEY (path, hash)
        );
        CREATE TABLE IF NOT EXISTS chunk_blame (
            chunk_id INTEGER NOT NULL,
            hash     TEXT NOT NULL,
            PRIMARY KEY (chunk_id, hash)
        );
        ",
    )?;
    Ok(conn)
}

/// Open (creating if absent) `memory.db` at `path`, ensuring the schema from
/// contract §A exists. Returns the raw connection — Wave 2 owns all
/// read/write access beyond schema creation.
pub fn open_memory_db(path: &Path) -> Result<Connection> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let conn = Connection::open(path)?;
    conn.execute_batch(
        "
        CREATE TABLE IF NOT EXISTS notes (
            id         INTEGER PRIMARY KEY AUTOINCREMENT,
            created_ts INTEGER NOT NULL,
            updated_ts INTEGER NOT NULL,
            scope      TEXT NOT NULL,
            key        TEXT NOT NULL,
            content    TEXT NOT NULL,
            source     TEXT NOT NULL,
            UNIQUE(scope, key)
        );
        ",
    )?;
    Ok(conn)
}

// ── legacy → v13 migration / mirror ─────────────────────────────────────────

/// Recursively hard-link every file under `src` into the same relative path
/// under `dst`, creating directories as needed. Falls back to a real copy
/// for any file where `hard_link` fails (e.g. a cross-device mount) so the
/// mirror is always complete, just potentially non-free on odd filesystems.
///
/// ONLY safe for write-once/rename-replaced artifacts (tantivy `sparse/`):
/// hard links share the inode, so anything the builder later mutates
/// *in place* (SQLite page writes, `fs::write` truncation) would mutate the
/// mirror too. Mutable artifacts go through [`copy_tree`] instead.
fn hardlink_tree(src: &Path, dst: &Path) -> Result<()> {
    if src.is_dir() {
        std::fs::create_dir_all(dst)?;
        for entry in std::fs::read_dir(src)? {
            let entry = entry?;
            let name = entry.file_name();
            hardlink_tree(&src.join(&name), &dst.join(&name))?;
        }
    } else if src.is_file() {
        if let Some(parent) = dst.parent() {
            std::fs::create_dir_all(parent)?;
        }
        if std::fs::hard_link(src, dst).is_err() {
            std::fs::copy(src, dst)?;
        }
    }
    Ok(())
}

/// Recursively byte-copy every file under `src` into `dst` — a true
/// snapshot with its own inodes, immune to later in-place mutation of the
/// source. Used for the artifacts the builder rewrites in place
/// (`dense/**`, `meta.json`, `models.toml`).
fn copy_tree(src: &Path, dst: &Path) -> Result<()> {
    if src.is_dir() {
        std::fs::create_dir_all(dst)?;
        for entry in std::fs::read_dir(src)? {
            let entry = entry?;
            let name = entry.file_name();
            copy_tree(&src.join(&name), &dst.join(&name))?;
        }
    } else if src.is_file() {
        if let Some(parent) = dst.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::copy(src, dst)?;
    }
    Ok(())
}

/// Snapshot a live SQLite database into `dst`.
///
/// Primary path is `VACUUM INTO`, which produces a complete, consistent,
/// compacted copy **including any content still sitting in the `-wal` file**
/// — critical because the builder's own WAL-mode connection is typically
/// still open (un-checkpointed) when the mirror runs, so a plain file copy
/// of `chunks.db` alone would miss the newest rows. If `VACUUM INTO` is
/// unavailable/fails, fall back to `PRAGMA wal_checkpoint(TRUNCATE)` (fold
/// the WAL back into the main file) followed by a byte copy.
fn snapshot_sqlite_db(src: &Path, dst: &Path) -> Result<()> {
    if let Some(parent) = dst.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let conn = Connection::open(src)?;
    // VACUUM INTO refuses to overwrite; dst lives in a fresh tmp dir so it
    // never exists, but be defensive for the fallback/retry case.
    if dst.exists() {
        std::fs::remove_file(dst)?;
    }
    let dst_str = dst.to_string_lossy().into_owned();
    match conn.execute("VACUUM INTO ?1", [&dst_str]) {
        Ok(_) => Ok(()),
        Err(e) => {
            tracing::debug!("VACUUM INTO failed ({e}); falling back to checkpoint + copy");
            // Best-effort checkpoint; TRUNCATE also resets the -wal file so
            // the main db file is complete on its own. (query_row: this
            // PRAGMA returns a result row, so `execute` would error.)
            let _ = conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()));
            std::fs::copy(src, dst)?;
            Ok(())
        }
    }
}

/// Mirror the container root's current index content into
/// `indexes/<branch_key>/`, migrating a legacy (pre-v13) flat layout on
/// first encounter and refreshing an existing mirror on every subsequent
/// call. Rename-based and crash-safe: the mirror is built in a temporary
/// sibling directory and only swapped into place once complete, so a crash
/// mid-mirror leaves either the previous mirror or nothing — never a
/// half-written one — and the root (which this function never modifies)
/// stays fully functional throughout. No-op (returns `Ok(())`) if the
/// container root has no `chunks.db` yet (nothing built).
///
/// This is deliberately NOT a destructive move: the root stays the live,
/// authoritative copy that every existing (non-owned) reader depends on —
/// see the module doc for why.
///
/// Stamps the branch identity sidecar (branch name, `branch_key`,
/// head_commit) from the CURRENT git HEAD — correct for every existing call
/// site, which always passes `current_branch_key(project_root)` for
/// `branch_key` too, so the two never disagree. [`mirror_root_as`] is the
/// identity-parameterized core for the one caller (Wave 2's branch-switch
/// handling) that needs to snapshot the OUTGOING branch's root content — by
/// the time that runs, HEAD has already moved, so deriving identity from
/// HEAD would stamp the sidecar with the wrong (new) branch name.
pub fn mirror_into_branch_dir(project_root: &Path, branch_key: &str) -> Result<()> {
    let branch_meta = BranchMeta {
        branch: current_branch_name(project_root),
        branch_key: branch_key.to_string(),
        head_commit: resolve_git_head_commit(project_root),
    };
    mirror_root_as(project_root, &branch_meta)
}

/// Identity-parameterized core of [`mirror_into_branch_dir`] — snapshots the
/// container root's current index content into `indexes/<branch_meta.branch_key>/`,
/// stamping the sidecar (both there and at the root) with `branch_meta`
/// verbatim rather than re-deriving it from the current git HEAD. See
/// [`mirror_into_branch_dir`]'s doc for why that distinction matters.
pub fn mirror_root_as(project_root: &Path, branch_meta: &BranchMeta) -> Result<()> {
    let container = container_dir(project_root);
    if !container.join("chunks.db").exists() {
        return Ok(());
    }

    let branch_key = branch_meta.branch_key.as_str();
    let branch_dir = branch_index_dir(project_root, branch_key);
    // Pid-suffixed so two processes racing to mirror the same branch never
    // stomp each other's half-built tmp dir (same idiom as
    // `registry::save_registry_to`). Orphans from crashed processes are
    // swept by `cleanup_stale_tmp_artifacts` under the index lock.
    let tmp_dir =
        indexes_root(project_root).join(format!("{branch_key}.tmp-mirror.{}", std::process::id()));
    if tmp_dir.exists() {
        std::fs::remove_dir_all(&tmp_dir)?;
    }
    std::fs::create_dir_all(&tmp_dir)?;

    // chunks.db: SQLite snapshot — includes un-checkpointed WAL content and
    // detaches the mirror from future in-place page writes (see
    // `snapshot_sqlite_db`). NEVER hard-link a live SQLite db.
    //
    // history.db (and memory.db) are deliberately NOT part of the mirror:
    // both are repo-GLOBAL container-root files, not per-branch index state.
    // history.db in particular is an incrementally-accumulated view of the
    // repo's git log — git itself is the ever-present source of truth and
    // `index::history::populate_history` is idempotent/incremental, so a
    // snapshot protects nothing while a restore could replace a richer root
    // with a poorer snapshot. Branch switches must leave it untouched.
    snapshot_sqlite_db(&container.join("chunks.db"), &tmp_dir.join("chunks.db"))?;

    // meta.json / models.toml: rewritten in place by `fs::write` on later
    // builds (same inode, truncate + rewrite) — must be copies.
    for name in ["meta.json", "models.toml"] {
        let src = container.join(name);
        if src.is_file() {
            copy_tree(&src, &tmp_dir.join(name))?;
        }
    }
    // dense/**: vectors/pointer files are rewritten via `fs::write` on
    // incremental builds — must be copies.
    let dense_src = container.join("dense");
    if dense_src.is_dir() {
        copy_tree(&dense_src, &tmp_dir.join("dense"))?;
    }
    // sparse/ (tantivy): segment files are write-once and tantivy's own
    // meta.json is replaced by atomic rename — hard-link-safe, and it's the
    // bulk of the index, so links keep the snapshot near-free on disk.
    let sparse_src = container.join("sparse");
    if sparse_src.is_dir() {
        hardlink_tree(&sparse_src, &tmp_dir.join("sparse"))?;
    }

    // Branch identity sidecar (contract: per-index meta carries branch name +
    // head_commit; kept out of the shared IndexMeta struct — see module doc).
    // Written INTO the tmp dir BEFORE the swap so a crash can never leave a
    // snapshot in place without its identity sidecar (an identity-less
    // snapshot would be invisible to `read_branch_dir_meta` and wrongly
    // re-mirrored over on the next branch switch).
    let json = serde_json::to_string_pretty(branch_meta)?;
    std::fs::write(tmp_dir.join("branch.json"), &json)?;

    if branch_dir.exists() {
        std::fs::remove_dir_all(&branch_dir)?;
    }
    std::fs::rename(&tmp_dir, &branch_dir)?;

    // Wave 2: also stamp the root sidecar so `read_root_branch_meta` always
    // reflects which branch the LIVE `.semantex/` content currently belongs
    // to — the signal `index::branches::detect_and_handle_branch_switch`
    // compares against `current_branch_key` on every entry point.
    std::fs::write(container.join("branch.json"), &json)?;

    Ok(())
}

/// Reverse of [`mirror_into_branch_dir`]: restore a previously-snapshotted
/// `indexes/<branch_key>/` into the container root, making it the LIVE,
/// authoritative index again. Used when a branch switch lands on a branch
/// that already has a saved snapshot — restoring it first means the
/// subsequent incremental build only has to catch drift since the snapshot
/// was taken, instead of re-embedding the whole tree.
///
/// Same snapshot discipline as the forward direction, just inverted:
/// `chunks.db` is re-snapshotted (never hard-linked — the restored root will
/// immediately be written to in place by the next incremental build, and a
/// hard link would let those writes leak backward into the branch dir's own
/// mirror), `meta.json`/`models.toml`/`dense/**` are byte-copied, and
/// `sparse/` (tantivy) is hard-linked (write-once/rename-replace, so mutating
/// the restored root's tantivy dir later can never corrupt the branch dir's
/// copy — same reasoning as the forward direction). Individual files are
/// swapped into place via a tmp-then-rename so a crash mid-restore can never
/// leave the root with a torn/partial file — at worst it's left with a mix
/// of some already-restored and some still-old-branch files, all of them
/// individually intact, and safe to retry.
///
/// No-op if `branch_key` has no snapshot yet (nothing to restore).
///
/// MUST be called with the exclusive `<project>/.semantex/.semantex.lock`
/// held (the same lock `IndexBuilder::build` takes): readers use that lock
/// as the "index is being mutated" signal (`state::detect` returns
/// `Building` while it's held), and the WAL/SHM removal below is only safe
/// when no live writer connection exists. The one production caller,
/// [`crate::index::branches::detect_and_handle_branch_switch`], acquires it.
pub fn restore_branch_dir_into_root(project_root: &Path, branch_key: &str) -> Result<()> {
    let branch_dir = branch_index_dir(project_root, branch_key);
    if !branch_dir.join("chunks.db").exists() {
        return Ok(());
    }
    let container = container_dir(project_root);
    std::fs::create_dir_all(&container)?;

    // All tmp names are pid-suffixed so two processes racing to restore never
    // clobber each other's half-written files (same idiom as
    // `registry::save_registry_to`); orphans from crashed processes are swept
    // by `cleanup_stale_tmp_artifacts` under the index lock.
    let pid = std::process::id();

    // chunks.db: snapshot into a tmp file, then atomic rename over the root's.
    let tmp_chunks =
        indexes_root(project_root).join(format!("{branch_key}.chunks.tmp-restore.{pid}"));
    if tmp_chunks.exists() {
        std::fs::remove_file(&tmp_chunks)?;
    }
    snapshot_sqlite_db(&branch_dir.join("chunks.db"), &tmp_chunks)?;
    std::fs::rename(&tmp_chunks, container.join("chunks.db"))?;

    // The root's chunks.db is WAL-mode and long-lived connections are the
    // norm (serve daemon, MCP cached searchers), so the OLD branch's
    // `chunks.db-wal` / `chunks.db-shm` can survive the rename above. Left
    // in place, the next connection would replay the old branch's WAL frames
    // onto the NEW branch's freshly-restored db file — hybrid content or
    // outright "database disk image is malformed". The caller holds the
    // exclusive index lock here (see `branches::detect_and_handle_branch_switch`),
    // so no live writer exists and dropping the sidecar files is safe.
    for suffix in ["-wal", "-shm", "-journal"] {
        let sidecar = container.join(format!("chunks.db{suffix}"));
        match std::fs::remove_file(&sidecar) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => {
                return Err(e).with_context(|| {
                    format!(
                        "restore: failed to remove stale {} beside the restored chunks.db",
                        sidecar.display()
                    )
                });
            }
        }
    }

    // history.db / memory.db: intentionally NOT restored — they're
    // repo-global container-root files excluded from the per-branch mirror
    // (see the matching note in `mirror_root_as`), so a branch switch must
    // leave whatever the root has accumulated fully intact.

    // meta.json / models.toml: plain copies, tmp-then-rename swapped in.
    // When the snapshot LACKS one of these, remove the root's leftover copy
    // rather than keeping the old branch's — a stale root `models.toml`
    // could silently change embedder selection for the restored branch.
    for name in ["meta.json", "models.toml"] {
        let src = branch_dir.join(name);
        let dst = container.join(name);
        if !src.is_file() {
            match std::fs::remove_file(&dst) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => {
                    return Err(e).with_context(|| {
                        format!("restore: failed to remove leftover {}", dst.display())
                    });
                }
            }
            continue;
        }
        let tmp = indexes_root(project_root).join(format!("{branch_key}.{name}.tmp-restore.{pid}"));
        std::fs::copy(&src, &tmp)?;
        std::fs::rename(&tmp, dst)?;
    }

    // dense/**: rewritten in place by the builder — restore as a fresh copy,
    // swapped in via a tmp dir + rename so readers never see a half-written
    // dense/ directory.
    let dense_dst = container.join("dense");
    let dense_src = branch_dir.join("dense");
    if dense_src.is_dir() {
        let tmp_dense =
            indexes_root(project_root).join(format!("{branch_key}.dense.tmp-restore.{pid}"));
        if tmp_dense.exists() {
            std::fs::remove_dir_all(&tmp_dense)?;
        }
        copy_tree(&dense_src, &tmp_dense)?;
        if dense_dst.exists() {
            std::fs::remove_dir_all(&dense_dst)?;
        }
        std::fs::rename(&tmp_dense, &dense_dst)?;
    } else if dense_dst.exists() {
        std::fs::remove_dir_all(&dense_dst)?;
    }

    // sparse/ (tantivy): hard-link-safe in this direction too (write-once
    // segments + rename-replaced meta.json), same reasoning as the forward
    // mirror — and it's the bulk of the index, so this keeps restores cheap.
    let sparse_dst = container.join("sparse");
    let sparse_src = branch_dir.join("sparse");
    if sparse_src.is_dir() {
        let tmp_sparse =
            indexes_root(project_root).join(format!("{branch_key}.sparse.tmp-restore.{pid}"));
        if tmp_sparse.exists() {
            std::fs::remove_dir_all(&tmp_sparse)?;
        }
        hardlink_tree(&sparse_src, &tmp_sparse)?;
        if sparse_dst.exists() {
            std::fs::remove_dir_all(&sparse_dst)?;
        }
        std::fs::rename(&tmp_sparse, &sparse_dst)?;
    } else if sparse_dst.exists() {
        std::fs::remove_dir_all(&sparse_dst)?;
    }

    // Root sidecar now reflects the restored branch.
    if let Ok(branch_meta_json) = std::fs::read_to_string(branch_dir.join("branch.json")) {
        std::fs::write(container.join("branch.json"), branch_meta_json)?;
    }

    Ok(())
}

/// Best-effort sweep of orphaned in-flight artifacts (`*.tmp-mirror.*` /
/// `*.tmp-restore.*` files and dirs) left in `indexes/` by a crashed
/// mirror/restore. They are deliberately excluded from retention's eviction
/// (a live process's tmp dir must never be GC'd as a "stale branch"), so
/// without this sweep they would accumulate forever.
///
/// ONLY call while holding the exclusive `.semantex.lock` — every writer of
/// these tmp names (mirror via the builder's lock, restore via
/// `branches::detect_and_handle_branch_switch`'s lock) runs under it, so
/// with the lock held, anything matching the pattern is guaranteed to be an
/// orphan from a dead process, not another process's work in flight.
pub fn cleanup_stale_tmp_artifacts(project_root: &Path) {
    let indexes = indexes_root(project_root);
    let Ok(entries) = std::fs::read_dir(&indexes) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        if !name.contains(".tmp-") {
            continue;
        }
        let path = entry.path();
        let removed = if path.is_dir() {
            std::fs::remove_dir_all(&path)
        } else {
            std::fs::remove_file(&path)
        };
        match removed {
            Ok(()) => tracing::info!(path = %path.display(), "Removed orphaned tmp artifact"),
            Err(e) => tracing::debug!(path = %path.display(), "Could not remove tmp artifact: {e}"),
        }
    }
}

/// Ensure the full v13 layout exists for `project_root`: migrate/refresh the
/// per-branch mirror (if any index content exists yet), create the
/// `history.db` / `memory.db` schemas, and upgrade the top-level
/// `meta.json` to the v13 [`ProjectMeta`] shape (superset-compatible with
/// legacy `IndexMeta` readers). `project_id` is a stable identifier for this
/// project (see [`crate::index::registry`] for how it's minted/looked up).
///
/// Mirror-step failures are logged and do not fail the overall call — the
/// root index (built by the existing, unmodified `IndexBuilder` pipeline)
/// remains valid and searchable regardless of whether the v13 mirror could
/// be written.
pub fn sync_v13_layout(project_root: &Path, project_id: &str) -> Result<PathBuf> {
    let container = container_dir(project_root);
    std::fs::create_dir_all(&container)?;
    let branch_key = current_branch_key(project_root);

    if let Err(e) = mirror_into_branch_dir(project_root, &branch_key) {
        tracing::warn!("v13 layout mirror failed (root index still valid): {e}");
    }

    let _ = open_history_db(&history_db_path(project_root))?;
    let _ = open_memory_db(&memory_db_path(project_root))?;

    let meta_path = project_meta_path(project_root);
    if let Ok(existing) = std::fs::read_to_string(&meta_path)
        && let Ok(active_index_meta) = serde_json::from_str::<IndexMeta>(&existing)
    {
        let project_meta = ProjectMeta {
            layout_version: LAYOUT_VERSION,
            project_id: project_id.to_string(),
            default_branch: current_branch_name(project_root),
            active_index_meta,
        };
        let json = serde_json::to_string_pretty(&project_meta)?;
        std::fs::write(&meta_path, json)?;
    }

    Ok(branch_index_dir(project_root, &branch_key))
}

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

    #[test]
    fn sanitize_replaces_non_alnum() {
        assert_eq!(sanitize_branch_name("feature/foo-bar"), "feature-foo-bar");
        assert_eq!(sanitize_branch_name("main"), "main");
        assert_eq!(sanitize_branch_name("a b.c"), "a-b-c");
    }

    #[test]
    fn branch_key_is_deterministic_and_unique_per_name() {
        let k1 = branch_key_for_branch("main");
        let k2 = branch_key_for_branch("main");
        let k3 = branch_key_for_branch("develop");
        assert_eq!(k1, k2, "same branch name must yield the same key");
        assert_ne!(k1, k3, "different branch names must yield different keys");
        assert!(k1.starts_with("main-"));
        // sanitized-name + '-' + 8 hex chars
        let hash_part = k1.rsplit('-').next().unwrap();
        assert_eq!(hash_part.len(), 8);
        assert!(hash_part.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn non_git_dir_resolves_to_default_branch_key() {
        let tmp = TempDir::new().unwrap();
        assert_eq!(current_branch_key(tmp.path()), DEFAULT_BRANCH_KEY);
        assert_eq!(current_branch_name(tmp.path()), DEFAULT_BRANCH_KEY);
    }

    #[test]
    fn resolves_current_branch_from_real_git_dir() {
        let tmp = TempDir::new().unwrap();
        let git_dir = tmp.path().join(".git");
        std::fs::create_dir_all(git_dir.join("refs").join("heads")).unwrap();
        std::fs::write(git_dir.join("HEAD"), "ref: refs/heads/feature/x\n").unwrap();
        std::fs::write(git_dir.join("refs").join("heads").join("x"), "deadbeef\n").unwrap();
        assert_eq!(
            resolve_git_head_branch(tmp.path()),
            Some("feature/x".to_string())
        );
        assert_eq!(
            current_branch_key(tmp.path()),
            branch_key_for_branch("feature/x")
        );
    }

    #[test]
    fn git_head_file_resolves_in_main_repo_and_worktree() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".git")).unwrap();
        assert_eq!(
            git_head_file(tmp.path()),
            Some(tmp.path().join(".git").join("HEAD"))
        );

        // Non-git directory: nothing to watch.
        let non_git = TempDir::new().unwrap();
        assert_eq!(git_head_file(non_git.path()), None);

        // Linked worktree: HEAD lives in the private worktree gitdir, NOT
        // under project_root.
        let real_git = tmp.path().join("real.git").join("worktrees").join("wt1");
        std::fs::create_dir_all(&real_git).unwrap();
        let worktree = tmp.path().join("worktree-dir");
        std::fs::create_dir_all(&worktree).unwrap();
        std::fs::write(
            worktree.join(".git"),
            format!("gitdir: {}\n", real_git.display()),
        )
        .unwrap();
        assert_eq!(git_head_file(&worktree), Some(real_git.join("HEAD")));
    }

    #[test]
    fn detached_head_resolves_to_default() {
        let tmp = TempDir::new().unwrap();
        let git_dir = tmp.path().join(".git");
        std::fs::create_dir_all(&git_dir).unwrap();
        std::fs::write(git_dir.join("HEAD"), "deadbeefdeadbeefdeadbeef\n").unwrap();
        assert_eq!(resolve_git_head_branch(tmp.path()), None);
        assert_eq!(current_branch_key(tmp.path()), DEFAULT_BRANCH_KEY);
    }

    #[test]
    fn worktree_gitdir_pointer_is_followed() {
        let tmp = TempDir::new().unwrap();
        let real_git = tmp.path().join("real.git").join("worktrees").join("wt1");
        std::fs::create_dir_all(&real_git).unwrap();
        std::fs::write(real_git.join("HEAD"), "ref: refs/heads/main\n").unwrap();

        let worktree = tmp.path().join("worktree-dir");
        std::fs::create_dir_all(&worktree).unwrap();
        std::fs::write(
            worktree.join(".git"),
            format!("gitdir: {}\n", real_git.display()),
        )
        .unwrap();

        assert_eq!(resolve_git_head_branch(&worktree), Some("main".to_string()));
    }

    fn sample_index_meta() -> IndexMeta {
        IndexMeta {
            schema_version: IndexMeta::CURRENT_SCHEMA_VERSION,
            project_path: PathBuf::from("/x"),
            created_at: "0".to_string(),
            updated_at: "0".to_string(),
            file_count: 3,
            chunk_count: 9,
            embedding_model: "CodeRankEmbed".to_string(),
            embedding_dim: 768,
            use_bm25_stemmer: true,
            dense_backend: "coderank-hnsw".to_string(),
            embedder_fingerprint: "fp".to_string(),
        }
    }

    /// The whole point of flattening: existing readers that parse
    /// `meta.json` as plain `IndexMeta` must keep working against the v13
    /// top-level `ProjectMeta` shape.
    #[test]
    fn project_meta_is_superset_compatible_with_index_meta() {
        let project_meta = ProjectMeta {
            layout_version: LAYOUT_VERSION,
            project_id: "proj-abc".to_string(),
            default_branch: "main".to_string(),
            active_index_meta: sample_index_meta(),
        };
        let json = serde_json::to_string(&project_meta).unwrap();

        // A legacy reader doing exactly what state::is_stale / builder.rs do.
        let back: IndexMeta = serde_json::from_str(&json).unwrap();
        assert_eq!(back.schema_version, IndexMeta::CURRENT_SCHEMA_VERSION);
        assert_eq!(back.embedder_fingerprint, "fp");

        // And it must also round-trip as ProjectMeta.
        let back2: ProjectMeta = serde_json::from_str(&json).unwrap();
        assert_eq!(back2.layout_version, LAYOUT_VERSION);
        assert_eq!(back2.project_id, "proj-abc");
        assert_eq!(back2.default_branch, "main");
        assert_eq!(back2.active_index_meta.chunk_count, 9);
    }

    #[test]
    fn history_and_memory_db_schemas_are_created() {
        let tmp = TempDir::new().unwrap();
        let history = open_history_db(&tmp.path().join("history.db")).unwrap();
        history
            .execute(
                "INSERT INTO commits (hash, author, ts, message) VALUES ('h1', 'a', 1, 'm')",
                [],
            )
            .unwrap();
        history
            .execute(
                "INSERT INTO file_commits (path, hash) VALUES ('f.rs', 'h1')",
                [],
            )
            .unwrap();
        history
            .execute(
                "INSERT INTO chunk_blame (chunk_id, hash) VALUES (1, 'h1')",
                [],
            )
            .unwrap();

        let memory = open_memory_db(&tmp.path().join("memory.db")).unwrap();
        memory
            .execute(
                "INSERT INTO notes (created_ts, updated_ts, scope, key, content, source) \
                 VALUES (1, 1, 's', 'k', 'c', 'src')",
                [],
            )
            .unwrap();
        // UNIQUE(scope, key) must reject a duplicate.
        let dup = memory.execute(
            "INSERT INTO notes (created_ts, updated_ts, scope, key, content, source) \
             VALUES (2, 2, 's', 'k', 'c2', 'src2')",
            [],
        );
        assert!(dup.is_err(), "duplicate (scope,key) must be rejected");

        // Re-opening (idempotent schema creation) must not error.
        open_history_db(&tmp.path().join("history.db")).unwrap();
        open_memory_db(&tmp.path().join("memory.db")).unwrap();
    }

    /// Round-trip: build an index with the LEGACY (pre-v13) flat layout,
    /// then run the v13 sync — the content must be migrated into
    /// `indexes/<branch_key>/` and stay searchable there.
    #[test]
    fn legacy_layout_round_trips_through_v13_migration() {
        use crate::index::storage::ChunkStore;
        use crate::types::{Chunk, ChunkType};

        let tmp = TempDir::new().unwrap();
        let project = tmp.path();
        let container = container_dir(project);
        std::fs::create_dir_all(&container).unwrap();

        // Simulate a legacy build: chunks.db + meta.json directly at the root.
        let chunk_id = {
            let store = ChunkStore::open(&container.join("chunks.db")).unwrap();
            let chunk = Chunk {
                id: 0,
                file_path: PathBuf::from("src/lib.rs"),
                start_line: 1,
                end_line: 5,
                content: "fn legacy() {}".to_string(),
                chunk_type: ChunkType::TextWindow { window_index: 0 },
            };
            store.insert_chunk(&chunk, 0xdead, 0).unwrap()
        };
        std::fs::write(
            container.join("meta.json"),
            serde_json::to_string(&sample_index_meta()).unwrap(),
        )
        .unwrap();
        std::fs::create_dir_all(container.join("sparse")).unwrap();
        std::fs::write(container.join("sparse").join("seg.dat"), b"tantivy-ish").unwrap();

        let branch_dir = sync_v13_layout(project, "proj-123").unwrap();

        // Migrated: the branch dir now has its own chunks.db with the same data.
        assert!(branch_dir.join("chunks.db").exists());
        assert!(branch_dir.join("meta.json").exists());
        assert!(branch_dir.join("branch.json").exists());
        assert!(branch_dir.join("sparse").join("seg.dat").exists());

        let migrated_store = ChunkStore::open(&branch_dir.join("chunks.db")).unwrap();
        let chunk = migrated_store.get_chunk(chunk_id).unwrap();
        assert_eq!(chunk.content, "fn legacy() {}");

        // The branch meta.json is a snapshot of the root meta.json as of
        // mirror time (plain IndexMeta on this first legacy migration; the
        // flattened ProjectMeta on later syncs) — either way it must parse
        // as IndexMeta, the shape every per-index reader expects.
        let branch_meta_json = std::fs::read_to_string(branch_dir.join("meta.json")).unwrap();
        let branch_meta: IndexMeta = serde_json::from_str(&branch_meta_json).unwrap();
        assert_eq!(branch_meta.chunk_count, 9);

        // The root is UNCHANGED and still fully functional (no readers broke).
        let root_store = ChunkStore::open(&container.join("chunks.db")).unwrap();
        let root_chunk = root_store.get_chunk(chunk_id).unwrap();
        assert_eq!(root_chunk.content, "fn legacy() {}");

        // Top-level meta.json is now the v13 ProjectMeta shape, but still
        // parses as plain IndexMeta for legacy readers.
        let top_json = std::fs::read_to_string(container.join("meta.json")).unwrap();
        let top_as_project: ProjectMeta = serde_json::from_str(&top_json).unwrap();
        assert_eq!(top_as_project.layout_version, LAYOUT_VERSION);
        assert_eq!(top_as_project.project_id, "proj-123");
        let top_as_legacy: IndexMeta = serde_json::from_str(&top_json).unwrap();
        assert_eq!(top_as_legacy.chunk_count, 9);

        // Idempotent: running the sync again must not error and must refresh cleanly.
        let branch_dir_2 = sync_v13_layout(project, "proj-123").unwrap();
        assert_eq!(branch_dir, branch_dir_2);
        assert!(branch_dir_2.join("chunks.db").exists());

        // history.db / memory.db created at the container root.
        assert!(history_db_path(project).exists());
        assert!(memory_db_path(project).exists());
    }

    /// A brand-new project (no `chunks.db` yet) must not error — sync is a
    /// safe no-op for the mirror step, though it still creates the aux DBs.
    #[test]
    fn sync_on_empty_project_is_a_safe_no_op_for_mirror() {
        let tmp = TempDir::new().unwrap();
        let branch_dir = sync_v13_layout(tmp.path(), "proj-empty").unwrap();
        assert!(!branch_dir.join("chunks.db").exists());
        assert!(history_db_path(tmp.path()).exists());
        assert!(memory_db_path(tmp.path()).exists());
    }

    #[test]
    fn branch_key_name_prefix_is_capped() {
        let long_name = "x".repeat(500);
        let key = branch_key_for_branch(&long_name);
        // capped prefix + '-' + 8 hex chars
        assert_eq!(key.len(), BRANCH_KEY_NAME_MAX + 1 + 8, "key was: {key}");
        // Identity still lives in the hash: two long names sharing the first
        // 64 chars must still get distinct keys.
        let key2 = branch_key_for_branch(&format!("{}{}", "x".repeat(64), "different-tail"));
        assert_ne!(key, key2);
        // And the same name is still deterministic.
        assert_eq!(key, branch_key_for_branch(&long_name));
    }

    /// Linked-worktree layout: the worktree's private gitdir holds HEAD but
    /// refs/packed-refs live in the main repo's git dir, reachable via the
    /// `commondir` pointer file. head_commit must resolve through it.
    #[test]
    fn worktree_commondir_fallback_resolves_head_commit() {
        let tmp = TempDir::new().unwrap();
        // Main repo git dir with the actual ref.
        let main_git = tmp.path().join("main.git");
        std::fs::create_dir_all(main_git.join("refs").join("heads")).unwrap();
        std::fs::write(
            main_git.join("refs").join("heads").join("main"),
            "cafebabe\n",
        )
        .unwrap();
        // Worktree private gitdir: HEAD + commondir, but NO refs of its own.
        let wt_git = main_git.join("worktrees").join("wt1");
        std::fs::create_dir_all(&wt_git).unwrap();
        std::fs::write(wt_git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
        std::fs::write(wt_git.join("commondir"), "../..\n").unwrap();

        let worktree = tmp.path().join("wt");
        std::fs::create_dir_all(&worktree).unwrap();
        std::fs::write(
            worktree.join(".git"),
            format!("gitdir: {}\n", wt_git.display()),
        )
        .unwrap();

        assert_eq!(
            resolve_git_head_commit(&worktree),
            Some("cafebabe".to_string())
        );
        // packed-refs via commondir too.
        std::fs::remove_file(main_git.join("refs").join("heads").join("main")).unwrap();
        std::fs::write(main_git.join("packed-refs"), "deadf00d refs/heads/main\n").unwrap();
        assert_eq!(
            resolve_git_head_commit(&worktree),
            Some("deadf00d".to_string())
        );
    }

    /// THE snapshot guarantee (adversarial-review followup #3): after a
    /// mirror, mutating the ROOT index in place — new SQLite rows in
    /// chunks.db, `fs::write` truncation of dense/** and meta.json (exactly
    /// what an incremental re-index after a branch switch does) — must NOT
    /// change the mirrored branch dir. Hard-linked aliases fail this test;
    /// snapshots pass it.
    #[test]
    fn mirror_is_a_snapshot_not_an_alias_of_the_root() {
        use crate::index::storage::ChunkStore;
        use crate::types::{Chunk, ChunkType};

        let tmp = TempDir::new().unwrap();
        let project = tmp.path();
        let container = container_dir(project);
        std::fs::create_dir_all(container.join("dense").join("backend")).unwrap();

        let chunk = |id: u64, content: &str| Chunk {
            id,
            file_path: PathBuf::from("src/lib.rs"),
            start_line: 1,
            end_line: 2,
            content: content.to_string(),
            chunk_type: ChunkType::TextWindow { window_index: 0 },
        };

        let store = ChunkStore::open(&container.join("chunks.db")).unwrap();
        let old_id = store
            .insert_chunk(&chunk(0, "fn old_branch() {}"), 1, 0)
            .unwrap();
        std::fs::write(
            container.join("meta.json"),
            serde_json::to_string(&sample_index_meta()).unwrap(),
        )
        .unwrap();
        std::fs::write(
            container.join("dense").join("backend").join("vectors.bin"),
            b"old-branch-vectors",
        )
        .unwrap();

        mirror_into_branch_dir(project, "oldbranch-aaaa1111").unwrap();
        let mirror = branch_index_dir(project, "oldbranch-aaaa1111");

        // Simulate `git switch` + incremental re-index mutating the ROOT
        // in place, through the same inodes the old code hard-linked:
        // SQLite in-place writes...
        let new_id = store
            .insert_chunk(&chunk(0, "fn new_branch() {}"), 2, 0)
            .unwrap();
        drop(store);
        // ...and fs::write truncation of dense + meta.
        std::fs::write(
            container.join("dense").join("backend").join("vectors.bin"),
            b"NEW-branch-vectors-completely-different",
        )
        .unwrap();
        let mut new_meta = sample_index_meta();
        new_meta.chunk_count = 999;
        std::fs::write(
            container.join("meta.json"),
            serde_json::to_string(&new_meta).unwrap(),
        )
        .unwrap();

        // The mirror must still be the OLD branch's data, untouched.
        let mirror_store = ChunkStore::open(&mirror.join("chunks.db")).unwrap();
        assert_eq!(
            mirror_store.get_chunk(old_id).unwrap().content,
            "fn old_branch() {}"
        );
        assert!(
            mirror_store.get_chunk(new_id).is_err(),
            "post-mirror root writes must NOT leak into the mirror"
        );
        assert_eq!(
            std::fs::read(mirror.join("dense").join("backend").join("vectors.bin")).unwrap(),
            b"old-branch-vectors"
        );
        let mirror_meta: IndexMeta =
            serde_json::from_str(&std::fs::read_to_string(mirror.join("meta.json")).unwrap())
                .unwrap();
        assert_eq!(
            mirror_meta.chunk_count, 9,
            "meta snapshot must not follow the root"
        );
    }

    /// WAL correctness (followup #3a): the builder's WAL-mode connection is
    /// still OPEN (rows un-checkpointed, living only in `chunks.db-wal`)
    /// when the mirror runs. The snapshot must still contain those rows —
    /// `VACUUM INTO` (or checkpoint-then-copy) guarantees it; a naive file
    /// copy/hard-link of `chunks.db` alone would silently drop them.
    #[test]
    fn mirror_captures_unchekpointed_wal_content() {
        use crate::index::storage::ChunkStore;
        use crate::types::{Chunk, ChunkType};

        let tmp = TempDir::new().unwrap();
        let project = tmp.path();
        let container = container_dir(project);
        std::fs::create_dir_all(&container).unwrap();

        // ChunkStore opens in WAL mode; KEEP the connection open across the
        // mirror so nothing gets checkpointed by a connection close.
        let store = ChunkStore::open(&container.join("chunks.db")).unwrap();
        let id = store
            .insert_chunk(
                &Chunk {
                    id: 0,
                    file_path: PathBuf::from("src/wal.rs"),
                    start_line: 1,
                    end_line: 1,
                    content: "fn only_in_wal() {}".to_string(),
                    chunk_type: ChunkType::TextWindow { window_index: 0 },
                },
                7,
                0,
            )
            .unwrap();

        mirror_into_branch_dir(project, "walbranch-bbbb2222").unwrap();

        let mirror = branch_index_dir(project, "walbranch-bbbb2222");
        let mirror_store = ChunkStore::open(&mirror.join("chunks.db")).unwrap();
        assert_eq!(
            mirror_store.get_chunk(id).unwrap().content,
            "fn only_in_wal() {}",
            "rows still in the root's WAL must be present in the snapshot"
        );
        drop(store);
    }

    /// Branch-switch simulation (followup #4 semantics): after switching git
    /// HEAD to a new branch, a sync — even one triggered by a build that
    /// found zero content changes — must create the NEW branch's index dir
    /// while leaving the old branch's mirror intact.
    #[test]
    fn sync_after_branch_switch_creates_new_branch_dir_and_keeps_old() {
        use crate::index::storage::ChunkStore;
        use crate::types::{Chunk, ChunkType};

        let tmp = TempDir::new().unwrap();
        let project = tmp.path();
        let container = container_dir(project);
        std::fs::create_dir_all(&container).unwrap();

        // Fake git repo on branch `main`.
        let git = project.join(".git");
        std::fs::create_dir_all(git.join("refs").join("heads")).unwrap();
        std::fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
        std::fs::write(git.join("refs").join("heads").join("main"), "abc123\n").unwrap();

        {
            let store = ChunkStore::open(&container.join("chunks.db")).unwrap();
            store
                .insert_chunk(
                    &Chunk {
                        id: 0,
                        file_path: PathBuf::from("src/a.rs"),
                        start_line: 1,
                        end_line: 1,
                        content: "fn a() {}".to_string(),
                        chunk_type: ChunkType::TextWindow { window_index: 0 },
                    },
                    1,
                    0,
                )
                .unwrap();
        }
        std::fs::write(
            container.join("meta.json"),
            serde_json::to_string(&sample_index_meta()).unwrap(),
        )
        .unwrap();

        sync_v13_layout(project, "proj-sw").unwrap();
        let main_dir = branch_index_dir(project, &branch_key_for_branch("main"));
        assert!(main_dir.join("chunks.db").exists());

        // `git switch -c feature/new` (same tree → a re-index would find
        // zero content changes and take the builder's early return — which
        // now also syncs).
        std::fs::write(git.join("HEAD"), "ref: refs/heads/feature/new\n").unwrap();
        std::fs::write(git.join("refs").join("heads").join("feature"), "").unwrap(); // noise
        sync_v13_layout(project, "proj-sw").unwrap();

        let feature_dir = branch_index_dir(project, &branch_key_for_branch("feature/new"));
        assert!(
            feature_dir.join("chunks.db").exists(),
            "new branch dir must be created by a no-change sync"
        );
        assert!(
            main_dir.join("chunks.db").exists(),
            "old branch mirror must survive the switch"
        );
        // Each carries its own branch identity sidecar.
        let feature_meta: BranchMeta = serde_json::from_str(
            &std::fs::read_to_string(feature_dir.join("branch.json")).unwrap(),
        )
        .unwrap();
        assert_eq!(feature_meta.branch, "feature/new");
        let main_meta: BranchMeta =
            serde_json::from_str(&std::fs::read_to_string(main_dir.join("branch.json")).unwrap())
                .unwrap();
        assert_eq!(main_meta.branch, "main");
    }

    /// Wave 2: `mirror_into_branch_dir` also stamps the ROOT-level
    /// `branch.json` sidecar (`read_root_branch_meta`) — the signal
    /// `index::branches::detect_and_handle_branch_switch` compares against
    /// `current_branch_key` on every entry point.
    #[test]
    fn mirror_stamps_root_branch_sidecar() {
        use crate::index::storage::ChunkStore;
        use crate::types::{Chunk, ChunkType};

        let tmp = TempDir::new().unwrap();
        let project = tmp.path();
        let container = container_dir(project);
        std::fs::create_dir_all(&container).unwrap();

        assert!(
            read_root_branch_meta(project).is_none(),
            "no root sidecar before anything is built"
        );

        let store = ChunkStore::open(&container.join("chunks.db")).unwrap();
        let _ = store
            .insert_chunk(
                &Chunk {
                    id: 0,
                    file_path: PathBuf::from("src/a.rs"),
                    start_line: 1,
                    end_line: 1,
                    content: "fn a() {}".to_string(),
                    chunk_type: ChunkType::TextWindow { window_index: 0 },
                },
                1,
                0,
            )
            .unwrap();
        drop(store);
        std::fs::write(
            container.join("meta.json"),
            serde_json::to_string(&sample_index_meta()).unwrap(),
        )
        .unwrap();

        mirror_into_branch_dir(project, "somebranch-cafe1234").unwrap();
        let root_meta = read_root_branch_meta(project).expect("root sidecar written");
        assert_eq!(root_meta.branch_key, "somebranch-cafe1234");
    }

    /// `restore_branch_dir_into_root` is the reverse of
    /// `mirror_into_branch_dir`: it must overwrite the root's chunks.db,
    /// meta.json, dense/**, sparse/, and branch.json with the snapshot's
    /// content, discarding whatever the root held before.
    #[test]
    fn restore_branch_dir_into_root_replaces_live_content() {
        use crate::index::storage::ChunkStore;
        use crate::types::{Chunk, ChunkType};

        let tmp = TempDir::new().unwrap();
        let project = tmp.path();
        let container = container_dir(project);
        std::fs::create_dir_all(container.join("dense").join("backend")).unwrap();

        // Build + mirror branch "old" with its own content.
        {
            let store = ChunkStore::open(&container.join("chunks.db")).unwrap();
            store
                .insert_chunk(
                    &Chunk {
                        id: 0,
                        file_path: PathBuf::from("src/old.rs"),
                        start_line: 1,
                        end_line: 1,
                        content: "fn old_branch_fn() {}".to_string(),
                        chunk_type: ChunkType::TextWindow { window_index: 0 },
                    },
                    1,
                    0,
                )
                .unwrap();
        }
        std::fs::write(
            container.join("meta.json"),
            serde_json::to_string(&sample_index_meta()).unwrap(),
        )
        .unwrap();
        std::fs::write(
            container.join("dense").join("backend").join("vectors.bin"),
            b"old-vectors",
        )
        .unwrap();
        mirror_into_branch_dir(project, "old-key11112222").unwrap();

        // Now mutate the root to look like a DIFFERENT branch's content —
        // simulating what an incremental build for the new branch would do.
        std::fs::remove_file(container.join("chunks.db")).unwrap();
        let store = ChunkStore::open(&container.join("chunks.db")).unwrap();
        store
            .insert_chunk(
                &Chunk {
                    id: 0,
                    file_path: PathBuf::from("src/new.rs"),
                    start_line: 1,
                    end_line: 1,
                    content: "fn new_branch_fn() {}".to_string(),
                    chunk_type: ChunkType::TextWindow { window_index: 0 },
                },
                2,
                0,
            )
            .unwrap();
        drop(store);
        std::fs::write(
            container.join("dense").join("backend").join("vectors.bin"),
            b"new-vectors-totally-different",
        )
        .unwrap();

        // Restore "old" back into the root.
        restore_branch_dir_into_root(project, "old-key11112222").unwrap();

        let restored_store = ChunkStore::open(&container.join("chunks.db")).unwrap();
        // The root's chunks.db was replaced wholesale by the snapshot (not
        // merged): exactly the old branch's one row, with its content —
        // the "new" branch's row is gone even if ids happened to collide
        // across the two fresh single-row DBs.
        let ids = restored_store.get_all_chunk_ids().unwrap();
        assert_eq!(ids.len(), 1, "restore must replace, not merge, chunks.db");
        let restored = restored_store.get_chunk(ids[0]).unwrap();
        assert_eq!(restored.content, "fn old_branch_fn() {}");
        assert_eq!(
            std::fs::read(container.join("dense").join("backend").join("vectors.bin")).unwrap(),
            b"old-vectors"
        );
        let root_meta = read_root_branch_meta(project).unwrap();
        assert_eq!(root_meta.branch_key, "old-key11112222");
    }

    /// Restoring a branch_key with no snapshot yet must be a safe no-op
    /// (nothing to restore) rather than erroring or wiping the root.
    #[test]
    fn restore_of_nonexistent_branch_dir_is_a_no_op() {
        let tmp = TempDir::new().unwrap();
        let project = tmp.path();
        restore_branch_dir_into_root(project, "never-existed-00000000").unwrap();
        assert!(!branch_index_dir(project, "never-existed-00000000").exists());
    }

    /// v13 Wave 2 (history, adversarial-review design change): `history.db`
    /// is repo-GLOBAL — like `memory.db`, it must be EXCLUDED from branch
    /// snapshots entirely. A mirror must not copy it into the branch dir,
    /// and a restore must leave whatever the root has accumulated fully
    /// intact (git is the source of truth; `history::populate_history` is
    /// idempotent/incremental, so snapshots protect nothing).
    #[test]
    fn history_db_is_repo_global_excluded_from_mirror_and_restore() {
        use crate::index::storage::ChunkStore;
        use crate::types::{Chunk, ChunkType};

        let tmp = TempDir::new().unwrap();
        let project = tmp.path();
        let container = container_dir(project);
        std::fs::create_dir_all(&container).unwrap();

        {
            let store = ChunkStore::open(&container.join("chunks.db")).unwrap();
            store
                .insert_chunk(
                    &Chunk {
                        id: 0,
                        file_path: PathBuf::from("src/a.rs"),
                        start_line: 1,
                        end_line: 1,
                        content: "fn a() {}".to_string(),
                        chunk_type: ChunkType::TextWindow { window_index: 0 },
                    },
                    1,
                    0,
                )
                .unwrap();
        }
        {
            let history = open_history_db(&container.join("history.db")).unwrap();
            history
                .execute(
                    "INSERT INTO commits (hash, author, ts, message) VALUES ('h1', 'a', 1, 'm')",
                    [],
                )
                .unwrap();
        }

        // Mirror: history.db must NOT appear in the branch snapshot.
        mirror_into_branch_dir(project, "histbranch-dddd3333").unwrap();
        let mirror = branch_index_dir(project, "histbranch-dddd3333");
        assert!(mirror.join("chunks.db").exists());
        assert!(
            !mirror.join("history.db").exists(),
            "history.db is repo-global and must be excluded from branch mirrors"
        );

        // Root accumulates MORE history after the mirror (simulating builds
        // on another branch adding commits to the shared log).
        {
            let root_history = open_history_db(&container.join("history.db")).unwrap();
            root_history
                .execute(
                    "INSERT INTO commits (hash, author, ts, message) VALUES ('h2', 'b', 2, 'm2')",
                    [],
                )
                .unwrap();
        }

        // Restore (branch switch back): the root's richer history.db must
        // survive completely untouched.
        restore_branch_dir_into_root(project, "histbranch-dddd3333").unwrap();
        let root_history = open_history_db(&container.join("history.db")).unwrap();
        let count: i64 = root_history
            .query_row("SELECT COUNT(*) FROM commits", [], |r| r.get(0))
            .unwrap();
        assert_eq!(
            count, 2,
            "branch switches must leave the repo-global history.db untouched"
        );
    }
}