worktrunk 0.36.0

A CLI for Git worktree management, designed for parallel AI agent workflows
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
//! Configuration section structs.
//!
//! These structs represent individual configuration sections that can be set
//! globally or per-project. Each implements the `Merge` trait for layering.

use std::collections::BTreeMap;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::merge::{Merge, merge_optional};
use crate::config::HooksConfig;
use crate::config::commands::CommandConfig;

/// What to stage before committing
#[derive(
    Debug,
    Clone,
    Copy,
    Default,
    PartialEq,
    Eq,
    clap::ValueEnum,
    serde::Serialize,
    serde::Deserialize,
    JsonSchema,
)]
#[serde(rename_all = "kebab-case")]
pub enum StageMode {
    /// Stage everything: untracked files + unstaged tracked changes
    #[default]
    All,
    /// Stage tracked changes only (like `git add -u`)
    Tracked,
    /// Stage nothing, commit only what's already in the index
    None,
}

/// Configuration for commit message generation
///
/// The command is a shell string executed via `sh -c`. Environment variables
/// can be set inline (e.g., `MAX_THINKING_TOKENS=0 claude -p ...`).
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]
pub struct CommitGenerationConfig {
    /// Shell command to invoke for generating commit messages
    ///
    /// Examples:
    /// - `"llm -m claude-haiku-4.5"`
    /// - `"MAX_THINKING_TOKENS=0 claude -p --no-session-persistence --model=haiku"`
    ///
    /// The command receives the prompt via stdin and should output the commit message.
    #[serde(default)]
    pub command: Option<String>,

    /// Inline template for commit message prompt
    /// Available variables: {{ git_diff }}, {{ branch }}, {{ recent_commits }}, {{ repo }}
    #[serde(default)]
    pub template: Option<String>,

    /// Path to template file (mutually exclusive with template)
    /// Supports tilde expansion (e.g., "~/.config/worktrunk/commit-template.txt")
    #[serde(default, rename = "template-file")]
    pub template_file: Option<String>,

    /// Inline template for squash commit message prompt
    /// Available variables: {{ commits }}, {{ target_branch }}, {{ branch }}, {{ repo }}
    #[serde(default, rename = "squash-template")]
    pub squash_template: Option<String>,

    /// Path to squash template file (mutually exclusive with squash-template)
    /// Supports tilde expansion (e.g., "~/.config/worktrunk/squash-template.txt")
    #[serde(default, rename = "squash-template-file")]
    pub squash_template_file: Option<String>,
}

impl CommitGenerationConfig {
    /// Returns true if an LLM command is configured
    pub fn is_configured(&self) -> bool {
        self.command
            .as_ref()
            .map(|s| !s.trim().is_empty())
            .unwrap_or(false)
    }
}

impl Merge for CommitGenerationConfig {
    fn merge_with(&self, other: &Self) -> Self {
        // For template/template_file pairs: if project sets one, it clears the other
        // This prevents violating mutual exclusivity when global has one and project has the other
        let (template, template_file) = if other.template.is_some() {
            (other.template.clone(), None)
        } else if other.template_file.is_some() {
            (None, other.template_file.clone())
        } else {
            (self.template.clone(), self.template_file.clone())
        };

        let (squash_template, squash_template_file) = if other.squash_template.is_some() {
            (other.squash_template.clone(), None)
        } else if other.squash_template_file.is_some() {
            (None, other.squash_template_file.clone())
        } else {
            (
                self.squash_template.clone(),
                self.squash_template_file.clone(),
            )
        };

        Self {
            command: other.command.clone().or_else(|| self.command.clone()),
            template,
            template_file,
            squash_template,
            squash_template_file,
        }
    }
}

/// Configuration for the `wt list` command
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
pub struct ListConfig {
    /// Show CI and `main` diffstat by default
    #[serde(skip_serializing_if = "Option::is_none")]
    pub full: Option<bool>,

    /// Include branches without worktrees by default
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branches: Option<bool>,

    /// Include remote branches by default
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remotes: Option<bool>,

    /// Enable LLM-generated branch summaries (picker tab 5 + list Summary column).
    /// Requires `[commit.generation] command` to be configured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<bool>,

