autom8-cli 0.3.0

CLI automation tool for orchestrating Claude-powered development
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
//! Config command handler.
//!
//! Displays, modifies, and resets autom8 configuration values.

use crate::config::{
    global_config_path, load_global_config, load_project_config, project_config_path,
    save_global_config, save_project_config, validate_config, Config,
};
use crate::error::{Autom8Error, Result};
use crate::git::is_git_repo;
use crate::output::{BOLD, CYAN, GRAY, GREEN, RESET, YELLOW};
use clap::Subcommand;
use std::fs;

/// Valid configuration keys that can be set via `config set`.
pub const VALID_CONFIG_KEYS: &[&str] = &[
    "review",
    "commit",
    "pull_request",
    "pull_request_draft",
    "worktree",
    "worktree_path_pattern",
    "worktree_cleanup",
];

/// Scope for config operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigScope {
    /// Global configuration (~/.config/autom8/config.toml)
    Global,
    /// Project-specific configuration (~/.config/autom8/<project>/config.toml)
    Project,
    /// Both global and project configurations
    Both,
}

/// Subcommands for the config command.
#[derive(Subcommand, Debug, Clone)]
pub enum ConfigSubcommand {
    /// Set a configuration value
    #[command(after_help = "EXAMPLES:
    autom8 config set review false            # Disable review step in project config
    autom8 config set --global commit true    # Enable auto-commit globally
    autom8 config set worktree_path_pattern \"{repo}-feature-{branch}\"

VALID KEYS:
    review              - Enable code review step (true/false)
    commit              - Enable auto-commit (true/false)
    pull_request        - Enable auto-PR creation (true/false, requires commit=true)
    pull_request_draft  - Create PRs as drafts (true/false, requires pull_request=true)
    worktree            - Enable worktree mode (true/false)
    worktree_path_pattern - Pattern for worktree directory names (string)
    worktree_cleanup    - Auto-cleanup worktrees after completion (true/false)

VALUE FORMATS:
    Boolean: true, false (case-insensitive)
    String:  Quoted or unquoted text

VALIDATION:
    - Setting pull_request=true requires commit=true
    - Invalid keys or values are rejected with an error message")]
    Set {
        /// Set in global config instead of project config
        #[arg(short, long)]
        global: bool,

        /// The configuration key to set
        key: String,

        /// The value to set
        value: String,
    },

    /// Reset configuration to default values
    #[command(after_help = "EXAMPLES:
    autom8 config reset               # Reset project config (with confirmation)
    autom8 config reset --global      # Reset global config (with confirmation)
    autom8 config reset -y            # Reset without confirmation prompt
    autom8 config reset --global -y   # Reset global config without prompting

DEFAULT VALUES:
    review              = true
    commit              = true
    pull_request        = true
    pull_request_draft  = false
    worktree            = true
    worktree_path_pattern = \"{repo}-wt-{branch}\"
    worktree_cleanup    = false

BEHAVIOR:
    - Prompts for confirmation before resetting (unless -y/--yes is used)
    - Overwrites the config file with default values
    - Displays the new configuration after reset
    - If config file doesn't exist, informs you defaults are already in use")]
    Reset {
        /// Reset global config instead of project config
        #[arg(short, long)]
        global: bool,

        /// Skip confirmation prompt
        #[arg(short, long)]
        yes: bool,
    },
}

/// Display configuration values.
///
/// Shows the configuration in TOML format. When scope is `Both`, displays
/// global config first with a header, then project config with its header.
///
/// # Arguments
///
/// * `scope` - Which configuration(s) to display
///
/// # Returns
///
/// * `Ok(())` on success
/// * `Err(Autom8Error)` if the configuration cannot be read
pub fn config_display_command(scope: ConfigScope) -> Result<()> {
    match scope {
        ConfigScope::Global => display_global_config(),
        ConfigScope::Project => display_project_config(),
        ConfigScope::Both => {
            display_global_config()?;
            println!();
            display_project_config()
        }
    }
}

