worktrunk 0.37.1

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
//! 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;
use crate::config::is_default;

/// 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>,

    /// Accepted for backward compatibility; currently ignored.
    ///
    /// Previously bounded how long the picker blocked before rendering.
    /// The picker now renders its skeleton immediately and fills rows in
    /// place as results arrive, so there's no UI-freeze budget to tune.
    /// Left in the schema so existing configs keep parsing without error.
    #[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()
    }

    /// Parses the legacy `timeout-ms` field. Kept for schema round-tripping;
    /// the picker no longer consults it (progressive rendering made the
    /// UI-freeze budget obsolete).
    pub fn timeout(&self) -> Option<std::time::Duration> {
        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()),
        }
    }
}

/// 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 }}"
///
/// [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 hooks (append to global hooks)
    #[serde(flatten, default)]
    pub hooks: HooksConfig,

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

    #[serde(default, skip_serializing_if = "is_default")]
    pub list: ListConfig,

    #[serde(default, skip_serializing_if = "is_default")]
    pub commit: CommitConfig,

    #[serde(default, skip_serializing_if = "is_default")]
    pub merge: MergeConfig,

    #[serde(default, skip_serializing_if = "is_default")]
    pub switch: SwitchConfig,

    #[serde(default, skip_serializing_if = "is_default")]
    pub step: StepConfig,

    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub aliases: BTreeMap<String, CommandConfig>,
}