    /// Per-task timeout in milliseconds.
    /// Kills individual git commands that exceed this duration. Applies to both
    /// `wt list` and the `wt switch` picker. Set to 0 to explicitly disable
    /// (useful to override a global setting). Disabled when --full is used.
    #[serde(rename = "task-timeout-ms", skip_serializing_if = "Option::is_none")]
    pub task_timeout_ms: Option<u64>,

    /// Wall-clock budget for the entire collect phase in milliseconds.
    /// Tasks that complete within the budget contribute data; tasks still
    /// running when it expires are abandoned silently. Set to 0 to disable.
    /// Disabled when --full is used. Default: no budget (wait for all results).
    #[serde(rename = "timeout-ms", skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
}

impl ListConfig {
    /// Show CI and `main` diffstat by default (default: false)
    pub fn full(&self) -> bool {
        self.full.unwrap_or(false)
    }

    /// Include branches without worktrees by default (default: false)
    pub fn branches(&self) -> bool {
        self.branches.unwrap_or(false)
    }

    /// Include remote branches by default (default: false)
    pub fn remotes(&self) -> bool {
        self.remotes.unwrap_or(false)
    }

    /// Enable LLM-generated branch summaries (default: false)
    pub fn summary(&self) -> bool {
        self.summary.unwrap_or(false)
    }

    /// Per-task command timeout (default: None — no per-command timeout).
    /// Returns `None` when disabled (task_timeout_ms = 0 or unset).
    pub fn task_timeout(&self) -> Option<std::time::Duration> {
        self.task_timeout_ms
            .filter(|&ms| ms > 0)
            .map(std::time::Duration::from_millis)
    }

    /// Wall-clock budget for the collect phase (default: None — no budget).
    /// Returns `None` when disabled (timeout_ms = 0 or unset).
    pub fn timeout(&self) -> Option<std::time::Duration> {
        self.timeout_ms
            .filter(|&ms| ms > 0)
            .map(std::time::Duration::from_millis)
    }
}

impl Merge for ListConfig {
    fn merge_with(&self, other: &Self) -> Self {
        Self {
            full: other.full.or(self.full),
            branches: other.branches.or(self.branches),
            remotes: other.remotes.or(self.remotes),
            summary: other.summary.or(self.summary),
            task_timeout_ms: other.task_timeout_ms.or(self.task_timeout_ms),
            timeout_ms: other.timeout_ms.or(self.timeout_ms),
        }
    }
}

/// Configuration for the `wt step commit` command
///
/// Also used by `wt merge` for shared settings like `stage`.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
pub struct CommitConfig {
    /// What to stage before committing (default: all)
    /// Values: "all", "tracked", "none"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stage: Option<StageMode>,

    /// LLM commit message generation settings
    ///
    /// Nested under `[commit.generation]` in TOML.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub generation: Option<CommitGenerationConfig>,
}

impl CommitConfig {
    /// What to stage before committing (default: All)
    pub fn stage(&self) -> StageMode {
        self.stage.unwrap_or_default()
    }
}

impl Merge for CommitConfig {
    fn merge_with(&self, other: &Self) -> Self {
        Self {
            stage: other.stage.or(self.stage),
            generation: match (&self.generation, &other.generation) {
                (None, None) => None,
                (Some(s), None) => Some(s.clone()),
                (None, Some(o)) => Some(o.clone()),
                (Some(s), Some(o)) => Some(s.merge_with(o)),
            },
        }
    }
}

/// Configuration for the `wt merge` command
///
/// Note: `stage` defaults from `[commit]` section, not here.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
pub struct MergeConfig {
    /// Squash commits when merging (default: true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub squash: Option<bool>,

    /// Commit, squash, and rebase during merge (default: true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit: Option<bool>,

    /// Rebase onto target branch before merging (default: true)
    ///
    /// When false, merge fails if branch is not already rebased.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rebase: Option<bool>,

    /// Remove worktree after merge (default: true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remove: Option<bool>,

    /// Run project hooks (default: true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verify: Option<bool>,

    /// Fast-forward merge instead of creating a merge commit (default: true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ff: Option<bool>,
}

