git-workon-lib 0.13.2

API for managing worktrees
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
//! `gh stack` (`github/gh-stack` CLI extension) stack detection — read path.
//!
//! Stack metadata is read without invoking `gh`. Upstream writes one JSON file per git dir
//! (`schemaVersion: 1`, `{ repository, stacks: [{ id, number, trunk: branchRef, branches:
//! [branchRef] }] }`, `branchRef = { branch, head, base, pullRequest }`), which for a linked
//! worktree is per-worktree, not shared. workon keeps one canonical copy at
//! `<common-dir>/gh-stack` and symlinks each worktree's admin-dir path to it (see
//! [`link_worktree`]) so it behaves like Graphite's shared store.
//!
//! **Never use `repo.path()` here — always `repo.commondir()`.** `get_repo` (`get_repo.rs`)
//! follows `commondir` back and returns the bare repo, so `repo.path() == repo.commondir()`
//! at every CLI call site. But `Fixture::repo()` in tests can be a *worktree* handle where
//! they differ. A `path()`-based scan silently passes under test and fails for every real
//! linked worktree.
//!
//! ## Read order and the degraded union fallback
//!
//! [`read_metadata`] reads the canonical file first, then unions in [`unlinked_files`] —
//! worktree admin-dir files that are *not* symlinks resolving to canonical — in directory
//! order. In a healthy (fully-linked) repo `unlinked_files` is empty and the union never
//! runs. It exists because write-in-place (upstream truncates its target through the
//! symlink) is an implementation detail, not a contract: if gh-stack ever switches to
//! temp-and-rename, the rename replaces a worktree's canonical symlink with a real file, and
//! that worktree's writes silently stop reaching canonical. The union read means nothing goes
//! invisible in the meantime — `doctor` (added later) flags any unlinked file it finds.
//!
//! Dedupe when the union fires: identity is `number` when non-zero, else `id` when
//! non-empty, else `(trunk, first branch)`; **first wins wholesale** — the entire stack
//! object from the earliest source is kept, later ones with the same identity are discarded
//! entirely, never merged field-by-field. Merging two disagreeing ordered `branches` arrays
//! has no defined semantics (an insertion in one is indistinguishable from a deletion in the
//! other), so a field-level merge could synthesize a stack that existed in neither worktree.
//!
//! ## Truncated reads are tolerated, not fatal
//!
//! A partial file is the *expected* steady state during a concurrent `gh stack` command —
//! upstream's `os.WriteFile` truncates in place rather than writing to a temp file and
//! renaming, so a reader can observe a half-written file. [`read_metadata`] retries a
//! read-and-parse up to 3 times, 25ms apart, and skips the file with `log::warn!` if every
//! attempt still fails to parse. This is the deliberate opposite of Graphite's rule
//! (`graphite.rs`'s `read_branch_metadata`, where a present-but-unreadable database is a hard
//! error): sqlite writes are atomic, so unreadable there means corrupt, not mid-write.
//!
//! `schemaVersion > 1` is not retried — retrying a version mismatch cannot fix it, and
//! skipping it would silently render a confidently wrong (outdated) stack, so it is a hard
//! error ([`StackError::GhStackSchemaUnsupported`]). Missing or `0` is treated as `1`,
//! matching Go's zero-value behavior for an unset int field.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::Duration;

use git2::Repository;
use serde_json::Value;

#[cfg(unix)]
use std::os::unix::io::AsRawFd;

use super::metadata::{self, BranchMetadata, StackMetadata};
use super::Stack;
use crate::error::StackError;

/// One `branchRef` entry (`{ branch, head, base, pullRequest }`), pulled from a raw
/// `serde_json::Value` rather than a derived struct (this crate has no `serde` derive
/// dependency, only `serde_json`; see `graphite.rs` for the same raw-`Value` convention).
/// `head` and `pullRequest` are read from the file but not carried into [`StackMetadata`]:
/// assembly uses the live tip for `head`, and `pullRequest` has no `StackMetadata` field.
/// Both matter to the write path (added in a later changeset), which round-trips the raw
/// `Value` to preserve them.
#[derive(Debug)]
struct GhStackBranchRef {
    branch: String,
    base: String,
}

impl GhStackBranchRef {
    fn from_value(value: &Value) -> Option<Self> {
        Some(Self {
            branch: value.get("branch")?.as_str()?.to_string(),
            base: value
                .get("base")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
        })
    }
}

#[derive(Debug)]
struct GhStackEntry {
    id: String,
    number: u64,
    trunk: GhStackBranchRef,
    branches: Vec<GhStackBranchRef>,
}

impl GhStackEntry {
    fn from_value(value: &Value) -> Option<Self> {
        let trunk = GhStackBranchRef::from_value(value.get("trunk")?)?;
        let branches = value
            .get("branches")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(GhStackBranchRef::from_value)
                    .collect()
            })
            .unwrap_or_default();
        Some(Self {
            id: value
                .get("id")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            number: value.get("number").and_then(|v| v.as_u64()).unwrap_or(0),
            trunk,
            branches,
        })
    }
}

/// Parse `doc`'s `stacks` array. Entries missing a well-formed `trunk` are skipped (not fatal
/// — one malformed entry in an otherwise-valid file shouldn't blind the whole read).
fn parse_stacks(doc: &Value) -> Vec<GhStackEntry> {
    doc.get("stacks")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(GhStackEntry::from_value).collect())
        .unwrap_or_default()
}

/// Number of read-and-parse attempts before a persistently truncated/malformed file is
/// skipped with a warning. See the module docs' "Truncated reads" section.
const READ_ATTEMPTS: u32 = 3;
const READ_RETRY_DELAY: Duration = Duration::from_millis(25);

/// `<common-dir>/gh-stack` — the canonical store every worktree's admin-dir file is meant to
/// symlink to.
pub(crate) fn canonical_path(repo: &Repository) -> PathBuf {
    repo.commondir().join("gh-stack")
}

/// Worktree admin-dir `gh-stack` files that are NOT symlinks resolving to [`canonical_path`],
/// sorted by directory name. Empty in the healthy (fully-linked) case. Directory-name order
/// is the dedupe tiebreak in [`read_metadata`].
pub(crate) fn unlinked_files(repo: &Repository) -> Vec<PathBuf> {
    let canonical = canonical_path(repo);
    let worktrees_dir = repo.commondir().join("worktrees");
    let Ok(entries) = std::fs::read_dir(&worktrees_dir) else {
        return vec![];
    };

    let mut names: Vec<String> = entries
        .filter_map(|e| e.ok())
        .filter(|e| e.path().is_dir())
        .filter_map(|e| e.file_name().into_string().ok())
        .collect();
    names.sort();

    names
        .into_iter()
        .filter_map(|name| {
            let path = worktrees_dir.join(&name).join("gh-stack");
            if !path_exists_at_all(&path) || is_symlink_resolving_to(&path, &canonical) {
                None
            } else {
                Some(path)
            }
        })
        .collect()
}

fn path_exists_at_all(path: &Path) -> bool {
    std::fs::symlink_metadata(path).is_ok()
}

/// `true` if `path` is a symlink whose target, resolved lexically relative to `path`'s parent
/// (no `fs::canonicalize` — a dangling symlink to a not-yet-created canonical file is a valid
/// state; see the module docs), equals `canonical`.
fn is_symlink_resolving_to(path: &Path, canonical: &Path) -> bool {
    let Ok(meta) = std::fs::symlink_metadata(path) else {
        return false;
    };
    if !meta.file_type().is_symlink() {
        return false;
    }
    let Ok(target) = std::fs::read_link(path) else {
        return false;
    };
    let Some(parent) = path.parent() else {
        return false;
    };
    normalize_lexically(&parent.join(target)) == normalize_lexically(canonical)
}

