git-loom 0.18.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
use git2::Oid;

use super::*;

// ── Helper: create test OIDs ────────────────────────────────────────────

fn oid(hex: &str) -> Oid {
    // Pad to 40 chars with zeros (hex must be valid hex chars)
    let padded = format!("{:0<40}", hex);
    Oid::from_str(&padded).unwrap()
}

fn make_commit(hex: &str, message: &str) -> CommitEntry {
    CommitEntry {
        oid: oid(hex),
        short_hash: hex[..7.min(hex.len())].to_string(),
        message: message.to_string(),
        command: Command::Pick,
        update_refs: Vec::new(),
    }
}

fn make_commit_with_refs(hex: &str, message: &str, refs: Vec<&str>) -> CommitEntry {
    CommitEntry {
        oid: oid(hex),
        short_hash: hex[..7.min(hex.len())].to_string(),
        message: message.to_string(),
        command: Command::Pick,
        update_refs: refs.into_iter().map(String::from).collect(),
    }
}

// Use valid hex strings for test OIDs
const BASE: &str = "ba5e000";
const OID_A1: &str = "abc1234";
const OID_A2: &str = "def5678";
const OID_B1: &str = "bbb2222";
const OID_INT: &str = "1111111";
const OID_C1: &str = "ccc3333";
const OID_C2: &str = "ddd4444";
const OID_MERGE1: &str = "9999999";
const OID_MERGE2: &str = "8888888";
const OID_FIX: &str = "eee5555";

// ── Serialization tests ─────────────────────────────────────────────────

#[test]
fn serialize_single_branch_section() {
    let graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1"), make_commit(OID_A2, "A2")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
        }],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_INT, "Int")),
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE1)),
                label: "feature-a".to_string(),
            },
        ],
    };

    let todo = graph.to_todo();
    let lines: Vec<&str> = todo.lines().collect();

    assert_eq!(lines[0], "label onto");
    assert_eq!(lines[1], "");
    assert_eq!(lines[2], "reset onto");
    assert_eq!(lines[3], &format!("pick {} # A1", OID_A1));
    assert_eq!(lines[4], &format!("pick {} # A2", OID_A2));
    assert_eq!(lines[5], "label feature-a");
    assert_eq!(lines[6], "update-ref refs/heads/feature-a");
    assert_eq!(lines[7], "");
    assert_eq!(lines[8], "reset onto");
    assert_eq!(lines[9], &format!("pick {} # Int", OID_INT));
    assert!(lines[10].starts_with(&format!("merge -C {} feature-a", OID_MERGE1)));
}

#[test]
fn serialize_two_branch_sections() {
    let graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![
            BranchSection {
                reset_target: "onto".to_string(),
                commits: vec![make_commit(OID_A1, "A1")],
                label: "feature-a".to_string(),
                branch_names: vec!["feature-a".to_string()],
            },
            BranchSection {
                reset_target: "onto".to_string(),
                commits: vec![make_commit(OID_B1, "B1")],
                label: "feature-b".to_string(),
                branch_names: vec!["feature-b".to_string()],
            },
        ],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_INT, "Int")),
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE1)),
                label: "feature-a".to_string(),
            },
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE2)),
                label: "feature-b".to_string(),
            },
        ],
    };

    let todo = graph.to_todo();
    assert!(todo.contains("label feature-a\n"));
    assert!(todo.contains("label feature-b\n"));
    assert!(todo.contains(&format!("merge -C {} feature-a", OID_MERGE1)));
    assert!(todo.contains(&format!("merge -C {} feature-b", OID_MERGE2)));
}

#[test]
fn serialize_new_merge_without_oid() {
    let graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
        }],
        integration_line: vec![IntegrationEntry::Merge {
            original_oid: None,
            label: "feature-a".to_string(),
        }],
    };

    let todo = graph.to_todo();
    assert!(todo.contains("merge feature-a # Merge branch 'feature-a'"));
}

#[test]
fn serialize_colocated_branches() {
    let graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string(), "feature-b".to_string()],
        }],
        integration_line: vec![IntegrationEntry::Merge {
            original_oid: Some(oid(OID_MERGE1)),
            label: "feature-a".to_string(),
        }],
    };

    let todo = graph.to_todo();
    assert!(todo.contains("update-ref refs/heads/feature-a\n"));
    assert!(todo.contains("update-ref refs/heads/feature-b\n"));
}

