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, Copy, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "lowercase")]
270pub enum Trust {
271 Write,
273 Anyone,
275}
276
277impl std::fmt::Display for Trust {
278 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279 f.write_str(match self {
280 Trust::Write => "write",
281 Trust::Anyone => "anyone",
282 })
283 }
284}
285
286impl Trust {
287 pub fn may_act_on(self, association: &str) -> bool {
290 match self {
291 Trust::Anyone => true,
292 Trust::Write => matches!(
293 association.trim().to_uppercase().as_str(),
294 "OWNER" | "MEMBER" | "COLLABORATOR"
295 ),
296 }
297 }
298}
299
300#[derive(Debug, Clone, Default, Serialize, Deserialize)]
301#[serde(deny_unknown_fields)]
302pub struct EffortSchedule {
303 pub round_1: Option<String>,
305 pub rest: Option<String>,
307}
308
309#[derive(Debug, Clone, Serialize, Deserialize)]
313#[serde(default, deny_unknown_fields)]
314pub struct LoopCfg {
315 pub max_rounds: u32,
316 pub auto_merge: bool,
317 pub first_implementor: Option<String>,
318 pub base_branch: String,
319 pub worktrees: bool,
320 pub keep_worktrees: bool,
321 pub state_store: StateStore,
322 pub branch_prefix: String,
323 pub followups: Followups,
324 pub file_non_blocking: bool,
332 pub max_followups: usize,
335 pub file_nits: bool,
339 pub close_skipped: bool,
342 pub parallel_triage: bool,
345 pub min_number: i64,
353 pub absorb_new_issues: u32,
360 pub drafts: Drafts,
362 pub instructions: String,
374 pub max_issue_chars: usize,
382 pub max_triage_chars: usize,
390 pub checkin_trust: Trust,
392 pub checkin_resolve: bool,
397 pub max_checkin_comments: usize,
402 pub effort_schedule: EffortSchedule,
403}
404
405impl Default for LoopCfg {
406 fn default() -> Self {
407 Self {
408 max_rounds: 3,
409 auto_merge: false,
410 first_implementor: None,
411 base_branch: "main".into(),
412 worktrees: true,
413 keep_worktrees: false,
414 state_store: StateStore::Local,
415 branch_prefix: String::new(),
416 followups: Followups::Local,
417 file_non_blocking: false,
418 max_followups: 5,
419 file_nits: false,
420 close_skipped: true,
421 parallel_triage: true,
422 min_number: 0,
423 absorb_new_issues: 0,
424 drafts: Drafts::Never,
425 instructions: String::new(),
426 max_issue_chars: 60_000,
427 max_triage_chars: 200_000,
428 checkin_trust: Trust::Write,
429 checkin_resolve: true,
430 max_checkin_comments: 20,
431 effort_schedule: EffortSchedule::default(),
432 }
433 }
434}
435
436#[derive(Debug, Clone, Serialize, Deserialize)]
437#[serde(default, deny_unknown_fields)]
438pub struct StyleCfg {
439 pub ban_em_dash: bool,
440 pub ban_ai_attribution: bool,
441 pub terse: bool,
442 pub max_detail_chars: usize,
443 pub max_summary_chars: usize,
444 pub max_body_chars: usize,
445 pub max_issue_body_chars: usize,
449 pub max_title_chars: usize,
450 pub pr_comments: PrComments,
451}
452
453impl Default for StyleCfg {
454 fn default() -> Self {
464 let style = Style::default();
465 Self {
466 ban_em_dash: style.ban_em_dash,
467 ban_ai_attribution: style.ban_ai_attribution,
468 terse: style.terse,
469 max_detail_chars: style.max_detail_chars,
470 max_summary_chars: style.max_summary_chars,
471 max_body_chars: style.max_body_chars,
472 max_issue_body_chars: style.max_issue_body_chars,
473 max_title_chars: style.max_title_chars,
474 pr_comments: style.pr_comments,
475 }
476 }
477}
478
479impl StyleCfg {
480 pub fn to_style(&self) -> Style {
481 Style {
482 ban_em_dash: self.ban_em_dash,
483 ban_ai_attribution: self.ban_ai_attribution,
484 terse: self.terse,
485 max_detail_chars: self.max_detail_chars,
486 max_summary_chars: self.max_summary_chars,
487 max_body_chars: self.max_body_chars,
488 max_issue_body_chars: self.max_issue_body_chars,
489 max_title_chars: self.max_title_chars,
490 pr_comments: self.pr_comments,
491 }
492 }
493}
494
495#[derive(Debug, Clone)]
500pub struct Config {
501 pub agents: Vec<AgentSpec>,
503 pub loop_cfg: LoopCfg,
504 pub style: Style,
505 pub first_implementor: String,
507 pub source: Option<PathBuf>,
509}
510
511impl Config {
512 pub fn agent_names(&self) -> Vec<String> {
513 self.agents.iter().map(|a| a.name.clone()).collect()
514 }
515
516 pub fn has_agent(&self, name: &str) -> bool {
517 self.agents.iter().any(|a| a.name == name)
518 }
519
520 pub fn spec(&self, name: &str) -> Result<&AgentSpec> {
521 self.agents.iter().find(|a| a.name == name).ok_or_else(|| {
522 spar_err!(
523 "no agent named '{name}' ({})",
524 self.agent_names().join(", ")
525 )
526 })
527 }
528
529 pub fn other(&self, name: &str) -> String {
532 let names = self.agent_names();
533 if names.first().map(String::as_str) == Some(name) {
534 names.get(1).cloned().unwrap_or_else(|| name.to_string())
535 } else {
536 names.first().cloned().unwrap_or_else(|| name.to_string())
537 }
538 }
539
540 pub fn effort_for_round(&self, spec: &AgentSpec, round: u32) -> Option<String> {
543 let scheduled = if round <= 1 {
544 self.loop_cfg.effort_schedule.round_1.clone()
545 } else {
546 self.loop_cfg.effort_schedule.rest.clone()
547 };
548 scheduled
549 .filter(|s| !s.trim().is_empty())
550 .or_else(|| spec.effort.clone())
551 }
552
553 pub fn base_branch(&self) -> &str {
554 &self.loop_cfg.base_branch
555 }
556}
557
558#[derive(Debug, Deserialize)]
559#[serde(deny_unknown_fields)]
560struct RawConfig {
561 #[serde(default)]
562 agents: toml::Table,
563 #[serde(default)]
564 #[serde(rename = "loop")]
565 loop_cfg: Option<LoopCfg>,
566 #[serde(default)]
567 style: Option<StyleCfg>,
568}
569
570pub fn preset_dirs() -> Vec<PathBuf> {
583 let mut dirs = Vec::new();
584 if let Some(custom) = std::env::var_os("SPAR_PRESET_DIR") {
585 dirs.push(PathBuf::from(custom));
586 }
587 dirs.push(PathBuf::from(".spar").join("presets"));
588 if let Some(home) = home_dir() {
589 dirs.push(home.join(".config").join("spar").join("presets"));
590 }
591 dirs
592}
593
594pub fn available_presets() -> Vec<String> {
596 let mut names: Vec<String> = BUILTIN_PRESETS.iter().map(|(n, _)| n.to_string()).collect();
597 for dir in preset_dirs() {
598 if let Ok(entries) = std::fs::read_dir(&dir) {
599 for entry in entries.flatten() {
600 let path = entry.path();
601 if path.extension().and_then(|e| e.to_str()) == Some("toml") {
602 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
603 names.push(stem.to_string());
604 }
605 }
606 }
607 }
608 }
609 names.sort();
610 names.dedup();
611 names
612}
613
614fn parse_document(text: &str, what: &str) -> Result<Value> {
619 let table: toml::Table =
620 toml::from_str(text).map_err(|e| spar_err!("{what} is not valid TOML: {e}"))?;
621 Ok(Value::Table(table))
622}
623
624pub fn load_preset(name: &str) -> Result<Value> {
627 for dir in preset_dirs() {
628 let path = dir.join(format!("{name}.toml"));
629 if path.is_file() {
630 let text = std::fs::read_to_string(&path)
631 .map_err(|e| spar_err!("could not read preset {}: {e}", path.display()))?;
632 return parse_document(&text, &format!("preset {}", path.display()));
633 }
634 }
635 for (builtin, text) in BUILTIN_PRESETS {
636 if *builtin == name {
637 return parse_document(text, &format!("built in preset {name}"));
638 }
639 }
640 Err(spar_err!(
641 "unknown preset '{name}'. Available: {}",
642 available_presets().join(", ")
643 ))
644}
645
646fn merge(base: &Value, over: &Value) -> Value {
649 match (base, over) {
650 (Value::Table(b), Value::Table(o)) => {
651 let mut out = b.clone();
652 for (key, value) in o {
653 let merged = match out.get(key) {
654 Some(existing) => merge(existing, value),
655 None => value.clone(),
656 };
657 out.insert(key.clone(), merged);
658 }
659 Value::Table(out)
660 }
661 _ => over.clone(),
662 }
663}
664
665fn build_spec(name: &str, raw: &Value) -> Result<AgentSpec> {
666 let table = raw
667 .as_table()
668 .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
669
670 let merged = match table.get("preset").and_then(Value::as_str) {
671 Some(preset) => merge(&load_preset(preset)?, raw),
672 None => raw.clone(),
673 };
674
675 let mut merged_table = merged
676 .as_table()
677 .cloned()
678 .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
679 merged_table.remove("preset");
680 let fallback_raw = merged_table.remove("fallback");
683
684 if !merged_table.contains_key("command") {
685 bail!(
686 "agent '{name}' has no command and no preset. Set one of them, or pick a preset: {}",
687 available_presets().join(", ")
688 );
689 }
690
691 let mut spec: AgentSpec = Value::Table(merged_table)
692 .try_into()
693 .map_err(|e| spar_err!("agent '{name}': {e}"))?;
694 spec.name = name.to_string();
695
696 if spec.command.is_empty() {
697 bail!("agent '{name}' has an empty command");
698 }
699 if matches!(spec.command.first(), Some(CommandPart::Group(_))) {
700 bail!("agent '{name}': the first command element must be the program name, not a group");
701 }
702 if spec.output == OutputMode::Jsonl && spec.message_path.as_deref().unwrap_or("").is_empty() {
703 bail!(
704 "agent '{name}': output = \"jsonl\" needs a message_path saying where the answer lives"
705 );
706 }
707
708 if let Some(raw) = fallback_raw {
709 if !raw.is_table() {
710 bail!(
711 "agent '{name}': fallback is a whole agent, so write it as a table:\n [agents.{name}.fallback]\n preset = \"cursor\""
712 );
713 }
714 let backup = build_spec(&format!("{name}-fallback"), &raw)?;
717 if backup.fallback.is_some() {
718 bail!(
719 "agent '{name}': a fallback may not have a fallback of its own. Each one costs \
720 another full timeout on a call that has already failed once."
721 );
722 }
723 spec.fallback = Some(Box::new(backup));
724 }
725
726 Ok(spec)
727}
728
729#[derive(Debug, Clone)]
735pub struct OptionInfo {
736 pub section: &'static str,
737 pub key: String,
738 pub default: String,
739}
740
741pub fn known_options() -> Vec<OptionInfo> {
747 fn lines<T: Serialize>(section: &'static str, value: &T) -> Vec<OptionInfo> {
748 toml::to_string(value)
749 .unwrap_or_default()
750 .lines()
751 .filter_map(|line| line.split_once(" = "))
752 .map(|(key, default)| OptionInfo {
753 section,
754 key: key.trim().to_string(),
755 default: default.trim().to_string(),
756 })
757 .collect()
758 }
759 let mut out = lines("loop", &LoopCfg::default());
760 out.extend(lines("style", &StyleCfg::default()));
761 out.extend(lines(
762 "loop.effort_schedule",
763 &EffortSchedule {
764 round_1: Some("high".into()),
765 rest: Some("low".into()),
766 },
767 ));
768 out
769}
770
771pub fn mentions(config_text: &str, key: &str) -> bool {
773 config_text.lines().any(|line| {
774 let bare = line.trim_start().trim_start_matches('#').trim_start();
775 bare.starts_with(&format!("{key} ")) || bare.starts_with(&format!("{key}="))
776 })
777}
778
779pub fn unmentioned_options(config_text: &str) -> Vec<OptionInfo> {
782 known_options()
783 .into_iter()
784 .filter(|o| !mentions(config_text, &o.key))
785 .collect()
786}
787
788pub const CONFIG_NAMES: &[&str] = &["spar.toml", ".spar.toml"];
789
790pub fn find_config(explicit: Option<&Path>) -> Result<Option<PathBuf>> {
793 if let Some(path) = explicit {
794 if !path.is_file() {
795 bail!("config not found: {}", path.display());
796 }
797 return Ok(Some(path.to_path_buf()));
798 }
799 for name in CONFIG_NAMES {
800 let path = PathBuf::from(name);
801 if path.is_file() {
802 return Ok(Some(path));
803 }
804 }
805 if let Some(home) = home_dir() {
806 let path = home.join(".config").join("spar").join("spar.toml");
807 if path.is_file() {
808 return Ok(Some(path));
809 }
810 }
811 Ok(None)
812}
813
814pub fn load(explicit: Option<&Path>) -> Result<Config> {
815 let Some(path) = find_config(explicit)? else {
816 bail!(
817 "no spar.toml found. Run `spar init` to generate one from the CLIs you have installed."
818 );
819 };
820 let text = std::fs::read_to_string(&path)
821 .map_err(|e| spar_err!("could not read {}: {e}", path.display()))?;
822 let mut cfg = parse(&text).map_err(|e| spar_err!("{}: {e}", path.display()))?;
823 cfg.source = Some(path);
824 Ok(cfg)
825}
826
827pub fn parse(text: &str) -> Result<Config> {
828 let raw: RawConfig = toml::from_str(text)?;
829
830 if raw.agents.len() != 2 {
831 bail!(
832 "spar needs exactly two agents, found {}. The whole design is one reviewing the other.",
833 raw.agents.len()
834 );
835 }
836
837 let mut agents = Vec::new();
838 for (name, value) in raw.agents.iter() {
839 agents.push(build_spec(name, value)?);
840 }
841
842 let loop_cfg = raw.loop_cfg.unwrap_or_default();
843 let style = raw.style.unwrap_or_default().to_style();
844
845 if loop_cfg.max_rounds == 0 {
846 bail!("max_rounds must be at least 1");
847 }
848 if loop_cfg.auto_merge && loop_cfg.drafts == Drafts::Always {
853 bail!(
854 "auto_merge cannot be on with drafts = \"always\": merging a draft means marking it \
855 ready, which is what \"always\" asks spar not to do. Use drafts = \"until_approved\" \
856 to have it promoted when the review converges, or turn auto_merge off."
857 );
858 }
859
860 let first = match &loop_cfg.first_implementor {
861 Some(name) if !name.trim().is_empty() => name.trim().to_string(),
862 _ => agents[0].name.clone(),
863 };
864 if !agents.iter().any(|a| a.name == first) {
865 bail!(
866 "first_implementor '{first}' is not a configured agent ({})",
867 agents
868 .iter()
869 .map(|a| a.name.as_str())
870 .collect::<Vec<_>>()
871 .join(", ")
872 );
873 }
874
875 Ok(Config {
876 agents,
877 loop_cfg,
878 style,
879 first_implementor: first,
880 source: None,
881 })
882}
883
884pub fn resolve_search_path(raw: &str) -> PathBuf {
886 expand_tilde(raw)
887}
888
889#[cfg(test)]
890mod tests {
891 use super::*;
892
893 const TWO_AGENTS: &str = r#"
894[agents.claude]
895preset = "claude"
896model = "fable"
897
898[agents.codex]
899preset = "codex"
900model = "gpt-5.6-sol"
901"#;
902
903 #[test]
906 fn a_fallback_is_a_whole_agent_with_its_own_preset() {
907 let text = format!(
908 "{TWO_AGENTS}\n[agents.codex.fallback]\npreset = \"cursor\"\nmodel = \"kimi-k3\"\n"
909 );
910 let cfg = parse(&text).expect("parses");
911 assert_eq!(2, cfg.agents.len());
913 let codex = cfg.spec("codex").expect("codex");
914 let backup = codex.fallback.as_ref().expect("fallback");
915 assert_eq!("codex-fallback", backup.name);
916 assert_eq!(Some("kimi-k3"), backup.model.as_deref());
917 assert_eq!(
918 Some(&CommandPart::One("cursor-agent".into())),
919 backup.command.first()
920 );
921 }
922
923 #[test]
924 fn the_agent_without_a_fallback_does_not_grow_one() {
925 let cfg = parse(TWO_AGENTS).expect("parses");
926 assert!(cfg.agents.iter().all(|a| a.fallback.is_none()));
927 }
928
929 #[test]
930 fn a_fallback_may_not_have_one_of_its_own() {
931 let text = format!(
932 "{TWO_AGENTS}\n[agents.codex.fallback]\npreset = \"cursor\"\n\
933 [agents.codex.fallback.fallback]\npreset = \"gemini\"\n"
934 );
935 let err = parse(&text).expect_err("rejected");
936 assert!(err.message().contains("may not have a fallback"), "{err}");
937 }
938
939 #[test]
940 fn a_fallback_written_as_a_string_says_what_it_should_be() {
941 let text = "[agents.claude]\npreset = \"claude\"\n\n\
942 [agents.codex]\npreset = \"codex\"\nfallback = \"cursor\"\n";
943 let err = parse(text).expect_err("rejected");
944 assert!(err.message().contains("[agents.codex.fallback]"), "{err}");
945 }
946
947 #[test]
952 fn a_partial_block_keeps_the_defaults_it_did_not_name() {
953 let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 9\n\n[style]\nterse = false\n");
954 let cfg = parse(&text).expect("parses");
955
956 assert_eq!(9, cfg.loop_cfg.max_rounds);
957 assert_eq!(LoopCfg::default().followups, cfg.loop_cfg.followups);
958 assert_eq!(LoopCfg::default().close_skipped, cfg.loop_cfg.close_skipped);
959
960 assert!(!cfg.style.terse);
961 assert_eq!(Style::default().max_body_chars, cfg.style.max_body_chars);
962 assert_eq!(Style::default().max_title_chars, cfg.style.max_title_chars);
963 }
964
965 #[test]
969 fn the_config_layer_does_not_keep_its_own_copy_of_the_budgets() {
970 assert_eq!(Style::default(), StyleCfg::default().to_style());
971 }
972
973 #[test]
976 fn pull_requests_are_not_drafts_unless_asked_for() {
977 assert_eq!(Drafts::Never, parse(TWO_AGENTS).unwrap().loop_cfg.drafts);
978 }
979
980 #[test]
981 fn each_draft_setting_parses() {
982 for (text, want) in [
983 ("never", Drafts::Never),
984 ("until_approved", Drafts::UntilApproved),
985 ("always", Drafts::Always),
986 ] {
987 let cfg = parse(&format!("{TWO_AGENTS}\n[loop]\ndrafts = \"{text}\"\n"))
988 .unwrap_or_else(|e| panic!("{text}: {e}"));
989 assert_eq!(want, cfg.loop_cfg.drafts, "{text}");
990 }
991 }
992
993 #[test]
997 fn auto_merge_and_a_permanent_draft_are_refused_together() {
998 let text = format!("{TWO_AGENTS}\n[loop]\nauto_merge = true\ndrafts = \"always\"\n");
999 let err = parse(&text).expect_err("refused");
1000 assert!(err.message().contains("auto_merge"), "{err}");
1001 assert!(
1002 err.message().contains("until_approved"),
1003 "says the way out: {err}"
1004 );
1005 }
1006
1007 #[test]
1010 fn auto_merge_is_fine_with_a_draft_that_clears() {
1011 let text =
1012 format!("{TWO_AGENTS}\n[loop]\nauto_merge = true\ndrafts = \"until_approved\"\n");
1013 assert!(parse(&text).is_ok());
1014 }
1015
1016 #[test]
1017 fn every_builtin_preset_parses() {
1018 for (name, _) in BUILTIN_PRESETS {
1019 let value = load_preset(name).unwrap_or_else(|e| panic!("{name}: {e}"));
1020 assert!(value.get("command").is_some(), "{name} has no command");
1021 }
1022 }
1023
1024 #[test]
1025 fn every_builtin_preset_builds_a_spec() {
1026 for (name, _) in BUILTIN_PRESETS {
1027 let raw = parse_document(&format!("preset = \"{name}\""), "test").unwrap();
1028 build_spec(name, &raw).unwrap_or_else(|e| panic!("{name}: {e}"));
1029 }
1030 }
1031
1032 #[test]
1036 fn claude_preset_uses_the_equals_form_for_allowed_tools() {
1037 let spec = build_spec(
1038 "claude",
1039 &parse_document("preset = \"claude\"", "test").unwrap(),
1040 )
1041 .unwrap();
1042 let flat: Vec<&String> = spec.command.iter().flat_map(|p| p.args()).collect();
1043 assert!(flat.iter().any(|a| a.starts_with("--allowedTools=")));
1044 assert!(!flat.iter().any(|a| a.as_str() == "--allowedTools"));
1045 }
1046
1047 #[test]
1048 fn codex_preset_declares_where_its_answer_lives() {
1049 let spec = build_spec(
1050 "codex",
1051 &parse_document("preset = \"codex\"", "test").unwrap(),
1052 )
1053 .unwrap();
1054 assert_eq!(OutputMode::Jsonl, spec.output);
1055 assert_eq!(Some("item.text"), spec.message_path.as_deref());
1056 assert!(!spec.message_match.is_empty());
1057 }
1058
1059 #[test]
1060 fn agent_order_follows_declaration_order() {
1061 let cfg = parse(TWO_AGENTS).unwrap();
1062 assert_eq!(vec!["claude", "codex"], cfg.agent_names());
1063 assert_eq!("claude", cfg.first_implementor);
1064 }
1065
1066 #[test]
1067 fn other_alternates() {
1068 let cfg = parse(TWO_AGENTS).unwrap();
1069 assert_eq!("codex", cfg.other("claude"));
1070 assert_eq!("claude", cfg.other("codex"));
1071 }
1072
1073 #[test]
1074 fn a_config_block_overrides_one_preset_field() {
1075 let cfg = parse(TWO_AGENTS).unwrap();
1076 let claude = cfg.spec("claude").unwrap();
1077 assert_eq!(Some("fable"), claude.model.as_deref());
1078 assert!(claude.command.len() > 1, "the preset command survived");
1079 }
1080
1081 #[test]
1082 fn exactly_two_agents_are_required() {
1083 let one = "[agents.claude]\npreset = \"claude\"\n";
1084 assert!(parse(one).unwrap_err().to_string().contains("exactly two"));
1085 }
1086
1087 #[test]
1088 fn an_unknown_agent_option_is_named() {
1089 let text = "[agents.a]\ncommand = [\"x\"]\nwidget = 3\n[agents.b]\ncommand = [\"y\"]\n";
1090 let err = parse(text).unwrap_err().to_string();
1091 assert!(err.contains("widget"), "{err}");
1092 }
1093
1094 #[test]
1095 fn an_unknown_loop_option_is_named() {
1096 let text = format!("{TWO_AGENTS}\n[loop]\nmax_round = 4\n");
1097 let err = parse(&text).unwrap_err().to_string();
1098 assert!(err.contains("max_round"), "{err}");
1099 }
1100
1101 #[test]
1102 fn an_agent_with_no_command_and_no_preset_is_rejected() {
1103 let text = "[agents.a]\nmodel = \"x\"\n[agents.b]\ncommand = [\"y\"]\n";
1104 let err = parse(text).unwrap_err().to_string();
1105 assert!(err.contains("no command and no preset"), "{err}");
1106 }
1107
1108 #[test]
1109 fn jsonl_without_a_message_path_is_rejected() {
1110 let text =
1111 "[agents.a]\ncommand = [\"x\"]\noutput = \"jsonl\"\n[agents.b]\ncommand = [\"y\"]\n";
1112 let err = parse(text).unwrap_err().to_string();
1113 assert!(err.contains("message_path"), "{err}");
1114 }
1115
1116 #[test]
1117 fn first_implementor_must_name_a_configured_agent() {
1118 let text = format!("{TWO_AGENTS}\n[loop]\nfirst_implementor = \"nobody\"\n");
1119 let err = parse(&text).unwrap_err().to_string();
1120 assert!(err.contains("not a configured agent"), "{err}");
1121 }
1122
1123 #[test]
1124 fn defaults_are_the_conservative_ones() {
1125 let cfg = parse(TWO_AGENTS).unwrap();
1126 assert!(
1127 !cfg.loop_cfg.auto_merge,
1128 "auto_merge must be off by default"
1129 );
1130 assert!(cfg.loop_cfg.worktrees);
1131 assert!(
1132 !cfg.loop_cfg.file_nits,
1133 "a filed nit is somebody else's triage queue"
1134 );
1135 assert_eq!(3, cfg.loop_cfg.max_rounds);
1136 assert_eq!(
1137 Followups::Local,
1138 cfg.loop_cfg.followups,
1139 "the tracker is somebody's queue; the default must not write to it"
1140 );
1141 assert!(
1142 !cfg.loop_cfg.file_non_blocking,
1143 "a suggestion is not a tracker item"
1144 );
1145 assert_eq!(StateStore::Local, cfg.loop_cfg.state_store);
1146 assert!(cfg.style.terse);
1147 }
1148
1149 #[test]
1150 fn effort_schedule_splits_round_one_from_the_rest() {
1151 let text =
1152 format!("{TWO_AGENTS}\n[loop.effort_schedule]\nround_1 = \"ultra\"\nrest = \"high\"\n");
1153 let cfg = parse(&text).unwrap();
1154 let spec = cfg.spec("claude").unwrap();
1155 assert_eq!(Some("ultra".into()), cfg.effort_for_round(spec, 1));
1156 assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 2));
1157 assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 9));
1158 }
1159
1160 #[test]
1161 fn effort_falls_back_to_the_agents_own_setting() {
1162 let text = format!("{TWO_AGENTS}effort = \"low\"\n");
1163 let cfg = parse(&text).unwrap();
1164 let spec = cfg.spec("codex").unwrap();
1165 assert_eq!(Some("low".into()), cfg.effort_for_round(spec, 1));
1166 }
1167
1168 #[test]
1169 fn an_unset_model_and_an_empty_model_normalise_the_same() {
1170 let a = AgentSpec {
1171 name: "a".into(),
1172 command: vec![CommandPart::One("x".into())],
1173 model: None,
1174 effort: None,
1175 output: OutputMode::Text,
1176 message_match: BTreeMap::new(),
1177 message_path: None,
1178 search_paths: vec![],
1179 system_via: SystemVia::Prompt,
1180 timeout: 60,
1181 fallback: None,
1182 models: vec![],
1183 efforts: vec![],
1184 options_note: None,
1185 };
1186 let b = AgentSpec {
1187 model: Some(" ".into()),
1188 ..a.clone()
1189 };
1190 assert_eq!(a.model_key(), b.model_key());
1191 }
1192
1193 #[test]
1194 fn max_rounds_zero_is_rejected() {
1195 let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 0\n");
1196 assert!(parse(&text).is_err());
1197 }
1198
1199 #[test]
1200 fn an_inline_command_needs_no_preset() {
1201 let text = r#"
1202[agents.custom]
1203command = ["mytool", ["-m", "{model}"], "--prompt", "{prompt}"]
1204output = "text"
1205
1206[agents.other]
1207command = ["othertool", "{prompt}"]
1208"#;
1209 let cfg = parse(text).unwrap();
1210 assert_eq!(4, cfg.spec("custom").unwrap().command.len());
1211 }
1212
1213 #[test]
1214 fn style_budgets_are_configurable() {
1215 let text = format!("{TWO_AGENTS}\n[style]\nterse = false\nmax_detail_chars = 40\n");
1216 let cfg = parse(&text).unwrap();
1217 assert!(!cfg.style.terse);
1218 assert_eq!(40, cfg.style.max_detail_chars);
1219 }
1220}