mkit-cli 0.4.0

The mkit command-line tool: a content-addressed VCS with native attestation support
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
//! Native remote-tracking prerequisites: remote-tracking refs are
//! first-class citizens of revspec/merge/show-ref/for-each-ref,
//! printable opaque identities render as text, replays preserve
//! authorship, and `remote rename/remove` cleans tracking refs.
#![allow(clippy::unwrap_used)] // unwrap is the assertion in test helpers

mod common;

use common::Repo;
use mkit_core::layout::RepoLayout;
use mkit_core::object::{Identity, Object};
use mkit_core::refs;
use mkit_core::store::ObjectStore;

/// Simulate a fetched tracking ref pointing at a commit ahead of HEAD.
fn plant_tracking_ref(r: &Repo, remote: &str, branch: &str) -> mkit_core::Hash {
    // Advance main, record the tip as the "remote" position, then move
    // main back so the tracking ref is strictly ahead.
    let layout = RepoLayout::single(r.path());
    let before = refs::read_ref(&layout, "main").unwrap().unwrap();
    r.commit_file("ahead.txt", b"ahead\n", "remote is ahead");
    let ahead = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, remote, branch, &ahead).unwrap();
    // Rewind main (guarded reset path not needed for test setup).
    refs::write_ref(&layout, "main", &before).unwrap();
    let store = ObjectStore::open(&layout).unwrap();
    let Object::Commit(c) = store.read_object(&before).unwrap() else {
        panic!("not a commit")
    };
    let tree = c.tree_hash;
    drop(store);
    // Restore worktree to match the rewound HEAD so merge sees clean state.
    let out = r.run(&["reset", "--hard", "-f", &mkit_core::to_hex(&before)]);
    assert!(out.status.success(), "reset: {out:?}");
    let _ = tree;
    ahead
}

#[test]
fn merge_fast_forwards_from_tracking_ref() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let ahead = plant_tracking_ref(&r, "up", "main");

    // Short form `<remote>/<branch>` resolves and fast-forwards.
    let out = r.ok(&["merge", "up/main"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.to_lowercase().contains("fast-forward"),
        "stderr: {stderr}"
    );
    assert_eq!(
        refs::read_ref(&RepoLayout::single(r.path()), "main")
            .unwrap()
            .unwrap(),
        ahead
    );
}

#[test]
fn revspec_resolves_remote_tracking_forms() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let ahead = plant_tracking_ref(&r, "up", "main");
    let hex = mkit_core::to_hex(&ahead);

    for spec in ["up/main", "refs/remotes/up/main"] {
        let out = r.ok(&["rev-parse", spec]);
        assert_eq!(
            String::from_utf8_lossy(&out.stdout).trim(),
            hex,
            "spec {spec}"
        );
    }
    // Suffix navigation works on tracking refs too.
    let out = r.ok(&["rev-parse", "up/main~1"]);
    assert_ne!(String::from_utf8_lossy(&out.stdout).trim(), hex);
}

#[test]
fn show_ref_and_for_each_ref_list_tracking_refs() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    plant_tracking_ref(&r, "up", "main");

    let out = r.ok(&["show-ref"]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("refs/remotes/up/main"),
        "show-ref: {stdout}"
    );
    // --heads keeps its narrow meaning.
    let out = r.ok(&["show-ref", "--heads"]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(!stdout.contains("refs/remotes/"), "--heads: {stdout}");

    let out = r.ok(&["for-each-ref"]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("refs/remotes/up/main"),
        "for-each-ref: {stdout}"
    );
}

#[test]
fn printable_opaque_author_renders_as_text() {
    let r = Repo::new();
    r.write("a.txt", b"a\n");
    r.ok(&["add", "a.txt"]);
    r.ok(&[
        "commit",
        "-m",
        "imported-style author",
        "--author",
        "opaque:Alice Example <alice@example.com>",
    ]);
    let out = r.ok(&["log", "-n", "1"]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("Author: Alice Example <alice@example.com>"),
        "log: {stdout}"
    );
}

#[test]
fn cherry_pick_preserves_author_and_timestamp() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    r.ok(&["branch", "side"]);
    r.ok(&["checkout", "side"]);
    r.write("b.txt", b"b\n");
    r.ok(&["add", "b.txt"]);
    r.ok(&[
        "commit",
        "-m",
        "side work",
        "--author",
        "opaque:Original Author <orig@example.com>",
    ]);
    let layout = RepoLayout::single(r.path());
    let picked = refs::read_ref(&layout, "side").unwrap().unwrap();
    let store = ObjectStore::open(&layout).unwrap();
    let Object::Commit(orig) = store.read_object(&picked).unwrap() else {
        panic!("not a commit")
    };

    r.ok(&["checkout", "main"]);
    // Advance main so the replay gets a different parent (with an
    // identical parent, deterministic signing + preserved authorship
    // reproduce the byte-identical commit — content addressing dedupes).
    r.commit_file("main2.txt", b"m\n", "main advances");
    r.ok(&["cherry-pick", &mkit_core::to_hex(&picked)]);

    let tip = refs::resolve_head(&layout).unwrap().unwrap();
    let Object::Commit(replayed) = store.read_object(&tip).unwrap() else {
        panic!("not a commit")
    };
    assert_eq!(
        replayed.author,
        Identity::opaque(b"Original Author <orig@example.com>".to_vec())
    );
    assert_eq!(replayed.timestamp, orig.timestamp);
    assert_ne!(tip, picked, "replay must be a new commit");
}

