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    /// Ignore issues and pull requests numbered below this when spar is picking
263    /// for itself. 0 is no floor.
264    ///
265    /// A repository that has been going a while carries a tail of old issues
266    /// nobody is going to reach, and since spar takes the lowest numbered open
267    /// items it walks straight into them. A number you name explicitly is still
268    /// honoured: naming it is the point.
269    #[serde(default)]
270    pub min_number: i64,
271    /// Waves of newly filed follow-ups to fold back into the same run, rather
272    /// than leaving them for the next one.
273    ///
274    /// Off by default because it multiplies what a run costs, and because each
275    /// wave can file follow-ups of its own. Every wave is triaged like any
276    /// other issue, so both agents still have to agree it is worth doing.
277    #[serde(default)]
278    pub absorb_new_issues: u32,
279    #[serde(default)]
280    pub effort_schedule: EffortSchedule,
281}
282
283fn three() -> u32 {
284    3
285}
286fn main_branch() -> String {
287    "main".to_string()
288}
289fn yes() -> bool {
290    true
291}
292fn store_local() -> StateStore {
293    StateStore::Local
294}
295fn followups_issues() -> Followups {
296    Followups::Issues
297}
298
299impl Default for LoopCfg {
300    fn default() -> Self {
301        Self {
302            max_rounds: 3,
303            auto_merge: false,
304            first_implementor: None,
305            base_branch: "main".into(),
306            worktrees: true,
307            keep_worktrees: false,
308            state_store: StateStore::Local,
309            branch_prefix: String::new(),
310            followups: Followups::Issues,
311            file_nits: false,
312            close_skipped: true,
313            parallel_triage: true,
314            min_number: 0,
315            absorb_new_issues: 0,
316            effort_schedule: EffortSchedule::default(),
317        }
318    }
319}
320
321#[derive(Debug, Clone, Serialize, Deserialize)]
322#[serde(deny_unknown_fields)]
323pub struct StyleCfg {
324    #[serde(default = "yes")]
325    pub ban_em_dash: bool,
326    #[serde(default = "yes")]
327    pub ban_ai_attribution: bool,
328    #[serde(default = "yes")]
329    pub terse: bool,
330    #[serde(default = "d320")]
331    pub max_detail_chars: usize,
332    #[serde(default = "d200")]
333    pub max_summary_chars: usize,
334    #[serde(default = "d900")]
335    pub max_body_chars: usize,
336    /// A filed issue's body. Far larger than a PR comment's on purpose: a
337    /// comment is read with the diff in front of you, an issue is picked up
338    /// cold months later by somebody who needs the whole story.
339    #[serde(default = "d4000")]
340    pub max_issue_body_chars: usize,
341    #[serde(default = "d90")]
342    pub max_title_chars: usize,
343    #[serde(default = "outcome_only")]
344    pub pr_comments: PrComments,
345}
346
347fn outcome_only() -> PrComments {
348    PrComments::Outcome
349}
350
351fn d320() -> usize {
352    2000
353}
354fn d200() -> usize {
355    1200
356}
357fn d900() -> usize {
358    2000
359}
360fn d4000() -> usize {
361    8000
362}
363fn d90() -> usize {
364    140
365}
366
367impl Default for StyleCfg {
368    fn default() -> Self {
369        Self {
370            ban_em_dash: true,
371            ban_ai_attribution: true,
372            terse: true,
373            max_detail_chars: 2000,
374            max_summary_chars: 1200,
375            max_body_chars: 2000,
376            max_issue_body_chars: 8000,
377            max_title_chars: 140,
378            pr_comments: PrComments::Outcome,
379        }
380    }
381}
382
383impl StyleCfg {
384    pub fn to_style(&self) -> Style {
385        Style {
386            ban_em_dash: self.ban_em_dash,
387            ban_ai_attribution: self.ban_ai_attribution,
388            terse: self.terse,
389            max_detail_chars: self.max_detail_chars,
390            max_summary_chars: self.max_summary_chars,
391            max_body_chars: self.max_body_chars,
392            max_issue_body_chars: self.max_issue_body_chars,
393            max_title_chars: self.max_title_chars,
394            pr_comments: self.pr_comments,
395        }
396    }
397}
398
399// ---------------------------------------------------------------------------
400// The whole config
401// ---------------------------------------------------------------------------
402
403#[derive(Debug, Clone)]
404pub struct Config {
405    /// In declaration order, which is what `first_implementor` defaults to.
406    pub agents: Vec<AgentSpec>,
407    pub loop_cfg: LoopCfg,
408    pub style: Style,
409    /// Resolved: never empty, always one of the configured agents.
410    pub first_implementor: String,
411    /// Where this config was read from, for error messages.
412    pub source: Option<PathBuf>,
413}
414
415impl Config {
416    pub fn agent_names(&self) -> Vec<String> {
417        self.agents.iter().map(|a| a.name.clone()).collect()
418    }
419
420    pub fn has_agent(&self, name: &str) -> bool {
421        self.agents.iter().any(|a| a.name == name)
422    }
423
424    pub fn spec(&self, name: &str) -> Result<&AgentSpec> {
425        self.agents.iter().find(|a| a.name == name).ok_or_else(|| {
426            spar_err!(
427                "no agent named '{name}' ({})",
428                self.agent_names().join(", ")
429            )
430        })
431    }
432
433    /// The other agent. With exactly two configured, custody alternates by
434    /// definition.
435    pub fn other(&self, name: &str) -> String {
436        let names = self.agent_names();
437        if names.first().map(String::as_str) == Some(name) {
438            names.get(1).cloned().unwrap_or_else(|| name.to_string())
439        } else {
440            names.first().cloned().unwrap_or_else(|| name.to_string())
441        }
442    }
443
444    /// Round 1 gets the deep pass; later rounds only see a small delta, and a
445    /// full ultra review of a three line delta is money on fire.
446    pub fn effort_for_round(&self, spec: &AgentSpec, round: u32) -> Option<String> {
447        let scheduled = if round <= 1 {
448            self.loop_cfg.effort_schedule.round_1.clone()
449        } else {
450            self.loop_cfg.effort_schedule.rest.clone()
451        };
452        scheduled
453            .filter(|s| !s.trim().is_empty())
454            .or_else(|| spec.effort.clone())
455    }
456
457    pub fn base_branch(&self) -> &str {
458        &self.loop_cfg.base_branch
459    }
460}
461
462#[derive(Debug, Deserialize)]
463#[serde(deny_unknown_fields)]
464struct RawConfig {
465    #[serde(default)]
466    agents: toml::Table,
467    #[serde(default)]
468    #[serde(rename = "loop")]
469    loop_cfg: Option<LoopCfg>,
470    #[serde(default)]
471    style: Option<StyleCfg>,
472}
473
474// ---------------------------------------------------------------------------
475// Presets
476// ---------------------------------------------------------------------------
477
478/// Directories searched for preset overrides, nearest first.
479///
480/// Deliberately *not* a bare `presets/`. spar runs from inside the user's own
481/// repository, where `presets/` is a perfectly ordinary directory name for
482/// something unrelated (sampler configs, prompt libraries, editor themes), and
483/// a stray `presets/claude.toml` shadowing the built in preset produces a
484/// baffling failure: `spar init` reports Claude Code as missing while it sits
485/// on PATH. Overrides live somewhere that names spar.
486pub fn preset_dirs() -> Vec<PathBuf> {
487    let mut dirs = Vec::new();
488    if let Some(custom) = std::env::var_os("SPAR_PRESET_DIR") {
489        dirs.push(PathBuf::from(custom));
490    }
491    dirs.push(PathBuf::from(".spar").join("presets"));
492    if let Some(home) = home_dir() {
493        dirs.push(home.join(".config").join("spar").join("presets"));
494    }
495    dirs
496}
497
498/// Every preset name available, built in and on disk, sorted.
499pub fn available_presets() -> Vec<String> {
500    let mut names: Vec<String> = BUILTIN_PRESETS.iter().map(|(n, _)| n.to_string()).collect();
501    for dir in preset_dirs() {
502        if let Ok(entries) = std::fs::read_dir(&dir) {
503            for entry in entries.flatten() {
504                let path = entry.path();
505                if path.extension().and_then(|e| e.to_str()) == Some("toml") {
506                    if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
507                        names.push(stem.to_string());
508                    }
509                }
510            }
511        }
512    }
513    names.sort();
514    names.dedup();
515    names
516}
517
518/// Parse a whole TOML document into a `Value`.
519///
520/// `"...".parse::<Value>()` parses a single TOML *value*, not a document, so it
521/// rejects the first comment line of every preset.
522fn parse_document(text: &str, what: &str) -> Result<Value> {
523    let table: toml::Table =
524        toml::from_str(text).map_err(|e| spar_err!("{what} is not valid TOML: {e}"))?;
525    Ok(Value::Table(table))
526}
527
528/// Load a preset. A file on disk wins over the built in copy of the same name,
529/// so a drifting CLI can be corrected without waiting for a release.
530pub fn load_preset(name: &str) -> Result<Value> {
531    for dir in preset_dirs() {
532        let path = dir.join(format!("{name}.toml"));
533        if path.is_file() {
534            let text = std::fs::read_to_string(&path)
535                .map_err(|e| spar_err!("could not read preset {}: {e}", path.display()))?;
536            return parse_document(&text, &format!("preset {}", path.display()));
537        }
538    }
539    for (builtin, text) in BUILTIN_PRESETS {
540        if *builtin == name {
541            return parse_document(text, &format!("built in preset {name}"));
542        }
543    }
544    Err(spar_err!(
545        "unknown preset '{name}'. Available: {}",
546        available_presets().join(", ")
547    ))
548}
549
550/// Deep merge, with `over` winning. Used so a config block can override one
551/// field of a preset without restating the whole command template.
552fn merge(base: &Value, over: &Value) -> Value {
553    match (base, over) {
554        (Value::Table(b), Value::Table(o)) => {
555            let mut out = b.clone();
556            for (key, value) in o {
557                let merged = match out.get(key) {
558                    Some(existing) => merge(existing, value),
559                    None => value.clone(),
560                };
561                out.insert(key.clone(), merged);
562            }
563            Value::Table(out)
564        }
565        _ => over.clone(),
566    }
567}
568
569fn build_spec(name: &str, raw: &Value) -> Result<AgentSpec> {
570    let table = raw
571        .as_table()
572        .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
573
574    let merged = match table.get("preset").and_then(Value::as_str) {
575        Some(preset) => merge(&load_preset(preset)?, raw),
576        None => raw.clone(),
577    };
578
579    let mut merged_table = merged
580        .as_table()
581        .cloned()
582        .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
583    merged_table.remove("preset");
584
585    if !merged_table.contains_key("command") {
586        bail!(
587            "agent '{name}' has no command and no preset. Set one of them, or pick a preset: {}",
588            available_presets().join(", ")
589        );
590    }
591
592    let mut spec: AgentSpec = Value::Table(merged_table)
593        .try_into()
594        .map_err(|e| spar_err!("agent '{name}': {e}"))?;
595    spec.name = name.to_string();
596
597    if spec.command.is_empty() {
598        bail!("agent '{name}' has an empty command");
599    }
600    if matches!(spec.command.first(), Some(CommandPart::Group(_))) {
601        bail!("agent '{name}': the first command element must be the program name, not a group");
602    }
603    if spec.output == OutputMode::Jsonl && spec.message_path.as_deref().unwrap_or("").is_empty() {
604        bail!(
605            "agent '{name}': output = \"jsonl\" needs a message_path saying where the answer lives"
606        );
607    }
608    Ok(spec)
609}
610
611// ---------------------------------------------------------------------------
612// Loading
613// ---------------------------------------------------------------------------
614
615pub const CONFIG_NAMES: &[&str] = &["spar.toml", ".spar.toml"];
616
617/// Find a config: an explicit path, then the working directory, then
618/// `~/.config/spar/spar.toml`.
619pub fn find_config(explicit: Option<&Path>) -> Result<Option<PathBuf>> {
620    if let Some(path) = explicit {
621        if !path.is_file() {
622            bail!("config not found: {}", path.display());
623        }
624        return Ok(Some(path.to_path_buf()));
625    }
626    for name in CONFIG_NAMES {
627        let path = PathBuf::from(name);
628        if path.is_file() {
629            return Ok(Some(path));
630        }
631    }
632    if let Some(home) = home_dir() {
633        let path = home.join(".config").join("spar").join("spar.toml");
634        if path.is_file() {
635            return Ok(Some(path));
636        }
637    }
638    Ok(None)
639}
640
641pub fn load(explicit: Option<&Path>) -> Result<Config> {
642    let Some(path) = find_config(explicit)? else {
643        bail!(
644            "no spar.toml found. Run `spar init` to generate one from the CLIs you have installed."
645        );
646    };
647    let text = std::fs::read_to_string(&path)
648        .map_err(|e| spar_err!("could not read {}: {e}", path.display()))?;
649    let mut cfg = parse(&text).map_err(|e| spar_err!("{}: {e}", path.display()))?;
650    cfg.source = Some(path);
651    Ok(cfg)
652}
653
654pub fn parse(text: &str) -> Result<Config> {
655    let raw: RawConfig = toml::from_str(text)?;
656
657    if raw.agents.len() != 2 {
658        bail!(
659            "spar needs exactly two agents, found {}. The whole design is one reviewing the other.",
660            raw.agents.len()
661        );
662    }
663
664    let mut agents = Vec::new();
665    for (name, value) in raw.agents.iter() {
666        agents.push(build_spec(name, value)?);
667    }
668
669    let loop_cfg = raw.loop_cfg.unwrap_or_default();
670    let style = raw.style.unwrap_or_default().to_style();
671
672    if loop_cfg.max_rounds == 0 {
673        bail!("max_rounds must be at least 1");
674    }
675
676    let first = match &loop_cfg.first_implementor {
677        Some(name) if !name.trim().is_empty() => name.trim().to_string(),
678        _ => agents[0].name.clone(),
679    };
680    if !agents.iter().any(|a| a.name == first) {
681        bail!(
682            "first_implementor '{first}' is not a configured agent ({})",
683            agents
684                .iter()
685                .map(|a| a.name.as_str())
686                .collect::<Vec<_>>()
687                .join(", ")
688        );
689    }
690
691    Ok(Config {
692        agents,
693        loop_cfg,
694        style,
695        first_implementor: first,
696        source: None,
697    })
698}
699
700/// Resolve a configured search path, expanding a leading `~`.
701pub fn resolve_search_path(raw: &str) -> PathBuf {
702    expand_tilde(raw)
703}
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708
709    const TWO_AGENTS: &str = r#"
710[agents.claude]
711preset = "claude"
712model = "fable"
713
714[agents.codex]
715preset = "codex"
716model = "gpt-5.6-sol"
717"#;
718
719    #[test]
720    fn every_builtin_preset_parses() {
721        for (name, _) in BUILTIN_PRESETS {
722            let value = load_preset(name).unwrap_or_else(|e| panic!("{name}: {e}"));
723            assert!(value.get("command").is_some(), "{name} has no command");
724        }
725    }
726
727    #[test]
728    fn every_builtin_preset_builds_a_spec() {
729        for (name, _) in BUILTIN_PRESETS {
730            let raw = parse_document(&format!("preset = \"{name}\""), "test").unwrap();
731            build_spec(name, &raw).unwrap_or_else(|e| panic!("{name}: {e}"));
732        }
733    }
734
735    /// `--allowedTools` is variadic, so the separate form swallows the
736    /// following positional prompt unless another flag happens to sit between
737    /// them. The equals form is not cosmetic.
738    #[test]
739    fn claude_preset_uses_the_equals_form_for_allowed_tools() {
740        let spec = build_spec(
741            "claude",
742            &parse_document("preset = \"claude\"", "test").unwrap(),
743        )
744        .unwrap();
745        let flat: Vec<&String> = spec.command.iter().flat_map(|p| p.args()).collect();
746        assert!(flat.iter().any(|a| a.starts_with("--allowedTools=")));
747        assert!(!flat.iter().any(|a| a.as_str() == "--allowedTools"));
748    }
749
750    #[test]
751    fn codex_preset_declares_where_its_answer_lives() {
752        let spec = build_spec(
753            "codex",
754            &parse_document("preset = \"codex\"", "test").unwrap(),
755        )
756        .unwrap();
757        assert_eq!(OutputMode::Jsonl, spec.output);
758        assert_eq!(Some("item.text"), spec.message_path.as_deref());
759        assert!(!spec.message_match.is_empty());
760    }
761
762    #[test]
763    fn agent_order_follows_declaration_order() {
764        let cfg = parse(TWO_AGENTS).unwrap();
765        assert_eq!(vec!["claude", "codex"], cfg.agent_names());
766        assert_eq!("claude", cfg.first_implementor);
767    }
768
769    #[test]
770    fn other_alternates() {
771        let cfg = parse(TWO_AGENTS).unwrap();
772        assert_eq!("codex", cfg.other("claude"));
773        assert_eq!("claude", cfg.other("codex"));
774    }
775
776    #[test]
777    fn a_config_block_overrides_one_preset_field() {
778        let cfg = parse(TWO_AGENTS).unwrap();
779        let claude = cfg.spec("claude").unwrap();
780        assert_eq!(Some("fable"), claude.model.as_deref());
781        assert!(claude.command.len() > 1, "the preset command survived");
782    }
783
784    #[test]
785    fn exactly_two_agents_are_required() {
786        let one = "[agents.claude]\npreset = \"claude\"\n";
787        assert!(parse(one).unwrap_err().to_string().contains("exactly two"));
788    }
789
790    #[test]
791    fn an_unknown_agent_option_is_named() {
792        let text = "[agents.a]\ncommand = [\"x\"]\nwidget = 3\n[agents.b]\ncommand = [\"y\"]\n";
793        let err = parse(text).unwrap_err().to_string();
794        assert!(err.contains("widget"), "{err}");
795    }
796
797    #[test]
798    fn an_unknown_loop_option_is_named() {
799        let text = format!("{TWO_AGENTS}\n[loop]\nmax_round = 4\n");
800        let err = parse(&text).unwrap_err().to_string();
801        assert!(err.contains("max_round"), "{err}");
802    }
803
804    #[test]
805    fn an_agent_with_no_command_and_no_preset_is_rejected() {
806        let text = "[agents.a]\nmodel = \"x\"\n[agents.b]\ncommand = [\"y\"]\n";
807        let err = parse(text).unwrap_err().to_string();
808        assert!(err.contains("no command and no preset"), "{err}");
809    }
810
811    #[test]
812    fn jsonl_without_a_message_path_is_rejected() {
813        let text =
814            "[agents.a]\ncommand = [\"x\"]\noutput = \"jsonl\"\n[agents.b]\ncommand = [\"y\"]\n";
815        let err = parse(text).unwrap_err().to_string();
816        assert!(err.contains("message_path"), "{err}");
817    }
818
819    #[test]
820    fn first_implementor_must_name_a_configured_agent() {
821        let text = format!("{TWO_AGENTS}\n[loop]\nfirst_implementor = \"nobody\"\n");
822        let err = parse(&text).unwrap_err().to_string();
823        assert!(err.contains("not a configured agent"), "{err}");
824    }
825
826    #[test]
827    fn defaults_are_the_conservative_ones() {
828        let cfg = parse(TWO_AGENTS).unwrap();
829        assert!(
830            !cfg.loop_cfg.auto_merge,
831            "auto_merge must be off by default"
832        );
833        assert!(cfg.loop_cfg.worktrees);
834        assert!(
835            !cfg.loop_cfg.file_nits,
836            "a filed nit is somebody else's triage queue"
837        );
838        assert_eq!(3, cfg.loop_cfg.max_rounds);
839        assert_eq!(Followups::Issues, cfg.loop_cfg.followups);
840        assert_eq!(StateStore::Local, cfg.loop_cfg.state_store);
841        assert!(cfg.style.terse);
842    }
843
844    #[test]
845    fn effort_schedule_splits_round_one_from_the_rest() {
846        let text =
847            format!("{TWO_AGENTS}\n[loop.effort_schedule]\nround_1 = \"ultra\"\nrest = \"high\"\n");
848        let cfg = parse(&text).unwrap();
849        let spec = cfg.spec("claude").unwrap();
850        assert_eq!(Some("ultra".into()), cfg.effort_for_round(spec, 1));
851        assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 2));
852        assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 9));
853    }
854
855    #[test]
856    fn effort_falls_back_to_the_agents_own_setting() {
857        let text = format!("{TWO_AGENTS}effort = \"low\"\n");
858        let cfg = parse(&text).unwrap();
859        let spec = cfg.spec("codex").unwrap();
860        assert_eq!(Some("low".into()), cfg.effort_for_round(spec, 1));
861    }
862
863    #[test]
864    fn an_unset_model_and_an_empty_model_normalise_the_same() {
865        let a = AgentSpec {
866            name: "a".into(),
867            command: vec![CommandPart::One("x".into())],
868            model: None,
869            effort: None,
870            output: OutputMode::Text,
871            message_match: BTreeMap::new(),
872            message_path: None,
873            search_paths: vec![],
874            system_via: SystemVia::Prompt,
875            timeout: 60,
876            models: vec![],
877            efforts: vec![],
878            options_note: None,
879        };
880        let b = AgentSpec {
881            model: Some("  ".into()),
882            ..a.clone()
883        };
884        assert_eq!(a.model_key(), b.model_key());
885    }
886
887    #[test]
888    fn max_rounds_zero_is_rejected() {
889        let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 0\n");
890        assert!(parse(&text).is_err());
891    }
892
893    #[test]
894    fn an_inline_command_needs_no_preset() {
895        let text = r#"
896[agents.custom]
897command = ["mytool", ["-m", "{model}"], "--prompt", "{prompt}"]
898output = "text"
899
900[agents.other]
901command = ["othertool", "{prompt}"]
902"#;
903        let cfg = parse(text).unwrap();
904        assert_eq!(4, cfg.spec("custom").unwrap().command.len());
905    }
906
907    #[test]
908    fn style_budgets_are_configurable() {
909        let text = format!("{TWO_AGENTS}\n[style]\nterse = false\nmax_detail_chars = 40\n");
910        let cfg = parse(&text).unwrap();
911        assert!(!cfg.style.terse);
912        assert_eq!(40, cfg.style.max_detail_chars);
913    }
914}