#[test]
fn serialize_update_refs_on_integration_line() {
    let graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![],
        integration_line: vec![IntegrationEntry::Pick(make_commit_with_refs(
            OID_C1,
            "C1",
            vec!["non-woven"],
        ))],
    };

    let todo = graph.to_todo();
    assert!(todo.contains(&format!("pick {} # C1\n", OID_C1)));
    assert!(todo.contains("update-ref refs/heads/non-woven\n"));
}

#[test]
fn serialize_empty_graph() {
    let graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![],
        integration_line: vec![],
    };

    let todo = graph.to_todo();
    assert_eq!(todo, "label onto\n\nreset onto\n");
}

// ── Mutation tests ──────────────────────────────────────────────────────

#[test]
fn drop_commit_from_branch_section() {
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1"), make_commit(OID_A2, "A2")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
        }],
        integration_line: vec![IntegrationEntry::Merge {
            original_oid: Some(oid(OID_MERGE1)),
            label: "feature-a".to_string(),
        }],
    };

    graph.drop_commit(oid(OID_A1));

    assert_eq!(graph.branch_sections.len(), 1);
    assert_eq!(graph.branch_sections[0].commits.len(), 1);
    assert_eq!(graph.branch_sections[0].commits[0].message, "A2");
}

#[test]
fn drop_last_commit_removes_section_and_merge() {
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
        }],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_INT, "Int")),
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE1)),
                label: "feature-a".to_string(),
            },
        ],
    };

    graph.drop_commit(oid(OID_A1));

    assert!(graph.branch_sections.is_empty());
    assert_eq!(graph.integration_line.len(), 1); // Only "Int" pick remains
}

#[test]
fn drop_commit_from_integration_line() {
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_C1, "C1")),
            IntegrationEntry::Pick(make_commit(OID_C2, "C2")),
        ],
    };

    graph.drop_commit(oid(OID_C1));

    assert_eq!(graph.integration_line.len(), 1);
}

#[test]
fn drop_branch_removes_section_and_merge() {
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![
            BranchSection {
                reset_target: "onto".to_string(),
                commits: vec![make_commit(OID_A1, "A1")],
                label: "feature-a".to_string(),
                branch_names: vec!["feature-a".to_string()],
            },
            BranchSection {
                reset_target: "onto".to_string(),
                commits: vec![make_commit(OID_B1, "B1")],
                label: "feature-b".to_string(),
                branch_names: vec!["feature-b".to_string()],
            },
        ],
        integration_line: vec![
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE1)),
                label: "feature-a".to_string(),
            },
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE2)),
                label: "feature-b".to_string(),
            },
        ],
    };

    graph.drop_branch("feature-a");

    assert_eq!(graph.branch_sections.len(), 1);
    assert_eq!(graph.branch_sections[0].label, "feature-b");
    assert_eq!(graph.integration_line.len(), 1);
}

#[test]
fn move_commit_to_branch() {
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
        }],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_C1, "C1")),
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE1)),
                label: "feature-a".to_string(),
            },
        ],
    };

    graph.move_commit(oid(OID_C1), "feature-a").unwrap();

    // C1 should now be at the end of feature-a's section
    assert_eq!(graph.branch_sections[0].commits.len(), 2);
    assert_eq!(graph.branch_sections[0].commits[1].message, "C1");
    // C1 should be gone from integration line
    assert_eq!(graph.integration_line.len(), 1);
}

