nitpicker 0.9.2

Multi-reviewer code review using LLMs with parallel agents and debate mode
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
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
use clap::{Args as ClapArgs, Parser, Subcommand};
use eyre::{Result, WrapErr};
use std::path::{Path, PathBuf};
use tracing_subscriber::EnvFilter;

use nitpicker_agent::{config, openrouter};

mod context;
mod debate;
mod detect;
#[cfg(feature = "antigravity")]
mod gemini_proxy;
mod output;
mod pr;
mod presets;
mod progress;
mod prompts;
mod proxy;
mod reflect;
mod review;

/// Flags shared across the default review mode and the subcommands. Declared once here and
/// marked `global`, so they are accepted before or after a subcommand and always land in
/// `Args.common` — per-subcommand copies would be independent namespaces, and a flag parsed
/// into the copy an arm doesn't read would be silently dropped.
#[derive(Debug, ClapArgs)]
struct CommonArgs {
    #[arg(long, global = true, default_value = ".")]
    repo: PathBuf,

    #[arg(long, global = true)]
    config: Option<PathBuf>,

    #[arg(long, short, global = true)]
    verbose: bool,

    /// Try the next configured reviewer when the selected model fails
    #[arg(long, global = true)]
    fallback: bool,
}

/// `--context-file`, kept out of the global `CommonArgs` deliberately: clap propagates a global
/// arg by keeping one winning occurrence list (the subcommand's), so a repeatable flag split
/// around the subcommand would silently drop the root's values. Instead this struct is flattened
/// at the root and into `ask`/`pr`, and the two vectors are concatenated root-first (= the
/// command-line order) at each use site.
#[derive(Debug, ClapArgs)]
struct ContextFileArgs {
    /// Read a file into the prompt verbatim; repeatable. Unlike the agents' own tools, this is not
    /// confined to the repo, so it can carry design notes or working docs that live outside it.
    #[arg(long = "context-file", value_name = "PATH")]
    context_file: Vec<PathBuf>,
}

fn merged_context_files(root: &ContextFileArgs, sub: &ContextFileArgs) -> Vec<PathBuf> {
    root.context_file
        .iter()
        .chain(&sub.context_file)
        .cloned()
        .collect()
}

/// `--preset`, shaped exactly like `ContextFileArgs` and for the same reason: a repeatable
/// flag must not be `global` (clap would keep only the subcommand's occurrence list), so it
/// is flattened at the root and into `pr`, and merged root-first at each use site.
#[derive(Debug, ClapArgs)]
struct PresetArgs {
    /// Review preset(s) to run — repeatable and comma-separated (e.g. --preset security,ml-rigor).
    /// Replaces the configured `[defaults].presets` list for this run.
    #[arg(long = "preset", value_name = "NAME", value_delimiter = ',')]
    preset: Vec<String>,
}

fn merged_presets(root: &PresetArgs, sub: &PresetArgs) -> Vec<String> {
    root.preset.iter().chain(&sub.preset).cloned().collect()
}

/// Presets pick review rubrics; `ask`/`init`/`reflect` have none. Root-position `--preset`
/// parses fine before any subcommand, so without an explicit rejection it would be silently
/// discarded there (`pr` and the default review arms consume it).
fn presets_allowed(command: &Option<Command>) -> bool {
    match command {
        None | Some(Command::Pr(_)) => true,
        Some(Command::Ask { .. } | Command::Init { .. } | Command::Reflect { .. }) => false,
    }
}

fn fallback_allowed(command: &Option<Command>) -> bool {
    matches!(command, None | Some(Command::Ask { .. } | Command::Pr(_)))
}

pub(crate) fn resolve_routing_modes(
    config: &config::Config,
    cli_alloy: bool,
    cli_fallback: bool,
) -> Result<(bool, bool)> {
    let alloy = cli_alloy || config.default_alloy();
    config.validate_alloy(alloy)?;
    let fallback = cli_fallback || config.default_fallback();
    config.validate_fallback(fallback)?;
    Ok((alloy, fallback))
}

#[derive(Debug, Parser)]
#[command(name = "nitpicker")]
struct Args {
    #[command(subcommand)]
    command: Option<Command>,

    #[command(flatten)]
    common: CommonArgs,

    #[command(flatten)]
    context: ContextFileArgs,

    #[command(flatten)]
    presets: PresetArgs,