/// Display the global configuration.
fn display_global_config() -> Result<()> {
    println!("{BOLD}# Global config{RESET}");
    println!("{GRAY}# {}{RESET}", global_config_path()?.display());
    println!();

    let config_path = global_config_path()?;

    if !config_path.exists() {
        println!("{YELLOW}# (file does not exist, using defaults){RESET}");
        println!();
        print_config_as_toml(&Config::default());
        return Ok(());
    }

    let config = load_config_from_path(&config_path)?;
    print_config_as_toml(&config);

    Ok(())
}

/// Display the project configuration.
fn display_project_config() -> Result<()> {
    // Check if we're in a git repo - required for project config
    if !is_git_repo() {
        return Err(Autom8Error::Config(
            "Not in a git repository.\n\n\
            Project configuration requires being inside a git repository.\n\
            Run this command from within a git repository, or use --global to view global config."
                .to_string(),
        ));
    }

    println!("{BOLD}# Project config{RESET}");
    println!("{GRAY}# {}{RESET}", project_config_path()?.display());
    println!();

    let config_path = project_config_path()?;

    if !config_path.exists() {
        println!("{YELLOW}# (file does not exist, using global config or defaults){RESET}");
        println!();
        // Show what would be effective - either global config or defaults
        let effective_config = if global_config_path()?.exists() {
            load_config_from_path(&global_config_path()?)?
        } else {
            Config::default()
        };
        print_config_as_toml(&effective_config);
        return Ok(());
    }

    let config = load_config_from_path(&config_path)?;
    print_config_as_toml(&config);

    Ok(())
}

/// Load a config from a specific path without any fallback logic.
fn load_config_from_path(path: &std::path::Path) -> Result<Config> {
    let content = fs::read_to_string(path)?;
    toml::from_str(&content).map_err(|e| {
        Autom8Error::Config(format!("Failed to parse config file at {:?}: {}", path, e))
    })
}

// ============================================================================
// Config Set Command (US-002)
// ============================================================================

/// Set a configuration value.
///
/// Sets a single configuration key to the specified value, with immediate
/// validation. Creates the config file if it doesn't exist.
///
/// # Arguments
///
/// * `key` - The configuration key to set (e.g., "review", "commit")
/// * `value` - The value to set (booleans: "true"/"false", strings as-is)
/// * `global` - If true, sets in global config; otherwise in project config
///
/// # Returns
///
/// * `Ok(())` on success
/// * `Err(Autom8Error)` if the key is invalid, value is invalid, or validation fails
pub fn config_set_command(key: &str, value: &str, global: bool) -> Result<()> {
    // Validate the key
    if !VALID_CONFIG_KEYS.contains(&key) {
        return Err(Autom8Error::Config(format!(
            "Invalid configuration key: '{}'\n\n\
            Valid keys are:\n  - {}\n\n\
            Use 'autom8 config set --help' for more information.",
            key,
            VALID_CONFIG_KEYS.join("\n  - ")
        )));
    }

    // Check if we're in a git repo for project config
    if !global && !is_git_repo() {
        return Err(Autom8Error::Config(
            "Not in a git repository.\n\n\
            Project configuration requires being inside a git repository.\n\
            Either:\n  - Run this command from within a git repository, or\n  - Use --global to set the global config."
                .to_string(),
        ));
    }

    // Load the current config (create default if doesn't exist)
    let mut config = if global {
        load_global_config()?
    } else {
        load_project_config()?
    };

    // Parse and set the value
    set_config_value(&mut config, key, value)?;

    // Validate the resulting configuration
    validate_config(&config).map_err(|e| Autom8Error::Config(e.to_string()))?;

    // Save the config
    let config_type = if global { "global" } else { "project" };
    if global {
        save_global_config(&config)?;
    } else {
        save_project_config(&config)?;
    }

    // Print confirmation
    let display_value = format_value_for_display(key, &config);
    println!("{GREEN}Set {CYAN}{key}{RESET} = {display_value} in {config_type} config{RESET}");

    Ok(())
}

