nitpicker-agent 0.5.1

Reusable agentic loop (file/git tools + parallel subagents) extracted from nitpicker
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
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
use eyre::Result;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

pub const DEFAULT_MAX_TURNS: usize = 100;

/// The aggregator writes one bounded synthesis and never calls a tool, so a budget fits there.
/// Reviewer turns get no cap by default, since any fixed one is spent on reasoning first.
pub const DEFAULT_AGGREGATOR_MAX_TOKENS: u64 = 16_384;

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub defaults: Option<DefaultsConfig>,
    pub aggregator: AggregatorConfig,
    pub reviewer: Vec<ReviewerConfig>,
    /// Project-defined review presets: `[presets.<name>] prompt = "..."`. Data only — the
    /// built-in registry and all name resolution live in the binary (`src/presets.rs`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub presets: Option<BTreeMap<String, PresetConfig>>,
}

/// One `[presets.<name>]` table: the rubric prompt for a single named review angle.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PresetConfig {
    pub prompt: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DefaultsConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub debate: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alloy: Option<bool>,
    /// Fall through the configured reviewer priority order when a model fails.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fallback: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_turns: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compact_threshold: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub log_trajectories: Option<bool>,
    /// Ordered preset selection for review runs; overridden by CLI `--preset`. Name
    /// resolution (against built-ins and `[presets]`) happens in the binary.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub presets: Option<Vec<String>>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AggregatorConfig {
    #[serde(default)]
    pub model: String,
    pub provider: ProviderType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key_env: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth: Option<String>,
    /// AAD scope for `auth = "azure-ad"` (defaults to the Cognitive Services scope).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub azure_scope: Option<String>,
    /// Azure credential chain selector for `auth = "azure-ad"`: `"dev"`, `"prod"`, or unset.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub azure_credentials: Option<String>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReviewerConfig {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub model: String,
    pub provider: ProviderType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key_env: Option<String>,
    /// Output cap per turn. Unset means no cap: the provider's own per-model limit applies.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compact_threshold: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth: Option<String>,
    /// AAD scope for `auth = "azure-ad"` (defaults to the Cognitive Services scope).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub azure_scope: Option<String>,
    /// Azure credential chain selector for `auth = "azure-ad"`: `"dev"`, `"prod"`, or unset.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub azure_credentials: Option<String>,
}

/// Borrowed view over the connection fields `ReviewerConfig` and `AggregatorConfig` share, so
/// env-var selection (here) and client construction (`provider.rs`) are written once instead
/// of per role.
pub(crate) struct ClientSettings<'a> {
    pub(crate) provider: &'a ProviderType,
    pub(crate) auth: Option<&'a str>,
    pub(crate) base_url: Option<&'a str>,
    pub(crate) api_key_env: Option<&'a str>,
    pub(crate) azure_scope: Option<&'a str>,
    pub(crate) azure_credentials: Option<&'a str>,
}

impl<'a> From<&'a ReviewerConfig> for ClientSettings<'a> {
    fn from(reviewer: &'a ReviewerConfig) -> Self {
        Self {
            provider: &reviewer.provider,
            auth: reviewer.auth.as_deref(),
            base_url: reviewer.base_url.as_deref(),
            api_key_env: reviewer.api_key_env.as_deref(),
            azure_scope: reviewer.azure_scope.as_deref(),
            azure_credentials: reviewer.azure_credentials.as_deref(),
        }
    }
}

impl<'a> From<&'a AggregatorConfig> for ClientSettings<'a> {
    fn from(agg: &'a AggregatorConfig) -> Self {
        Self {
            provider: &agg.provider,
            auth: agg.auth.as_deref(),
            base_url: agg.base_url.as_deref(),
            api_key_env: agg.api_key_env.as_deref(),
            azure_scope: agg.azure_scope.as_deref(),
            azure_credentials: agg.azure_credentials.as_deref(),
        }
    }
}

#[derive(Serialize, Deserialize)]
pub enum ProviderType {
    #[serde(rename = "anthropic", alias = "anthropic_compatible")]
    Anthropic,
    #[serde(rename = "gemini")]
    Gemini,
    #[serde(rename = "openai", alias = "openai_compatible")]
    OpenAi,
    #[serde(rename = "openrouter")]
    OpenRouter,
}