impl MergeConfig {
    /// Squash commits when merging (default: true)
    pub fn squash(&self) -> bool {
        self.squash.unwrap_or(true)
    }

    /// Commit, squash, and rebase during merge (default: true)
    pub fn commit(&self) -> bool {
        self.commit.unwrap_or(true)
    }

    /// Rebase onto target branch before merging (default: true)
    pub fn rebase(&self) -> bool {
        self.rebase.unwrap_or(true)
    }

    /// Remove worktree after merge (default: true)
    pub fn remove(&self) -> bool {
        self.remove.unwrap_or(true)
    }

    /// Run project hooks (default: true)
    pub fn verify(&self) -> bool {
        self.verify.unwrap_or(true)
    }

    /// Fast-forward merge instead of creating a merge commit (default: true)
    pub fn ff(&self) -> bool {
        self.ff.unwrap_or(true)
    }
}

impl Merge for MergeConfig {
    fn merge_with(&self, other: &Self) -> Self {
        Self {
            squash: other.squash.or(self.squash),
            commit: other.commit.or(self.commit),
            rebase: other.rebase.or(self.rebase),
            remove: other.remove.or(self.remove),
            verify: other.verify.or(self.verify),
            ff: other.ff.or(self.ff),
        }
    }
}

/// Configuration for the `wt switch` interactive picker.
///
/// New format under `[switch.picker]`. Replaces the deprecated `[select]` section.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
pub struct SwitchPickerConfig {
    /// Pager command with flags for diff preview
    ///
    /// Overrides git's core.pager for the interactive picker's preview panel.
    /// Use this to specify pager flags needed for non-TTY contexts.
    ///
    /// Example: `pager = "delta --paging=never"`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pager: Option<String>,

    /// Wall-clock budget for picker data collection in milliseconds.
    ///
    /// Controls how long the picker waits for git data before displaying.
    /// Tasks still running when the budget expires are abandoned.
    ///
    /// - Unset: 500ms default
    /// - `0`: No budget (wait for all results)
    /// - Positive value: Custom budget in milliseconds
    #[serde(rename = "timeout-ms", skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
}

impl SwitchPickerConfig {
    /// Pager command for diff preview (default: None, uses git default)
    pub fn pager(&self) -> Option<&str> {
        self.pager.as_deref()
    }

    /// Wall-clock budget for picker data collection (default: 500ms).
    /// Returns `None` when disabled (timeout_ms = 0 or WORKTRUNK_TEST_PICKER_NO_TIMEOUT set).
    pub fn timeout(&self) -> Option<std::time::Duration> {
        // Env var bypass for test reliability — config file loading is unreliable
        // in PTY subprocesses on macOS CI, so tests disable the timeout directly.
        if std::env::var_os("WORKTRUNK_TEST_PICKER_NO_TIMEOUT").is_some() {
            return None;
        }
        match self.timeout_ms {
            Some(0) => None,
            Some(ms) => Some(std::time::Duration::from_millis(ms)),
            None => Some(std::time::Duration::from_millis(500)),
        }
    }
}

impl Merge for SwitchPickerConfig {
    fn merge_with(&self, other: &Self) -> Self {
        Self {
            pager: other.pager.clone().or_else(|| self.pager.clone()),
            timeout_ms: other.timeout_ms.or(self.timeout_ms),
        }
    }
}

/// Configuration for the `wt switch` command
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
pub struct SwitchConfig {
    /// Change directory after switch (default: true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cd: Option<bool>,

    /// Picker settings for the interactive selector
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub picker: Option<SwitchPickerConfig>,
}

impl SwitchConfig {
    /// Change directory after switch (default: true)
    pub fn cd(&self) -> bool {
        self.cd.unwrap_or(true)
    }
}

impl Merge for SwitchConfig {
    fn merge_with(&self, other: &Self) -> Self {
        Self {
            cd: other.cd.or(self.cd),
            picker: match (&self.picker, &other.picker) {
                (None, None) => None,
                (Some(s), None) => Some(s.clone()),
                (None, Some(o)) => Some(o.clone()),
                (Some(s), Some(o)) => Some(s.merge_with(o)),
            },
        }
    }
}