    #[arg(
        long,
        help = "Additional review instructions appended to the diff context (use `ask` for fully custom prompts)"
    )]
    prompt: Option<String>,

    /// Analyze existing code instead of reviewing changes
    #[arg(long, value_name = "PATH", num_args = 0..=1, default_missing_value = "")]
    analyze: Option<PathBuf>,

    /// Disable actor-critic debate and use parallel aggregation instead
    #[arg(long)]
    no_debate: bool,

    /// Mix all reviewer models into a shared pool; each LLM call picks one at random
    #[arg(long)]
    alloy: bool,

    /// Maximum debate rounds
    #[arg(long, default_value = "5")]
    rounds: usize,

    /// Maximum tool-use turns per agent or debate turn
    #[arg(long, value_parser = parse_positive_usize)]
    max_turns: Option<usize>,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Generate a nitpicker config template
    Init {
        /// Write to ~/.nitpicker/config.toml instead of <repo>/nitpicker.toml
        #[arg(long)]
        global: bool,

        /// Prefer OpenRouter experimental free models in the generated config
        #[arg(long)]
        free: bool,
    },
    /// Ask multiple LLM agents a free-form question about the codebase
    Ask {
        #[command(flatten)]
        context: ContextFileArgs,
        /// Question or topic to discuss
        topic: String,
        /// Disable actor-critic debate and use parallel aggregation instead
        #[arg(long)]
        no_debate: bool,
        /// Mix all reviewer models into a shared pool; each LLM call picks one at random
        #[arg(long)]
        alloy: bool,
        /// Maximum debate rounds
        #[arg(long, default_value = "5")]
        rounds: usize,
        /// Maximum tool-use turns per agent or debate turn
        #[arg(long, value_parser = parse_positive_usize)]
        max_turns: Option<usize>,
    },
    /// Review a GitHub PR (current branch's PR or a remote PR by URL)
    Pr(pr::PrArgs),
    /// Reflect on past nitpicker sessions to identify patterns and friction points
    Reflect {
        /// Directory containing sessions (default: ~/.nitpicker/sessions)
        #[arg(long)]
        sessions_dir: Option<PathBuf>,
        /// Number of most recent sessions to analyze
        #[arg(long, default_value = "20")]
        n: usize,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();

    let verbose = args.common.verbose;
    let is_reflect = matches!(&args.command, Some(Command::Reflect { .. }));
    let default_level = if verbose || is_reflect {
        "info"
    } else {
        "warn"
    };
    let filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_level));
    // logs are never the report — keep stdout reserved for the deliverable so
    // `pr --format json` emits a clean single JSON object.
    tracing_subscriber::fmt()
        .with_writer(progress::stderr_log_writer)
        .with_env_filter(filter)
        .with_target(false)
        .with_thread_ids(false)
        .with_thread_names(false)
        .with_file(false)
        .with_line_number(false)
        .with_level(true)
        .with_ansi(progress::stderr_supports_color())
        .compact()
        .init();

    if !presets_allowed(&args.command) && !args.presets.preset.is_empty() {
        eyre::bail!("--preset applies to review modes only (default review, --analyze, pr)");
    }
    if args.common.fallback && !fallback_allowed(&args.command) {
        eyre::bail!("--fallback applies to review and ask modes only");
    }

    // note: no json panic hook. reviewer work runs in tokio::spawn tasks whose
    // panics are caught as JoinError and folded into a degraded report (exit 3
    // for review/ask, status ok for pr); a process-wide hook would double-emit
    // there. a genuine top-level panic aborts non-zero with a stderr message,
    // which is an acceptable catastrophic-failure signal for the consumer.
    match args.command {
        Some(Command::Init { global, free }) => {
            // the global flags parse here too; `init` generates a config, so honoring --config
            // would be nonsense — reject it rather than silently ignore it
            if args.common.config.is_some() {
                eyre::bail!("--config has no effect on init, which generates a config file");
            }
            let path = init_config_path(global, &args.common.repo)?;
            if path.exists() {
                eyre::bail!("{} already exists", path.display());
            }
            run_init(path, free).await?;
            return Ok(());
        }
        Some(Command::Ask {
            context,
            topic,
            no_debate,
            alloy,
            rounds,
            max_turns,
        }) => {
            let repo = resolve_repo_root(&args.common.repo)?;
            let mut config = load_config(args.common.config.as_deref(), &repo)?;
            // CLI-only routing validation must precede free-model smoke completions.
            let (use_alloy, use_fallback) =
                resolve_routing_modes(&config, alloy, args.common.fallback)?;
            finalize_routing_config(&mut config, use_fallback).await?;
            let config = config;
            let topic = context::append_to_prompt(
                topic,
                &context::load_context_files(&merged_context_files(&args.context, &context))?,
            );
            let max_turns = config.max_turns(max_turns)?;

            if use_alloy && no_debate {
                eprintln!("warning: --alloy has no effect with --no-debate");
            }

            if !no_debate && config.default_debate() {
                if config.reviewer.len() < 2 {
                    eyre::bail!(
                        "debate mode requires at least 2 reviewers, found {} — add another reviewer or set debate = false in [defaults]",
                        config.reviewer.len()
                    );
                }
                let outcome = debate::run_debate(
                    &repo,
                    &topic,
                    &config,
                    debate::DebateOptions {
                        max_rounds: rounds,
                        max_turns,
                        verbose: args.common.verbose,
                        task: prompts::RunTask::Ask,
                        alloy: use_alloy,
                        fallback: use_fallback,
                        format: output::OutputFormat::Text,
                    },
                )
                .await?;
                println!("{}", outcome.report);
                if args.common.verbose {
                    eprintln!(
                        "\nTranscript saved to: {}",
                        outcome.transcript_path.display()
                    );
                }
                exit_if_degraded(outcome.degraded);
                return Ok(());
            }

            let outcome = review::run_review(
                &repo,
                &topic,
                &config,
                max_turns,
                args.common.verbose,
                prompts::RunTask::Ask,
                use_fallback,
            )
            .await?;
            println!("{}", outcome.report);
            exit_if_degraded(outcome.degraded);
            return Ok(());
        }
        Some(Command::Pr(pr_args)) => {
            let context_files = merged_context_files(&args.context, &pr_args.context);
            let preset_names = merged_presets(&args.presets, &pr_args.presets);
            // config loading happens inside run_pr so its failures honor --format json too
            let degraded = pr::run_pr(pr_args, args.common, context_files, preset_names).await?;
            exit_if_degraded(degraded);
            return Ok(());
        }
        Some(Command::Reflect { sessions_dir, n }) => {
            let repo = resolve_repo_root(&args.common.repo)?;
            let config = load_resolved_config(args.common.config.as_deref(), &repo).await?;
            return reflect::run_reflect(reflect::ReflectArgs {
                sessions_dir,
                n,
                repo,
                config,
            })
            .await;
        }
        None => {}
    }

    let repo = resolve_repo_root(&args.common.repo)?;

    let mut config = load_config(args.common.config.as_deref(), &repo)?;
    // Resolve presets and CLI-only routing validation before free-model resolution: pure usage
    // errors must fail before any network call (the resolver can run live smoke completions).
    let presets = presets::resolve(&args.presets.preset, &config)?;
    let (use_alloy, use_fallback) =
        resolve_routing_modes(&config, args.alloy, args.common.fallback)?;
    finalize_routing_config(&mut config, use_fallback).await?;
    let config = config;
    let max_turns = config.max_turns(args.max_turns)?;

    let scope = match args.analyze {
        Some(_) => prompts::ReviewScope::Static,
        None => prompts::ReviewScope::Diff,
    };
    let prompt = if let Some(path) = args.analyze {
        let path_opt = if path.as_os_str().is_empty() {
            None
        } else {
            Some(path.as_path())
        };
        build_analysis_prompt(path_opt, args.prompt.as_deref())
    } else {
        let base = detect_diff_context(&repo)?;
        match args.prompt {
            Some(p) => format!("{base}\n\nAdditional instructions: {p}"),
            None => base,
        }
    };
    let prompt = context::append_to_prompt(
        prompt,
        &context::load_context_files(&args.context.context_file)?,
    );

    if use_alloy && args.no_debate {
        eprintln!("warning: --alloy has no effect with --no-debate");
    }

    if !args.no_debate && config.default_debate() {
        if config.reviewer.len() < 2 {
            eyre::bail!(
                "debate mode requires at least 2 reviewers, found {} — add another reviewer or set debate = false in [defaults]",
                config.reviewer.len()
            );
        }
        let outcome = debate::run_debate(
            &repo,
            &prompt,
            &config,
            debate::DebateOptions {
                max_rounds: args.rounds,
                max_turns,
                verbose: args.common.verbose,
                task: prompts::RunTask::Review {
                    scope,
                    presets: &presets,
                },
                alloy: use_alloy,
                fallback: use_fallback,
                format: output::OutputFormat::Text,
            },
        )
        .await?;
        println!("{}", outcome.report);
        if args.common.verbose {
            eprintln!(
                "\nTranscript saved to: {}",
                outcome.transcript_path.display()
            );
        }
        exit_if_degraded(outcome.degraded);
        Ok(())
    } else {
        let outcome = review::run_review(
            &repo,
            &prompt,
            &config,
            max_turns,
            args.common.verbose,
            prompts::RunTask::Review {
                scope,
                presets: &presets,
            },
            use_fallback,
        )
        .await?;
        println!("{}", outcome.report);
        exit_if_degraded(outcome.degraded);
        Ok(())
    }
}