impl ProviderType {
    // only consulted by the antigravity-gated gemini-proxy predicates in provider.rs
    #[cfg(feature = "antigravity")]
    pub fn is_gemini(&self) -> bool {
        matches!(self, ProviderType::Gemini)
    }
}

impl Config {
    pub fn validate(&self) -> Result<()> {
        self.validate_structure()?;
        self.validate_credentials()
    }

    /// Validate config shape without requiring every configured route to be usable in the current
    /// environment. Fallback-aware callers use this before client construction, where an unusable
    /// route can be skipped in favor of the next configured route.
    pub fn validate_structure(&self) -> Result<()> {
        if self.reviewer.is_empty() {
            eyre::bail!("no reviewers configured");
        }

        self.validate_alloy(self.default_alloy())?;
        self.validate_fallback(self.default_fallback())?;

        validate_free_model(
            "[aggregator]",
            &self.aggregator.provider,
            &self.aggregator.model,
        )?;

        // Validate `auth` before the env-var check (matching the reviewer loop below): an unknown
        // auth value like the typo `azure_ad` should surface its own clear error rather than being
        // masked by a missing-API-key error when the provider key happens to be unset.
        validate_auth(
            "[aggregator]",
            &self.aggregator.provider,
            &self.aggregator.auth,
            self.aggregator.base_url.as_deref(),
            self.aggregator.api_key_env.as_deref(),
            self.aggregator.azure_credentials.as_deref(),
        )?;

        for reviewer in &self.reviewer {
            let reviewer_label = match reviewer.name.is_empty() {
                true => "reviewer <unnamed>".to_string(),
                false => format!("reviewer {}", reviewer.name),
            };
            validate_free_model(&reviewer_label, &reviewer.provider, &reviewer.model)?;
            validate_auth(
                &reviewer_label,
                &reviewer.provider,
                &reviewer.auth,
                reviewer.base_url.as_deref(),
                reviewer.api_key_env.as_deref(),
                reviewer.azure_credentials.as_deref(),
            )?;
            if reviewer.compact_threshold == Some(0) {
                eyre::bail!(
                    "reviewer {}: compact_threshold must be greater than 0",
                    reviewer.name
                );
            }
            if reviewer.max_tokens == Some(0) {
                eyre::bail!(
                    "reviewer {}: max_tokens must be greater than 0",
                    reviewer.name
                );
            }
        }

        if self.aggregator.max_tokens == Some(0) {
            eyre::bail!("[aggregator].max_tokens must be greater than 0");
        }

        if self.defaults.as_ref().and_then(|d| d.compact_threshold) == Some(0) {
            eyre::bail!("[defaults].compact_threshold must be greater than 0");
        }

        validate_presets(self.presets.as_ref())?;

        Ok(())
    }

    pub fn default_debate(&self) -> bool {
        self.defaults
            .as_ref()
            .and_then(|d| d.debate)
            .unwrap_or(true)
    }

    pub fn validate_alloy(&self, alloy: bool) -> Result<()> {
        if alloy && self.reviewer.len() < 2 {
            eyre::bail!(
                "--alloy requires at least 2 reviewers, found {}",
                self.reviewer.len()
            );
        }
        Ok(())
    }

    /// Require credentials for every configured route. Non-fallback execution keeps this eager
    /// check so a pure configuration error fails before any provider request is attempted.
    pub fn validate_credentials(&self) -> Result<()> {
        if let Some(env) = required_env_var(ClientSettings::from(&self.aggregator)) {
            check_env_var(env)
                .map_err(|_| eyre::eyre!("[aggregator]: env var {env} is not set"))?;
        }
        for reviewer in &self.reviewer {
            if let Some(env) = required_env_var(ClientSettings::from(reviewer)) {
                check_env_var(env).map_err(|_| {
                    eyre::eyre!("reviewer {}: env var {env} is not set", reviewer.name)
                })?;
            }
        }
        Ok(())
    }

    pub fn default_alloy(&self) -> bool {
        self.defaults
            .as_ref()
            .and_then(|d| d.alloy)
            .unwrap_or(false)
    }

