kono-wt 1.8.1

A single-binary CLI + TUI for managing Git worktrees and their GitHub pull requests.
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
//! The resolved [`Config`] and the per-layer [`ConfigLayer`], plus the merge
//! semantics (spec ยง11).

#[cfg(feature = "tui")]
use ratatui::style::Color;

use crate::agent::{AgentKind, AgentModel, Effort};
use crate::cx::Env;
#[cfg(feature = "tui")]
use crate::keys::{KeyAction, KeyChord, Keymap};
use crate::model::Column;
use crate::output::color::{ColorChoice, resolve_color};
use crate::template::DEFAULT_TEMPLATE;
#[cfg(feature = "tui")]
use crate::tui::theme::{Palette, ThemePreset};

/// When to initialize git submodules after a worktree is created or a branch is
/// checked out (`[submodules] init`, issue #50). The default ([`Prompt`]) asks
/// before initializing at an interactive terminal; `always`/`never` decide
/// without a prompt.
///
/// [`Prompt`]: SubmoduleInit::Prompt
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SubmoduleInit {
    /// Ask before initializing (the default): at an interactive terminal, prompt
    /// `[Y/n]` (defaulting to yes) when uninitialized submodules are present;
    /// non-interactively, leave them alone.
    #[default]
    Prompt,
    /// Never initialize submodules automatically.
    Never,
    /// Always run `git submodule update --init --recursive` when uninitialized
    /// submodules are present.
    Always,
}

impl SubmoduleInit {
    /// Parses a `submodules.init` value (`prompt`, `never`, `always`).
    pub fn parse(value: &str) -> Option<SubmoduleInit> {
        match value {
            "prompt" => Some(SubmoduleInit::Prompt),
            "never" => Some(SubmoduleInit::Never),
            "always" => Some(SubmoduleInit::Always),
            _ => None,
        }
    }

    /// The config identifier this policy round-trips through.
    pub fn identifier(self) -> &'static str {
        match self {
            SubmoduleInit::Prompt => "prompt",
            SubmoduleInit::Never => "never",
            SubmoduleInit::Always => "always",
        }
    }
}

/// Whether to populate a new worktree's submodules from the repository's own
/// local object stores instead of re-cloning them (`[submodules] seed`).
///
/// A linked worktree does not share `.git/modules`, so initializing submodules
/// in one normally re-clones every submodule over the network. Seeding clones
/// from those existing mirrors instead, which hardlinks the objects.
///
/// Seeding never changes the outcome, only the cost: it is always followed by a
/// stock `git submodule update --init --recursive`, so anything it skips or gets
/// wrong is reconciled by git itself. That is why [`Auto`] is the default.
///
/// [`Auto`]: SubmoduleSeed::Auto
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SubmoduleSeed {
    /// Seed from a local mirror whenever one exists (the default).
    #[default]
    Auto,
    /// Never seed; always let git clone submodules from their remotes.
    Never,
}

impl SubmoduleSeed {
    /// Parses a `submodules.seed` value (`auto`, `never`).
    pub fn parse(value: &str) -> Option<SubmoduleSeed> {
        match value {
            "auto" => Some(SubmoduleSeed::Auto),
            "never" => Some(SubmoduleSeed::Never),
            _ => None,
        }
    }

    /// Whether seeding is enabled.
    pub fn is_enabled(self) -> bool {
        matches!(self, SubmoduleSeed::Auto)
    }

    /// The config identifier this strategy round-trips through.
    pub fn identifier(self) -> &'static str {
        match self {
            SubmoduleSeed::Auto => "auto",
            SubmoduleSeed::Never => "never",
        }
    }
}

/// Whether to materialize a new worktree by copy-on-write cloning an existing
/// one's files instead of checking them out (`[create] reflink`).
///
/// On a CoW filesystem (btrfs, XFS with `reflink=1`, APFS, ReFS) this shares the
/// extents of every file, so a new worktree of a large repository costs almost
/// no disk and almost no writing. It also carries the source's ignored build
/// output along, which is usually the point and occasionally not. The source's
/// untracked files are left behind, so the new worktree still comes up clean and
/// [`Config::copy`] still governs which non-tracked files travel.
///
/// Off by default: it only pays off on a CoW filesystem, and copying a source's
/// ignored files is a bigger behavioural change than seeding.
/// `auto` uses it when the filesystem supports it and a source worktree is
/// already at the same tree, and silently checks out normally otherwise.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CreateReflink {
    /// Never clone; always check out (the default).
    #[default]
    Never,
    /// Clone when the filesystem and the source worktree allow it.
    Auto,
}