/// Configuration for `wt step copy-ignored`
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
pub struct CopyIgnoredConfig {
    /// Gitignore-style patterns to exclude from `wt step copy-ignored`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exclude: Vec<String>,
}

impl CopyIgnoredConfig {
    pub fn merged_with(&self, other: &Self) -> Self {
        let mut exclude = self.exclude.clone();
        for pattern in &other.exclude {
            if !exclude.contains(pattern) {
                exclude.push(pattern.clone());
            }
        }
        Self { exclude }
    }
}

impl Merge for CopyIgnoredConfig {
    fn merge_with(&self, other: &Self) -> Self {
        self.merged_with(other)
    }
}

/// Configuration for `wt step` subcommands.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
pub struct StepConfig {
    /// Configuration for `wt step copy-ignored`.
    #[serde(
        default,
        rename = "copy-ignored",
        skip_serializing_if = "Option::is_none"
    )]
    pub copy_ignored: Option<CopyIgnoredConfig>,
}

impl StepConfig {
    /// Returns the resolved copy-ignored config, defaulting to empty if unset.
    pub fn copy_ignored(&self) -> CopyIgnoredConfig {
        self.copy_ignored.clone().unwrap_or_default()
    }
}

impl Merge for StepConfig {
    fn merge_with(&self, other: &Self) -> Self {
        Self {
            copy_ignored: merge_optional(self.copy_ignored.as_ref(), other.copy_ignored.as_ref()),
        }
    }
}

/// Settings that can be set globally or per-project.
///
/// This struct is flattened into both `UserConfig` (global) and `UserProjectOverrides`
/// (per-project), ensuring new settings are automatically available in both
/// contexts without manual synchronization.
///
/// Note: Hooks use append semantics when merging global with per-project:
/// - Global hooks (top-level in TOML) are in `UserConfig.configs.hooks`
/// - Per-project hooks are in `UserProjectOverrides.overrides.hooks`
/// - The `UserConfig::hooks()` method merges both with global running first
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
pub struct OverridableConfig {
    /// Hooks configuration.
    ///
    /// At top level: global hooks that run for all projects.
    /// In `[projects."..."]`: per-project hooks that append to global hooks.
    #[serde(flatten, default)]
    pub hooks: HooksConfig,

    /// Worktree path template
    #[serde(
        rename = "worktree-path",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub worktree_path: Option<String>,

    /// Configuration for the `wt list` command
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub list: Option<ListConfig>,

    /// Configuration for the `wt step commit` command (also used by merge)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commit: Option<CommitConfig>,

    /// Configuration for the `wt merge` command
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merge: Option<MergeConfig>,

    /// Configuration for the `wt switch` command
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub switch: Option<SwitchConfig>,

    /// Configuration for `wt step` subcommands.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub step: Option<StepConfig>,

    /// \[experimental\] Command aliases for `wt step <name>`.
    ///
    /// Each alias maps a name to one or more command templates. All hook
    /// template variables are available (e.g., `{{ branch }}`, `{{ worktree_path }}`).
    ///
    /// Per-project aliases append to global aliases on name collision (global
    /// first, then per-project), matching hook merge semantics.
    ///
    /// Uses `CommandConfig` for consistency with hooks. This means the
    /// named-table format (`[aliases.deploy] build = "..." run = "..."`)
    /// technically works, but the single-string format is the expected usage.
    ///
    /// ```toml
    /// [aliases]
    /// deploy = "cd {{ worktree_path }} && make deploy"
    /// lint = "npm run lint"
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aliases: Option<BTreeMap<String, CommandConfig>>,
}

impl OverridableConfig {
    /// Returns true if all settings are None/default.
    ///
    /// Includes hooks check for per-project configs where hooks are stored here.
    pub fn is_empty(&self) -> bool {
        self.hooks == HooksConfig::default()
            && self.worktree_path.is_none()
            && self.list.is_none()
            && self.commit.is_none()
            && self.merge.is_none()
            && self.switch.is_none()
            && self.step.is_none()
            && self.aliases.is_none()
    }
}

