Skip to main content

spar/
config.rs

1//! Configuration, and the agent presets that make a new CLI a data change
2//! rather than a code change.
3//!
4//! Presets are compiled into the binary. That is not an optimisation: a
5//! `cargo install`ed binary has no source tree beside it, so a preset read from
6//! a relative path would work for the author and fail for everyone else. Files
7//! on disk still win over the built in copies, so a preset can be overridden or
8//! a new one added without rebuilding.
9
10use 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
21/// Presets that ship inside the binary.
22pub 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    ("gemini", include_str!("../presets/gemini.toml")),
27];
28
29// ---------------------------------------------------------------------------
30// Agents
31// ---------------------------------------------------------------------------
32
33/// One element of a command template: a bare argument, or a group that is
34/// dropped whole when its placeholder is unset.
35#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
36#[serde(untagged)]
37pub enum CommandPart {
38    One(String),
39    Group(Vec<String>),
40}
41
42impl CommandPart {
43    pub fn args(&self) -> &[String] {
44        match self {
45            CommandPart::One(s) => std::slice::from_ref(s),
46            CommandPart::Group(v) => v,
47        }
48    }
49}
50
51/// How to read the answer out of what a CLI printed.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "lowercase")]
54pub enum OutputMode {
55    /// Everything on stdout is the answer.
56    Text,
57    /// Same as text; named separately because it reads better in a preset.
58    Json,
59    /// An event stream, one JSON object per line.
60    Jsonl,
61}
62
63/// Where the style rules go when a CLI has a system prompt flag.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "lowercase")]
66pub enum SystemVia {
67    /// Prepended to the prompt.
68    Prompt,
69    /// Passed through the `{system}` placeholder.
70    Placeholder,
71}
72
73fn default_timeout() -> u64 {
74    crate::proc::DEFAULT_TIMEOUT_SECS
75}
76
77fn default_output() -> OutputMode {
78    OutputMode::Text
79}
80
81fn default_system_via() -> SystemVia {
82    SystemVia::Prompt
83}
84
85/// Everything needed to drive one CLI. An agent is data, not a class:
86/// supporting a new tool is a preset file.
87#[derive(Debug, Clone, Serialize, Deserialize)]
88#[serde(deny_unknown_fields)]
89pub struct AgentSpec {
90    #[serde(skip)]
91    pub name: String,
92    pub command: Vec<CommandPart>,
93    #[serde(default)]
94    pub model: Option<String>,
95    #[serde(default)]
96    pub effort: Option<String>,
97    #[serde(default = "default_output")]
98    pub output: OutputMode,
99    /// For `jsonl`: the event fields that identify the agent's own message.
100    #[serde(default)]
101    pub message_match: BTreeMap<String, String>,
102    /// For `jsonl`: the dotted path to the text inside a matching event.
103    #[serde(default)]
104    pub message_path: Option<String>,
105    /// Extra places to look for the binary when it is not on PATH.
106    #[serde(default)]
107    pub search_paths: Vec<String>,
108    #[serde(default = "default_system_via")]
109    pub system_via: SystemVia,
110    #[serde(default = "default_timeout")]
111    pub timeout: u64,
112
113    // -- hints, inert at runtime -----------------------------------------
114    //
115    // Written into a generated config as comments so nobody has to guess what
116    // to put in `model` or `effort`. Deliberately never validated against: a
117    // CLI's options drift, and a stale allow list that refuses a model which
118    // actually works would be worse than no hint at all.
119    /// Model names this CLI is known to accept.
120    #[serde(default)]
121    pub models: Vec<String>,
122    /// Effort levels this CLI is known to accept.
123    #[serde(default)]
124    pub efforts: Vec<String>,
125    /// Where to check the current list, when spar cannot enumerate it.
126    #[serde(default)]
127    pub options_note: Option<String>,
128}
129
130impl AgentSpec {
131    /// The model as configured, normalised. An unset and an empty value both
132    /// mean "let the CLI pick", because `render` drops the flag either way.
133    pub fn model_key(&self) -> String {
134        self.model.as_deref().unwrap_or("").trim().to_string()
135    }
136
137    pub fn describe(&self) -> String {
138        format!(
139            "{}/{}",
140            self.model.as_deref().unwrap_or("default model"),
141            self.effort.as_deref().unwrap_or("default effort")
142        )
143    }
144}
145
146// ---------------------------------------------------------------------------
147// Loop and style blocks
148// ---------------------------------------------------------------------------
149
150/// Where an out of scope finding goes. On your own repository an issue is the
151/// right home. On a large repository that is not yours it is somebody else's
152/// notification and somebody else's triage queue.
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(rename_all = "lowercase")]
155pub enum Followups {
156    Issues,
157    Local,
158    None,
159}
160
161impl std::fmt::Display for Followups {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        f.write_str(match self {
164            Followups::Issues => "issues",
165            Followups::Local => "local",
166            Followups::None => "none",
167        })
168    }
169}
170
171/// How much of its own working spar narrates into a pull request thread.
172///
173/// The agents never read the PR: they receive findings through their prompts,
174/// so nothing in the loop depends on any of this being posted. It exists purely
175/// for the person who reads the thread later, which is why the default is the
176/// outcome rather than the play by play.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(rename_all = "lowercase")]
179pub enum PrComments {
180    /// One comment when the run finishes, and only if it has something to say.
181    Outcome,
182    /// A comment per review and per response, as it happens. An audit trail,
183    /// at the cost of a thread nobody wants to read.
184    Rounds,
185    /// Never comment on a pull request. Everything goes to the terminal.
186    None,
187}
188
189impl std::fmt::Display for PrComments {
190    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191        f.write_str(match self {
192            PrComments::Outcome => "outcome",
193            PrComments::Rounds => "rounds",
194            PrComments::None => "none",
195        })
196    }
197}
198
199/// Where resume state lives. Local keeps the PR clean and costs no API calls;
200/// writing to the PR only buys anything if a run might be resumed from a
201/// different checkout.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "lowercase")]
204pub enum StateStore {
205    Local,
206    Pr,
207    Both,
208}
209
210impl StateStore {
211    pub fn writes_local(self) -> bool {
212        matches!(self, StateStore::Local | StateStore::Both)
213    }
214    pub fn writes_pr(self) -> bool {
215        matches!(self, StateStore::Pr | StateStore::Both)
216    }
217}
218
219#[derive(Debug, Clone, Default, Serialize, Deserialize)]
220#[serde(deny_unknown_fields)]
221pub struct EffortSchedule {
222    /// The deep first review.
223    pub round_1: Option<String>,
224    /// Later rounds only see a small delta.
225    pub rest: Option<String>,
226}
227
228#[derive(Debug, Clone, Serialize, Deserialize)]
229#[serde(deny_unknown_fields)]
230pub struct LoopCfg {
231    #[serde(default = "three")]
232    pub max_rounds: u32,
233    #[serde(default)]
234    pub auto_merge: bool,
235    #[serde(default)]
236    pub first_implementor: Option<String>,
237    #[serde(default = "main_branch")]
238    pub base_branch: String,
239    #[serde(default = "yes")]
240    pub worktrees: bool,
241    #[serde(default)]
242    pub keep_worktrees: bool,
243    #[serde(default = "store_local")]
244    pub state_store: StateStore,
245    #[serde(default)]
246    pub branch_prefix: String,
247    #[serde(default = "followups_issues")]
248    pub followups: Followups,
249    /// Nits stay in the PR thread by default. A filed nit is somebody else's
250    /// notification: a run on a production codebase once opened an issue titled
251    /// "Log wording".
252    #[serde(default)]
253    pub file_nits: bool,
254    /// Close an issue that both agents independently declined, after posting
255    /// the shared reasoning. One agent's opinion is never enough.
256    #[serde(default = "yes")]
257    pub close_skipped: bool,
258    /// Ask both agents to triage at the same time. They only read during
259    /// triage, so there is nothing to serialise.
260    #[serde(default = "yes")]
261    pub parallel_triage: bool,
262    #[serde(default)]
263    pub effort_schedule: EffortSchedule,
264}
265
266fn three() -> u32 {
267    3
268}
269fn main_branch() -> String {
270    "main".to_string()
271}
272fn yes() -> bool {
273    true
274}
275fn store_local() -> StateStore {
276    StateStore::Local
277}
278fn followups_issues() -> Followups {
279    Followups::Issues
280}
281
282impl Default for LoopCfg {
283    fn default() -> Self {
284        Self {
285            max_rounds: 3,
286            auto_merge: false,
287            first_implementor: None,
288            base_branch: "main".into(),
289            worktrees: true,
290            keep_worktrees: false,
291            state_store: StateStore::Local,
292            branch_prefix: String::new(),
293            followups: Followups::Issues,
294            file_nits: false,
295            close_skipped: true,
296            parallel_triage: true,
297            effort_schedule: EffortSchedule::default(),
298        }
299    }
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize)]
303#[serde(deny_unknown_fields)]
304pub struct StyleCfg {
305    #[serde(default = "yes")]
306    pub ban_em_dash: bool,
307    #[serde(default = "yes")]
308    pub ban_ai_attribution: bool,
309    #[serde(default = "yes")]
310    pub terse: bool,
311    #[serde(default = "d320")]
312    pub max_detail_chars: usize,
313    #[serde(default = "d200")]
314    pub max_summary_chars: usize,
315    #[serde(default = "d900")]
316    pub max_body_chars: usize,
317    #[serde(default = "d90")]
318    pub max_title_chars: usize,
319    #[serde(default = "outcome_only")]
320    pub pr_comments: PrComments,
321}
322
323fn outcome_only() -> PrComments {
324    PrComments::Outcome
325}
326
327fn d320() -> usize {
328    320
329}
330fn d200() -> usize {
331    200
332}
333fn d900() -> usize {
334    900
335}
336fn d90() -> usize {
337    90
338}
339
340impl Default for StyleCfg {
341    fn default() -> Self {
342        Self {
343            ban_em_dash: true,
344            ban_ai_attribution: true,
345            terse: true,
346            max_detail_chars: 320,
347            max_summary_chars: 200,
348            max_body_chars: 900,
349            max_title_chars: 90,
350            pr_comments: PrComments::Outcome,
351        }
352    }
353}
354
355impl StyleCfg {
356    pub fn to_style(&self) -> Style {
357        Style {
358            ban_em_dash: self.ban_em_dash,
359            ban_ai_attribution: self.ban_ai_attribution,
360            terse: self.terse,
361            max_detail_chars: self.max_detail_chars,
362            max_summary_chars: self.max_summary_chars,
363            max_body_chars: self.max_body_chars,
364            max_title_chars: self.max_title_chars,
365            pr_comments: self.pr_comments,
366        }
367    }
368}
369
370// ---------------------------------------------------------------------------
371// The whole config
372// ---------------------------------------------------------------------------
373
374#[derive(Debug, Clone)]
375pub struct Config {
376    /// In declaration order, which is what `first_implementor` defaults to.
377    pub agents: Vec<AgentSpec>,
378    pub loop_cfg: LoopCfg,
379    pub style: Style,
380    /// Resolved: never empty, always one of the configured agents.
381    pub first_implementor: String,
382    /// Where this config was read from, for error messages.
383    pub source: Option<PathBuf>,
384}
385
386impl Config {
387    pub fn agent_names(&self) -> Vec<String> {
388        self.agents.iter().map(|a| a.name.clone()).collect()
389    }
390
391    pub fn has_agent(&self, name: &str) -> bool {
392        self.agents.iter().any(|a| a.name == name)
393    }
394
395    pub fn spec(&self, name: &str) -> Result<&AgentSpec> {
396        self.agents.iter().find(|a| a.name == name).ok_or_else(|| {
397            spar_err!(
398                "no agent named '{name}' ({})",
399                self.agent_names().join(", ")
400            )
401        })
402    }
403
404    /// The other agent. With exactly two configured, custody alternates by
405    /// definition.
406    pub fn other(&self, name: &str) -> String {
407        let names = self.agent_names();
408        if names.first().map(String::as_str) == Some(name) {
409            names.get(1).cloned().unwrap_or_else(|| name.to_string())
410        } else {
411            names.first().cloned().unwrap_or_else(|| name.to_string())
412        }
413    }
414
415    /// Round 1 gets the deep pass; later rounds only see a small delta, and a
416    /// full ultra review of a three line delta is money on fire.
417    pub fn effort_for_round(&self, spec: &AgentSpec, round: u32) -> Option<String> {
418        let scheduled = if round <= 1 {
419            self.loop_cfg.effort_schedule.round_1.clone()
420        } else {
421            self.loop_cfg.effort_schedule.rest.clone()
422        };
423        scheduled
424            .filter(|s| !s.trim().is_empty())
425            .or_else(|| spec.effort.clone())
426    }
427
428    pub fn base_branch(&self) -> &str {
429        &self.loop_cfg.base_branch
430    }
431}
432
433#[derive(Debug, Deserialize)]
434#[serde(deny_unknown_fields)]
435struct RawConfig {
436    #[serde(default)]
437    agents: toml::Table,
438    #[serde(default)]
439    #[serde(rename = "loop")]
440    loop_cfg: Option<LoopCfg>,
441    #[serde(default)]
442    style: Option<StyleCfg>,
443}
444
445// ---------------------------------------------------------------------------
446// Presets
447// ---------------------------------------------------------------------------
448
449/// Directories searched for preset overrides, nearest first.
450///
451/// Deliberately *not* a bare `presets/`. spar runs from inside the user's own
452/// repository, where `presets/` is a perfectly ordinary directory name for
453/// something unrelated (sampler configs, prompt libraries, editor themes), and
454/// a stray `presets/claude.toml` shadowing the built in preset produces a
455/// baffling failure: `spar init` reports Claude Code as missing while it sits
456/// on PATH. Overrides live somewhere that names spar.
457pub fn preset_dirs() -> Vec<PathBuf> {
458    let mut dirs = Vec::new();
459    if let Some(custom) = std::env::var_os("SPAR_PRESET_DIR") {
460        dirs.push(PathBuf::from(custom));
461    }
462    dirs.push(PathBuf::from(".spar").join("presets"));
463    if let Some(home) = home_dir() {
464        dirs.push(home.join(".config").join("spar").join("presets"));
465    }
466    dirs
467}
468
469/// Every preset name available, built in and on disk, sorted.
470pub fn available_presets() -> Vec<String> {
471    let mut names: Vec<String> = BUILTIN_PRESETS.iter().map(|(n, _)| n.to_string()).collect();
472    for dir in preset_dirs() {
473        if let Ok(entries) = std::fs::read_dir(&dir) {
474            for entry in entries.flatten() {
475                let path = entry.path();
476                if path.extension().and_then(|e| e.to_str()) == Some("toml") {
477                    if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
478                        names.push(stem.to_string());
479                    }
480                }
481            }
482        }
483    }
484    names.sort();
485    names.dedup();
486    names
487}
488
489/// Parse a whole TOML document into a `Value`.
490///
491/// `"...".parse::<Value>()` parses a single TOML *value*, not a document, so it
492/// rejects the first comment line of every preset.
493fn parse_document(text: &str, what: &str) -> Result<Value> {
494    let table: toml::Table =
495        toml::from_str(text).map_err(|e| spar_err!("{what} is not valid TOML: {e}"))?;
496    Ok(Value::Table(table))
497}
498
499/// Load a preset. A file on disk wins over the built in copy of the same name,
500/// so a drifting CLI can be corrected without waiting for a release.
501pub fn load_preset(name: &str) -> Result<Value> {
502    for dir in preset_dirs() {
503        let path = dir.join(format!("{name}.toml"));
504        if path.is_file() {
505            let text = std::fs::read_to_string(&path)
506                .map_err(|e| spar_err!("could not read preset {}: {e}", path.display()))?;
507            return parse_document(&text, &format!("preset {}", path.display()));
508        }
509    }
510    for (builtin, text) in BUILTIN_PRESETS {
511        if *builtin == name {
512            return parse_document(text, &format!("built in preset {name}"));
513        }
514    }
515    Err(spar_err!(
516        "unknown preset '{name}'. Available: {}",
517        available_presets().join(", ")
518    ))
519}
520
521/// Deep merge, with `over` winning. Used so a config block can override one
522/// field of a preset without restating the whole command template.
523fn merge(base: &Value, over: &Value) -> Value {
524    match (base, over) {
525        (Value::Table(b), Value::Table(o)) => {
526            let mut out = b.clone();
527            for (key, value) in o {
528                let merged = match out.get(key) {
529                    Some(existing) => merge(existing, value),
530                    None => value.clone(),
531                };
532                out.insert(key.clone(), merged);
533            }
534            Value::Table(out)
535        }
536        _ => over.clone(),
537    }
538}
539
540fn build_spec(name: &str, raw: &Value) -> Result<AgentSpec> {
541    let table = raw
542        .as_table()
543        .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
544
545    let merged = match table.get("preset").and_then(Value::as_str) {
546        Some(preset) => merge(&load_preset(preset)?, raw),
547        None => raw.clone(),
548    };
549
550    let mut merged_table = merged
551        .as_table()
552        .cloned()
553        .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
554    merged_table.remove("preset");
555
556    if !merged_table.contains_key("command") {
557        bail!(
558            "agent '{name}' has no command and no preset. Set one of them, or pick a preset: {}",
559            available_presets().join(", ")
560        );
561    }
562
563    let mut spec: AgentSpec = Value::Table(merged_table)
564        .try_into()
565        .map_err(|e| spar_err!("agent '{name}': {e}"))?;
566    spec.name = name.to_string();
567
568    if spec.command.is_empty() {
569        bail!("agent '{name}' has an empty command");
570    }
571    if matches!(spec.command.first(), Some(CommandPart::Group(_))) {
572        bail!("agent '{name}': the first command element must be the program name, not a group");
573    }
574    if spec.output == OutputMode::Jsonl && spec.message_path.as_deref().unwrap_or("").is_empty() {
575        bail!(
576            "agent '{name}': output = \"jsonl\" needs a message_path saying where the answer lives"
577        );
578    }
579    Ok(spec)
580}
581
582// ---------------------------------------------------------------------------
583// Loading
584// ---------------------------------------------------------------------------
585
586pub const CONFIG_NAMES: &[&str] = &["spar.toml", ".spar.toml"];
587
588/// Find a config: an explicit path, then the working directory, then
589/// `~/.config/spar/spar.toml`.
590pub fn find_config(explicit: Option<&Path>) -> Result<Option<PathBuf>> {
591    if let Some(path) = explicit {
592        if !path.is_file() {
593            bail!("config not found: {}", path.display());
594        }
595        return Ok(Some(path.to_path_buf()));
596    }
597    for name in CONFIG_NAMES {
598        let path = PathBuf::from(name);
599        if path.is_file() {
600            return Ok(Some(path));
601        }
602    }
603    if let Some(home) = home_dir() {
604        let path = home.join(".config").join("spar").join("spar.toml");
605        if path.is_file() {
606            return Ok(Some(path));
607        }
608    }
609    Ok(None)
610}
611
612pub fn load(explicit: Option<&Path>) -> Result<Config> {
613    let Some(path) = find_config(explicit)? else {
614        bail!(
615            "no spar.toml found. Run `spar init` to generate one from the CLIs you have installed."
616        );
617    };
618    let text = std::fs::read_to_string(&path)
619        .map_err(|e| spar_err!("could not read {}: {e}", path.display()))?;
620    let mut cfg = parse(&text).map_err(|e| spar_err!("{}: {e}", path.display()))?;
621    cfg.source = Some(path);
622    Ok(cfg)
623}
624
625pub fn parse(text: &str) -> Result<Config> {
626    let raw: RawConfig = toml::from_str(text)?;
627
628    if raw.agents.len() != 2 {
629        bail!(
630            "spar needs exactly two agents, found {}. The whole design is one reviewing the other.",
631            raw.agents.len()
632        );
633    }
634
635    let mut agents = Vec::new();
636    for (name, value) in raw.agents.iter() {
637        agents.push(build_spec(name, value)?);
638    }
639
640    let loop_cfg = raw.loop_cfg.unwrap_or_default();
641    let style = raw.style.unwrap_or_default().to_style();
642
643    if loop_cfg.max_rounds == 0 {
644        bail!("max_rounds must be at least 1");
645    }
646
647    let first = match &loop_cfg.first_implementor {
648        Some(name) if !name.trim().is_empty() => name.trim().to_string(),
649        _ => agents[0].name.clone(),
650    };
651    if !agents.iter().any(|a| a.name == first) {
652        bail!(
653            "first_implementor '{first}' is not a configured agent ({})",
654            agents
655                .iter()
656                .map(|a| a.name.as_str())
657                .collect::<Vec<_>>()
658                .join(", ")
659        );
660    }
661
662    Ok(Config {
663        agents,
664        loop_cfg,
665        style,
666        first_implementor: first,
667        source: None,
668    })
669}
670
671/// Resolve a configured search path, expanding a leading `~`.
672pub fn resolve_search_path(raw: &str) -> PathBuf {
673    expand_tilde(raw)
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679
680    const TWO_AGENTS: &str = r#"
681[agents.claude]
682preset = "claude"
683model = "fable"
684
685[agents.codex]
686preset = "codex"
687model = "gpt-5.6-sol"
688"#;
689
690    #[test]
691    fn every_builtin_preset_parses() {
692        for (name, _) in BUILTIN_PRESETS {
693            let value = load_preset(name).unwrap_or_else(|e| panic!("{name}: {e}"));
694            assert!(value.get("command").is_some(), "{name} has no command");
695        }
696    }
697
698    #[test]
699    fn every_builtin_preset_builds_a_spec() {
700        for (name, _) in BUILTIN_PRESETS {
701            let raw = parse_document(&format!("preset = \"{name}\""), "test").unwrap();
702            build_spec(name, &raw).unwrap_or_else(|e| panic!("{name}: {e}"));
703        }
704    }
705
706    /// `--allowedTools` is variadic, so the separate form swallows the
707    /// following positional prompt unless another flag happens to sit between
708    /// them. The equals form is not cosmetic.
709    #[test]
710    fn claude_preset_uses_the_equals_form_for_allowed_tools() {
711        let spec = build_spec(
712            "claude",
713            &parse_document("preset = \"claude\"", "test").unwrap(),
714        )
715        .unwrap();
716        let flat: Vec<&String> = spec.command.iter().flat_map(|p| p.args()).collect();
717        assert!(flat.iter().any(|a| a.starts_with("--allowedTools=")));
718        assert!(!flat.iter().any(|a| a.as_str() == "--allowedTools"));
719    }
720
721    #[test]
722    fn codex_preset_declares_where_its_answer_lives() {
723        let spec = build_spec(
724            "codex",
725            &parse_document("preset = \"codex\"", "test").unwrap(),
726        )
727        .unwrap();
728        assert_eq!(OutputMode::Jsonl, spec.output);
729        assert_eq!(Some("item.text"), spec.message_path.as_deref());
730        assert!(!spec.message_match.is_empty());
731    }
732
733    #[test]
734    fn agent_order_follows_declaration_order() {
735        let cfg = parse(TWO_AGENTS).unwrap();
736        assert_eq!(vec!["claude", "codex"], cfg.agent_names());
737        assert_eq!("claude", cfg.first_implementor);
738    }
739
740    #[test]
741    fn other_alternates() {
742        let cfg = parse(TWO_AGENTS).unwrap();
743        assert_eq!("codex", cfg.other("claude"));
744        assert_eq!("claude", cfg.other("codex"));
745    }
746
747    #[test]
748    fn a_config_block_overrides_one_preset_field() {
749        let cfg = parse(TWO_AGENTS).unwrap();
750        let claude = cfg.spec("claude").unwrap();
751        assert_eq!(Some("fable"), claude.model.as_deref());
752        assert!(claude.command.len() > 1, "the preset command survived");
753    }
754
755    #[test]
756    fn exactly_two_agents_are_required() {
757        let one = "[agents.claude]\npreset = \"claude\"\n";
758        assert!(parse(one).unwrap_err().to_string().contains("exactly two"));
759    }
760
761    #[test]
762    fn an_unknown_agent_option_is_named() {
763        let text = "[agents.a]\ncommand = [\"x\"]\nwidget = 3\n[agents.b]\ncommand = [\"y\"]\n";
764        let err = parse(text).unwrap_err().to_string();
765        assert!(err.contains("widget"), "{err}");
766    }
767
768    #[test]
769    fn an_unknown_loop_option_is_named() {
770        let text = format!("{TWO_AGENTS}\n[loop]\nmax_round = 4\n");
771        let err = parse(&text).unwrap_err().to_string();
772        assert!(err.contains("max_round"), "{err}");
773    }
774
775    #[test]
776    fn an_agent_with_no_command_and_no_preset_is_rejected() {
777        let text = "[agents.a]\nmodel = \"x\"\n[agents.b]\ncommand = [\"y\"]\n";
778        let err = parse(text).unwrap_err().to_string();
779        assert!(err.contains("no command and no preset"), "{err}");
780    }
781
782    #[test]
783    fn jsonl_without_a_message_path_is_rejected() {
784        let text =
785            "[agents.a]\ncommand = [\"x\"]\noutput = \"jsonl\"\n[agents.b]\ncommand = [\"y\"]\n";
786        let err = parse(text).unwrap_err().to_string();
787        assert!(err.contains("message_path"), "{err}");
788    }
789
790    #[test]
791    fn first_implementor_must_name_a_configured_agent() {
792        let text = format!("{TWO_AGENTS}\n[loop]\nfirst_implementor = \"nobody\"\n");
793        let err = parse(&text).unwrap_err().to_string();
794        assert!(err.contains("not a configured agent"), "{err}");
795    }
796
797    #[test]
798    fn defaults_are_the_conservative_ones() {
799        let cfg = parse(TWO_AGENTS).unwrap();
800        assert!(
801            !cfg.loop_cfg.auto_merge,
802            "auto_merge must be off by default"
803        );
804        assert!(cfg.loop_cfg.worktrees);
805        assert!(
806            !cfg.loop_cfg.file_nits,
807            "a filed nit is somebody else's triage queue"
808        );
809        assert_eq!(3, cfg.loop_cfg.max_rounds);
810        assert_eq!(Followups::Issues, cfg.loop_cfg.followups);
811        assert_eq!(StateStore::Local, cfg.loop_cfg.state_store);
812        assert!(cfg.style.terse);
813    }
814
815    #[test]
816    fn effort_schedule_splits_round_one_from_the_rest() {
817        let text =
818            format!("{TWO_AGENTS}\n[loop.effort_schedule]\nround_1 = \"ultra\"\nrest = \"high\"\n");
819        let cfg = parse(&text).unwrap();
820        let spec = cfg.spec("claude").unwrap();
821        assert_eq!(Some("ultra".into()), cfg.effort_for_round(spec, 1));
822        assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 2));
823        assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 9));
824    }
825
826    #[test]
827    fn effort_falls_back_to_the_agents_own_setting() {
828        let text = format!("{TWO_AGENTS}effort = \"low\"\n");
829        let cfg = parse(&text).unwrap();
830        let spec = cfg.spec("codex").unwrap();
831        assert_eq!(Some("low".into()), cfg.effort_for_round(spec, 1));
832    }
833
834    #[test]
835    fn an_unset_model_and_an_empty_model_normalise_the_same() {
836        let a = AgentSpec {
837            name: "a".into(),
838            command: vec![CommandPart::One("x".into())],
839            model: None,
840            effort: None,
841            output: OutputMode::Text,
842            message_match: BTreeMap::new(),
843            message_path: None,
844            search_paths: vec![],
845            system_via: SystemVia::Prompt,
846            timeout: 60,
847            models: vec![],
848            efforts: vec![],
849            options_note: None,
850        };
851        let b = AgentSpec {
852            model: Some("  ".into()),
853            ..a.clone()
854        };
855        assert_eq!(a.model_key(), b.model_key());
856    }
857
858    #[test]
859    fn max_rounds_zero_is_rejected() {
860        let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 0\n");
861        assert!(parse(&text).is_err());
862    }
863
864    #[test]
865    fn an_inline_command_needs_no_preset() {
866        let text = r#"
867[agents.custom]
868command = ["mytool", ["-m", "{model}"], "--prompt", "{prompt}"]
869output = "text"
870
871[agents.other]
872command = ["othertool", "{prompt}"]
873"#;
874        let cfg = parse(text).unwrap();
875        assert_eq!(4, cfg.spec("custom").unwrap().command.len());
876    }
877
878    #[test]
879    fn style_budgets_are_configurable() {
880        let text = format!("{TWO_AGENTS}\n[style]\nterse = false\nmax_detail_chars = 40\n");
881        let cfg = parse(&text).unwrap();
882        assert!(!cfg.style.terse);
883        assert_eq!(40, cfg.style.max_detail_chars);
884    }
885}