/// Set a configuration value on a Config struct.
///
/// Parses the string value and sets the appropriate field.
fn set_config_value(config: &mut Config, key: &str, value: &str) -> Result<()> {
    match key {
        "review" => {
            config.review = parse_bool_value(value, key)?;
        }
        "commit" => {
            config.commit = parse_bool_value(value, key)?;
        }
        "pull_request" => {
            config.pull_request = parse_bool_value(value, key)?;
        }
        "pull_request_draft" => {
            config.pull_request_draft = parse_bool_value(value, key)?;
        }
        "worktree" => {
            config.worktree = parse_bool_value(value, key)?;
        }
        "worktree_path_pattern" => {
            config.worktree_path_pattern = value.to_string();
        }
        "worktree_cleanup" => {
            config.worktree_cleanup = parse_bool_value(value, key)?;
        }
        _ => {
            // This shouldn't happen if VALID_CONFIG_KEYS is kept in sync
            return Err(Autom8Error::Config(format!("Unknown key: {}", key)));
        }
    }
    Ok(())
}

/// Parse a boolean value from a string (case-insensitive).
fn parse_bool_value(value: &str, key: &str) -> Result<bool> {
    match value.to_lowercase().as_str() {
        "true" => Ok(true),
        "false" => Ok(false),
        _ => Err(Autom8Error::Config(format!(
            "Invalid value for '{}': expected boolean (true/false), got '{}'",
            key, value
        ))),
    }
}

/// Format a config value for display in the confirmation message.
fn format_value_for_display(key: &str, config: &Config) -> String {
    match key {
        "review" => config.review.to_string(),
        "commit" => config.commit.to_string(),
        "pull_request" => config.pull_request.to_string(),
        "pull_request_draft" => config.pull_request_draft.to_string(),
        "worktree" => config.worktree.to_string(),
        "worktree_path_pattern" => format!("\"{}\"", config.worktree_path_pattern),
        "worktree_cleanup" => config.worktree_cleanup.to_string(),
        _ => "unknown".to_string(),
    }
}

// ============================================================================
// Config Reset Command (US-003)
// ============================================================================

/// Reset configuration to default values.
///
/// Resets the specified config file to default values. Prompts for
/// confirmation before resetting (unless `--yes` is used).
///
/// # Arguments
///
/// * `global` - If true, resets global config; otherwise resets project config
/// * `yes` - If true, skips confirmation prompt
///
/// # Returns
///
/// * `Ok(())` on success
/// * `Err(Autom8Error)` if the reset fails or user cancels
pub fn config_reset_command(global: bool, yes: bool) -> Result<()> {
    // Check if we're in a git repo for project config
    if !global && !is_git_repo() {
        return Err(Autom8Error::Config(
            "Not in a git repository.\n\n\
            Project configuration requires being inside a git repository.\n\
            Either:\n  - Run this command from within a git repository, or\n  - Use --global to reset the global config."
                .to_string(),
        ));
    }

    let config_type = if global { "global" } else { "project" };
    let config_path = if global {
        global_config_path()?
    } else {
        project_config_path()?
    };

    // Check if config file exists
    if !config_path.exists() {
        println!(
            "{YELLOW}Config file does not exist: {}{RESET}",
            config_path.display()
        );
        println!();
        println!("Default values are already in use:");
        println!();
        print_config_as_toml(&Config::default());
        return Ok(());
    }

    // Prompt for confirmation unless --yes is set
    if !yes {
        print!("Reset {} config to defaults? [y/N] ", config_type);
        std::io::Write::flush(&mut std::io::stdout())?;

        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;

        let input = input.trim().to_lowercase();
        if input != "y" && input != "yes" {
            println!("{YELLOW}Reset cancelled.{RESET}");
            return Ok(());
        }
    }

    // Create default config and save it
    let default_config = Config::default();

    if global {
        save_global_config(&default_config)?;
    } else {
        save_project_config(&default_config)?;
    }

    // Print confirmation and new config
    println!("{GREEN}Reset {} config to defaults:{RESET}", config_type);
    println!();
    print_config_as_toml(&default_config);

    Ok(())
}