/// Exit-code contract for the default-review, `ask`, and `pr` arms: 0 = clean verdict,
/// 1 = hard failure (no verdict), 3 = degraded verdict (report printed, but at least one
/// reviewer or debate turn failed). 2 is deliberately unused — clap exits 2
/// on usage errors, and the whole point is an unambiguous subprocess signal.
/// In `pr --json` the envelope (carrying `degraded: true`) is emitted and flushed first,
/// and `run_pr` returns before this runs, so its checkout-restore guards have dropped.
fn exit_if_degraded(degraded: bool) {
    if !degraded {
        return;
    }
    // process::exit skips stdout teardown; without a flush a piped report would be lost
    // (same reasoning as output::emit_json).
    match std::io::Write::flush(&mut std::io::stdout()) {
        Ok(()) => {}
        Err(err) => {
            eprintln!("error: failed to flush report to stdout: {err}");
            std::process::exit(1);
        }
    }
    eprintln!("warning: degraded verdict — a reviewer or debate turn failed (exit code 3)");
    std::process::exit(3);
}

pub(crate) fn load_config(explicit_path: Option<&Path>, repo: &Path) -> Result<config::Config> {
    let config: config::Config = if let Some(path) = explicit_path {
        let content = std::fs::read_to_string(path)
            .map_err(|e| eyre::eyre!("failed to read config {:?}: {e}", path))?;
        toml::from_str(&content).map_err(|e| eyre::eyre!("invalid config: {e}"))?
    } else if repo.join("nitpicker.toml").exists() {
        let path = repo.join("nitpicker.toml");
        let content = std::fs::read_to_string(&path)
            .map_err(|e| eyre::eyre!("failed to read config {:?}: {e}", path))?;
        toml::from_str(&content).map_err(|e| eyre::eyre!("invalid config: {e}"))?
    } else {
        return load_global_config();
    };
    config.validate_structure()?;
    Ok(config)
}

/// Resolve the worktree containing `path` through Git itself. Linked worktrees and checked-out
/// submodules represent `.git` as a file, so its filesystem shape is not a repository invariant.
pub(crate) fn git_worktree_root(path: &Path) -> Option<PathBuf> {
    let output = std::process::Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(path)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }

    let root = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
    root.canonicalize().ok()
}

