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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::remote::ForgeType;

/// Main config (safe to commit to dotfiles)
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Config {
    #[serde(default)]
    pub branch: BranchConfig,
    #[serde(default)]
    pub remote: RemoteConfig,
    #[serde(default)]
    pub submit: SubmitConfig,
    #[serde(default)]
    pub ci: CiConfig,
    #[serde(default)]
    pub ui: UiConfig,
    #[serde(default)]
    pub ai: AiConfig,
    #[serde(default)]
    pub auth: AuthConfig,
    #[serde(default)]
    pub worktree: WorktreeConfig,
    #[serde(default)]
    pub git: GitConfig,
    #[serde(default)]
    pub restack: RestackConfig,
}

#[derive(Debug, Deserialize, Default)]
struct TrustedNetworkRepoConfig {
    #[serde(default)]
    remote: TrustedNetworkRepoRemoteConfig,
}

#[derive(Debug, Deserialize, Default)]
struct TrustedNetworkRepoRemoteConfig {
    #[serde(default)]
    name: Option<String>,
}

/// User-configurable restack behaviour.
#[derive(Debug, Serialize, Deserialize)]
pub struct RestackConfig {
    /// Automatically use `merge-base(parent, branch)` as the rebase boundary
    /// when the stored `parentBranchRevision` would replay a much larger range
    /// (default: true).
    #[serde(default = "default_true")]
    pub preflight_auto_repair: bool,
    /// Print a non-fatal advisory before rebasing a branch when the stored
    /// `parentBranchRevision` would have forced git to replay a much larger range
    /// than `merge-base(parent, branch)` would (default: true).
    #[serde(default = "default_true")]
    pub preflight_warn: bool,
}