#[test]
fn move_commit_to_colocated_branch_splits_section() {
    // Setup: feature-a and feature-b are co-located (same section).
    // Moving a commit to feature-b should split the section so the commit
    // only appears on feature-b, not on feature-a.
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![
            BranchSection {
                reset_target: "onto".to_string(),
                commits: vec![make_commit(OID_A1, "A1")],
                label: "feature-a".to_string(),
                branch_names: vec!["feature-a".to_string(), "feature-b".to_string()],
            },
            BranchSection {
                reset_target: "onto".to_string(),
                commits: vec![make_commit(OID_B1, "B1"), make_commit(OID_C1, "C1")],
                label: "feature-c".to_string(),
                branch_names: vec!["feature-c".to_string()],
            },
        ],
        integration_line: vec![
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE1)),
                label: "feature-a".to_string(),
            },
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE2)),
                label: "feature-c".to_string(),
            },
        ],
    };

    graph.move_commit(oid(OID_C1), "feature-b").unwrap();

    // Should now have 3 sections: feature-a, feature-b (stacked on a), feature-c
    assert_eq!(graph.branch_sections.len(), 3);

    // feature-a keeps its original commits and only has feature-a in branch_names
    assert_eq!(graph.branch_sections[0].label, "feature-a");
    assert_eq!(graph.branch_sections[0].commits.len(), 1);
    assert_eq!(graph.branch_sections[0].commits[0].message, "A1");
    assert_eq!(
        graph.branch_sections[0].branch_names,
        vec!["feature-a".to_string()]
    );

    // feature-b is stacked on feature-a with the moved commit
    assert_eq!(graph.branch_sections[1].label, "feature-b");
    assert_eq!(graph.branch_sections[1].reset_target, "feature-a");
    assert_eq!(graph.branch_sections[1].commits.len(), 1);
    assert_eq!(graph.branch_sections[1].commits[0].message, "C1");
    assert_eq!(
        graph.branch_sections[1].branch_names,
        vec!["feature-b".to_string()]
    );

    // feature-c lost one commit
    assert_eq!(graph.branch_sections[2].label, "feature-c");
    assert_eq!(graph.branch_sections[2].commits.len(), 1);

    // The merge entry that was "feature-a" should now reference "feature-b" (outermost)
    if let IntegrationEntry::Merge { label, .. } = &graph.integration_line[0] {
        assert_eq!(label, "feature-b");
    } else {
        panic!("Expected Merge entry");
    }

    // Verify serialized todo: feature-b section resets to feature-a
    let todo = graph.to_todo();
    assert!(todo.contains("label feature-a\nupdate-ref refs/heads/feature-a\n"));
    assert!(todo.contains("reset feature-a\n"));
    assert!(todo.contains("label feature-b\nupdate-ref refs/heads/feature-b\n"));
}

#[test]
fn move_commit_to_colocated_branch_when_target_is_label() {
    // Setup: section label IS the target branch.
    // Moving a commit to the label branch should rename the base section to
    // a remaining branch and create a stacked section for the target.
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string(), "feature-b".to_string()],
        }],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_C1, "C1")),
            IntegrationEntry::Merge {
                original_oid: Some(oid(OID_MERGE1)),
                label: "feature-a".to_string(),
            },
        ],
    };

    graph.move_commit(oid(OID_C1), "feature-a").unwrap();

    // Should have 2 sections now
    assert_eq!(graph.branch_sections.len(), 2);

    // Base section is renamed to feature-b
    assert_eq!(graph.branch_sections[0].label, "feature-b");
    assert_eq!(
        graph.branch_sections[0].branch_names,
        vec!["feature-b".to_string()]
    );

    // Stacked section for feature-a
    assert_eq!(graph.branch_sections[1].label, "feature-a");
    assert_eq!(graph.branch_sections[1].reset_target, "feature-b");
    assert_eq!(graph.branch_sections[1].commits.len(), 1);
    assert_eq!(graph.branch_sections[1].commits[0].message, "C1");

    // C1 was removed from integration line, only the merge remains
    assert_eq!(graph.integration_line.len(), 1);

    // Merge entry should reference feature-a (the outermost)
    if let IntegrationEntry::Merge { label, .. } = &graph.integration_line[0] {
        assert_eq!(label, "feature-a");
    } else {
        panic!("Expected Merge entry");
    }
}

#[test]
fn fixup_commit_moves_and_changes_command() {
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_C1, "C1")),
            IntegrationEntry::Pick(make_commit(OID_C2, "C2")),
            IntegrationEntry::Pick(make_commit(OID_FIX, "Fixup for C1")),
        ],
    };

    graph.fixup_commit(oid(OID_FIX), oid(OID_C1)).unwrap();

    assert_eq!(graph.integration_line.len(), 3);

    // C1 at index 0, fixup at index 1, C2 at index 2
    if let IntegrationEntry::Pick(c) = &graph.integration_line[0] {
        assert_eq!(c.message, "C1");
    }
    if let IntegrationEntry::Pick(c) = &graph.integration_line[1] {
        assert_eq!(c.message, "Fixup for C1");
        assert_eq!(c.command, Command::Fixup);
    }
    if let IntegrationEntry::Pick(c) = &graph.integration_line[2] {
        assert_eq!(c.message, "C2");
    }
}