/// Print a Config struct as valid TOML format.
fn print_config_as_toml(config: &Config) {
    println!("{CYAN}review{RESET} = {}", config.review);
    println!("{CYAN}commit{RESET} = {}", config.commit);
    println!("{CYAN}pull_request{RESET} = {}", config.pull_request);
    println!(
        "{CYAN}pull_request_draft{RESET} = {}",
        config.pull_request_draft
    );
    println!("{CYAN}worktree{RESET} = {}", config.worktree);
    println!(
        "{CYAN}worktree_path_pattern{RESET} = \"{}\"",
        config.worktree_path_pattern
    );
    println!(
        "{CYAN}worktree_cleanup{RESET} = {}",
        config.worktree_cleanup
    );
}

/// Convert a Config to a TOML string (for testing).
#[cfg(test)]
fn config_to_toml_string(config: &Config) -> String {
    format!(
        "review = {}\n\
         commit = {}\n\
         pull_request = {}\n\
         pull_request_draft = {}\n\
         worktree = {}\n\
         worktree_path_pattern = \"{}\"\n\
         worktree_cleanup = {}",
        config.review,
        config.commit,
        config.pull_request,
        config.pull_request_draft,
        config.worktree,
        config.worktree_path_pattern,
        config.worktree_cleanup
    )
}

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

    // ========================================================================
    // US-001: Config display tests
    // ========================================================================

    #[test]
    fn test_us001_config_to_toml_produces_valid_toml() {
        let config = Config::default();
        let toml_str = config_to_toml_string(&config);

        // Parse the generated TOML to verify it's valid
        let parsed: std::result::Result<Config, _> = toml::from_str(&toml_str);
        assert!(
            parsed.is_ok(),
            "Generated TOML should be parseable: {:?}",
            parsed.err()
        );

        // Verify the parsed config matches the original
        let parsed_config = parsed.unwrap();
        assert_eq!(parsed_config, config);
    }

    #[test]
    fn test_us001_config_to_toml_includes_all_fields() {
        let config = Config {
            review: false,
            commit: true,
            pull_request: false,
            pull_request_draft: true,
            worktree: false,
            worktree_path_pattern: "custom-{branch}".to_string(),
            worktree_cleanup: true,
        };
        let toml_str = config_to_toml_string(&config);

        assert!(toml_str.contains("review = false"));
        assert!(toml_str.contains("commit = true"));
        assert!(toml_str.contains("pull_request = false"));
        assert!(toml_str.contains("pull_request_draft = true"));
        assert!(toml_str.contains("worktree = false"));
        assert!(toml_str.contains("worktree_path_pattern = \"custom-{branch}\""));
        assert!(toml_str.contains("worktree_cleanup = true"));
    }

    #[test]
    fn test_us001_config_to_toml_default_values() {
        let config = Config::default();
        let toml_str = config_to_toml_string(&config);

        // Verify default values are correct
        assert!(toml_str.contains("review = true"));
        assert!(toml_str.contains("commit = true"));
        assert!(toml_str.contains("pull_request = true"));
        assert!(toml_str.contains("worktree = true"));
        assert!(toml_str.contains("worktree_path_pattern = \"{repo}-wt-{branch}\""));
        assert!(toml_str.contains("worktree_cleanup = false"));
    }

    #[test]
    fn test_us001_config_scope_variants() {
        // Verify all scope variants exist and are distinct
        assert_ne!(ConfigScope::Global, ConfigScope::Project);
        assert_ne!(ConfigScope::Global, ConfigScope::Both);
        assert_ne!(ConfigScope::Project, ConfigScope::Both);
    }

    // ========================================================================
    // US-002: Config set tests
    // ========================================================================

    #[test]
    fn test_us002_valid_config_keys_constant() {
        // Verify all expected keys are in the VALID_CONFIG_KEYS constant
        assert!(VALID_CONFIG_KEYS.contains(&"review"));
        assert!(VALID_CONFIG_KEYS.contains(&"commit"));
        assert!(VALID_CONFIG_KEYS.contains(&"pull_request"));
        assert!(VALID_CONFIG_KEYS.contains(&"pull_request_draft"));
        assert!(VALID_CONFIG_KEYS.contains(&"worktree"));
        assert!(VALID_CONFIG_KEYS.contains(&"worktree_path_pattern"));
        assert!(VALID_CONFIG_KEYS.contains(&"worktree_cleanup"));
        assert_eq!(
            VALID_CONFIG_KEYS.len(),
            7,
            "Should have exactly 7 valid keys"
        );
    }

    #[test]
    fn test_us002_parse_bool_value_true() {
        // Test various true spellings (case-insensitive)
        assert!(parse_bool_value("true", "test").unwrap());
        assert!(parse_bool_value("TRUE", "test").unwrap());
        assert!(parse_bool_value("True", "test").unwrap());
        assert!(parse_bool_value("tRuE", "test").unwrap());
    }

    #[test]
    fn test_us002_parse_bool_value_false() {
        // Test various false spellings (case-insensitive)
        assert!(!parse_bool_value("false", "test").unwrap());
        assert!(!parse_bool_value("FALSE", "test").unwrap());
        assert!(!parse_bool_value("False", "test").unwrap());
        assert!(!parse_bool_value("fAlSe", "test").unwrap());
    }

    #[test]
    fn test_us002_parse_bool_value_invalid() {
        // Test invalid values
        let result = parse_bool_value("yes", "review");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Invalid value for 'review'"));
        assert!(err.contains("expected boolean"));
        assert!(err.contains("yes"));

        let result = parse_bool_value("1", "commit");
        assert!(result.is_err());

        let result = parse_bool_value("on", "worktree");
        assert!(result.is_err());

        let result = parse_bool_value("", "review");
        assert!(result.is_err());
    }

    #[test]
    fn test_us002_set_config_value_review() {
        let mut config = Config::default();
        assert!(config.review); // default is true

        set_config_value(&mut config, "review", "false").unwrap();
        assert!(!config.review);

        set_config_value(&mut config, "review", "true").unwrap();
        assert!(config.review);
    }

    #[test]
    fn test_us002_set_config_value_commit() {
        let mut config = Config::default();
        set_config_value(&mut config, "commit", "false").unwrap();
        assert!(!config.commit);
    }

    #[test]
    fn test_us002_set_config_value_pull_request() {
        let mut config = Config::default();
        set_config_value(&mut config, "pull_request", "false").unwrap();
        assert!(!config.pull_request);
    }

    #[test]
    fn test_us002_set_config_value_worktree() {
        let mut config = Config::default();
        set_config_value(&mut config, "worktree", "false").unwrap();
        assert!(!config.worktree);
    }

    #[test]
    fn test_us002_set_config_value_worktree_cleanup() {
        let mut config = Config::default();
        assert!(!config.worktree_cleanup); // default is false

        set_config_value(&mut config, "worktree_cleanup", "true").unwrap();
        assert!(config.worktree_cleanup);
    }

    #[test]
    fn test_us002_set_config_value_worktree_path_pattern() {
        let mut config = Config::default();
        let custom_pattern = "{repo}-feature-{branch}";

        set_config_value(&mut config, "worktree_path_pattern", custom_pattern).unwrap();
        assert_eq!(config.worktree_path_pattern, custom_pattern);
    }

    #[test]
    fn test_us002_set_config_value_worktree_path_pattern_with_spaces() {
        let mut config = Config::default();
        let pattern_with_spaces = "my-repo wt {branch}";

        set_config_value(&mut config, "worktree_path_pattern", pattern_with_spaces).unwrap();
        assert_eq!(config.worktree_path_pattern, pattern_with_spaces);
    }

    #[test]
    fn test_us002_format_value_for_display_boolean() {
        let mut config = Config::default();
        config.review = true;
        config.commit = false;

        assert_eq!(format_value_for_display("review", &config), "true");
        assert_eq!(format_value_for_display("commit", &config), "false");
    }

    #[test]
    fn test_us002_format_value_for_display_string() {
        let mut config = Config::default();
        config.worktree_path_pattern = "custom-{branch}".to_string();

        // String values should be quoted
        assert_eq!(
            format_value_for_display("worktree_path_pattern", &config),
            "\"custom-{branch}\""
        );
    }

    #[test]
    fn test_us002_invalid_key_rejected() {
        let mut config = Config::default();
        let result = set_config_value(&mut config, "invalid_key", "value");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Unknown key"));
    }

    #[test]
    fn test_us002_all_valid_keys_settable() {
        // Verify each valid key can be set
        for key in VALID_CONFIG_KEYS.iter() {
            let mut config = Config::default();
            let value = match *key {
                "worktree_path_pattern" => "custom-pattern",
                _ => "false", // Boolean keys
            };
            let result = set_config_value(&mut config, key, value);
            assert!(result.is_ok(), "Setting key '{}' should succeed", key);
        }
    }

    #[test]
    fn test_us002_validation_enforced_pr_without_commit() {
        // Test that setting pull_request=true when commit=false would fail validation
        let mut config = Config {
            review: true,
            commit: false,
            pull_request: false,
            ..Default::default()
        };

        // Set pull_request to true
        set_config_value(&mut config, "pull_request", "true").unwrap();

        // The config should fail validation (this is what config_set_command checks)
        let validation_result = validate_config(&config);
        assert!(validation_result.is_err());
        assert!(validation_result
            .unwrap_err()
            .to_string()
            .contains("commit"));
    }

    #[test]
    fn test_us002_validation_enforced_commit_false_with_pr_true() {
        // Test that setting commit=false when pull_request=true would fail validation
        let mut config = Config {
            review: true,
            commit: true,
            pull_request: true,
            ..Default::default()
        };

        // Set commit to false
        set_config_value(&mut config, "commit", "false").unwrap();

        // The config should fail validation
        let validation_result = validate_config(&config);
        assert!(validation_result.is_err());
    }

    #[test]
    fn test_us002_valid_combinations_pass_validation() {
        // Test valid combinations
        let valid_combos = [
            (true, true, true),   // all true
            (true, true, false),  // commit true, pr false
            (true, false, false), // commit false, pr false
            (false, true, true),  // review false, others true
        ];

        for (review, commit, pull_request) in valid_combos {
            let config = Config {
                review,
                commit,
                pull_request,
                ..Default::default()
            };
            let result = validate_config(&config);
            assert!(
                result.is_ok(),
                "Config (review={}, commit={}, pull_request={}) should be valid",
                review,
                commit,
                pull_request
            );
        }
    }

    #[test]
    fn test_us002_case_insensitive_boolean_values() {
        let mut config = Config::default();

        // Test various case combinations
        set_config_value(&mut config, "review", "TRUE").unwrap();
        assert!(config.review);

        set_config_value(&mut config, "review", "False").unwrap();
        assert!(!config.review);

        set_config_value(&mut config, "worktree", "TrUe").unwrap();
        assert!(config.worktree);
    }

    #[test]
    fn test_us002_invalid_boolean_value_descriptive_error() {
        let result = parse_bool_value("yes", "review");
        assert!(result.is_err());

        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("review"), "Error should mention the key");
        assert!(
            error_msg.contains("boolean"),
            "Error should mention expected type"
        );
        assert!(
            error_msg.contains("true/false"),
            "Error should mention valid values"
        );
        assert!(
            error_msg.contains("yes"),
            "Error should mention the invalid value"
        );
    }

    // ========================================================================
    // US-003: Config reset tests
    // ========================================================================

    #[test]
    fn test_us003_config_reset_function_exists() {
        // Verify the config_reset_command function exists and has correct signature
        use super::config_reset_command;
        let _: fn(bool, bool) -> Result<()> = config_reset_command;
    }

    #[test]
    fn test_us003_default_config_values() {
        // Verify the default config values that reset would restore
        let config = Config::default();
        assert!(config.review, "default review should be true");
        assert!(config.commit, "default commit should be true");
        assert!(config.pull_request, "default pull_request should be true");
        assert!(config.worktree, "default worktree should be true");
        assert_eq!(
            config.worktree_path_pattern, "{repo}-wt-{branch}",
            "default worktree_path_pattern should be '{{repo}}-wt-{{branch}}'"
        );
        assert!(
            !config.worktree_cleanup,
            "default worktree_cleanup should be false"
        );
    }

    #[test]
    fn test_us003_reset_produces_defaults() {
        // Verify that a reset would produce the same values as Config::default()
        let reset_config = Config::default();
        let expected = Config::default();

        assert_eq!(reset_config.review, expected.review);
        assert_eq!(reset_config.commit, expected.commit);
        assert_eq!(reset_config.pull_request, expected.pull_request);
        assert_eq!(reset_config.worktree, expected.worktree);
        assert_eq!(
            reset_config.worktree_path_pattern,
            expected.worktree_path_pattern
        );
        assert_eq!(reset_config.worktree_cleanup, expected.worktree_cleanup);
    }

    #[test]
    fn test_us003_config_toml_from_default() {
        // Verify the default config serializes correctly to TOML
        let config = Config::default();
        let toml_str = config_to_toml_string(&config);

        // Should contain all default values
        assert!(toml_str.contains("review = true"));
        assert!(toml_str.contains("commit = true"));
        assert!(toml_str.contains("pull_request = true"));
        assert!(toml_str.contains("worktree = true"));
        assert!(toml_str.contains("worktree_path_pattern = \"{repo}-wt-{branch}\""));
        assert!(toml_str.contains("worktree_cleanup = false"));
    }

    #[test]
    fn test_us003_reset_toml_round_trip() {
        // Verify the default config can be written and read back correctly
        let default_config = Config::default();
        let toml_str = config_to_toml_string(&default_config);

        let parsed: Config = toml::from_str(&toml_str).unwrap();
        assert_eq!(parsed.review, default_config.review);
        assert_eq!(parsed.commit, default_config.commit);
        assert_eq!(parsed.pull_request, default_config.pull_request);
        assert_eq!(parsed.worktree, default_config.worktree);
        assert_eq!(
            parsed.worktree_path_pattern,
            default_config.worktree_path_pattern
        );
        assert_eq!(parsed.worktree_cleanup, default_config.worktree_cleanup);
    }

    #[test]
    fn test_us003_modified_config_differs_from_default() {
        // Verify we can detect when a config differs from default
        let mut modified = Config::default();
        modified.review = false;
        modified.commit = false;
        modified.worktree_path_pattern = "custom-{branch}".to_string();

        let default = Config::default();

        assert_ne!(modified.review, default.review);
        assert_ne!(modified.commit, default.commit);
        assert_ne!(
            modified.worktree_path_pattern,
            default.worktree_path_pattern
        );
    }

    #[test]
    fn test_us003_global_vs_project_config_paths_different() {
        // Verify global and project config paths are different
        // (reset should only affect the specified config)
        let global_path = global_config_path();
        let project_path = project_config_path();

        // Both should succeed or global succeeds and project fails (not in git repo)
        if let (Ok(global), Ok(project)) = (global_path, project_path) {
            assert_ne!(
                global, project,
                "Global and project config paths should be different"
            );
        }
    }

    #[test]
    fn test_us003_save_global_config_available() {
        // Verify save_global_config function is available (used by reset)
        let config = Config::default();
        // Just verify the function exists and accepts the right type
        // We don't call it in tests to avoid side effects
        let _ = &config; // Suppress unused warning
                         // The actual function call would be: save_global_config(&config)
    }

    #[test]
    fn test_us003_save_project_config_available() {
        // Verify save_project_config function is available (used by reset)
        let config = Config::default();
        let _ = &config;
        // The actual function call would be: save_project_config(&config)
    }
}