#[test]
fn remote_rename_moves_and_remove_deletes_tracking_refs() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "old", "main", &tip).unwrap();

    // Named remote in config so rename/remove operate on it.
    r.ok(&["remote", "add", "old", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "rename", "old", "new"]);
    assert!(
        refs::read_remote_ref(&layout, "new", "main")
            .unwrap()
            .is_some(),
        "rename must move tracking refs"
    );
    assert!(
        refs::read_remote_ref(&layout, "old", "main")
            .unwrap()
            .is_none()
    );

    r.ok(&["remote", "remove", "new"]);
    assert!(
        refs::read_remote_ref(&layout, "new", "main")
            .unwrap()
            .is_none(),
        "remove must delete tracking refs"
    );
}

/// Plant a marker file under `.mkit/git/<name>/` to stand in for
/// bridge state (leases/maps/staging mirror) without needing a real
/// git-bridge remote wired up.
fn plant_bridge_state(layout: &RepoLayout, name: &str) -> std::path::PathBuf {
    let dir = layout.git_state_dir().join(name);
    std::fs::create_dir_all(&dir).unwrap();
    let marker = dir.join("marker.txt");
    std::fs::write(&marker, b"bridge state\n").unwrap();
    marker
}

#[test]
fn remote_rename_single_to_multi_segment_moves_refs_and_bridge_state() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    plant_bridge_state(&layout, "a");

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    let out = r.ok(&["remote", "rename", "a", "team/upstream"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("could not move"),
        "single->multi-segment rename must not degrade: {stderr}"
    );

    assert!(
        refs::read_remote_ref(&layout, "team/upstream", "main")
            .unwrap()
            .is_some(),
        "rename must move tracking refs into the nested destination"
    );
    assert!(
        refs::read_remote_ref(&layout, "a", "main")
            .unwrap()
            .is_none()
    );

    let moved_marker = layout.git_state_dir().join("team/upstream/marker.txt");
    assert!(
        moved_marker.exists(),
        "bridge state must move into the nested destination"
    );
    assert_eq!(
        std::fs::read(&moved_marker).unwrap(),
        b"bridge state\n",
        "marker contents must survive the move"
    );
    assert!(!layout.git_state_dir().join("a").exists());
}

#[test]
fn remote_rename_multi_to_single_segment_moves_refs_and_prunes_empty_parent() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "team/upstream", "main", &tip).unwrap();
    plant_bridge_state(&layout, "team/upstream");

    r.ok(&["remote", "add", "team/upstream", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "rename", "team/upstream", "b"]);

    assert!(
        refs::read_remote_ref(&layout, "b", "main")
            .unwrap()
            .is_some(),
        "rename must move tracking refs to the flat destination"
    );
    assert!(
        refs::read_remote_ref(&layout, "team/upstream", "main")
            .unwrap()
            .is_none()
    );
    // No orphaned content left behind under the old multi-segment path.
    assert!(!layout.remotes_dir().join("team").exists());

    let moved_marker = layout.git_state_dir().join("b/marker.txt");
    assert!(moved_marker.exists(), "bridge state must move to 'b'");
    // The now-empty `team/` parent under git state must be pruned too.
    assert!(!layout.git_state_dir().join("team").exists());
}

#[test]
fn remote_rename_multi_to_multi_segment_moves_refs_and_bridge_state() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "team/upstream", "main", &tip).unwrap();
    plant_bridge_state(&layout, "team/upstream");

    r.ok(&["remote", "add", "team/upstream", "mkit+file:///tmp/nowhere"]);
    let out = r.ok(&["remote", "rename", "team/upstream", "archive/upstream"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("could not move"),
        "multi->multi-segment rename must not degrade: {stderr}"
    );

    assert!(
        refs::read_remote_ref(&layout, "archive/upstream", "main")
            .unwrap()
            .is_some(),
        "rename must move tracking refs to the new nested destination"
    );
    assert!(
        refs::read_remote_ref(&layout, "team/upstream", "main")
            .unwrap()
            .is_none()
    );

    let moved_marker = layout.git_state_dir().join("archive/upstream/marker.txt");
    assert!(
        moved_marker.exists(),
        "bridge state must move to archive/upstream"
    );
    assert!(!layout.remotes_dir().join("team").exists());
    assert!(!layout.git_state_dir().join("team").exists());
}