fn normalize_lexically(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            std::path::Component::ParentDir => {
                out.pop();
            }
            std::path::Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// Returns `true` if this repository has a gh-stack file anywhere workon knows to look —
/// canonical or an unlinked worktree file.
pub(crate) fn is_gh_stack_repo(repo: &Repository) -> bool {
    canonical_path(repo).exists() || !unlinked_files(repo).is_empty()
}

/// Read, parse, and schema-check the gh-stack file at `path`.
///
/// Returns `Ok(None)` if the file does not exist, or if every read-and-parse attempt fails
/// (logged via `log::warn!`) — both are non-fatal per the module docs. Returns `Err` only for
/// `schemaVersion > 1`, which is never retried.
fn read_doc(path: &Path) -> Result<Option<Vec<GhStackEntry>>, StackError> {
    let mut last_error: Option<String> = None;

    for attempt in 0..READ_ATTEMPTS {
        match std::fs::read(path) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => last_error = Some(e.to_string()),
            Ok(bytes) => match serde_json::from_slice::<Value>(&bytes) {
                Err(e) => last_error = Some(e.to_string()),
                Ok(value) => {
                    let version = value
                        .get("schemaVersion")
                        .and_then(|v| v.as_u64())
                        .filter(|&v| v != 0)
                        .unwrap_or(1);
                    if version > 1 {
                        return Err(StackError::GhStackSchemaUnsupported {
                            path: path.to_path_buf(),
                            version,
                        });
                    }
                    return Ok(Some(parse_stacks(&value)));
                }
            },
        }
        if attempt + 1 < READ_ATTEMPTS {
            std::thread::sleep(READ_RETRY_DELAY);
        }
    }

    log::warn!(
        "gh-stack: skipping unreadable file {}: {}",
        path.display(),
        last_error.unwrap_or_default()
    );
    Ok(None)
}

/// Identity used to dedupe [`GhStackEntry`] values across canonical + unlinked files. See the
/// module docs' "Read order and the degraded union fallback" section.
#[derive(Debug, PartialEq, Eq, Hash)]
enum StackIdentity {
    Number(u64),
    Id(String),
    TrunkAndFirstBranch(String, String),
}

fn identity(entry: &GhStackEntry) -> StackIdentity {
    if entry.number != 0 {
        StackIdentity::Number(entry.number)
    } else if !entry.id.is_empty() {
        StackIdentity::Id(entry.id.clone())
    } else {
        let first_branch = entry
            .branches
            .first()
            .map(|b| b.branch.clone())
            .unwrap_or_default();
        StackIdentity::TrunkAndFirstBranch(entry.trunk.branch.clone(), first_branch)
    }
}

/// Read gh-stack's stack metadata into provider-agnostic [`StackMetadata`].
///
/// Reads canonical first, then unions in [`unlinked_files`] (directory order), deduping by
/// [`StackIdentity`] with first-seen-wins. See the module docs for why the union is a
/// degraded fallback rather than the primary path, and why first-wins never merges.
pub(crate) fn read_metadata(repo: &Repository) -> Result<StackMetadata, StackError> {
    let mut seen: HashSet<StackIdentity> = HashSet::new();
    let mut kept: Vec<GhStackEntry> = Vec::new();

    let mut sources = vec![canonical_path(repo)];
    sources.extend(unlinked_files(repo));

    for path in sources {
        let Some(entries) = read_doc(&path)? else {
            continue;
        };
        for entry in entries {
            if seen.insert(identity(&entry)) {
                kept.push(entry);
            }
        }
    }

    let mut trunks: Vec<String> = Vec::new();
    let mut parents: HashMap<String, BranchMetadata> = HashMap::new();
    let mut stack_numbers: HashMap<String, u64> = HashMap::new();

    for entry in &kept {
        if !trunks.contains(&entry.trunk.branch) {
            trunks.push(entry.trunk.branch.clone());
        }

        // branches[i].base maps to parent_revision, empty string normalizing to None
        // (matches graphite.rs's treatment of parentBranchRevision); branches[i].head is
        // discarded, assembly uses the branch's live tip instead.
        let mut parent = entry.trunk.branch.clone();
        for branch_ref in &entry.branches {
            let parent_revision = if branch_ref.base.is_empty() {
                None
            } else {
                Some(branch_ref.base.clone())
            };
            // First-wins wholesale, matching `trunks` above: if a branch appears in two
            // stacks, the earliest source's parent and stack number stick and `doctor` flags
            // the divergence, rather than the last-seen source silently overwriting them.
            parents
                .entry(branch_ref.branch.clone())
                .or_insert(BranchMetadata {
                    parent: parent.clone(),
                    parent_revision,
                });
            if entry.number != 0 {
                stack_numbers
                    .entry(branch_ref.branch.clone())
                    .or_insert(entry.number);
            }
            parent = branch_ref.branch.clone();
        }
    }

    Ok(StackMetadata {
        trunks,
        parents,
        pr_titles: HashMap::new(),
        stack_numbers,
    })
}

/// Return all gh-stack stacks, one per connected component, ghost branches PRUNED.
pub(crate) fn enumerate_stacks(repo: &Repository) -> Result<Vec<Stack>, StackError> {
    Ok(metadata::enumerate(repo, &read_metadata(repo)?))
}

/// Get the gh-stack stack for the worktree whose HEAD is `head_branch`, ghost branches
/// RETAINED (see [`metadata::current`]).
pub(crate) fn current_stack(
    repo: &Repository,
    head_branch: &str,
) -> Result<Option<Stack>, StackError> {
    Ok(metadata::current(&read_metadata(repo)?, head_branch))
}

// ── Linking worktrees to the canonical file ─────────────────────────────────────────────

/// RAII guard holding `<common-dir>/gh-stack.lock`'s `flock`. Released on drop.
#[cfg(unix)]
struct LockGuard(std::fs::File);

#[cfg(unix)]
impl Drop for LockGuard {
    fn drop(&mut self) {
        // SAFETY: `self.0` is a valid, open file descriptor for the whole guard lifetime.
        unsafe {
            libc::flock(self.0.as_raw_fd(), libc::LOCK_UN);
        }
    }
}

#[cfg(not(unix))]
struct LockGuard;

const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
const LOCK_RETRY_DELAY: Duration = Duration::from_millis(100);

/// Take `<common-dir>/gh-stack.lock` (`flock(LOCK_EX | LOCK_NB)`, retried every 100ms up to
/// 5s), so a concurrent `gh stack` run in any worktree is genuinely excluded — every
/// worktree's lock path symlinks to this same file (see [`link_worktree`]). A no-op guard on
/// non-unix targets, mirroring `graphite.rs`'s `#[cfg(not(unix))]` fallback.
#[cfg(unix)]
fn lock_canonical(repo: &Repository) -> Result<LockGuard, StackError> {
    let lock_path = repo.commondir().join("gh-stack.lock");
    let file = std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(false) // lock file's contents (if any) are irrelevant; never clobber them
        .open(&lock_path)
        .map_err(|e| StackError::GhStackWriteFailed {
            path: lock_path.clone(),
            message: e.to_string(),
        })?;

    let deadline = std::time::Instant::now() + LOCK_TIMEOUT;
    loop {
        let ret = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
        if ret == 0 {
            return Ok(LockGuard(file));
        }
        let err = std::io::Error::last_os_error();
        if err.raw_os_error() != Some(libc::EWOULDBLOCK) || std::time::Instant::now() >= deadline {
            return Err(StackError::GhStackLocked { path: lock_path });
        }
        std::thread::sleep(LOCK_RETRY_DELAY);
    }
}

#[cfg(not(unix))]
fn lock_canonical(_repo: &Repository) -> Result<LockGuard, StackError> {
    Ok(LockGuard)
}

#[cfg(unix)]
fn create_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(target, link)
}

#[cfg(windows)]
fn create_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::windows::fs::symlink_file(target, link)
}

