rvpm 3.30.3

Fast Neovim plugin manager with pre-compiled loader and merge optimization
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
use anyhow::Result;
use gix::bstr::BString;
use std::path::Path;

pub struct Repo<'a> {
    pub url: &'a str,
    pub dst: &'a Path,
    pub rev: Option<&'a str>,
}

#[derive(Debug, PartialEq, Eq)]
pub enum RepoStatus {
    NotInstalled,
    Clean,
    Modified,
    Error(String),
}

/// `Repo::sync` / `Repo::update` の差分情報。`rvpm log` の永続化用。
///
/// `from = None` は新規 clone を意味する (commit walk もしないので subjects 等は空)。
/// `from == to` (no-op の sync / update) の場合、呼び出し側は `Option<GitChange>::None`
/// を受け取る (Repo 側で「変更なし」を判別して丸める)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitChange {
    pub from: Option<String>,
    pub to: String,
    pub subjects: Vec<String>,
    pub breaking_subjects: Vec<String>,
    pub doc_files_changed: Vec<String>,
}

impl<'a> Repo<'a> {
    pub fn new(url: &'a str, dst: &'a Path, rev: Option<&'a str>) -> Self {
        Self { url, dst, rev }
    }

    /// clone 済みなら fetch + checkout、未 clone なら shallow clone。
    /// `Option<GitChange>` で差分を返す。HEAD が動かなかった場合は `None`。
    pub async fn sync(&self) -> Result<Option<GitChange>> {
        let url = resolve_url(self.url);
        let dst = self.dst.to_path_buf();
        let rev = self.rev.map(|s| s.to_string());
        tokio::task::spawn_blocking(move || sync_impl(&url, &dst, rev.as_deref()))
            .await
            .map_err(|e| anyhow::anyhow!("sync task panicked: {}", e))?
    }

    /// 既存 clone のみ受け付けて pull する。`Option<GitChange>` で差分を返す。
    /// HEAD が動かなかった場合は `None`。
    pub async fn update(&self) -> Result<Option<GitChange>> {
        let url = resolve_url(self.url);
        let dst = self.dst.to_path_buf();
        let rev = self.rev.map(|s| s.to_string());
        tokio::task::spawn_blocking(move || update_impl(&url, &dst, rev.as_deref()))
            .await
            .map_err(|e| anyhow::anyhow!("update task panicked: {}", e))?
    }

    pub async fn get_status(&self) -> RepoStatus {
        let dst = self.dst.to_path_buf();
        let rev = self.rev.map(|s| s.to_string());
        tokio::task::spawn_blocking(move || get_status_impl(&dst, rev.as_deref()))
            .await
            .unwrap_or(RepoStatus::Error("status check panicked".to_string()))
    }

    /// 現在 checkout 中の HEAD commit hash を返す。
    /// lockfile 書き込み時に "no-op sync でも現在の commit を記録する" ために使う
    /// (`sync()` の `GitChange` は HEAD が動いた時しか返されないため)。
    pub async fn head_commit(&self) -> Result<String> {
        let dst = self.dst.to_path_buf();
        tokio::task::spawn_blocking(move || read_head(&dst))
            .await
            .map_err(|e| anyhow::anyhow!("head_commit task panicked: {}", e))?
    }

    /// 既存 clone に対して **fetch せず** `rev` を checkout する。fetch cache の
    /// fast-path で「HEAD を effective_rev に揃えたいが window 内なので fetch は
    /// したくない」ケースに使う。rev が local DB に無ければエラーを返すので、
    /// caller は full sync にフォールバック (または `--no-refresh` なら error)
    /// する。`sync()` と同じく `Option<GitChange>` で HEAD 差分を返す。
    pub async fn checkout_locally(&self, rev: &str) -> Result<Option<GitChange>> {
        let dst = self.dst.to_path_buf();
        let rev = rev.to_string();
        tokio::task::spawn_blocking(move || checkout_local_impl(&dst, &rev))
            .await
            .map_err(|e| anyhow::anyhow!("checkout_locally task panicked: {}", e))?
    }

    /// `rev` (commit SHA / branch / tag) をローカルリポジトリで解決し、対応する
    /// commit SHA を返す。network を打たない。
    ///
    /// fetch cache の fast-path で「effective_rev (branch 名など) と local HEAD が
    /// 同じ commit を指してるか」を判定するために使う。commit SHA 同士の直接
    /// 比較だと `rev = "main"` / `rev = "v1.2.3"` 系をフォローできず、fast path
    /// の恩恵が失われるため。
    ///
    /// 未 clone / rev が local DB に無い / パースエラー → `Ok(None)` (caller は
    /// fast path 不適用として full flow に fall through する)。
    pub async fn resolve_revision_locally(&self, rev: &str) -> Result<Option<String>> {
        let dst = self.dst.to_path_buf();
        let rev = rev.to_string();
        tokio::task::spawn_blocking(move || resolve_revision_impl(&dst, &rev))
            .await
            .map_err(|e| anyhow::anyhow!("resolve_revision task panicked: {}", e))?
    }

    /// fetch 後の remote tracking branch の tip commit を返す。HEAD は動かさない。
    ///
    /// lockfile pin (rev なしで lockfile commit に寄せられているケース) が remote の
    /// 最新から乖離しているかを run_sync 側で判定するためのヘルパー。
    /// HEAD を読むわけではないので `head_commit()` と組み合わせて使う:
    /// `head != remote_head` なら「held back」。
    ///
    /// 解決順 (`gix_reset_to_remote` と同じロジック):
    /// 1. `refs/remotes/<remote>/<current_branch>`
    /// 2. `refs/remotes/<remote>/HEAD` (detached HEAD 時の fallback)
    ///
    /// どちらも解決できない場合は `None` (malformed repo、未 fetch 等)。
    /// caller は `None` を「判定不能」として扱い held-back 分類から除外する。
    pub async fn remote_head(&self) -> Result<Option<String>> {
        let dst = self.dst.to_path_buf();
        tokio::task::spawn_blocking(move || read_remote_head(&dst))
            .await
            .map_err(|e| anyhow::anyhow!("remote_head task panicked: {}", e))?
    }
}

