worktrunk 0.35.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
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
//! Configuration system for worktrunk
//!
//! Three configuration sources, loaded in order (later overrides earlier):
//!
//! 1. **System config** (`/etc/xdg/worktrunk/config.toml` or platform equivalent) -
//!    Organization-wide defaults, optional
//! 2. **User config** (`~/.config/worktrunk/config.toml`) - Personal preferences
//! 3. **Project config** (`.config/wt.toml`) - Lifecycle hooks, checked into git
//!
//! System and user configs share the same schema and are merged by the `config`
//! crate's builder (user values override system values at the key level).
//! Project config is independent — different schema, different purpose.
//!
//! See `wt config --help` for complete documentation.

pub mod approvals;
mod commands;
pub(crate) mod deprecation;
mod expansion;
mod hooks;
mod project;
#[cfg(test)]
mod test;
mod user;

/// Trait for worktrunk config types (user and project config).
///
/// Both config types use JsonSchema to derive valid keys, allowing validation
/// to detect misplaced or misspelled keys. The `Other` associated type enables
/// checking whether a key belongs in the other config.
pub trait WorktrunkConfig: for<'de> serde::Deserialize<'de> + Sized {
    /// The other config type (UserConfig ↔ ProjectConfig).
    type Other: WorktrunkConfig;

    /// Human-readable description of where this config lives.
    fn description() -> &'static str;

    /// Check if a key would be valid in this config type.
    /// Uses JsonSchema-derived keys for validation.
    fn is_valid_key(key: &str) -> bool;
}

impl WorktrunkConfig for UserConfig {
    type Other = ProjectConfig;

    fn description() -> &'static str {
        "user config"
    }

    fn is_valid_key(key: &str) -> bool {
        use std::sync::OnceLock;
        static VALID_KEYS: OnceLock<Vec<String>> = OnceLock::new();
        let valid_keys = VALID_KEYS.get_or_init(user::valid_user_config_keys);
        valid_keys.iter().any(|k| k == key)
    }
}

impl WorktrunkConfig for ProjectConfig {
    type Other = UserConfig;

    fn description() -> &'static str {
        "project config"
    }

    fn is_valid_key(key: &str) -> bool {
        use std::sync::OnceLock;
        static VALID_KEYS: OnceLock<Vec<String>> = OnceLock::new();
        let valid_keys = VALID_KEYS.get_or_init(project::valid_project_config_keys);
        valid_keys.iter().any(|k| k == key)
    }
}

// Re-export public types
pub use approvals::{Approvals, approvals_path};
pub use commands::{Command, CommandConfig, HookStep, append_aliases};
pub use deprecation::CheckAndMigrateResult;
pub use deprecation::DeprecationInfo;
pub use deprecation::Deprecations;
pub use deprecation::check_and_migrate;
pub use deprecation::detect_deprecations;
pub use deprecation::format_brief_warning;
pub use deprecation::format_deprecation_details;
pub use deprecation::format_deprecation_warnings;
pub use deprecation::format_migration_diff;
pub use deprecation::migrate_content;
pub use deprecation::normalize_template_vars;
pub use deprecation::write_migration_file;
pub use deprecation::{
    DEPRECATED_SECTION_KEYS, DeprecatedSection, UnknownKeyKind, classify_unknown_key,
    key_belongs_in, warn_unknown_fields,
};
pub use expansion::{
    DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, TemplateExpandError, expand_template,
    redact_credentials, sanitize_branch_name, sanitize_db, short_hash, template_references_var,
    validate_template,
};
pub use hooks::HooksConfig;
pub use project::{
    ProjectCiConfig, ProjectConfig, ProjectListConfig,
    find_unknown_keys as find_unknown_project_keys, valid_project_config_keys,
};
pub use user::{
    CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig,
    OverridableConfig, ResolvedConfig, StageMode, StepConfig, SwitchConfig, SwitchPickerConfig,
    UserConfig, UserProjectOverrides, config_path, default_config_path, default_system_config_path,
    find_unknown_keys as find_unknown_user_keys, set_config_path, system_config_path,
    valid_user_config_keys,
};

#[cfg(test)]
mod tests {
    use insta::assert_snapshot;

    use super::*;
    use crate::testing::TestRepo;

    fn test_repo() -> TestRepo {
        TestRepo::new()
    }