/// Plant `admin_dir/<filename>` as a relative symlink (`../../<filename>`) to
/// `<common-dir>/<filename>`. Idempotent — a no-op if the symlink already points there.
/// Never replaces a regular file: that is [`migrate_worktree`]'s job alone.
fn plant_link(admin_dir: &Path, filename: &str) -> Result<(), StackError> {
    let link_path = admin_dir.join(filename);
    let relative_target = Path::new("..").join("..").join(filename);

    match std::fs::symlink_metadata(&link_path) {
        Ok(meta) if meta.file_type().is_symlink() => {
            if std::fs::read_link(&link_path).ok().as_deref() == Some(relative_target.as_path()) {
                return Ok(()); // already correctly linked
            }
            std::fs::remove_file(&link_path).map_err(|e| StackError::GhStackLinkFailed {
                path: link_path.clone(),
                message: e.to_string(),
            })?;
            create_symlink(&relative_target, &link_path).map_err(|e| {
                StackError::GhStackLinkFailed {
                    path: link_path,
                    message: e.to_string(),
                }
            })
        }
        Ok(_) => Ok(()), // a real file is here — never replace it, see migrate_worktree
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            create_symlink(&relative_target, &link_path).map_err(|e| {
                StackError::GhStackLinkFailed {
                    path: link_path,
                    message: e.to_string(),
                }
            })
        }
        Err(e) => Err(StackError::GhStackLinkFailed {
            path: link_path,
            message: e.to_string(),
        }),
    }
}

/// Plant `gh-stack` and `gh-stack.lock` in `<common>/worktrees/<worktree_name>/` as relative
/// symlinks (`../../gh-stack`) to the canonical store. Idempotent. Never replaces a regular
/// file — that is [`migrate_worktree`]'s job.
///
/// Safe to call before any stack exists: `open()` with `O_CREAT` through a dangling symlink
/// creates the target, so the first `gh stack init` in any linked worktree creates canonical.
/// See the module docs.
pub(crate) fn link_worktree(repo: &Repository, worktree_name: &str) -> Result<(), StackError> {
    let admin_dir = repo.commondir().join("worktrees").join(worktree_name);
    plant_link(&admin_dir, "gh-stack")?;
    plant_link(&admin_dir, "gh-stack.lock")?;
    Ok(())
}

/// Identity computed straight from a raw `stacks[]` entry `Value`, mirroring [`identity`] but
/// without parsing into [`GhStackEntry`] first — used by [`migrate_worktree`], which must
/// preserve `id`/`pullRequest`/`head` verbatim rather than round-tripping through the
/// read-path's lossy struct.
fn raw_identity(entry: &Value) -> StackIdentity {
    let number = entry.get("number").and_then(|v| v.as_u64()).unwrap_or(0);
    if number != 0 {
        return StackIdentity::Number(number);
    }
    let id = entry.get("id").and_then(|v| v.as_str()).unwrap_or_default();
    if !id.is_empty() {
        return StackIdentity::Id(id.to_string());
    }
    let trunk = entry
        .get("trunk")
        .and_then(|t| t.get("branch"))
        .and_then(|v| v.as_str())
        .unwrap_or_default()
        .to_string();
    let first_branch = entry
        .get("branches")
        .and_then(|b| b.as_array())
        .and_then(|arr| arr.first())
        .and_then(|b| b.get("branch"))
        .and_then(|v| v.as_str())
        .unwrap_or_default()
        .to_string();
    StackIdentity::TrunkAndFirstBranch(trunk, first_branch)
}

/// Read `path` as a whole raw `Value` (no [`GhStackEntry`] parsing, so every top-level field —
/// `repository`, `id`, `pullRequest`, anything a future gh-stack adds — survives), rejecting
/// `schemaVersion > 1`. `Ok(None)` for a missing file. A single attempt, no retries: called
/// only under [`lock_canonical`] during `doctor --fix` or [`register_branch`], not on the hot
/// read path [`read_doc`] serves.
fn read_raw_doc(path: &Path) -> Result<Option<Value>, StackError> {
    match std::fs::read(path) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(StackError::GhStackParseFailed {
            path: path.to_path_buf(),
            message: e.to_string(),
        }),
        Ok(bytes) => {
            let value: Value =
                serde_json::from_slice(&bytes).map_err(|e| StackError::GhStackParseFailed {
                    path: path.to_path_buf(),
                    message: e.to_string(),
                })?;
            let version = value
                .get("schemaVersion")
                .and_then(|v| v.as_u64())
                .filter(|&v| v != 0)
                .unwrap_or(1);
            if version > 1 {
                return Err(StackError::GhStackSchemaUnsupported {
                    path: path.to_path_buf(),
                    version,
                });
            }
            Ok(Some(value))
        }
    }
}

/// Read `path`'s `stacks[]` array as raw `Value`s (no [`GhStackEntry`] parsing, so `id` and
/// `pullRequest` survive). Missing file, or a file with no `stacks` array, is an empty vec.
fn read_raw_stacks(path: &Path) -> Result<Vec<Value>, StackError> {
    Ok(read_raw_doc(path)?
        .and_then(|doc| doc.get("stacks").and_then(|v| v.as_array()).cloned())
        .unwrap_or_default())
}

/// Merge a worktree's real `gh-stack` file into canonical, then replace it with a symlink.
/// Writes `gh-stack.bak` alongside the original before removing it. Takes the canonical lock
/// throughout.
///
/// This is the only place workon replaces a file another tool wrote, so it is reachable only
/// from `doctor --fix` — never automatically, never from `workon new`. If `worktree_name`'s
/// `gh-stack` path is missing or already a symlink, this degrades to [`link_worktree`]: there
/// is no real file to migrate.
///
/// Merge order matches [`read_metadata`]'s dedupe rule: canonical entries are seeded first, so
/// a colliding identity in the worktree file is dropped, never merged field-by-field.
pub(crate) fn migrate_worktree(repo: &Repository, worktree_name: &str) -> Result<(), StackError> {
    let admin_dir = repo.commondir().join("worktrees").join(worktree_name);
    let worktree_file = admin_dir.join("gh-stack");

    let is_regular_file = matches!(
        std::fs::symlink_metadata(&worktree_file),
        Ok(meta) if !meta.file_type().is_symlink()
    );
    if !is_regular_file {
        remove_stale_lock_file(&admin_dir)?;
        return link_worktree(repo, worktree_name);
    }

    let _lock = lock_canonical(repo)?;

    let canonical = canonical_path(repo);
    let canonical_doc = read_raw_doc(&canonical)?;

    // Base the merged document on canonical's whole `Value` when it exists, falling back to
    // the worktree file's, so every top-level field outside `stacks` — `repository` above
    // all — round-trips instead of being discarded. Mirrors `plan_registered_doc`, which
    // round-trips the same way for the same reason.
    let mut doc = match &canonical_doc {
        Some(v) => v.clone(),
        None => read_raw_doc(&worktree_file)?
            .unwrap_or_else(|| serde_json::json!({ "schemaVersion": 1, "stacks": [] })),
    };

    let mut merged: Vec<Value> = canonical_doc
        .as_ref()
        .and_then(|v| v.get("stacks"))
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    let mut seen: HashSet<StackIdentity> = merged.iter().map(raw_identity).collect();
    for entry in read_raw_stacks(&worktree_file)? {
        if seen.insert(raw_identity(&entry)) {
            merged.push(entry);
        }
    }

    doc["schemaVersion"] = serde_json::json!(1);
    doc["stacks"] = serde_json::Value::Array(merged);

    // Verify the merged result parses before touching anything on disk or unlinking the
    // worktree's original — never destroy the only copy of data that failed to round-trip.
    let bytes = serde_json::to_vec_pretty(&doc).map_err(|e| StackError::GhStackWriteFailed {
        path: canonical.clone(),
        message: e.to_string(),
    })?;
    serde_json::from_slice::<Value>(&bytes).map_err(|e| StackError::GhStackParseFailed {
        path: canonical.clone(),
        message: e.to_string(),
    })?;

    let tmp_path = canonical.with_extension("tmp");
    std::fs::write(&tmp_path, &bytes).map_err(|e| StackError::GhStackWriteFailed {
        path: tmp_path.clone(),
        message: e.to_string(),
    })?;
    std::fs::rename(&tmp_path, &canonical).map_err(|e| StackError::GhStackWriteFailed {
        path: canonical.clone(),
        message: e.to_string(),
    })?;

    // Re-read the bytes actually on disk (not just the in-memory copy) before unlinking the
    // worktree's original file. `read_raw_stacks`, not `read_doc`: `read_doc` only ever
    // returns `Err` for a schema mismatch that can't happen on a doc we just wrote with
    // `schemaVersion: 1`, so it can never fail here and isn't a real guard. `read_raw_stacks`
    // is single-attempt and genuinely errors on a parse failure.
    read_raw_stacks(&canonical)?;

    let bak_path = next_available_backup_path(&admin_dir);
    std::fs::rename(&worktree_file, &bak_path).map_err(|e| StackError::GhStackWriteFailed {
        path: worktree_file.clone(),
        message: e.to_string(),
    })?;

    remove_stale_lock_file(&admin_dir)?;
    link_worktree(repo, worktree_name)
}