#[test]
fn rename_into_own_subtree_moves_state() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    plant_bridge_state(&layout, "a");

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    let out = r.ok(&["remote", "rename", "a", "a/sub"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("could not move"),
        "rename into own subtree must not degrade: {stderr}"
    );

    assert!(
        refs::read_remote_ref(&layout, "a/sub", "main")
            .unwrap()
            .is_some(),
        "rename must move tracking refs into the subtree destination"
    );

    let moved_marker = layout.git_state_dir().join("a/sub/marker.txt");
    assert!(
        moved_marker.exists(),
        "bridge state must move into the subtree destination"
    );
    assert_eq!(std::fs::read(&moved_marker).unwrap(), b"bridge state\n");

    // The `a` level now contains only `sub/` — no stray files directly
    // under the old locations.
    let refs_a_entries: Vec<_> = std::fs::read_dir(layout.remotes_dir().join("a"))
        .unwrap()
        .map(|e| e.unwrap().file_name())
        .collect();
    assert_eq!(refs_a_entries, vec![std::ffi::OsString::from("sub")]);
    let state_a_entries: Vec<_> = std::fs::read_dir(layout.git_state_dir().join("a"))
        .unwrap()
        .map(|e| e.unwrap().file_name())
        .collect();
    assert_eq!(state_a_entries, vec![std::ffi::OsString::from("sub")]);
}

#[test]
fn rename_out_of_own_subtree_moves_state() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a/sub", "main", &tip).unwrap();
    plant_bridge_state(&layout, "a/sub");

    r.ok(&["remote", "add", "a/sub", "mkit+file:///tmp/nowhere"]);
    let out = r.ok(&["remote", "rename", "a/sub", "a"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("could not move"),
        "rename out of own subtree must not degrade: {stderr}"
    );

    assert!(
        refs::read_remote_ref(&layout, "a", "main")
            .unwrap()
            .is_some(),
        "rename must move tracking refs to the flat destination"
    );
    // No remnant of the old nesting under either state root.
    assert!(!layout.remotes_dir().join("a/sub").exists());
    assert!(!layout.git_state_dir().join("a/sub").exists());

    let moved_marker = layout.git_state_dir().join("a/marker.txt");
    assert!(moved_marker.exists(), "bridge state must move to 'a'");
    assert_eq!(std::fs::read(&moved_marker).unwrap(), b"bridge state\n");
}

#[test]
fn rename_out_of_deep_nesting_prunes_parents() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "x/y/z", "main", &tip).unwrap();
    plant_bridge_state(&layout, "x/y/z");

    r.ok(&["remote", "add", "x/y/z", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "rename", "x/y/z", "flat"]);

    assert!(
        refs::read_remote_ref(&layout, "flat", "main")
            .unwrap()
            .is_some(),
        "rename must move tracking refs to the flat destination"
    );
    // The whole emptied `x/y/z` chain must be pruned, including the
    // top-level `x` directory.
    assert!(!layout.remotes_dir().join("x").exists());
    assert!(!layout.git_state_dir().join("x").exists());

    let moved_marker = layout.git_state_dir().join("flat/marker.txt");
    assert!(moved_marker.exists(), "bridge state must move to 'flat'");
}

#[test]
fn failed_rename_restores_source_state() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "orig", "main", &tip).unwrap();
    plant_bridge_state(&layout, "orig");
    r.ok(&["remote", "add", "orig", "mkit+file:///tmp/nowhere"]);

    // A non-empty orphaned state dir at the destination, with no config
    // entry — exactly what `remote remove` leaves behind for bridge
    // state (see `warn_orphaned_bridge_state`). Its non-emptiness makes
    // the final rename into it fail (ENOTEMPTY-ish).
    let taken_state = layout.git_state_dir().join("taken");
    std::fs::create_dir_all(&taken_state).unwrap();
    std::fs::write(taken_state.join("occupied.txt"), b"pre-existing\n").unwrap();

    let out = r.ok(&["remote", "rename", "orig", "taken"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("could not move git-bridge state"),
        "expected a warning for the failed bridge-state move: {stderr}"
    );

    // Restore contract: orig's bridge state is back/intact at its
    // original location, not stranded in a temp dir.
    let restored_marker = layout.git_state_dir().join("orig/marker.txt");
    assert!(
        restored_marker.exists(),
        "bridge state must be restored to 'orig' after a failed move"
    );
    assert_eq!(std::fs::read(&restored_marker).unwrap(), b"bridge state\n");
    // The pre-existing occupant at the destination is untouched.
    assert!(taken_state.join("occupied.txt").exists());
    // No `.rename.tmp.*` temp dir left under the state root.
    let stray_temp = std::fs::read_dir(layout.git_state_dir())
        .unwrap()
        .filter_map(std::result::Result::ok)
        .any(|e| e.file_name().to_string_lossy().starts_with(".rename.tmp."));
    assert!(!stray_temp, "no temp dir should remain after a failed move");
}