    #[test]
    fn test_config_serialization() {
        // Default config serializes to empty (no optional fields)
        assert_snapshot!(toml::to_string(&UserConfig::default()).unwrap(), @"[projects]");

        // With worktree-path set
        let config = UserConfig {
            configs: OverridableConfig {
                worktree_path: Some("custom/{{ branch }}".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_snapshot!(toml::to_string(&config).unwrap(), @r#"
        worktree-path = "custom/{{ branch }}"

        [projects]
        "#);
    }

    #[test]
    fn test_default_config() {
        let config = UserConfig::default();
        // worktree_path is None by default, but the getter returns the default
        assert!(config.configs.worktree_path.is_none());
        assert_eq!(
            config.worktree_path(),
            "{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"
        );
        assert!(config.projects.is_empty());
    }

    #[test]
    fn test_format_worktree_path() {
        let test = test_repo();
        let config = UserConfig {
            configs: OverridableConfig {
                worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(
            config
                .format_path("myproject", "feature-x", &test.repo, None)
                .unwrap(),
            "myproject.feature-x"
        );
    }

    #[test]
    fn test_format_worktree_path_custom_template() {
        let test = test_repo();
        let config = UserConfig {
            configs: OverridableConfig {
                worktree_path: Some("{{ main_worktree }}-{{ branch }}".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(
            config
                .format_path("myproject", "feature-x", &test.repo, None)
                .unwrap(),
            "myproject-feature-x"
        );
    }

    #[test]
    fn test_format_worktree_path_only_branch() {
        let test = test_repo();
        let config = UserConfig {
            configs: OverridableConfig {
                worktree_path: Some(".worktrees/{{ main_worktree }}/{{ branch }}".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(
            config
                .format_path("myproject", "feature-x", &test.repo, None)
                .unwrap(),
            ".worktrees/myproject/feature-x"
        );
    }

    #[test]
    fn test_format_worktree_path_with_slashes() {
        let test = test_repo();
        // Use {{ branch | sanitize }} to replace slashes with dashes
        let config = UserConfig {
            configs: OverridableConfig {
                worktree_path: Some("{{ main_worktree }}.{{ branch | sanitize }}".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(
            config
                .format_path("myproject", "feature/foo", &test.repo, None)
                .unwrap(),
            "myproject.feature-foo"
        );
    }

    #[test]
    fn test_format_worktree_path_with_multiple_slashes() {
        let test = test_repo();
        let config = UserConfig {
            configs: OverridableConfig {
                worktree_path: Some(
                    ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),
                ),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(
            config
                .format_path("myproject", "feature/sub/task", &test.repo, None)
                .unwrap(),
            ".worktrees/myproject/feature-sub-task"
        );
    }

    #[test]
    fn test_format_worktree_path_with_backslashes() {
        let test = test_repo();
        // Windows-style path separators should also be sanitized
        let config = UserConfig {
            configs: OverridableConfig {
                worktree_path: Some(
                    ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),
                ),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(
            config
                .format_path("myproject", "feature\\foo", &test.repo, None)
                .unwrap(),
            ".worktrees/myproject/feature-foo"
        );
    }

    #[test]
    fn test_format_worktree_path_raw_branch() {
        let test = test_repo();
        // {{ branch }} without filter gives raw branch name
        let config = UserConfig {
            configs: OverridableConfig {
                worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(
            config
                .format_path("myproject", "feature/foo", &test.repo, None)
                .unwrap(),
            "myproject.feature/foo"
        );
    }

    #[test]
    fn test_command_config_single() {
        let toml = r#"post-create = "npm install""#;
        let config: ProjectConfig = toml::from_str(toml).unwrap();
        let cmd_config = config.hooks.post_create.unwrap();
        let commands: Vec<_> = cmd_config.commands().collect();
        assert_eq!(commands.len(), 1);
        assert_eq!(*commands[0], Command::new(None, "npm install".to_string()));
    }

    #[test]
    fn test_command_config_named() {
        let toml = r#"
            [post-start]
            server = "npm run dev"
            watch = "npm run watch"
        "#;
        let config: ProjectConfig = toml::from_str(toml).unwrap();
        let cmd_config = config.hooks.post_start.unwrap();
        let commands: Vec<_> = cmd_config.commands().collect();
        assert_eq!(commands.len(), 2);
        // Preserves TOML insertion order
        assert_eq!(
            *commands[0],
            Command::new(Some("server".to_string()), "npm run dev".to_string())
        );
        assert_eq!(
            *commands[1],
            Command::new(Some("watch".to_string()), "npm run watch".to_string())
        );
    }

    #[test]
    fn test_command_config_named_preserves_toml_order() {
        // Test that named commands preserve TOML order (not alphabetical)
        let toml = r#"
            [pre-merge]
            insta = "cargo insta test"
            doc = "cargo doc"
            clippy = "cargo clippy"
        "#;
        let config: ProjectConfig = toml::from_str(toml).unwrap();
        let cmd_config = config.hooks.pre_merge.unwrap();
        let commands: Vec<_> = cmd_config.commands().collect();

        // Extract just the names for easier verification
        let names: Vec<_> = commands
            .iter()
            .map(|cmd| cmd.name.as_deref().unwrap())
            .collect();

        // Verify TOML insertion order is preserved
        assert_eq!(names, vec!["insta", "doc", "clippy"]);

        // Verify it's NOT alphabetical (which would be clippy, doc, insta)
        let mut alphabetical = names.clone();
        alphabetical.sort();
        assert_ne!(
            names, alphabetical,
            "Order should be TOML insertion order, not alphabetical"
        );
    }

    #[test]
    fn test_command_config_task_order() {
        // Test exact ordering as used in post_start tests
        let toml = r#"
[post-start]
task1 = "echo 'Task 1 running' > task1.txt"
task2 = "echo 'Task 2 running' > task2.txt"
"#;
        let config: ProjectConfig = toml::from_str(toml).unwrap();
        let cmd_config = config.hooks.post_start.unwrap();
        let commands: Vec<_> = cmd_config.commands().collect();

        assert_eq!(commands.len(), 2);
        // Should be in TOML order: task1, task2
        assert_eq!(
            commands[0].name.as_deref(),
            Some("task1"),
            "First command should be task1"
        );
        assert_eq!(
            commands[1].name.as_deref(),
            Some("task2"),
            "Second command should be task2"
        );
    }

    #[test]
    fn test_project_config_both_commands() {
        let toml = r#"
            post-create = "npm install"

            [post-start]
            server = "npm run dev"
        "#;
        let config: ProjectConfig = toml::from_str(toml).unwrap();
        assert!(config.hooks.post_create.is_some());
        assert!(config.hooks.post_start.is_some());
    }

    #[test]
    fn test_pre_merge_command_single() {
        let toml = r#"pre-merge = "cargo test""#;
        let config: ProjectConfig = toml::from_str(toml).unwrap();
        let cmd_config = config.hooks.pre_merge.unwrap();
        let commands: Vec<_> = cmd_config.commands().collect();
        assert_eq!(commands.len(), 1);
        assert_eq!(*commands[0], Command::new(None, "cargo test".to_string()));
    }

    #[test]
    fn test_pre_merge_command_named() {
        let toml = r#"
            [pre-merge]
            format = "cargo fmt -- --check"
            lint = "cargo clippy"
            test = "cargo test"
        "#;
        let config: ProjectConfig = toml::from_str(toml).unwrap();
        let cmd_config = config.hooks.pre_merge.unwrap();
        let commands: Vec<_> = cmd_config.commands().collect();
        assert_eq!(commands.len(), 3);
        // Preserves TOML insertion order
        assert_eq!(
            *commands[0],
            Command::new(
                Some("format".to_string()),
                "cargo fmt -- --check".to_string()
            )
        );
        assert_eq!(
            *commands[1],
            Command::new(Some("lint".to_string()), "cargo clippy".to_string())
        );
        assert_eq!(
            *commands[2],
            Command::new(Some("test".to_string()), "cargo test".to_string())
        );
    }

    #[test]
    fn test_command_config_roundtrip_single() {
        let original = r#"post-create = "npm install""#;
        let config: ProjectConfig = toml::from_str(original).unwrap();
        let serialized = toml::to_string(&config).unwrap();
        let config2: ProjectConfig = toml::from_str(&serialized).unwrap();
        assert_eq!(config, config2);
        assert_snapshot!(serialized, @r#"post-create = "npm install""#);
    }

    #[test]
    fn test_command_config_roundtrip_named() {
        let original = r#"
            [post-start]
            server = "npm run dev"
            watch = "npm run watch"
        "#;
        let config: ProjectConfig = toml::from_str(original).unwrap();
        let serialized = toml::to_string(&config).unwrap();
        let config2: ProjectConfig = toml::from_str(&serialized).unwrap();
        assert_eq!(config, config2);
        assert_snapshot!(serialized, @r#"
        [post-start]
        server = "npm run dev"
        watch = "npm run watch"
        "#);
    }

    #[test]
    fn test_expand_template_basic() {
        use std::collections::HashMap;

        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("main_worktree", "myrepo");
        vars.insert("branch", "feature-x");
        let result = expand_template(
            "../{{ main_worktree }}.{{ branch }}",
            &vars,
            true,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_eq!(result, "../myrepo.feature-x");
    }

    #[test]
    fn test_expand_template_sanitizes_branch() {
        use std::collections::HashMap;

        let test = test_repo();

        // Use {{ branch | sanitize }} filter for filesystem-safe paths
        // shell_escape=false to test filter in isolation (shell escaping tested separately)
        let mut vars = HashMap::new();
        vars.insert("main_worktree", "myrepo");
        vars.insert("branch", "feature/foo");
        let result = expand_template(
            "{{ main_worktree }}/{{ branch | sanitize }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_eq!(result, "myrepo/feature-foo");

        let mut vars = HashMap::new();
        vars.insert("main_worktree", "myrepo");
        vars.insert("branch", "feat\\bar");
        let result = expand_template(
            ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_eq!(result, ".worktrees/myrepo/feat-bar");
    }

    #[test]
    fn test_expand_template_with_extra_vars() {
        use std::collections::HashMap;

        let mut vars = HashMap::new();
        vars.insert("worktree", "/path/to/worktree");
        vars.insert("repo_root", "/path/to/repo");

        let result = expand_template(
            "{{ repo_root }}/target -> {{ worktree }}/target",
            &vars,
            true,
            &test_repo().repo,
            "test",
        )
        .unwrap();
        assert_eq!(result, "/path/to/repo/target -> /path/to/worktree/target");
    }

    #[test]
    fn test_commit_generation_config_mutually_exclusive_validation() {
        // Test that deserialization rejects both template and template-file
        let toml_content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"

[commit.generation]
command = "llm"
template = "inline template"
template-file = "~/file.txt"
"#;

        // Parse the TOML directly
        let config_result: Result<UserConfig, _> = toml::from_str(toml_content);

        // The deserialization should succeed, but validation in load() would fail
        // Since we can't easily test load() without env vars, we verify the fields deserialize
        if let Ok(config) = config_result {
            let generation = config
                .configs
                .commit
                .as_ref()
                .and_then(|c| c.generation.as_ref());
            // Verify validation logic: both fields should not be Some
            let has_both = generation
                .map(|g| g.template.is_some() && g.template_file.is_some())
                .unwrap_or(false);
            assert!(
                has_both,
                "Config should have both template fields set for this test"
            );
        }
    }

    #[test]
    fn test_squash_template_mutually_exclusive_validation() {
        // Test that deserialization rejects both squash-template and squash-template-file
        let toml_content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"

[commit.generation]
command = "llm"
squash-template = "inline template"
squash-template-file = "~/file.txt"
"#;

        // Parse the TOML directly
        let config_result: Result<UserConfig, _> = toml::from_str(toml_content);

        // The deserialization should succeed, but validation in load() would fail
        // Since we can't easily test load() without env vars, we verify the fields deserialize
        if let Ok(config) = config_result {
            let generation = config
                .configs
                .commit
                .as_ref()
                .and_then(|c| c.generation.as_ref());
            // Verify validation logic: both fields should not be Some
            let has_both = generation
                .map(|g| g.squash_template.is_some() && g.squash_template_file.is_some())
                .unwrap_or(false);
            assert!(
                has_both,
                "Config should have both squash template fields set for this test"
            );
        }
    }

    #[test]
    fn test_commit_generation_config_serialization() {
        let config = CommitGenerationConfig {
            command: Some("llm -m model".to_string()),
            template: Some("template content".to_string()),
            template_file: None,
            squash_template: None,
            squash_template_file: None,
        };

        assert_snapshot!(toml::to_string(&config).unwrap(), @r#"
        command = "llm -m model"
        template = "template content"
        "#);
    }

    #[test]
    fn test_find_unknown_project_keys_with_typo() {
        let toml_str = "[post-merge-command]\ndeploy = \"task deploy\"";
        let unknown = find_unknown_project_keys(toml_str);
        assert!(unknown.contains_key("post-merge-command"));
        assert_eq!(unknown.len(), 1);
    }

    #[test]
    fn test_find_unknown_project_keys_valid() {
        let toml_str =
            "[post-merge]\ndeploy = \"task deploy\"\n\n[pre-merge]\ntest = \"cargo test\"";
        let unknown = find_unknown_project_keys(toml_str);
        assert!(unknown.is_empty());
    }

    #[test]
    fn test_find_unknown_project_keys_multiple() {
        let toml_str = "[post-merge-command]\ndeploy = \"task deploy\"\n\n[after-create]\nsetup = \"npm install\"";
        let unknown = find_unknown_project_keys(toml_str);
        assert_eq!(unknown.len(), 2);
        assert!(unknown.contains_key("post-merge-command"));
        assert!(unknown.contains_key("after-create"));
    }

    #[test]
    fn test_find_unknown_user_keys_with_typo() {
        let toml_str = "worktree-path = \"../test\"\n\n[commit-gen]\ncommand = \"llm\"";
        let unknown = find_unknown_user_keys(toml_str);
        assert!(unknown.contains_key("commit-gen"));
        assert_eq!(unknown.len(), 1);
    }

    #[test]
    fn test_find_unknown_user_keys_valid() {
        let toml_str = "worktree-path = \"../test\"\n\n[commit.generation]\ncommand = \"llm\"\n\n[list]\nfull = true";
        let unknown = find_unknown_user_keys(toml_str);
        assert!(unknown.is_empty());
    }

    #[test]
    fn test_find_unknown_keys_invalid_toml() {
        let toml = "this is not valid toml {{{";
        let unknown_project = find_unknown_project_keys(toml);
        let unknown_user = find_unknown_user_keys(toml);
        assert!(unknown_project.is_empty());
        assert!(unknown_user.is_empty());
    }

    #[test]
    fn test_user_hooks_config_parsing() {
        let toml_str = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"

[post-create]
log = "echo '{{ repo }}' >> ~/.log"

[pre-merge]
test = "cargo test"
lint = "cargo clippy"
"#;
        let config: UserConfig = toml::from_str(toml_str).unwrap();

        // Check post-create
        let post_create = config
            .configs
            .hooks
            .post_create
            .expect("post-create should be present");
        let commands: Vec<_> = post_create.commands().collect();
        assert_eq!(commands.len(), 1);
        assert_eq!(commands[0].name.as_deref(), Some("log"));

        // Check pre-merge (multiple commands preserve order)
        let pre_merge = config
            .configs
            .hooks
            .pre_merge
            .expect("pre-merge should be present");
        let commands: Vec<_> = pre_merge.commands().collect();
        assert_eq!(commands.len(), 2);
        assert_eq!(commands[0].name.as_deref(), Some("test"));
        assert_eq!(commands[1].name.as_deref(), Some("lint"));
    }

    #[test]
    fn test_user_hooks_config_single_command() {
        let toml_str = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
post-create = "npm install"
"#;
        let config: UserConfig = toml::from_str(toml_str).unwrap();

        let post_create = config
            .configs
            .hooks
            .post_create
            .expect("post-create should be present");
        let commands: Vec<_> = post_create.commands().collect();
        assert_eq!(commands.len(), 1);
        assert!(commands[0].name.is_none()); // single command has no name
        assert_eq!(commands[0].template, "npm install");
    }

    #[test]
    fn test_user_hooks_not_reported_as_unknown() {
        let toml_str = r#"
worktree-path = "../test"
post-create = "npm install"

[pre-merge]
test = "cargo test"
"#;
        let unknown = find_unknown_user_keys(toml_str);
        assert!(
            unknown.is_empty(),
            "hook fields should not be reported as unknown: {:?}",
            unknown
        );
    }

    #[test]
    fn test_user_config_key_in_project_config_is_detected() {
        // skip-shell-integration-prompt is a user-config-only key
        let toml_str = "skip-shell-integration-prompt = true\n";
        let unknown = find_unknown_project_keys(toml_str);
        assert!(
            unknown.contains_key("skip-shell-integration-prompt"),
            "skip-shell-integration-prompt should be unknown in project config"
        );

        // Verify it's valid in user config
        let unknown_in_user = find_unknown_user_keys(toml_str);
        assert!(
            unknown_in_user.is_empty(),
            "skip-shell-integration-prompt should be valid in user config"
        );
    }

    #[test]
    fn test_project_config_key_in_user_config_is_detected() {
        // ci is a project-config-only key
        let toml_str = r#"
[ci]
platform = "github"
"#;
        let unknown = find_unknown_user_keys(toml_str);
        assert!(
            unknown.contains_key("ci"),
            "ci should be unknown in user config"
        );

        // Verify it's valid in project config
        let unknown_in_project = find_unknown_project_keys(toml_str);
        assert!(
            unknown_in_project.is_empty(),
            "ci should be valid in project config"
        );
    }
}