stax 0.96.3

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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
use anyhow::{Context, Result, bail};
use colored::Colorize;
use dialoguer::{Confirm, theme::ColorfulTheme};
use std::fs;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};

const INTEGRATION_MARKER: &str = "stax shell-setup";
const POSIX_INTEGRATION_FILENAME: &str = "shell-setup.sh";
const FISH_INTEGRATION_FILENAME: &str = "shell-setup.fish";

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ShellKind {
    Posix,
    Fish,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SkillInstallMode {
    Ask,
    Skip,
    Install,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AuthSetupMode {
    Ask,
    Skip,
    ImportFromGh,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SetupOptions {
    pub auto_accept: bool,
    pub skill_install_mode: SkillInstallMode,
    pub auth_setup_mode: AuthSetupMode,
}

/// The shell function block that users source in their shell config.
/// It intercepts worktree commands that need shell-side directory changes,
/// performs the actual `cd` in the calling shell process, and can safely
/// relocate the shell before removing the current worktree.
fn shell_snippet(shell_kind: ShellKind) -> &'static str {
    match shell_kind {
        ShellKind::Posix => posix_shell_snippet(),
        ShellKind::Fish => fish_shell_snippet(),
    }
}

fn posix_shell_snippet() -> &'static str {
    r#"# Generated by stax shell-setup
# Existing aliases break zsh function definitions, so clear them first.
unalias stax 2>/dev/null || true
unalias st 2>/dev/null || true
unalias sw 2>/dev/null || true

export STAX_SHELL_INTEGRATION=1
__STAX_BIN=""

__stax_lookup_path() {
  local name="$1"
  local resolved=""

  if [[ -n "${ZSH_VERSION:-}" ]]; then
    resolved=$(whence -p "$name" 2>/dev/null)
  else
    resolved=$(type -P "$name" 2>/dev/null)
  fi

  if [[ -n "$resolved" ]]; then
    printf '%s\n' "$resolved"
    return 0
  fi

  return 1
}

__stax_resolve_bin() {
  if [[ -n "${__STAX_BIN:-}" && -x "$__STAX_BIN" ]]; then
    printf '%s\n' "$__STAX_BIN"
    return 0
  fi

  if __STAX_BIN=$(__stax_lookup_path stax); then
    printf '%s\n' "$__STAX_BIN"
    return 0
  fi

  if __STAX_BIN=$(__stax_lookup_path st); then
    printf '%s\n' "$__STAX_BIN"
    return 0
  fi

  echo "stax: no 'stax' or 'st' binary found on PATH" >&2
  return 127
}

__stax_exec() {
  local bin
  bin=$(__stax_resolve_bin) || return $?
  "$bin" "$@"
}

__stax_run_worktree_shell() {
  local raw
  local target_path=""
  local launch=""
  local message=""
  local passthrough=()
  local cmd=()
  local inserted=0
  local item

  for item in "$@"; do
    if [[ $inserted -eq 0 && "$item" == "--" ]]; then
      cmd+=("--shell-output")
      inserted=1
    fi
    cmd+=("$item")
  done

  if [[ $inserted -eq 0 ]]; then
    cmd+=("--shell-output")
  fi

  raw=$(__stax_exec "${cmd[@]}") || return $?

  while IFS= read -r line; do
    case "$line" in
      STAX_SHELL_PATH=*) target_path="${line#STAX_SHELL_PATH=}" ;;
      STAX_SHELL_LAUNCH=*) launch="${line#STAX_SHELL_LAUNCH=}" ;;
      STAX_SHELL_MESSAGE=*) message="${line#STAX_SHELL_MESSAGE=}" ;;
      *) passthrough+=("$line") ;;
    esac
  done <<< "$raw"

  if [[ -n "$target_path" ]]; then
    builtin cd "$target_path" || return 1
  fi

  if [[ ${#passthrough[@]} -gt 0 ]]; then
    printf '%s\n' "${passthrough[@]}"
  fi

  if [[ -n "$message" ]]; then
    echo "$message"
  fi

  if [[ -n "$launch" ]]; then
    eval "$launch"
  elif [[ -n "$target_path" && -z "$message" ]]; then
    echo "$(tput bold)$(tput setaf 6)~$(tput sgr0) $(basename "$target_path")"
  fi
}

__stax_remove_current_worktree() {
  local current
  local main
  current=$(pwd -P)
  main=$(git worktree list --porcelain 2>/dev/null | sed -n 's/^worktree //p' | head -n1)

  if [[ -n "$main" && -d "$main" ]]; then
    builtin cd "$main" || return 1
  fi

  __stax_exec "$@" "$current"
}

__stax_dispatch() {
  case "$1" in
    checkout|co|bco)
      __stax_run_worktree_shell "$@" ;;
    branch|b)
      case "$2" in
        checkout|co)
          __stax_run_worktree_shell "$@" ;;
        *)
          __stax_exec "$@" ;;
      esac ;;
    wtgo)
      __stax_run_worktree_shell worktree go "${@:2}" ;;
    wtc)
      __stax_run_worktree_shell worktree create "${@:2}" ;;
    lane)
      __stax_run_worktree_shell "$@" ;;
    wtrm)
      if [[ -z "$2" || "$2" == -* ]]; then
        __stax_remove_current_worktree worktree remove "${@:2}"
      else
        __stax_exec "$@"
      fi ;;
    worktree|wt)
      case "$2" in
        go|create|c|promote)
          __stax_run_worktree_shell "$@" ;;
        remove|rm)
          if [[ -z "$3" || "$3" == -* ]]; then
            __stax_remove_current_worktree "$@"
          else
            __stax_exec "$@"
          fi ;;
        *)
          __stax_exec "$@" ;;
      esac ;;
    *)
      __stax_exec "$@" ;;
  esac
}
stax() { __stax_dispatch "$@"; }
st() { __stax_dispatch "$@"; }
sw() { st wt go "$@"; }"#
}