fn resolve_repo_root(path: &Path) -> Result<PathBuf> {
    let canonical = path
        .canonicalize()
        .wrap_err("failed to canonicalize --repo path")?;
    git_worktree_root(&canonical)
        .ok_or_else(|| eyre::eyre!("--repo must point inside a Git worktree"))
}

/// The `~/.nitpicker/config.toml` fallback alone — `pr` mode reaches for this directly,
/// since its repo-level config comes from the PR base branch blob, never the working tree.
pub(crate) fn load_global_config() -> Result<config::Config> {
    let path = dirs::home_dir()
        .map(|home| home.join(".nitpicker").join("config.toml"))
        .filter(|path| path.exists())
        .ok_or_else(|| {
            eyre::eyre!("no config found — run `nitpicker init [--global]` to generate one")
        })?;
    let content = std::fs::read_to_string(&path)
        .map_err(|e| eyre::eyre!("failed to read config {:?}: {e}", path))?;
    let config: config::Config =
        toml::from_str(&content).map_err(|e| eyre::eyre!("invalid config: {e}"))?;
    config.validate_structure()?;
    Ok(config)
}

pub(crate) async fn load_resolved_config(
    explicit_path: Option<&Path>,
    repo: &Path,
) -> Result<config::Config> {
    let mut config = load_config(explicit_path, repo)?;
    finalize_routing_config(&mut config, false).await?;
    Ok(config)
}

/// Finish config validation and experimental route resolution after the caller has resolved the
/// effective CLI/config fallback mode. Strict execution requires every credential up front;
/// fallback execution lets route construction skip unusable entries.
pub(crate) async fn finalize_routing_config(
    config: &mut config::Config,
    fallback: bool,
) -> Result<()> {
    if !fallback {
        config.validate_credentials()?;
    }
    openrouter::resolve_free_models_with_fallback(config, fallback).await
}

async fn run_init(path: PathBuf, prefer_free: bool) -> eyre::Result<()> {
    println!("Detecting available providers...\n");
    let detected = detect::detect_all().await;

    if detected.is_empty() {
        eyre::bail!(
            "no providers detected — set at least one of: \
             ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, \
             OPENROUTER_API_KEY, KIMI_API_KEY, ZAI_API_KEY, MINIMAX_API_KEY, MISTRAL_API_KEY, \
             DATABRICKS_TOKEN (with DATABRICKS_HOST or ~/.databrickscfg)"
        );
    }

    println!("Detected providers:");
    for d in &detected {
        let key_info = match d.api_key_env {
            Some(env) => env.to_string(),
            None => d.auth.unwrap_or("api_key").to_string(),
        };
        println!("  ✓ {} ({}) via {}", d.name, key_info, d.source);
    }

    let use_openrouter_free = should_prefer_openrouter_free(&detected, prefer_free);
    if prefer_free && !use_openrouter_free {
        println!(
            "\nWarning: `--free` prefers OpenRouter free models, but OPENROUTER_API_KEY is not set; using the normal provider order."
        );
    }

    let prioritized = prioritize_init_detected(&detected, use_openrouter_free);
    let config = build_init_config(&prioritized, use_openrouter_free);
    let mut toml_str = toml::to_string_pretty(&config)
        .map_err(|e| eyre::eyre!("failed to serialize config: {e}"))?;

    let active_names: std::collections::HashSet<&str> = config
        .reviewer
        .iter()
        .map(|r| r.name.as_str())
        .chain(std::iter::once(prioritized[0].name))
        .collect();
    let extras: Vec<&detect::Detected> = detected
        .iter()
        .filter(|d| !active_names.contains(d.name))
        .collect();
    if !extras.is_empty() {
        toml_str.push_str("\n# Other detected providers — uncomment to add as a reviewer:\n");
        for d in extras {
            toml_str.push('\n');
            toml_str.push_str(&format_commented_reviewer(d));
            toml_str.push('\n');
        }
    }

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&path, &toml_str)?;
    println!("\nCreated {}", path.display());

    print_init_hints(&detected);
    Ok(())
}

fn format_commented_reviewer(d: &detect::Detected) -> String {
    let mut lines = vec![
        "# [[reviewer]]".to_string(),
        format!("# name = \"{}\"", d.name),
        format!("# model = \"{}\"", d.model),
        format!("# provider = \"{}\"", d.provider),
    ];
    if let Some(url) = &d.base_url {
        lines.push(format!("# base_url = \"{url}\""));
    }
    if let Some(env) = d.api_key_env {
        if d.local_server {
            lines.push(format!(
                "# api_key_env = \"{env}\"  # set to any non-empty value"
            ));
        } else {
            lines.push(format!("# api_key_env = \"{env}\""));
        }
    }
    if let Some(auth) = d.auth {
        lines.push(format!("# auth = \"{auth}\""));
    }
    lines.join("\n")
}