/// Remove `admin_dir/gh-stack.lock` if it is a regular file, so the following
/// [`link_worktree`] call can plant a proper symlink — [`plant_link`] never replaces a regular
/// file. Its contents are irrelevant (upstream never reads them, it is a pure `flock` target;
/// see the module docs' shared-canonical-file section), so simply discarding it is safe.
///
/// A worktree that has already run `gh stack` almost always has a real `gh-stack.lock`
/// alongside its real `gh-stack` file (upstream opens it `O_CREATE` on every lock attempt), so
/// this runs on every path through [`migrate_worktree`], not only the merge path — leaving it
/// behind would silently keep that worktree flocking a private inode instead of the shared
/// canonical lock, defeating cross-worktree mutual exclusion without [`worktree_link_status`]
/// (which now checks both paths) reporting it.
fn remove_stale_lock_file(admin_dir: &Path) -> Result<(), StackError> {
    let lock_path = admin_dir.join("gh-stack.lock");
    let is_regular_file = matches!(
        std::fs::symlink_metadata(&lock_path),
        Ok(meta) if !meta.file_type().is_symlink()
    );
    if is_regular_file {
        std::fs::remove_file(&lock_path).map_err(|e| StackError::GhStackWriteFailed {
            path: lock_path,
            message: e.to_string(),
        })?;
    }
    Ok(())
}

/// The first of `gh-stack.bak`, `gh-stack.bak.1`, `gh-stack.bak.2`, ... that doesn't already
/// exist in `admin_dir`. A worktree can legitimately acquire a real `gh-stack` file again
/// after a prior migration — the write-in-place risk this crate's module docs describe (a
/// gh-stack release switching to temp-and-rename would cause exactly this) — so re-migrating
/// must never clobber the backup a previous migration left behind.
fn next_available_backup_path(admin_dir: &Path) -> PathBuf {
    let base = admin_dir.join("gh-stack.bak");
    if std::fs::symlink_metadata(&base).is_err() {
        return base;
    }
    (1u32..)
        .map(|n| admin_dir.join(format!("gh-stack.bak.{n}")))
        .find(|candidate| std::fs::symlink_metadata(candidate).is_err())
        .expect("u32 backup suffixes are effectively inexhaustible")
}

// ── Registering new branches (write path) ───────────────────────────────────────────────

/// Resolve `name`'s local branch tip. `workon new` has already created both `branch` and
/// (normally) `base_branch` by the time [`register_branch`] runs, so failure here means
/// something is badly wrong rather than an expected condition — reported as
/// [`StackError::GhStackWriteFailed`] since there's no more specific variant for "the thing
/// we were asked to register doesn't resolve to a commit".
fn branch_tip(repo: &Repository, name: &str) -> Result<git2::Oid, StackError> {
    let branch = repo
        .find_branch(name, git2::BranchType::Local)
        .map_err(|e| StackError::GhStackWriteFailed {
            path: canonical_path(repo),
            message: format!("branch '{name}' not found: {e}"),
        })?;
    branch
        .get()
        .target()
        .ok_or_else(|| StackError::GhStackWriteFailed {
            path: canonical_path(repo),
            message: format!("branch '{name}' has no target (unborn?)"),
        })
}

/// Find the index in `stacks` (a `stacks[]` array of raw `Value`s) whose stack currently ends
/// at `base_branch`: either its last `branches` element is `base_branch`, or it has no
/// `branches` yet and its `trunk.branch` is `base_branch`. First match wins when more than
/// one qualifies — `doctor`'s `GhStackDivergentStacks` check is what flags that situation,
/// not this function.
fn select_target_index(stacks: &[Value], base_branch: &str) -> Option<usize> {
    stacks
        .iter()
        .position(|stack| {
            stack
                .get("branches")
                .and_then(|b| b.as_array())
                .and_then(|arr| arr.last())
                .and_then(|b| b.get("branch"))
                .and_then(|v| v.as_str())
                == Some(base_branch)
        })
        .or_else(|| {
            stacks.iter().position(|stack| {
                let branches_empty = stack
                    .get("branches")
                    .and_then(|b| b.as_array())
                    .map(|arr| arr.is_empty())
                    .unwrap_or(true);
                branches_empty
                    && stack
                        .get("trunk")
                        .and_then(|t| t.get("branch"))
                        .and_then(|v| v.as_str())
                        == Some(base_branch)
            })
        })
}

/// Build the full replacement document (as pretty-printed bytes) for `register_branch`,
/// given the raw bytes currently on disk (`existing`, possibly empty for "file doesn't exist
/// yet"). Round-trips through `serde_json::Value` rather than a typed struct so `id`,
/// `pullRequest`, and any other field on untouched `stacks[]` entries survive unchanged —
/// only the target stack's `branches` array gains one new, minimal entry.
fn plan_registered_doc(
    existing: &[u8],
    branch: &str,
    base_branch: &str,
    base: &str,
    head: &str,
    canonical: &Path,
) -> Result<Vec<u8>, StackError> {
    let mut doc: Value = if existing.is_empty() {
        serde_json::json!({ "schemaVersion": 1, "stacks": [] })
    } else {
        serde_json::from_slice(existing).map_err(|e| StackError::GhStackParseFailed {
            path: canonical.to_path_buf(),
            message: e.to_string(),
        })?
    };

    let version = doc
        .get("schemaVersion")
        .and_then(|v| v.as_u64())
        .filter(|&v| v != 0)
        .unwrap_or(1);
    if version > 1 {
        return Err(StackError::GhStackSchemaUnsupported {
            path: canonical.to_path_buf(),
            version,
        });
    }

    let stacks = doc
        .get_mut("stacks")
        .and_then(|v| v.as_array_mut())
        .ok_or_else(|| StackError::GhStackNoStackForBase {
            base: base_branch.to_string(),
        })?;

    let idx = select_target_index(stacks, base_branch).ok_or_else(|| {
        StackError::GhStackNoStackForBase {
            base: base_branch.to_string(),
        }
    })?;

    // `pullRequest` is deliberately omitted, matching upstream's `omitempty` on a fresh entry.
    let new_entry = serde_json::json!({ "branch": branch, "head": head, "base": base });
    match stacks[idx]
        .get_mut("branches")
        .and_then(|v| v.as_array_mut())
    {
        Some(arr) => arr.push(new_entry),
        None => stacks[idx]["branches"] = serde_json::json!([new_entry]),
    }

    serde_json::to_vec_pretty(&doc).map_err(|e| StackError::GhStackWriteFailed {
        path: canonical.to_path_buf(),
        message: e.to_string(),
    })
}