    pub fn validate_fallback(&self, fallback: bool) -> Result<()> {
        if fallback && self.reviewer.len() < 2 {
            eyre::bail!(
                "fallback = true / --fallback requires at least 2 reviewers, found {}",
                self.reviewer.len()
            );
        }
        Ok(())
    }

    pub fn default_fallback(&self) -> bool {
        self.defaults
            .as_ref()
            .and_then(|d| d.fallback)
            .unwrap_or(false)
    }

    pub fn max_turns(&self, override_max_turns: Option<usize>) -> Result<usize> {
        match override_max_turns {
            Some(max_turns) => Ok(max_turns),
            None => self.default_max_turns(),
        }
    }

    pub fn default_max_turns(&self) -> Result<usize> {
        let max_turns = self
            .defaults
            .as_ref()
            .and_then(|d| d.max_turns)
            .unwrap_or(DEFAULT_MAX_TURNS);

        if max_turns == 0 {
            eyre::bail!("[defaults].max_turns must be greater than 0");
        }

        Ok(max_turns)
    }

    pub fn default_compact_threshold(&self) -> Option<u64> {
        self.defaults.as_ref().and_then(|d| d.compact_threshold)
    }

    pub fn log_trajectories(&self) -> bool {
        self.defaults
            .as_ref()
            .and_then(|d| d.log_trajectories)
            .unwrap_or(false)
    }

    pub fn aggregator_max_tokens(&self) -> u64 {
        self.aggregator
            .max_tokens
            .unwrap_or(DEFAULT_AGGREGATOR_MAX_TOKENS)
    }

    pub fn reviewer_compact_threshold(&self, reviewer: &ReviewerConfig) -> Option<u64> {
        reviewer
            .compact_threshold
            .or(self.default_compact_threshold())
    }
}

fn validate_presets(presets: Option<&BTreeMap<String, PresetConfig>>) -> Result<()> {
    let presets = match presets {
        Some(presets) => presets,
        None => return Ok(()),
    };
    for (name, preset) in presets {
        if name.trim().is_empty() {
            eyre::bail!("[presets]: preset names must contain non-whitespace content");
        }
        // selection trims before lookup, so a padded key could never be selected — and worse,
        // would silently resolve to the same-named built-in instead of this definition
        if name != name.trim() {
            eyre::bail!("[presets.{name:?}]: preset names must not have surrounding whitespace");
        }
        // names reach terminals raw (cast lines, progress prefixes) and head report
        // sections; control bytes would enable escape-sequence injection from a config
        if name.chars().any(char::is_control) {
            eyre::bail!("[presets.{name:?}]: preset names must not contain control characters");
        }
        if preset.prompt.trim().is_empty() {
            eyre::bail!("[presets.{name}].prompt must contain non-whitespace content");
        }
    }
    Ok(())
}

fn validate_free_model(label: &str, provider: &ProviderType, model: &str) -> Result<()> {
    if model == "free" && !matches!(provider, ProviderType::OpenRouter) {
        eyre::bail!("{label}: model = \"free\" is only supported with provider = \"openrouter\"");
    }

    Ok(())
}

