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