/// Write `bytes` to `canonical` via `<common-dir>/gh-stack.tmp` then `fs::rename`, mode 0644.
/// Atomic, unlike upstream's `os.WriteFile` — always call this with `canonical` itself
/// ([`canonical_path`]'s return value), never a worktree's symlinked admin-dir path: renaming
/// onto a symlink replaces the link with a real file instead of updating what it points to,
/// silently detaching that worktree from the shared store.
fn write_canonical_atomic(canonical: &Path, bytes: &[u8]) -> Result<(), StackError> {
    let tmp_path = canonical.with_extension("tmp");
    std::fs::write(&tmp_path, bytes).map_err(|e| StackError::GhStackWriteFailed {
        path: tmp_path.clone(),
        message: e.to_string(),
    })?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o644)).map_err(
            |e| StackError::GhStackWriteFailed {
                path: tmp_path.clone(),
                message: e.to_string(),
            },
        )?;
    }

    std::fs::rename(&tmp_path, canonical).map_err(|e| StackError::GhStackWriteFailed {
        path: canonical.to_path_buf(),
        message: e.to_string(),
    })
}

/// Append `branch` to the canonical file's stack that currently ends at `base_branch`.
/// Round-trips through `serde_json::Value` — a typed struct would silently drop `id`,
/// `pullRequest`, and any field a future gh-stack adds.
///
/// `base` is `repo.merge_base(base_branch's tip, branch's tip)` — equal to `base_branch`'s
/// tip in the normal case, but still correct if `base_branch` moved between worktree creation
/// and this call. Guarded by [`lock_canonical`], so a concurrent `gh stack` run in any
/// worktree (every worktree's lock symlinks to the same file) is genuinely excluded.
///
/// The file is read only after the lock is held. No lock-respecting writer (every `gh stack`
/// invocation, and every other `git-workon` call into this module) can be mid-write once the
/// lock is ours, so a read-under-lock always sees a complete file — there is nothing to
/// compare-and-swap against. A pre-lock read would risk observing upstream's non-atomic
/// `os.WriteFile` mid-truncation and handing a partial prefix to [`plan_registered_doc`],
/// which is exactly the failure this ordering avoids.
pub fn register_branch(
    repo: &Repository,
    branch: &str,
    base_branch: &str,
) -> Result<(), StackError> {
    let head = branch_tip(repo, branch)?;
    let base_tip = branch_tip(repo, base_branch)?;
    let base = repo.merge_base(base_tip, head).unwrap_or(base_tip);

    let canonical = canonical_path(repo);
    let _lock = lock_canonical(repo)?;

    let existing = std::fs::read(&canonical).unwrap_or_default();
    let new_bytes = match plan_registered_doc(
        &existing,
        branch,
        base_branch,
        &base.to_string(),
        &head.to_string(),
        &canonical,
    ) {
        // `read_metadata` (used by `list`/`find`) unions canonical with `unlinked_files`, but
        // this function reads canonical alone — deliberately, since it must never write
        // through a worktree symlink (see `write_canonical_atomic`'s docs). So the spec's
        // accepted chicken-and-egg case (someone runs `gh stack init` inside a worktree before
        // ever running `doctor --fix`) reads fine everywhere but fails registration here with
        // a message that looks identical to "no such stack at all". Point at the fix instead.
        Err(StackError::GhStackNoStackForBase { base }) if !unlinked_files(repo).is_empty() => {
            return Err(StackError::GhStackStackInUnlinkedWorktree { base });
        }
        Err(e) => return Err(e),
        Ok(bytes) => bytes,
    };

    write_canonical_atomic(&canonical, &new_bytes)
}

// ── `doctor` support ─────────────────────────────────────────────────────────────────────

/// Per-worktree link status, for `doctor`'s `GhStackWorktreeNotLinked` check and its `--fix`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkStatus {
    /// Correctly symlinked to canonical.
    Linked,
    /// Not linked. `holds_file` distinguishes the two `--fix` actions: `true` means a real
    /// file is present and must be merged ([`migrate_worktree`]); `false` means the path is
    /// simply missing (or a symlink pointing somewhere else) and can be planted directly
    /// ([`link_worktree`]).
    NotLinked { holds_file: bool },
}

/// `Linked`/`NotLinked { holds_file }` for a single admin-dir path against `expected_target`
/// — the canonical file *that path's own filename* symlinks to (`<common-dir>/gh-stack` for a
/// `gh-stack` path, `<common-dir>/gh-stack.lock` for a `gh-stack.lock` path). Factored out of
/// [`worktree_link_status`] so it can be applied to both filenames — a stale `gh-stack.lock`
/// regular file (upstream opens it `O_CREATE` on every lock attempt, so a worktree that has run
/// `gh stack` almost always has one) is just as unlinked as a stale `gh-stack` file, and must be
/// equally visible to `doctor`.
fn link_status_for_path(path: &Path, expected_target: &Path) -> LinkStatus {
    match std::fs::symlink_metadata(path) {
        Err(_) => LinkStatus::NotLinked { holds_file: false },
        Ok(meta) if meta.file_type().is_symlink() => {
            if is_symlink_resolving_to(path, expected_target) {
                LinkStatus::Linked
            } else {
                LinkStatus::NotLinked { holds_file: false }
            }
        }
        Ok(_) => LinkStatus::NotLinked { holds_file: true },
    }
}

/// Compute [`LinkStatus`] for `worktree_name`'s `gh-stack` and `gh-stack.lock` admin-dir
/// paths, `NotLinked` if either is unlinked. `holds_file` reflects only the `gh-stack` path —
/// whether there is a real stack file needing [`migrate_worktree`]'s merge — never the lock
/// file, whose contents are irrelevant and whose own staleness is fully handled by
/// [`migrate_worktree`] discarding it before relinking; a stale lock alone must route through
/// [`link_worktree`], not `migrate_worktree`.
///
/// Each path is checked against its own target: `plant_link` symlinks `gh-stack` to
/// `../../gh-stack` and `gh-stack.lock` to `../../gh-stack.lock`, so comparing both against
/// `canonical_path` alone would mean the `gh-stack.lock` check can never resolve to it —
/// `is_symlink_resolving_to` compares the *lock's* resolved target against the *stack file's*
/// path, which are never equal.
pub(crate) fn worktree_link_status(repo: &Repository, worktree_name: &str) -> LinkStatus {
    let admin_dir = repo.commondir().join("worktrees").join(worktree_name);
    let canonical = canonical_path(repo);
    let canonical_lock = repo.commondir().join("gh-stack.lock");

    let gh_stack_status = link_status_for_path(&admin_dir.join("gh-stack"), &canonical);
    if matches!(gh_stack_status, LinkStatus::NotLinked { .. }) {
        return gh_stack_status;
    }

    match link_status_for_path(&admin_dir.join("gh-stack.lock"), &canonical_lock) {
        LinkStatus::Linked => LinkStatus::Linked,
        LinkStatus::NotLinked { .. } => LinkStatus::NotLinked { holds_file: false },
    }
}

/// Files (canonical + [`unlinked_files`]) that exist but fail to parse, or whose
/// `schemaVersion` is unsupported — for `doctor`'s `GhStackFileUnreadable` check.
///
/// Unlike [`read_doc`], this is a single-attempt read: `doctor` is a point-in-time health
/// check, not the hot read path a concurrent `gh stack` write races against, so there is no
/// truncated-read tolerance to preserve here — a transient mid-write read just gets reported
/// and re-checked on the next `doctor` run.
pub(crate) fn readability_errors(repo: &Repository) -> Vec<(PathBuf, StackError)> {
    let mut sources = vec![canonical_path(repo)];
    sources.extend(unlinked_files(repo));

    sources
        .into_iter()
        .filter(|path| path.exists())
        .filter_map(|path| match read_raw_stacks(&path) {
            Ok(_) => None,
            Err(e) => Some((path, e)),
        })
        .collect()
}