/// owner/repo 形式のショートハンドを GitHub URL に変換。
/// ローカルパス (./  ../  ~/  絶対パス等) はそのまま返す。
fn resolve_url(url: &str) -> String {
    // 明らかに URL やパスの場合はそのまま
    if url.contains("://")
        || url.contains('@')
        || url.starts_with('/')
        || url.starts_with('~')
        || url.starts_with('.')
        || url.starts_with('\\')
        || (url.len() >= 2 && url.as_bytes()[1] == b':')
    // C:\ 等
    {
        return url.to_string();
    }
    // owner/repo 形式: exactly one slash, no special chars
    if url.matches('/').count() == 1 && !url.contains(' ') {
        format!("https://github.com/{}", url)
    } else {
        url.to_string()
    }
}

// ======================================================
// clone / fetch — gix で in-process 実行
// checkout — gix の checkout API は複雑なため git コマンドにフォールバック
// status — gix で in-process 実行 (プロセス fork なし)
// ======================================================

fn sync_impl(url: &str, dst: &Path, rev: Option<&str>) -> Result<Option<GitChange>> {
    if dst.exists() {
        let before = read_head(dst).ok();
        fetch_impl(dst)?;
        if let Some(rev) = rev {
            gix_checkout(dst, rev)?;
        } else {
            gix_reset_to_remote(dst)?;
        }
        let after = read_head(dst)?;
        Ok(build_change(dst, before, after))
    } else {
        clone_impl(url, dst)?;
        if let Some(rev) = rev {
            // 新規 clone は default branch しか fetch されてない (`gix::prepare_clone`
            // の narrow refspec)。user が `rev = "v1"` 等の non-default branch を
            // 指定したケースは、ここで全 branch refspec で再 fetch して
            // `refs/remotes/origin/<rev>` を populate しないと checkout できない。
            // `fetch_impl` 自体が冒頭で `ensure_all_branches_refspec` を呼ぶので、
            // この経路で .git/config も同時に正しい状態になる。
            fetch_impl(dst)?;
            gix_checkout(dst, rev)?;
        }
        let after = read_head(dst)?;
        // 新規 clone は from = None。subjects は空のまま。
        Ok(Some(GitChange {
            from: None,
            to: after,
            subjects: Vec::new(),
            breaking_subjects: Vec::new(),
            doc_files_changed: Vec::new(),
        }))
    }
}

fn update_impl(_url: &str, dst: &Path, rev: Option<&str>) -> Result<Option<GitChange>> {
    if !dst.exists() {
        anyhow::bail!("Plugin not installed: {}", dst.display());
    }
    let before = read_head(dst).ok();
    fetch_impl(dst)?;
    if let Some(rev) = rev {
        gix_checkout(dst, rev)?;
    } else {
        gix_reset_to_remote(dst)?;
    }
    let after = read_head(dst)?;
    Ok(build_change(dst, before, after))
}

/// HEAD の commit hash を読み取る。failure は呼び出し側で None 化することもある。
fn read_head(dst: &Path) -> Result<String> {
    let repo = gix::open(dst)?;
    let head = repo.head_commit()?;
    Ok(head.id().to_string())
}

/// 既存 clone に対して fetch せず `rev` を checkout する。
/// rev が local DB に無い場合は `gix_checkout` がエラーを返す (caller で fallback)。
fn checkout_local_impl(dst: &Path, rev: &str) -> Result<Option<GitChange>> {
    if !dst.exists() {
        anyhow::bail!("Plugin not installed: {}", dst.display());
    }
    let before = read_head(dst).ok();
    gix_checkout(dst, rev)?;
    let after = read_head(dst)?;
    Ok(build_change(dst, before, after))
}

/// `rev` を local DB で解決して **commit の** SHA 文字列を返す。
/// 未 clone / 未解決は `None`。
///
/// `rev_parse_single` 単独では annotated tag のときに tag object の SHA が返って
/// くる (commit SHA ではない)。そのまま local HEAD の commit SHA と比較すると
/// 常に不一致になり fast path が無効化されるので、git の `<rev>^{commit}` 記法で
/// tag chain を peel して commit に落とす。lightweight tag / branch / 生 SHA
/// ではこの記法は no-op なので副作用なし。
fn resolve_revision_impl(dst: &Path, rev: &str) -> Result<Option<String>> {
    if !dst.exists() {
        return Ok(None);
    }
    let repo = match gix::open(dst) {
        Ok(r) => r,
        Err(_) => return Ok(None),
    };
    let peeled = format!("{}^{{commit}}", rev);
    if let Ok(id) = repo.rev_parse_single(&peeled[..]) {
        return Ok(Some(id.detach().to_string()));
    }
    // `^{commit}` が効かない edge case (gix が記法非対応の revision 形式等) の
    // 保険: plain parse を試す。
    match repo.rev_parse_single(rev) {
        Ok(id) => Ok(Some(id.detach().to_string())),
        Err(_) => Ok(None),
    }
}

/// remote tracking branch の tip を読み取る。HEAD は動かさない。
/// tracking branch (`refs/remotes/<remote>/<branch>`) が見つからなければ
/// `refs/remotes/<remote>/HEAD` に fallback。それも無ければ `Ok(None)`。
fn read_remote_head(dst: &Path) -> Result<Option<String>> {
    let repo = gix::open(dst)?;
    let remote_name = repo
        .find_default_remote(gix::remote::Direction::Fetch)
        .and_then(|r| r.ok())
        .and_then(|r| r.name().map(|n| n.as_bstr().to_string()))
        .unwrap_or_else(|| "origin".to_string());

    // tracking ref が見つかっても peel 失敗時は `Ok(None)` に落とす (resilience:
    // malformed ref や stale packed-refs で held-back 判定全体が止まるのを避け、
    // 代わりにそのプラグインを「判定不能」として分類から除外する)。
    if let Some(head_name) = repo.head_name()? {
        let branch = head_name.as_bstr().to_string();
        let tracking = branch.replace("refs/heads/", &format!("refs/remotes/{}/", remote_name));
        if let Ok(mut tr) = repo.find_reference(&tracking)
            && let Ok(id) = tr.peel_to_id()
        {
            return Ok(Some(id.detach().to_string()));
        }
    }

    let remote_head_ref = format!("refs/remotes/{}/HEAD", remote_name);
    if let Ok(mut r) = repo.find_reference(&remote_head_ref)
        && let Ok(id) = r.peel_to_id()
    {
        return Ok(Some(id.detach().to_string()));
    }
    Ok(None)
}