#[test]
fn move_commit_to_missing_section_errors() {
    let mut graph = Weave {
        base_oid: oid(BASE),
        branch_sections: vec![],
        integration_line: vec![IntegrationEntry::Pick(make_commit(OID_C1, "C1"))],
    };

    let result = graph.move_commit(oid(OID_C1), "nonexistent-branch");
    assert!(result.is_err());
    assert!(
        result.unwrap_err().to_string().contains("not found"),
        "should mention target not found"
    );

    // C1 should still be in the integration line (not lost)
    assert_eq!(graph.integration_line.len(), 1);
}

#[test]
fn fixup_commit_to_missing_target_errors() {
    let mut graph = Weave {
        base_oid: oid(BASE),
        branch_sections: vec![],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_C1, "C1")),
            IntegrationEntry::Pick(make_commit(OID_FIX, "Fixup")),
        ],
    };

    // Try to fixup to a non-existent target
    let result = graph.fixup_commit(oid(OID_FIX), oid(OID_C2));
    assert!(result.is_err());
    assert!(
        result.unwrap_err().to_string().contains("not found"),
        "should mention target not found"
    );

    // Both commits should still be in the graph (not lost)
    assert_eq!(graph.integration_line.len(), 2);
}

#[test]
fn edit_commit_changes_command() {
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![],
        integration_line: vec![IntegrationEntry::Pick(make_commit(OID_C1, "C1"))],
    };

    graph.edit_commit(oid(OID_C1));

    if let IntegrationEntry::Pick(c) = &graph.integration_line[0] {
        assert_eq!(c.command, Command::Edit);
    }
}

#[test]
fn add_branch_section_and_merge() {
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![],
        integration_line: vec![IntegrationEntry::Pick(make_commit(OID_C1, "C1"))],
    };

    graph.add_branch_section(
        "new-branch".to_string(),
        vec!["new-branch".to_string()],
        vec![make_commit(OID_B1, "N1")],
        "onto".to_string(),
    );

    graph.add_merge("new-branch".to_string(), None, None);

    assert_eq!(graph.branch_sections.len(), 1);
    assert_eq!(graph.branch_sections[0].label, "new-branch");
    assert_eq!(graph.integration_line.len(), 2);
}

#[test]
fn reassign_branch_renames_section() {
    let mut graph = Weave {
        base_oid: oid(BASE),

        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string(), "feature-b".to_string()],
        }],
        integration_line: vec![IntegrationEntry::Merge {
            original_oid: Some(oid(OID_MERGE1)),
            label: "feature-a".to_string(),
        }],
    };

    graph.reassign_branch("feature-a", "feature-b");

    assert_eq!(graph.branch_sections[0].label, "feature-b");
    assert!(
        !graph.branch_sections[0]
            .branch_names
            .contains(&"feature-a".to_string())
    );
    assert!(
        graph.branch_sections[0]
            .branch_names
            .contains(&"feature-b".to_string())
    );

    if let IntegrationEntry::Merge { label, .. } = &graph.integration_line[0] {
        assert_eq!(label, "feature-b");
    }
}

// ── Integration test: from_repo ─────────────────────────────────────────

#[test]
fn from_repo_linear_integration() {
    use crate::core::test_helpers::TestRepo;

    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("C1", "c1.txt");
    test_repo.commit("C2", "c2.txt");

    let graph = Weave::from_repo(&test_repo.repo).unwrap();

    assert!(graph.branch_sections.is_empty());
    assert_eq!(graph.integration_line.len(), 2);

    // Oldest first
    if let IntegrationEntry::Pick(c) = &graph.integration_line[0] {
        assert_eq!(c.message, "C1");
    } else {
        panic!("Expected Pick entry");
    }
    if let IntegrationEntry::Pick(c) = &graph.integration_line[1] {
        assert_eq!(c.message, "C2");
    } else {
        panic!("Expected Pick entry");
    }
}

