Skip to main content

nitpicker_agent/
config.rs

1use eyre::Result;
2use serde::{Deserialize, Serialize};
3
4pub const DEFAULT_MAX_TURNS: usize = 100;
5
6/// The aggregator writes one bounded synthesis and never calls a tool, so a budget fits there.
7/// Reviewer turns get no cap by default, since any fixed one is spent on reasoning first.
8pub const DEFAULT_AGGREGATOR_MAX_TOKENS: u64 = 16_384;
9
10#[derive(Serialize, Deserialize)]
11#[serde(deny_unknown_fields)]
12pub struct Config {
13    #[serde(skip_serializing_if = "Option::is_none")]
14    pub defaults: Option<DefaultsConfig>,
15    pub aggregator: AggregatorConfig,
16    pub reviewer: Vec<ReviewerConfig>,
17}
18
19#[derive(Serialize, Deserialize)]
20#[serde(deny_unknown_fields)]
21pub struct DefaultsConfig {
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub debate: Option<bool>,
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub alloy: Option<bool>,
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub max_turns: Option<usize>,
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub compact_threshold: Option<u64>,
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub log_trajectories: Option<bool>,
32}
33
34#[derive(Serialize, Deserialize)]
35#[serde(deny_unknown_fields)]
36pub struct AggregatorConfig {
37    #[serde(default)]
38    pub model: String,
39    pub provider: ProviderType,
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub base_url: Option<String>,
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub api_key_env: Option<String>,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub max_tokens: Option<u64>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub auth: Option<String>,
48    /// AAD scope for `auth = "azure-ad"` (defaults to the Cognitive Services scope).
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub azure_scope: Option<String>,
51    /// Azure credential chain selector for `auth = "azure-ad"`: `"dev"`, `"prod"`, or unset.
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub azure_credentials: Option<String>,
54}
55
56#[derive(Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct ReviewerConfig {
59    #[serde(default)]
60    pub name: String,
61    #[serde(default)]
62    pub model: String,
63    pub provider: ProviderType,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub base_url: Option<String>,
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub api_key_env: Option<String>,
68    /// Output cap per turn. Unset means no cap: the provider's own per-model limit applies.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub max_tokens: Option<u64>,
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub compact_threshold: Option<u64>,
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub auth: Option<String>,
75    /// AAD scope for `auth = "azure-ad"` (defaults to the Cognitive Services scope).
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub azure_scope: Option<String>,
78    /// Azure credential chain selector for `auth = "azure-ad"`: `"dev"`, `"prod"`, or unset.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub azure_credentials: Option<String>,
81}
82
83/// Borrowed view over the connection fields `ReviewerConfig` and `AggregatorConfig` share, so
84/// env-var selection (here) and client construction (`provider.rs`) are written once instead
85/// of per role.
86pub(crate) struct ClientSettings<'a> {
87    pub(crate) provider: &'a ProviderType,
88    pub(crate) auth: Option<&'a str>,
89    pub(crate) base_url: Option<&'a str>,
90    pub(crate) api_key_env: Option<&'a str>,
91    pub(crate) azure_scope: Option<&'a str>,
92    pub(crate) azure_credentials: Option<&'a str>,
93}
94
95impl<'a> From<&'a ReviewerConfig> for ClientSettings<'a> {
96    fn from(reviewer: &'a ReviewerConfig) -> Self {
97        Self {
98            provider: &reviewer.provider,
99            auth: reviewer.auth.as_deref(),
100            base_url: reviewer.base_url.as_deref(),
101            api_key_env: reviewer.api_key_env.as_deref(),
102            azure_scope: reviewer.azure_scope.as_deref(),
103            azure_credentials: reviewer.azure_credentials.as_deref(),
104        }
105    }
106}
107
108impl<'a> From<&'a AggregatorConfig> for ClientSettings<'a> {
109    fn from(agg: &'a AggregatorConfig) -> Self {
110        Self {
111            provider: &agg.provider,
112            auth: agg.auth.as_deref(),
113            base_url: agg.base_url.as_deref(),
114            api_key_env: agg.api_key_env.as_deref(),
115            azure_scope: agg.azure_scope.as_deref(),
116            azure_credentials: agg.azure_credentials.as_deref(),
117        }
118    }
119}
120
121#[derive(Serialize, Deserialize)]
122pub enum ProviderType {
123    #[serde(rename = "anthropic", alias = "anthropic_compatible")]
124    Anthropic,
125    #[serde(rename = "gemini")]
126    Gemini,
127    #[serde(rename = "openai", alias = "openai_compatible")]
128    OpenAi,
129    #[serde(rename = "openrouter")]
130    OpenRouter,
131}
132
133impl ProviderType {
134    // only consulted by the antigravity-gated gemini-proxy predicates in provider.rs
135    #[cfg(feature = "antigravity")]
136    pub fn is_gemini(&self) -> bool {
137        matches!(self, ProviderType::Gemini)
138    }
139}
140
141impl Config {
142    pub fn validate(&self) -> Result<()> {
143        if self.reviewer.is_empty() {
144            eyre::bail!("no reviewers configured");
145        }
146
147        self.validate_alloy(self.default_alloy())?;
148
149        validate_free_model(
150            "[aggregator]",
151            &self.aggregator.provider,
152            &self.aggregator.model,
153        )?;
154
155        // Validate `auth` before the env-var check (matching the reviewer loop below): an unknown
156        // auth value like the typo `azure_ad` should surface its own clear error rather than being
157        // masked by a missing-API-key error when the provider key happens to be unset.
158        validate_auth(
159            "[aggregator]",
160            &self.aggregator.provider,
161            &self.aggregator.auth,
162            self.aggregator.base_url.as_deref(),
163            self.aggregator.api_key_env.as_deref(),
164            self.aggregator.azure_credentials.as_deref(),
165        )?;
166
167        if let Some(env) = required_env_var(ClientSettings::from(&self.aggregator)) {
168            check_env_var(env)
169                .map_err(|_| eyre::eyre!("[aggregator]: env var {env} is not set"))?;
170        }
171
172        for reviewer in &self.reviewer {
173            let reviewer_label = match reviewer.name.is_empty() {
174                true => "reviewer <unnamed>".to_string(),
175                false => format!("reviewer {}", reviewer.name),
176            };
177            validate_free_model(&reviewer_label, &reviewer.provider, &reviewer.model)?;
178            validate_auth(
179                &reviewer_label,
180                &reviewer.provider,
181                &reviewer.auth,
182                reviewer.base_url.as_deref(),
183                reviewer.api_key_env.as_deref(),
184                reviewer.azure_credentials.as_deref(),
185            )?;
186            if let Some(env) = required_env_var(ClientSettings::from(reviewer)) {
187                check_env_var(env).map_err(|_| {
188                    eyre::eyre!("reviewer {}: env var {env} is not set", reviewer.name)
189                })?;
190            }
191            if reviewer.compact_threshold == Some(0) {
192                eyre::bail!(
193                    "reviewer {}: compact_threshold must be greater than 0",
194                    reviewer.name
195                );
196            }
197            if reviewer.max_tokens == Some(0) {
198                eyre::bail!(
199                    "reviewer {}: max_tokens must be greater than 0",
200                    reviewer.name
201                );
202            }
203        }
204
205        if self.aggregator.max_tokens == Some(0) {
206            eyre::bail!("[aggregator].max_tokens must be greater than 0");
207        }
208
209        if self.defaults.as_ref().and_then(|d| d.compact_threshold) == Some(0) {
210            eyre::bail!("[defaults].compact_threshold must be greater than 0");
211        }
212
213        Ok(())
214    }
215
216    pub fn default_debate(&self) -> bool {
217        self.defaults
218            .as_ref()
219            .and_then(|d| d.debate)
220            .unwrap_or(true)
221    }
222
223    pub fn validate_alloy(&self, alloy: bool) -> Result<()> {
224        if alloy && self.reviewer.len() < 2 {
225            eyre::bail!(
226                "--alloy requires at least 2 reviewers, found {}",
227                self.reviewer.len()
228            );
229        }
230        Ok(())
231    }
232
233    pub fn default_alloy(&self) -> bool {
234        self.defaults
235            .as_ref()
236            .and_then(|d| d.alloy)
237            .unwrap_or(false)
238    }
239
240    pub fn max_turns(&self, override_max_turns: Option<usize>) -> Result<usize> {
241        match override_max_turns {
242            Some(max_turns) => Ok(max_turns),
243            None => self.default_max_turns(),
244        }
245    }
246
247    pub fn default_max_turns(&self) -> Result<usize> {
248        let max_turns = self
249            .defaults
250            .as_ref()
251            .and_then(|d| d.max_turns)
252            .unwrap_or(DEFAULT_MAX_TURNS);
253
254        if max_turns == 0 {
255            eyre::bail!("[defaults].max_turns must be greater than 0");
256        }
257
258        Ok(max_turns)
259    }
260
261    pub fn default_compact_threshold(&self) -> Option<u64> {
262        self.defaults.as_ref().and_then(|d| d.compact_threshold)
263    }
264
265    pub fn log_trajectories(&self) -> bool {
266        self.defaults
267            .as_ref()
268            .and_then(|d| d.log_trajectories)
269            .unwrap_or(false)
270    }
271
272    pub fn aggregator_max_tokens(&self) -> u64 {
273        self.aggregator
274            .max_tokens
275            .unwrap_or(DEFAULT_AGGREGATOR_MAX_TOKENS)
276    }
277
278    pub fn reviewer_compact_threshold(&self, reviewer: &ReviewerConfig) -> Option<u64> {
279        reviewer
280            .compact_threshold
281            .or(self.default_compact_threshold())
282    }
283}
284
285fn validate_free_model(label: &str, provider: &ProviderType, model: &str) -> Result<()> {
286    if model == "free" && !matches!(provider, ProviderType::OpenRouter) {
287        eyre::bail!("{label}: model = \"free\" is only supported with provider = \"openrouter\"");
288    }
289
290    Ok(())
291}
292
293fn validate_auth(
294    label: &str,
295    provider: &ProviderType,
296    auth: &Option<String>,
297    base_url: Option<&str>,
298    api_key_env: Option<&str>,
299    azure_credentials: Option<&str>,
300) -> Result<()> {
301    match (provider, auth.as_deref()) {
302        // Unset auth is always fine — providers fall back to their default env-var key.
303        (_, None) => Ok(()),
304        (ProviderType::Gemini, Some("oauth")) => {
305            eyre::bail!(
306                "{label}: auth = \"oauth\" has been removed — use auth = \"agy-keyring\" (see README) or unset `auth` to use GEMINI_API_KEY"
307            );
308        }
309        // agy-keyring routes through the local Gemini proxy, gated behind the `antigravity`
310        // feature (mirrors the azure-ad gate below).
311        (ProviderType::Gemini, Some("agy-keyring")) => {
312            if !cfg!(feature = "antigravity") {
313                eyre::bail!(
314                    "{label}: auth = \"agy-keyring\" requires building nitpicker with `--features antigravity`"
315                );
316            }
317            Ok(())
318        }
319        (ProviderType::Gemini, Some(other)) => {
320            eyre::bail!(
321                "{label}: unknown auth value \"{other}\" — expected \"agy-keyring\" or unset"
322            );
323        }
324        // Azure AD is only meaningful for the OpenAI/Anthropic Foundry passthrough endpoints,
325        // and only works when the `azure` feature was compiled in.
326        (ProviderType::OpenAi | ProviderType::Anthropic, Some("azure-ad")) => {
327            if !cfg!(feature = "azure") {
328                eyre::bail!(
329                    "{label}: auth = \"azure-ad\" requires building nitpicker with `--features azure`"
330                );
331            }
332            validate_azure_fields(label, base_url, azure_credentials)
333        }
334        (_, Some("azure-ad")) => {
335            eyre::bail!(
336                "{label}: auth = \"azure-ad\" is only supported with provider \"openai\" or \"anthropic\""
337            );
338        }
339        // Codex/ChatGPT subscription auth reuses the OpenAI Responses endpoint, so it only makes
340        // sense for the OpenAI provider; the token comes from `~/.codex/auth.json`, not an env var.
341        // Client construction returns the fixed shared CodexClient and ignores base_url/api_key_env,
342        // so reject them rather than silently dropping a configured endpoint or key.
343        (ProviderType::OpenAi, Some("codex")) => {
344            if base_url.is_some() {
345                eyre::bail!(
346                    "{label}: auth = \"codex\" ignores `base_url` (requests always go to the Codex endpoint) — remove it"
347                );
348            }
349            if api_key_env.is_some() {
350                eyre::bail!(
351                    "{label}: auth = \"codex\" ignores `api_key_env` (the token comes from ~/.codex/auth.json) — remove it"
352                );
353            }
354            Ok(())
355        }
356        (_, Some("codex")) => {
357            eyre::bail!("{label}: auth = \"codex\" is only supported with provider \"openai\"");
358        }
359        // Any other auth value on a non-Gemini provider is a typo or unsupported — reject it at
360        // config time rather than failing cryptically at client construction.
361        (_, Some(other)) => {
362            eyre::bail!("{label}: unknown auth value \"{other}\"");
363        }
364    }
365}
366
367/// Validate the mandatory `auth = "azure-ad"` fields at config time so a typo fails fast here
368/// instead of at the first LLM call. Mirrors the runtime checks in `azure::build_azure_client`
369/// (base_url) and `azure::build_credential_chain` (azure_credentials).
370fn validate_azure_fields(
371    label: &str,
372    base_url: Option<&str>,
373    azure_credentials: Option<&str>,
374) -> Result<()> {
375    if base_url.map(str::trim).filter(|u| !u.is_empty()).is_none() {
376        eyre::bail!(
377            "{label}: auth = \"azure-ad\" requires a non-empty `base_url` (the Azure Foundry endpoint)"
378        );
379    }
380    // Validate whichever credential mode the runtime would actually use. `build_credential_chain`
381    // resolves explicit config first, then the `AZURE_TOKEN_CREDENTIALS` env var — so a bogus env
382    // value (with `azure_credentials` unset) would otherwise pass config validation and only fail
383    // at the first LLM call. Mirror that fallback here so it fails fast too.
384    match azure_credentials {
385        Some(mode) => validate_azure_credentials_mode(label, "azure_credentials", mode)?,
386        None => {
387            if let Ok(env_mode) = std::env::var("AZURE_TOKEN_CREDENTIALS") {
388                validate_azure_credentials_mode(label, "AZURE_TOKEN_CREDENTIALS", &env_mode)?;
389            }
390        }
391    }
392    Ok(())
393}
394
395/// Reject an unknown Azure credential-chain selector. Empty/whitespace is allowed: the runtime
396/// (`build_credential_chain`) treats it as unset and falls back to `"auto"`. `source` names where
397/// the value came from so the error points at the right place (the `azure_credentials` config field
398/// vs the `AZURE_TOKEN_CREDENTIALS` env var).
399fn validate_azure_credentials_mode(label: &str, source: &str, mode: &str) -> Result<()> {
400    let normalized = mode.trim().to_ascii_lowercase();
401    if !normalized.is_empty() && !matches!(normalized.as_str(), "dev" | "prod" | "auto") {
402        eyre::bail!(
403            "{label}: unknown {source} value \"{mode}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
404        );
405    }
406    Ok(())
407}
408
409fn check_env_var(name: &str) -> Result<(), std::env::VarError> {
410    // gemini accepts either GEMINI_API_KEY or GOOGLE_AI_API_KEY
411    if name == "GEMINI_API_KEY" {
412        if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_AI_API_KEY").is_ok() {
413            return Ok(());
414        }
415        return Err(std::env::VarError::NotPresent);
416    }
417    std::env::var(name).map(|_| ())
418}
419
420fn is_local_server(base_url: Option<&str>) -> bool {
421    base_url
422        .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
423        .unwrap_or(false)
424}
425
426fn required_env_var<'a>(settings: ClientSettings<'a>) -> Option<&'a str> {
427    if matches!(settings.provider, ProviderType::Gemini) && is_gemini_proxy_auth(settings.auth) {
428        return None;
429    }
430    if is_azure_ad_auth(settings.auth) {
431        return None;
432    }
433    if is_codex_auth(settings.auth) {
434        return None;
435    }
436    if is_local_server(settings.base_url) {
437        return None;
438    }
439    if let Some(env) = settings.api_key_env {
440        return Some(env);
441    }
442    default_env_var(settings.provider)
443}
444
445fn is_gemini_proxy_auth(auth: Option<&str>) -> bool {
446    matches!(auth, Some("agy-keyring"))
447}
448
449/// Canonical check shared with `provider.rs` (the client-build path), kept here next to the
450/// config types so validation and construction can't drift apart.
451pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
452    matches!(auth, Some("azure-ad"))
453}
454
455/// Codex/ChatGPT subscription auth. Canonical check shared with `provider.rs`.
456pub fn is_codex_auth(auth: Option<&str>) -> bool {
457    matches!(auth, Some("codex"))
458}
459
460fn default_env_var(provider: &ProviderType) -> Option<&'static str> {
461    match provider {
462        ProviderType::Anthropic => Some("ANTHROPIC_API_KEY"),
463        ProviderType::Gemini => Some("GEMINI_API_KEY"),
464        ProviderType::OpenAi => Some("OPENAI_API_KEY"),
465        ProviderType::OpenRouter => Some("OPENROUTER_API_KEY"),
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472
473    const FOUNDRY_URL: &str = "https://res.services.ai.azure.com/openai/v1";
474
475    #[test]
476    fn azure_ad_auth_detection() {
477        assert!(is_azure_ad_auth(Some("azure-ad")));
478        assert!(!is_azure_ad_auth(Some("agy-keyring")));
479        assert!(!is_azure_ad_auth(None));
480    }
481
482    #[test]
483    fn validate_auth_rejects_azure_ad_on_unsupported_providers() {
484        let auth = Some("azure-ad".to_string());
485        assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
486        assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
487    }
488
489    #[test]
490    fn validate_auth_azure_ad_on_supported_providers() {
491        let auth = Some("azure-ad".to_string());
492        // Pass an explicit credential mode so the assertion can't depend on an ambient
493        // `AZURE_TOKEN_CREDENTIALS` (which `None` would make `validate_azure_fields` read).
494        let creds = Some("auto");
495        let openai = validate_auth(
496            "[t]",
497            &ProviderType::OpenAi,
498            &auth,
499            Some(FOUNDRY_URL),
500            None,
501            creds,
502        );
503        let anthropic = validate_auth(
504            "[t]",
505            &ProviderType::Anthropic,
506            &auth,
507            Some(FOUNDRY_URL),
508            None,
509            creds,
510        );
511        // Accepted only when compiled with the `azure` feature; otherwise validation fails fast
512        // with a build hint.
513        if cfg!(feature = "azure") {
514            assert!(openai.is_ok());
515            assert!(anthropic.is_ok());
516        } else {
517            assert!(openai.is_err());
518            assert!(anthropic.is_err());
519        }
520    }
521
522    #[test]
523    fn validate_auth_allows_unset_and_known_values() {
524        assert!(validate_auth("[t]", &ProviderType::OpenAi, &None, None, None, None).is_ok());
525        // agy-keyring is accepted only when compiled with the `antigravity` feature; otherwise
526        // validation fails fast with a build hint (mirrors the azure gate).
527        let agy = validate_auth(
528            "[t]",
529            &ProviderType::Gemini,
530            &Some("agy-keyring".to_string()),
531            None,
532            None,
533            None,
534        );
535        if cfg!(feature = "antigravity") {
536            assert!(agy.is_ok());
537        } else {
538            assert!(agy.is_err());
539        }
540    }
541
542    #[test]
543    fn validate_auth_codex_rejects_ignored_fields() {
544        let auth = Some("codex".to_string());
545        // bare codex auth is fine
546        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
547        // base_url / api_key_env would be silently dropped, so they must be rejected
548        assert!(
549            validate_auth(
550                "[t]",
551                &ProviderType::OpenAi,
552                &auth,
553                Some("https://example.com"),
554                None,
555                None,
556            )
557            .is_err()
558        );
559        assert!(
560            validate_auth(
561                "[t]",
562                &ProviderType::OpenAi,
563                &auth,
564                None,
565                Some("MY_KEY"),
566                None,
567            )
568            .is_err()
569        );
570    }
571
572    #[test]
573    fn codex_auth_detection() {
574        assert!(is_codex_auth(Some("codex")));
575        assert!(!is_codex_auth(Some("azure-ad")));
576        assert!(!is_codex_auth(None));
577    }
578
579    #[test]
580    fn validate_auth_codex_only_on_openai() {
581        let auth = Some("codex".to_string());
582        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
583        assert!(validate_auth("[t]", &ProviderType::Anthropic, &auth, None, None, None).is_err());
584        assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
585        assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
586    }
587
588    /// Codex auth needs no env var, so this validates the same wherever it runs.
589    fn config_with(reviewer_max_tokens: Option<u64>, aggregator_max_tokens: Option<u64>) -> Config {
590        Config {
591            defaults: None,
592            aggregator: AggregatorConfig {
593                model: "gpt-5.4".to_string(),
594                provider: ProviderType::OpenAi,
595                base_url: None,
596                api_key_env: None,
597                max_tokens: aggregator_max_tokens,
598                auth: Some("codex".to_string()),
599                azure_scope: None,
600                azure_credentials: None,
601            },
602            reviewer: vec![ReviewerConfig {
603                name: "r".to_string(),
604                model: "gpt-5.4".to_string(),
605                provider: ProviderType::OpenAi,
606                base_url: None,
607                api_key_env: None,
608                max_tokens: reviewer_max_tokens,
609                compact_threshold: None,
610                auth: Some("codex".to_string()),
611                azure_scope: None,
612                azure_credentials: None,
613            }],
614        }
615    }
616
617    /// Zero is not "no cap" — the provider answers it with nothing. Unset is how no cap is spelled.
618    #[test]
619    fn zero_max_tokens_is_rejected_on_both_entities() {
620        assert!(config_with(None, None).validate().is_ok());
621        assert!(config_with(Some(0), None).validate().is_err());
622        assert!(config_with(None, Some(0)).validate().is_err());
623    }
624
625    #[test]
626    fn codex_auth_requires_no_env_var() {
627        let reviewer = ReviewerConfig {
628            name: "r".to_string(),
629            model: "gpt-5.4".to_string(),
630            provider: ProviderType::OpenAi,
631            base_url: None,
632            api_key_env: None,
633            max_tokens: None,
634            compact_threshold: None,
635            auth: Some("codex".to_string()),
636            azure_scope: None,
637            azure_credentials: None,
638        };
639        assert_eq!(required_env_var(ClientSettings::from(&reviewer)), None);
640        let agg = AggregatorConfig {
641            model: "gpt-5.4".to_string(),
642            provider: ProviderType::OpenAi,
643            base_url: None,
644            api_key_env: None,
645            max_tokens: None,
646            auth: Some("codex".to_string()),
647            azure_scope: None,
648            azure_credentials: None,
649        };
650        assert_eq!(required_env_var(ClientSettings::from(&agg)), None);
651    }
652
653    /// The five short-circuit branches and their precedence, exercised through both role
654    /// functions. The collision rows matter most: a regression that reorders the checks
655    /// (e.g. explicit `api_key_env` consulted before proxy/local short-circuits) passes a
656    /// membership-only table but fails these.
657    #[test]
658    fn required_env_var_branch_table_and_precedence() {
659        fn provider(name: &str) -> ProviderType {
660            match name {
661                "anthropic" => ProviderType::Anthropic,
662                "gemini" => ProviderType::Gemini,
663                "openai" => ProviderType::OpenAi,
664                "openrouter" => ProviderType::OpenRouter,
665                other => panic!("unknown provider in table: {other}"),
666            }
667        }
668
669        // (provider, auth, base_url, api_key_env, expected). Rows pairing a short-circuit
670        // with an explicit api_key_env pin precedence; the last four pin the default table.
671        #[rustfmt::skip]
672        let rows = [
673            ("gemini",     Some("agy-keyring"), None,                              None,             None),
674            ("gemini",     Some("agy-keyring"), None,                              Some("EXPLICIT"), None),
675            // agy-keyring only short-circuits on gemini; elsewhere it falls through
676            ("openai",     Some("agy-keyring"), None,                              None,             Some("OPENAI_API_KEY")),
677            ("openai",     Some("azure-ad"),    Some("https://f.example/v1"),      Some("EXPLICIT"), None),
678            ("openai",     Some("codex"),       None,                              Some("EXPLICIT"), None),
679            ("openai",     None,                Some("http://localhost:1234/v1"),  Some("EXPLICIT"), None),
680            ("openai",     None,                Some("http://127.0.0.1:1234/v1"),  None,             None),
681            // a non-local base_url does not bypass the key; explicit env beats the default
682            ("anthropic",  None,                Some("https://gw.example"),        Some("EXPLICIT"), Some("EXPLICIT")),
683            ("anthropic",  None,                None,                              None,             Some("ANTHROPIC_API_KEY")),
684            ("gemini",     None,                None,                              None,             Some("GEMINI_API_KEY")),
685            ("openai",     None,                None,                              None,             Some("OPENAI_API_KEY")),
686            ("openrouter", None,                None,                              None,             Some("OPENROUTER_API_KEY")),
687        ];
688
689        for (name, auth, base_url, api_key_env, expected) in rows {
690            let reviewer = ReviewerConfig {
691                name: String::new(),
692                model: String::new(),
693                provider: provider(name),
694                base_url: base_url.map(str::to_string),
695                api_key_env: api_key_env.map(str::to_string),
696                max_tokens: None,
697                compact_threshold: None,
698                auth: auth.map(str::to_string),
699                azure_scope: None,
700                azure_credentials: None,
701            };
702            let agg = AggregatorConfig {
703                model: String::new(),
704                provider: provider(name),
705                base_url: base_url.map(str::to_string),
706                api_key_env: api_key_env.map(str::to_string),
707                max_tokens: None,
708                auth: auth.map(str::to_string),
709                azure_scope: None,
710                azure_credentials: None,
711            };
712            for (role, settings) in [
713                ("reviewer", ClientSettings::from(&reviewer)),
714                ("aggregator", ClientSettings::from(&agg)),
715            ] {
716                assert_eq!(
717                    required_env_var(settings),
718                    expected,
719                    "{role}: {name} auth={auth:?} base_url={base_url:?} api_key_env={api_key_env:?}"
720                );
721            }
722        }
723    }
724
725    #[test]
726    fn validate_auth_rejects_unknown_value_on_non_gemini() {
727        // Typos like `azure_ad`/`Azure-AD` must fail at config time, not at client construction.
728        let typo = Some("azure_ad".to_string());
729        assert!(
730            validate_auth(
731                "[t]",
732                &ProviderType::OpenAi,
733                &typo,
734                Some(FOUNDRY_URL),
735                None,
736                None
737            )
738            .is_err()
739        );
740        assert!(validate_auth("[t]", &ProviderType::Anthropic, &typo, None, None, None).is_err());
741    }
742
743    #[cfg(feature = "azure")]
744    #[test]
745    fn validate_auth_azure_ad_requires_base_url() {
746        let auth = Some("azure-ad".to_string());
747        // The two error cases bail on `base_url` before any credential check, so they're already
748        // env-independent; the ok case passes an explicit mode so it doesn't read the ambient
749        // `AZURE_TOKEN_CREDENTIALS` (which a `None` here would).
750        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_err());
751        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, Some(""), None, None).is_err());
752        assert!(
753            validate_auth(
754                "[t]",
755                &ProviderType::OpenAi,
756                &auth,
757                Some(FOUNDRY_URL),
758                None,
759                Some("auto")
760            )
761            .is_ok()
762        );
763    }
764
765    #[test]
766    fn validate_azure_credentials_mode_rejects_unknown_only() {
767        // Known modes pass (case/whitespace normalized like the runtime chain builder).
768        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "dev").is_ok());
769        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "PROD").is_ok());
770        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "auto").is_ok());
771        // Empty/whitespace is treated as unset (runtime falls back to "auto"), so it's allowed.
772        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
773        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "   ").is_ok());
774        // A bogus value is rejected, and the message names the source so a config with no
775        // `azure_credentials` field but a bad env var points the user at the env var.
776        let err = validate_azure_credentials_mode("[t]", "AZURE_TOKEN_CREDENTIALS", "bogus")
777            .unwrap_err()
778            .to_string();
779        assert!(err.contains("AZURE_TOKEN_CREDENTIALS"), "got: {err}");
780        assert!(err.contains("bogus"), "got: {err}");
781    }
782
783    #[cfg(feature = "azure")]
784    #[test]
785    fn validate_auth_azure_ad_validates_credentials() {
786        let auth = Some("azure-ad".to_string());
787        let ok = |creds| {
788            validate_auth(
789                "[t]",
790                &ProviderType::OpenAi,
791                &auth,
792                Some(FOUNDRY_URL),
793                None,
794                creds,
795            )
796            .is_ok()
797        };
798        // Use explicit modes only — `None` would make validation read the ambient
799        // `AZURE_TOKEN_CREDENTIALS`, so a developer/CI with a bogus value set would fail spuriously.
800        // The "unset falls back to auto" behavior is covered hermetically by
801        // `validate_azure_credentials_mode_rejects_unknown_only` (empty string is accepted).
802        assert!(ok(Some("auto")));
803        assert!(ok(Some("dev")));
804        assert!(ok(Some("PROD"))); // case/whitespace normalized like the runtime chain builder
805        assert!(ok(Some("auto")));
806        assert!(
807            validate_auth(
808                "[t]",
809                &ProviderType::OpenAi,
810                &auth,
811                Some(FOUNDRY_URL),
812                None,
813                Some("deve")
814            )
815            .is_err()
816        );
817    }
818}