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        // Grok CLI subscription auth routes through the Grok CLI proxy's OpenAI Responses
423        // endpoint; tokens come from `~/.grok/auth.json`, not an env var.
424        (ProviderType::OpenAi, Some("grok")) => {
425            if settings.base_url.is_some() {
426                eyre::bail!(
427                    "{label}: auth = \"grok\" ignores `base_url` (requests always go to the Grok proxy endpoint) — remove it"
428                );
429            }
430            if settings.api_key_env.is_some() {
431                eyre::bail!(
432                    "{label}: auth = \"grok\" ignores `api_key_env` (the token comes from ~/.grok/auth.json) — remove it"
433                );
434            }
435            Ok(())
436        }
437        (_, Some("grok")) => {
438            eyre::bail!("{label}: auth = \"grok\" is only supported with provider \"openai\"");
439        }
440        // Any other auth value on a non-Gemini provider is a typo or unsupported — reject it at
441        // config time rather than failing cryptically at client construction.
442        (_, Some(other)) => {
443            eyre::bail!("{label}: unknown auth value \"{other}\"");
444        }
445    }
446}
447
448/// Validate the mandatory `auth = "azure-ad"` fields at config time so a typo fails fast here
449/// instead of at the first LLM call. Mirrors the runtime checks in `azure::build_azure_client`
450/// (base_url) and `azure::build_credential_chain` (azure_credentials).
451fn validate_azure_fields(
452    label: &str,
453    base_url: Option<&str>,
454    azure_credentials: Option<&str>,
455) -> Result<()> {
456    if base_url.map(str::trim).filter(|u| !u.is_empty()).is_none() {
457        eyre::bail!(
458            "{label}: auth = \"azure-ad\" requires a non-empty `base_url` (the Azure Foundry endpoint)"
459        );
460    }
461    // Validate whichever credential mode the runtime would actually use. `build_credential_chain`
462    // resolves explicit config first, then the `AZURE_TOKEN_CREDENTIALS` env var — so a bogus env
463    // value (with `azure_credentials` unset) would otherwise pass config validation and only fail
464    // at the first LLM call. Mirror that fallback here so it fails fast too.
465    match azure_credentials {
466        Some(mode) => validate_azure_credentials_mode(label, "azure_credentials", mode)?,
467        None => {
468            if let Ok(env_mode) = std::env::var("AZURE_TOKEN_CREDENTIALS") {
469                validate_azure_credentials_mode(label, "AZURE_TOKEN_CREDENTIALS", &env_mode)?;
470            }
471        }
472    }
473    Ok(())
474}
475
476/// Reject an unknown Azure credential-chain selector. Empty/whitespace is allowed: the runtime
477/// (`build_credential_chain`) treats it as unset and falls back to `"auto"`. `source` names where
478/// the value came from so the error points at the right place (the `azure_credentials` config field
479/// vs the `AZURE_TOKEN_CREDENTIALS` env var).
480fn validate_azure_credentials_mode(label: &str, source: &str, mode: &str) -> Result<()> {
481    let normalized = mode.trim().to_ascii_lowercase();
482    if !normalized.is_empty() && !matches!(normalized.as_str(), "dev" | "prod" | "auto") {
483        eyre::bail!(
484            "{label}: unknown {source} value \"{mode}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
485        );
486    }
487    Ok(())
488}
489
490fn check_env_var(name: &str) -> Result<(), std::env::VarError> {
491    // gemini accepts either GEMINI_API_KEY or GOOGLE_AI_API_KEY
492    if name == "GEMINI_API_KEY" {
493        if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_AI_API_KEY").is_ok() {
494            return Ok(());
495        }
496        return Err(std::env::VarError::NotPresent);
497    }
498    std::env::var(name).map(|_| ())
499}
500
501fn is_local_server(base_url: Option<&str>) -> bool {
502    base_url
503        .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
504        .unwrap_or(false)
505}
506
507fn required_env_var<'a>(settings: ClientSettings<'a>) -> Option<&'a str> {
508    if matches!(settings.provider, ProviderType::Gemini) && is_gemini_proxy_auth(settings.auth) {
509        return None;
510    }
511    if is_azure_ad_auth(settings.auth) {
512        return None;
513    }
514    if is_codex_auth(settings.auth) || is_grok_auth(settings.auth) {
515        return None;
516    }
517    if is_local_server(settings.base_url) {
518        return None;
519    }
520    if let Some(env) = settings.api_key_env {
521        return Some(env);
522    }
523    default_env_var(settings.provider)
524}
525
526fn is_gemini_proxy_auth(auth: Option<&str>) -> bool {
527    matches!(auth, Some("agy-keyring"))
528}
529
530/// Canonical check shared with `provider.rs` (the client-build path), kept here next to the
531/// config types so validation and construction can't drift apart.
532pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
533    matches!(auth, Some("azure-ad"))
534}
535
536/// Codex/ChatGPT subscription auth. Canonical check shared with `provider.rs`.
537pub fn is_codex_auth(auth: Option<&str>) -> bool {
538    matches!(auth, Some("codex"))
539}
540
541/// Grok CLI subscription auth. Canonical check shared with `provider.rs`.
542pub fn is_grok_auth(auth: Option<&str>) -> bool {
543    matches!(auth, Some("grok"))
544}
545
546fn default_env_var(provider: &ProviderType) -> Option<&'static str> {
547    match provider {
548        ProviderType::Anthropic => Some("ANTHROPIC_API_KEY"),
549        ProviderType::Gemini => Some("GEMINI_API_KEY"),
550        ProviderType::OpenAi => Some("OPENAI_API_KEY"),
551        ProviderType::OpenRouter => Some("OPENROUTER_API_KEY"),
552        ProviderType::OpenCode | ProviderType::OpenCodeGo => Some("OPENCODE_API_KEY"),
553    }
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559
560    const FOUNDRY_URL: &str = "https://res.services.ai.azure.com/openai/v1";
561
562    fn client_settings<'a>(
563        provider: &'a ProviderType,
564        auth: Option<&'a str>,
565    ) -> ClientSettings<'a> {
566        ClientSettings {
567            provider,
568            auth,
569            base_url: None,
570            api_key_env: None,
571            azure_scope: None,
572            azure_credentials: None,
573        }
574    }
575
576    #[test]
577    fn validate_auth_rejects_azure_ad_on_unsupported_providers() {
578        let auth = Some("azure-ad");
579        assert!(validate_auth("[t]", client_settings(&ProviderType::Gemini, auth),).is_err());
580        assert!(validate_auth("[t]", client_settings(&ProviderType::OpenRouter, auth),).is_err());
581    }
582
583    #[test]
584    fn validate_auth_azure_ad_on_supported_providers() {
585        let auth = Some("azure-ad");
586        // Pass an explicit credential mode so the assertion can't depend on an ambient
587        // `AZURE_TOKEN_CREDENTIALS` (which `None` would make `validate_azure_fields` read).
588        let creds = Some("auto");
589        let openai = validate_auth(
590            "[t]",
591            ClientSettings {
592                base_url: Some(FOUNDRY_URL),
593                azure_credentials: creds,
594                ..client_settings(&ProviderType::OpenAi, auth)
595            },
596        );
597        let anthropic = validate_auth(
598            "[t]",
599            ClientSettings {
600                base_url: Some(FOUNDRY_URL),
601                azure_credentials: creds,
602                ..client_settings(&ProviderType::Anthropic, auth)
603            },
604        );
605        // Accepted only when compiled with the `azure` feature; otherwise validation fails fast
606        // with a build hint.
607        if cfg!(feature = "azure") {
608            assert!(openai.is_ok());
609            assert!(anthropic.is_ok());
610        } else {
611            assert!(openai.is_err());
612            assert!(anthropic.is_err());
613        }
614    }
615
616    #[test]
617    fn validate_auth_allows_unset_and_known_values() {
618        assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, None),).is_ok());
619        // agy-keyring is accepted only when compiled with the `antigravity` feature; otherwise
620        // validation fails fast with a build hint (mirrors the azure gate).
621        let agy = validate_auth(
622            "[t]",
623            client_settings(&ProviderType::Gemini, Some("agy-keyring")),
624        );
625        if cfg!(feature = "antigravity") {
626            assert!(agy.is_ok());
627        } else {
628            assert!(agy.is_err());
629        }
630    }
631
632    #[test]
633    fn validate_auth_codex_rejects_ignored_fields() {
634        let auth = Some("codex");
635        // bare codex auth is fine
636        assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, auth),).is_ok());
637        // base_url / api_key_env would be silently dropped, so they must be rejected
638        assert!(
639            validate_auth(
640                "[t]",
641                ClientSettings {
642                    base_url: Some("https://example.com"),
643                    ..client_settings(&ProviderType::OpenAi, auth)
644                },
645            )
646            .is_err()
647        );
648        assert!(
649            validate_auth(
650                "[t]",
651                ClientSettings {
652                    api_key_env: Some("MY_KEY"),
653                    ..client_settings(&ProviderType::OpenAi, auth)
654                },
655            )
656            .is_err()
657        );
658    }
659
660    #[test]
661    fn validate_auth_grok_rejects_ignored_fields_and_other_providers() {
662        let auth = Some("grok");
663        assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, auth)).is_ok());
664        assert!(
665            validate_auth(
666                "[t]",
667                ClientSettings {
668                    base_url: Some("https://example.com"),
669                    ..client_settings(&ProviderType::OpenAi, auth)
670                },
671            )
672            .is_err()
673        );
674        assert!(
675            validate_auth(
676                "[t]",
677                ClientSettings {
678                    api_key_env: Some("MY_KEY"),
679                    ..client_settings(&ProviderType::OpenAi, auth)
680                },
681            )
682            .is_err()
683        );
684        assert!(validate_auth("[t]", client_settings(&ProviderType::Anthropic, auth)).is_err());
685        assert!(validate_auth("[t]", client_settings(&ProviderType::Gemini, auth)).is_err());
686        assert!(validate_auth("[t]", client_settings(&ProviderType::OpenRouter, auth)).is_err());
687    }
688
689    #[test]
690    fn validate_auth_codex_only_on_openai() {
691        let auth = Some("codex");
692        assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, auth),).is_ok());
693        assert!(validate_auth("[t]", client_settings(&ProviderType::Anthropic, auth),).is_err());
694        assert!(validate_auth("[t]", client_settings(&ProviderType::Gemini, auth),).is_err());
695        assert!(validate_auth("[t]", client_settings(&ProviderType::OpenRouter, auth),).is_err());
696    }
697
698    /// Codex auth needs no env var, so this validates the same wherever it runs.
699    fn config_with(reviewer_max_tokens: Option<u64>, aggregator_max_tokens: Option<u64>) -> Config {
700        Config {
701            defaults: None,
702            aggregator: AggregatorConfig {
703                model: "gpt-5.4".to_string(),
704                provider: ProviderType::OpenAi,
705                base_url: None,
706                api_key_env: None,
707                max_tokens: aggregator_max_tokens,
708                auth: Some("codex".to_string()),
709                azure_scope: None,
710                azure_credentials: None,
711            },
712            reviewer: vec![ReviewerConfig {
713                name: "r".to_string(),
714                model: "gpt-5.4".to_string(),
715                provider: ProviderType::OpenAi,
716                base_url: None,
717                api_key_env: None,
718                max_tokens: reviewer_max_tokens,
719                compact_threshold: None,
720                auth: Some("codex".to_string()),
721                azure_scope: None,
722                azure_credentials: None,
723            }],
724            presets: None,
725        }
726    }
727
728    #[test]
729    fn structural_validation_reports_first_error_in_role_order() {
730        let mut config = config_with(Some(0), Some(0));
731        config.aggregator.model = "free".to_string();
732        config.aggregator.auth = Some("aggregator-typo".to_string());
733        config.reviewer[0].model = "free".to_string();
734        config.reviewer[0].auth = Some("reviewer-typo".to_string());
735        config.reviewer[0].compact_threshold = Some(0);
736
737        let error = config.validate_structure().unwrap_err().to_string();
738        assert!(error.contains("[aggregator]") && error.contains("free"));
739        config.aggregator.model = "gpt-5.4".to_string();
740        let error = config.validate_structure().unwrap_err().to_string();
741        assert!(error.contains("[aggregator]") && error.contains("aggregator-typo"));
742        config.aggregator.auth = Some("codex".to_string());
743        let error = config.validate_structure().unwrap_err().to_string();
744        assert!(error.contains("reviewer r") && error.contains("free"));
745        config.reviewer[0].model = "gpt-5.4".to_string();
746        let error = config.validate_structure().unwrap_err().to_string();
747        assert!(error.contains("reviewer r") && error.contains("reviewer-typo"));
748        config.reviewer[0].auth = Some("codex".to_string());
749        let error = config.validate_structure().unwrap_err().to_string();
750        assert!(error.contains("reviewer r") && error.contains("compact_threshold"));
751        config.reviewer[0].compact_threshold = None;
752        let error = config.validate_structure().unwrap_err().to_string();
753        assert!(error.contains("reviewer r") && error.contains("max_tokens"));
754        config.reviewer[0].max_tokens = None;
755        let error = config.validate_structure().unwrap_err().to_string();
756        assert!(error.contains("[aggregator]") && error.contains("max_tokens"));
757        config.aggregator.max_tokens = None;
758        assert!(config.validate_structure().is_ok());
759    }
760
761    /// Zero is not "no cap" — the provider answers it with nothing. Unset is how no cap is spelled.
762    #[test]
763    fn zero_max_tokens_is_rejected_on_both_entities() {
764        assert!(config_with(None, None).validate().is_ok());
765        assert!(config_with(Some(0), None).validate().is_err());
766        assert!(config_with(None, Some(0)).validate().is_err());
767    }
768
769    #[test]
770    fn fallback_default_is_opt_in_and_requires_a_next_reviewer() {
771        let mut config = config_with(None, None);
772        assert!(!config.default_fallback());
773        config.defaults = Some(DefaultsConfig {
774            debate: None,
775            alloy: None,
776            fallback: Some(true),
777            max_turns: None,
778            compact_threshold: None,
779            log_trajectories: None,
780            presets: None,
781        });
782        assert!(config.default_fallback());
783        assert!(config.validate().is_err());
784
785        config.reviewer.push(ReviewerConfig {
786            name: "r2".to_string(),
787            model: "gpt-5.4".to_string(),
788            provider: ProviderType::OpenAi,
789            base_url: None,
790            api_key_env: None,
791            max_tokens: None,
792            compact_threshold: None,
793            auth: Some("codex".to_string()),
794            azure_scope: None,
795            azure_credentials: None,
796        });
797        assert!(config.validate().is_ok());
798    }
799
800    #[test]
801    fn structural_validation_defers_missing_route_credentials() {
802        let mut config = config_with(None, None);
803        config.aggregator.auth = None;
804        config.aggregator.api_key_env =
805            Some("NITPICKER_TEST_MISSING_AGGREGATOR_CREDENTIAL_FOR_FALLBACK_7C51".to_string());
806
807        assert!(config.validate_structure().is_ok());
808        let err = config.validate_credentials().unwrap_err();
809        assert!(format!("{err:#}").contains("env var"));
810        assert!(config.validate().is_err());
811    }
812
813    /// The five short-circuit branches and their precedence, exercised through both role
814    /// functions. The collision rows matter most: a regression that reorders the checks
815    /// (e.g. explicit `api_key_env` consulted before proxy/local short-circuits) passes a
816    /// membership-only table but fails these.
817    #[test]
818    fn required_env_var_branch_table_and_precedence() {
819        fn provider(name: &str) -> ProviderType {
820            match name {
821                "anthropic" => ProviderType::Anthropic,
822                "gemini" => ProviderType::Gemini,
823                "openai" => ProviderType::OpenAi,
824                "openrouter" => ProviderType::OpenRouter,
825                other => panic!("unknown provider in table: {other}"),
826            }
827        }
828
829        // (provider, auth, base_url, api_key_env, expected). Rows pairing a short-circuit
830        // with an explicit api_key_env pin precedence; the last four pin the default table.
831        #[rustfmt::skip]
832        let rows = [
833            ("gemini",     Some("agy-keyring"), None,                              None,             None),
834            ("gemini",     Some("agy-keyring"), None,                              Some("EXPLICIT"), None),
835            // agy-keyring only short-circuits on gemini; elsewhere it falls through
836            ("openai",     Some("agy-keyring"), None,                              None,             Some("OPENAI_API_KEY")),
837            ("openai",     Some("azure-ad"),    Some("https://f.example/v1"),      Some("EXPLICIT"), None),
838            ("openai",     Some("codex"),       None,                              None,             None),
839            ("openai",     Some("codex"),       None,                              Some("EXPLICIT"), None),
840            ("openai",     Some("grok"),        None,                              None,             None),
841            ("openai",     Some("grok"),        None,                              Some("EXPLICIT"), None),
842            ("openai",     None,                Some("http://localhost:1234/v1"),  Some("EXPLICIT"), None),
843            ("openai",     None,                Some("http://127.0.0.1:1234/v1"),  None,             None),
844            // a non-local base_url does not bypass the key; explicit env beats the default
845            ("anthropic",  None,                Some("https://gw.example"),        Some("EXPLICIT"), Some("EXPLICIT")),
846            ("anthropic",  None,                None,                              None,             Some("ANTHROPIC_API_KEY")),
847            ("gemini",     None,                None,                              None,             Some("GEMINI_API_KEY")),
848            ("openai",     None,                None,                              None,             Some("OPENAI_API_KEY")),
849            ("openrouter", None,                None,                              None,             Some("OPENROUTER_API_KEY")),
850        ];
851
852        for (name, auth, base_url, api_key_env, expected) in rows {
853            let reviewer = ReviewerConfig {
854                name: String::new(),
855                model: String::new(),
856                provider: provider(name),
857                base_url: base_url.map(str::to_string),
858                api_key_env: api_key_env.map(str::to_string),
859                max_tokens: None,
860                compact_threshold: None,
861                auth: auth.map(str::to_string),
862                azure_scope: None,
863                azure_credentials: None,
864            };
865            let agg = AggregatorConfig {
866                model: String::new(),
867                provider: provider(name),
868                base_url: base_url.map(str::to_string),
869                api_key_env: api_key_env.map(str::to_string),
870                max_tokens: None,
871                auth: auth.map(str::to_string),
872                azure_scope: None,
873                azure_credentials: None,
874            };
875            for (role, settings) in [
876                ("reviewer", ClientSettings::from(&reviewer)),
877                ("aggregator", ClientSettings::from(&agg)),
878            ] {
879                assert_eq!(
880                    required_env_var(settings),
881                    expected,
882                    "{role}: {name} auth={auth:?} base_url={base_url:?} api_key_env={api_key_env:?}"
883                );
884            }
885        }
886    }
887
888    #[test]
889    fn validate_auth_rejects_unknown_value_on_non_gemini() {
890        // Typos like `azure_ad`/`Azure-AD` must fail at config time, not at client construction.
891        let typo = Some("azure_ad");
892        assert!(
893            validate_auth(
894                "[t]",
895                ClientSettings {
896                    base_url: Some(FOUNDRY_URL),
897                    ..client_settings(&ProviderType::OpenAi, typo)
898                },
899            )
900            .is_err()
901        );
902        assert!(validate_auth("[t]", client_settings(&ProviderType::Anthropic, typo),).is_err());
903    }
904
905    #[cfg(feature = "azure")]
906    #[test]
907    fn validate_auth_azure_ad_requires_base_url() {
908        let auth = Some("azure-ad");
909        // The two error cases bail on `base_url` before any credential check, so they're already
910        // env-independent; the ok case passes an explicit mode so it doesn't read the ambient
911        // `AZURE_TOKEN_CREDENTIALS` (which a `None` here would).
912        assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, auth),).is_err());
913        assert!(
914            validate_auth(
915                "[t]",
916                ClientSettings {
917                    base_url: Some(""),
918                    ..client_settings(&ProviderType::OpenAi, auth)
919                },
920            )
921            .is_err()
922        );
923        assert!(
924            validate_auth(
925                "[t]",
926                ClientSettings {
927                    base_url: Some(FOUNDRY_URL),
928                    azure_credentials: Some("auto"),
929                    ..client_settings(&ProviderType::OpenAi, auth)
930                },
931            )
932            .is_ok()
933        );
934    }
935
936    #[test]
937    fn validate_azure_credentials_mode_rejects_unknown_only() {
938        // Known modes pass (case/whitespace normalized like the runtime chain builder).
939        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "dev").is_ok());
940        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "PROD").is_ok());
941        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "auto").is_ok());
942        // Empty/whitespace is treated as unset (runtime falls back to "auto"), so it's allowed.
943        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
944        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "   ").is_ok());
945        // A bogus value is rejected, and the message names the source so a config with no
946        // `azure_credentials` field but a bad env var points the user at the env var.
947        let err = validate_azure_credentials_mode("[t]", "AZURE_TOKEN_CREDENTIALS", "bogus")
948            .unwrap_err()
949            .to_string();
950        assert!(err.contains("AZURE_TOKEN_CREDENTIALS"), "got: {err}");
951        assert!(err.contains("bogus"), "got: {err}");
952    }
953
954    #[cfg(feature = "azure")]
955    #[test]
956    fn validate_auth_azure_ad_validates_credentials() {
957        let auth = Some("azure-ad");
958        let ok = |creds| {
959            validate_auth(
960                "[t]",
961                ClientSettings {
962                    base_url: Some(FOUNDRY_URL),
963                    azure_credentials: creds,
964                    ..client_settings(&ProviderType::OpenAi, auth)
965                },
966            )
967            .is_ok()
968        };
969        // Use explicit modes only — `None` would make validation read the ambient
970        // `AZURE_TOKEN_CREDENTIALS`, so a developer/CI with a bogus value set would fail spuriously.
971        // The "unset falls back to auto" behavior is covered hermetically by
972        // `validate_azure_credentials_mode_rejects_unknown_only` (empty string is accepted).
973        assert!(ok(Some("auto")));
974        assert!(!ok(Some("deve")));
975    }
976
977    /// Selection trims names before lookup, so a padded `[presets." x "]` key could never be
978    /// selected — it must be rejected at validation instead of silently shadowed; blank
979    /// prompts and blank names are data errors the library owns.
980    #[test]
981    fn preset_tables_reject_blank_and_padded_names_and_blank_prompts() {
982        let table = |name: &str, prompt: &str| {
983            let mut presets = BTreeMap::new();
984            presets.insert(
985                name.to_string(),
986                PresetConfig {
987                    prompt: prompt.to_string(),
988                },
989            );
990            presets
991        };
992        assert!(validate_presets(None).is_ok());
993        assert!(validate_presets(Some(&table("tone", "review the docs"))).is_ok());
994        assert!(validate_presets(Some(&table(" tone", "review the docs"))).is_err());
995        assert!(validate_presets(Some(&table("  ", "review the docs"))).is_err());
996        assert!(validate_presets(Some(&table("tone", "   "))).is_err());
997    }
998
999    /// Preset names reach terminal output and report headers raw, so C0/C1 (and thereby
1000    /// OSC/CSI escape openers) must be rejected at validation, not sanitized at display.
1001    #[test]
1002    fn preset_tables_reject_control_bytes_in_names() {
1003        let table = |name: &str| {
1004            let mut presets = BTreeMap::new();
1005            presets.insert(
1006                name.to_string(),
1007                PresetConfig {
1008                    prompt: "review the docs".to_string(),
1009                },
1010            );
1011            presets
1012        };
1013        for name in [
1014            "esc\u{1b}]0;pwn\u{7}",
1015            "csi\u{9b}31m",
1016            "tab\tname",
1017            "nl\nname",
1018        ] {
1019            let err = validate_presets(Some(&table(name))).expect_err("control bytes rejected");
1020            assert!(
1021                format!("{err:#}").contains("control characters"),
1022                "wrong error for {name:?}: {err:#}"
1023            );
1024        }
1025    }
1026}