/// Plants a `.rename.tmp.<pid>.0`-shaped orphan directly under
/// `refs/remotes/` — exactly the crash debris `rename_state_dir` can
/// leave behind between its two renames — and confirms both native ref
/// listing enumerators treat it as inert: `show-ref` and `for-each-ref`
/// never surface a phantom `refs/remotes/.rename.tmp.../...` ref or
/// remote. The companion bridge-side assertion (zero-arg bridge-state
/// resolution via `state_names`/`resolve_state` ignoring the same
/// shape planted under `.mkit/git/`) lives in
/// `git_tools::tests::state_names_and_resolve_state_skip_dot_leading_orphans`
/// (feature `git-bridge`), since those functions only exist under that
/// feature. This is the test the PR #659 review's finding 1 called out
/// as missing: before the dot-leading-segment rejection in
/// `validate_ref_name`, this orphan was a fully populated, listable ref
/// namespace, not the harmless empty-directory debris the old docs
/// claimed.
#[test]
fn orphaned_rename_temp_dir_is_inert_in_listings() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    plant_tracking_ref(&r, "orig", "main");

    // Crash debris under `refs/remotes/`: a dot-leading dir with a real
    // ref file inside, just like a crash between `rename_state_dir`'s
    // two renames would leave.
    let ref_orphan = layout.remotes_dir().join(".rename.tmp.99999.0");
    std::fs::create_dir_all(&ref_orphan).unwrap();
    std::fs::write(ref_orphan.join("main"), b"not a real ref, never read\n").unwrap();

    let out = r.ok(&["show-ref"]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("refs/remotes/orig/main"),
        "show-ref must still list the legitimate tracking ref: {stdout}"
    );
    assert!(
        !stdout.contains(".rename.tmp"),
        "show-ref must not surface the dot-leading orphan as a ref or remote: {stdout}"
    );

    let out = r.ok(&["for-each-ref"]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("refs/remotes/orig/main"),
        "for-each-ref must still list the legitimate tracking ref: {stdout}"
    );
    assert!(
        !stdout.contains(".rename.tmp"),
        "for-each-ref must not surface the dot-leading orphan: {stdout}"
    );
}

#[test]
fn prefix_nested_remotes_coexist() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "add", "a/b", "mkit+file:///tmp/nowhere-b"]);

    let out = r.ok(&["remote"]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains('a'), "listing: {stdout}");
    assert!(stdout.contains("a/b"), "listing: {stdout}");

    r.ok(&["remote", "remove", "a"]);

    let out = r.ok(&["remote"]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("a/b"),
        "a/b must survive removal of unrelated remote 'a': {stdout}"
    );
    let out = r.ok(&["remote", "get-url", "a/b"]);
    assert_eq!(
        String::from_utf8_lossy(&out.stdout).trim(),
        "mkit+file:///tmp/nowhere-b",
        "a/b's config entry must remain intact"
    );
}

/// #660: `remote remove a` must not delete the tracking refs of a
/// configured sibling `a/b` nested under it — the directory-keyed
/// layout means `a/b`'s refs live under `refs/remotes/a/b/`, inside
/// `a`'s own directory prefix, but they belong to a different remote.
/// This is git parity: `git remote remove a` preserves `refs/remotes/a/b/*`
/// too.
#[test]
fn remove_prefix_remote_preserves_nested_sibling() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    refs::write_remote_ref(&layout, "a/b", "main", &tip).unwrap();

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "add", "a/b", "mkit+file:///tmp/nowhere-b"]);

    let out = r.ok(&["remote", "remove", "a"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("warning"),
        "the sibling-aware selective removal must not degrade: {stderr}"
    );

    assert!(
        refs::read_remote_ref(&layout, "a", "main")
            .unwrap()
            .is_none(),
        "a's own tracking ref must be gone"
    );
    assert!(
        refs::read_remote_ref(&layout, "a/b", "main")
            .unwrap()
            .is_some(),
        "a/b's tracking ref must survive removal of 'a'"
    );

    let out = r.ok(&["remote"]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.lines().any(|l| l == "a/b"),
        "a/b must still be listed: {stdout}"
    );
    assert!(
        !stdout.lines().any(|l| l == "a"),
        "'a' itself must be gone: {stdout}"
    );
}