/// before/after の HEAD から `GitChange` を組み立てる。
/// before == after なら `None` (no-op の sync/update を caller が判別できるように)。
fn build_change(dst: &Path, before: Option<String>, after: String) -> Option<GitChange> {
    match before {
        Some(b) if b == after => None,
        Some(b) => {
            let (subjects, breaking) = collect_subjects_and_breaking(dst, &b, &after);
            let doc_files = doc_files_changed(dst, &b, &after);
            Some(GitChange {
                from: Some(b),
                to: after,
                subjects,
                breaking_subjects: breaking,
                doc_files_changed: doc_files,
            })
        }
        None => Some(GitChange {
            from: None,
            to: after,
            subjects: Vec::new(),
            breaking_subjects: Vec::new(),
            doc_files_changed: Vec::new(),
        }),
    }
}

/// `<from>..<to>` を gix で walk し、(subjects, breaking_subjects) を返す。
/// commit graph の取得や revparse に失敗した場合は空ベクタ (resilience: log は best-effort)。
fn collect_subjects_and_breaking(dst: &Path, from: &str, to: &str) -> (Vec<String>, Vec<String>) {
    let mut subjects = Vec::new();
    let mut breaking = Vec::new();

    let repo = match gix::open(dst) {
        Ok(r) => r,
        Err(_) => return (subjects, breaking),
    };
    let from_id = match repo.rev_parse_single(from) {
        Ok(id) => id.detach(),
        Err(_) => return (subjects, breaking),
    };
    let to_id = match repo.rev_parse_single(to) {
        Ok(id) => id.detach(),
        Err(_) => return (subjects, breaking),
    };

    // walk to → ... → from (exclude from itself)
    let walk = match repo.rev_walk([to_id]).with_hidden([from_id]).all() {
        Ok(w) => w,
        Err(_) => return (subjects, breaking),
    };

    // 上限: 長期未更新後の pull や branch 切り替えで履歴が膨大になっても
    // `update_log.json` を肥大化させないため、subjects は最大 100 commit に制限。
    // 100 を超えた場合は新しい順 100 件だけ残る (rev_walk は新しい順)。
    const SUBJECT_WALK_LIMIT: usize = 100;
    for info in walk.flatten().take(SUBJECT_WALK_LIMIT) {
        let commit = match info.object() {
            Ok(c) => c,
            Err(_) => continue,
        };
        // gix の message_raw_sloppy は subject + body 全部入りの bytes。
        // subject は最初の改行まで、body は残り。
        let message = commit.message_raw_sloppy().to_string();
        let (subject, body) = split_subject_body(&message);
        let subj_str = subject.trim().to_string();
        if subj_str.is_empty() {
            continue;
        }
        let is_break = crate::update_log::is_breaking(&subj_str, body);
        if is_break {
            breaking.push(subj_str.clone());
        }
        subjects.push(subj_str);
    }

    (subjects, breaking)
}

fn split_subject_body(msg: &str) -> (&str, &str) {
    if let Some(idx) = msg.find('\n') {
        (&msg[..idx], &msg[idx + 1..])
    } else {
        (msg, "")
    }
}