fn fish_shell_snippet() -> &'static str {
    r#"# Generated by stax shell-setup
set -gx STAX_SHELL_INTEGRATION 1
set -g __STAX_BIN ""

function __stax_resolve_bin
    if test -n "$__STAX_BIN"; and test -x "$__STAX_BIN"
        printf '%s\n' "$__STAX_BIN"
        return 0
    end

    set -l resolved (type -p stax 2>/dev/null)
    if test -n "$resolved"
        set -g __STAX_BIN "$resolved"
        printf '%s\n' "$resolved"
        return 0
    end

    set resolved (type -p st 2>/dev/null)
    if test -n "$resolved"
        set -g __STAX_BIN "$resolved"
        printf '%s\n' "$resolved"
        return 0
    end

    printf '%s\n' "stax: no 'stax' or 'st' binary found on PATH" >&2
    return 127
end

function __stax_exec
    set -l bin (__stax_resolve_bin)
    or return $status

    "$bin" $argv
end

function __stax_insert_shell_output
    set -l inserted 0

    for arg in $argv
        if test $inserted -eq 0; and test "$arg" = "--"
            printf '%s\n' --shell-output
            set inserted 1
        end

        printf '%s\n' "$arg"
    end

    if test $inserted -eq 0
        printf '%s\n' --shell-output
    end
end

function __stax_run_worktree_shell
    set -l path ""
    set -l launch ""
    set -l message ""
    set -l passthrough
    set -l cmd (__stax_insert_shell_output $argv)
    set -l raw (__stax_exec $cmd)
    or return $status

    # Split on newlines only: `for line in $raw` would split paths/commands on spaces.
    for line in (string split \n -- $raw)
        if test -z "$line"
            continue
        end
        switch $line
            case 'STAX_SHELL_PATH=*'
                set path (string replace -- 'STAX_SHELL_PATH=' '' $line)
            case 'STAX_SHELL_LAUNCH=*'
                set launch (string replace -- 'STAX_SHELL_LAUNCH=' '' $line)
            case 'STAX_SHELL_MESSAGE=*'
                set message (string replace -- 'STAX_SHELL_MESSAGE=' '' $line)
            case '*'
                set -a passthrough $line
        end
    end

    if test -n "$path"
        cd "$path"; or return 1
    end

    if test (count $passthrough) -gt 0
        printf '%s\n' $passthrough
    end

    if test -n "$message"
        printf '%s\n' "$message"
    end

    if test -n "$launch"
        eval "$launch"
    else if test -n "$path"; and test -z "$message"
        printf '~ %s\n' (basename "$path")
    end
end

function __stax_remove_current_worktree
    set -l current (pwd -P)
    set -l main (git worktree list --porcelain 2>/dev/null | sed -n 's/^worktree //p' | head -n1)

    if test -n "$main"; and test -d "$main"
        cd "$main"; or return 1
    end

    __stax_exec $argv "$current"
end

function __stax_dispatch
    switch "$argv[1]"
        case checkout co bco
            __stax_run_worktree_shell $argv
        case branch b
            switch "$argv[2]"
                case checkout co
                    __stax_run_worktree_shell $argv
                case '*'
                    __stax_exec $argv
            end
        case wtgo
            __stax_run_worktree_shell worktree go $argv[2..-1]
        case wtc
            __stax_run_worktree_shell worktree create $argv[2..-1]
        case lane
            __stax_run_worktree_shell $argv
        case wtrm
            if test (count $argv) -lt 2; or string match -qr '^-' -- "$argv[2]"
                __stax_remove_current_worktree worktree remove $argv[2..-1]
            else
                __stax_exec $argv
            end
        case worktree wt
            switch "$argv[2]"
                case go create c promote
                    __stax_run_worktree_shell $argv
                case remove rm
                    if test (count $argv) -lt 3; or string match -qr '^-' -- "$argv[3]"
                        __stax_remove_current_worktree $argv
                    else
                        __stax_exec $argv
                    end
                case '*'
                    __stax_exec $argv
            end
        case '*'
            __stax_exec $argv
    end
end

functions -e stax 2>/dev/null
functions -e st 2>/dev/null
functions -e sw 2>/dev/null
function stax
    __stax_dispatch $argv
end
function st
    __stax_dispatch $argv
end
function sw
    st wt go $argv
end"#
}

/// Setup shell integration and enable rerere. By default installs; use --print to just see the snippet.
pub fn run(print: bool, refresh: bool, options: SetupOptions) -> Result<()> {
    if refresh {
        return refresh_installed_snippets();
    }

    if cfg!(target_os = "windows") {
        bail!(
            "Shell integration is not yet available on Windows.\n\
             Workaround: use WSL or Git Bash, where bash/zsh/fish shells are available.\n\
             All stax commands still work on Windows — only the transparent `cd` on \
             `stax wt create` / `stax wt go` requires shell integration."
        );
    }

    let shell_setup_completed = if print {
        // Just print the snippet for manual setup
        println!("{}", shell_snippet(detect_shell_kind()));
        true
    } else {
        // Default: install shell integration
        install_to_shell_config(options.auto_accept)?
    };

    // Always enable rerere when in a git repo (unless we're just printing)
    if shell_setup_completed && !print {
        enable_rerere_if_in_repo()?;
        maybe_install_skills(options)?;
        maybe_setup_auth(options)?;
    }

    Ok(())
}

