1use eyre::Result;
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4
5pub const DEFAULT_MAX_TURNS: usize = 100;
6
7pub const DEFAULT_AGGREGATOR_MAX_TOKENS: u64 = 16_384;
11
12#[derive(Serialize, Deserialize)]
13#[serde(deny_unknown_fields)]
14pub struct Config {
15 #[serde(skip_serializing_if = "Option::is_none")]
16 pub defaults: Option<DefaultsConfig>,
17 pub aggregator: AggregatorConfig,
18 pub reviewer: Vec<ReviewerConfig>,
19 #[serde(skip_serializing_if = "Option::is_none")]
22 pub presets: Option<BTreeMap<String, PresetConfig>>,
23}
24
25#[derive(Serialize, Deserialize)]
27#[serde(deny_unknown_fields)]
28pub struct PresetConfig {
29 pub prompt: String,
30}
31
32#[derive(Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct DefaultsConfig {
35 #[serde(skip_serializing_if = "Option::is_none")]
36 pub debate: Option<bool>,
37 #[serde(skip_serializing_if = "Option::is_none")]
38 pub alloy: Option<bool>,
39 #[serde(skip_serializing_if = "Option::is_none")]
41 pub fallback: Option<bool>,
42 #[serde(skip_serializing_if = "Option::is_none")]
43 pub max_turns: Option<usize>,
44 #[serde(skip_serializing_if = "Option::is_none")]
45 pub compact_threshold: Option<u64>,
46 #[serde(skip_serializing_if = "Option::is_none")]
47 pub log_trajectories: Option<bool>,
48 #[serde(skip_serializing_if = "Option::is_none")]
51 pub presets: Option<Vec<String>>,
52}
53
54#[derive(Serialize, Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct AggregatorConfig {
57 #[serde(default)]
58 pub model: String,
59 pub provider: ProviderType,
60 #[serde(skip_serializing_if = "Option::is_none")]
61 pub base_url: Option<String>,
62 #[serde(skip_serializing_if = "Option::is_none")]
63 pub api_key_env: Option<String>,
64 #[serde(skip_serializing_if = "Option::is_none")]
65 pub max_tokens: Option<u64>,
66 #[serde(skip_serializing_if = "Option::is_none")]
67 pub auth: Option<String>,
68 #[serde(skip_serializing_if = "Option::is_none")]
70 pub azure_scope: Option<String>,
71 #[serde(skip_serializing_if = "Option::is_none")]
73 pub azure_credentials: Option<String>,
74}
75
76#[derive(Serialize, Deserialize)]
77#[serde(deny_unknown_fields)]
78pub struct ReviewerConfig {
79 #[serde(default)]
80 pub name: String,
81 #[serde(default)]
82 pub model: String,
83 pub provider: ProviderType,
84 #[serde(skip_serializing_if = "Option::is_none")]
85 pub base_url: Option<String>,
86 #[serde(skip_serializing_if = "Option::is_none")]
87 pub api_key_env: Option<String>,
88 #[serde(skip_serializing_if = "Option::is_none")]
91 pub max_tokens: Option<u64>,
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub compact_threshold: Option<u64>,
94 #[serde(skip_serializing_if = "Option::is_none")]
95 pub auth: Option<String>,
96 #[serde(skip_serializing_if = "Option::is_none")]
98 pub azure_scope: Option<String>,
99 #[serde(skip_serializing_if = "Option::is_none")]
101 pub azure_credentials: Option<String>,
102}
103
104pub(crate) struct ClientSettings<'a> {
108 pub(crate) provider: &'a ProviderType,
109 pub(crate) auth: Option<&'a str>,
110 pub(crate) base_url: Option<&'a str>,
111 pub(crate) api_key_env: Option<&'a str>,
112 pub(crate) azure_scope: Option<&'a str>,
113 pub(crate) azure_credentials: Option<&'a str>,
114}
115
116impl<'a> From<&'a ReviewerConfig> for ClientSettings<'a> {
117 fn from(reviewer: &'a ReviewerConfig) -> Self {
118 Self {
119 provider: &reviewer.provider,
120 auth: reviewer.auth.as_deref(),
121 base_url: reviewer.base_url.as_deref(),
122 api_key_env: reviewer.api_key_env.as_deref(),
123 azure_scope: reviewer.azure_scope.as_deref(),
124 azure_credentials: reviewer.azure_credentials.as_deref(),
125 }
126 }
127}
128
129impl<'a> From<&'a AggregatorConfig> for ClientSettings<'a> {
130 fn from(agg: &'a AggregatorConfig) -> Self {
131 Self {
132 provider: &agg.provider,
133 auth: agg.auth.as_deref(),
134 base_url: agg.base_url.as_deref(),
135 api_key_env: agg.api_key_env.as_deref(),
136 azure_scope: agg.azure_scope.as_deref(),
137 azure_credentials: agg.azure_credentials.as_deref(),
138 }
139 }
140}
141
142#[derive(Serialize, Deserialize)]
143pub enum ProviderType {
144 #[serde(rename = "anthropic", alias = "anthropic_compatible")]
145 Anthropic,
146 #[serde(rename = "gemini")]
147 Gemini,
148 #[serde(rename = "openai", alias = "openai_compatible")]
149 OpenAi,
150 #[serde(rename = "openrouter")]
151 OpenRouter,
152 #[serde(rename = "opencode")]
153 OpenCode,
154 #[serde(rename = "opencode-go")]
155 OpenCodeGo,
156}
157
158impl ProviderType {
159 #[cfg(feature = "antigravity")]
161 pub fn is_gemini(&self) -> bool {
162 matches!(self, ProviderType::Gemini)
163 }
164}
165
166impl Config {
167 pub fn validate(&self) -> Result<()> {
168 self.validate_structure()?;
169 self.validate_credentials()
170 }
171
172 pub fn validate_structure(&self) -> Result<()> {
176 if self.reviewer.is_empty() {
177 eyre::bail!("no reviewers configured");
178 }
179
180 self.validate_alloy(self.default_alloy())?;
181 self.validate_fallback(self.default_fallback())?;
182
183 validate_free_model(
184 "[aggregator]",
185 &self.aggregator.provider,
186 &self.aggregator.model,
187 )?;
188
189 validate_auth("[aggregator]", ClientSettings::from(&self.aggregator))?;
193
194 for reviewer in &self.reviewer {
195 let reviewer_label = match reviewer.name.is_empty() {
196 true => "reviewer <unnamed>".to_string(),
197 false => format!("reviewer {}", reviewer.name),
198 };
199 validate_free_model(&reviewer_label, &reviewer.provider, &reviewer.model)?;
200 validate_auth(&reviewer_label, ClientSettings::from(reviewer))?;
201 if reviewer.compact_threshold == Some(0) {
202 eyre::bail!(
203 "reviewer {}: compact_threshold must be greater than 0",
204 reviewer.name
205 );
206 }
207 if reviewer.max_tokens == Some(0) {
208 eyre::bail!(
209 "reviewer {}: max_tokens must be greater than 0",
210 reviewer.name
211 );
212 }
213 }
214
215 if self.aggregator.max_tokens == Some(0) {
216 eyre::bail!("[aggregator].max_tokens must be greater than 0");
217 }
218
219 if self.defaults.as_ref().and_then(|d| d.compact_threshold) == Some(0) {
220 eyre::bail!("[defaults].compact_threshold must be greater than 0");
221 }
222
223 validate_presets(self.presets.as_ref())?;
224
225 Ok(())
226 }
227
228 pub fn default_debate(&self) -> bool {
229 self.defaults
230 .as_ref()
231 .and_then(|d| d.debate)
232 .unwrap_or(true)
233 }
234
235 pub fn validate_alloy(&self, alloy: bool) -> Result<()> {
236 if alloy && self.reviewer.len() < 2 {
237 eyre::bail!(
238 "--alloy requires at least 2 reviewers, found {}",
239 self.reviewer.len()
240 );
241 }
242 Ok(())
243 }
244
245 pub fn validate_credentials(&self) -> Result<()> {
248 if let Some(env) = required_env_var(ClientSettings::from(&self.aggregator)) {
249 check_env_var(env)
250 .map_err(|_| eyre::eyre!("[aggregator]: env var {env} is not set"))?;
251 }
252 for reviewer in &self.reviewer {
253 if let Some(env) = required_env_var(ClientSettings::from(reviewer)) {
254 check_env_var(env).map_err(|_| {
255 eyre::eyre!("reviewer {}: env var {env} is not set", reviewer.name)
256 })?;
257 }
258 }
259 Ok(())
260 }
261
262 pub fn default_alloy(&self) -> bool {
263 self.defaults
264 .as_ref()
265 .and_then(|d| d.alloy)
266 .unwrap_or(false)
267 }
268
269 pub fn validate_fallback(&self, fallback: bool) -> Result<()> {
270 if fallback && self.reviewer.len() < 2 {
271 eyre::bail!(
272 "fallback = true / --fallback requires at least 2 reviewers, found {}",
273 self.reviewer.len()
274 );
275 }
276 Ok(())
277 }
278
279 pub fn default_fallback(&self) -> bool {
280 self.defaults
281 .as_ref()
282 .and_then(|d| d.fallback)
283 .unwrap_or(false)
284 }
285
286 pub fn max_turns(&self, override_max_turns: Option<usize>) -> Result<usize> {
287 match override_max_turns {
288 Some(max_turns) => Ok(max_turns),
289 None => self.default_max_turns(),
290 }
291 }
292
293 pub fn default_max_turns(&self) -> Result<usize> {
294 let max_turns = self
295 .defaults
296 .as_ref()
297 .and_then(|d| d.max_turns)
298 .unwrap_or(DEFAULT_MAX_TURNS);
299
300 if max_turns == 0 {
301 eyre::bail!("[defaults].max_turns must be greater than 0");
302 }
303
304 Ok(max_turns)
305 }
306
307 pub fn default_compact_threshold(&self) -> Option<u64> {
308 self.defaults.as_ref().and_then(|d| d.compact_threshold)
309 }
310
311 pub fn log_trajectories(&self) -> bool {
312 self.defaults
313 .as_ref()
314 .and_then(|d| d.log_trajectories)
315 .unwrap_or(false)
316 }
317
318 pub fn aggregator_max_tokens(&self) -> u64 {
319 self.aggregator
320 .max_tokens
321 .unwrap_or(DEFAULT_AGGREGATOR_MAX_TOKENS)
322 }
323
324 pub fn reviewer_compact_threshold(&self, reviewer: &ReviewerConfig) -> Option<u64> {
325 reviewer
326 .compact_threshold
327 .or(self.default_compact_threshold())
328 }
329}
330
331fn validate_presets(presets: Option<&BTreeMap<String, PresetConfig>>) -> Result<()> {
332 let presets = match presets {
333 Some(presets) => presets,
334 None => return Ok(()),
335 };
336 for (name, preset) in presets {
337 if name.trim().is_empty() {
338 eyre::bail!("[presets]: preset names must contain non-whitespace content");
339 }
340 if name != name.trim() {
343 eyre::bail!("[presets.{name:?}]: preset names must not have surrounding whitespace");
344 }
345 if name.chars().any(char::is_control) {
348 eyre::bail!("[presets.{name:?}]: preset names must not contain control characters");
349 }
350 if preset.prompt.trim().is_empty() {
351 eyre::bail!("[presets.{name}].prompt must contain non-whitespace content");
352 }
353 }
354 Ok(())
355}
356
357fn validate_free_model(label: &str, provider: &ProviderType, model: &str) -> Result<()> {
358 if model == "free" && !matches!(provider, ProviderType::OpenRouter) {
359 eyre::bail!("{label}: model = \"free\" is only supported with provider = \"openrouter\"");
360 }
361
362 Ok(())
363}
364
365fn validate_auth(label: &str, settings: ClientSettings<'_>) -> Result<()> {
366 match (settings.provider, settings.auth) {
367 (_, None) => Ok(()),
369 (ProviderType::Gemini, Some("oauth")) => {
370 eyre::bail!(
371 "{label}: auth = \"oauth\" has been removed — use auth = \"agy-keyring\" (see README) or unset `auth` to use GEMINI_API_KEY"
372 );
373 }
374 (ProviderType::Gemini, Some("agy-keyring")) => {
377 if !cfg!(feature = "antigravity") {
378 eyre::bail!(
379 "{label}: auth = \"agy-keyring\" requires building nitpicker with `--features antigravity`"
380 );
381 }
382 Ok(())
383 }
384 (ProviderType::Gemini, Some(other)) => {
385 eyre::bail!(
386 "{label}: unknown auth value \"{other}\" — expected \"agy-keyring\" or unset"
387 );
388 }
389 (ProviderType::OpenAi | ProviderType::Anthropic, Some("azure-ad")) => {
392 if !cfg!(feature = "azure") {
393 eyre::bail!(
394 "{label}: auth = \"azure-ad\" requires building nitpicker with `--features azure`"
395 );
396 }
397 validate_azure_fields(label, settings.base_url, settings.azure_credentials)
398 }
399 (_, Some("azure-ad")) => {
400 eyre::bail!(
401 "{label}: auth = \"azure-ad\" is only supported with provider \"openai\" or \"anthropic\""
402 );
403 }
404 (ProviderType::OpenAi, Some("codex")) => {
409 if settings.base_url.is_some() {
410 eyre::bail!(
411 "{label}: auth = \"codex\" ignores `base_url` (requests always go to the Codex endpoint) — remove it"
412 );
413 }
414 if settings.api_key_env.is_some() {
415 eyre::bail!(
416 "{label}: auth = \"codex\" ignores `api_key_env` (the token comes from ~/.codex/auth.json) — remove it"
417 );
418 }
419 Ok(())
420 }
421 (_, Some("codex")) => {
422 eyre::bail!("{label}: auth = \"codex\" is only supported with provider \"openai\"");
423 }
424 (ProviderType::OpenAi, Some("grok")) => {
427 if settings.base_url.is_some() {
428 eyre::bail!(
429 "{label}: auth = \"grok\" ignores `base_url` (requests always go to the Grok proxy endpoint) — remove it"
430 );
431 }
432 if settings.api_key_env.is_some() {
433 eyre::bail!(
434 "{label}: auth = \"grok\" ignores `api_key_env` (the token comes from ~/.grok/auth.json) — remove it"
435 );
436 }
437 Ok(())
438 }
439 (_, Some("grok")) => {
440 eyre::bail!("{label}: auth = \"grok\" is only supported with provider \"openai\"");
441 }
442 (_, Some(other)) => {
445 eyre::bail!("{label}: unknown auth value \"{other}\"");
446 }
447 }
448}
449
450fn validate_azure_fields(
454 label: &str,
455 base_url: Option<&str>,
456 azure_credentials: Option<&str>,
457) -> Result<()> {
458 if base_url.map(str::trim).filter(|u| !u.is_empty()).is_none() {
459 eyre::bail!(
460 "{label}: auth = \"azure-ad\" requires a non-empty `base_url` (the Azure Foundry endpoint)"
461 );
462 }
463 match azure_credentials {
468 Some(mode) => validate_azure_credentials_mode(label, "azure_credentials", mode)?,
469 None => {
470 if let Ok(env_mode) = std::env::var("AZURE_TOKEN_CREDENTIALS") {
471 validate_azure_credentials_mode(label, "AZURE_TOKEN_CREDENTIALS", &env_mode)?;
472 }
473 }
474 }
475 Ok(())
476}
477
478fn validate_azure_credentials_mode(label: &str, source: &str, mode: &str) -> Result<()> {
483 let normalized = mode.trim().to_ascii_lowercase();
484 if !normalized.is_empty() && !matches!(normalized.as_str(), "dev" | "prod" | "auto") {
485 eyre::bail!(
486 "{label}: unknown {source} value \"{mode}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
487 );
488 }
489 Ok(())
490}
491
492fn check_env_var(name: &str) -> Result<(), std::env::VarError> {
493 if name == "GEMINI_API_KEY" {
495 if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_AI_API_KEY").is_ok() {
496 return Ok(());
497 }
498 return Err(std::env::VarError::NotPresent);
499 }
500 std::env::var(name).map(|_| ())
501}
502
503fn is_local_server(base_url: Option<&str>) -> bool {
504 base_url
505 .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
506 .unwrap_or(false)
507}
508
509fn required_env_var<'a>(settings: ClientSettings<'a>) -> Option<&'a str> {
510 if matches!(settings.provider, ProviderType::Gemini) && is_gemini_proxy_auth(settings.auth) {
511 return None;
512 }
513 if is_azure_ad_auth(settings.auth) {
514 return None;
515 }
516 if is_codex_auth(settings.auth) || is_grok_auth(settings.auth) {
517 return None;
518 }
519 if is_local_server(settings.base_url) {
520 return None;
521 }
522 if let Some(env) = settings.api_key_env {
523 return Some(env);
524 }
525 default_env_var(settings.provider)
526}
527
528fn is_gemini_proxy_auth(auth: Option<&str>) -> bool {
529 matches!(auth, Some("agy-keyring"))
530}
531
532pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
535 matches!(auth, Some("azure-ad"))
536}
537
538pub fn is_codex_auth(auth: Option<&str>) -> bool {
540 matches!(auth, Some("codex"))
541}
542
543pub fn is_grok_auth(auth: Option<&str>) -> bool {
545 matches!(auth, Some("grok"))
546}
547
548fn default_env_var(provider: &ProviderType) -> Option<&'static str> {
549 match provider {
550 ProviderType::Anthropic => Some("ANTHROPIC_API_KEY"),
551 ProviderType::Gemini => Some("GEMINI_API_KEY"),
552 ProviderType::OpenAi => Some("OPENAI_API_KEY"),
553 ProviderType::OpenRouter => Some("OPENROUTER_API_KEY"),
554 ProviderType::OpenCode | ProviderType::OpenCodeGo => Some("OPENCODE_API_KEY"),
555 }
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561
562 const FOUNDRY_URL: &str = "https://res.services.ai.azure.com/openai/v1";
563
564 fn client_settings<'a>(
565 provider: &'a ProviderType,
566 auth: Option<&'a str>,
567 ) -> ClientSettings<'a> {
568 ClientSettings {
569 provider,
570 auth,
571 base_url: None,
572 api_key_env: None,
573 azure_scope: None,
574 azure_credentials: None,
575 }
576 }
577
578 #[test]
579 fn validate_auth_rejects_azure_ad_on_unsupported_providers() {
580 let auth = Some("azure-ad");
581 assert!(validate_auth("[t]", client_settings(&ProviderType::Gemini, auth),).is_err());
582 assert!(validate_auth("[t]", client_settings(&ProviderType::OpenRouter, auth),).is_err());
583 }
584
585 #[test]
586 fn validate_auth_azure_ad_on_supported_providers() {
587 let auth = Some("azure-ad");
588 let creds = Some("auto");
591 let openai = validate_auth(
592 "[t]",
593 ClientSettings {
594 base_url: Some(FOUNDRY_URL),
595 azure_credentials: creds,
596 ..client_settings(&ProviderType::OpenAi, auth)
597 },
598 );
599 let anthropic = validate_auth(
600 "[t]",
601 ClientSettings {
602 base_url: Some(FOUNDRY_URL),
603 azure_credentials: creds,
604 ..client_settings(&ProviderType::Anthropic, auth)
605 },
606 );
607 if cfg!(feature = "azure") {
610 assert!(openai.is_ok());
611 assert!(anthropic.is_ok());
612 } else {
613 assert!(openai.is_err());
614 assert!(anthropic.is_err());
615 }
616 }
617
618 #[test]
619 fn validate_auth_allows_unset_and_known_values() {
620 assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, None),).is_ok());
621 let agy = validate_auth(
624 "[t]",
625 client_settings(&ProviderType::Gemini, Some("agy-keyring")),
626 );
627 if cfg!(feature = "antigravity") {
628 assert!(agy.is_ok());
629 } else {
630 assert!(agy.is_err());
631 }
632 }
633
634 #[test]
635 fn validate_auth_codex_rejects_ignored_fields() {
636 let auth = Some("codex");
637 assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, auth),).is_ok());
639 assert!(
641 validate_auth(
642 "[t]",
643 ClientSettings {
644 base_url: Some("https://example.com"),
645 ..client_settings(&ProviderType::OpenAi, auth)
646 },
647 )
648 .is_err()
649 );
650 assert!(
651 validate_auth(
652 "[t]",
653 ClientSettings {
654 api_key_env: Some("MY_KEY"),
655 ..client_settings(&ProviderType::OpenAi, auth)
656 },
657 )
658 .is_err()
659 );
660 }
661
662 #[test]
663 fn validate_auth_grok_rejects_ignored_fields_and_other_providers() {
664 let auth = Some("grok");
665 assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, auth)).is_ok());
666 assert!(
667 validate_auth(
668 "[t]",
669 ClientSettings {
670 base_url: Some("https://example.com"),
671 ..client_settings(&ProviderType::OpenAi, auth)
672 },
673 )
674 .is_err()
675 );
676 assert!(
677 validate_auth(
678 "[t]",
679 ClientSettings {
680 api_key_env: Some("MY_KEY"),
681 ..client_settings(&ProviderType::OpenAi, auth)
682 },
683 )
684 .is_err()
685 );
686 assert!(validate_auth("[t]", client_settings(&ProviderType::Anthropic, auth)).is_err());
687 assert!(validate_auth("[t]", client_settings(&ProviderType::Gemini, auth)).is_err());
688 assert!(validate_auth("[t]", client_settings(&ProviderType::OpenRouter, auth)).is_err());
689 }
690
691 #[test]
692 fn validate_auth_codex_only_on_openai() {
693 let auth = Some("codex");
694 assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, auth),).is_ok());
695 assert!(validate_auth("[t]", client_settings(&ProviderType::Anthropic, auth),).is_err());
696 assert!(validate_auth("[t]", client_settings(&ProviderType::Gemini, auth),).is_err());
697 assert!(validate_auth("[t]", client_settings(&ProviderType::OpenRouter, auth),).is_err());
698 }
699
700 fn config_with(reviewer_max_tokens: Option<u64>, aggregator_max_tokens: Option<u64>) -> Config {
702 Config {
703 defaults: None,
704 aggregator: AggregatorConfig {
705 model: "gpt-5.4".to_string(),
706 provider: ProviderType::OpenAi,
707 base_url: None,
708 api_key_env: None,
709 max_tokens: aggregator_max_tokens,
710 auth: Some("codex".to_string()),
711 azure_scope: None,
712 azure_credentials: None,
713 },
714 reviewer: vec![ReviewerConfig {
715 name: "r".to_string(),
716 model: "gpt-5.4".to_string(),
717 provider: ProviderType::OpenAi,
718 base_url: None,
719 api_key_env: None,
720 max_tokens: reviewer_max_tokens,
721 compact_threshold: None,
722 auth: Some("codex".to_string()),
723 azure_scope: None,
724 azure_credentials: None,
725 }],
726 presets: None,
727 }
728 }
729
730 #[test]
731 fn structural_validation_reports_first_error_in_role_order() {
732 let mut config = config_with(Some(0), Some(0));
733 config.aggregator.model = "free".to_string();
734 config.aggregator.auth = Some("aggregator-typo".to_string());
735 config.reviewer[0].model = "free".to_string();
736 config.reviewer[0].auth = Some("reviewer-typo".to_string());
737 config.reviewer[0].compact_threshold = Some(0);
738
739 let error = config.validate_structure().unwrap_err().to_string();
740 assert!(error.contains("[aggregator]") && error.contains("free"));
741 config.aggregator.model = "gpt-5.4".to_string();
742 let error = config.validate_structure().unwrap_err().to_string();
743 assert!(error.contains("[aggregator]") && error.contains("aggregator-typo"));
744 config.aggregator.auth = Some("codex".to_string());
745 let error = config.validate_structure().unwrap_err().to_string();
746 assert!(error.contains("reviewer r") && error.contains("free"));
747 config.reviewer[0].model = "gpt-5.4".to_string();
748 let error = config.validate_structure().unwrap_err().to_string();
749 assert!(error.contains("reviewer r") && error.contains("reviewer-typo"));
750 config.reviewer[0].auth = Some("codex".to_string());
751 let error = config.validate_structure().unwrap_err().to_string();
752 assert!(error.contains("reviewer r") && error.contains("compact_threshold"));
753 config.reviewer[0].compact_threshold = None;
754 let error = config.validate_structure().unwrap_err().to_string();
755 assert!(error.contains("reviewer r") && error.contains("max_tokens"));
756 config.reviewer[0].max_tokens = None;
757 let error = config.validate_structure().unwrap_err().to_string();
758 assert!(error.contains("[aggregator]") && error.contains("max_tokens"));
759 config.aggregator.max_tokens = None;
760 assert!(config.validate_structure().is_ok());
761 }
762
763 #[test]
765 fn zero_max_tokens_is_rejected_on_both_entities() {
766 assert!(config_with(None, None).validate().is_ok());
767 assert!(config_with(Some(0), None).validate().is_err());
768 assert!(config_with(None, Some(0)).validate().is_err());
769 }
770
771 #[test]
772 fn fallback_default_is_opt_in_and_requires_a_next_reviewer() {
773 let mut config = config_with(None, None);
774 assert!(!config.default_fallback());
775 config.defaults = Some(DefaultsConfig {
776 debate: None,
777 alloy: None,
778 fallback: Some(true),
779 max_turns: None,
780 compact_threshold: None,
781 log_trajectories: None,
782 presets: None,
783 });
784 assert!(config.default_fallback());
785 assert!(config.validate().is_err());
786
787 config.reviewer.push(ReviewerConfig {
788 name: "r2".to_string(),
789 model: "gpt-5.4".to_string(),
790 provider: ProviderType::OpenAi,
791 base_url: None,
792 api_key_env: None,
793 max_tokens: None,
794 compact_threshold: None,
795 auth: Some("codex".to_string()),
796 azure_scope: None,
797 azure_credentials: None,
798 });
799 assert!(config.validate().is_ok());
800 }
801
802 #[test]
803 fn structural_validation_defers_missing_route_credentials() {
804 let mut config = config_with(None, None);
805 config.aggregator.auth = None;
806 config.aggregator.api_key_env =
807 Some("NITPICKER_TEST_MISSING_AGGREGATOR_CREDENTIAL_FOR_FALLBACK_7C51".to_string());
808
809 assert!(config.validate_structure().is_ok());
810 let err = config.validate_credentials().unwrap_err();
811 assert!(format!("{err:#}").contains("env var"));
812 assert!(config.validate().is_err());
813 }
814
815 #[test]
820 fn required_env_var_branch_table_and_precedence() {
821 fn provider(name: &str) -> ProviderType {
822 match name {
823 "anthropic" => ProviderType::Anthropic,
824 "gemini" => ProviderType::Gemini,
825 "openai" => ProviderType::OpenAi,
826 "openrouter" => ProviderType::OpenRouter,
827 other => panic!("unknown provider in table: {other}"),
828 }
829 }
830
831 #[rustfmt::skip]
834 let rows = [
835 ("gemini", Some("agy-keyring"), None, None, None),
836 ("gemini", Some("agy-keyring"), None, Some("EXPLICIT"), None),
837 ("openai", Some("agy-keyring"), None, None, Some("OPENAI_API_KEY")),
839 ("openai", Some("azure-ad"), Some("https://f.example/v1"), Some("EXPLICIT"), None),
840 ("openai", Some("codex"), None, None, None),
841 ("openai", Some("codex"), None, Some("EXPLICIT"), None),
842 ("openai", Some("grok"), None, None, None),
843 ("openai", Some("grok"), None, Some("EXPLICIT"), None),
844 ("openai", None, Some("http://localhost:1234/v1"), Some("EXPLICIT"), None),
845 ("openai", None, Some("http://127.0.0.1:1234/v1"), None, None),
846 ("anthropic", None, Some("https://gw.example"), Some("EXPLICIT"), Some("EXPLICIT")),
848 ("anthropic", None, None, None, Some("ANTHROPIC_API_KEY")),
849 ("gemini", None, None, None, Some("GEMINI_API_KEY")),
850 ("openai", None, None, None, Some("OPENAI_API_KEY")),
851 ("openrouter", None, None, None, Some("OPENROUTER_API_KEY")),
852 ];
853
854 for (name, auth, base_url, api_key_env, expected) in rows {
855 let reviewer = ReviewerConfig {
856 name: String::new(),
857 model: String::new(),
858 provider: provider(name),
859 base_url: base_url.map(str::to_string),
860 api_key_env: api_key_env.map(str::to_string),
861 max_tokens: None,
862 compact_threshold: None,
863 auth: auth.map(str::to_string),
864 azure_scope: None,
865 azure_credentials: None,
866 };
867 let agg = AggregatorConfig {
868 model: String::new(),
869 provider: provider(name),
870 base_url: base_url.map(str::to_string),
871 api_key_env: api_key_env.map(str::to_string),
872 max_tokens: None,
873 auth: auth.map(str::to_string),
874 azure_scope: None,
875 azure_credentials: None,
876 };
877 for (role, settings) in [
878 ("reviewer", ClientSettings::from(&reviewer)),
879 ("aggregator", ClientSettings::from(&agg)),
880 ] {
881 assert_eq!(
882 required_env_var(settings),
883 expected,
884 "{role}: {name} auth={auth:?} base_url={base_url:?} api_key_env={api_key_env:?}"
885 );
886 }
887 }
888 }
889
890 #[test]
891 fn validate_auth_rejects_unknown_value_on_non_gemini() {
892 let typo = Some("azure_ad");
894 assert!(
895 validate_auth(
896 "[t]",
897 ClientSettings {
898 base_url: Some(FOUNDRY_URL),
899 ..client_settings(&ProviderType::OpenAi, typo)
900 },
901 )
902 .is_err()
903 );
904 assert!(validate_auth("[t]", client_settings(&ProviderType::Anthropic, typo),).is_err());
905 }
906
907 #[cfg(feature = "azure")]
908 #[test]
909 fn validate_auth_azure_ad_requires_base_url() {
910 let auth = Some("azure-ad");
911 assert!(validate_auth("[t]", client_settings(&ProviderType::OpenAi, auth),).is_err());
915 assert!(
916 validate_auth(
917 "[t]",
918 ClientSettings {
919 base_url: Some(""),
920 ..client_settings(&ProviderType::OpenAi, auth)
921 },
922 )
923 .is_err()
924 );
925 assert!(
926 validate_auth(
927 "[t]",
928 ClientSettings {
929 base_url: Some(FOUNDRY_URL),
930 azure_credentials: Some("auto"),
931 ..client_settings(&ProviderType::OpenAi, auth)
932 },
933 )
934 .is_ok()
935 );
936 }
937
938 #[test]
939 fn validate_azure_credentials_mode_rejects_unknown_only() {
940 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "dev").is_ok());
942 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "PROD").is_ok());
943 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "auto").is_ok());
944 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
946 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", " ").is_ok());
947 let err = validate_azure_credentials_mode("[t]", "AZURE_TOKEN_CREDENTIALS", "bogus")
950 .unwrap_err()
951 .to_string();
952 assert!(err.contains("AZURE_TOKEN_CREDENTIALS"), "got: {err}");
953 assert!(err.contains("bogus"), "got: {err}");
954 }
955
956 #[cfg(feature = "azure")]
957 #[test]
958 fn validate_auth_azure_ad_validates_credentials() {
959 let auth = Some("azure-ad");
960 let ok = |creds| {
961 validate_auth(
962 "[t]",
963 ClientSettings {
964 base_url: Some(FOUNDRY_URL),
965 azure_credentials: creds,
966 ..client_settings(&ProviderType::OpenAi, auth)
967 },
968 )
969 .is_ok()
970 };
971 assert!(ok(Some("auto")));
976 assert!(!ok(Some("deve")));
977 }
978
979 #[test]
983 fn preset_tables_reject_blank_and_padded_names_and_blank_prompts() {
984 let table = |name: &str, prompt: &str| {
985 let mut presets = BTreeMap::new();
986 presets.insert(
987 name.to_string(),
988 PresetConfig {
989 prompt: prompt.to_string(),
990 },
991 );
992 presets
993 };
994 assert!(validate_presets(None).is_ok());
995 assert!(validate_presets(Some(&table("tone", "review the docs"))).is_ok());
996 assert!(validate_presets(Some(&table(" tone", "review the docs"))).is_err());
997 assert!(validate_presets(Some(&table(" ", "review the docs"))).is_err());
998 assert!(validate_presets(Some(&table("tone", " "))).is_err());
999 }
1000
1001 #[test]
1004 fn preset_tables_reject_control_bytes_in_names() {
1005 let table = |name: &str| {
1006 let mut presets = BTreeMap::new();
1007 presets.insert(
1008 name.to_string(),
1009 PresetConfig {
1010 prompt: "review the docs".to_string(),
1011 },
1012 );
1013 presets
1014 };
1015 for name in [
1016 "esc\u{1b}]0;pwn\u{7}",
1017 "csi\u{9b}31m",
1018 "tab\tname",
1019 "nl\nname",
1020 ] {
1021 let err = validate_presets(Some(&table(name))).expect_err("control bytes rejected");
1022 assert!(
1023 format!("{err:#}").contains("control characters"),
1024 "wrong error for {name:?}: {err:#}"
1025 );
1026 }
1027 }
1028}