/// Stack numbers that appear, with genuinely different content, in more than one gh-stack
/// source — only possible when the degraded union read (see the module docs) actually combines
/// canonical with an unlinked worktree file. For `doctor`'s `GhStackDivergentStacks` check.
///
/// Each number is counted at most once *per source*, so two stacks numbered 1 inside a single
/// file don't get flagged as spanning "more than one gh-stack source" — that phrase means
/// files, not array entries. And a number is only reported when its sources disagree: an
/// unlinked worktree file holding a byte-identical copy of a canonical stack (the common state
/// right after someone copies a worktree) is compared by content — at minimum its branch list —
/// so an identical copy is not reported.
pub(crate) fn divergent_stack_numbers(repo: &Repository) -> Vec<u64> {
    let mut sources = vec![canonical_path(repo)];
    sources.extend(unlinked_files(repo));

    // number -> one branch-list signature per source that contains it (deduped within that
    // source, so a file with two same-numbered stacks contributes one signature, not two).
    let mut signatures_by_number: HashMap<u64, Vec<Vec<String>>> = HashMap::new();
    for path in &sources {
        if let Ok(Some(entries)) = read_doc(path) {
            let mut numbers_in_this_source: HashSet<u64> = HashSet::new();
            for entry in entries {
                if entry.number != 0 && numbers_in_this_source.insert(entry.number) {
                    let branches: Vec<String> =
                        entry.branches.iter().map(|b| b.branch.clone()).collect();
                    signatures_by_number
                        .entry(entry.number)
                        .or_default()
                        .push(branches);
                }
            }
        }
    }

    let mut divergent: Vec<u64> = signatures_by_number
        .into_iter()
        .filter(|(_, signatures)| signatures.iter().any(|s| s != &signatures[0]))
        .map(|(number, _)| number)
        .collect();
    divergent.sort_unstable();
    divergent
}

#[cfg(test)]
mod tests {
    use super::*;
    use git_workon_fixture::prelude::*;

    #[test]
    fn reads_linear_stack_from_canonical() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .gh_stack(None, 12, "main", &["feat-a", "feat-b"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        let meta = read_metadata(repo).unwrap();
        assert_eq!(meta.trunks, vec!["main".to_string()]);
        assert_eq!(meta.parents["feat-a"].parent, "main");
        assert_eq!(meta.parents["feat-b"].parent, "feat-a");
        assert_eq!(meta.stack_numbers["feat-a"], 12);
        assert_eq!(meta.stack_numbers["feat-b"], 12);

        let stacks = enumerate_stacks(repo).unwrap();
        assert_eq!(stacks.len(), 1);
        assert_eq!(stacks[0].number, Some(12));
        assert_eq!(stacks[0].diffs, vec!["feat-a", "feat-b"]);
    }

    #[test]
    fn ghost_retained_by_current_stack_and_pruned_by_enumerate() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .gh_stack(None, 5, "main", &["feat-a"])
            .gh_stack_ghost_branch(None, 5, "feat-b")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        // current_stack retains the ghost when walking from a live descendant... but feat-b
        // has no ref, so retrieve current_stack from feat-a (the live branch) instead, which
        // must still see feat-b was never linked as a child in enumerate's pruned output.
        let current = current_stack(repo, "feat-a").unwrap().expect("tracked");
        assert!(current.diffs.contains(&"feat-a".to_string()));

        let enumerated = enumerate_stacks(repo).unwrap();
        assert_eq!(enumerated.len(), 1);
        assert!(!enumerated[0].diffs.contains(&"feat-b".to_string()));
        assert!(enumerated[0].diffs.contains(&"feat-a".to_string()));
    }