/// Enable git rerere if we're in a git repository
fn enable_rerere_if_in_repo() -> Result<()> {
    if let Ok(repo) = crate::git::repo::GitRepo::open() {
        match repo.enable_rerere() {
            Ok(_) => println!(
                "{}  Enabled git rerere for conflict resolution memory",
                "✓".green().bold()
            ),
            Err(e) => eprintln!(
                "{}  Failed to enable rerere: {}",
                "Warning:".yellow().bold(),
                e
            ),
        }
    }
    Ok(())
}

/// Refresh generated shell integration files in-place after upgrades.
///
/// This keeps the single `source ~/.config/stax/shell-setup.*` model current
/// without rewriting the user's shell rc on every run.
pub fn refresh_installed_snippets() -> Result<()> {
    if cfg!(target_os = "windows") {
        return Ok(());
    }

    refresh_snippet_if_installed(ShellKind::Posix)?;
    refresh_snippet_if_installed(ShellKind::Fish)?;
    Ok(())
}

/// Returns true if `STAX_SHELL_INTEGRATION` is set in the environment,
/// which means the shell function has been sourced.
pub fn is_installed() -> bool {
    std::env::var("STAX_SHELL_INTEGRATION").is_ok()
}

/// If shell integration is not installed and we're in an interactive terminal,
/// offer to install it. Silent in non-interactive contexts.
#[allow(dead_code)]
pub fn prompt_if_missing() -> Result<()> {
    if cfg!(target_os = "windows") || is_installed() {
        return Ok(());
    }
    if !std::io::stdin().is_terminal() {
        return Ok(());
    }

    eprintln!("{} Shell integration not detected.", "stax:".cyan().bold());
    eprintln!(
        "  Run {} for transparent worktree navigation (cd).",
        "stax setup".cyan()
    );
    eprintln!();

    let install = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Install shell integration now?")
        .default(true)
        .interact()?;

    if install {
        install_to_shell_config(false)?;
        eprintln!();
        eprintln!(
            "{}  Restart your shell or run: {}",
            "Done.".green().bold(),
            shell_source_cmd().cyan()
        );
        eprintln!();
    }

    Ok(())
}

fn install_to_shell_config(auto_accept: bool) -> Result<bool> {
    let shell_kind = detect_shell_kind();
    let config_path = detect_shell_config()?;
    let integration_path = shell_integration_path(shell_kind)?;
    let source_line = shell_source_line(&integration_path);

    let existing = if config_path.exists() {
        fs::read_to_string(&config_path)?
    } else {
        String::new()
    };
    let (updated_config, config_changed) = update_shell_config_contents(&existing, &source_line);

    if !config_changed {
        write_integration_file(&integration_path, shell_snippet(shell_kind))?;
        println!(
            "{}  Shell integration already configured in {}",
            "OK".green().bold(),
            config_path.display()
        );
        println!("  Refreshed {}", integration_path.display());
        return Ok(true);
    }

    println!(
        "Will write shell integration to {}.",
        integration_path.display()
    );
    println!("Will update {}:", config_path.display());
    println!();
    println!("  {}", source_line.cyan());
    println!();

    let proceed = if auto_accept {
        true
    } else {
        Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Proceed?")
            .default(true)
            .interact()?
    };

    if !proceed {
        println!("{}", "Aborted.".dimmed());
        return Ok(false);
    }

    write_integration_file(&integration_path, shell_snippet(shell_kind))?;
    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&config_path, updated_config)?;

    println!(
        "{}  Added to {}",
        "Done.".green().bold(),
        config_path.display()
    );
    println!("  Wrote {}", integration_path.display());
    println!("  Restart your shell or run: {}", shell_source_cmd().cyan());

    Ok(true)
}

fn maybe_install_skills(options: SetupOptions) -> Result<()> {
    let should_install = match options.skill_install_mode {
        SkillInstallMode::Install => true,
        SkillInstallMode::Skip => false,
        SkillInstallMode::Ask => {
            if options.auto_accept {
                true
            } else {
                prompt_for_skill_install()?
            }
        }
    };

    if !should_install {
        return Ok(());
    }

    println!();
    crate::commands::skills::run_update(false)
}

fn maybe_setup_auth(options: SetupOptions) -> Result<()> {
    let status = crate::config::Config::github_auth_status();
    if has_non_gh_auth(&status) {
        return Ok(());
    }

    match options.auth_setup_mode {
        AuthSetupMode::Skip => Ok(()),
        AuthSetupMode::ImportFromGh => import_auth_from_gh(),
        AuthSetupMode::Ask => handle_default_auth_setup(status, options.auto_accept),
    }
}

fn has_non_gh_auth(status: &crate::config::GitHubAuthStatus) -> bool {
    status.stax_env_available
        || status.credentials_file_available
        || (status.allow_github_token_env && status.github_env_available)
}