impl CreateReflink {
    /// Parses a `create.reflink` value (`auto`, `never`).
    pub fn parse(value: &str) -> Option<CreateReflink> {
        match value {
            "auto" => Some(CreateReflink::Auto),
            "never" => Some(CreateReflink::Never),
            _ => None,
        }
    }

    /// Whether copy-on-write materialization is enabled.
    pub fn is_enabled(self) -> bool {
        matches!(self, CreateReflink::Auto)
    }

    /// The config identifier this strategy round-trips through.
    pub fn identifier(self) -> &'static str {
        match self {
            CreateReflink::Auto => "auto",
            CreateReflink::Never => "never",
        }
    }
}

/// The generation agent profile (`[agent.generation]`): which agent `wt` drives
/// for the short, structured generation steps it owns โ€” the PR auto-fill and
/// the `wt issue` branch/brief proposal.
///
/// `wt` owns *generation* only. Running a coding agent on the work itself is
/// karet's job, which is why there is no work profile here and why
/// `[agent.work]` is rejected with a pointer to karet.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GenerationAgentConfig {
    /// Which agent CLI to drive.
    pub provider: AgentKind,
    /// The model to request.
    pub model: AgentModel,
    /// The reasoning effort to request.
    pub effort: Effort,
}

impl Default for GenerationAgentConfig {
    fn default() -> Self {
        // Unchanged from the flat `[agent]` defaults these keys replace, so
        // `wt pr open --ai` behaves identically before and after the move.
        GenerationAgentConfig {
            provider: AgentKind::Claude,
            model: AgentModel::default(),
            effort: Effort::default(),
        }
    }
}

/// The fully-resolved configuration after merging all layers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    /// Worktree-store path template (spec ยง6).
    pub path_template: String,
    /// Base ref for `new` when a branch is created; `None` resolves the repo's
    /// default branch at runtime.
    pub default_base: Option<String>,
    /// Glob patterns to copy into new worktrees (spec ยง8).
    pub copy: Vec<String>,
    /// Shell command run after worktree creation.
    pub hooks_post_create: Option<String>,
    /// Shell command run before worktree removal.
    pub hooks_pre_remove: Option<String>,
    /// Editor command; `None` falls back to `$VISUAL`/`$EDITOR`.
    pub editor: Option<String>,
    /// Delete a wt-created branch on `remove` if fully merged.
    pub remove_delete_merged_branch: bool,
    /// Whether untracked files count as dirty for the remove guard. Prune always
    /// counts them.
    pub remove_untracked_blocks: bool,
    /// Remote used for PR fetches.
    pub pr_default_remote: String,
    /// When to auto-initialize git submodules on create/checkout (issue #50).
    pub submodules_init: SubmoduleInit,
    /// Whether to seed a new worktree's submodules from the repository's own
    /// local object stores instead of re-cloning them.
    pub submodules_seed: SubmoduleSeed,
    /// Whether to copy-on-write clone a new worktree's content from an existing
    /// worktree instead of checking it out.
    pub create_reflink: CreateReflink,
    /// The generation agent profile (`[agent.generation]`), used by the AI PR
    /// auto-fill (`wt pr open --ai`) and by `wt issue`. Model and effort are
    /// overridable per-invocation by `--model`/`--effort` or the TUI's
    /// `Ctrl-M`/`Ctrl-E` keys.
    pub agent_generation: GenerationAgentConfig,
    /// Show `?` in the dirty column for untracked files.
    pub list_show_untracked: bool,
    /// Ordered list of columns to display in `wt list`.
    pub list_columns: Vec<Column>,
    /// Enable Nerd Font glyphs in the TUI.
    pub ui_nerd_fonts: bool,
    /// Enable mouse support in the TUI.
    pub ui_mouse: bool,
    /// Color output setting (reconciled with `--color`/`NO_COLOR`).
    pub ui_color: ColorChoice,
    /// Built-in theme preset (the base TUI palette).
    #[cfg(feature = "tui")]
    pub ui_theme: ThemePreset,
    /// Per-color overrides layered on top of the preset (`[ui.theme]`).
    #[cfg(feature = "tui")]
    pub theme_overrides: ThemeOverrides,
    /// Accumulated `ui.keybindings` overrides (applied over the defaults).
    #[cfg(feature = "tui")]
    pub keybinding_overrides: Vec<(KeyAction, KeyChord)>,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            path_template: DEFAULT_TEMPLATE.to_string(),
            default_base: None,
            copy: Vec::new(),
            hooks_post_create: None,
            hooks_pre_remove: None,
            editor: None,
            remove_delete_merged_branch: true,
            remove_untracked_blocks: false,
            pr_default_remote: "origin".to_string(),
            submodules_init: SubmoduleInit::default(),
            submodules_seed: SubmoduleSeed::default(),
            create_reflink: CreateReflink::default(),
            agent_generation: GenerationAgentConfig::default(),
            list_show_untracked: true,
            list_columns: Column::ALL.to_vec(),
            ui_nerd_fonts: false,
            ui_mouse: true,
            ui_color: ColorChoice::Auto,
            #[cfg(feature = "tui")]
            ui_theme: ThemePreset::default(),
            #[cfg(feature = "tui")]
            theme_overrides: ThemeOverrides::default(),
            #[cfg(feature = "tui")]
            keybinding_overrides: Vec::new(),
        }
    }
}

