Skip to main content

nitpicker_agent/
config.rs

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