/// #660: `remote rename a x` must not drag a configured sibling `a/b`'s
/// refs or bridge state along to `x/b` — `a/b`'s state must stay
/// exactly where it is, and its config entry (still `a/b` -> its own
/// URL) is untouched throughout. This is stricter than git (git 2.50.1
/// has the same drag bug on rename), justified because the
/// directory-keyed layout needs it to make nested remote names safe.
#[test]
fn rename_prefix_remote_preserves_nested_sibling() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    refs::write_remote_ref(&layout, "a/b", "main", &tip).unwrap();
    plant_bridge_state(&layout, "a");
    plant_bridge_state(&layout, "a/b");

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "add", "a/b", "mkit+file:///tmp/nowhere-b"]);

    let out = r.ok(&["remote", "rename", "a", "x"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("could not move"),
        "sibling-aware rename must not degrade: {stderr}"
    );

    // `x`'s own refs moved into place; `a`'s own refs are gone.
    assert!(
        refs::read_remote_ref(&layout, "x", "main")
            .unwrap()
            .is_some(),
        "rename must move x's own tracking refs"
    );
    assert!(
        refs::read_remote_ref(&layout, "a", "main")
            .unwrap()
            .is_none()
    );

    // `a/b`'s refs are untouched, STILL resolving at the old prefix.
    assert!(
        refs::read_remote_ref(&layout, "a/b", "main")
            .unwrap()
            .is_some(),
        "a/b's tracking ref must remain at a/b, not move with the rename of 'a'"
    );

    // Bridge state: x's marker moved; a/b's marker untouched in place.
    let x_marker = layout.git_state_dir().join("x/marker.txt");
    assert!(x_marker.exists(), "x's bridge state must move");
    assert_eq!(std::fs::read(&x_marker).unwrap(), b"bridge state\n");
    let ab_marker = layout.git_state_dir().join("a/b/marker.txt");
    assert!(
        ab_marker.exists(),
        "a/b's bridge state must remain at .mkit/git/a/b/, untouched"
    );
    assert_eq!(std::fs::read(&ab_marker).unwrap(), b"bridge state\n");

    // a/b's config entry is unaffected by the rename of 'a'.
    let out = r.ok(&["remote", "get-url", "a/b"]);
    assert_eq!(
        String::from_utf8_lossy(&out.stdout).trim(),
        "mkit+file:///tmp/nowhere-b",
        "a/b's config entry must remain intact"
    );
}

/// #660: exercises the ancestor-recursion arm of `walk_unprotected` —
/// the sibling nests two levels down (`a/b/c`), so the walker must
/// recurse through the intermediate `b` directory rather than treating
/// it as removable whole.
#[test]
fn deeply_nested_sibling_survives() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    refs::write_remote_ref(&layout, "a/b/c", "main", &tip).unwrap();

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "add", "a/b/c", "mkit+file:///tmp/nowhere-c"]);

    r.ok(&["remote", "remove", "a"]);

    assert!(
        refs::read_remote_ref(&layout, "a", "main")
            .unwrap()
            .is_none()
    );
    assert!(
        refs::read_remote_ref(&layout, "a/b/c", "main")
            .unwrap()
            .is_some(),
        "deeply nested sibling a/b/c must survive removal of 'a'"
    );
}

/// #789 review finding 1 (blocking): the exact repro that broke the old
/// per-entry selective move. Remote `a` has both an ordinary branch
/// (`main`) and a multi-segment branch `b/main`, so `refs/remotes/a/b/`
/// exists as an ordinary, *unprotected* branch-namespace directory — one
/// that collides with the destination component when `a` is renamed into
/// `a/b`. A configured sibling `a/x` forces the selective (non-fast)
/// path. The old per-entry `fs::rename` hit EINVAL here: `a`'s own `b`
/// entry got renamed straight onto `refs/remotes/a/b`, asking the OS to
/// move a directory into its own subtree. The temp-sibling two-phase
/// move sidesteps this structurally — every unprotected entry (including
/// `b`) is extracted into a temp dir first, so `root/a/b` is free by the
/// time the one final rename runs — and the sibling `a/x` (refs + bridge
/// state) must come through completely untouched.
#[test]
fn rename_into_own_subtree_with_sibling_present() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    // Remote `a`: an ordinary branch...
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    // ...and a multi-segment branch `b/main`, giving `a` its own
    // unprotected `b` entry under `refs/remotes/a/`.
    refs::write_remote_ref(&layout, "a", "b/main", &tip).unwrap();
    // Configured sibling `a/x`, nested under `a`, forcing the selective
    // path.
    refs::write_remote_ref(&layout, "a/x", "main", &tip).unwrap();
    plant_bridge_state(&layout, "a/x");

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "add", "a/x", "mkit+file:///tmp/nowhere-x"]);

    let out = r.ok(&["remote", "rename", "a", "a/b"]);
    assert_eq!(
        out.status.code(),
        Some(0),
        "rename must succeed, not EINVAL: {out:?}"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.is_empty(), "expected zero warnings: {stderr}");

    // `a/b`'s refs resolve to old `a`'s hashes.
    assert_eq!(
        refs::read_remote_ref(&layout, "a/b", "main").unwrap(),
        Some(tip),
        "a/b/main must resolve to old a/main"
    );
    assert_eq!(
        refs::read_remote_ref(&layout, "a/b", "b/main").unwrap(),
        Some(tip),
        "a/b/b/main must resolve to old a/b/main"
    );

    // Sibling `a/x`'s refs and bridge state are untouched throughout.
    assert_eq!(
        refs::read_remote_ref(&layout, "a/x", "main").unwrap(),
        Some(tip),
        "a/x's tracking ref must survive the rename of 'a'"
    );
    assert!(
        layout.git_state_dir().join("a/x/marker.txt").exists(),
        "a/x's bridge state must remain untouched"
    );
}