impl Config {
    /// Applies a parsed layer on top of this config (spec ยง11 merge semantics):
    /// scalars replace, arrays (`copy`, `list.columns`) replace wholesale,
    /// `ui.keybindings` deep-merges per action, and the `[ui.theme]` colors
    /// deep-merge per slot (the `preset` is a scalar). Overrides accumulate in
    /// apply order, so a later layer wins.
    pub fn apply(&mut self, layer: ConfigLayer) {
        if let Some(v) = layer.path_template {
            self.path_template = v;
        }
        if let Some(v) = layer.default_base {
            self.default_base = Some(v);
        }
        if let Some(v) = layer.copy {
            self.copy = v;
        }
        if let Some(v) = layer.editor {
            self.editor = Some(v);
        }
        if let Some(v) = layer.hooks_post_create {
            self.hooks_post_create = Some(v);
        }
        if let Some(v) = layer.hooks_pre_remove {
            self.hooks_pre_remove = Some(v);
        }
        if let Some(v) = layer.remove_delete_merged_branch {
            self.remove_delete_merged_branch = v;
        }
        if let Some(v) = layer.remove_untracked_blocks {
            self.remove_untracked_blocks = v;
        }
        if let Some(v) = layer.pr_default_remote {
            self.pr_default_remote = v;
        }
        if let Some(v) = layer.submodules_init {
            self.submodules_init = v;
        }
        if let Some(v) = layer.submodules_seed {
            self.submodules_seed = v;
        }
        if let Some(v) = layer.create_reflink {
            self.create_reflink = v;
        }
        if let Some(v) = layer.agent_generation_provider {
            self.agent_generation.provider = v;
        }
        if let Some(v) = layer.agent_generation_model {
            self.agent_generation.model = v;
        }
        if let Some(v) = layer.agent_generation_effort {
            self.agent_generation.effort = v;
        }
        if let Some(v) = layer.list_show_untracked {
            self.list_show_untracked = v;
        }
        if let Some(v) = layer.list_columns {
            self.list_columns = v;
        }
        if let Some(v) = layer.ui_nerd_fonts {
            self.ui_nerd_fonts = v;
        }
        if let Some(v) = layer.ui_mouse {
            self.ui_mouse = v;
        }
        if let Some(v) = layer.ui_color {
            self.ui_color = v;
        }
        #[cfg(feature = "tui")]
        {
            if let Some(v) = layer.ui_theme {
                self.ui_theme = v;
            }
            self.theme_overrides.merge(layer.theme_overrides);
            self.keybinding_overrides.extend(layer.ui_keybindings);
        }
    }

    /// Resolves the effective TUI [`Palette`]: the selected preset's base palette
    /// with any `[ui.theme]` per-color overrides applied on top.
    #[cfg(feature = "tui")]
    pub fn palette(&self) -> Palette {
        let mut palette = self.ui_theme.palette();
        self.theme_overrides.apply_to(&mut palette);
        palette
    }

    /// Builds the effective TUI keymap: the defaults with the configured
    /// overrides applied in order.
    #[cfg(feature = "tui")]
    pub fn keymap(&self) -> Keymap {
        let mut keymap = Keymap::defaults();
        for (action, chord) in &self.keybinding_overrides {
            keymap.rebind(*action, *chord);
        }
        keymap
    }