fn handle_default_auth_setup(
    status: crate::config::GitHubAuthStatus,
    auto_accept: bool,
) -> Result<()> {
    if status.gh_cli_available {
        let should_import = if auto_accept {
            true
        } else {
            prompt_for_gh_auth_import()?
        };

        if should_import {
            return import_auth_from_gh();
        }

        return Ok(());
    }

    if auto_accept {
        print_auth_setup_hint();
        return Ok(());
    }

    if prompt_for_auth_setup_hint()? {
        print_auth_setup_hint();
    }

    Ok(())
}

fn import_auth_from_gh() -> Result<()> {
    println!();
    crate::commands::auth::run(None, true)
}

fn prompt_for_skill_install() -> Result<bool> {
    if !can_prompt() {
        return Ok(false);
    }

    eprintln!();
    Ok(Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Install stax AI agent skills too?")
        .default(true)
        .interact()?)
}

fn prompt_for_gh_auth_import() -> Result<bool> {
    if !can_prompt() {
        return Ok(false);
    }

    eprintln!();
    Ok(Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Import GitHub auth from `gh` now?")
        .default(true)
        .interact()?)
}

fn prompt_for_auth_setup_hint() -> Result<bool> {
    if !can_prompt() {
        return Ok(false);
    }

    eprintln!();
    Ok(Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Show GitHub auth setup steps?")
        .default(true)
        .interact()?)
}

fn print_auth_setup_hint() {
    println!();
    println!("{}", "GitHub auth is not configured yet.".yellow().bold());
    println!(
        "Run {} to sign in with GitHub CLI.",
        "`gh auth login`".cyan()
    );
    println!(
        "Then import that token with {}.",
        "`st auth --from-gh`".cyan()
    );
    println!("Or save a token directly with {}.", "`st auth`".cyan());
}

fn can_prompt() -> bool {
    std::io::stdin().is_terminal() && std::io::stderr().is_terminal()
}

fn detect_shell_kind() -> ShellKind {
    let shell = std::env::var("SHELL").unwrap_or_default();
    if shell.ends_with("fish") {
        ShellKind::Fish
    } else {
        ShellKind::Posix
    }
}

fn detect_shell_config() -> Result<PathBuf> {
    let shell = std::env::var("SHELL").unwrap_or_default();
    let home = dirs::home_dir().context("Could not find home directory")?;

    let path = if shell.ends_with("zsh") {
        home.join(".zshrc")
    } else if shell.ends_with("bash") {
        // Prefer .bash_profile on macOS, .bashrc on Linux
        let profile = home.join(".bash_profile");
        if cfg!(target_os = "macos") && !profile.exists() {
            home.join(".bashrc")
        } else if cfg!(target_os = "macos") {
            profile
        } else {
            home.join(".bashrc")
        }
    } else if shell.ends_with("fish") {
        home.join(".config").join("fish").join("config.fish")
    } else {
        // Fallback to .profile
        home.join(".profile")
    };

    Ok(path)
}

fn shell_integration_path(shell_kind: ShellKind) -> Result<PathBuf> {
    let config_dir = crate::config::Config::dir()?;

    let filename = match shell_kind {
        ShellKind::Posix => POSIX_INTEGRATION_FILENAME,
        ShellKind::Fish => FISH_INTEGRATION_FILENAME,
    };

    Ok(config_dir.join(filename))
}

fn refresh_snippet_if_installed(shell_kind: ShellKind) -> Result<bool> {
    let path = shell_integration_path(shell_kind)?;
    refresh_generated_integration_file(&path, shell_snippet(shell_kind))
}

fn shell_source_line(integration_path: &Path) -> String {
    format!(
        "source {} # {}",
        shell_quote_path(integration_path),
        INTEGRATION_MARKER
    )
}

fn shell_quote_path(path: &Path) -> String {
    let path = path.display().to_string();
    let escaped = path
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('$', "\\$")
        .replace('`', "\\`");
    format!("\"{}\"", escaped)
}

fn update_shell_config_contents(existing: &str, source_line: &str) -> (String, bool) {
    if let Some(updated) = replace_source_marker_lines(existing, source_line) {
        let changed = updated != existing;
        return (updated, changed);
    }

    if let Some(updated) = replace_legacy_eval_line(existing, source_line) {
        return (updated, true);
    }

    if let Some(updated) = replace_inline_shell_block(existing, source_line) {
        return (updated, true);
    }

    let suffix = if existing.is_empty() || existing.ends_with('\n') {
        format!("{}\n", source_line)
    } else {
        format!("\n{}\n", source_line)
    };
    let updated = format!("{}{}", existing, suffix);
    (updated, true)
}

fn refresh_generated_integration_file(path: &Path, desired: &str) -> Result<bool> {
    if !path.exists() {
        return Ok(false);
    }

    let existing = fs::read_to_string(path)?;
    if existing == desired || !is_generated_snippet(&existing) {
        return Ok(false);
    }

    write_integration_file(path, desired)?;
    Ok(true)
}

fn is_generated_snippet(contents: &str) -> bool {
    contents.contains("# Generated by stax shell-setup")
}

fn replace_source_marker_lines(existing: &str, source_line: &str) -> Option<String> {
    let marker_lines = existing
        .lines()
        .filter(|line| is_source_marker_line(line))
        .count();
    if marker_lines == 0 {
        return None;
    }

    let mut updated_lines = Vec::new();
    let mut inserted = false;

    for line in existing.lines() {
        if is_source_marker_line(line) {
            if !inserted {
                updated_lines.push(source_line.to_string());
                inserted = true;
            }
            continue;
        }

        updated_lines.push(line.to_string());
    }

    let mut updated = updated_lines.join("\n");
    if existing.ends_with('\n') {
        updated.push('\n');
    }
    Some(updated)
}