/// #789 review finding 2 (blocking): with a sibling present (forcing the
/// selective path), an occupied destination must fail closed with the
/// same restore contract the fast path (`rename_state_dir`) already has
/// — not merge into the occupant, and not strand state in the temp
/// directory.
#[test]
fn selective_move_restores_on_occupied_destination() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    refs::write_remote_ref(&layout, "a/x", "main", &tip).unwrap();
    plant_bridge_state(&layout, "a/x");

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "add", "a/x", "mkit+file:///tmp/nowhere-x"]);

    // A non-empty orphan directory already sitting at the destination —
    // no config entry, just like the bridge-state orphans
    // `warn_orphaned_bridge_state` deliberately leaves behind — makes the
    // final rename fail (ENOTEMPTY-ish).
    let taken = layout.remotes_dir().join("taken");
    std::fs::create_dir_all(&taken).unwrap();
    std::fs::write(taken.join("occupied.txt"), b"pre-existing\n").unwrap();

    let out = r.ok(&["remote", "rename", "a", "taken"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("could not move tracking refs"),
        "expected a warning for the failed selective move: {stderr}"
    );

    // Source state fully restored: `a`'s own ref resolves at the old
    // name, and the sibling was never touched in the first place.
    assert_eq!(
        refs::read_remote_ref(&layout, "a", "main").unwrap(),
        Some(tip),
        "a's tracking ref must be restored after a failed move"
    );
    assert_eq!(
        refs::read_remote_ref(&layout, "a/x", "main").unwrap(),
        Some(tip),
        "a/x's tracking ref must be unaffected by the failed move"
    );
    assert!(
        layout.git_state_dir().join("a/x/marker.txt").exists(),
        "a/x's bridge state must be unaffected by the failed move"
    );

    // The pre-existing occupant at the destination is untouched.
    assert!(taken.join("occupied.txt").exists());

    // No `.rename.tmp.*` debris left under the root.
    let stray_temp = std::fs::read_dir(layout.remotes_dir())
        .unwrap()
        .filter_map(std::result::Result::ok)
        .any(|e| e.file_name().to_string_lossy().starts_with(".rename.tmp."));
    assert!(!stray_temp, "no temp dir should remain after a failed move");
}

/// #789 review finding 2 (blocking): exercises the move closure's
/// relative-path composition end-to-end when the sibling nests more than
/// one level down (`a/b/c`, not a direct child of `a`) — the walker must
/// recurse through the intermediate `b` directory, and the moved entries
/// must land at the correct relative depth under the temp dir and then
/// under the destination.
#[test]
fn deeply_nested_sibling_survives_rename() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    refs::write_remote_ref(&layout, "a/b/c", "main", &tip).unwrap();
    plant_bridge_state(&layout, "a/b/c");

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "add", "a/b/c", "mkit+file:///tmp/nowhere-c"]);

    let out = r.ok(&["remote", "rename", "a", "x"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("could not move"),
        "unexpected warning: {stderr}"
    );

    assert_eq!(
        refs::read_remote_ref(&layout, "x", "main").unwrap(),
        Some(tip),
        "x's tracking ref must move"
    );
    assert_eq!(
        refs::read_remote_ref(&layout, "a", "main").unwrap(),
        None,
        "old name 'a' must be gone"
    );
    assert_eq!(
        refs::read_remote_ref(&layout, "a/b/c", "main").unwrap(),
        Some(tip),
        "deeply nested sibling a/b/c's refs must stay exactly where they are"
    );
    assert!(
        layout.git_state_dir().join("a/b/c/marker.txt").exists(),
        "deeply nested sibling a/b/c's bridge state must stay exactly where it is"
    );

    // No stray debris left under either root.
    for root in [layout.remotes_dir(), layout.git_state_dir()] {
        if let Ok(entries) = std::fs::read_dir(&root) {
            let stray = entries
                .filter_map(std::result::Result::ok)
                .any(|e| e.file_name().to_string_lossy().starts_with(".rename.tmp."));
            assert!(!stray, "no temp dir should remain under {}", root.display());
        }
    }
}