impl Default for RestackConfig {
    fn default() -> Self {
        Self {
            preflight_auto_repair: true,
            preflight_warn: true,
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BranchConfig {
    /// Prefix for new branches (e.g., "cesar/")
    /// DEPRECATED: Use `format` instead. Kept for backward compatibility.
    #[serde(default)]
    pub prefix: Option<String>,
    /// Whether to add date to branch names
    /// DEPRECATED: Use `format` instead. Kept for backward compatibility.
    #[serde(default)]
    pub date: bool,
    /// Date format string (default: "%m-%d", e.g., "01-19")
    /// Use chrono strftime format: %Y=year, %m=month, %d=day
    #[serde(default = "default_date_format")]
    pub date_format: String,
    /// Character to replace spaces and special chars (default: "-")
    #[serde(default = "default_replacement")]
    pub replacement: String,
    /// Branch name format template. Placeholders:
    /// - {user}: Git username (from config.branch.user or git user.name)
    /// - {date}: Current date (formatted by date_format)
    /// - {message}: The branch name/message input
    ///
    /// Examples: "{message}", "{user}/{message}", "{user}/{date}/{message}"
    #[serde(default)]
    pub format: Option<String>,
    /// Username for branch naming. If not set, uses git config user.name
    #[serde(default)]
    pub user: Option<String>,
    /// Number of days without commits before a branch is considered stale by `stax sweep` (default: 30)
    #[serde(default = "default_stale_days")]
    pub stale_days: u64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RemoteConfig {
    /// Git remote name (default: "origin")
    #[serde(default = "default_remote_name")]
    pub name: String,
    /// Base web URL for GitHub (e.g., https://github.com or GitHub Enterprise URL)
    #[serde(default = "default_remote_base_url")]
    pub base_url: String,
    /// API base URL (GitHub Enterprise), e.g., https://github.company.com/api/v3
    #[serde(default)]
    pub api_base_url: Option<String>,
    /// Explicit forge type override: "github", "gitlab", or "gitea" / "forgejo".
    /// When set, skips auto-detection from the remote hostname.
    #[serde(default)]
    pub forge: Option<ForgeType>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SubmitConfig {
    /// Where stax-managed stack links should be synced on submit.
    #[serde(default)]
    pub stack_links: StackLinksMode,
    /// Whether to register a native GitHub Stack via `gh stack` after submit.
    #[serde(default)]
    pub native_stack: NativeStackMode,
    /// Whether stax-managed stack links should still sync when native stack
    /// registration succeeds.
    #[serde(default)]
    pub stack_links_when_native: StackLinksWhenNative,
    /// Whether to sync stack links when the stack has only one PR.
    /// `On` (default) always syncs per `stack_links`. `Off` skips link sync
    /// (and cleans up stale links) while the stack has <= 1 PRs; once a 2nd
    /// PR exists, all PRs in the stack get links synced normally.
    #[serde(default)]
    pub single_stack: SingleStackMode,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct CiConfig {
    /// Play a sound when `stax ci --watch` exits after CI completion.
    #[serde(default)]
    pub alert: bool,
    /// Optional custom sound file for successful CI completion alerts.
    #[serde(default)]
    pub success_alert_sound: Option<String>,
    /// Optional custom sound file for failed CI completion alerts.
    #[serde(default)]
    pub error_alert_sound: Option<String>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum StackLinksMode {
    #[default]
    Comment,
    Body,
    Both,
    Off,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum NativeStackMode {
    Off,
    Link,
    #[default]
    Auto,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum StackLinksWhenNative {
    #[default]
    Keep,
    Off,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum SingleStackMode {
    #[default]
    On,
    Off,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UiConfig {
    /// Whether to show contextual tips/suggestions (default: true)
    #[serde(default = "default_tips")]
    pub tips: bool,
}

#[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct AiFeatureConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct AiConfig {
    /// AI agent to use: "claude", "codex", "gemini", or "opencode" (default: auto-detect)
    #[serde(default)]
    pub agent: Option<String>,
    /// Model to use with the AI agent (default: agent's own default)
    #[serde(default)]
    pub model: Option<String>,
    /// Per-feature overrides for create/PR generation (`stax create --ai`, `stax generate`, `stax submit --ai`)
    #[serde(default, skip_serializing_if = "AiFeatureConfig::is_empty")]
    pub generate: AiFeatureConfig,
    /// Per-feature overrides for standup summaries (`stax standup --ai`)
    #[serde(default, skip_serializing_if = "AiFeatureConfig::is_empty")]
    pub standup: AiFeatureConfig,
    /// Per-feature overrides for conflict resolution (`stax resolve`)
    #[serde(default, skip_serializing_if = "AiFeatureConfig::is_empty")]
    pub resolve: AiFeatureConfig,
    /// Per-feature overrides for interactive AI lanes (`stax lane`)
    #[serde(default, skip_serializing_if = "AiFeatureConfig::is_empty")]
    pub lane: AiFeatureConfig,
}

impl AiFeatureConfig {
    pub fn is_empty(&self) -> bool {
        self.agent.is_none() && self.model.is_none()
    }
}

impl AiConfig {
    /// Return a mutable reference to the per-feature config for `feature`.
    /// Returns `None` for unknown feature keys.
    pub fn feature_config_mut(&mut self, feature: &str) -> Option<&mut AiFeatureConfig> {
        match feature {
            "generate" => Some(&mut self.generate),
            "standup" => Some(&mut self.standup),
            "resolve" => Some(&mut self.resolve),
            "lane" => Some(&mut self.lane),
            _ => None,
        }
    }

    /// Resolve the agent for a given feature, falling back to the global default.
    pub fn agent_for(&self, feature: &str) -> Option<&str> {
        let feature_cfg = match feature {
            "generate" => &self.generate,
            "standup" => &self.standup,
            "resolve" => &self.resolve,
            "lane" => &self.lane,
            _ => return self.agent.as_deref(),
        };
        feature_cfg
            .agent
            .as_deref()
            .filter(|a| !a.is_empty())
            .or(self.agent.as_deref())
    }

    /// Resolve the model for a given feature, falling back to the global default.
    pub fn model_for(&self, feature: &str) -> Option<&str> {
        let feature_cfg = match feature {
            "generate" => &self.generate,
            "standup" => &self.standup,
            "resolve" => &self.resolve,
            "lane" => &self.lane,
            _ => return self.model.as_deref(),
        };
        feature_cfg
            .model
            .as_deref()
            .filter(|m| !m.is_empty())
            .or(self.model.as_deref())
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AuthConfig {
    /// Whether to use `gh auth token` as a fallback auth source (default: true)
    #[serde(default = "default_use_gh_cli")]
    pub use_gh_cli: bool,
    /// Whether to allow ambient GITHUB_TOKEN env var (default: false)
    #[serde(default = "default_allow_github_token_env")]
    pub allow_github_token_env: bool,
    /// Optional GitHub hostname for `gh auth token --hostname` (enterprise)
    #[serde(default)]
    pub gh_hostname: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WorktreeConfig {
    /// Directory for stax-managed worktrees. Empty means the default external root:
    /// ~/.stax/worktrees/<repo>.
    #[serde(default = "default_worktree_root_dir")]
    pub root_dir: String,
    /// Recycle removed worktrees as warm slots instead of deleting them, so a new
    /// lane can adopt an existing directory (keeping built gitignored deps) rather
    /// than a cold `git worktree add` (default: true).
    #[serde(default = "default_true")]
    pub reuse_slots: bool,
    /// Maximum number of idle warm slots to keep parked in the pool (default: 4).
    #[serde(default = "default_max_idle_slots")]
    pub max_idle_slots: usize,
    /// Optional command run (non-fatally) inside a worktree after it is adopted
    /// from the warm pool, to re-sync dependencies (e.g. "pnpm install").
    #[serde(default)]
    pub reconcile: Option<String>,
    #[serde(default)]
    pub hooks: WorktreeHooksConfig,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct WorktreeHooksConfig {
    /// Blocking hook run after creating a worktree and before launch
    #[serde(default)]
    pub post_create: Option<String>,
    /// Background hook run after a new worktree is ready
    #[serde(default)]
    pub post_start: Option<String>,
    /// Background hook run after jumping to an existing worktree
    #[serde(default)]
    pub post_go: Option<String>,
    /// Blocking hook run before removing a worktree
    #[serde(default)]
    pub pre_remove: Option<String>,
    /// Background hook run after removing a worktree
    #[serde(default)]
    pub post_remove: Option<String>,
}

impl Default for WorktreeConfig {
    fn default() -> Self {
        Self {
            root_dir: default_worktree_root_dir(),
            reuse_slots: true,
            max_idle_slots: default_max_idle_slots(),
            reconcile: None,
            hooks: WorktreeHooksConfig::default(),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GitConfig {
    /// Auto-enable git rerere on init (default: true)
    #[serde(default = "default_true")]
    pub rerere: bool,
}

impl Default for GitConfig {
    fn default() -> Self {
        Self { rerere: true }
    }
}

fn default_true() -> bool {
    true
}

fn default_max_idle_slots() -> usize {
    4
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitHubAuthSource {
    StaxGithubTokenEnv,
    CredentialsFile,
    GhCli,
    GithubTokenEnv,
}

impl GitHubAuthSource {
    pub fn display_name(self) -> &'static str {
        match self {
            Self::StaxGithubTokenEnv => "STAX_GITHUB_TOKEN",
            Self::CredentialsFile => "credentials file (~/.config/stax/.credentials)",
            Self::GhCli => "gh auth token",
            Self::GithubTokenEnv => "GITHUB_TOKEN",
        }
    }
}

#[derive(Debug, Clone)]
pub struct GitHubAuthStatus {
    pub active_source: Option<GitHubAuthSource>,
    pub stax_env_available: bool,
    pub credentials_file_available: bool,
    pub gh_cli_available: bool,
    pub github_env_available: bool,
    pub use_gh_cli: bool,
    pub allow_github_token_env: bool,
    pub gh_hostname: Option<String>,
}

impl Default for BranchConfig {
    fn default() -> Self {
        Self {
            prefix: None,
            date: false,
            date_format: default_date_format(),
            replacement: default_replacement(),
            format: None,
            user: None,
            stale_days: default_stale_days(),
        }
    }
}

fn default_date_format() -> String {
    "%m-%d".to_string()
}

fn default_stale_days() -> u64 {
    30
}

impl Default for RemoteConfig {
    fn default() -> Self {
        Self {
            name: default_remote_name(),
            base_url: default_remote_base_url(),
            api_base_url: None,
            forge: None,
        }
    }
}

impl Default for UiConfig {
    fn default() -> Self {
        Self {
            tips: default_tips(),
        }
    }
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            use_gh_cli: default_use_gh_cli(),
            allow_github_token_env: default_allow_github_token_env(),
            gh_hostname: None,
        }
    }
}

fn default_replacement() -> String {
    "-".to_string()
}

fn default_worktree_root_dir() -> String {
    String::new()
}

fn default_remote_name() -> String {
    "origin".to_string()
}

fn default_remote_base_url() -> String {
    "https://github.com".to_string()
}

fn default_tips() -> bool {
    true
}

fn default_use_gh_cli() -> bool {
    true
}

fn default_allow_github_token_env() -> bool {
    false
}

impl Config {
    /// Get the config directory.
    /// Default: `~/.config/stax` (Unix) or `C:\Users\<you>\.config\stax` (Windows).
    /// Override with `STAX_CONFIG_DIR` env var for testing or custom locations.
    pub fn dir() -> Result<PathBuf> {
        if let Ok(dir) = std::env::var("STAX_CONFIG_DIR") {
            return Ok(PathBuf::from(dir));
        }
        let home = std::env::var_os("HOME")
            .filter(|home| !home.is_empty())
            .map(PathBuf::from)
            .or_else(dirs::home_dir)
            .context("Could not find home directory")?;
        Ok(home.join(".config").join("stax"))
    }

    /// Get the config file path
    pub fn path() -> Result<PathBuf> {
        Ok(Self::dir()?.join("config.toml"))
    }

    /// Get the repo-local config file path when the current directory is inside
    /// a git repository and `stax.toml` exists at its root.
    fn repo_local_path() -> Result<Option<PathBuf>> {
        let Some(root) = git_root()? else {
            return Ok(None);
        };

        let path = root.join("stax.toml");
        Ok(path.exists().then_some(path))
    }

    /// Get the credentials file path (separate from config, not for dotfiles)
    fn credentials_path() -> Result<PathBuf> {
        Ok(Self::dir()?.join(".credentials"))
    }

    /// Ensure config exists, creating default if needed
    /// Call this once at startup
    pub fn ensure_exists() -> Result<()> {
        let path = Self::path()?;
        if !path.exists() {
            let config = Config::default();
            config.save()?;
        }
        Ok(())
    }

    /// Load config from file
    pub fn load() -> Result<Self> {
        let path = Self::path()?;
        if std::env::var("STAX_CONFIG_DIR").is_ok() {
            return Self::load_path_or_default(&path);
        }

        let config = Self::load_path_or_default(&path)?;
        if let Some(repo_path) = Self::repo_local_path()? {
            Self::load_with_overlay(config, &repo_path)
        } else {
            Ok(config)
        }
    }

    /// Load global config with the selected repository's `stax.toml` overlay.
    ///
    /// `STAX_CONFIG_DIR` intentionally keeps its existing test-isolation
    /// behavior and disables repository overlays.
    pub(crate) fn load_for_repo(root: &Path) -> Result<Self> {
        let path = Self::path()?;
        let config = Self::load_path_or_default(&path)?;
        if std::env::var("STAX_CONFIG_DIR").is_ok() {
            return Ok(config);
        }

        let repo_path = root.join("stax.toml");
        if repo_path.exists() {
            Self::load_with_overlay(config, &repo_path)
        } else {
            Ok(config)
        }
    }

    /// Load config for noninteractive credential-bearing repository network access.
    ///
    /// Repository-local config may select the non-secret Git remote name, but
    /// network destinations, provider selection, and auth settings are loaded
    /// only from the trusted global config.
    pub(crate) fn load_for_trusted_network(root: &Path) -> Result<Self> {
        let path = Self::path()?;
        let mut config = Self::load_path_or_default(&path)?;
        let repo_path = root.join("stax.toml");
        if !repo_path.exists() {
            return Ok(config);
        }

        let repo_content = fs::read_to_string(&repo_path)
            .with_context(|| format!("Failed to read repo config {}", repo_path.display()))?;
        let repo_config: TrustedNetworkRepoConfig = toml::from_str(&repo_content)
            .with_context(|| format!("Failed to parse repo config {}", repo_path.display()))?;
        if let Some(remote_name) = repo_config
            .remote
            .name
            .map(|name| name.trim().to_string())
            .filter(|name| !name.is_empty())
        {
            config.remote.name = remote_name;
        }
        Ok(config)
    }

    /// Load global config plus repository-local submit preferences only.
    ///
    /// Unlike the general repository overlay, this method ignores repository
    /// `remote.*`, `auth.*`, and provider/API settings so submit preferences
    /// cannot redirect trusted network endpoints.
    #[allow(dead_code)]
    pub(crate) fn load_repository_submit_preferences(root: &Path) -> Result<Self> {
        let path = Self::path()?;
        let mut config = Self::load_path_or_default(&path)?;
        let repo_path = root.join("stax.toml");
        if !repo_path.exists() {
            return Ok(config);
        }

        let repo_content = fs::read_to_string(&repo_path)
            .with_context(|| format!("Failed to read repo config {}", repo_path.display()))?;
        let repo_overlay: toml::Value = toml::from_str(&repo_content)
            .with_context(|| format!("Failed to parse repo config {}", repo_path.display()))?;
        let Some(submit_overlay) = repo_overlay.get("submit").cloned() else {
            return Ok(config);
        };

        let mut submit = toml::Value::try_from(config.submit.clone())?;
        merge_toml_values(&mut submit, submit_overlay);
        config.submit = submit.try_into()?;
        Ok(config)
    }

    fn load_path_or_default(path: &Path) -> Result<Self> {
        if path.exists() {
            let content = fs::read_to_string(path)?;
            let config: Config = toml::from_str(&content)?;
            Ok(config)
        } else {
            Ok(Config::default())
        }
    }

    fn load_with_overlay(config: Config, repo_path: &Path) -> Result<Self> {
        let mut base = toml::Value::try_from(config)?;
        let repo_content = fs::read_to_string(repo_path)
            .with_context(|| format!("Failed to read repo config {}", repo_path.display()))?;
        let repo_overlay: toml::Value = toml::from_str(&repo_content)
            .with_context(|| format!("Failed to parse repo config {}", repo_path.display()))?;
        merge_toml_values(&mut base, repo_overlay);
        Ok(base.try_into()?)
    }

    /// Save config to file
    pub fn save(&self) -> Result<()> {
        let path = Self::path()?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let content = toml::to_string_pretty(self)?;
        fs::write(&path, content)?;
        Ok(())
    }

    /// Clear any saved AI agent/model defaults so interactive commands can re-prompt.
    pub fn clear_ai_defaults(&mut self) -> bool {
        let had_saved_defaults = self.ai.agent.is_some()
            || self.ai.model.is_some()
            || !self.ai.generate.is_empty()
            || !self.ai.standup.is_empty()
            || !self.ai.resolve.is_empty()
            || !self.ai.lane.is_empty();
        self.ai.agent = None;
        self.ai.model = None;
        self.ai.generate = AiFeatureConfig::default();
        self.ai.standup = AiFeatureConfig::default();
        self.ai.resolve = AiFeatureConfig::default();
        self.ai.lane = AiFeatureConfig::default();
        had_saved_defaults
    }

    /// Get GitHub token (from env var, credentials file, or gh cli)
    /// Priority:
    /// 1. STAX_GITHUB_TOKEN
    /// 2. credentials file (~/.config/stax/.credentials)
    /// 3. gh auth token (if auth.use_gh_cli = true)
    /// 4. GITHUB_TOKEN (if auth.allow_github_token_env = true)
    pub fn github_token() -> Option<String> {
        let auth_config = Self::load().map(|c| c.auth).unwrap_or_default();
        Self::resolve_github_auth_with_config(&auth_config).map(|(_, token)| token)
    }

    /// Like `github_token` but also returns the source for error messages.
    pub fn github_token_with_source() -> Option<(GitHubAuthSource, String)> {
        let auth_config = Self::load().map(|c| c.auth).unwrap_or_default();
        Self::resolve_github_auth_with_config(&auth_config)
    }

    /// Resolve GitHub auth for a validated trusted network destination.
    ///
    /// The gh CLI lookup is always scoped to the validated Git remote host. An
    /// explicitly configured global hostname must match before gh is executed.
    pub(crate) fn github_token_with_source_for_host(
        &self,
        validated_host: &str,
    ) -> Result<Option<(GitHubAuthSource, String)>> {
        if self
            .auth
            .gh_hostname
            .as_deref()
            .and_then(Self::normalize_token)
            .is_some_and(|configured| !configured.eq_ignore_ascii_case(validated_host))
        {
            anyhow::bail!(
                "Configured GitHub auth hostname does not match the validated Git remote \
                 hostname; update global auth.gh_hostname before noninteractive repository network access"
            );
        }

        if let Some(token) = Self::read_env_token("STAX_GITHUB_TOKEN") {
            return Ok(Some((GitHubAuthSource::StaxGithubTokenEnv, token)));
        }

        if let Some(token) = Self::token_from_credentials_file() {
            return Ok(Some((GitHubAuthSource::CredentialsFile, token)));
        }

        if self.auth.use_gh_cli {
            if let Some(token) = Self::token_from_gh_cli(Some(validated_host))? {
                return Ok(Some((GitHubAuthSource::GhCli, token)));
            }
        }

        if self.auth.allow_github_token_env {
            if let Some(token) = Self::read_env_token("GITHUB_TOKEN") {
                return Ok(Some((GitHubAuthSource::GithubTokenEnv, token)));
            }
        }

        Ok(None)
    }

    /// Get the saved credentials-file token written by `stax auth`.
    ///
    /// This stored token is forge-agnostic and can be reused across GitHub,
    /// GitLab, and Gitea when forge-specific env vars are not set.
    pub fn saved_forge_token() -> Option<String> {
        Self::token_from_credentials_file()
    }

    pub fn github_auth_status() -> GitHubAuthStatus {
        let auth_config = Self::load().map(|c| c.auth).unwrap_or_default();

        let stax_env_available = Self::read_env_token("STAX_GITHUB_TOKEN").is_some();
        let credentials_file_available = Self::token_from_credentials_file().is_some();
        let gh_cli_available = if auth_config.use_gh_cli {
            Self::token_from_gh_cli(auth_config.gh_hostname.as_deref())
                .ok()
                .flatten()
                .is_some()
        } else {
            false
        };
        let github_env_available = Self::read_env_token("GITHUB_TOKEN").is_some();

        let active_source = if stax_env_available {
            Some(GitHubAuthSource::StaxGithubTokenEnv)
        } else if credentials_file_available {
            Some(GitHubAuthSource::CredentialsFile)
        } else if auth_config.use_gh_cli && gh_cli_available {
            Some(GitHubAuthSource::GhCli)
        } else if auth_config.allow_github_token_env && github_env_available {
            Some(GitHubAuthSource::GithubTokenEnv)
        } else {
            None
        };

        GitHubAuthStatus {
            active_source,
            stax_env_available,
            credentials_file_available,
            gh_cli_available,
            github_env_available,
            use_gh_cli: auth_config.use_gh_cli,
            allow_github_token_env: auth_config.allow_github_token_env,
            gh_hostname: auth_config.gh_hostname,
        }
    }

    /// Set the saved API token (to credentials file)
    pub fn set_github_token(token: &str) -> Result<()> {
        let path = Self::credentials_path()?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&path, token)?;

        // Set restrictive permissions on Unix
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(0o600);
            fs::set_permissions(&path, perms)?;
        }

        Ok(())
    }

    /// Read token from gh CLI for explicit import (`stax auth --from-gh`).
    pub fn gh_cli_token_for_import() -> Result<String> {
        let auth_config = Self::load().map(|c| c.auth).unwrap_or_default();

        Self::token_from_gh_cli(auth_config.gh_hostname.as_deref())?.context(
            "Could not read token from `gh auth token`.\n\
             Ensure GitHub CLI is installed and authenticated (`gh auth login`).",
        )
    }

    fn read_env_token(var_name: &str) -> Option<String> {
        std::env::var(var_name)
            .ok()
            .and_then(|value| Self::normalize_token(value.as_str()))
    }

    fn token_from_credentials_file() -> Option<String> {
        let path = Self::credentials_path().ok()?;
        let token = fs::read_to_string(path).ok()?;
        Self::normalize_token(token.as_str())
    }

    fn token_from_gh_cli(hostname: Option<&str>) -> Result<Option<String>> {
        let mut command = Command::new("gh");
        command.args(["auth", "token"]);
        if let Some(host) = hostname.and_then(Self::normalize_token) {
            command.args(["--hostname", host.as_str()]);
        }

        let output = match command.output() {
            Ok(output) => output,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(err) => return Err(err).context("Failed to execute `gh auth token`"),
        };

        if !output.status.success() {
            return Ok(None);
        }

        let token = String::from_utf8_lossy(&output.stdout);
        Ok(Self::normalize_token(token.as_ref()))
    }

    fn normalize_token(token: &str) -> Option<String> {
        let trimmed = token.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    }

    fn resolve_github_auth_with_config(
        auth_config: &AuthConfig,
    ) -> Option<(GitHubAuthSource, String)> {
        if let Some(token) = Self::read_env_token("STAX_GITHUB_TOKEN") {
            return Some((GitHubAuthSource::StaxGithubTokenEnv, token));
        }

        if let Some(token) = Self::token_from_credentials_file() {
            return Some((GitHubAuthSource::CredentialsFile, token));
        }

        if auth_config.use_gh_cli {
            if let Ok(Some(token)) = Self::token_from_gh_cli(auth_config.gh_hostname.as_deref()) {
                return Some((GitHubAuthSource::GhCli, token));
            }
        }

        if auth_config.allow_github_token_env {
            if let Some(token) = Self::read_env_token("GITHUB_TOKEN") {
                return Some((GitHubAuthSource::GithubTokenEnv, token));
            }
        }

        None
    }

    /// Format a branch name according to config settings
    pub fn format_branch_name(&self, name: &str) -> String {
        self.format_branch_name_with_prefix_override(name, None)
    }

    /// Format a branch name, optionally overriding the configured prefix
    pub fn format_branch_name_with_prefix_override(
        &self,
        name: &str,
        prefix_override: Option<&str>,
    ) -> String {
        // Sanitize the message/name first
        let sanitized_name = self.sanitize_branch_segment(name);

        // If format template is set, use it (new behavior)
        if let Some(ref format_template) = self.branch.format {
            if !format_template.contains("{message}") {
                eprintln!(
                    "Warning: branch.format template is missing {{message}} placeholder. \
                     The branch name input will not appear in the generated name."
                );
            }
            return self.apply_format_template(format_template, &sanitized_name, prefix_override);
        }

        // Legacy behavior: use prefix/date fields for backward compatibility
        let replacement = &self.branch.replacement;
        let mut result = sanitized_name;

        // Add date if enabled (legacy, preserves original %Y-%m-%d format)
        if self.branch.date {
            let date = chrono::Local::now().format("%Y-%m-%d").to_string();
            result = format!("{}{}{}", date, replacement, result);
        }

        let prefix = if let Some(override_prefix) = prefix_override {
            let trimmed = override_prefix.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(Self::normalize_prefix_override(trimmed))
            }
        } else {
            self.branch.prefix.clone()
        };

        if let Some(prefix) = prefix {
            if !result.starts_with(&prefix) {
                result = format!("{}{}", prefix, result);
            }
        }

        result
    }

    /// Apply the format template to create a branch name
    fn apply_format_template(
        &self,
        template: &str,
        message: &str,
        prefix_override: Option<&str>,
    ) -> String {
        let mut result = template.to_string();

        // Replace {message} placeholder
        result = result.replace("{message}", message);

        // Replace {date} placeholder if present
        if result.contains("{date}") {
            let date = chrono::Local::now()
                .format(&self.branch.date_format)
                .to_string();
            result = result.replace("{date}", &date);
        }

        // Replace {user} placeholder if present
        if result.contains("{user}") {
            let user = self.get_user_for_branch();
            result = result.replace("{user}", &user);
        }

        // Clean up empty segments: collapse repeated separators and trim leading/trailing ones
        // This handles cases where {user} resolves to "" (e.g., "/02-11/msg" -> "02-11/msg")
        while result.contains("//") {
            result = result.replace("//", "/");
        }
        result = result.trim_matches('/').to_string();

        // Handle prefix override (for -p flag compatibility)
        if let Some(override_prefix) = prefix_override {
            let trimmed = override_prefix.trim();
            if !trimmed.is_empty() {
                let normalized = Self::normalize_prefix_override(trimmed);
                if !result.starts_with(&normalized) {
                    result = format!("{}{}", normalized, result);
                }
            }
        }

        result
    }

    /// Sanitize a segment of the branch name (replace special chars, collapse duplicates)
    fn sanitize_branch_segment(&self, segment: &str) -> String {
        let replacement = &self.branch.replacement;

        let mut result: String = segment
            .chars()
            .map(|c| {
                if c.is_alphanumeric() || c == '-' || c == '_' || c == '/' {
                    c
                } else {
                    replacement.chars().next().unwrap_or('-')
                }
            })
            .collect();

        // Replace multiple consecutive replacements with single one
        while result.contains(&format!("{}{}", replacement, replacement)) {
            result = result.replace(&format!("{}{}", replacement, replacement), replacement);
        }

        // Trim leading/trailing replacement chars
        let replacement_char = replacement.chars().next().unwrap_or('-');
        result = result
            .trim_start_matches(replacement_char)
            .trim_end_matches(replacement_char)
            .to_string();

        result
    }

    /// Get the username for branch naming
    /// Priority: 1. config.branch.user (explicit empty disables fallback),
    /// 2. git config user.name, 3. empty string
    fn get_user_for_branch(&self) -> String {
        // First check config
        if let Some(ref user) = self.branch.user {
            if user.is_empty() {
                return String::new();
            }
            return self.sanitize_branch_segment(user);
        }

        // Then try git config user.name
        if let Ok(output) = std::process::Command::new("git")
            .args(["config", "user.name"])
            .output()
        {
            if output.status.success() {
                let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if !name.is_empty() {
                    return self.sanitize_branch_segment(&name);
                }
            }
        }

        // Fallback to empty
        String::new()
    }

    fn normalize_prefix_override(prefix: &str) -> String {
        if prefix.ends_with('/') || prefix.ends_with('-') || prefix.ends_with('_') {
            prefix.to_string()
        } else {
            format!("{}/", prefix)
        }
    }

    pub fn remote_name(&self) -> &str {
        self.remote.name.as_str()
    }

    pub fn remote_base_url(&self) -> &str {
        self.remote.base_url.as_str()
    }

    pub fn remote_forge_override(&self) -> Option<ForgeType> {
        self.remote.forge
    }
}

fn git_root() -> Result<Option<PathBuf>> {
    Ok(git2::Repository::discover(".")
        .ok()
        .and_then(|repo| repo.workdir().map(PathBuf::from)))
}

fn merge_toml_values(base: &mut toml::Value, overlay: toml::Value) {
    match (base, overlay) {
        (toml::Value::Table(base_table), toml::Value::Table(overlay_table)) => {
            for (key, value) in overlay_table {
                match base_table.get_mut(&key) {
                    Some(base_value) => merge_toml_values(base_value, value),
                    None => {
                        base_table.insert(key, value);
                    }
                }
            }
        }
        (base_value, overlay_value) => {
            *base_value = overlay_value;
        }
    }
}

#[cfg(test)]
mod tests;