    /// Resolves whether to emit color, reconciling the `--color` flag, the
    /// `NO_COLOR` env var, and `ui.color` (spec ยง11 precedence).
    pub fn color_enabled(&self, flag: Option<ColorChoice>, env: &Env, stdout_is_tty: bool) -> bool {
        resolve_color(
            flag,
            env.is_set_nonempty("NO_COLOR"),
            Some(self.ui_color),
            stdout_is_tty,
        )
    }
}

/// One configuration layer (a single file's settings, or flags); every field is
/// optional and only present keys override lower layers.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConfigLayer {
    /// `path_template`.
    pub path_template: Option<String>,
    /// `default_base`.
    pub default_base: Option<String>,
    /// `copy`.
    pub copy: Option<Vec<String>>,
    /// `editor`.
    pub editor: Option<String>,
    /// `hooks.post_create`.
    pub hooks_post_create: Option<String>,
    /// `hooks.pre_remove`.
    pub hooks_pre_remove: Option<String>,
    /// `remove.delete_merged_branch`.
    pub remove_delete_merged_branch: Option<bool>,
    /// `remove.untracked_blocks`.
    pub remove_untracked_blocks: Option<bool>,
    /// `pr.default_remote`.
    pub pr_default_remote: Option<String>,
    /// `submodules.init`.
    pub submodules_init: Option<SubmoduleInit>,
    /// `submodules.seed`.
    pub submodules_seed: Option<SubmoduleSeed>,
    /// `create.reflink`.
    pub create_reflink: Option<CreateReflink>,
    /// `agent.generation.provider`.
    pub agent_generation_provider: Option<AgentKind>,
    /// `agent.generation.model`, or its deprecated `agent.model` alias.
    pub agent_generation_model: Option<AgentModel>,
    /// `agent.generation.effort`, or its deprecated `agent.effort` alias.
    pub agent_generation_effort: Option<Effort>,
    /// `list.show_untracked`.
    pub list_show_untracked: Option<bool>,
    /// `list.columns`.
    pub list_columns: Option<Vec<Column>>,
    /// `ui.nerd_fonts`.
    pub ui_nerd_fonts: Option<bool>,
    /// `ui.mouse`.
    pub ui_mouse: Option<bool>,
    /// `ui.color`.
    pub ui_color: Option<ColorChoice>,
    /// `ui.theme.preset`.
    #[cfg(feature = "tui")]
    pub ui_theme: Option<ThemePreset>,
    /// `[ui.theme]` per-color overrides present in this layer.
    #[cfg(feature = "tui")]
    pub theme_overrides: ThemeOverrides,
    /// `ui.keybindings` (action โ†’ chord) overrides.
    #[cfg(feature = "tui")]
    pub ui_keybindings: Vec<(KeyAction, KeyChord)>,
}

/// Per-color overrides for the TUI palette (`[ui.theme]`). Each field mirrors a
/// [`Palette`] slot; `None` leaves the preset's color untouched.
#[cfg(feature = "tui")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ThemeOverrides {
    /// `ui.theme.accent`.
    pub accent: Option<Color>,
    /// `ui.theme.green`.
    pub green: Option<Color>,
    /// `ui.theme.red`.
    pub red: Option<Color>,
    /// `ui.theme.yellow`.
    pub yellow: Option<Color>,
    /// `ui.theme.orange`.
    pub orange: Option<Color>,
    /// `ui.theme.cyan`.
    pub cyan: Option<Color>,
    /// `ui.theme.magenta`.
    pub magenta: Option<Color>,
    /// `ui.theme.gray`.
    pub gray: Option<Color>,
    /// `ui.theme.selection_bg`.
    pub selection_bg: Option<Color>,
    /// `ui.theme.chip_fg`.
    pub chip_fg: Option<Color>,
}

#[cfg(feature = "tui")]
impl ThemeOverrides {
    /// Merges another layer's overrides on top of these (set slots win).
    pub fn merge(&mut self, other: ThemeOverrides) {
        self.accent = other.accent.or(self.accent);
        self.green = other.green.or(self.green);
        self.red = other.red.or(self.red);
        self.yellow = other.yellow.or(self.yellow);
        self.orange = other.orange.or(self.orange);
        self.cyan = other.cyan.or(self.cyan);
        self.magenta = other.magenta.or(self.magenta);
        self.gray = other.gray.or(self.gray);
        self.selection_bg = other.selection_bg.or(self.selection_bg);
        self.chip_fg = other.chip_fg.or(self.chip_fg);
    }