fn is_source_marker_line(line: &str) -> bool {
    line.contains(INTEGRATION_MARKER) && line.contains("source ")
}

fn replace_legacy_eval_line(existing: &str, source_line: &str) -> Option<String> {
    let lines: Vec<&str> = existing.lines().collect();
    let idx = lines.iter().position(|line| {
        line.contains("eval \"$(stax shell-setup)\"")
            || line.contains("eval \"$(st shell-setup)\"")
            || line.contains("source <(stax shell-setup)")
            || line.contains("source <(st shell-setup)")
    })?;
    Some(replace_line_range(existing, idx, idx + 1, source_line))
}

fn replace_inline_shell_block(existing: &str, source_line: &str) -> Option<String> {
    let lines: Vec<&str> = existing.lines().collect();

    if let Some((start, end)) = find_inline_posix_shell_block(&lines) {
        return Some(replace_line_range(existing, start, end, source_line));
    }

    if let Some((start, end)) = find_inline_fish_shell_block(&lines) {
        return Some(replace_line_range(existing, start, end, source_line));
    }

    None
}

fn find_inline_posix_shell_block(lines: &[&str]) -> Option<(usize, usize)> {
    let end = lines
        .iter()
        .position(|line| line.contains(r#"sw() { st wt go "$@"; }"#))?;
    let start = posix_block_start(lines, end)?;

    let mut block_end = end + 1;
    if lines.get(block_end).is_some_and(|line| line.trim() == "fi") {
        block_end += 1;
    }

    Some((start, block_end))
}

fn posix_block_start(lines: &[&str], end: usize) -> Option<usize> {
    let start = lines
        .iter()
        .enumerate()
        .take(end + 1)
        .find(|(_, line)| {
            line.contains("__stax_insert_shell_output()")
                || line.contains("__stax_dispatch()")
                || line.contains("# Generated by stax shell-setup")
                || line.contains("export STAX_SHELL_INTEGRATION=1")
        })?
        .0;

    if let Some(if_idx) = (0..=start)
        .rev()
        .find(|&idx| lines[idx].contains("if (( $+commands[stax] ))"))
    {
        let mut block_start = if_idx;
        if block_start > 0 && lines[block_start - 1].contains("# Static stax shell integration") {
            block_start -= 1;
        }
        return Some(block_start);
    }

    if start > 0 && lines[start - 1].contains("# Static stax shell integration") {
        return Some(start - 1);
    }

    Some(start)
}

fn find_inline_fish_shell_block(lines: &[&str]) -> Option<(usize, usize)> {
    let start = lines.iter().position(|line| {
        line.contains("function __stax_insert_shell_output")
            || line.contains("# Generated by stax shell-setup")
            || line.contains("set -gx STAX_SHELL_INTEGRATION 1")
    })?;
    let sw_idx = lines.iter().position(|line| line.trim() == "function sw")?;
    let end = lines
        .iter()
        .enumerate()
        .skip(sw_idx + 1)
        .find(|(_, line)| line.trim() == "end")?
        .0
        + 1;

    Some((start, end))
}

fn replace_line_range(existing: &str, start: usize, end: usize, replacement: &str) -> String {
    let lines: Vec<&str> = existing.lines().collect();
    let mut updated_lines = Vec::new();
    updated_lines.extend(lines[..start].iter().copied().map(str::to_string));
    updated_lines.push(replacement.to_string());
    updated_lines.extend(lines[end..].iter().copied().map(str::to_string));

    let mut updated = updated_lines.join("\n");
    if existing.ends_with('\n') {
        updated.push('\n');
    }
    updated
}

fn write_integration_file(path: &Path, contents: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, contents)?;
    Ok(())
}

fn shell_source_cmd() -> String {
    if let Ok(path) = shell_integration_path(detect_shell_kind()) {
        return format!("source {}", shell_quote_path(&path));
    }
    "source ~/.config/stax/shell-setup.sh".to_string()
}

#[cfg(test)]
mod tests {
    use super::{
        INTEGRATION_MARKER, ShellKind, refresh_generated_integration_file, shell_snippet,
        shell_source_line, update_shell_config_contents,
    };
    use std::{fs, io::ErrorKind, path::Path, process::Command};
    use tempfile::tempdir;

    #[test]
    fn posix_shell_snippet_clears_aliases_before_function_definitions() {
        let snippet = shell_snippet(ShellKind::Posix);

        let unalias_stax = snippet.find("unalias stax").expect("missing stax unalias");
        let unalias_st = snippet.find("unalias st ").expect("missing st unalias");
        let unalias_sw = snippet.find("unalias sw").expect("missing sw unalias");
        let stax_fn = snippet.find("stax()").expect("missing stax function");
        let st_fn = snippet.find("st()").expect("missing st function");
        let sw_fn = snippet.find("sw()").expect("missing sw function");

        assert!(unalias_stax < stax_fn);
        assert!(unalias_st < st_fn);
        assert!(unalias_sw < sw_fn);
    }

    #[test]
    fn posix_shell_snippet_resolves_stax_or_st_binary() {
        let snippet = shell_snippet(ShellKind::Posix);

        assert!(snippet.contains("__stax_lookup_path()"));
        assert!(snippet.contains("whence -p"));
        assert!(snippet.contains("type -P"));
        assert!(snippet.contains("__stax_exec()"));
    }

    #[test]
    fn posix_shell_snippet_builds_shell_output_args_without_process_substitution() {
        let snippet = shell_snippet(ShellKind::Posix);

        assert!(
            !snippet.contains("< <(__stax_insert_shell_output"),
            "shell-output argument handling must not leave asynchronous process-substitution children"
        );
    }

    #[test]
    fn fish_shell_snippet_routes_worktree_promote_through_shell_output() {
        let snippet = shell_snippet(ShellKind::Fish);

        assert!(snippet.contains("case go create c promote"));
    }

    #[cfg(unix)]
    #[test]
    fn posix_shell_snippet_wraps_worktree_promote_in_zsh() {
        use std::os::unix::fs::PermissionsExt;

        if let Err(err) = Command::new("zsh").arg("-lc").arg("exit 0").output() {
            if err.kind() == ErrorKind::NotFound {
                return;
            }
            panic!("failed to probe zsh: {err}");
        }

        let dir = tempdir().expect("tempdir");
        let bin_dir = dir.path().join("bin");
        fs::create_dir_all(&bin_dir).expect("create bin dir");

        let fake_stax = bin_dir.join("stax");
        fs::write(&fake_stax, "#!/bin/sh\nprintf 'args:%s\\n' \"$*\"\n").expect("write fake stax");
        let mut perms = fs::metadata(&fake_stax)
            .expect("fake stax metadata")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&fake_stax, perms).expect("chmod fake stax");

        let snippet_path = dir.path().join("shell-setup.sh");
        fs::write(&snippet_path, shell_snippet(ShellKind::Posix)).expect("write snippet");

        let original_path = std::env::var("PATH").unwrap_or_default();
        let path_env = format!("{}:{original_path}", bin_dir.display());
        let command = format!("source \"{}\"; st wt promote", snippet_path.display());
        let output = Command::new("zsh")
            .arg("-lc")
            .arg(&command)
            .env("PATH", path_env)
            .output()
            .expect("run zsh shell snippet");

        assert!(
            output.status.success(),
            "stdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains("args:wt promote --shell-output"),
            "expected promote to inject --shell-output, got:\n{stdout}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn posix_shell_snippet_relocates_after_successful_promote_only() {
        use std::os::unix::fs::PermissionsExt;

        if let Err(err) = Command::new("zsh").arg("-lc").arg("exit 0").output() {
            if err.kind() == ErrorKind::NotFound {
                return;
            }
            panic!("failed to probe zsh: {err}");
        }

        let dir = tempdir().expect("tempdir");
        let bin_dir = dir.path().join("bin");
        let source = dir.path().join("source");
        let target = dir.path().join("main");
        fs::create_dir_all(&bin_dir).expect("create bin dir");
        fs::create_dir_all(&source).expect("create source dir");
        fs::create_dir_all(&target).expect("create target dir");

        let fake_stax = bin_dir.join("stax");
        fs::write(
            &fake_stax,
            "#!/bin/sh\nprintf 'STAX_SHELL_PATH=%s\\n' \"$PROMOTE_TARGET\"\nprintf 'STAX_SHELL_MESSAGE=promoted\\n'\n",
        )
        .expect("write fake stax");
        let mut perms = fs::metadata(&fake_stax)
            .expect("fake stax metadata")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&fake_stax, perms).expect("chmod fake stax");

        let snippet_path = dir.path().join("shell-setup.sh");
        fs::write(&snippet_path, shell_snippet(ShellKind::Posix)).expect("write snippet");
        let original_path = std::env::var("PATH").unwrap_or_default();
        let path_env = format!("{}:{original_path}", bin_dir.display());
        let command = format!(
            "source \"{}\"; cd \"{}\"; st wt promote; printf 'cwd:%s\\n' \"$PWD\"",
            snippet_path.display(),
            source.display()
        );
        let output = Command::new("zsh")
            .arg("-lc")
            .arg(&command)
            .env("PATH", &path_env)
            .env("PROMOTE_TARGET", &target)
            .output()
            .expect("run successful promote wrapper");
        assert!(output.status.success());
        assert!(
            String::from_utf8_lossy(&output.stdout).contains(&format!("cwd:{}", target.display()))
        );

        fs::write(
            &fake_stax,
            "#!/bin/sh\nprintf 'STAX_SHELL_PATH=%s\\n' \"$PROMOTE_TARGET\"\nexit 1\n",
        )
        .expect("write failing fake stax");
        let command = format!(
            "source \"{}\"; cd \"{}\"; st wt promote || true; printf 'cwd:%s\\n' \"$PWD\"",
            snippet_path.display(),
            source.display()
        );
        let output = Command::new("zsh")
            .arg("-lc")
            .arg(&command)
            .env("PATH", path_env)
            .env("PROMOTE_TARGET", &target)
            .output()
            .expect("run failing promote wrapper");
        assert!(output.status.success());
        assert!(
            String::from_utf8_lossy(&output.stdout).contains(&format!("cwd:{}", source.display()))
        );
    }

    #[cfg(unix)]
    #[test]
    fn posix_shell_snippet_resolves_real_binary_in_zsh() {
        use std::os::unix::fs::PermissionsExt;

        if let Err(err) = Command::new("zsh").arg("-dfc").arg("exit 0").output() {
            if err.kind() == ErrorKind::NotFound {
                return;
            }
            panic!("failed to probe zsh: {err}");
        }

        let dir = tempdir().expect("tempdir");
        let bin_dir = dir.path().join("bin");
        fs::create_dir_all(&bin_dir).expect("create bin dir");

        let fake_stax = bin_dir.join("stax");
        fs::write(
            &fake_stax,
            "#!/bin/sh\nprintf 'resolved:%s\\n' \"$0\"\nprintf 'args:%s\\n' \"$*\"\n",
        )
        .expect("write fake stax");
        let mut perms = fs::metadata(&fake_stax)
            .expect("fake stax metadata")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&fake_stax, perms).expect("chmod fake stax");

        let snippet_path = dir.path().join("shell-setup.sh");
        fs::write(&snippet_path, shell_snippet(ShellKind::Posix)).expect("write snippet");

        let original_path = std::env::var("PATH").unwrap_or_default();
        let path_env = format!("{}:{original_path}", bin_dir.display());
        let command = format!("source \"{}\"; st config", snippet_path.display());
        let output = Command::new("zsh")
            .arg("-dfc")
            .arg(&command)
            .env("PATH", path_env)
            .output()
            .expect("run zsh shell snippet");

        assert!(
            output.status.success(),
            "stdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );

        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains(&format!("resolved:{}", fake_stax.display())),
            "expected zsh wrapper to resolve fake stax binary, got:\n{}",
            stdout
        );
        assert!(
            stdout.contains("args:config"),
            "expected wrapper to forward command args, got:\n{}",
            stdout
        );
    }

    #[cfg(unix)]
    #[test]
    fn posix_shell_snippet_keeps_path_for_worktree_shell_commands_in_zsh() {
        use std::os::unix::fs::PermissionsExt;

        if let Err(err) = Command::new("zsh").arg("-dfc").arg("exit 0").output() {
            if err.kind() == ErrorKind::NotFound {
                return;
            }
            panic!("failed to probe zsh: {err}");
        }

        let dir = tempdir().expect("tempdir");
        let bin_dir = dir.path().join("bin");
        fs::create_dir_all(&bin_dir).expect("create bin dir");

        let fake_stax = bin_dir.join("stax");
        fs::write(
            &fake_stax,
            "#!/bin/sh\nprintf 'resolved:%s\\n' \"$0\"\nprintf 'args:%s\\n' \"$*\"\n",
        )
        .expect("write fake stax");
        let mut perms = fs::metadata(&fake_stax)
            .expect("fake stax metadata")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&fake_stax, perms).expect("chmod fake stax");

        let snippet_path = dir.path().join("shell-setup.sh");
        fs::write(&snippet_path, shell_snippet(ShellKind::Posix)).expect("write snippet");

        let original_path = std::env::var("PATH").unwrap_or_default();
        let path_env = format!("{}:{original_path}", bin_dir.display());
        let command = format!("source \"{}\"; st wtgo demo-lane", snippet_path.display());
        let output = Command::new("zsh")
            .arg("-dfc")
            .arg(&command)
            .env("PATH", path_env)
            .output()
            .expect("run zsh shell snippet");

        assert!(
            output.status.success(),
            "stdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );

        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains(&format!("resolved:{}", fake_stax.display())),
            "expected zsh wrapper to resolve fake stax binary for worktree shell commands, got:\n{}",
            stdout
        );
        assert!(
            stdout.contains("args:worktree go demo-lane --shell-output"),
            "expected worktree shell command to preserve PATH and inject --shell-output, got:\n{}",
            stdout
        );
    }

    #[cfg(unix)]
    #[test]
    fn posix_shell_snippet_wraps_lane_commands_in_zsh() {
        use std::os::unix::fs::PermissionsExt;

        if let Err(err) = Command::new("zsh").arg("-dfc").arg("exit 0").output() {
            if err.kind() == ErrorKind::NotFound {
                return;
            }
            panic!("failed to probe zsh: {err}");
        }

        let dir = tempdir().expect("tempdir");
        let bin_dir = dir.path().join("bin");
        fs::create_dir_all(&bin_dir).expect("create bin dir");

        let fake_stax = bin_dir.join("stax");
        fs::write(
            &fake_stax,
            "#!/bin/sh\nprintf 'resolved:%s\\n' \"$0\"\nprintf 'args:%s\\n' \"$*\"\n",
        )
        .expect("write fake stax");
        let mut perms = fs::metadata(&fake_stax)
            .expect("fake stax metadata")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&fake_stax, perms).expect("chmod fake stax");

        let snippet_path = dir.path().join("shell-setup.sh");
        fs::write(&snippet_path, shell_snippet(ShellKind::Posix)).expect("write snippet");

        let original_path = std::env::var("PATH").unwrap_or_default();
        let path_env = format!("{}:{original_path}", bin_dir.display());
        let command = format!("source \"{}\"; st lane review-pass", snippet_path.display());
        let output = Command::new("zsh")
            .arg("-dfc")
            .arg(&command)
            .env("PATH", path_env)
            .output()
            .expect("run zsh shell snippet");

        assert!(
            output.status.success(),
            "stdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );

        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains(&format!("resolved:{}", fake_stax.display())),
            "expected zsh wrapper to resolve fake stax binary for lane commands, got:\n{}",
            stdout
        );
        assert!(
            stdout.contains("args:lane review-pass --shell-output"),
            "expected lane command to preserve PATH and inject --shell-output, got:\n{}",
            stdout
        );
    }

    #[cfg(unix)]
    #[test]
    fn posix_shell_snippet_wraps_checkout_commands_in_zsh() {
        use std::os::unix::fs::PermissionsExt;

        if let Err(err) = Command::new("zsh").arg("-dfc").arg("exit 0").output() {
            if err.kind() == ErrorKind::NotFound {
                return;
            }
            panic!("failed to probe zsh: {err}");
        }

        let dir = tempdir().expect("tempdir");
        let bin_dir = dir.path().join("bin");
        fs::create_dir_all(&bin_dir).expect("create bin dir");

        let fake_stax = bin_dir.join("stax");
        fs::write(
            &fake_stax,
            "#!/bin/sh\nprintf 'resolved:%s\\n' \"$0\"\nprintf 'args:%s\\n' \"$*\"\n",
        )
        .expect("write fake stax");
        let mut perms = fs::metadata(&fake_stax)
            .expect("fake stax metadata")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&fake_stax, perms).expect("chmod fake stax");

        let snippet_path = dir.path().join("shell-setup.sh");
        fs::write(&snippet_path, shell_snippet(ShellKind::Posix)).expect("write snippet");

        let original_path = std::env::var("PATH").unwrap_or_default();
        let path_env = format!("{}:{original_path}", bin_dir.display());
        let command = format!("source \"{}\"; st bco feature", snippet_path.display());
        let output = Command::new("zsh")
            .arg("-dfc")
            .arg(&command)
            .env("PATH", path_env)
            .output()
            .expect("run zsh shell snippet");

        assert!(
            output.status.success(),
            "stdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );

        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains(&format!("resolved:{}", fake_stax.display())),
            "expected zsh wrapper to resolve fake stax binary for checkout commands, got:\n{}",
            stdout
        );
        assert!(
            stdout.contains("args:bco feature --shell-output"),
            "expected checkout command to be wrapped with --shell-output, got:\n{}",
            stdout
        );
    }

    #[test]
    fn shell_source_line_uses_static_integration_file() {
        let line = shell_source_line(Path::new("/tmp/stax/shell-setup.sh"));
        assert_eq!(
            line,
            format!(
                "source \"/tmp/stax/shell-setup.sh\" # {}",
                INTEGRATION_MARKER
            )
        );
    }

    #[test]
    fn update_shell_config_replaces_legacy_eval_line() {
        let source_line = shell_source_line(Path::new("/tmp/stax/shell-setup.sh"));
        let existing = "export PATH=/usr/local/bin:$PATH\neval \"$(stax shell-setup)\"\n";

        let (updated, changed) = update_shell_config_contents(existing, &source_line);

        assert!(changed);
        assert_eq!(
            updated,
            format!("export PATH=/usr/local/bin:$PATH\n{}\n", source_line)
        );
    }

    #[test]
    fn update_shell_config_replaces_inline_posix_shell_block() {
        let source_line = shell_source_line(Path::new("/tmp/stax/shell-setup.sh"));
        let existing = r#"export PATH=/usr/local/bin:$PATH
# Static stax shell integration; avoid running `stax shell-setup` on every shell open.
if (( $+commands[stax] )); then
  export STAX_SHELL_INTEGRATION=1

  __stax_insert_shell_output() {
    printf '%s\0' "$@"
  }

  __stax_run_worktree_shell() {
    local raw
    raw=$(command stax "$@") || return $?
  }

  __stax_remove_current_worktree() {
    command stax "$@" "$current"
  }

  __stax_dispatch() {
    command stax "$@"
  }

  unalias stax 2>/dev/null || true
  unalias st 2>/dev/null || true
  unalias sw 2>/dev/null || true
  stax() { __stax_dispatch "$@"; }
  st() { __stax_dispatch "$@"; }
  sw() { st wt go "$@"; }
fi
"#;

        let (updated, changed) = update_shell_config_contents(existing, &source_line);

        assert!(changed);
        assert_eq!(
            updated,
            format!("export PATH=/usr/local/bin:$PATH\n{}\n", source_line)
        );
    }

    #[test]
    fn update_shell_config_is_idempotent_for_existing_source_line() {
        let source_line = shell_source_line(Path::new("/tmp/stax/shell-setup.sh"));
        let existing = format!("export PATH=/usr/local/bin:$PATH\n{}\n", source_line);

        let (updated, changed) = update_shell_config_contents(&existing, &source_line);

        assert!(!changed);
        assert_eq!(updated, existing);
    }

    #[test]
    fn refresh_generated_integration_file_rewrites_stale_generated_snippet() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("shell-setup.sh");
        fs::write(
            &path,
            "# Generated by stax shell-setup\ncommand stax old-wrapper\n",
        )
        .expect("write stale snippet");

        let refreshed = refresh_generated_integration_file(&path, shell_snippet(ShellKind::Posix))
            .expect("refresh snippet");

        assert!(refreshed);
        let updated = fs::read_to_string(&path).expect("read refreshed snippet");
        assert!(updated.contains("__stax_resolve_bin()"));
        assert!(!updated.contains("command stax old-wrapper"));
    }

    #[test]
    fn refresh_generated_integration_file_skips_non_generated_files() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("shell-setup.sh");
        fs::write(&path, "echo custom shell setup\n").expect("write custom snippet");

        let refreshed = refresh_generated_integration_file(&path, shell_snippet(ShellKind::Posix))
            .expect("refresh snippet");

        assert!(!refreshed);
        let updated = fs::read_to_string(&path).expect("read custom snippet");
        assert_eq!(updated, "echo custom shell setup\n");
    }
}