/// #789 review finding 4: exercises `merge_tree_into`'s recursive arm
/// during a *restore* — not just the ordinary extraction path the other
/// sibling tests above already cover. Sibling `a/b/c` is configured, so
/// `a/b` is a retained ancestor directory that survives extraction (it
/// still holds `c/`). Remote `a` also has a branch namespace `b/main`,
/// so extraction pulls an ordinary, unprotected `refs/remotes/a/b/main`
/// out from underneath that same retained ancestor and into
/// `tmp/b/main`. An occupied destination forces the phase-4 failure, so
/// the restore has to merge `tmp/b/main` back into `src/b/`, which still
/// exists (holding `c/`) — exactly the "recurse into a like-named
/// directory that already exists at the destination" arm
/// `merge_tree_into` carries for this reason.
#[test]
fn selective_move_restore_recurses_into_retained_ancestors() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    // Unprotected content nested under the retained ancestor `a/b`.
    refs::write_remote_ref(&layout, "a", "b/main", &tip).unwrap();
    // Sibling two levels down forces `a/b` to be recursed into (as an
    // ancestor of the protected root) rather than moved/removed whole.
    refs::write_remote_ref(&layout, "a/b/c", "main", &tip).unwrap();

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "add", "a/b/c", "mkit+file:///tmp/nowhere-c"]);

    // Occupied, non-empty destination forces the final rename (phase 4)
    // to fail, driving the restore path.
    let taken = layout.remotes_dir().join("taken");
    std::fs::create_dir_all(&taken).unwrap();
    std::fs::write(taken.join("occupied.txt"), b"pre-existing\n").unwrap();

    let out = r.ok(&["remote", "rename", "a", "taken"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("could not move tracking refs"),
        "expected a warning for the failed selective move: {stderr}"
    );

    // Full restore: both of `a`'s own refs resolve back at their
    // original paths, including the one nested under the retained
    // ancestor `a/b`.
    assert_eq!(
        refs::read_remote_ref(&layout, "a", "main").unwrap(),
        Some(tip),
        "a's own tracking ref must be restored"
    );
    assert_eq!(
        refs::read_remote_ref(&layout, "a", "b/main").unwrap(),
        Some(tip),
        "a's branch-namespace ref nested under the retained ancestor a/b \
         must be restored via merge_tree_into's recursive arm"
    );
    // Sibling untouched throughout.
    assert_eq!(
        refs::read_remote_ref(&layout, "a/b/c", "main").unwrap(),
        Some(tip),
        "sibling a/b/c must be unaffected by the failed move"
    );
    // The pre-existing occupant at the destination is untouched.
    assert!(taken.join("occupied.txt").exists());
    // No `.rename.tmp.*` debris left under the root.
    let stray_temp = std::fs::read_dir(layout.remotes_dir())
        .unwrap()
        .filter_map(std::result::Result::ok)
        .any(|e| e.file_name().to_string_lossy().starts_with(".rename.tmp."));
    assert!(!stray_temp, "no temp dir should remain after a failed move");
}