#[test]
fn from_repo_with_woven_branch() {
    use crate::core::test_helpers::TestRepo;

    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feature-a at merge-base
    test_repo.create_branch_at("feature-a", &base_oid.to_string());

    // Switch to feature-a and add commits
    test_repo.switch_branch("feature-a");
    test_repo.commit("A1", "a1.txt");
    test_repo.commit("A2", "a2.txt");

    // Switch back to integration
    test_repo.switch_branch("integration");

    // Add a commit on integration before merging
    test_repo.commit("Int", "int.txt");

    // Merge feature-a
    test_repo.merge_no_ff("feature-a");

    let graph = Weave::from_repo(&test_repo.repo).unwrap();

    // Should have one branch section for feature-a
    assert_eq!(graph.branch_sections.len(), 1);
    assert_eq!(graph.branch_sections[0].label, "feature-a");
    assert_eq!(graph.branch_sections[0].commits.len(), 2);
    assert_eq!(graph.branch_sections[0].commits[0].message, "A1");
    assert_eq!(graph.branch_sections[0].commits[1].message, "A2");

    // Integration line should have Int + merge
    assert_eq!(graph.integration_line.len(), 2);
    if let IntegrationEntry::Pick(c) = &graph.integration_line[0] {
        assert_eq!(c.message, "Int");
    } else {
        panic!("Expected Pick entry for Int");
    }
    if let IntegrationEntry::Merge {
        label,
        original_oid,
    } = &graph.integration_line[1]
    {
        assert_eq!(label, "feature-a");
        assert!(original_oid.is_some());
    } else {
        panic!("Expected Merge entry for feature-a");
    }
}

#[test]
fn from_repo_with_non_woven_branch() {
    use crate::core::test_helpers::TestRepo;

    let test_repo = TestRepo::new_with_remote();

    // Add commits on integration
    test_repo.commit("C1", "c1.txt");
    let c1_oid = test_repo.head_oid();

    // Create feature-a at C1 (non-woven, just a branch pointing at a commit)
    test_repo.create_branch_at("feature-a", &c1_oid.to_string());

    test_repo.commit("C2", "c2.txt");

    let graph = Weave::from_repo(&test_repo.repo).unwrap();

    // No branch sections (not woven)
    assert!(graph.branch_sections.is_empty());

    // Integration line should have C1 with update-ref + C2
    assert_eq!(graph.integration_line.len(), 2);
    if let IntegrationEntry::Pick(c) = &graph.integration_line[0] {
        assert_eq!(c.message, "C1");
        assert!(c.update_refs.contains(&"feature-a".to_string()));
    } else {
        panic!("Expected Pick entry for C1");
    }
}

#[test]
fn from_repo_round_trip_preserves_identity() {
    use crate::core::test_helpers::TestRepo;

    let test_repo = TestRepo::new_with_remote();
    let workdir = test_repo.workdir();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Build a non-trivial graph
    test_repo.create_branch_at("feature-a", &base_oid.to_string());
    test_repo.switch_branch("feature-a");
    test_repo.commit("A1", "a1.txt");
    test_repo.switch_branch("integration");
    test_repo.commit("Int", "int.txt");
    test_repo.merge_no_ff("feature-a");

    // Record state before round-trip
    let messages_before: Vec<String> = {
        let info = repo::gather_repo_info(&test_repo.repo, false, 1).unwrap();
        info.commits.iter().map(|c| c.message.clone()).collect()
    };

    // Build graph, serialize, and run through rebase
    let graph = Weave::from_repo(&test_repo.repo).unwrap();
    let todo = graph.to_todo();

    // Pass the merge-base OID directly as upstream (not merge_base^)
    run_rebase(workdir.as_path(), Some(&graph.base_oid.to_string()), &todo).unwrap();

    // Verify identity: same commits after round-trip
    let messages_after: Vec<String> = {
        let info = repo::gather_repo_info(&test_repo.repo, false, 1).unwrap();
        info.commits.iter().map(|c| c.message.clone()).collect()
    };

    assert_eq!(messages_before, messages_after);
}

// ── drop_commit update_refs transfer tests ──────────────────────────────

#[test]
fn drop_commit_transfers_update_refs_to_adjacent() {
    let mut graph = Weave {
        base_oid: oid("aaa"),
        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
            commits: vec![
                make_commit("111", "C1"),
                make_commit_with_refs("222", "C2", vec!["non-woven-branch"]),
                make_commit("333", "C3"),
            ],
        }],
        integration_line: vec![IntegrationEntry::Merge {
            label: "feature-a".to_string(),
            original_oid: None,
        }],
    };

    graph.drop_commit(oid("222"));

    // update_refs should transfer to adjacent commit (C1, preceding)
    assert_eq!(graph.branch_sections[0].commits.len(), 2);
    assert!(
        graph.branch_sections[0].commits[0]
            .update_refs
            .contains(&"non-woven-branch".to_string()),
        "update_refs should transfer to preceding commit"
    );
}