impl Merge for OverridableConfig {
    fn merge_with(&self, other: &Self) -> Self {
        use super::merge::merge_optional;

        Self {
            hooks: self.hooks.merge_with(&other.hooks), // Append semantics
            worktree_path: other
                .worktree_path
                .clone()
                .or_else(|| self.worktree_path.clone()),
            list: merge_optional(self.list.as_ref(), other.list.as_ref()),
            commit: merge_optional(self.commit.as_ref(), other.commit.as_ref()),
            merge: merge_optional(self.merge.as_ref(), other.merge.as_ref()),
            switch: merge_optional(self.switch.as_ref(), other.switch.as_ref()),
            step: merge_optional(self.step.as_ref(), other.step.as_ref()),
            aliases: merge_alias_maps(&self.aliases, &other.aliases), // Append semantics
        }
    }
}

/// Merge two optional alias maps using append semantics.
///
/// Both base and other aliases run on name collision (base first, then other),
/// matching how `HooksConfig::merge_with` appends hooks.
fn merge_alias_maps(
    base: &Option<BTreeMap<String, CommandConfig>>,
    other: &Option<BTreeMap<String, CommandConfig>>,
) -> Option<BTreeMap<String, CommandConfig>> {
    match (base, other) {
        (None, None) => None,
        (Some(b), None) => Some(b.clone()),
        (None, Some(o)) => Some(o.clone()),
        (Some(b), Some(o)) => {
            let mut merged = b.clone();
            crate::config::commands::append_aliases(&mut merged, o);
            Some(merged)
        }
    }
}

/// Per-project overrides in the user's config file
///
/// Stored under `[projects."project-id"]` in the user's config.
/// These are user preferences (not checked into git) that override
/// the corresponding global settings when set.
///
/// # TOML Format
/// ```toml
/// [projects."github.com/user/repo"]
/// worktree-path = ".worktrees/{{ branch | sanitize }}"
/// approved-commands = ["npm install", "npm test"]
///
/// [projects."github.com/user/repo".commit.generation]
/// command = "llm -m gpt-4"
///
/// [projects."github.com/user/repo".list]
/// full = true
///
/// [projects."github.com/user/repo".merge]
/// squash = false
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]
pub struct UserProjectOverrides {
    /// Commands that have been approved for automatic execution in this project
    #[serde(
        default,
        rename = "approved-commands",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub approved_commands: Vec<String>,

    /// Per-project overrides (worktree-path, list, commit, merge, switch, step)
    #[serde(flatten, default)]
    pub overrides: OverridableConfig,
}

impl UserProjectOverrides {
    /// Returns true if all fields are empty/None (no settings configured).
    ///
    /// Approvals are stored in `approvals.toml`, so `approved_commands` is only
    /// kept here for backward-compatible parsing and migration — not checked.
    pub fn is_empty(&self) -> bool {
        self.overrides.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_merge_alias_maps_both_none() {
        assert_eq!(merge_alias_maps(&None, &None), None);
    }

    #[test]
    fn test_merge_alias_maps_base_only() {
        let base = BTreeMap::from([("a".into(), CommandConfig::single("1"))]);
        let result = merge_alias_maps(&Some(base.clone()), &None);
        assert_eq!(result, Some(base));
    }

    #[test]
    fn test_merge_alias_maps_other_only() {
        let other = BTreeMap::from([("b".into(), CommandConfig::single("2"))]);
        let result = merge_alias_maps(&None, &Some(other.clone()));
        assert_eq!(result, Some(other));
    }

    #[test]
    fn test_merge_alias_maps_appends_on_collision() {
        let base = BTreeMap::from([
            ("a".into(), CommandConfig::single("1")),
            ("shared".into(), CommandConfig::single("base-cmd")),
        ]);
        let other = BTreeMap::from([
            ("b".into(), CommandConfig::single("2")),
            ("shared".into(), CommandConfig::single("other-cmd")),
        ]);
        let result = merge_alias_maps(&Some(base), &Some(other)).unwrap();
        assert_eq!(result["a"].commands().count(), 1);
        assert_eq!(result["b"].commands().count(), 1);
        // Collision: both commands are preserved (base first, then other)
        let shared: Vec<_> = result["shared"].commands().collect();
        assert_eq!(shared.len(), 2);
        assert_eq!(shared[0].template, "base-cmd");
        assert_eq!(shared[1].template, "other-cmd");
    }
}