    #[test]
    fn truncated_file_is_skipped() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .raw_gh_stack(None, b"{\"schemaVersion\": 1, \"stacks\": [".to_vec())
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        let meta = read_metadata(repo).unwrap();
        assert!(meta.trunks.is_empty());
        assert!(meta.parents.is_empty());
    }

    #[test]
    fn schema_version_2_is_a_hard_error() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .raw_gh_stack(None, br#"{"schemaVersion": 2, "stacks": []}"#.to_vec())
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        match read_metadata(repo) {
            Err(StackError::GhStackSchemaUnsupported { version: 2, .. }) => {}
            Err(e) => panic!("expected GhStackSchemaUnsupported{{version: 2}}, got {e:?}"),
            Ok(_) => panic!("expected GhStackSchemaUnsupported{{version: 2}}, got Ok"),
        }
    }

    #[test]
    fn missing_schema_version_defaults_to_1() {
        // The module doc claims a missing `schemaVersion` is treated as `1`, matching Go's
        // zero-value behavior for an unset int field. No prior test omitted the field.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .branch("feat-a")
            .raw_gh_stack(
                None,
                br#"{"stacks": [{"number": 1, "trunk": {"branch": "main", "head": "", "base": ""}, "branches": [{"branch": "feat-a", "head": "", "base": ""}]}]}"#.to_vec(),
            )
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        let meta = read_metadata(repo).unwrap();
        assert_eq!(meta.parents["feat-a"].parent, "main");
        assert_eq!(meta.stack_numbers["feat-a"], 1);
    }

    #[test]
    fn schema_version_0_defaults_to_1() {
        // Same claim, explicit `schemaVersion: 0` — Go's own zero value for the field, and
        // distinct from "the field is absent" (missing_schema_version_defaults_to_1 above),
        // since the two arrive through different branches of `.filter(|&v| v != 0)`.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .branch("feat-a")
            .raw_gh_stack(
                None,
                br#"{"schemaVersion": 0, "stacks": [{"number": 1, "trunk": {"branch": "main", "head": "", "base": ""}, "branches": [{"branch": "feat-a", "head": "", "base": ""}]}]}"#.to_vec(),
            )
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        let meta = read_metadata(repo).unwrap();
        assert_eq!(meta.parents["feat-a"].parent, "main");
        assert_eq!(meta.stack_numbers["feat-a"], 1);
    }

    #[test]
    fn needs_restack_true_when_base_differs_from_parent_live_tip() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .gh_stack_at(
                None,
                1,
                "main",
                &[("feat-a", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")],
            )
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        let meta = read_metadata(repo).unwrap();
        let entry = meta.parents.get("feat-a").unwrap();
        assert_eq!(
            entry.parent_revision.as_deref(),
            Some("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")
        );
        let main_tip = repo
            .find_branch("main", git2::BranchType::Local)
            .unwrap()
            .get()
            .target()
            .unwrap();
        assert_ne!(
            entry.parent_revision.as_deref(),
            Some(main_tip.to_string().as_str())
        );
    }

    #[test]
    fn degraded_union_pulls_in_unlinked_worktree_file() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .gh_stack(Some("feat-a"), 9, "main", &["feat-a"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        let meta = read_metadata(repo).unwrap();
        assert_eq!(meta.parents["feat-a"].parent, "main");
        assert_eq!(meta.stack_numbers["feat-a"], 9);
    }

    #[test]
    fn degraded_union_first_wins_on_disagreeing_unlinked_files() {
        // Two worktrees each hold their own unlinked file, both claiming stack number 1 for
        // a different branch set. Canonical is empty, so both are unioned; directory-name
        // order ("feat-a" < "feat-b") makes feat-a's file win the number-1 identity.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .worktree("feat-b")
            .gh_stack(Some("feat-a"), 1, "main", &["feat-a"])
            .gh_stack(Some("feat-b"), 1, "main", &["feat-b"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        let meta = read_metadata(repo).unwrap();
        assert!(meta.parents.contains_key("feat-a"));
        assert!(!meta.parents.contains_key("feat-b"));
    }

    // ── divergent_stack_numbers ─────────────────────────────────────────────────

    #[test]
    fn two_numbered_stacks_in_one_file_are_not_divergent() {
        // Regression test for finding H(a): divergent_stack_numbers used to increment a
        // global per-number counter across all sources, so two *different* stacks both
        // numbered 1 inside the SAME file tripped count > 1, contradicting the doc comment
        // "appear in more than one gh-stack source" (source means file, not array entry).
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .branch("other-trunk")
            .worktree("main")
            .gh_stack(None, 1, "main", &["feat-a"])
            .gh_stack(None, 1, "other-trunk", &["feat-b"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        assert!(divergent_stack_numbers(repo).is_empty());
    }

    #[test]
    fn identical_copy_across_canonical_and_unlinked_is_not_divergent() {
        // Regression test for finding H(b): an unlinked worktree file holding a byte-identical
        // copy of a canonical stack is the common state right after someone copies a
        // worktree, not a real divergence, so it must not be flagged.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .gh_stack(None, 4, "main", &["feat-a"])
            .gh_stack(Some("feat-a"), 4, "main", &["feat-a"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        assert!(divergent_stack_numbers(repo).is_empty());
    }

    #[test]
    fn genuinely_differing_copy_across_sources_is_divergent() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .branch("feat-b")
            .gh_stack(None, 4, "main", &["feat-a"])
            .gh_stack(Some("feat-a"), 4, "main", &["feat-b"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        assert_eq!(divergent_stack_numbers(repo), vec![4]);
    }

    #[test]
    fn branch_spanning_two_stacks_keeps_the_first_stacks_parent_and_number() {
        // Regression test for finding E: read_metadata's flattening loop deduped `trunks`
        // first-wins but wrote `parents`/`stack_numbers` last-wins, contradicting the module
        // doc's "first wins wholesale" and the spec's "first-seen wins, doctor flags it". Two
        // canonical stacks, both listing "shared" — stack 1 comes first in file order, so its
        // parent ("main") and number (1) must stick even though stack 2 ("other-trunk", 2) is
        // read afterward.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .branch("other-trunk")
            .worktree("main")
            .gh_stack(None, 1, "main", &["shared"])
            .gh_stack(None, 2, "other-trunk", &["shared"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        let meta = read_metadata(repo).unwrap();
        assert_eq!(meta.parents["shared"].parent, "main");
        assert_eq!(meta.stack_numbers["shared"], 1);
    }

    // ── link_worktree / migrate_worktree ────────────────────────────────────────

    #[test]
    fn link_worktree_plants_relative_symlinks() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        link_worktree(repo, "feat-a").unwrap();

        repo.assert(predicate::repo::gh_stack_is_linked("feat-a"));
        let lock_target = std::fs::read_link(
            repo.commondir()
                .join("worktrees")
                .join("feat-a")
                .join("gh-stack.lock"),
        )
        .unwrap();
        assert_eq!(lock_target, Path::new("../../gh-stack.lock"));
    }

    #[test]
    fn link_worktree_is_idempotent() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        link_worktree(repo, "feat-a").unwrap();
        link_worktree(repo, "feat-a").unwrap();

        repo.assert(predicate::repo::gh_stack_is_linked("feat-a"));
    }

    #[test]
    fn link_worktree_replaces_a_symlink_pointing_somewhere_wrong() {
        // plant_link has three arms: already-correct (link_worktree_is_idempotent), missing
        // (link_worktree_plants_relative_symlinks), and remove-and-recreate for a symlink that
        // exists but resolves elsewhere. Only the first two had coverage.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();
        let admin_dir = repo.commondir().join("worktrees").join("feat-a");

        create_symlink(Path::new("../../nonsense"), &admin_dir.join("gh-stack")).unwrap();

        link_worktree(repo, "feat-a").unwrap();

        repo.assert(predicate::repo::gh_stack_is_linked("feat-a"));
    }

    #[test]
    fn link_worktree_never_replaces_a_real_file() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .gh_stack(Some("feat-a"), 3, "main", &["feat-a"])
            .gh_stack_unlinked("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        link_worktree(repo, "feat-a").unwrap();

        // Still a real file — link_worktree must never clobber it.
        repo.assert(predicate::repo::gh_stack_contains_branch(
            Some("feat-a"),
            "feat-a",
            0,
        ));
        let meta =
            std::fs::symlink_metadata(repo.commondir().join("worktrees/feat-a/gh-stack")).unwrap();
        assert!(!meta.file_type().is_symlink());
    }

    #[test]
    fn migrate_worktree_merges_into_canonical_and_leaves_backup() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .gh_stack(Some("feat-a"), 7, "main", &["feat-a"])
            .gh_stack_unlinked("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        migrate_worktree(repo, "feat-a").unwrap();

        // Merged into canonical...
        repo.assert(predicate::repo::gh_stack_contains_branch(None, "feat-a", 0));
        // ...and the worktree is now linked to it.
        repo.assert(predicate::repo::gh_stack_is_linked("feat-a"));
        // ...with a backup of the original left behind.
        assert!(repo
            .commondir()
            .join("worktrees/feat-a/gh-stack.bak")
            .exists());

        let meta = read_metadata(repo).unwrap();
        assert_eq!(meta.stack_numbers["feat-a"], 7);
    }

    #[test]
    fn migrate_worktree_preserves_top_level_fields_when_canonical_is_absent() {
        // No `gh_stack`/`gh_stack_at` call targets `None` (canonical), so canonical doesn't
        // exist before migration and the merged document must be seeded from the worktree
        // file's whole `Value` — including `repository` — not synthesized from scratch.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .gh_stack(Some("feat-a"), 7, "main", &["feat-a"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        migrate_worktree(repo, "feat-a").unwrap();

        repo.assert(predicate::repo::gh_stack_preserves(
            None,
            "/repository",
            "git-workon-fixture/gh-stack",
        ));
        repo.assert(predicate::repo::gh_stack_contains_branch(None, "feat-a", 0));
    }

    #[test]
    fn migrate_worktree_falls_back_to_link_when_nothing_to_merge() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        migrate_worktree(repo, "feat-a").unwrap();

        repo.assert(predicate::repo::gh_stack_is_linked("feat-a"));
        assert!(!repo
            .commondir()
            .join("worktrees/feat-a/gh-stack.bak")
            .exists());
    }

    #[test]
    fn migrate_worktree_never_clobbers_an_existing_backup() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .gh_stack(Some("feat-a"), 7, "main", &["feat-a"])
            .gh_stack_unlinked("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        migrate_worktree(repo, "feat-a").unwrap();

        let admin_dir = repo.commondir().join("worktrees/feat-a");
        let first_backup = admin_dir.join("gh-stack.bak");
        assert!(first_backup.exists());
        let first_backup_contents = std::fs::read(&first_backup).unwrap();

        // Simulate a gh-stack release switching to temp-and-rename: the symlink this
        // worktree's `gh-stack` path was left as gets replaced with a real file again.
        std::fs::remove_file(admin_dir.join("gh-stack")).unwrap();
        std::fs::write(
            admin_dir.join("gh-stack"),
            br#"{"schemaVersion":1,"stacks":[]}"#,
        )
        .unwrap();

        migrate_worktree(repo, "feat-a").unwrap();

        // The first backup is untouched...
        assert_eq!(std::fs::read(&first_backup).unwrap(), first_backup_contents);
        // ...and the second migration's original landed in a numbered backup instead.
        assert!(admin_dir.join("gh-stack.bak.1").exists());
        repo.assert(predicate::repo::gh_stack_is_linked("feat-a"));
    }

    #[test]
    fn migrate_worktree_also_migrates_a_stale_lock_file() {
        // A worktree that has already run `gh stack` almost always has a real `gh-stack.lock`
        // alongside its real `gh-stack` file (upstream opens it O_CREATE on every lock
        // attempt). Both must end up symlinked, or this worktree's `gh stack` keeps flocking a
        // private inode while `register_branch` flocks the shared canonical lock.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .gh_stack(Some("feat-a"), 7, "main", &["feat-a"])
            .gh_stack_unlinked("feat-a")
            .gh_stack_lock_unlinked("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        let admin_dir = repo.commondir().join("worktrees/feat-a");
        let lock_meta_before = std::fs::symlink_metadata(admin_dir.join("gh-stack.lock")).unwrap();
        assert!(!lock_meta_before.file_type().is_symlink());

        migrate_worktree(repo, "feat-a").unwrap();

        repo.assert(predicate::repo::gh_stack_is_linked("feat-a"));
        let lock_meta_after = std::fs::symlink_metadata(admin_dir.join("gh-stack.lock")).unwrap();
        assert!(
            lock_meta_after.file_type().is_symlink(),
            "gh-stack.lock must be a symlink after migration"
        );
        let lock_target = std::fs::read_link(admin_dir.join("gh-stack.lock")).unwrap();
        assert_eq!(lock_target, Path::new("../../gh-stack.lock"));
    }

    #[test]
    fn worktree_link_status_reports_linked_for_a_fully_linked_worktree() {
        // Regression test: link_status_for_path used to compare BOTH the gh-stack and
        // gh-stack.lock paths against canonical_path (the gh-stack target), but plant_link
        // symlinks gh-stack.lock to `../../gh-stack.lock`, which can never resolve to
        // `../../gh-stack`. A correctly, fully linked worktree reported NotLinked forever, and
        // no test anywhere asserted LinkStatus::Linked, which is why this regression shipped.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .gh_stack(None, 1, "main", &["feat-a"])
            .gh_stack_linked("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        assert_eq!(worktree_link_status(repo, "feat-a"), LinkStatus::Linked);

        // Healthy-path invariants that also had no coverage: a fully linked worktree leaves
        // nothing for the degraded union fallback to pick up, and no stack number collides
        // with itself across sources.
        assert!(unlinked_files(repo).is_empty());
        assert!(divergent_stack_numbers(repo).is_empty());
    }

    #[test]
    fn worktree_link_status_reports_not_linked_when_lock_is_a_regular_file() {
        // gh-stack itself is correctly linked, but gh-stack.lock reverted to a real file (the
        // write-in-place risk this module's docs describe). worktree_link_status must catch
        // this from the gh-stack path alone being insufficient — doctor would otherwise report
        // `Linked` forever with no way to detect the lost cross-worktree exclusion.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .gh_stack_linked("feat-a")
            .gh_stack_lock_unlinked("feat-a")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        match worktree_link_status(repo, "feat-a") {
            LinkStatus::NotLinked { holds_file } => {
                // holds_file describes the gh-stack path, not the lock, and the gh-stack path
                // here is correctly linked (not holding a real file).
                assert!(!holds_file);
            }
            LinkStatus::Linked => panic!("expected NotLinked, got Linked"),
        }
    }

    // ── register_branch ─────────────────────────────────────────────────────────

    #[test]
    fn register_branch_appends_onto_a_trunk_with_no_branches_yet() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .branch("feat-a")
            .gh_stack(None, 1, "main", &[])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        register_branch(repo, "feat-a", "main").unwrap();

        repo.assert(predicate::repo::gh_stack_contains_branch(None, "feat-a", 0));
        let head_oid = repo
            .find_branch("feat-a", git2::BranchType::Local)
            .unwrap()
            .get()
            .target()
            .unwrap();
        repo.assert(predicate::repo::gh_stack_branch_base(
            None,
            "feat-a",
            head_oid.to_string(),
        ));
    }

    #[test]
    fn register_branch_appends_onto_the_top_of_an_existing_stack() {
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .gh_stack(None, 1, "main", &["feat-a"])
            .branch("feat-b")
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        register_branch(repo, "feat-b", "feat-a").unwrap();

        repo.assert(predicate::repo::gh_stack_contains_branch(None, "feat-a", 0));
        repo.assert(predicate::repo::gh_stack_contains_branch(None, "feat-b", 1));
    }

    #[test]
    fn register_branch_preserves_id_and_pull_request_on_untouched_entries() {
        // The existing entry's `id` and its branch's `pullRequest` are fields workon never
        // reads. A typed struct would silently drop them on write; the raw-Value round-trip
        // must not.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .branch("feat-a")
            .branch("feat-b")
            .raw_gh_stack(
                None,
                br#"{
                    "schemaVersion": 1,
                    "stacks": [{
                        "id": "stack-abc",
                        "number": 3,
                        "trunk": { "branch": "main", "head": "", "base": "" },
                        "branches": [{
                            "branch": "feat-a",
                            "head": "0000000000000000000000000000000000000a",
                            "base": "0000000000000000000000000000000000000b",
                            "pullRequest": { "number": 42, "id": "PR_1", "merged": false }
                        }]
                    }]
                }"#
                .to_vec(),
            )
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        register_branch(repo, "feat-b", "feat-a").unwrap();

        repo.assert(predicate::repo::gh_stack_contains_branch(None, "feat-a", 0));
        repo.assert(predicate::repo::gh_stack_contains_branch(None, "feat-b", 1));
        repo.assert(predicate::repo::gh_stack_preserves(
            None,
            "/stacks/0/id",
            "stack-abc",
        ));
        repo.assert(predicate::repo::gh_stack_preserves(
            None,
            "/stacks/0/branches/0/pullRequest/number",
            "42",
        ));
    }

    #[test]
    fn register_branch_surfaces_parse_failed_for_truncated_canonical() {
        // A truncated canonical file under an uncontended lock is genuine corruption, not a
        // mid-write race (a lock-respecting writer can't be mid-write once we hold the lock).
        // The read-under-lock ordering means this must deterministically surface
        // GhStackParseFailed rather than a stale pre-lock snapshot masking the truncation.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .branch("feat-a")
            .branch("feat-b")
            .gh_stack(None, 1, "main", &["feat-a"])
            .raw_gh_stack(None, b"{\"schemaVersion\": 1, \"stacks\": [".to_vec())
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        match register_branch(repo, "feat-b", "feat-a") {
            Err(StackError::GhStackParseFailed { .. }) => {}
            other => panic!("expected GhStackParseFailed, got {other:?}"),
        }
    }

    #[test]
    fn register_branch_errors_when_no_stack_ends_at_base() {
        // "main" is a real branch, but the only stack's last branch is "feat-a", not "main",
        // and its `branches` isn't empty, so "main" doesn't match either target-selection
        // rule.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .branch("feat-a")
            .branch("feat-b")
            .gh_stack(None, 1, "main", &["feat-a"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        match register_branch(repo, "feat-b", "main") {
            Err(StackError::GhStackNoStackForBase { base }) => {
                assert_eq!(base, "main");
            }
            other => panic!("expected GhStackNoStackForBase, got {other:?}"),
        }
    }

    #[test]
    fn register_branch_points_at_doctor_fix_when_stack_is_unlinked_only() {
        // Finding F: the chicken-and-egg case the spec explicitly accepts — `gh stack init`
        // run inside a worktree before `doctor --fix` ever migrates it. `read_metadata` unions
        // in unlinked_files, so `list`/`find` render the stack correctly, but `register_branch`
        // reads canonical alone (it must never write through a worktree symlink) and would
        // otherwise report the same generic GhStackNoStackForBase as "no such stack anywhere",
        // which is indistinguishable from user error. It must instead point at `doctor --fix`.
        let fixture = FixtureBuilder::new()
            .bare(true)
            .default_branch("main")
            .worktree("main")
            .worktree("feat-a")
            .branch("feat-b")
            .gh_stack(Some("feat-a"), 1, "main", &["feat-a"])
            .build()
            .unwrap();
        let repo = fixture.repo().unwrap();

        // Sanity: read_metadata (the list/find path) sees the stack fine via the degraded
        // union, so the failure below is specific to register_branch's canonical-only read.
        let meta = read_metadata(repo).unwrap();
        assert_eq!(meta.parents["feat-a"].parent, "main");

        match register_branch(repo, "feat-b", "feat-a") {
            Err(StackError::GhStackStackInUnlinkedWorktree { base }) => {
                assert_eq!(base, "feat-a");
            }
            other => panic!("expected GhStackStackInUnlinkedWorktree, got {other:?}"),
        }
    }
}