fn validate_auth(
    label: &str,
    provider: &ProviderType,
    auth: &Option<String>,
    base_url: Option<&str>,
    api_key_env: Option<&str>,
    azure_credentials: Option<&str>,
) -> Result<()> {
    match (provider, auth.as_deref()) {
        // Unset auth is always fine — providers fall back to their default env-var key.
        (_, None) => Ok(()),
        (ProviderType::Gemini, Some("oauth")) => {
            eyre::bail!(
                "{label}: auth = \"oauth\" has been removed — use auth = \"agy-keyring\" (see README) or unset `auth` to use GEMINI_API_KEY"
            );
        }
        // agy-keyring routes through the local Gemini proxy, gated behind the `antigravity`
        // feature (mirrors the azure-ad gate below).
        (ProviderType::Gemini, Some("agy-keyring")) => {
            if !cfg!(feature = "antigravity") {
                eyre::bail!(
                    "{label}: auth = \"agy-keyring\" requires building nitpicker with `--features antigravity`"
                );
            }
            Ok(())
        }
        (ProviderType::Gemini, Some(other)) => {
            eyre::bail!(
                "{label}: unknown auth value \"{other}\" — expected \"agy-keyring\" or unset"
            );
        }
        // Azure AD is only meaningful for the OpenAI/Anthropic Foundry passthrough endpoints,
        // and only works when the `azure` feature was compiled in.
        (ProviderType::OpenAi | ProviderType::Anthropic, Some("azure-ad")) => {
            if !cfg!(feature = "azure") {
                eyre::bail!(
                    "{label}: auth = \"azure-ad\" requires building nitpicker with `--features azure`"
                );
            }
            validate_azure_fields(label, base_url, azure_credentials)
        }
        (_, Some("azure-ad")) => {
            eyre::bail!(
                "{label}: auth = \"azure-ad\" is only supported with provider \"openai\" or \"anthropic\""
            );
        }
        // Codex/ChatGPT subscription auth reuses the OpenAI Responses endpoint, so it only makes
        // sense for the OpenAI provider; the token comes from `~/.codex/auth.json`, not an env var.
        // Client construction returns the fixed shared CodexClient and ignores base_url/api_key_env,
        // so reject them rather than silently dropping a configured endpoint or key.
        (ProviderType::OpenAi, Some("codex")) => {
            if base_url.is_some() {
                eyre::bail!(
                    "{label}: auth = \"codex\" ignores `base_url` (requests always go to the Codex endpoint) — remove it"
                );
            }
            if api_key_env.is_some() {
                eyre::bail!(
                    "{label}: auth = \"codex\" ignores `api_key_env` (the token comes from ~/.codex/auth.json) — remove it"
                );
            }
            Ok(())
        }
        (_, Some("codex")) => {
            eyre::bail!("{label}: auth = \"codex\" is only supported with provider \"openai\"");
        }
        // Any other auth value on a non-Gemini provider is a typo or unsupported — reject it at
        // config time rather than failing cryptically at client construction.
        (_, Some(other)) => {
            eyre::bail!("{label}: unknown auth value \"{other}\"");
        }
    }
}

/// Validate the mandatory `auth = "azure-ad"` fields at config time so a typo fails fast here
/// instead of at the first LLM call. Mirrors the runtime checks in `azure::build_azure_client`
/// (base_url) and `azure::build_credential_chain` (azure_credentials).
fn validate_azure_fields(
    label: &str,
    base_url: Option<&str>,
    azure_credentials: Option<&str>,
) -> Result<()> {
    if base_url.map(str::trim).filter(|u| !u.is_empty()).is_none() {
        eyre::bail!(
            "{label}: auth = \"azure-ad\" requires a non-empty `base_url` (the Azure Foundry endpoint)"
        );
    }
    // Validate whichever credential mode the runtime would actually use. `build_credential_chain`
    // resolves explicit config first, then the `AZURE_TOKEN_CREDENTIALS` env var — so a bogus env
    // value (with `azure_credentials` unset) would otherwise pass config validation and only fail
    // at the first LLM call. Mirror that fallback here so it fails fast too.
    match azure_credentials {
        Some(mode) => validate_azure_credentials_mode(label, "azure_credentials", mode)?,
        None => {
            if let Ok(env_mode) = std::env::var("AZURE_TOKEN_CREDENTIALS") {
                validate_azure_credentials_mode(label, "AZURE_TOKEN_CREDENTIALS", &env_mode)?;
            }
        }
    }
    Ok(())
}

/// Reject an unknown Azure credential-chain selector. Empty/whitespace is allowed: the runtime
/// (`build_credential_chain`) treats it as unset and falls back to `"auto"`. `source` names where
/// the value came from so the error points at the right place (the `azure_credentials` config field
/// vs the `AZURE_TOKEN_CREDENTIALS` env var).
fn validate_azure_credentials_mode(label: &str, source: &str, mode: &str) -> Result<()> {
    let normalized = mode.trim().to_ascii_lowercase();
    if !normalized.is_empty() && !matches!(normalized.as_str(), "dev" | "prod" | "auto") {
        eyre::bail!(
            "{label}: unknown {source} value \"{mode}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
        );
    }
    Ok(())
}

fn check_env_var(name: &str) -> Result<(), std::env::VarError> {
    // gemini accepts either GEMINI_API_KEY or GOOGLE_AI_API_KEY
    if name == "GEMINI_API_KEY" {
        if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_AI_API_KEY").is_ok() {
            return Ok(());
        }
        return Err(std::env::VarError::NotPresent);
    }
    std::env::var(name).map(|_| ())
}