/// `<from>..<to>` で変更があった README/CHANGELOG/doc 系ファイルの相対パス一覧を返す。
/// `git diff --name-only` を spawn する (gix の diff API は複雑なため subprocess)。
/// `git` が PATH に無い / 失敗時は空 Vec (resilience)。
fn doc_files_changed(dst: &Path, from: &str, to: &str) -> Vec<String> {
    let output = match std::process::Command::new("git")
        .arg("-C")
        .arg(dst)
        .args([
            "diff",
            "--name-only",
            &format!("{}..{}", from, to),
            "--",
            "README*",
            "readme*",
            "Readme*",
            "CHANGELOG*",
            "changelog*",
            "Changelog*",
            "doc/",
        ])
        .output()
    {
        Ok(o) => o,
        Err(_) => return Vec::new(),
    };
    if !output.status.success() {
        return Vec::new();
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut files: Vec<String> = stdout
        .lines()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();
    files.sort();
    files.dedup();
    files
}

fn clone_impl(url: &str, dst: &Path) -> Result<()> {
    if let Some(parent) = dst.parent() {
        std::fs::create_dir_all(parent)?;
    }

    // shallow clone (depth 1) で高速化
    let (mut _checkout, _outcome) = gix::prepare_clone(url, dst)?
        .with_shallow(gix::remote::fetch::Shallow::DepthAtRemote(
            std::num::NonZeroU32::new(1).unwrap(),
        ))
        .fetch_then_checkout(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)
        .map_err(|e| {
            let _ = std::fs::remove_dir_all(dst);
            anyhow::anyhow!("git clone failed: {}", e)
        })?;

    _checkout
        .main_worktree(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)
        .map_err(|e| {
            let _ = std::fs::remove_dir_all(dst);
            anyhow::anyhow!("checkout failed: {}", e)
        })?;

    // clone 直後に refspec を全 branch に正規化しておくと、user が `rev = "v1"`
    // 等の非デフォルト branch を指定したケースで次回 fetch から拾える。
    // エラーを `?` で伝播 (Gemini #99 指摘): silent 握り潰しだと clone は成功した
    // のに後続 fetch で謎の "rev not found" になり原因究明が困難。
    ensure_all_branches_refspec(dst)?;

    Ok(())
}

fn fetch_impl(dst: &Path) -> Result<()> {
    // gix の prepare_clone は default で「default branch のみ」refspec を書く。
    // user が `rev = "v1"` のように非デフォルト branch を指定したとき rev_parse_single
    // が refs/remotes/origin/v1 を見つけられず "rev not found" になる。
    // → fetch のたびに `.git/config` の refspec を全 branch に正規化して
    //   次回以降 `git fetch` が全 branch を取れるようにする (idempotent)。
    ensure_all_branches_refspec(dst)?;

    let repo = gix::open(dst)?;
    let remote = repo
        .find_default_remote(gix::remote::Direction::Fetch)
        .ok_or_else(|| anyhow::anyhow!("no remote configured"))??;

    remote
        .connect(gix::remote::Direction::Fetch)?
        .prepare_fetch(gix::progress::Discard, Default::default())?
        .with_shallow(gix::remote::fetch::Shallow::Deepen(1))
        .receive(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)?;

    Ok(())
}

/// `.git/config` の `[remote "origin"] fetch = ...` を全 branch refspec に正規化する。
///
/// gix の `prepare_clone` は default で `refs/heads/<default>:refs/remotes/origin/<default>`
/// だけを書くが、これだと user が `rev = "v1"` (= origin の v1 branch) を指定したとき、
/// fetch しても v1 が remote tracking ref として作られず checkout できない。
///
/// git CLI の標準動作 (`+refs/heads/*:refs/remotes/origin/*`) に揃えれば、以降の
/// fetch_impl で全 branch が `refs/remotes/origin/<branch>` として取れる。
///
/// 既存 .git/config でも同じ問題があるので、fetch のたびにこの関数を呼ぶ
/// (idempotent: 既に正しい設定なら no-op)。
fn ensure_all_branches_refspec(dst: &Path) -> Result<()> {
    let config_path = dst.join(".git").join("config");
    let content = match std::fs::read_to_string(&config_path) {
        Ok(c) => c,
        Err(_) => return Ok(()), // .git/config が無いなら fetch 側でエラーになるので静観
    };
    let want = "+refs/heads/*:refs/remotes/origin/*";
    if content.contains(want) {
        return Ok(());
    }
    // `[remote "origin"]` セクション内の `fetch = ...` 行を全 branch refspec に置換。
    // セクション境界は次の `[...]` 行か EOF。
    //
    // 旧実装は append 経路で「`replaced = false` なら末尾に追記」していたが、
    // `[remote "origin"]` の後に他のセクションが続いていると新 fetch 行が誤って
    // 末尾セクション (例: `[branch "main"]`) の所属になっていた (Gemini High 指摘)。
    // → 今は **iterate 中に origin セクションのスコープを追跡し、フェッチ行が
    //   無いまま origin が閉じる瞬間に注入する**。EOF までに見つからなければ
    //   末尾に origin セクションごと追加する。
    let mut new_content = String::with_capacity(content.len() + 64);
    let mut in_origin_section = false;
    let mut replaced = false;
    let mut pending_origin_fetch_inject = false;
    let leading_ws_default = "\t"; // git config の慣習
    for line in content.lines() {
        let trimmed = line.trim_start();
        let starts_section = trimmed.starts_with('[');

        // 既に origin セクション内で fetch 行未発見、かつ次のセクション開始 →
        // ここで fetch 行を origin の所属として注入してから次セクションへ進む。
        if starts_section && pending_origin_fetch_inject {
            new_content.push_str(leading_ws_default);
            new_content.push_str("fetch = ");
            new_content.push_str(want);
            new_content.push('\n');
            pending_origin_fetch_inject = false;
            replaced = true;
        }

        if starts_section {
            // 新しいセクション開始
            in_origin_section = trimmed.starts_with("[remote \"origin\"]")
                || trimmed.starts_with("[remote 'origin']");
            if in_origin_section {
                // origin に入った瞬間に「fetch 行を注入したい」状態に入れる。
                // この後の行で `fetch = ...` が見つかれば置換に切り替えて
                // pending を解除する。
                pending_origin_fetch_inject = true;
            }
        } else if in_origin_section
            && let Some(idx) = trimmed.find("fetch")
            && trimmed[idx..]
                .trim_start_matches("fetch")
                .trim_start()
                .starts_with('=')
        {
            // `fetch = ...` 行を上書き
            let leading_ws = &line[..line.len() - line.trim_start().len()];
            new_content.push_str(leading_ws);
            new_content.push_str("fetch = ");
            new_content.push_str(want);
            new_content.push('\n');
            replaced = true;
            pending_origin_fetch_inject = false;
            continue;
        }
        new_content.push_str(line);
        new_content.push('\n');
    }
    // EOF までに origin セクション内で fetch 行を一度も見ていない場合 (= origin が
    // 最後のセクションで `fetch = ...` 自体が無いケース)。pending_origin_fetch_inject
    // が立っていれば末尾に挿入。
    if pending_origin_fetch_inject {
        new_content.push_str(leading_ws_default);
        new_content.push_str("fetch = ");
        new_content.push_str(want);
        new_content.push('\n');
        replaced = true;
    }
    // origin セクションそのものが無いケース (rvpm が clone した直後なら必ずあるが、
    // .git/config が手動で壊された等のガード)。末尾に新規セクションを足す。
    if !replaced && !new_content.contains("[remote \"origin\"]") {
        new_content.push_str("[remote \"origin\"]\n");
        new_content.push_str(leading_ws_default);
        new_content.push_str("fetch = ");
        new_content.push_str(want);
        new_content.push('\n');
    }
    std::fs::write(&config_path, new_content)?;
    Ok(())
}

/// gix で特定の rev に checkout。branch の場合は branch を維持。
///
/// rev 解決順 (git CLI の `git checkout <rev>` と挙動を揃える):
///   1. `rev_parse_single(rev)` — 直接 ref / tag / SHA を試す
///   2. (1) が失敗で rev が non-default branch のとき: `refs/remotes/origin/<rev>` を
///      明示的に試して、ローカル branch を作る (git CLI の auto-track 相当)
///
/// 旧実装は (1) のみだったので `rev = "v1"` 等の非デフォルト branch は、`.git/config`
/// が全 branch refspec を持ち remote tracking ref も存在していても "rev not found"
/// になっていた (#user 報告)。
fn gix_checkout(dst: &Path, rev: &str) -> Result<()> {
    let repo = gix::open(dst)?;

    // (1) 直接解決
    let direct = repo.rev_parse_single(rev);
    let (commit_id, source) = match direct {
        Ok(id) => (id.detach(), DirectOrRemote::Direct),
        Err(_) => {
            // (2) refs/remotes/origin/<rev> を試す (= remote tracking branch)
            let remote_ref = format!("refs/remotes/origin/{rev}");
            let remote_id = repo
                .find_reference(&remote_ref)
                .ok()
                .and_then(|mut r| r.peel_to_id().ok())
                .ok_or_else(|| anyhow::anyhow!("rev '{}' not found", rev))?;
            (remote_id.detach(), DirectOrRemote::FromRemote)
        }
    };

    // rev が local branch (refs/heads/<rev>) を指す or 上記 (2) で remote から
    // 拾ったケースのどちらでも、symbolic HEAD で local branch を立てる。
    // (2) のとき local branch がまだ無ければ作る (= git CLI の `checkout <branch>`
    // で自動 tracking branch を作るのと同じ振る舞い)。
    let branch_ref = format!("refs/heads/{}", rev);
    let local_branch_exists = repo.find_reference(&branch_ref).is_ok();
    // local branch が既にあれば必ず symbolic HEAD で track。それが無くても
    // remote から拾った場合は新規作成する (`git checkout` の auto-tracking 相当)。
    // `Direct && exists` のチェックは `local_branch_exists` に内包されるので冗長 (Gemini 指摘)。
    let should_set_branch = local_branch_exists || matches!(source, DirectOrRemote::FromRemote);

    if should_set_branch {
        let head_path = repo.git_dir().join("HEAD");
        std::fs::write(&head_path, format!("ref: {}\n", branch_ref))?;
        repo.reference(
            branch_ref.as_str(),
            commit_id,
            gix::refs::transaction::PreviousValue::Any,
            BString::from(format!("rvpm: checkout branch {}", rev)),
        )?;
    } else {
        // tag/hash の場合は detached HEAD
        repo.reference(
            "HEAD",
            commit_id,
            gix::refs::transaction::PreviousValue::Any,
            BString::from(format!("rvpm: checkout {}", rev)),
        )?;
    }

    gix_checkout_head(&repo)?;
    Ok(())
}

/// `gix_checkout` の rev 解決経路 (debug / test 用)。
#[derive(Debug, Clone, Copy)]
enum DirectOrRemote {
    /// `rev_parse_single` で直接解決できた (local branch / tag / SHA)。
    Direct,
    /// `refs/remotes/origin/<rev>` から拾った (= remote tracking branch fallback)。
    FromRemote,
}

/// fetch 後に working tree を remote の最新に更新 (git reset --hard 相当)。
fn gix_reset_to_remote(dst: &Path) -> Result<()> {
    let repo = gix::open(dst)?;

    // remote 名を動的に取得 (通常は "origin")
    let remote_name = repo
        .find_default_remote(gix::remote::Direction::Fetch)
        .and_then(|r| r.ok())
        .and_then(|r| r.name().map(|n| n.as_bstr().to_string()))
        .unwrap_or_else(|| "origin".to_string());

    // remote tracking branch からターゲット commit を取得
    let target_id = {
        let head_name = repo.head_name()?;
        let tracking_ref = if let Some(ref name) = head_name {
            // refs/heads/master → refs/remotes/<remote>/master
            let branch = name.as_bstr().to_string();
            let tracking = branch.replace("refs/heads/", &format!("refs/remotes/{}/", remote_name));
            repo.find_reference(&tracking).ok()
        } else {
            None
        };

        if let Some(mut tr) = tracking_ref {
            tr.peel_to_id()?.detach()
        } else {
            // フォールバック: <remote>/HEAD
            let remote_head = format!("refs/remotes/{}/HEAD", remote_name);
            if let Ok(mut r) = repo.find_reference(&remote_head) {
                r.peel_to_id()?.detach()
            } else {
                return Ok(());
            }
        }
    };

    // ローカル branch を更新 (detached HEAD の場合は HEAD 直接更新)
    if let Some(head_name) = repo.head_name()? {
        repo.reference(
            head_name.as_ref(),
            target_id,
            gix::refs::transaction::PreviousValue::Any,
            BString::from("rvpm: fast-forward"),
        )?;
    } else {
        repo.reference(
            "HEAD",
            target_id,
            gix::refs::transaction::PreviousValue::Any,
            BString::from("rvpm: fast-forward detached"),
        )?;
    }

    // worktree を更新
    gix_checkout_head(&repo)?;
    Ok(())
}

/// HEAD の tree を worktree に展開 (gix_worktree_state::checkout)。
fn gix_checkout_head(repo: &gix::Repository) -> Result<()> {
    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow::anyhow!("bare repository"))?;

    let head = repo.head_commit()?;
    let tree_id = head.tree_id()?;

    let co_opts =
        repo.checkout_options(gix::worktree::stack::state::attributes::Source::IdMapping)?;
    let index = gix::index::State::from_tree(&tree_id, &repo.objects, Default::default())
        .map_err(|e| anyhow::anyhow!("index from tree: {}", e))?;
    let mut index_file = gix::index::File::from_state(index, repo.index_path());

    let opts = gix::worktree::state::checkout::Options {
        destination_is_initially_empty: false,
        overwrite_existing: true,
        ..co_opts
    };

    let progress = gix::progress::Discard;
    gix::worktree::state::checkout(
        &mut index_file,
        workdir,
        repo.objects.clone().into_arc()?,
        &progress,
        &progress,
        &gix::interrupt::IS_INTERRUPTED,
        opts,
    )
    .map_err(|e| anyhow::anyhow!("checkout failed: {}", e))?;

    index_file
        .write(Default::default())
        .map_err(|e| anyhow::anyhow!("write index: {}", e))?;

    Ok(())
}