fn build_init_config(
    detected: &[&detect::Detected],
    prefer_openrouter_free: bool,
) -> config::Config {
    let non_local_count = detected.iter().filter(|d| !d.local_server).count();
    let debate = non_local_count >= 2;

    // aggregator: highest priority (list is already sorted)
    let agg = detected[0];
    let aggregator = config::AggregatorConfig {
        model: init_model_for_detected(agg, prefer_openrouter_free),
        provider: parse_provider_type(agg.provider),
        base_url: agg.base_url.clone(),
        api_key_env: agg.api_key_env.map(str::to_string),
        max_tokens: None,
        auth: agg.auth.map(str::to_string),
        azure_scope: None,
        azure_credentials: None,
    };

    // Fallback needs a second route even when debate is disabled. OpenRouter free selection can
    // produce two distinct model routes from its one detected credential.
    let reviewer_slots = if detected.len() >= 2 || prefer_openrouter_free {
        2
    } else {
        1
    };
    let reviewers = pick_reviewers(detected, reviewer_slots, prefer_openrouter_free);
    let fallback = reviewers.len() >= 2;

    config::Config {
        defaults: Some(config::DefaultsConfig {
            debate: Some(debate),
            alloy: None,
            fallback: Some(fallback),
            max_turns: Some(config::DEFAULT_MAX_TURNS),
            compact_threshold: Some(100_000),
            log_trajectories: Some(false),
            presets: None,
        }),
        aggregator,
        reviewer: reviewers,
        presets: None,
    }
}

fn pick_reviewers(
    detected: &[&detect::Detected],
    count: usize,
    prefer_openrouter_free: bool,
) -> Vec<config::ReviewerConfig> {
    if prefer_openrouter_free {
        return detected
            .first()
            .into_iter()
            .cycle()
            .take(count)
            .map(|d| make_reviewer(d, prefer_openrouter_free))
            .collect();
    }

    let mut result = Vec::new();
    let mut seen_names: std::collections::HashSet<&str> = Default::default();

    // first pass: diverse provider names
    for d in detected {
        if result.len() >= count {
            break;
        }
        if seen_names.insert(d.name) {
            result.push(make_reviewer(d, prefer_openrouter_free));
        }
    }

    // second pass: fill remaining slots with any provider
    for d in detected {
        if result.len() >= count {
            break;
        }
        if result
            .iter()
            .all(|r: &config::ReviewerConfig| r.name != d.name)
        {
            result.push(make_reviewer(d, prefer_openrouter_free));
        }
    }

    result
}

fn make_reviewer(d: &detect::Detected, prefer_openrouter_free: bool) -> config::ReviewerConfig {
    config::ReviewerConfig {
        name: d.name.to_string(),
        model: init_model_for_detected(d, prefer_openrouter_free),
        provider: parse_provider_type(d.provider),
        base_url: d.base_url.clone(),
        api_key_env: d.api_key_env.map(str::to_string),
        max_tokens: None,
        compact_threshold: None,
        auth: d.auth.map(str::to_string),
        azure_scope: None,
        azure_credentials: None,
    }
}

fn should_prefer_openrouter_free(detected: &[detect::Detected], prefer_free: bool) -> bool {
    if !prefer_free {
        return false;
    }

    let has_openrouter = detected.iter().any(|d| d.name == "openrouter");
    has_openrouter && std::env::var("OPENROUTER_API_KEY").is_ok()
}

fn prioritize_init_detected(
    detected: &[detect::Detected],
    prefer_openrouter_free: bool,
) -> Vec<&detect::Detected> {
    let mut prioritized: Vec<&detect::Detected> = detected.iter().collect();
    if prefer_openrouter_free {
        prioritized.sort_by_key(|d| if d.name == "openrouter" { 0 } else { 1 });
    }
    prioritized
}

fn init_model_for_detected(d: &detect::Detected, prefer_openrouter_free: bool) -> String {
    if prefer_openrouter_free && d.name == "openrouter" {
        return "free".to_string();
    }

    d.model.clone()
}

fn parse_provider_type(s: &str) -> config::ProviderType {
    match s {
        "anthropic" => config::ProviderType::Anthropic,
        "gemini" => config::ProviderType::Gemini,
        "openrouter" => config::ProviderType::OpenRouter,
        _ => config::ProviderType::OpenAi,
    }
}

fn print_init_hints(detected: &[detect::Detected]) {
    let unset: Vec<&detect::Detected> = detected
        .iter()
        .filter(|d| {
            !d.local_server
                && d.api_key_env
                    .map(|env| std::env::var(env).is_err())
                    .unwrap_or(false)
        })
        .collect();

    if !unset.is_empty() {
        println!("\nProviders detected but env vars not yet set:");
        for d in unset {
            println!(
                "  export {}=...  # found via {}",
                d.api_key_env.unwrap(),
                d.source
            );
        }
    }

    let has_google_ai_key =
        std::env::var("GOOGLE_AI_API_KEY").is_ok() && std::env::var("GEMINI_API_KEY").is_err();
    if has_google_ai_key {
        println!("\n  Note: found GOOGLE_AI_API_KEY — the gemini client reads GEMINI_API_KEY;");
        println!("  add `export GEMINI_API_KEY=$GOOGLE_AI_API_KEY` to your shell profile.");
    }
}

fn init_config_path(global: bool, repo: &Path) -> Result<PathBuf> {
    if global {
        let home =
            dirs::home_dir().ok_or_else(|| eyre::eyre!("failed to resolve home directory"))?;
        Ok(home.join(".nitpicker").join("config.toml"))
    } else {
        // --repo is a global flag, so `init --repo <dir>` must target that repo's root
        // rather than silently writing into the cwd
        Ok(repo.join("nitpicker.toml"))
    }
}

pub(crate) fn parse_positive_usize(value: &str) -> Result<usize, String> {
    let parsed = value
        .parse::<usize>()
        .map_err(|_| format!("invalid positive integer: {value}"))?;

    if parsed == 0 {
        return Err("value must be greater than 0".to_string());
    }

    Ok(parsed)
}