#[test]
fn drop_commit_transfers_update_refs_to_next_when_first() {
    let mut graph = Weave {
        base_oid: oid("aaa"),
        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
            commits: vec![
                make_commit_with_refs("111", "C1", vec!["non-woven-branch"]),
                make_commit("222", "C2"),
            ],
        }],
        integration_line: vec![IntegrationEntry::Merge {
            label: "feature-a".to_string(),
            original_oid: None,
        }],
    };

    graph.drop_commit(oid("111"));

    assert_eq!(graph.branch_sections[0].commits.len(), 1);
    assert!(
        graph.branch_sections[0].commits[0]
            .update_refs
            .contains(&"non-woven-branch".to_string()),
        "update_refs should transfer to next commit when first is dropped"
    );
}

#[test]
fn drop_commit_on_integration_line_transfers_update_refs() {
    let mut graph = Weave {
        base_oid: oid("aaa"),
        branch_sections: vec![],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit("111", "C1")),
            IntegrationEntry::Pick(make_commit_with_refs("222", "C2", vec!["loose-branch"])),
            IntegrationEntry::Pick(make_commit("333", "C3")),
        ],
    };

    graph.drop_commit(oid("222"));

    // Should transfer to an adjacent Pick on the integration line
    let picks: Vec<&CommitEntry> = graph
        .integration_line
        .iter()
        .filter_map(|e| {
            if let IntegrationEntry::Pick(c) = e {
                Some(c)
            } else {
                None
            }
        })
        .collect();
    assert_eq!(picks.len(), 2);
    let has_ref = picks
        .iter()
        .any(|c| c.update_refs.contains(&"loose-branch".to_string()));
    assert!(
        has_ref,
        "update_refs should transfer to adjacent pick on integration line"
    );
}

// ── drop_branch update_refs preservation tests ──────────────────────────

#[test]
fn drop_branch_preserves_colocated_update_refs_at_boundary() {
    let mut graph = Weave {
        base_oid: oid("aaa"),
        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            label: "feat3".to_string(),
            branch_names: vec!["feat3".to_string()],
            commits: vec![
                make_commit_with_refs("111", "C1", vec!["feat1", "feat2"]),
                make_commit("222", "C2"),
            ],
        }],
        integration_line: vec![IntegrationEntry::Merge {
            label: "feat3".to_string(),
            original_oid: None,
        }],
    };

    graph.drop_branch("feat3");

    // feat1 should be the new section label (first ref found)
    assert_eq!(graph.branch_sections[0].label, "feat1");
    // feat2 should still be in update_refs, NOT cleared
    assert!(
        graph.branch_sections[0].commits[0]
            .update_refs
            .contains(&"feat2".to_string()),
        "co-located inner refs must be preserved"
    );
}

// ── weave_branch unit tests ──────────────────────────────────────────────

#[test]
fn weave_branch_moves_picks_into_section() {
    let mut graph = Weave {
        base_oid: oid("aaa"),
        branch_sections: vec![],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit("111", "C1")),
            IntegrationEntry::Pick(make_commit_with_refs("222", "C2", vec!["feature-x"])),
            IntegrationEntry::Pick(make_commit("333", "C3")),
        ],
    };

    graph.weave_branch("feature-x");

    // C1 and C2 should be in a new branch section
    assert_eq!(graph.branch_sections.len(), 1);
    assert_eq!(graph.branch_sections[0].label, "feature-x");
    assert_eq!(graph.branch_sections[0].commits.len(), 2);

    // The integration line should be [Merge(feature-x), Pick(C3)]:
    // merge comes first so loose commits sit on top of it.
    assert_eq!(graph.integration_line.len(), 2);
    assert!(
        matches!(&graph.integration_line[0], IntegrationEntry::Merge { label, .. } if label == "feature-x"),
        "expected Merge(feature-x) at position 0"
    );
    assert!(
        matches!(&graph.integration_line[1], IntegrationEntry::Pick(c) if c.message == "C3"),
        "expected Pick(C3) at position 1"
    );
}

// ── swap_commits unit tests ──────────────────────────────────────────────

#[test]
fn swap_commits_on_integration_line() {
    let mut graph = Weave {
        base_oid: oid(BASE),
        branch_sections: vec![],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_C1, "C1")),
            IntegrationEntry::Pick(make_commit(OID_C2, "C2")),
        ],
    };

    graph.swap_commits(oid(OID_C1), oid(OID_C2)).unwrap();

    if let IntegrationEntry::Pick(c) = &graph.integration_line[0] {
        assert_eq!(c.message, "C2");
    } else {
        panic!("Expected Pick");
    }
    if let IntegrationEntry::Pick(c) = &graph.integration_line[1] {
        assert_eq!(c.message, "C1");
    } else {
        panic!("Expected Pick");
    }
}

