stax 0.50.2

Fast stacked Git branches and PRs
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
mod common;

use common::{OutputAssertions, TestRepo};
use std::collections::{HashMap, HashSet};

#[test]
fn test_split_hunk_help() {
    let repo = TestRepo::new();
    let output = repo.run_stax(&["split", "--help"]);
    output.assert_success();

    let stdout = TestRepo::stdout(&output);
    assert!(
        stdout.contains("--hunk"),
        "Expected --hunk in help output, got: {}",
        stdout
    );
}

// =============================================================================
// Error Case Tests (validation before TUI)
// =============================================================================

#[test]
fn test_split_hunk_on_trunk_fails() {
    let repo = TestRepo::new();
    let output = repo.run_stax(&["split", "--hunk"]);
    output.assert_failure();

    let stderr = TestRepo::stderr(&output);
    assert!(
        stderr.contains("trunk") || stderr.contains("Cannot split"),
        "Expected trunk error, got: {}",
        stderr
    );
}

#[test]
fn test_split_hunk_untracked_branch_fails() {
    let repo = TestRepo::new();
    repo.git(&["checkout", "-b", "untracked-branch"]);
    repo.create_file("file1.txt", "content");
    repo.commit("commit 1");

    let output = repo.run_stax(&["split", "--hunk"]);
    output.assert_failure();

    let stderr = TestRepo::stderr(&output);
    assert!(
        stderr.contains("not tracked") || stderr.contains("track"),
        "Expected untracked error, got: {}",
        stderr
    );
}

#[test]
fn test_split_commit_mode_single_commit_suggests_hunk() {
    let repo = TestRepo::new();
    repo.create_stack(&["single-commit"]);

    let output = repo.run_stax(&["split"]);
    output.assert_failure();

    let stderr = TestRepo::stderr(&output);
    assert!(
        stderr.contains("--hunk") || stderr.contains("hunk"),
        "Expected hint about --hunk for single commit, got: {}",
        stderr
    );
}

#[test]
fn test_split_hunk_requires_terminal() {
    let repo = TestRepo::new();
    repo.create_stack(&["test-branch"]);
    repo.create_file("file1.txt", "content");
    repo.commit("commit 1");

    let output = repo.run_stax(&["split", "--hunk"]);
    output.assert_failure();

    let stderr = TestRepo::stderr(&output);
    assert!(
        stderr.contains("terminal") || stderr.contains("interactive"),
        "Expected terminal requirement error, got: {}",
        stderr
    );
}

// =============================================================================
// End-to-end success tests (scripted TUI via pseudo-terminal)
// =============================================================================

/// Each round: j(down to hunk), Space(select), Enter(finish round), Enter(accept name).
fn split_hunk_script(rounds: usize) -> String {
    let mut parts = vec!["sleep 1".to_string()];
    for _ in 0..rounds {
        parts.push("printf 'j \\r\\r'".to_string());
        parts.push("sleep 2".to_string());
    }
    parts.join("; ")
}

fn parent_map(repo: &TestRepo) -> HashMap<String, String> {
    let json = repo.get_status_json();
    json["branches"]
        .as_array()
        .map(|branches| {
            branches
                .iter()
                .filter_map(|b| {
                    let name = b["name"].as_str()?;
                    let parent = b["parent"].as_str()?;
                    Some((name.to_string(), parent.to_string()))
                })
                .collect()
        })
        .unwrap_or_default()
}

fn introduced_files(repo: &TestRepo, base: &str, branch: &str) -> HashSet<String> {
    let output = repo.git(&["diff", "--name-only", base, branch]);
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|l| l.trim().to_string())
        .filter(|l| !l.is_empty())
        .collect()
}