// Describes only the target and optional user instructions — the investigation angles come
// from the resolved presets, not from a focus list baked in here.
fn build_analysis_prompt(path: Option<&Path>, custom_prompt: Option<&str>) -> String {
    let target = match path {
        Some(p) => format!("`{}`", p.display()),
        None => "the entire repository".to_string(),
    };
    let base = format!(
        "Analyze the following code for issues and improvement opportunities:\n\
         - Target: {}",
        target
    );
    match custom_prompt {
        Some(p) if !p.trim().is_empty() => {
            format!("{}\n\nAdditional instructions: {}", base, p)
        }
        _ => base,
    }
}

pub(crate) struct BaseBranch {
    pub(crate) name: String,
    pub(crate) revision: String,
}

pub fn detect_diff_context(repo: &Path) -> Result<String> {
    let branch = run_git(repo, &["rev-parse", "--abbrev-ref", "HEAD"])?;
    let branch = branch.trim();

    if branch == "HEAD" {
        eyre::bail!("detached HEAD state: checkout a branch before running nitpicker");
    }

    let base = detect_base_branch(repo);

    let has_uncommitted = !run_git(repo, &["status", "--porcelain"])
        .unwrap_or_default()
        .trim()
        .is_empty();

    let has_branch_commits = match base.as_ref() {
        Some(base) if branch != base.name => !run_git(
            repo,
            &["log", &format!("{}..HEAD", base.revision), "--oneline"],
        )?
        .trim()
        .is_empty(),
        _ => false,
    };

    if !has_uncommitted && !has_branch_commits {
        if let Some(base) = base.as_ref() {
            eyre::bail!(
                "no changes to review: no uncommitted changes and no branch commits vs {}",
                base.name
            );
        }
        eyre::bail!(
            "no changes to review: no uncommitted changes and no detectable base branch commits"
        );
    }

    let mut parts = Vec::new();
    if has_uncommitted {
        parts.push("- uncommitted changes (`git diff HEAD`)".to_string());
    }
    if has_branch_commits {
        let base = base
            .as_ref()
            .ok_or_else(|| eyre::eyre!("base branch required when branch commits are present"))?;
        parts.push(format!(
            "- commits on this branch vs {} (`git log {}..HEAD`, `git diff {}...HEAD`)",
            base.name, base.revision, base.revision
        ));
    }

    Ok(format!(
        "Review the following changes:\n{}",
        parts.join("\n")
    ))
}

pub(crate) fn detect_base_branch(repo: &Path) -> Option<BaseBranch> {
    run_git(repo, &["symbolic-ref", "refs/remotes/origin/HEAD"])
        .ok()
        .and_then(|s| {
            s.trim()
                .strip_prefix("refs/remotes/origin/")
                .map(str::to_string)
        })
        .and_then(|branch| resolve_base_branch(repo, &branch))
        .or_else(|| {
            ["main", "master"]
                .into_iter()
                .find_map(|branch| resolve_base_branch(repo, branch))
        })
}

fn resolve_base_branch(repo: &Path, branch: &str) -> Option<BaseBranch> {
    let local = format!("refs/heads/{branch}");
    if run_git(repo, &["rev-parse", "--verify", &local]).is_ok() {
        return Some(BaseBranch {
            name: branch.to_string(),
            revision: branch.to_string(),
        });
    }

    let remote = format!("refs/remotes/origin/{branch}");
    if run_git(repo, &["rev-parse", "--verify", &remote]).is_ok() {
        return Some(BaseBranch {
            name: branch.to_string(),
            revision: format!("origin/{branch}"),
        });
    }

    None
}