    /// Applies the set overrides onto a base [`Palette`].
    fn apply_to(&self, palette: &mut Palette) {
        if let Some(c) = self.accent {
            palette.accent = c;
        }
        if let Some(c) = self.green {
            palette.green = c;
        }
        if let Some(c) = self.red {
            palette.red = c;
        }
        if let Some(c) = self.yellow {
            palette.yellow = c;
        }
        if let Some(c) = self.orange {
            palette.orange = c;
        }
        if let Some(c) = self.cyan {
            palette.cyan = c;
        }
        if let Some(c) = self.magenta {
            palette.magenta = c;
        }
        if let Some(c) = self.gray {
            palette.gray = c;
        }
        if let Some(c) = self.selection_bg {
            palette.selection_bg = c;
        }
        if let Some(c) = self.chip_fg {
            palette.chip_fg = c;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "tui")]
    use crossterm::event::KeyCode;

    #[test]
    fn defaults_match_spec() {
        let c = Config::default();
        assert_eq!(c.path_template, DEFAULT_TEMPLATE);
        assert!(c.default_base.is_none());
        assert!(c.copy.is_empty());
        assert!(c.remove_delete_merged_branch);
        assert!(!c.remove_untracked_blocks);
        assert_eq!(c.pr_default_remote, "origin");
        assert_eq!(c.submodules_init, SubmoduleInit::Prompt);
        assert_eq!(c.agent_generation.provider, AgentKind::Claude);
        assert_eq!(c.agent_generation.model, AgentModel::Sonnet);
        assert_eq!(c.agent_generation.effort, Effort::Medium);
        assert!(c.list_show_untracked);
        assert_eq!(c.list_columns, Column::ALL.to_vec());
        assert!(!c.ui_nerd_fonts);
        assert!(c.ui_mouse);
        assert_eq!(c.ui_color, ColorChoice::Auto);
    }

    #[test]
    fn scalars_replace_on_apply() {
        let mut c = Config::default();
        c.apply(ConfigLayer {
            pr_default_remote: Some("upstream".into()),
            ui_mouse: Some(false),
            ..Default::default()
        });
        assert_eq!(c.pr_default_remote, "upstream");
        assert!(!c.ui_mouse);
        // Untouched fields keep their defaults.
        assert!(c.list_show_untracked);
    }

    #[test]
    fn arrays_replace_wholesale() {
        let mut c = Config::default();
        c.apply(ConfigLayer {
            copy: Some(vec![".env".into()]),
            list_columns: Some(vec![Column::Branch, Column::Pr]),
            ..Default::default()
        });
        assert_eq!(c.copy, vec![".env".to_string()]);
        assert_eq!(c.list_columns, vec![Column::Branch, Column::Pr]);
        // A second layer replaces, not concatenates.
        c.apply(ConfigLayer {
            copy: Some(vec![".envrc".into()]),
            ..Default::default()
        });
        assert_eq!(c.copy, vec![".envrc".to_string()]);
    }

    #[test]
    fn apply_sets_every_scalar_and_optional_field() {
        let mut c = Config::default();
        c.apply(ConfigLayer {
            path_template: Some("{home}/{branch_slug}".into()),
            default_base: Some("trunk".into()),
            editor: Some("hx".into()),
            hooks_post_create: Some("setup".into()),
            hooks_pre_remove: Some("teardown".into()),
            remove_delete_merged_branch: Some(false),
            remove_untracked_blocks: Some(true),
            submodules_init: Some(SubmoduleInit::Always),
            agent_generation_model: Some(AgentModel::Haiku),
            agent_generation_effort: Some(Effort::Low),
            list_show_untracked: Some(false),
            ui_nerd_fonts: Some(true),
            ui_color: Some(ColorChoice::Never),
            ..Default::default()
        });
        assert_eq!(c.path_template, "{home}/{branch_slug}");
        assert_eq!(c.default_base.as_deref(), Some("trunk"));
        assert_eq!(c.editor.as_deref(), Some("hx"));
        assert_eq!(c.hooks_post_create.as_deref(), Some("setup"));
        assert_eq!(c.hooks_pre_remove.as_deref(), Some("teardown"));
        assert!(!c.remove_delete_merged_branch);
        assert!(c.remove_untracked_blocks);
        assert_eq!(c.submodules_init, SubmoduleInit::Always);
        assert_eq!(c.agent_generation.model, AgentModel::Haiku);
        assert_eq!(c.agent_generation.effort, Effort::Low);
        assert!(!c.list_show_untracked);
        assert!(c.ui_nerd_fonts);
        assert_eq!(c.ui_color, ColorChoice::Never);
    }