fn is_local_server(base_url: Option<&str>) -> bool {
    base_url
        .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
        .unwrap_or(false)
}

fn required_env_var<'a>(settings: ClientSettings<'a>) -> Option<&'a str> {
    if matches!(settings.provider, ProviderType::Gemini) && is_gemini_proxy_auth(settings.auth) {
        return None;
    }
    if is_azure_ad_auth(settings.auth) {
        return None;
    }
    if is_codex_auth(settings.auth) {
        return None;
    }
    if is_local_server(settings.base_url) {
        return None;
    }
    if let Some(env) = settings.api_key_env {
        return Some(env);
    }
    default_env_var(settings.provider)
}

fn is_gemini_proxy_auth(auth: Option<&str>) -> bool {
    matches!(auth, Some("agy-keyring"))
}

/// Canonical check shared with `provider.rs` (the client-build path), kept here next to the
/// config types so validation and construction can't drift apart.
pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
    matches!(auth, Some("azure-ad"))
}

/// Codex/ChatGPT subscription auth. Canonical check shared with `provider.rs`.
pub fn is_codex_auth(auth: Option<&str>) -> bool {
    matches!(auth, Some("codex"))
}

fn default_env_var(provider: &ProviderType) -> Option<&'static str> {
    match provider {
        ProviderType::Anthropic => Some("ANTHROPIC_API_KEY"),
        ProviderType::Gemini => Some("GEMINI_API_KEY"),
        ProviderType::OpenAi => Some("OPENAI_API_KEY"),
        ProviderType::OpenRouter => Some("OPENROUTER_API_KEY"),
    }
}

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

    const FOUNDRY_URL: &str = "https://res.services.ai.azure.com/openai/v1";

    #[test]
    fn azure_ad_auth_detection() {
        assert!(is_azure_ad_auth(Some("azure-ad")));
        assert!(!is_azure_ad_auth(Some("agy-keyring")));
        assert!(!is_azure_ad_auth(None));
    }

    #[test]
    fn validate_auth_rejects_azure_ad_on_unsupported_providers() {
        let auth = Some("azure-ad".to_string());
        assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
        assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
    }

    #[test]
    fn validate_auth_azure_ad_on_supported_providers() {
        let auth = Some("azure-ad".to_string());
        // Pass an explicit credential mode so the assertion can't depend on an ambient
        // `AZURE_TOKEN_CREDENTIALS` (which `None` would make `validate_azure_fields` read).
        let creds = Some("auto");
        let openai = validate_auth(
            "[t]",
            &ProviderType::OpenAi,
            &auth,
            Some(FOUNDRY_URL),
            None,
            creds,
        );
        let anthropic = validate_auth(
            "[t]",
            &ProviderType::Anthropic,
            &auth,
            Some(FOUNDRY_URL),
            None,
            creds,
        );
        // Accepted only when compiled with the `azure` feature; otherwise validation fails fast
        // with a build hint.
        if cfg!(feature = "azure") {
            assert!(openai.is_ok());
            assert!(anthropic.is_ok());
        } else {
            assert!(openai.is_err());
            assert!(anthropic.is_err());
        }
    }

    #[test]
    fn validate_auth_allows_unset_and_known_values() {
        assert!(validate_auth("[t]", &ProviderType::OpenAi, &None, None, None, None).is_ok());
        // agy-keyring is accepted only when compiled with the `antigravity` feature; otherwise
        // validation fails fast with a build hint (mirrors the azure gate).
        let agy = validate_auth(
            "[t]",
            &ProviderType::Gemini,
            &Some("agy-keyring".to_string()),
            None,
            None,
            None,
        );
        if cfg!(feature = "antigravity") {
            assert!(agy.is_ok());
        } else {
            assert!(agy.is_err());
        }
    }

    #[test]
    fn validate_auth_codex_rejects_ignored_fields() {
        let auth = Some("codex".to_string());
        // bare codex auth is fine
        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
        // base_url / api_key_env would be silently dropped, so they must be rejected
        assert!(
            validate_auth(
                "[t]",
                &ProviderType::OpenAi,
                &auth,
                Some("https://example.com"),
                None,
                None,
            )
            .is_err()
        );
        assert!(
            validate_auth(
                "[t]",
                &ProviderType::OpenAi,
                &auth,
                None,
                Some("MY_KEY"),
                None,
            )
            .is_err()
        );
    }

    #[test]
    fn codex_auth_detection() {
        assert!(is_codex_auth(Some("codex")));
        assert!(!is_codex_auth(Some("azure-ad")));
        assert!(!is_codex_auth(None));
    }

    #[test]
    fn validate_auth_codex_only_on_openai() {
        let auth = Some("codex".to_string());
        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
        assert!(validate_auth("[t]", &ProviderType::Anthropic, &auth, None, None, None).is_err());
        assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
        assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
    }

    /// Codex auth needs no env var, so this validates the same wherever it runs.
    fn config_with(reviewer_max_tokens: Option<u64>, aggregator_max_tokens: Option<u64>) -> Config {
        Config {
            defaults: None,
            aggregator: AggregatorConfig {
                model: "gpt-5.4".to_string(),
                provider: ProviderType::OpenAi,
                base_url: None,
                api_key_env: None,
                max_tokens: aggregator_max_tokens,
                auth: Some("codex".to_string()),
                azure_scope: None,
                azure_credentials: None,
            },
            reviewer: vec![ReviewerConfig {
                name: "r".to_string(),
                model: "gpt-5.4".to_string(),
                provider: ProviderType::OpenAi,
                base_url: None,
                api_key_env: None,
                max_tokens: reviewer_max_tokens,
                compact_threshold: None,
                auth: Some("codex".to_string()),
                azure_scope: None,
                azure_credentials: None,
            }],
            presets: None,
        }
    }

    /// Zero is not "no cap" — the provider answers it with nothing. Unset is how no cap is spelled.
    #[test]
    fn zero_max_tokens_is_rejected_on_both_entities() {
        assert!(config_with(None, None).validate().is_ok());
        assert!(config_with(Some(0), None).validate().is_err());
        assert!(config_with(None, Some(0)).validate().is_err());
    }

    #[test]
    fn fallback_default_is_opt_in_and_requires_a_next_reviewer() {
        let mut config = config_with(None, None);
        assert!(!config.default_fallback());
        config.defaults = Some(DefaultsConfig {
            debate: None,
            alloy: None,
            fallback: Some(true),
            max_turns: None,
            compact_threshold: None,
            log_trajectories: None,
            presets: None,
        });
        assert!(config.default_fallback());
        assert!(config.validate().is_err());

        config.reviewer.push(ReviewerConfig {
            name: "r2".to_string(),
            model: "gpt-5.4".to_string(),
            provider: ProviderType::OpenAi,
            base_url: None,
            api_key_env: None,
            max_tokens: None,
            compact_threshold: None,
            auth: Some("codex".to_string()),
            azure_scope: None,
            azure_credentials: None,
        });
        assert!(config.validate().is_ok());
    }

    #[test]
    fn structural_validation_defers_missing_route_credentials() {
        let mut config = config_with(None, None);
        config.aggregator.auth = None;
        config.aggregator.api_key_env =
            Some("NITPICKER_TEST_MISSING_AGGREGATOR_CREDENTIAL_FOR_FALLBACK_7C51".to_string());

        assert!(config.validate_structure().is_ok());
        let err = config.validate_credentials().unwrap_err();
        assert!(format!("{err:#}").contains("env var"));
        assert!(config.validate().is_err());
    }

    #[test]
    fn codex_auth_requires_no_env_var() {
        let reviewer = ReviewerConfig {
            name: "r".to_string(),
            model: "gpt-5.4".to_string(),
            provider: ProviderType::OpenAi,
            base_url: None,
            api_key_env: None,
            max_tokens: None,
            compact_threshold: None,
            auth: Some("codex".to_string()),
            azure_scope: None,
            azure_credentials: None,
        };
        assert_eq!(required_env_var(ClientSettings::from(&reviewer)), None);
        let agg = AggregatorConfig {
            model: "gpt-5.4".to_string(),
            provider: ProviderType::OpenAi,
            base_url: None,
            api_key_env: None,
            max_tokens: None,
            auth: Some("codex".to_string()),
            azure_scope: None,
            azure_credentials: None,
        };
        assert_eq!(required_env_var(ClientSettings::from(&agg)), None);
    }

    /// The five short-circuit branches and their precedence, exercised through both role
    /// functions. The collision rows matter most: a regression that reorders the checks
    /// (e.g. explicit `api_key_env` consulted before proxy/local short-circuits) passes a
    /// membership-only table but fails these.
    #[test]
    fn required_env_var_branch_table_and_precedence() {
        fn provider(name: &str) -> ProviderType {
            match name {
                "anthropic" => ProviderType::Anthropic,
                "gemini" => ProviderType::Gemini,
                "openai" => ProviderType::OpenAi,
                "openrouter" => ProviderType::OpenRouter,
                other => panic!("unknown provider in table: {other}"),
            }
        }

        // (provider, auth, base_url, api_key_env, expected). Rows pairing a short-circuit
        // with an explicit api_key_env pin precedence; the last four pin the default table.
        #[rustfmt::skip]
        let rows = [
            ("gemini",     Some("agy-keyring"), None,                              None,             None),
            ("gemini",     Some("agy-keyring"), None,                              Some("EXPLICIT"), None),
            // agy-keyring only short-circuits on gemini; elsewhere it falls through
            ("openai",     Some("agy-keyring"), None,                              None,             Some("OPENAI_API_KEY")),
            ("openai",     Some("azure-ad"),    Some("https://f.example/v1"),      Some("EXPLICIT"), None),
            ("openai",     Some("codex"),       None,                              Some("EXPLICIT"), None),
            ("openai",     None,                Some("http://localhost:1234/v1"),  Some("EXPLICIT"), None),
            ("openai",     None,                Some("http://127.0.0.1:1234/v1"),  None,             None),
            // a non-local base_url does not bypass the key; explicit env beats the default
            ("anthropic",  None,                Some("https://gw.example"),        Some("EXPLICIT"), Some("EXPLICIT")),
            ("anthropic",  None,                None,                              None,             Some("ANTHROPIC_API_KEY")),
            ("gemini",     None,                None,                              None,             Some("GEMINI_API_KEY")),
            ("openai",     None,                None,                              None,             Some("OPENAI_API_KEY")),
            ("openrouter", None,                None,                              None,             Some("OPENROUTER_API_KEY")),
        ];

        for (name, auth, base_url, api_key_env, expected) in rows {
            let reviewer = ReviewerConfig {
                name: String::new(),
                model: String::new(),
                provider: provider(name),
                base_url: base_url.map(str::to_string),
                api_key_env: api_key_env.map(str::to_string),
                max_tokens: None,
                compact_threshold: None,
                auth: auth.map(str::to_string),
                azure_scope: None,
                azure_credentials: None,
            };
            let agg = AggregatorConfig {
                model: String::new(),
                provider: provider(name),
                base_url: base_url.map(str::to_string),
                api_key_env: api_key_env.map(str::to_string),
                max_tokens: None,
                auth: auth.map(str::to_string),
                azure_scope: None,
                azure_credentials: None,
            };
            for (role, settings) in [
                ("reviewer", ClientSettings::from(&reviewer)),
                ("aggregator", ClientSettings::from(&agg)),
            ] {
                assert_eq!(
                    required_env_var(settings),
                    expected,
                    "{role}: {name} auth={auth:?} base_url={base_url:?} api_key_env={api_key_env:?}"
                );
            }
        }
    }

    #[test]
    fn validate_auth_rejects_unknown_value_on_non_gemini() {
        // Typos like `azure_ad`/`Azure-AD` must fail at config time, not at client construction.
        let typo = Some("azure_ad".to_string());
        assert!(
            validate_auth(
                "[t]",
                &ProviderType::OpenAi,
                &typo,
                Some(FOUNDRY_URL),
                None,
                None
            )
            .is_err()
        );
        assert!(validate_auth("[t]", &ProviderType::Anthropic, &typo, None, None, None).is_err());
    }

    #[cfg(feature = "azure")]
    #[test]
    fn validate_auth_azure_ad_requires_base_url() {
        let auth = Some("azure-ad".to_string());
        // The two error cases bail on `base_url` before any credential check, so they're already
        // env-independent; the ok case passes an explicit mode so it doesn't read the ambient
        // `AZURE_TOKEN_CREDENTIALS` (which a `None` here would).
        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_err());
        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, Some(""), None, None).is_err());
        assert!(
            validate_auth(
                "[t]",
                &ProviderType::OpenAi,
                &auth,
                Some(FOUNDRY_URL),
                None,
                Some("auto")
            )
            .is_ok()
        );
    }

    #[test]
    fn validate_azure_credentials_mode_rejects_unknown_only() {
        // Known modes pass (case/whitespace normalized like the runtime chain builder).
        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "dev").is_ok());
        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "PROD").is_ok());
        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "auto").is_ok());
        // Empty/whitespace is treated as unset (runtime falls back to "auto"), so it's allowed.
        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "   ").is_ok());
        // A bogus value is rejected, and the message names the source so a config with no
        // `azure_credentials` field but a bad env var points the user at the env var.
        let err = validate_azure_credentials_mode("[t]", "AZURE_TOKEN_CREDENTIALS", "bogus")
            .unwrap_err()
            .to_string();
        assert!(err.contains("AZURE_TOKEN_CREDENTIALS"), "got: {err}");
        assert!(err.contains("bogus"), "got: {err}");
    }

    #[cfg(feature = "azure")]
    #[test]
    fn validate_auth_azure_ad_validates_credentials() {
        let auth = Some("azure-ad".to_string());
        let ok = |creds| {
            validate_auth(
                "[t]",
                &ProviderType::OpenAi,
                &auth,
                Some(FOUNDRY_URL),
                None,
                creds,
            )
            .is_ok()
        };
        // Use explicit modes only — `None` would make validation read the ambient
        // `AZURE_TOKEN_CREDENTIALS`, so a developer/CI with a bogus value set would fail spuriously.
        // The "unset falls back to auto" behavior is covered hermetically by
        // `validate_azure_credentials_mode_rejects_unknown_only` (empty string is accepted).
        assert!(ok(Some("auto")));
        assert!(ok(Some("dev")));
        assert!(ok(Some("PROD"))); // case/whitespace normalized like the runtime chain builder
        assert!(ok(Some("auto")));
        assert!(
            validate_auth(
                "[t]",
                &ProviderType::OpenAi,
                &auth,
                Some(FOUNDRY_URL),
                None,
                Some("deve")
            )
            .is_err()
        );
    }

    /// Selection trims names before lookup, so a padded `[presets." x "]` key could never be
    /// selected — it must be rejected at validation instead of silently shadowed; blank
    /// prompts and blank names are data errors the library owns.
    #[test]
    fn preset_tables_reject_blank_and_padded_names_and_blank_prompts() {
        let table = |name: &str, prompt: &str| {
            let mut presets = BTreeMap::new();
            presets.insert(
                name.to_string(),
                PresetConfig {
                    prompt: prompt.to_string(),
                },
            );
            presets
        };
        assert!(validate_presets(None).is_ok());
        assert!(validate_presets(Some(&table("tone", "review the docs"))).is_ok());
        assert!(validate_presets(Some(&table(" tone", "review the docs"))).is_err());
        assert!(validate_presets(Some(&table("  ", "review the docs"))).is_err());
        assert!(validate_presets(Some(&table("tone", "   "))).is_err());
    }

    /// Preset names reach terminal output and report headers raw, so C0/C1 (and thereby
    /// OSC/CSI escape openers) must be rejected at validation, not sanitized at display.
    #[test]
    fn preset_tables_reject_control_bytes_in_names() {
        let table = |name: &str| {
            let mut presets = BTreeMap::new();
            presets.insert(
                name.to_string(),
                PresetConfig {
                    prompt: "review the docs".to_string(),
                },
            );
            presets
        };
        for name in [
            "esc\u{1b}]0;pwn\u{7}",
            "csi\u{9b}31m",
            "tab\tname",
            "nl\nname",
        ] {
            let err = validate_presets(Some(&table(name))).expect_err("control bytes rejected");
            assert!(
                format!("{err:#}").contains("control characters"),
                "wrong error for {name:?}: {err:#}"
            );
        }
    }
}