fn run_git(repo: &Path, args: &[&str]) -> Result<String> {
    let output = std::process::Command::new("git")
        .args(args)
        .current_dir(repo)
        .output()?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eyre::bail!("git {}: {}", args.join(" "), stderr.trim());
    }
    Ok(String::from_utf8(output.stdout)?)
}

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

    #[test]
    fn cli_definition_is_valid() {
        Args::command().debug_assert();
    }

    fn parse(argv: &[&str]) -> Args {
        Args::try_parse_from(argv).expect("argv parses")
    }

    fn ask_context(args: &Args) -> Vec<PathBuf> {
        match &args.command {
            Some(Command::Ask { context, .. }) => merged_context_files(&args.context, context),
            _ => panic!("expected ask subcommand"),
        }
    }

    fn pr_context(args: &Args) -> Vec<PathBuf> {
        match &args.command {
            Some(Command::Pr(pr_args)) => merged_context_files(&args.context, &pr_args.context),
            _ => panic!("expected pr subcommand"),
        }
    }

    #[test]
    fn context_file_before_the_subcommand_reaches_ask() {
        let args = parse(&["nitpicker", "--context-file", "/a", "ask", "topic"]);
        assert_eq!(ask_context(&args), [PathBuf::from("/a")]);
    }

    #[test]
    fn context_file_after_the_subcommand_reaches_ask() {
        let args = parse(&["nitpicker", "ask", "--context-file", "/a", "topic"]);
        assert_eq!(ask_context(&args), [PathBuf::from("/a")]);
    }

    #[test]
    fn context_files_split_around_the_subcommand_merge_in_cli_order() {
        let args = parse(&[
            "nitpicker",
            "--context-file",
            "/a",
            "ask",
            "--context-file",
            "/b",
            "topic",
        ]);
        assert_eq!(
            ask_context(&args),
            [PathBuf::from("/a"), PathBuf::from("/b")]
        );

        let args = parse(&[
            "nitpicker",
            "--context-file",
            "/a",
            "pr",
            "--context-file",
            "/b",
        ]);
        assert_eq!(
            pr_context(&args),
            [PathBuf::from("/a"), PathBuf::from("/b")]
        );
    }

    #[test]
    fn global_scalars_land_in_common_from_either_side_of_the_subcommand() {
        let args = parse(&["nitpicker", "-v", "--repo", "/x", "ask", "topic"]);
        assert!(args.common.verbose);
        assert_eq!(args.common.repo, PathBuf::from("/x"));

        let args = parse(&["nitpicker", "ask", "topic", "--repo", "/x", "-v"]);
        assert!(args.common.verbose);
        assert_eq!(args.common.repo, PathBuf::from("/x"));

        let args = parse(&["nitpicker", "pr", "--repo", "/x", "--config", "/c.toml"]);
        assert!(!args.common.verbose);
        assert_eq!(args.common.repo, PathBuf::from("/x"));
        assert_eq!(args.common.config, Some(PathBuf::from("/c.toml")));

        let args = parse(&["nitpicker", "--fallback", "ask", "topic"]);
        assert!(args.common.fallback);
        let args = parse(&["nitpicker", "pr", "--fallback"]);
        assert!(args.common.fallback);
    }

    #[test]
    fn init_writes_into_the_repo_named_by_the_global_repo_flag() {
        let path = init_config_path(false, Path::new("/some/repo")).unwrap();
        assert_eq!(path, PathBuf::from("/some/repo/nitpicker.toml"));
    }

    fn detected_provider(name: &'static str, provider: &'static str) -> detect::Detected {
        detect::Detected {
            name,
            provider,
            model: format!("{name}-model"),
            base_url: None,
            api_key_env: None,
            auth: None,
            source: "test",
            local_server: false,
        }
    }

    #[test]
    fn init_enables_fallback_when_it_can_generate_two_routes() {
        let first = detected_provider("first", "openai");
        let second = detected_provider("second", "anthropic");
        let config = build_init_config(&[&first, &second], false);

        assert_eq!(config.reviewer.len(), 2);
        assert!(config.default_fallback());
        assert!(
            toml::to_string_pretty(&config)
                .unwrap()
                .contains("fallback = true")
        );
    }

    #[test]
    fn free_init_generates_two_fallback_routes_from_openrouter() {
        let openrouter = detected_provider("openrouter", "openrouter");
        let config = build_init_config(&[&openrouter], true);

        assert_eq!(config.reviewer.len(), 2);
        assert!(config.reviewer.iter().all(|route| route.model == "free"));
        assert!(config.default_fallback());
        assert!(
            toml::to_string_pretty(&config)
                .unwrap()
                .contains("fallback = true")
        );
    }

    #[test]
    fn init_does_not_enable_impossible_single_route_fallback() {
        let only = detected_provider("only", "openai");
        let config = build_init_config(&[&only], false);

        assert_eq!(config.reviewer.len(), 1);
        assert!(!config.default_fallback());
    }

    #[test]
    fn git_discovers_primary_and_linked_worktree_roots() {
        let dir = tempfile::tempdir().unwrap();
        let primary = dir.path().join("primary");
        std::fs::create_dir(&primary).unwrap();
        run_git(&primary, &["init", "-b", "main"]).unwrap();
        run_git(
            &primary,
            &[
                "-c",
                "user.name=Test",
                "-c",
                "user.email=test@example.com",
                "commit",
                "--allow-empty",
                "-m",
                "initial",
            ],
        )
        .unwrap();

        let linked = dir.path().join("linked");
        run_git(
            &primary,
            &["worktree", "add", "-b", "feature", linked.to_str().unwrap()],
        )
        .unwrap();

        let primary = primary.canonicalize().unwrap();
        let linked = linked.canonicalize().unwrap();
        assert!(primary.join(".git").is_dir());
        assert!(linked.join(".git").is_file());
        assert_eq!(git_worktree_root(&primary).as_deref(), Some(&*primary));
        assert_eq!(git_worktree_root(&linked).as_deref(), Some(&*linked));

        let nested = linked.join("nested");
        std::fs::create_dir(&nested).unwrap();
        assert_eq!(git_worktree_root(&nested).as_deref(), Some(&*linked));

        let fake = dir.path().join("fake");
        std::fs::create_dir(&fake).unwrap();
        std::fs::write(fake.join(".git"), "not a gitdir pointer").unwrap();
        assert!(git_worktree_root(&fake).is_none());
    }

    #[test]
    fn subcommands_without_context_files_reject_the_flag() {
        for argv in [
            ["nitpicker", "reflect", "--context-file", "/a"],
            ["nitpicker", "init", "--context-file", "/a"],
        ] {
            assert!(Args::try_parse_from(argv).is_err());
        }
    }

    fn pr_presets(args: &Args) -> Vec<String> {
        match &args.command {
            Some(Command::Pr(pr_args)) => merged_presets(&args.presets, &pr_args.presets),
            _ => panic!("expected pr subcommand"),
        }
    }

    #[test]
    fn preset_reaches_pr_from_either_side_of_the_subcommand() {
        let args = parse(&["nitpicker", "--preset", "security", "pr"]);
        assert_eq!(pr_presets(&args), ["security"]);

        let args = parse(&["nitpicker", "pr", "--preset", "security"]);
        assert_eq!(pr_presets(&args), ["security"]);
    }

    /// Repeated flags append, commas split within one occurrence, and values split around
    /// the subcommand merge root-first (= command-line order) — same contract as
    /// `--context-file`, and the reason `--preset` is not a clap `global`.
    #[test]
    fn presets_split_around_the_subcommand_merge_in_cli_order_with_commas_expanded() {
        let args = parse(&[
            "nitpicker",
            "--preset",
            "security,ml-rigor",
            "pr",
            "--preset",
            "tone",
        ]);
        assert_eq!(pr_presets(&args), ["security", "ml-rigor", "tone"]);
    }

    #[test]
    fn repeated_preset_flags_append_on_the_root_review_path() {
        let args = parse(&["nitpicker", "--preset", "security", "--preset", "tone"]);
        assert!(args.command.is_none());
        assert_eq!(args.presets.preset, ["security", "tone"]);
    }

    #[test]
    fn subcommands_without_presets_reject_the_flag() {
        let cases: [&[&str]; 3] = [
            &["nitpicker", "ask", "topic", "--preset", "security"],
            &["nitpicker", "reflect", "--preset", "security"],
            &["nitpicker", "init", "--preset", "security"],
        ];
        for argv in cases {
            assert!(Args::try_parse_from(argv).is_err(), "argv: {argv:?}");
        }
    }

    /// Root-position `--preset` parses before any subcommand, so the non-review arms must
    /// reject it explicitly instead of silently discarding it.
    #[test]
    fn root_position_presets_are_rejected_for_non_review_subcommands() {
        let cases: [&[&str]; 3] = [
            &["nitpicker", "--preset", "security", "ask", "topic"],
            &["nitpicker", "--preset", "security", "init"],
            &["nitpicker", "--preset", "security", "reflect"],
        ];
        for argv in cases {
            let args = parse(argv);
            assert!(!presets_allowed(&args.command), "argv: {argv:?}");
        }

        let args = parse(&["nitpicker", "--preset", "security", "pr"]);
        assert!(presets_allowed(&args.command));
        let args = parse(&["nitpicker", "--preset", "security"]);
        assert!(presets_allowed(&args.command));
    }

    #[test]
    fn fallback_is_scoped_to_review_and_ask_commands() {
        for argv in [
            &["nitpicker", "--fallback"][..],
            &["nitpicker", "--fallback", "ask", "topic"][..],
            &["nitpicker", "pr", "--fallback"][..],
        ] {
            let args = parse(argv);
            assert!(fallback_allowed(&args.command), "argv: {argv:?}");
        }
        for argv in [
            &["nitpicker", "init", "--fallback"][..],
            &["nitpicker", "reflect", "--fallback"][..],
        ] {
            let args = parse(argv);
            assert!(!fallback_allowed(&args.command), "argv: {argv:?}");
        }
    }

    #[test]
    fn routing_modes_reject_cli_pooling_with_one_reviewer() {
        let config: config::Config = toml::from_str(
            r#"
                [aggregator]
                model = "m"
                provider = "openai"
                auth = "codex"

                [[reviewer]]
                model = "m"
                provider = "openai"
                auth = "codex"
            "#,
        )
        .unwrap();

        let err = resolve_routing_modes(&config, false, true).unwrap_err();
        assert!(format!("{err:#}").contains("requires at least 2 reviewers"));
        let err = resolve_routing_modes(&config, true, false).unwrap_err();
        assert!(format!("{err:#}").contains("--alloy requires at least 2 reviewers"));
        assert_eq!(
            resolve_routing_modes(&config, false, false).unwrap(),
            (false, false)
        );
    }

    /// The config file shape for presets: `[presets.<name>]` tables and the
    /// `[defaults].presets` selection list round-trip through the library's Config.
    #[test]
    fn preset_config_tables_parse_and_validate() {
        let toml_str = r#"
            [defaults]
            presets = ["tone", "security"]

            [aggregator]
            model = "m"
            provider = "openai"
            auth = "codex"

            [[reviewer]]
            name = "r"
            model = "m"
            provider = "openai"
            auth = "codex"

            [presets.tone]
            prompt = "review the docs for tone"
        "#;
        let config: config::Config = toml::from_str(toml_str).expect("parses");
        config.validate().expect("validates");
        let defaults = config.defaults.as_ref().expect("defaults present");
        assert_eq!(
            defaults.presets.as_deref(),
            Some(&["tone".to_string(), "security".to_string()][..])
        );
        let presets = config.presets.as_ref().expect("presets present");
        assert_eq!(presets["tone"].prompt, "review the docs for tone");
    }

    #[test]
    fn unknown_fields_inside_a_preset_table_are_rejected() {
        let toml_str = r#"
            [aggregator]
            model = "m"
            provider = "openai"
            auth = "codex"

            [[reviewer]]
            model = "m"
            provider = "openai"
            auth = "codex"

            [presets.tone]
            prompt = "p"
            model = "sneaky-per-preset-model"
        "#;
        assert!(toml::from_str::<config::Config>(toml_str).is_err());
    }

    #[test]
    fn blank_preset_prompts_fail_validation() {
        let toml_str = r#"
            [aggregator]
            model = "m"
            provider = "openai"
            auth = "codex"

            [[reviewer]]
            model = "m"
            provider = "openai"
            auth = "codex"

            [presets.tone]
            prompt = "   "
        "#;
        let config: config::Config = toml::from_str(toml_str).expect("parses");
        let err = config.validate().expect_err("blank prompt");
        assert!(format!("{err:#}").contains("[presets.tone].prompt"));
    }
}