fn run_split_hunk(repo: &TestRepo, rounds: usize) {
    let script = split_hunk_script(rounds);
    let output = common::run_stax_in_script(&repo.path(), &["split", "--hunk"], &script);
    assert!(
        output.status.success(),
        "Split hunk TUI failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn file_content(repo: &TestRepo, branch: &str, path: &str) -> String {
    let output = repo.git(&["show", &format!("{}:{}", branch, path)]);
    String::from_utf8_lossy(&output.stdout).to_string()
}

#[test]
fn test_split_hunk_two_files_into_two_branches() {
    let repo = TestRepo::new();
    repo.create_stack(&["feature-a"]);
    let original = repo.current_branch();
    repo.create_file("extra.txt", "extra content\n");
    repo.commit("add extra file");

    run_split_hunk(&repo, 2);

    let split_1 = format!("{}_split_1", original);
    let branches = repo.list_branches();
    assert!(
        branches.contains(&split_1),
        "Missing {split_1}, got: {branches:?}"
    );
    assert!(
        branches.contains(&original),
        "Missing {original}, got: {branches:?}"
    );

    let parents = parent_map(&repo);
    assert_eq!(parents.get(&split_1).map(String::as_str), Some("main"));
    assert_eq!(
        parents.get(&original).map(String::as_str),
        Some(split_1.as_str())
    );

    // Each branch should introduce exactly one of the two files
    let s1_files = introduced_files(&repo, "main", &split_1);
    let orig_files = introduced_files(&repo, &split_1, &original);
    assert!(
        (s1_files.contains("extra.txt") && orig_files.contains("feature-a.txt"))
            || (s1_files.contains("feature-a.txt") && orig_files.contains("extra.txt")),
        "Each branch should introduce one file. split_1: {:?}, original: {:?}",
        s1_files,
        orig_files
    );
}

#[test]
fn test_split_hunk_three_files_three_branches() {
    let repo = TestRepo::new();
    repo.create_stack(&["multi-split"]);
    let original = repo.current_branch();
    repo.create_file("file_b.txt", "content b\n");
    repo.commit("add file b");
    repo.create_file("file_c.txt", "content c\n");
    repo.commit("add file c");

    run_split_hunk(&repo, 3);

    let split_1 = format!("{}_split_1", original);
    let split_2 = format!("{}_split_2", original);
    let branches = repo.list_branches();
    assert!(
        branches.contains(&split_1),
        "Missing {split_1}, got: {branches:?}"
    );
    assert!(
        branches.contains(&split_2),
        "Missing {split_2}, got: {branches:?}"
    );
    assert!(
        branches.contains(&original),
        "Missing {original}, got: {branches:?}"
    );

    let parents = parent_map(&repo);
    assert_eq!(parents.get(&split_1).map(String::as_str), Some("main"));
    assert_eq!(
        parents.get(&split_2).map(String::as_str),
        Some(split_1.as_str())
    );
    assert_eq!(
        parents.get(&original).map(String::as_str),
        Some(split_2.as_str())
    );
}

#[test]
fn test_split_hunk_children_reparented() {
    let repo = TestRepo::new();
    let stack = repo.create_stack(&["parent-branch", "child-branch"]);
    let child = stack[1].clone();

    repo.run_stax(&["checkout", &stack[0]]).assert_success();
    let parent_name = repo.current_branch();
    repo.create_file("second.txt", "second content\n");
    repo.commit("add second file");

    run_split_hunk(&repo, 2);

    let parents = parent_map(&repo);
    assert_eq!(
        parents.get(&child).map(String::as_str),
        Some(parent_name.as_str()),
        "child's parent should be the last split branch (original name)"
    );
}

#[test]
fn test_split_hunk_with_new_file() {
    let repo = TestRepo::new();
    repo.create_stack(&["new-file-test"]);
    let original = repo.current_branch();
    repo.create_file("brand_new.txt", "brand new content\n");
    repo.commit("add brand new file");

    run_split_hunk(&repo, 2);

    let split_1 = format!("{}_split_1", original);
    let branches = repo.list_branches();
    assert!(branches.contains(&split_1));
    assert!(branches.contains(&original));

    let s1_files = introduced_files(&repo, "main", &split_1);
    let orig_files = introduced_files(&repo, &split_1, &original);
    assert!(
        s1_files.contains("brand_new.txt") ^ orig_files.contains("brand_new.txt"),
        "brand_new.txt should be introduced by exactly one branch: split_1={:?}, original={:?}",
        s1_files,
        orig_files
    );
}

#[test]
fn test_split_hunk_abort_with_dirty_workdir_preserves_changes() {
    let repo = TestRepo::new();
    repo.create_stack(&["dirty-test"]);
    let original = repo.current_branch();

    repo.create_file("tracked.txt", "tracked content\n");
    repo.commit("add tracked file");

    // Create uncommitted changes (dirty workdir)
    repo.create_file("dirty.txt", "dirty content\n");

    // Abort immediately: q(quit) y(confirm)
    let script = "sleep 1; printf 'qy'; sleep 2";
    let output = common::run_stax_in_script(&repo.path(), &["split", "--hunk"], script);

    assert!(
        output.status.success(),
        "Split hunk abort failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Should be back on the original branch
    assert_eq!(repo.current_branch(), original);

    // Dirty file should still exist in the working directory
    let dirty_path = repo.path().join("dirty.txt");
    assert!(
        dirty_path.exists(),
        "dirty.txt should be restored after abort"
    );
    let content = std::fs::read_to_string(&dirty_path).unwrap();
    assert_eq!(content, "dirty content\n");
}

// =============================================================================
// Regression tests: same-file multi-hunk splits (stale offset bug)
// =============================================================================

#[test]
fn test_split_hunk_same_file_two_hunks() {
    let repo = TestRepo::new();

    let base_content: String = (1..=30).map(|i| format!("line {}\n", i)).collect();
    repo.create_file("shared.txt", &base_content);
    repo.commit("add shared file");

    let output = repo.run_stax(&["bc", "same-file-split"]);
    assert!(
        output.status.success(),
        "bc failed: {}",
        TestRepo::stderr(&output)
    );
    let original = repo.current_branch();

    let modified: String = (1..=30)
        .map(|i| match i {
            3 => "line 3 MODIFIED\n".to_string(),
            25 => "line 25 MODIFIED\n".to_string(),
            _ => format!("line {}\n", i),
        })
        .collect();
    repo.create_file("shared.txt", &modified);
    repo.commit("modify shared file in two places");

    run_split_hunk(&repo, 2);

    let split_1 = format!("{}_split_1", original);
    let branches = repo.list_branches();
    assert!(
        branches.contains(&split_1),
        "Missing {split_1}, got: {branches:?}"
    );
    assert!(
        branches.contains(&original),
        "Missing {original}, got: {branches:?}"
    );

    let parents = parent_map(&repo);
    assert_eq!(parents.get(&split_1).map(String::as_str), Some("main"));
    assert_eq!(
        parents.get(&original).map(String::as_str),
        Some(split_1.as_str())
    );

    let s1_content = file_content(&repo, &split_1, "shared.txt");
    assert!(
        s1_content.contains("line 3 MODIFIED"),
        "split_1 should have line 3 modification"
    );
    assert!(
        !s1_content.contains("line 25 MODIFIED"),
        "split_1 should NOT have line 25 modification"
    );

    let final_content = file_content(&repo, &original, "shared.txt");
    assert!(
        final_content.contains("line 3 MODIFIED"),
        "final branch should have line 3 modification"
    );
    assert!(
        final_content.contains("line 25 MODIFIED"),
        "final branch should have line 25 modification"
    );
}

#[test]
fn test_split_hunk_same_file_three_hunks() {
    let repo = TestRepo::new();

    let base_content: String = (1..=40).map(|i| format!("line {}\n", i)).collect();
    repo.create_file("shared.txt", &base_content);
    repo.commit("add shared file");

    let output = repo.run_stax(&["bc", "three-way-split"]);
    assert!(
        output.status.success(),
        "bc failed: {}",
        TestRepo::stderr(&output)
    );
    let original = repo.current_branch();

    let modified: String = (1..=40)
        .map(|i| match i {
            3 => "line 3 MODIFIED\n".to_string(),
            20 => "line 20 MODIFIED\n".to_string(),
            37 => "line 37 MODIFIED\n".to_string(),
            _ => format!("line {}\n", i),
        })
        .collect();
    repo.create_file("shared.txt", &modified);
    repo.commit("modify shared file in three places");

    run_split_hunk(&repo, 3);

    let split_1 = format!("{}_split_1", original);
    let split_2 = format!("{}_split_2", original);
    let branches = repo.list_branches();
    assert!(
        branches.contains(&split_1),
        "Missing {split_1}, got: {branches:?}"
    );
    assert!(
        branches.contains(&split_2),
        "Missing {split_2}, got: {branches:?}"
    );
    assert!(
        branches.contains(&original),
        "Missing {original}, got: {branches:?}"
    );

    let parents = parent_map(&repo);
    assert_eq!(parents.get(&split_1).map(String::as_str), Some("main"));
    assert_eq!(
        parents.get(&split_2).map(String::as_str),
        Some(split_1.as_str())
    );
    assert_eq!(
        parents.get(&original).map(String::as_str),
        Some(split_2.as_str())
    );

    let s1_content = file_content(&repo, &split_1, "shared.txt");
    assert!(s1_content.contains("line 3 MODIFIED"));
    assert!(!s1_content.contains("line 20 MODIFIED"));
    assert!(!s1_content.contains("line 37 MODIFIED"));

    let s2_content = file_content(&repo, &split_2, "shared.txt");
    assert!(s2_content.contains("line 3 MODIFIED"));
    assert!(s2_content.contains("line 20 MODIFIED"));
    assert!(!s2_content.contains("line 37 MODIFIED"));

    let final_content = file_content(&repo, &original, "shared.txt");
    assert!(final_content.contains("line 3 MODIFIED"));
    assert!(final_content.contains("line 20 MODIFIED"));
    assert!(final_content.contains("line 37 MODIFIED"));
}

#[test]
fn test_split_hunk_line_additions_partial_select() {
    let repo = TestRepo::new();

    // Create base file with enough lines for 4 hunks (lines 8 apart minimum)
    let base: String = (1..=60).map(|i| format!("line {}\n", i)).collect();
    repo.create_file("main.txt", &base);
    repo.commit("add base file");

    let output = repo.run_stax(&["bc", "add-lines-split"]);
    assert!(
        output.status.success(),
        "bc failed: {}",
        TestRepo::stderr(&output)
    );
    let original = repo.current_branch();

    // ADD new lines (not modify) at 4 locations — this shifts offsets between hunks
    let modified: String = (1..=60)
        .flat_map(|i| {
            let mut lines = vec![format!("line {}\n", i)];
            match i {
                5 => {
                    lines.push("ADDED AFTER 5a\n".to_string());
                    lines.push("ADDED AFTER 5b\n".to_string());
                }
                18 => {
                    lines.push("ADDED AFTER 18a\n".to_string());
                    lines.push("ADDED AFTER 18b\n".to_string());
                    lines.push("ADDED AFTER 18c\n".to_string());
                }
                35 => {
                    lines.push("ADDED AFTER 35a\n".to_string());
                }
                50 => {
                    lines.push("ADDED AFTER 50a\n".to_string());
                    lines.push("ADDED AFTER 50b\n".to_string());
                }
                _ => {}
            }
            lines
        })
        .collect();
    repo.create_file("main.txt", &modified);
    repo.commit("add lines at 4 locations");

    // Flat list:
    //   [0] FileHeader(main.txt)
    //   [1] Hunk 0 (adds 2 lines after line 5)
    //   [2] Hunk 1 (adds 3 lines after line 18)
    //   [3] Hunk 2 (adds 1 line after line 35)
    //   [4] Hunk 3 (adds 2 lines after line 50)
    //
    // Round 1: select hunk 0 only (j, space, Enter, Enter)
    // Round 2: select hunk 1 only (j, space, Enter, Enter)
    // Round 3: select hunks 2 and 3 (j, space, j, space, Enter, Enter)

    let script = [
        "sleep 1",
        "printf 'j \\r\\r'",
        "sleep 3",
        "printf 'j \\r\\r'",
        "sleep 3",
        "printf 'j j \\r\\r'",
        "sleep 2",
    ]
    .join("; ");
    let output = common::run_stax_in_script(&repo.path(), &["split", "--hunk"], &script);
    assert!(
        output.status.success(),
        "Split TUI failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let split_1 = format!("{}_split_1", original);
    let split_2 = format!("{}_split_2", original);
    let branches = repo.list_branches();
    assert!(
        branches.contains(&split_1),
        "Missing {split_1}, got: {branches:?}"
    );
    assert!(
        branches.contains(&split_2),
        "Missing {split_2}, got: {branches:?}"
    );
    assert!(
        branches.contains(&original),
        "Missing {original}, got: {branches:?}"
    );

    // Verify split_1 only has hunk 0
    let s1 = file_content(&repo, &split_1, "main.txt");
    assert!(s1.contains("ADDED AFTER 5a"), "split_1 should have hunk 0");
    assert!(
        !s1.contains("ADDED AFTER 18a"),
        "split_1 should NOT have hunk 1"
    );

    // Verify split_2 has hunks 0+1
    let s2 = file_content(&repo, &split_2, "main.txt");
    assert!(s2.contains("ADDED AFTER 5a"));
    assert!(s2.contains("ADDED AFTER 18a"));
    assert!(!s2.contains("ADDED AFTER 35a"));

    // Final branch has everything
    let fin = file_content(&repo, &original, "main.txt");
    assert!(fin.contains("ADDED AFTER 5a"));
    assert!(fin.contains("ADDED AFTER 18a"));
    assert!(fin.contains("ADDED AFTER 35a"));
    assert!(fin.contains("ADDED AFTER 50a"));
}

#[test]
fn test_split_hunk_partial_file_selection_gets_second_round() {
    let repo = TestRepo::new();

    // Create a base file on main with enough lines for 4 well-separated hunks
    let base_a: String = (1..=50).map(|i| format!("a line {}\n", i)).collect();
    repo.create_file("file_a.txt", &base_a);
    let base_b: String = (1..=20).map(|i| format!("b line {}\n", i)).collect();
    repo.create_file("file_b.txt", &base_b);
    repo.commit("add base files");

    let output = repo.run_stax(&["bc", "partial-select"]);
    assert!(
        output.status.success(),
        "bc failed: {}",
        TestRepo::stderr(&output)
    );
    let original = repo.current_branch();

    // Modify file_a in 4 well-separated locations (4 hunks)
    let mod_a: String = (1..=50)
        .map(|i| match i {
            3 => "a line 3 MODIFIED\n".to_string(),
            15 => "a line 15 MODIFIED\n".to_string(),
            30 => "a line 30 MODIFIED\n".to_string(),
            45 => "a line 45 MODIFIED\n".to_string(),
            _ => format!("a line {}\n", i),
        })
        .collect();
    repo.create_file("file_a.txt", &mod_a);

    // Modify file_b in 2 well-separated locations (2 hunks)
    let mod_b: String = (1..=20)
        .map(|i| match i {
            3 => "b line 3 MODIFIED\n".to_string(),
            15 => "b line 15 MODIFIED\n".to_string(),
            _ => format!("b line {}\n", i),
        })
        .collect();
    repo.create_file("file_b.txt", &mod_b);
    repo.commit("modify both files");

    // Flat list:
    //   [0] FileHeader(file_a.txt)
    //   [1] Hunk(A, 0) - line 3
    //   [2] Hunk(A, 1) - line 15
    //   [3] Hunk(A, 2) - line 30
    //   [4] Hunk(A, 3) - line 45
    //   [5] FileHeader(file_b.txt)
    //   [6] Hunk(B, 0) - line 3
    //   [7] Hunk(B, 1) - line 15
    //
    // Round 1: select A:0, A:1, and all of B (skip A:2, A:3)
    //   j=A:0, space=select, j=A:1, space=select, j=A:2, j=A:3, j=FileHeader(B), a=select-all-B
    //   Enter=commit, Enter=accept name
    //
    // Round 2: should have A:2, A:3 remaining
    //   j=A:2(now idx 0), space=select, j=A:3(now idx 1), space=select
    //   Enter=commit, Enter=accept name

    let script = "sleep 1; printf 'j j jjja\\r\\r'; sleep 3; printf 'j j \\r\\r'; sleep 2";
    let output = common::run_stax_in_script(&repo.path(), &["split", "--hunk"], &script);
    assert!(
        output.status.success(),
        "Split hunk TUI failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let split_1 = format!("{}_split_1", original);
    let branches = repo.list_branches();
    assert!(
        branches.contains(&split_1),
        "Missing {split_1}, got: {branches:?}"
    );
    assert!(
        branches.contains(&original),
        "Missing {original}, got: {branches:?}"
    );

    // split_1 should have A:0, A:1 + all of B
    let s1_a = file_content(&repo, &split_1, "file_a.txt");
    assert!(s1_a.contains("a line 3 MODIFIED"));
    assert!(s1_a.contains("a line 15 MODIFIED"));
    assert!(
        !s1_a.contains("a line 30 MODIFIED"),
        "split_1 should NOT have A hunk 2"
    );
    assert!(
        !s1_a.contains("a line 45 MODIFIED"),
        "split_1 should NOT have A hunk 3"
    );

    // original should have all modifications
    let final_a = file_content(&repo, &original, "file_a.txt");
    assert!(final_a.contains("a line 3 MODIFIED"));
    assert!(final_a.contains("a line 15 MODIFIED"));
    assert!(
        final_a.contains("a line 30 MODIFIED"),
        "final branch should have A hunk 2"
    );
    assert!(
        final_a.contains("a line 45 MODIFIED"),
        "final branch should have A hunk 3"
    );
}

// =============================================================================
// Interaction pattern tests: different ways to select the same hunks
// =============================================================================

/// Set up a repo with file_a (4 hunks) and file_b (2 hunks) on a stax branch.
/// Returns (repo, original_branch_name).
fn setup_two_file_four_two_hunks() -> (TestRepo, String) {
    let repo = TestRepo::new();

    let base_a: String = (1..=50).map(|i| format!("a line {}\n", i)).collect();
    repo.create_file("file_a.txt", &base_a);
    let base_b: String = (1..=20).map(|i| format!("b line {}\n", i)).collect();
    repo.create_file("file_b.txt", &base_b);
    repo.commit("add base files");

    let output = repo.run_stax(&["bc", "interaction-test"]);
    assert!(
        output.status.success(),
        "bc failed: {}",
        TestRepo::stderr(&output)
    );
    let original = repo.current_branch();

    let mod_a: String = (1..=50)
        .map(|i| match i {
            3 => "a line 3 MODIFIED\n".to_string(),
            15 => "a line 15 MODIFIED\n".to_string(),
            30 => "a line 30 MODIFIED\n".to_string(),
            45 => "a line 45 MODIFIED\n".to_string(),
            _ => format!("a line {}\n", i),
        })
        .collect();
    repo.create_file("file_a.txt", &mod_a);

    let mod_b: String = (1..=20)
        .map(|i| match i {
            3 => "b line 3 MODIFIED\n".to_string(),
            15 => "b line 15 MODIFIED\n".to_string(),
            _ => format!("b line {}\n", i),
        })
        .collect();
    repo.create_file("file_b.txt", &mod_b);
    repo.commit("modify both files");

    (repo, original)
}

/// Flat list layout for 4+2 hunk setup:
///   [0] FileHeader(file_a.txt)
///   [1] Hunk(A, 0) - line 3
///   [2] Hunk(A, 1) - line 15
///   [3] Hunk(A, 2) - line 30
///   [4] Hunk(A, 3) - line 45
///   [5] FileHeader(file_b.txt)
///   [6] Hunk(B, 0) - line 3
///   [7] Hunk(B, 1) - line 15
fn assert_split_1_has_a01_and_all_b(repo: &TestRepo, split_1: &str, original: &str) {
    let s1_a = file_content(repo, split_1, "file_a.txt");
    assert!(
        s1_a.contains("a line 3 MODIFIED"),
        "split_1 should have A:0"
    );
    assert!(
        s1_a.contains("a line 15 MODIFIED"),
        "split_1 should have A:1"
    );
    assert!(
        !s1_a.contains("a line 30 MODIFIED"),
        "split_1 should NOT have A:2"
    );
    assert!(
        !s1_a.contains("a line 45 MODIFIED"),
        "split_1 should NOT have A:3"
    );

    let s1_b = file_content(repo, split_1, "file_b.txt");
    assert!(
        s1_b.contains("b line 3 MODIFIED"),
        "split_1 should have B:0"
    );
    assert!(
        s1_b.contains("b line 15 MODIFIED"),
        "split_1 should have B:1"
    );

    let final_a = file_content(repo, original, "file_a.txt");
    assert!(final_a.contains("a line 3 MODIFIED"));
    assert!(final_a.contains("a line 15 MODIFIED"));
    assert!(
        final_a.contains("a line 30 MODIFIED"),
        "final should have A:2"
    );
    assert!(
        final_a.contains("a line 45 MODIFIED"),
        "final should have A:3"
    );
}

#[test]
fn test_split_hunk_toggle_file_then_deselect() {
    let (repo, original) = setup_two_file_four_two_hunks();

    // Round 1: 'a' on file_a header selects all A, then deselect A:2 and A:3,
    //          then 'a' on file_b header selects all B.
    //
    // [0] FileHeader(A) ← cursor starts here
    //   a → select all A (A:0..A:3 = true)
    //   j → [1] A:0
    //   j → [2] A:1
    //   j → [3] A:2
    //   space → deselect A:2
    //   j → [4] A:3
    //   space → deselect A:3
    //   j → [5] FileHeader(B)
    //   a → select all B
    //   Enter → commit (4/6 selected: A:0,A:1,B:0,B:1)
    //   Enter → accept name
    //
    // Round 2 (list mode): file_a with 2 remaining hunks
    //   j → first hunk, space, j → second hunk, space, Enter, Enter

    let script = "sleep 1; printf 'ajjj j ja\\r\\r'; sleep 3; printf 'j j \\r\\r'; sleep 2";
    let output = common::run_stax_in_script(&repo.path(), &["split", "--hunk"], script);
    assert!(
        output.status.success(),
        "Split failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let split_1 = format!("{}_split_1", original);
    let branches = repo.list_branches();
    assert!(
        branches.contains(&split_1),
        "Missing {split_1}, got: {branches:?}"
    );
    assert!(
        branches.contains(&original),
        "Missing {original}, got: {branches:?}"
    );

    assert_split_1_has_a01_and_all_b(&repo, &split_1, &original);
}

#[test]
fn test_split_hunk_select_later_hunks_first() {
    let (repo, original) = setup_two_file_four_two_hunks();

    // Round 1: skip A:0 and A:1, select A:2 and A:3, then 'a' on file_b.
    //
    // [0] FileHeader(A) ← start
    //   j → [1] A:0 (skip)
    //   j → [2] A:1 (skip)
    //   j → [3] A:2
    //   space → select A:2
    //   j → [4] A:3
    //   space → select A:3
    //   j → [5] FileHeader(B)
    //   a → select all B
    //   Enter → commit (4/6 selected: A:2,A:3,B:0,B:1)
    //   Enter → accept name
    //
    // Round 2: file_a with A:0 and A:1 remaining
    //   j → first hunk, space, j → second hunk, space, Enter, Enter

    let script = "sleep 1; printf 'jjj j ja\\r\\r'; sleep 3; printf 'j j \\r\\r'; sleep 2";
    let output = common::run_stax_in_script(&repo.path(), &["split", "--hunk"], script);
    assert!(
        output.status.success(),
        "Split failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let split_1 = format!("{}_split_1", original);
    let branches = repo.list_branches();
    assert!(
        branches.contains(&split_1),
        "Missing {split_1}, got: {branches:?}"
    );
    assert!(
        branches.contains(&original),
        "Missing {original}, got: {branches:?}"
    );

    // split_1 should have A:2, A:3 + all B (inverted from the other tests)
    let s1_a = file_content(&repo, &split_1, "file_a.txt");
    assert!(
        !s1_a.contains("a line 3 MODIFIED"),
        "split_1 should NOT have A:0"
    );
    assert!(
        !s1_a.contains("a line 15 MODIFIED"),
        "split_1 should NOT have A:1"
    );
    assert!(
        s1_a.contains("a line 30 MODIFIED"),
        "split_1 should have A:2"
    );
    assert!(
        s1_a.contains("a line 45 MODIFIED"),
        "split_1 should have A:3"
    );

    // original should have everything
    let final_a = file_content(&repo, &original, "file_a.txt");
    assert!(final_a.contains("a line 3 MODIFIED"));
    assert!(final_a.contains("a line 15 MODIFIED"));
    assert!(final_a.contains("a line 30 MODIFIED"));
    assert!(final_a.contains("a line 45 MODIFIED"));
}

#[test]
fn test_split_hunk_sequential_mode_partial() {
    let (repo, original) = setup_two_file_four_two_hunks();

    // Round 1 via sequential mode:
    //   Tab → enter sequential mode (cursor at [0] FileHeader A)
    //   y → no-op on header, advance to [1] A:0
    //   y → accept A:0, advance to [2] A:1
    //   y → accept A:1, advance to [3] A:2
    //   n → skip A:2, advance to [4] A:3
    //   n → skip A:3, advance to [6] B:0 (skips FileHeader)
    //   a → toggle file B (selects all B) + advance past B → auto-enters Naming
    //   Enter → accept name
    //
    // Round 2 (list mode): remaining A:2, A:3
    //   j, space, j, space, Enter, Enter

    let script = "sleep 1; printf '\\tyyynnna\\r'; sleep 3; printf 'j j \\r\\r'; sleep 2";
    let output = common::run_stax_in_script(&repo.path(), &["split", "--hunk"], script);
    assert!(
        output.status.success(),
        "Split failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let split_1 = format!("{}_split_1", original);
    let branches = repo.list_branches();
    assert!(
        branches.contains(&split_1),
        "Missing {split_1}, got: {branches:?}"
    );
    assert!(
        branches.contains(&original),
        "Missing {original}, got: {branches:?}"
    );

    assert_split_1_has_a01_and_all_b(&repo, &split_1, &original);
}

#[test]
fn test_split_hunk_debug_log_captures_selections() {
    let (repo, original) = setup_two_file_four_two_hunks();

    // Same as partial-select: select A:0, A:1 + all B, expect round 2 with A:2, A:3
    let script = "sleep 1; printf 'j j jjja\\r\\r'; sleep 3; printf 'j j \\r\\r'; sleep 2";
    let output = common::run_stax_in_script_with_env(
        &repo.path(),
        &["split", "--hunk"],
        script,
        &[("STAX_SPLIT_DEBUG", "1")],
    );
    assert!(
        output.status.success(),
        "Split failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Verify the debug log was written and contains expected data
    let log_path = std::env::temp_dir().join("stax-split-debug.log");
    assert!(log_path.exists(), "Debug log should exist");

    let log = std::fs::read_to_string(&log_path).unwrap();

    // Round 1 should show 4/6 selected (A:0,A:1,B:0,B:1)
    assert!(
        log.contains("Selected: 4/6"),
        "Debug log should show 4/6 selected in round 1, got:\n{}",
        log
    );

    // Round 2 should show 2/2 selected (remaining A:2,A:3)
    assert!(
        log.contains("Selected: 2/2"),
        "Debug log should show 2/2 selected in round 2, got:\n{}",
        log
    );

    // Should NOT contain the bug marker
    assert!(
        !log.contains("!!! BUG"),
        "Debug log should not contain bug marker, got:\n{}",
        log
    );

    // Verify branches were created correctly
    let split_1 = format!("{}_split_1", original);
    assert_split_1_has_a01_and_all_b(&repo, &split_1, &original);
}