/// gix を使ったプロセス fork なしのステータスチェック。
fn get_status_impl(dst: &Path, rev: Option<&str>) -> RepoStatus {
    if !dst.exists() {
        return RepoStatus::NotInstalled;
    }

    let repo = match gix::open(dst) {
        Ok(r) => r,
        Err(_) => return RepoStatus::Error("Failed to open git repo".to_string()),
    };

    // ワーキングツリーの変更を検出
    match repo.is_dirty() {
        Ok(true) => return RepoStatus::Modified,
        Ok(false) => {}
        Err(e) => return RepoStatus::Error(format!("status check failed: {}", e)),
    }

    // rev が指定されている場合、ローカルに存在するか確認
    if let Some(rev) = rev {
        match repo.rev_parse_single(rev) {
            Ok(_) => {}
            Err(_) => return RepoStatus::Error(format!("rev '{}' not found in local repo", rev)),
        }
    }

    RepoStatus::Clean
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;
    use tokio::process::Command;

    fn git_cmd(dir: &Path) -> Command {
        let mut cmd = Command::new("git");
        cmd.current_dir(dir)
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_CONFIG_GLOBAL", dir.join(".gitconfig-test"))
            .env("GIT_AUTHOR_NAME", "test")
            .env("GIT_AUTHOR_EMAIL", "test@test.com")
            .env("GIT_COMMITTER_NAME", "test")
            .env("GIT_COMMITTER_EMAIL", "test@test.com");
        cmd
    }

    #[tokio::test]
    async fn test_get_status_not_installed() {
        let root = tempdir().unwrap();
        let dst = root.path().join("nonexistent");
        let repo = Repo::new("dummy", &dst, None);
        assert_eq!(repo.get_status().await, RepoStatus::NotInstalled);
    }

    #[tokio::test]
    async fn test_get_status_clean() {
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("hello.txt"), "hello").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();

        let repo = Repo::new(src.to_str().unwrap(), &src, None);
        assert_eq!(repo.get_status().await, RepoStatus::Clean);
    }

    #[tokio::test]
    async fn test_get_status_modified() {
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("hello.txt"), "hello").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();

        fs::write(src.join("hello.txt"), "modified").unwrap();
        let repo = Repo::new(src.to_str().unwrap(), &src, None);
        assert_eq!(repo.get_status().await, RepoStatus::Modified);
    }

    #[tokio::test]
    async fn test_get_status_errors_on_invalid_rev() {
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("hello.txt"), "hello").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();

        let repo = Repo::new(src.to_str().unwrap(), &src, Some("nonexistent-rev"));
        let status = repo.get_status().await;
        assert!(matches!(status, RepoStatus::Error(_)));
    }

    #[tokio::test]
    async fn test_update_fails_when_not_installed() {
        let root = tempdir().unwrap();
        let dst = root.path().join("nonexistent");
        let repo = Repo::new("dummy/repo", &dst, None);
        let result = repo.update().await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not installed"));
    }

    #[tokio::test]
    async fn test_resolve_url_adds_github_prefix() {
        assert_eq!(resolve_url("owner/repo"), "https://github.com/owner/repo");
        assert_eq!(
            resolve_url("https://github.com/owner/repo"),
            "https://github.com/owner/repo"
        );
    }

    #[tokio::test]
    async fn test_sync_clones_new_repo() {
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        let dst = root.path().join("dst");

        // ローカル bare repo を作成
        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("hello.txt"), "hello").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();

        let repo = Repo::new(src.to_str().unwrap(), &dst, None);
        let change = repo.sync().await.unwrap();

        assert!(dst.join("hello.txt").exists());
        let content = fs::read_to_string(dst.join("hello.txt")).unwrap();
        assert_eq!(content, "hello");

        // 新規 clone は from = None で GitChange::Some を返す
        let c = change.expect("new clone should produce a GitChange");
        assert!(c.from.is_none());
        assert!(!c.to.is_empty());
        assert!(c.subjects.is_empty());
    }

    #[tokio::test]
    async fn test_sync_updates_existing_repo() {
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        let dst = root.path().join("dst");

        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("hello.txt"), "hello").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();

        let repo = Repo::new(src.to_str().unwrap(), &dst, None);
        let initial = repo.sync().await.unwrap();
        assert!(initial.is_some(), "first sync = clone produces a change");

        // 同じ HEAD で再 sync → no-op (None)
        let noop = repo.sync().await.unwrap();
        assert!(noop.is_none(), "no-op sync should yield None");

        // src を更新
        fs::write(src.join("hello.txt"), "updated").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "update"])
            .output()
            .await
            .unwrap();

        // 再 sync で差分発生
        let updated = repo.sync().await.unwrap().expect("HEAD moved");
        assert!(updated.from.is_some(), "from should be the previous HEAD");
        assert_ne!(updated.from.as_deref(), Some(updated.to.as_str()));
        assert!(
            updated.subjects.iter().any(|s| s.contains("update")),
            "subjects should contain the new commit, got {:?}",
            updated.subjects
        );

        let content = fs::read_to_string(dst.join("hello.txt")).unwrap();
        assert_eq!(content, "updated");
    }

    #[tokio::test]
    async fn test_sync_breaking_commit_detected() {
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        let dst = root.path().join("dst");

        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("hello.txt"), "v1").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();

        let repo = Repo::new(src.to_str().unwrap(), &dst, None);
        repo.sync().await.unwrap();

        // bang 形式の breaking commit を 1 件追加
        fs::write(src.join("hello.txt"), "v2").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "feat!: redesign"])
            .output()
            .await
            .unwrap();

        let change = repo.sync().await.unwrap().expect("HEAD moved");
        assert_eq!(change.breaking_subjects.len(), 1, "{:?}", change);
        assert!(change.breaking_subjects[0].contains("feat!: redesign"));
    }

    async fn git_head(dir: &Path) -> String {
        let out = git_cmd(dir)
            .args(["rev-parse", "HEAD"])
            .output()
            .await
            .unwrap();
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    }

    #[tokio::test]
    async fn test_remote_head_reports_tracking_branch_tip() {
        // Mirrors the "held back by lockfile pin" scenario: pin to an old
        // commit, advance the remote, verify that remote_head reflects the
        // new remote tip while HEAD stays at the pin.
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        let dst = root.path().join("dst");

        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("a.txt"), "v1").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();
        let initial = git_head(&src).await;

        // Fresh clone → local HEAD == remote tip.
        let repo = Repo::new(src.to_str().unwrap(), &dst, None);
        repo.sync().await.unwrap();
        assert_eq!(
            repo.remote_head().await.unwrap().as_deref(),
            Some(initial.as_str()),
            "fresh clone: remote_head should match HEAD"
        );

        // Advance the remote by one commit.
        fs::write(src.join("a.txt"), "v2").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "advance"])
            .output()
            .await
            .unwrap();
        let new_tip = git_head(&src).await;
        assert_ne!(new_tip, initial, "remote tip must have moved");

        // Re-sync with the pinned rev: fetch brings the new ref in, but
        // HEAD stays at `initial`.
        let pinned = Repo::new(src.to_str().unwrap(), &dst, Some(initial.as_str()));
        pinned.sync().await.unwrap();
        assert_eq!(
            pinned.head_commit().await.unwrap(),
            initial,
            "pinned sync must keep HEAD at the requested rev"
        );

        // remote_head must return the NEW tip, signalling the held-back state.
        let rh = pinned.remote_head().await.unwrap();
        assert_eq!(
            rh.as_deref(),
            Some(new_tip.as_str()),
            "remote_head must report the fetched remote tip, not HEAD"
        );
        assert_ne!(rh.as_deref(), Some(initial.as_str()));
    }

    #[tokio::test]
    async fn test_resolve_revision_locally_handles_sha_branch_tag_and_missing() {
        // Fast-path comparison depends on being able to resolve branch/tag
        // refs to SHAs locally without hitting the network. Exercise all
        // four cases (full SHA / branch / tag / bogus) from a single repo.
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        let dst = root.path().join("dst");

        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("a.txt"), "seed").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();
        git_cmd(&src)
            .args(["tag", "v1.0.0"])
            .output()
            .await
            .unwrap();
        let head_sha = git_head(&src).await;
        let branch = {
            let out = git_cmd(&src)
                .args(["rev-parse", "--abbrev-ref", "HEAD"])
                .output()
                .await
                .unwrap();
            String::from_utf8(out.stdout).unwrap().trim().to_string()
        };

        let repo = Repo::new(src.to_str().unwrap(), &dst, None);
        repo.sync().await.unwrap();

        // Full SHA round-trips.
        assert_eq!(
            repo.resolve_revision_locally(&head_sha).await.unwrap(),
            Some(head_sha.clone()),
        );
        // Branch name resolves to the same SHA.
        assert_eq!(
            repo.resolve_revision_locally(&branch).await.unwrap(),
            Some(head_sha.clone()),
        );
        // Tag name resolves to the same SHA.
        assert_eq!(
            repo.resolve_revision_locally("v1.0.0").await.unwrap(),
            Some(head_sha.clone()),
        );
        // Nonexistent rev degrades to None (caller falls through to full sync).
        assert_eq!(
            repo.resolve_revision_locally("no-such-rev").await.unwrap(),
            None,
        );
    }

    #[tokio::test]
    async fn test_resolve_revision_locally_returns_none_on_missing_clone() {
        let root = tempdir().unwrap();
        let dst = root.path().join("never-cloned");
        let repo = Repo::new("dummy", &dst, None);
        assert_eq!(repo.resolve_revision_locally("HEAD").await.unwrap(), None,);
    }

    #[tokio::test]
    async fn test_resolve_revision_locally_peels_annotated_tag_to_commit() {
        // Annotated tags are backed by their own tag object whose SHA differs
        // from the commit they point at. Plain `rev_parse_single` returns the
        // tag-object SHA, which would never match HEAD and silently disable
        // the fast path. Verify we peel to the underlying commit.
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        let dst = root.path().join("dst");

        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("a.txt"), "seed").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();
        git_cmd(&src)
            .args(["tag", "-a", "v2.0.0", "-m", "annotated"])
            .output()
            .await
            .unwrap();
        let head_sha = git_head(&src).await;

        let repo = Repo::new(src.to_str().unwrap(), &dst, None);
        repo.sync().await.unwrap();

        assert_eq!(
            repo.resolve_revision_locally("v2.0.0").await.unwrap(),
            Some(head_sha),
            "annotated tag must resolve to the target commit SHA",
        );
    }

    #[tokio::test]
    async fn test_checkout_locally_moves_head_to_existing_commit() {
        // --no-refresh path: HEAD at commit B, user wants A, and A is already
        // in the local object DB. `checkout_locally` must move HEAD without
        // talking to the network. We build the DB directly with `git init` +
        // two commits in dst, bypassing `repo.sync()` — sync uses a shallow
        // (depth-1) clone that would not keep the older commit locally and
        // would mask the exact code path we want to exercise.
        let root = tempdir().unwrap();
        let dst = root.path().join("dst");

        fs::create_dir_all(&dst).unwrap();
        git_cmd(&dst).args(["init"]).output().await.unwrap();
        fs::write(dst.join("a.txt"), "v1").unwrap();
        git_cmd(&dst).args(["add", "."]).output().await.unwrap();
        git_cmd(&dst)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();
        let first = git_head(&dst).await;
        fs::write(dst.join("a.txt"), "v2").unwrap();
        git_cmd(&dst).args(["add", "."]).output().await.unwrap();
        git_cmd(&dst)
            .args(["commit", "-m", "bump"])
            .output()
            .await
            .unwrap();
        let second = git_head(&dst).await;

        let repo = Repo::new("dummy", &dst, None);
        assert_eq!(repo.head_commit().await.unwrap(), second);

        let change = repo.checkout_locally(&first).await.unwrap();
        assert!(
            change.is_some(),
            "HEAD should have moved, expected a GitChange"
        );
        assert_eq!(repo.head_commit().await.unwrap(), first);

        // Re-checkout of the same rev is a no-op (None GitChange).
        let change = repo.checkout_locally(&first).await.unwrap();
        assert!(change.is_none(), "re-checkout of same rev should be no-op");
    }

    #[test]
    fn ensure_all_branches_refspec_replaces_narrow_default_refspec() {
        // gix の prepare_clone は default で `.../<default>:.../<default>` の narrow
        // な refspec を書く。これだと `rev = "v1"` 等の非デフォルト branch が
        // fetch されない (issue: user 報告で rev 'v1' not found)。
        // この helper で `+refs/heads/*:refs/remotes/origin/*` (= git CLI の default)
        // に正規化される。
        let tmp = tempdir().unwrap();
        let dst = tmp.path();
        fs::create_dir_all(dst.join(".git")).unwrap();
        let initial = "[remote \"origin\"]\n\turl = https://github.com/foo/bar\n\tfetch = +refs/heads/main:refs/remotes/origin/main\n";
        fs::write(dst.join(".git/config"), initial).unwrap();

        ensure_all_branches_refspec(dst).unwrap();

        let after = fs::read_to_string(dst.join(".git/config")).unwrap();
        assert!(
            after.contains("+refs/heads/*:refs/remotes/origin/*"),
            "should rewrite to all-branch refspec: {after}"
        );
        assert!(
            !after.contains("refs/remotes/origin/main"),
            "narrow refspec should be replaced, not duplicated: {after}"
        );
    }

    #[test]
    fn ensure_all_branches_refspec_is_idempotent_when_already_correct() {
        let tmp = tempdir().unwrap();
        let dst = tmp.path();
        fs::create_dir_all(dst.join(".git")).unwrap();
        let already_correct =
            "[remote \"origin\"]\n\turl = x\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n";
        fs::write(dst.join(".git/config"), already_correct).unwrap();

        ensure_all_branches_refspec(dst).unwrap();

        let after = fs::read_to_string(dst.join(".git/config")).unwrap();
        // 1 行だけ存在することを確認 (重複追記してない)
        assert_eq!(
            after.matches("fetch = ").count(),
            1,
            "refspec should not be duplicated: {after}"
        );
    }

    #[test]
    fn ensure_all_branches_refspec_only_touches_origin_section() {
        // 他の remote セクションの fetch 行は触らない (rvpm は origin だけ管理)。
        let tmp = tempdir().unwrap();
        let dst = tmp.path();
        fs::create_dir_all(dst.join(".git")).unwrap();
        let mixed = "[remote \"upstream\"]\n\tfetch = +refs/heads/main:refs/remotes/upstream/main\n[remote \"origin\"]\n\tfetch = +refs/heads/main:refs/remotes/origin/main\n";
        fs::write(dst.join(".git/config"), mixed).unwrap();

        ensure_all_branches_refspec(dst).unwrap();

        let after = fs::read_to_string(dst.join(".git/config")).unwrap();
        assert!(
            after.contains("upstream/main"),
            "upstream section must be preserved: {after}"
        );
        assert!(
            after.contains("+refs/heads/*:refs/remotes/origin/*"),
            "origin should be normalized: {after}"
        );
    }

    #[test]
    fn ensure_all_branches_refspec_inserts_into_origin_when_origin_is_not_last_section() {
        // 旧実装は `replaced = false` 経路で末尾に append していたが、`[remote "origin"]`
        // が中間にある config だと新 fetch 行が **後続セクション** (例: `[branch "main"]`)
        // の所属になっていた (Gemini High 指摘 #99)。
        // 修正後: origin スコープを iterate 中に追跡し、次セクション開始 or EOF 直前に
        // 注入する。
        let tmp = tempdir().unwrap();
        let dst = tmp.path();
        fs::create_dir_all(dst.join(".git")).unwrap();
        // origin セクションには fetch 行が **無い**、後続に branch セクション。
        let initial = "[remote \"origin\"]\n\turl = https://github.com/foo/bar\n[branch \"main\"]\n\tremote = origin\n\tmerge = refs/heads/main\n";
        fs::write(dst.join(".git/config"), initial).unwrap();

        ensure_all_branches_refspec(dst).unwrap();

        let after = fs::read_to_string(dst.join(".git/config")).unwrap();
        // fetch 行は origin セクション内 (= branch セクションの **前**) にあるべき
        let fetch_pos = after
            .find("fetch = +refs/heads/*")
            .expect("fetch line written");
        let branch_pos = after
            .find("[branch \"main\"]")
            .expect("branch section preserved");
        assert!(
            fetch_pos < branch_pos,
            "fetch line must be inside [remote \"origin\"], i.e. BEFORE [branch \"main\"]:\n{after}"
        );
        // branch セクションの内容が壊れていないこと
        assert!(after.contains("merge = refs/heads/main"));
    }

    #[tokio::test]
    async fn test_sync_resolves_non_default_branch_via_full_refspec() {
        // 非デフォルト branch 名 (e.g. `v1`) を rev に指定したとき、fetch が
        // ちゃんと remote tracking ref を作って checkout が成功することを確認。
        // user 報告: blink.cmp の `rev = "v1"` が "rev not found" になるバグの
        // 回帰 test。
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        let dst = root.path().join("dst");

        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        // **最重要**: `git init` 直後の default branch を確定させる (CodeRabbit
        // PR #99 review 指摘)。後で v1 を作って checkout するので、この段階で
        // default を控えておかないと、setup 末尾で「現在の HEAD = v1」を
        // default だと誤認識して checkout を skip し、clone 元 src の HEAD が
        // v1 のまま残ってしまう。すると `gix::prepare_clone` が v1 を default
        // として cloning し、`rev_parse_single("v1")` の direct path だけで
        // 解決してしまうので、この test の本来の対象 (refs/remotes/origin/v1
        // fallback path) が exercise されなくなる。
        let init_head = git_cmd(&src)
            .args(["symbolic-ref", "--short", "HEAD"])
            .output()
            .await
            .expect("symbolic-ref HEAD just after init");
        let default_branch = String::from_utf8_lossy(&init_head.stdout)
            .trim()
            .to_string();
        assert_ne!(
            default_branch, "v1",
            "test invariant: init default must not be v1"
        );

        // master/main 上に commit
        fs::write(src.join("a.txt"), "main-1").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "main"])
            .output()
            .await
            .unwrap();
        // v1 branch を作って別 commit
        git_cmd(&src)
            .args(["checkout", "-b", "v1"])
            .output()
            .await
            .unwrap();
        fs::write(src.join("a.txt"), "v1-1").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "v1"])
            .output()
            .await
            .unwrap();
        let v1_head = git_head(&src).await;

        // src を default branch に戻す。これで `gix::prepare_clone` 時の
        // default ref は v1 ではなく default_branch になり、
        // `gix_checkout(dst, "v1")` は `refs/remotes/origin/v1` の fallback path
        // を経由して解決される (= この test の主旨)。
        git_cmd(&src)
            .args(["checkout", &default_branch])
            .output()
            .await
            .expect("checkout init default before clone");

        let url = format!("file://{}", src.display());
        let repo = Repo::new(&url, &dst, Some("v1"));
        repo.sync()
            .await
            .expect("sync to v1 should succeed after refspec normalization");

        // v1 の HEAD に揃っていること
        let head = repo.head_commit().await.unwrap();
        assert_eq!(head, v1_head, "checkout should land on v1 tip");
    }

    #[tokio::test]
    async fn test_checkout_locally_errors_when_rev_not_present() {
        // The commit isn't in the local object DB → error. Caller uses this
        // signal to fall through to full sync (or surface under --no-refresh).
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        let dst = root.path().join("dst");

        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("a.txt"), "only").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();

        let repo = Repo::new(src.to_str().unwrap(), &dst, None);
        repo.sync().await.unwrap();

        let result = repo
            .checkout_locally("ffffffffffffffffffffffffffffffffffffffff")
            .await;
        assert!(
            result.is_err(),
            "unknown rev must error, not silently succeed"
        );
    }

    #[tokio::test]
    async fn test_update_returns_change_or_none() {
        let root = tempdir().unwrap();
        let src = root.path().join("src");
        let dst = root.path().join("dst");

        fs::create_dir_all(&src).unwrap();
        git_cmd(&src).args(["init"]).output().await.unwrap();
        fs::write(src.join("a.txt"), "a").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "init"])
            .output()
            .await
            .unwrap();

        // sync first to install
        let repo = Repo::new(src.to_str().unwrap(), &dst, None);
        repo.sync().await.unwrap();

        // update with no remote changes → None
        assert!(repo.update().await.unwrap().is_none());

        // bump remote
        fs::write(src.join("a.txt"), "b").unwrap();
        git_cmd(&src).args(["add", "."]).output().await.unwrap();
        git_cmd(&src)
            .args(["commit", "-m", "bump"])
            .output()
            .await
            .unwrap();

        let c = repo.update().await.unwrap().expect("HEAD moved");
        assert!(c.from.is_some());
        assert!(c.subjects.iter().any(|s| s.contains("bump")));
    }
}