1use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12
13use serde::{Deserialize, Serialize};
14use toml::Value;
15
16use crate::error::Result;
17use crate::proc::{expand_tilde, home_dir};
18use crate::style::Style;
19use crate::{bail, spar_err};
20
21pub const BUILTIN_PRESETS: &[(&str, &str)] = &[
23 ("aider", include_str!("../presets/aider.toml")),
24 ("claude", include_str!("../presets/claude.toml")),
25 ("codex", include_str!("../presets/codex.toml")),
26 ("cursor", include_str!("../presets/cursor.toml")),
27 ("gemini", include_str!("../presets/gemini.toml")),
28];
29
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
37#[serde(untagged)]
38pub enum CommandPart {
39 One(String),
40 Group(Vec<String>),
41}
42
43impl CommandPart {
44 pub fn args(&self) -> &[String] {
45 match self {
46 CommandPart::One(s) => std::slice::from_ref(s),
47 CommandPart::Group(v) => v,
48 }
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "lowercase")]
55pub enum OutputMode {
56 Text,
58 Json,
60 Jsonl,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "lowercase")]
67pub enum SystemVia {
68 Prompt,
70 Placeholder,
72}
73
74fn default_timeout() -> u64 {
75 crate::proc::DEFAULT_TIMEOUT_SECS
76}
77
78fn default_output() -> OutputMode {
79 OutputMode::Text
80}
81
82fn default_system_via() -> SystemVia {
83 SystemVia::Prompt
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
89#[serde(deny_unknown_fields)]
90pub struct AgentSpec {
91 #[serde(skip)]
92 pub name: String,
93 pub command: Vec<CommandPart>,
94 #[serde(default)]
95 pub model: Option<String>,
96 #[serde(default)]
97 pub effort: Option<String>,
98 #[serde(default = "default_output")]
99 pub output: OutputMode,
100 #[serde(default)]
102 pub message_match: BTreeMap<String, String>,
103 #[serde(default)]
105 pub message_path: Option<String>,
106 #[serde(default)]
108 pub search_paths: Vec<String>,
109 #[serde(default = "default_system_via")]
110 pub system_via: SystemVia,
111 #[serde(default = "default_timeout")]
112 pub timeout: u64,
113 #[serde(skip)]
124 pub fallback: Option<Box<AgentSpec>>,
125
126 #[serde(default)]
134 pub models: Vec<String>,
135 #[serde(default)]
137 pub efforts: Vec<String>,
138 #[serde(default)]
140 pub options_note: Option<String>,
141}
142
143impl AgentSpec {
144 pub fn model_key(&self) -> String {
147 self.model.as_deref().unwrap_or("").trim().to_string()
148 }
149
150 pub fn describe(&self) -> String {
151 format!(
152 "{}/{}",
153 self.model.as_deref().unwrap_or("default model"),
154 self.effort.as_deref().unwrap_or("default effort")
155 )
156 }
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
167#[serde(rename_all = "lowercase")]
168pub enum Followups {
169 Issues,
170 Local,
171 None,
172}
173
174impl std::fmt::Display for Followups {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 f.write_str(match self {
177 Followups::Issues => "issues",
178 Followups::Local => "local",
179 Followups::None => "none",
180 })
181 }
182}
183
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "snake_case")]
194pub enum Drafts {
195 Never,
197 UntilApproved,
199 Always,
201}
202
203impl std::fmt::Display for Drafts {
204 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205 f.write_str(match self {
206 Drafts::Never => "never",
207 Drafts::UntilApproved => "until_approved",
208 Drafts::Always => "always",
209 })
210 }
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(rename_all = "lowercase")]
221pub enum PrComments {
222 Outcome,
224 Rounds,
227 None,
229}
230
231impl std::fmt::Display for PrComments {
232 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233 f.write_str(match self {
234 PrComments::Outcome => "outcome",
235 PrComments::Rounds => "rounds",
236 PrComments::None => "none",
237 })
238 }
239}
240
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
245#[serde(rename_all = "lowercase")]
246pub enum StateStore {
247 Local,
248 Pr,
249 Both,
250}
251
252impl StateStore {
253 pub fn writes_local(self) -> bool {
254 matches!(self, StateStore::Local | StateStore::Both)
255 }
256 pub fn writes_pr(self) -> bool {
257 matches!(self, StateStore::Pr | StateStore::Both)
258 }
259}
260
261#[derive(Debug, Clone, Default, Serialize, Deserialize)]
262#[serde(deny_unknown_fields)]
263pub struct EffortSchedule {
264 pub round_1: Option<String>,
266 pub rest: Option<String>,
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
274#[serde(default, deny_unknown_fields)]
275pub struct LoopCfg {
276 pub max_rounds: u32,
277 pub auto_merge: bool,
278 pub first_implementor: Option<String>,
279 pub base_branch: String,
280 pub worktrees: bool,
281 pub keep_worktrees: bool,
282 pub state_store: StateStore,
283 pub branch_prefix: String,
284 pub followups: Followups,
285 pub file_non_blocking: bool,
293 pub max_followups: usize,
296 pub file_nits: bool,
300 pub close_skipped: bool,
303 pub parallel_triage: bool,
306 pub min_number: i64,
314 pub absorb_new_issues: u32,
321 pub drafts: Drafts,
323 pub instructions: String,
335 pub max_issue_chars: usize,
343 pub max_triage_chars: usize,
351 pub effort_schedule: EffortSchedule,
352}
353
354impl Default for LoopCfg {
355 fn default() -> Self {
356 Self {
357 max_rounds: 3,
358 auto_merge: false,
359 first_implementor: None,
360 base_branch: "main".into(),
361 worktrees: true,
362 keep_worktrees: false,
363 state_store: StateStore::Local,
364 branch_prefix: String::new(),
365 followups: Followups::Local,
366 file_non_blocking: false,
367 max_followups: 5,
368 file_nits: false,
369 close_skipped: true,
370 parallel_triage: true,
371 min_number: 0,
372 absorb_new_issues: 0,
373 drafts: Drafts::Never,
374 instructions: String::new(),
375 max_issue_chars: 60_000,
376 max_triage_chars: 200_000,
377 effort_schedule: EffortSchedule::default(),
378 }
379 }
380}
381
382#[derive(Debug, Clone, Serialize, Deserialize)]
383#[serde(default, deny_unknown_fields)]
384pub struct StyleCfg {
385 pub ban_em_dash: bool,
386 pub ban_ai_attribution: bool,
387 pub terse: bool,
388 pub max_detail_chars: usize,
389 pub max_summary_chars: usize,
390 pub max_body_chars: usize,
391 pub max_issue_body_chars: usize,
395 pub max_title_chars: usize,
396 pub pr_comments: PrComments,
397}
398
399impl Default for StyleCfg {
400 fn default() -> Self {
410 let style = Style::default();
411 Self {
412 ban_em_dash: style.ban_em_dash,
413 ban_ai_attribution: style.ban_ai_attribution,
414 terse: style.terse,
415 max_detail_chars: style.max_detail_chars,
416 max_summary_chars: style.max_summary_chars,
417 max_body_chars: style.max_body_chars,
418 max_issue_body_chars: style.max_issue_body_chars,
419 max_title_chars: style.max_title_chars,
420 pr_comments: style.pr_comments,
421 }
422 }
423}
424
425impl StyleCfg {
426 pub fn to_style(&self) -> Style {
427 Style {
428 ban_em_dash: self.ban_em_dash,
429 ban_ai_attribution: self.ban_ai_attribution,
430 terse: self.terse,
431 max_detail_chars: self.max_detail_chars,
432 max_summary_chars: self.max_summary_chars,
433 max_body_chars: self.max_body_chars,
434 max_issue_body_chars: self.max_issue_body_chars,
435 max_title_chars: self.max_title_chars,
436 pr_comments: self.pr_comments,
437 }
438 }
439}
440
441#[derive(Debug, Clone)]
446pub struct Config {
447 pub agents: Vec<AgentSpec>,
449 pub loop_cfg: LoopCfg,
450 pub style: Style,
451 pub first_implementor: String,
453 pub source: Option<PathBuf>,
455}
456
457impl Config {
458 pub fn agent_names(&self) -> Vec<String> {
459 self.agents.iter().map(|a| a.name.clone()).collect()
460 }
461
462 pub fn has_agent(&self, name: &str) -> bool {
463 self.agents.iter().any(|a| a.name == name)
464 }
465
466 pub fn spec(&self, name: &str) -> Result<&AgentSpec> {
467 self.agents.iter().find(|a| a.name == name).ok_or_else(|| {
468 spar_err!(
469 "no agent named '{name}' ({})",
470 self.agent_names().join(", ")
471 )
472 })
473 }
474
475 pub fn other(&self, name: &str) -> String {
478 let names = self.agent_names();
479 if names.first().map(String::as_str) == Some(name) {
480 names.get(1).cloned().unwrap_or_else(|| name.to_string())
481 } else {
482 names.first().cloned().unwrap_or_else(|| name.to_string())
483 }
484 }
485
486 pub fn effort_for_round(&self, spec: &AgentSpec, round: u32) -> Option<String> {
489 let scheduled = if round <= 1 {
490 self.loop_cfg.effort_schedule.round_1.clone()
491 } else {
492 self.loop_cfg.effort_schedule.rest.clone()
493 };
494 scheduled
495 .filter(|s| !s.trim().is_empty())
496 .or_else(|| spec.effort.clone())
497 }
498
499 pub fn base_branch(&self) -> &str {
500 &self.loop_cfg.base_branch
501 }
502}
503
504#[derive(Debug, Deserialize)]
505#[serde(deny_unknown_fields)]
506struct RawConfig {
507 #[serde(default)]
508 agents: toml::Table,
509 #[serde(default)]
510 #[serde(rename = "loop")]
511 loop_cfg: Option<LoopCfg>,
512 #[serde(default)]
513 style: Option<StyleCfg>,
514}
515
516pub fn preset_dirs() -> Vec<PathBuf> {
529 let mut dirs = Vec::new();
530 if let Some(custom) = std::env::var_os("SPAR_PRESET_DIR") {
531 dirs.push(PathBuf::from(custom));
532 }
533 dirs.push(PathBuf::from(".spar").join("presets"));
534 if let Some(home) = home_dir() {
535 dirs.push(home.join(".config").join("spar").join("presets"));
536 }
537 dirs
538}
539
540pub fn available_presets() -> Vec<String> {
542 let mut names: Vec<String> = BUILTIN_PRESETS.iter().map(|(n, _)| n.to_string()).collect();
543 for dir in preset_dirs() {
544 if let Ok(entries) = std::fs::read_dir(&dir) {
545 for entry in entries.flatten() {
546 let path = entry.path();
547 if path.extension().and_then(|e| e.to_str()) == Some("toml") {
548 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
549 names.push(stem.to_string());
550 }
551 }
552 }
553 }
554 }
555 names.sort();
556 names.dedup();
557 names
558}
559
560fn parse_document(text: &str, what: &str) -> Result<Value> {
565 let table: toml::Table =
566 toml::from_str(text).map_err(|e| spar_err!("{what} is not valid TOML: {e}"))?;
567 Ok(Value::Table(table))
568}
569
570pub fn load_preset(name: &str) -> Result<Value> {
573 for dir in preset_dirs() {
574 let path = dir.join(format!("{name}.toml"));
575 if path.is_file() {
576 let text = std::fs::read_to_string(&path)
577 .map_err(|e| spar_err!("could not read preset {}: {e}", path.display()))?;
578 return parse_document(&text, &format!("preset {}", path.display()));
579 }
580 }
581 for (builtin, text) in BUILTIN_PRESETS {
582 if *builtin == name {
583 return parse_document(text, &format!("built in preset {name}"));
584 }
585 }
586 Err(spar_err!(
587 "unknown preset '{name}'. Available: {}",
588 available_presets().join(", ")
589 ))
590}
591
592fn merge(base: &Value, over: &Value) -> Value {
595 match (base, over) {
596 (Value::Table(b), Value::Table(o)) => {
597 let mut out = b.clone();
598 for (key, value) in o {
599 let merged = match out.get(key) {
600 Some(existing) => merge(existing, value),
601 None => value.clone(),
602 };
603 out.insert(key.clone(), merged);
604 }
605 Value::Table(out)
606 }
607 _ => over.clone(),
608 }
609}
610
611fn build_spec(name: &str, raw: &Value) -> Result<AgentSpec> {
612 let table = raw
613 .as_table()
614 .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
615
616 let merged = match table.get("preset").and_then(Value::as_str) {
617 Some(preset) => merge(&load_preset(preset)?, raw),
618 None => raw.clone(),
619 };
620
621 let mut merged_table = merged
622 .as_table()
623 .cloned()
624 .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
625 merged_table.remove("preset");
626 let fallback_raw = merged_table.remove("fallback");
629
630 if !merged_table.contains_key("command") {
631 bail!(
632 "agent '{name}' has no command and no preset. Set one of them, or pick a preset: {}",
633 available_presets().join(", ")
634 );
635 }
636
637 let mut spec: AgentSpec = Value::Table(merged_table)
638 .try_into()
639 .map_err(|e| spar_err!("agent '{name}': {e}"))?;
640 spec.name = name.to_string();
641
642 if spec.command.is_empty() {
643 bail!("agent '{name}' has an empty command");
644 }
645 if matches!(spec.command.first(), Some(CommandPart::Group(_))) {
646 bail!("agent '{name}': the first command element must be the program name, not a group");
647 }
648 if spec.output == OutputMode::Jsonl && spec.message_path.as_deref().unwrap_or("").is_empty() {
649 bail!(
650 "agent '{name}': output = \"jsonl\" needs a message_path saying where the answer lives"
651 );
652 }
653
654 if let Some(raw) = fallback_raw {
655 if !raw.is_table() {
656 bail!(
657 "agent '{name}': fallback is a whole agent, so write it as a table:\n [agents.{name}.fallback]\n preset = \"cursor\""
658 );
659 }
660 let backup = build_spec(&format!("{name}-fallback"), &raw)?;
663 if backup.fallback.is_some() {
664 bail!(
665 "agent '{name}': a fallback may not have a fallback of its own. Each one costs \
666 another full timeout on a call that has already failed once."
667 );
668 }
669 spec.fallback = Some(Box::new(backup));
670 }
671
672 Ok(spec)
673}
674
675#[derive(Debug, Clone)]
681pub struct OptionInfo {
682 pub section: &'static str,
683 pub key: String,
684 pub default: String,
685}
686
687pub fn known_options() -> Vec<OptionInfo> {
693 fn lines<T: Serialize>(section: &'static str, value: &T) -> Vec<OptionInfo> {
694 toml::to_string(value)
695 .unwrap_or_default()
696 .lines()
697 .filter_map(|line| line.split_once(" = "))
698 .map(|(key, default)| OptionInfo {
699 section,
700 key: key.trim().to_string(),
701 default: default.trim().to_string(),
702 })
703 .collect()
704 }
705 let mut out = lines("loop", &LoopCfg::default());
706 out.extend(lines("style", &StyleCfg::default()));
707 out.extend(lines(
708 "loop.effort_schedule",
709 &EffortSchedule {
710 round_1: Some("high".into()),
711 rest: Some("low".into()),
712 },
713 ));
714 out
715}
716
717pub fn mentions(config_text: &str, key: &str) -> bool {
719 config_text.lines().any(|line| {
720 let bare = line.trim_start().trim_start_matches('#').trim_start();
721 bare.starts_with(&format!("{key} ")) || bare.starts_with(&format!("{key}="))
722 })
723}
724
725pub fn unmentioned_options(config_text: &str) -> Vec<OptionInfo> {
728 known_options()
729 .into_iter()
730 .filter(|o| !mentions(config_text, &o.key))
731 .collect()
732}
733
734pub const CONFIG_NAMES: &[&str] = &["spar.toml", ".spar.toml"];
735
736pub fn find_config(explicit: Option<&Path>) -> Result<Option<PathBuf>> {
739 if let Some(path) = explicit {
740 if !path.is_file() {
741 bail!("config not found: {}", path.display());
742 }
743 return Ok(Some(path.to_path_buf()));
744 }
745 for name in CONFIG_NAMES {
746 let path = PathBuf::from(name);
747 if path.is_file() {
748 return Ok(Some(path));
749 }
750 }
751 if let Some(home) = home_dir() {
752 let path = home.join(".config").join("spar").join("spar.toml");
753 if path.is_file() {
754 return Ok(Some(path));
755 }
756 }
757 Ok(None)
758}
759
760pub fn load(explicit: Option<&Path>) -> Result<Config> {
761 let Some(path) = find_config(explicit)? else {
762 bail!(
763 "no spar.toml found. Run `spar init` to generate one from the CLIs you have installed."
764 );
765 };
766 let text = std::fs::read_to_string(&path)
767 .map_err(|e| spar_err!("could not read {}: {e}", path.display()))?;
768 let mut cfg = parse(&text).map_err(|e| spar_err!("{}: {e}", path.display()))?;
769 cfg.source = Some(path);
770 Ok(cfg)
771}
772
773pub fn parse(text: &str) -> Result<Config> {
774 let raw: RawConfig = toml::from_str(text)?;
775
776 if raw.agents.len() != 2 {
777 bail!(
778 "spar needs exactly two agents, found {}. The whole design is one reviewing the other.",
779 raw.agents.len()
780 );
781 }
782
783 let mut agents = Vec::new();
784 for (name, value) in raw.agents.iter() {
785 agents.push(build_spec(name, value)?);
786 }
787
788 let loop_cfg = raw.loop_cfg.unwrap_or_default();
789 let style = raw.style.unwrap_or_default().to_style();
790
791 if loop_cfg.max_rounds == 0 {
792 bail!("max_rounds must be at least 1");
793 }
794 if loop_cfg.auto_merge && loop_cfg.drafts == Drafts::Always {
799 bail!(
800 "auto_merge cannot be on with drafts = \"always\": merging a draft means marking it \
801 ready, which is what \"always\" asks spar not to do. Use drafts = \"until_approved\" \
802 to have it promoted when the review converges, or turn auto_merge off."
803 );
804 }
805
806 let first = match &loop_cfg.first_implementor {
807 Some(name) if !name.trim().is_empty() => name.trim().to_string(),
808 _ => agents[0].name.clone(),
809 };
810 if !agents.iter().any(|a| a.name == first) {
811 bail!(
812 "first_implementor '{first}' is not a configured agent ({})",
813 agents
814 .iter()
815 .map(|a| a.name.as_str())
816 .collect::<Vec<_>>()
817 .join(", ")
818 );
819 }
820
821 Ok(Config {
822 agents,
823 loop_cfg,
824 style,
825 first_implementor: first,
826 source: None,
827 })
828}
829
830pub fn resolve_search_path(raw: &str) -> PathBuf {
832 expand_tilde(raw)
833}
834
835#[cfg(test)]
836mod tests {
837 use super::*;
838
839 const TWO_AGENTS: &str = r#"
840[agents.claude]
841preset = "claude"
842model = "fable"
843
844[agents.codex]
845preset = "codex"
846model = "gpt-5.6-sol"
847"#;
848
849 #[test]
852 fn a_fallback_is_a_whole_agent_with_its_own_preset() {
853 let text = format!(
854 "{TWO_AGENTS}\n[agents.codex.fallback]\npreset = \"cursor\"\nmodel = \"kimi-k3\"\n"
855 );
856 let cfg = parse(&text).expect("parses");
857 assert_eq!(2, cfg.agents.len());
859 let codex = cfg.spec("codex").expect("codex");
860 let backup = codex.fallback.as_ref().expect("fallback");
861 assert_eq!("codex-fallback", backup.name);
862 assert_eq!(Some("kimi-k3"), backup.model.as_deref());
863 assert_eq!(
864 Some(&CommandPart::One("cursor-agent".into())),
865 backup.command.first()
866 );
867 }
868
869 #[test]
870 fn the_agent_without_a_fallback_does_not_grow_one() {
871 let cfg = parse(TWO_AGENTS).expect("parses");
872 assert!(cfg.agents.iter().all(|a| a.fallback.is_none()));
873 }
874
875 #[test]
876 fn a_fallback_may_not_have_one_of_its_own() {
877 let text = format!(
878 "{TWO_AGENTS}\n[agents.codex.fallback]\npreset = \"cursor\"\n\
879 [agents.codex.fallback.fallback]\npreset = \"gemini\"\n"
880 );
881 let err = parse(&text).expect_err("rejected");
882 assert!(err.message().contains("may not have a fallback"), "{err}");
883 }
884
885 #[test]
886 fn a_fallback_written_as_a_string_says_what_it_should_be() {
887 let text = "[agents.claude]\npreset = \"claude\"\n\n\
888 [agents.codex]\npreset = \"codex\"\nfallback = \"cursor\"\n";
889 let err = parse(text).expect_err("rejected");
890 assert!(err.message().contains("[agents.codex.fallback]"), "{err}");
891 }
892
893 #[test]
898 fn a_partial_block_keeps_the_defaults_it_did_not_name() {
899 let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 9\n\n[style]\nterse = false\n");
900 let cfg = parse(&text).expect("parses");
901
902 assert_eq!(9, cfg.loop_cfg.max_rounds);
903 assert_eq!(LoopCfg::default().followups, cfg.loop_cfg.followups);
904 assert_eq!(LoopCfg::default().close_skipped, cfg.loop_cfg.close_skipped);
905
906 assert!(!cfg.style.terse);
907 assert_eq!(Style::default().max_body_chars, cfg.style.max_body_chars);
908 assert_eq!(Style::default().max_title_chars, cfg.style.max_title_chars);
909 }
910
911 #[test]
915 fn the_config_layer_does_not_keep_its_own_copy_of_the_budgets() {
916 assert_eq!(Style::default(), StyleCfg::default().to_style());
917 }
918
919 #[test]
922 fn pull_requests_are_not_drafts_unless_asked_for() {
923 assert_eq!(Drafts::Never, parse(TWO_AGENTS).unwrap().loop_cfg.drafts);
924 }
925
926 #[test]
927 fn each_draft_setting_parses() {
928 for (text, want) in [
929 ("never", Drafts::Never),
930 ("until_approved", Drafts::UntilApproved),
931 ("always", Drafts::Always),
932 ] {
933 let cfg = parse(&format!("{TWO_AGENTS}\n[loop]\ndrafts = \"{text}\"\n"))
934 .unwrap_or_else(|e| panic!("{text}: {e}"));
935 assert_eq!(want, cfg.loop_cfg.drafts, "{text}");
936 }
937 }
938
939 #[test]
943 fn auto_merge_and_a_permanent_draft_are_refused_together() {
944 let text = format!("{TWO_AGENTS}\n[loop]\nauto_merge = true\ndrafts = \"always\"\n");
945 let err = parse(&text).expect_err("refused");
946 assert!(err.message().contains("auto_merge"), "{err}");
947 assert!(
948 err.message().contains("until_approved"),
949 "says the way out: {err}"
950 );
951 }
952
953 #[test]
956 fn auto_merge_is_fine_with_a_draft_that_clears() {
957 let text =
958 format!("{TWO_AGENTS}\n[loop]\nauto_merge = true\ndrafts = \"until_approved\"\n");
959 assert!(parse(&text).is_ok());
960 }
961
962 #[test]
963 fn every_builtin_preset_parses() {
964 for (name, _) in BUILTIN_PRESETS {
965 let value = load_preset(name).unwrap_or_else(|e| panic!("{name}: {e}"));
966 assert!(value.get("command").is_some(), "{name} has no command");
967 }
968 }
969
970 #[test]
971 fn every_builtin_preset_builds_a_spec() {
972 for (name, _) in BUILTIN_PRESETS {
973 let raw = parse_document(&format!("preset = \"{name}\""), "test").unwrap();
974 build_spec(name, &raw).unwrap_or_else(|e| panic!("{name}: {e}"));
975 }
976 }
977
978 #[test]
982 fn claude_preset_uses_the_equals_form_for_allowed_tools() {
983 let spec = build_spec(
984 "claude",
985 &parse_document("preset = \"claude\"", "test").unwrap(),
986 )
987 .unwrap();
988 let flat: Vec<&String> = spec.command.iter().flat_map(|p| p.args()).collect();
989 assert!(flat.iter().any(|a| a.starts_with("--allowedTools=")));
990 assert!(!flat.iter().any(|a| a.as_str() == "--allowedTools"));
991 }
992
993 #[test]
994 fn codex_preset_declares_where_its_answer_lives() {
995 let spec = build_spec(
996 "codex",
997 &parse_document("preset = \"codex\"", "test").unwrap(),
998 )
999 .unwrap();
1000 assert_eq!(OutputMode::Jsonl, spec.output);
1001 assert_eq!(Some("item.text"), spec.message_path.as_deref());
1002 assert!(!spec.message_match.is_empty());
1003 }
1004
1005 #[test]
1006 fn agent_order_follows_declaration_order() {
1007 let cfg = parse(TWO_AGENTS).unwrap();
1008 assert_eq!(vec!["claude", "codex"], cfg.agent_names());
1009 assert_eq!("claude", cfg.first_implementor);
1010 }
1011
1012 #[test]
1013 fn other_alternates() {
1014 let cfg = parse(TWO_AGENTS).unwrap();
1015 assert_eq!("codex", cfg.other("claude"));
1016 assert_eq!("claude", cfg.other("codex"));
1017 }
1018
1019 #[test]
1020 fn a_config_block_overrides_one_preset_field() {
1021 let cfg = parse(TWO_AGENTS).unwrap();
1022 let claude = cfg.spec("claude").unwrap();
1023 assert_eq!(Some("fable"), claude.model.as_deref());
1024 assert!(claude.command.len() > 1, "the preset command survived");
1025 }
1026
1027 #[test]
1028 fn exactly_two_agents_are_required() {
1029 let one = "[agents.claude]\npreset = \"claude\"\n";
1030 assert!(parse(one).unwrap_err().to_string().contains("exactly two"));
1031 }
1032
1033 #[test]
1034 fn an_unknown_agent_option_is_named() {
1035 let text = "[agents.a]\ncommand = [\"x\"]\nwidget = 3\n[agents.b]\ncommand = [\"y\"]\n";
1036 let err = parse(text).unwrap_err().to_string();
1037 assert!(err.contains("widget"), "{err}");
1038 }
1039
1040 #[test]
1041 fn an_unknown_loop_option_is_named() {
1042 let text = format!("{TWO_AGENTS}\n[loop]\nmax_round = 4\n");
1043 let err = parse(&text).unwrap_err().to_string();
1044 assert!(err.contains("max_round"), "{err}");
1045 }
1046
1047 #[test]
1048 fn an_agent_with_no_command_and_no_preset_is_rejected() {
1049 let text = "[agents.a]\nmodel = \"x\"\n[agents.b]\ncommand = [\"y\"]\n";
1050 let err = parse(text).unwrap_err().to_string();
1051 assert!(err.contains("no command and no preset"), "{err}");
1052 }
1053
1054 #[test]
1055 fn jsonl_without_a_message_path_is_rejected() {
1056 let text =
1057 "[agents.a]\ncommand = [\"x\"]\noutput = \"jsonl\"\n[agents.b]\ncommand = [\"y\"]\n";
1058 let err = parse(text).unwrap_err().to_string();
1059 assert!(err.contains("message_path"), "{err}");
1060 }
1061
1062 #[test]
1063 fn first_implementor_must_name_a_configured_agent() {
1064 let text = format!("{TWO_AGENTS}\n[loop]\nfirst_implementor = \"nobody\"\n");
1065 let err = parse(&text).unwrap_err().to_string();
1066 assert!(err.contains("not a configured agent"), "{err}");
1067 }
1068
1069 #[test]
1070 fn defaults_are_the_conservative_ones() {
1071 let cfg = parse(TWO_AGENTS).unwrap();
1072 assert!(
1073 !cfg.loop_cfg.auto_merge,
1074 "auto_merge must be off by default"
1075 );
1076 assert!(cfg.loop_cfg.worktrees);
1077 assert!(
1078 !cfg.loop_cfg.file_nits,
1079 "a filed nit is somebody else's triage queue"
1080 );
1081 assert_eq!(3, cfg.loop_cfg.max_rounds);
1082 assert_eq!(
1083 Followups::Local,
1084 cfg.loop_cfg.followups,
1085 "the tracker is somebody's queue; the default must not write to it"
1086 );
1087 assert!(
1088 !cfg.loop_cfg.file_non_blocking,
1089 "a suggestion is not a tracker item"
1090 );
1091 assert_eq!(StateStore::Local, cfg.loop_cfg.state_store);
1092 assert!(cfg.style.terse);
1093 }
1094
1095 #[test]
1096 fn effort_schedule_splits_round_one_from_the_rest() {
1097 let text =
1098 format!("{TWO_AGENTS}\n[loop.effort_schedule]\nround_1 = \"ultra\"\nrest = \"high\"\n");
1099 let cfg = parse(&text).unwrap();
1100 let spec = cfg.spec("claude").unwrap();
1101 assert_eq!(Some("ultra".into()), cfg.effort_for_round(spec, 1));
1102 assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 2));
1103 assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 9));
1104 }
1105
1106 #[test]
1107 fn effort_falls_back_to_the_agents_own_setting() {
1108 let text = format!("{TWO_AGENTS}effort = \"low\"\n");
1109 let cfg = parse(&text).unwrap();
1110 let spec = cfg.spec("codex").unwrap();
1111 assert_eq!(Some("low".into()), cfg.effort_for_round(spec, 1));
1112 }
1113
1114 #[test]
1115 fn an_unset_model_and_an_empty_model_normalise_the_same() {
1116 let a = AgentSpec {
1117 name: "a".into(),
1118 command: vec![CommandPart::One("x".into())],
1119 model: None,
1120 effort: None,
1121 output: OutputMode::Text,
1122 message_match: BTreeMap::new(),
1123 message_path: None,
1124 search_paths: vec![],
1125 system_via: SystemVia::Prompt,
1126 timeout: 60,
1127 fallback: None,
1128 models: vec![],
1129 efforts: vec![],
1130 options_note: None,
1131 };
1132 let b = AgentSpec {
1133 model: Some(" ".into()),
1134 ..a.clone()
1135 };
1136 assert_eq!(a.model_key(), b.model_key());
1137 }
1138
1139 #[test]
1140 fn max_rounds_zero_is_rejected() {
1141 let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 0\n");
1142 assert!(parse(&text).is_err());
1143 }
1144
1145 #[test]
1146 fn an_inline_command_needs_no_preset() {
1147 let text = r#"
1148[agents.custom]
1149command = ["mytool", ["-m", "{model}"], "--prompt", "{prompt}"]
1150output = "text"
1151
1152[agents.other]
1153command = ["othertool", "{prompt}"]
1154"#;
1155 let cfg = parse(text).unwrap();
1156 assert_eq!(4, cfg.spec("custom").unwrap().command.len());
1157 }
1158
1159 #[test]
1160 fn style_budgets_are_configurable() {
1161 let text = format!("{TWO_AGENTS}\n[style]\nterse = false\nmax_detail_chars = 40\n");
1162 let cfg = parse(&text).unwrap();
1163 assert!(!cfg.style.terse);
1164 assert_eq!(40, cfg.style.max_detail_chars);
1165 }
1166}