    #[test]
    fn color_enabled_follows_precedence() {
        use crate::output::color::ColorChoice;
        let mut c = Config::default();
        let no_env = Env::from_map(std::collections::HashMap::new());
        // Default ui.color=auto -> follows stdout TTY.
        assert!(c.color_enabled(None, &no_env, true));
        assert!(!c.color_enabled(None, &no_env, false));
        // ui.color=never overrides auto.
        c.ui_color = ColorChoice::Never;
        assert!(!c.color_enabled(None, &no_env, true));
        // --color always beats config.
        assert!(c.color_enabled(Some(ColorChoice::Always), &no_env, false));
        // NO_COLOR beats config 'always'.
        c.ui_color = ColorChoice::Always;
        let no_color = Env::from_map(
            [("NO_COLOR".to_string(), "1".to_string())]
                .into_iter()
                .collect(),
        );
        assert!(!c.color_enabled(None, &no_color, true));
    }

    #[cfg(feature = "tui")]
    #[test]
    fn keybindings_deep_merge_per_action() {
        let mut c = Config::default();
        // Global layer rebinds navigate-up.
        c.apply(ConfigLayer {
            ui_keybindings: vec![(KeyAction::NavigateUp, KeyChord::key(KeyCode::Char('w')))],
            ..Default::default()
        });
        // Per-repo layer rebinds navigate-up again, plus quit.
        c.apply(ConfigLayer {
            ui_keybindings: vec![
                (KeyAction::NavigateUp, KeyChord::key(KeyCode::Char('e'))),
                (KeyAction::Quit, KeyChord::key(KeyCode::Char('x'))),
            ],
            ..Default::default()
        });
        let km = c.keymap();
        // Per-repo wins for navigate-up.
        assert_eq!(
            km.action_for(KeyChord::key(KeyCode::Char('e'))),
            Some(KeyAction::NavigateUp)
        );
        assert_eq!(km.action_for(KeyChord::key(KeyCode::Char('w'))), None);
        // Quit rebound, but unrelated actions keep their defaults.
        assert_eq!(
            km.action_for(KeyChord::key(KeyCode::Char('x'))),
            Some(KeyAction::Quit)
        );
        assert_eq!(
            km.action_for(KeyChord::key(KeyCode::Char('n'))),
            Some(KeyAction::New)
        );
    }

    #[cfg(feature = "tui")]
    #[test]
    fn theme_defaults_to_one_dark() {
        let c = Config::default();
        assert_eq!(c.ui_theme, ThemePreset::OneDark);
        assert_eq!(c.theme_overrides, ThemeOverrides::default());
        assert_eq!(c.palette(), Palette::one_dark());
    }

    #[cfg(feature = "tui")]
    #[test]
    fn theme_preset_and_overrides_apply_and_merge() {
        let mut c = Config::default();
        // Global layer: solarized preset + an accent override.
        c.apply(ConfigLayer {
            ui_theme: Some(ThemePreset::Solarized),
            theme_overrides: ThemeOverrides {
                accent: Some(Color::Rgb(1, 1, 1)),
                ..Default::default()
            },
            ..Default::default()
        });
        // Per-repo layer: override red only; preset and accent untouched.
        c.apply(ConfigLayer {
            theme_overrides: ThemeOverrides {
                red: Some(Color::Rgb(2, 2, 2)),
                ..Default::default()
            },
            ..Default::default()
        });
        assert_eq!(c.ui_theme, ThemePreset::Solarized);
        let p = c.palette();
        // Both overrides survive (deep-merge per slot).
        assert_eq!(p.accent, Color::Rgb(1, 1, 1));
        assert_eq!(p.red, Color::Rgb(2, 2, 2));
        // A non-overridden slot keeps the solarized base.
        assert_eq!(p.green, Palette::solarized().green);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn later_theme_override_wins_for_same_slot() {
        let mut o = ThemeOverrides {
            accent: Some(Color::Rgb(1, 1, 1)),
            ..Default::default()
        };
        o.merge(ThemeOverrides {
            accent: Some(Color::Rgb(9, 9, 9)),
            ..Default::default()
        });
        assert_eq!(o.accent, Some(Color::Rgb(9, 9, 9)));
    }
}