/// #789 review finding 3 (should-fix, minimum bar): documents and pins
/// the destination-side nesting boundary that `move_state_dir`'s
/// `protected` set does not cover — a configured sibling nesting under
/// the DESTINATION of a rename, rather than under `old`'s own directory
/// prefix. Remotes `a` and `a/x` (sibling nested under `a`); `rename a
/// a/b` succeeds first (`a` is `old`, so `a/x` is correctly protected
/// and left in place, landing the result at `a/b` with the sibling still
/// at `a/x`). The round trip `rename a/b a` computes `protected` from
/// `a/b` (`old`), which has no nested siblings of its own — `a/x` nests
/// under `a` (`new`), invisible to that computation — so the move takes
/// the ordinary fast path and lands on the now-occupied `a/` directory
/// (still holding `x/`), failing closed via the same restore contract
/// rather than merging into the sibling or dragging it along. This is
/// the documented boundary of what nesting handles (see
/// `move_state_dir`'s doc).
#[test]
fn rename_round_trip_into_sibling_fails_closed() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "a", "main", &tip).unwrap();
    refs::write_remote_ref(&layout, "a/x", "main", &tip).unwrap();

    r.ok(&["remote", "add", "a", "mkit+file:///tmp/nowhere"]);
    r.ok(&["remote", "add", "a/x", "mkit+file:///tmp/nowhere-x"]);

    // First leg: `a` -> `a/b`. `a/x` is a sibling of `old` ("a"), so it
    // is protected and this succeeds cleanly.
    let out = r.ok(&["remote", "rename", "a", "a/b"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.contains("could not move"),
        "first rename must not degrade: {stderr}"
    );
    assert_eq!(
        refs::read_remote_ref(&layout, "a/b", "main").unwrap(),
        Some(tip)
    );
    assert_eq!(
        refs::read_remote_ref(&layout, "a/x", "main").unwrap(),
        Some(tip),
        "sibling a/x must survive the first rename"
    );

    // Second leg (the round trip): `a/b` -> `a`. `a/x` nests under `a`
    // (the DESTINATION), not under `a/b` (`old`), so it is invisible to
    // `nested_sibling_names(remotes, "a/b")` and the move takes the
    // ordinary fast path — landing on the now-occupied `a/` directory
    // (still holding `x/`) and failing closed.
    let out = r.ok(&["remote", "rename", "a/b", "a"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("could not move tracking refs"),
        "expected the fail-closed warning: {stderr}"
    );
    assert_eq!(
        out.status.code(),
        Some(0),
        "warn-only contract: exit stays 0 even though the round trip degrades: {out:?}"
    );

    // Fail-closed = nothing moved, nothing lost: a/b's refs remain
    // resolvable at their pre-round-trip path.
    assert_eq!(
        refs::read_remote_ref(&layout, "a/b", "main").unwrap(),
        Some(tip),
        "a/b's tracking ref must remain resolvable at a/b after the failed round trip"
    );
    // The sibling a/x is untouched throughout.
    assert_eq!(
        refs::read_remote_ref(&layout, "a/x", "main").unwrap(),
        Some(tip),
        "sibling a/x must be untouched by the failed round trip"
    );
    // No temp debris left behind.
    let stray_temp = std::fs::read_dir(layout.remotes_dir())
        .unwrap()
        .filter_map(std::result::Result::ok)
        .any(|e| e.file_name().to_string_lossy().starts_with(".rename.tmp."));
    assert!(
        !stray_temp,
        "no temp dir should remain after the failed round trip"
    );
}

/// #660 regression guard: with no configured sibling nested under the
/// target, `move_state_dir`'s selective path is never invoked
/// (`nested_sibling_names` returns empty, so `protected` is empty) — the
/// pre-existing whole-directory fast paths (`remove_dir_all`,
/// `move_state_dir`'s whole-directory rename) still run unchanged and
/// still fully clean up.
#[test]
fn no_sibling_fast_path_unchanged() {
    let r = Repo::new();
    r.commit_file("a.txt", b"a\n", "base");
    let layout = RepoLayout::single(r.path());
    let tip = refs::read_ref(&layout, "main").unwrap().unwrap();
    refs::write_remote_ref(&layout, "team/upstream", "main", &tip).unwrap();
    plant_bridge_state(&layout, "team/upstream");
    r.ok(&["remote", "add", "team/upstream", "mkit+file:///tmp/nowhere"]);

    r.ok(&["remote", "remove", "team/upstream"]);

    assert!(
        refs::read_remote_ref(&layout, "team/upstream", "main")
            .unwrap()
            .is_none(),
        "tracking refs must be fully removed with no sibling present"
    );
    assert!(
        !layout.remotes_dir().join("team/upstream").exists(),
        "no leftover tracking-ref directory for the removed remote"
    );
    // `remote remove` deliberately leaves bridge state in place
    // (`warn_orphaned_bridge_state`) regardless of siblings — unaffected
    // by #660.
    assert!(
        layout
            .git_state_dir()
            .join("team/upstream/marker.txt")
            .exists()
    );
}

#[test]
fn named_remote_fetch_and_pull_use_their_namespace() {
    // Origin repo with one commit, exposed over mkit+file://.
    let origin = Repo::new();
    origin.commit_file("a.txt", b"a\n", "origin base");
    let origin_store = origin.path().join("store");
    std::fs::create_dir_all(&origin_store).unwrap();
    let url = format!("mkit+file://{}", origin_store.display());
    origin.ok(&["remote", "add", &url]);
    origin.ok(&["push", "--all"]);

    // Consumer adds it as a NAMED remote and fetches.
    let consumer = Repo::new();
    consumer.commit_file("local.txt", b"l\n", "local base");
    consumer.ok(&["remote", "add", "origin", &url]);
    let out = consumer.ok(&["fetch", "origin"]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    // git-shaped: `From <url>` + a per-ref summary line for the new branch.
    assert!(stderr.contains("From "), "fetch: {stderr}");
    assert!(stderr.contains("origin/main"), "fetch summary: {stderr}");
    assert!(
        refs::read_remote_ref(&RepoLayout::single(consumer.path()), "origin", "main")
            .unwrap()
            .is_some(),
        "named fetch must write refs/remotes/origin/*"
    );
    // Unknown name errors cleanly.
    let out = consumer.run(&["fetch", "nope"]);
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("unknown remote 'nope'"));
}