#[test]
fn swap_commits_in_branch_section() {
    let mut graph = Weave {
        base_oid: oid(BASE),
        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1"), make_commit(OID_A2, "A2")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
        }],
        integration_line: vec![IntegrationEntry::Merge {
            original_oid: Some(oid(OID_MERGE1)),
            label: "feature-a".to_string(),
        }],
    };

    graph.swap_commits(oid(OID_A1), oid(OID_A2)).unwrap();

    assert_eq!(graph.branch_sections[0].commits[0].message, "A2");
    assert_eq!(graph.branch_sections[0].commits[1].message, "A1");
}

#[test]
fn swap_commits_across_sections_errors() {
    let mut graph = Weave {
        base_oid: oid(BASE),
        branch_sections: vec![
            BranchSection {
                reset_target: "onto".to_string(),
                commits: vec![make_commit(OID_A1, "A1")],
                label: "feature-a".to_string(),
                branch_names: vec!["feature-a".to_string()],
            },
            BranchSection {
                reset_target: "onto".to_string(),
                commits: vec![make_commit(OID_B1, "B1")],
                label: "feature-b".to_string(),
                branch_names: vec!["feature-b".to_string()],
            },
        ],
        integration_line: vec![
            IntegrationEntry::Merge {
                original_oid: None,
                label: "feature-a".to_string(),
            },
            IntegrationEntry::Merge {
                original_oid: None,
                label: "feature-b".to_string(),
            },
        ],
    };

    let result = graph.swap_commits(oid(OID_A1), oid(OID_B1));
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("different"));
}

#[test]
fn swap_commits_across_section_and_integration_errors() {
    let mut graph = Weave {
        base_oid: oid(BASE),
        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
        }],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_C1, "C1")),
            IntegrationEntry::Merge {
                original_oid: None,
                label: "feature-a".to_string(),
            },
        ],
    };

    let result = graph.swap_commits(oid(OID_A1), oid(OID_C1));
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("different"));
}

#[test]
fn swap_commits_with_itself_errors() {
    let mut graph = Weave {
        base_oid: oid(BASE),
        branch_sections: vec![],
        integration_line: vec![IntegrationEntry::Pick(make_commit(OID_C1, "C1"))],
    };

    let result = graph.swap_commits(oid(OID_C1), oid(OID_C1));
    assert!(result.is_err());
}

#[test]
fn swap_commits_not_found_errors() {
    let mut graph = Weave {
        base_oid: oid(BASE),
        branch_sections: vec![],
        integration_line: vec![IntegrationEntry::Pick(make_commit(OID_C1, "C1"))],
    };

    let result = graph.swap_commits(oid(OID_C1), oid(OID_C2));
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("not found"));
}

#[test]
fn swap_commits_on_integration_line_with_interleaved_merge() {
    // Swapping C1 and C2 across an interleaved Merge is allowed:
    // the merge entry stays at its position, only the picks swap.
    let mut graph = Weave {
        base_oid: oid(BASE),
        branch_sections: vec![BranchSection {
            reset_target: "onto".to_string(),
            commits: vec![make_commit(OID_A1, "A1")],
            label: "feature-a".to_string(),
            branch_names: vec!["feature-a".to_string()],
        }],
        integration_line: vec![
            IntegrationEntry::Pick(make_commit(OID_C1, "C1")),
            IntegrationEntry::Merge {
                original_oid: None,
                label: "feature-a".to_string(),
            },
            IntegrationEntry::Pick(make_commit(OID_C2, "C2")),
        ],
    };

    graph.swap_commits(oid(OID_C1), oid(OID_C2)).unwrap();

    // C2 is now at position 0, Merge stays at 1, C1 is at 2
    if let IntegrationEntry::Pick(c) = &graph.integration_line[0] {
        assert_eq!(c.message, "C2");
    } else {
        panic!("Expected Pick at 0");
    }
    assert!(matches!(
        &graph.integration_line[1],
        IntegrationEntry::Merge { .. }
    ));
    if let IntegrationEntry::Pick(c) = &graph.integration_line[2] {
        assert_eq!(c.message, "C1");
    } else {
        panic!("Expected Pick at 2");
    }
}