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