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    ("cursor", include_str!("../presets/cursor.toml")),
27    ("gemini", include_str!("../presets/gemini.toml")),
28];
29
30// ---------------------------------------------------------------------------
31// Agents
32// ---------------------------------------------------------------------------
33
34/// One element of a command template: a bare argument, or a group that is
35/// dropped whole when its placeholder is unset.
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
37#[serde(untagged)]
38pub enum CommandPart {
39    One(String),
40    Group(Vec<String>),
41}
42
43impl CommandPart {
44    pub fn args(&self) -> &[String] {
45        match self {
46            CommandPart::One(s) => std::slice::from_ref(s),
47            CommandPart::Group(v) => v,
48        }
49    }
50}
51
52/// How to read the answer out of what a CLI printed.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "lowercase")]
55pub enum OutputMode {
56    /// Everything on stdout is the answer.
57    Text,
58    /// Same as text; named separately because it reads better in a preset.
59    Json,
60    /// An event stream, one JSON object per line.
61    Jsonl,
62}
63
64/// Where the style rules go when a CLI has a system prompt flag.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "lowercase")]
67pub enum SystemVia {
68    /// Prepended to the prompt.
69    Prompt,
70    /// Passed through the `{system}` placeholder.
71    Placeholder,
72}
73
74fn default_timeout() -> u64 {
75    crate::proc::DEFAULT_TIMEOUT_SECS
76}
77
78fn default_output() -> OutputMode {
79    OutputMode::Text
80}
81
82fn default_system_via() -> SystemVia {
83    SystemVia::Prompt
84}
85
86/// Everything needed to drive one CLI. An agent is data, not a class:
87/// supporting a new tool is a preset file.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89#[serde(deny_unknown_fields)]
90pub struct AgentSpec {
91    #[serde(skip)]
92    pub name: String,
93    pub command: Vec<CommandPart>,
94    #[serde(default)]
95    pub model: Option<String>,
96    #[serde(default)]
97    pub effort: Option<String>,
98    #[serde(default = "default_output")]
99    pub output: OutputMode,
100    /// For `jsonl`: the event fields that identify the agent's own message.
101    #[serde(default)]
102    pub message_match: BTreeMap<String, String>,
103    /// For `jsonl`: the dotted path to the text inside a matching event.
104    #[serde(default)]
105    pub message_path: Option<String>,
106    /// Extra places to look for the binary when it is not on PATH.
107    #[serde(default)]
108    pub search_paths: Vec<String>,
109    #[serde(default = "default_system_via")]
110    pub system_via: SystemVia,
111    #[serde(default = "default_timeout")]
112    pub timeout: u64,
113    /// A stand in for when this agent cannot answer at all: a CLI that is down,
114    /// out of quota, or refusing the request on policy grounds.
115    ///
116    /// Declared as a nested table rather than by naming a third agent, because
117    /// spar takes exactly two and a backup is not a third opinion. It never
118    /// reviews alongside the pair, it only answers in place of the one that
119    /// failed, so the alternation the design rests on is unchanged.
120    ///
121    /// Built by `build_spec` from the `[agents.NAME.fallback]` table, never
122    /// deserialized directly, so a preset of its own still resolves.
123    #[serde(skip)]
124    pub fallback: Option<Box<AgentSpec>>,
125
126    // -- hints, inert at runtime -----------------------------------------
127    //
128    // Written into a generated config as comments so nobody has to guess what
129    // to put in `model` or `effort`. Deliberately never validated against: a
130    // CLI's options drift, and a stale allow list that refuses a model which
131    // actually works would be worse than no hint at all.
132    /// Model names this CLI is known to accept.
133    #[serde(default)]
134    pub models: Vec<String>,
135    /// Effort levels this CLI is known to accept.
136    #[serde(default)]
137    pub efforts: Vec<String>,
138    /// Where to check the current list, when spar cannot enumerate it.
139    #[serde(default)]
140    pub options_note: Option<String>,
141}
142
143impl AgentSpec {
144    /// The model as configured, normalised. An unset and an empty value both
145    /// mean "let the CLI pick", because `render` drops the flag either way.
146    pub fn model_key(&self) -> String {
147        self.model.as_deref().unwrap_or("").trim().to_string()
148    }
149
150    pub fn describe(&self) -> String {
151        format!(
152            "{}/{}",
153            self.model.as_deref().unwrap_or("default model"),
154            self.effort.as_deref().unwrap_or("default effort")
155        )
156    }
157}
158
159// ---------------------------------------------------------------------------
160// Loop and style blocks
161// ---------------------------------------------------------------------------
162
163/// Where an out of scope finding goes. On your own repository an issue is the
164/// right home. On a large repository that is not yours it is somebody else's
165/// notification and somebody else's triage queue.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
167#[serde(rename_all = "lowercase")]
168pub enum Followups {
169    Issues,
170    Local,
171    None,
172}
173
174impl std::fmt::Display for Followups {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        f.write_str(match self {
177            Followups::Issues => "issues",
178            Followups::Local => "local",
179            Followups::None => "none",
180        })
181    }
182}
183
184/// Whether a pull request spar opens starts as a draft, and when it stops being
185/// one.
186///
187/// A draft says the work is not for a person yet, which is exactly true while
188/// two agents are still arguing about it. `UntilApproved` makes that state mean
189/// something and clear itself: the loop marks the pull request ready the moment
190/// it has no blocking findings left. `Always` is for somebody who promotes
191/// every pull request by hand and wants spar to keep out of it.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "snake_case")]
194pub enum Drafts {
195    /// Open ordinary pull requests. The default, and what spar has always done.
196    Never,
197    /// Open as a draft, and mark it ready when the review converges.
198    UntilApproved,
199    /// Open as a draft and leave it that way.
200    Always,
201}
202
203impl std::fmt::Display for Drafts {
204    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205        f.write_str(match self {
206            Drafts::Never => "never",
207            Drafts::UntilApproved => "until_approved",
208            Drafts::Always => "always",
209        })
210    }
211}
212
213/// How much of its own working spar narrates into a pull request thread.
214///
215/// The agents never read the PR: they receive findings through their prompts,
216/// so nothing in the loop depends on any of this being posted. It exists purely
217/// for the person who reads the thread later, which is why the default is the
218/// outcome rather than the play by play.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(rename_all = "lowercase")]
221pub enum PrComments {
222    /// One comment when the run finishes, and only if it has something to say.
223    Outcome,
224    /// A comment per review and per response, as it happens. An audit trail,
225    /// at the cost of a thread nobody wants to read.
226    Rounds,
227    /// Never comment on a pull request. Everything goes to the terminal.
228    None,
229}
230
231impl std::fmt::Display for PrComments {
232    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233        f.write_str(match self {
234            PrComments::Outcome => "outcome",
235            PrComments::Rounds => "rounds",
236            PrComments::None => "none",
237        })
238    }
239}
240
241/// Where resume state lives. Local keeps the PR clean and costs no API calls;
242/// writing to the PR only buys anything if a run might be resumed from a
243/// different checkout.
244#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
245#[serde(rename_all = "lowercase")]
246pub enum StateStore {
247    Local,
248    Pr,
249    Both,
250}
251
252impl StateStore {
253    pub fn writes_local(self) -> bool {
254        matches!(self, StateStore::Local | StateStore::Both)
255    }
256    pub fn writes_pr(self) -> bool {
257        matches!(self, StateStore::Pr | StateStore::Both)
258    }
259}
260
261#[derive(Debug, Clone, Default, Serialize, Deserialize)]
262#[serde(deny_unknown_fields)]
263pub struct EffortSchedule {
264    /// The deep first review.
265    pub round_1: Option<String>,
266    /// Later rounds only see a small delta.
267    pub rest: Option<String>,
268}
269
270/// Every field takes its value from `LoopCfg::default()` when a config does not
271/// mention it, rather than from a per-field function saying the same thing in a
272/// second place. Two places is how a default goes stale.
273#[derive(Debug, Clone, Serialize, Deserialize)]
274#[serde(default, deny_unknown_fields)]
275pub struct LoopCfg {
276    pub max_rounds: u32,
277    pub auto_merge: bool,
278    pub first_implementor: Option<String>,
279    pub base_branch: String,
280    pub worktrees: bool,
281    pub keep_worktrees: bool,
282    pub state_store: StateStore,
283    pub branch_prefix: String,
284    pub followups: Followups,
285    /// File a non-blocking finding as a follow-up.
286    ///
287    /// Off by default, and this is the setting that stops a run breeding. A
288    /// thorough reviewer always finds improvements, and turning each one into a
289    /// tracker item made a single issue spawn ten, which spawned more: mean
290    /// offspring above one never terminates. Not gating a merge is not the same
291    /// as being worth somebody's triage queue.
292    pub file_non_blocking: bool,
293    /// Most follow-ups one run may record before it stops and says what it
294    /// dropped. A backstop, not a target.
295    pub max_followups: usize,
296    /// Nits stay in the PR thread by default. A filed nit is somebody else's
297    /// notification: a run on a production codebase once opened an issue titled
298    /// "Log wording".
299    pub file_nits: bool,
300    /// Close an issue that both agents independently declined, after posting
301    /// the shared reasoning. One agent's opinion is never enough.
302    pub close_skipped: bool,
303    /// Ask both agents to triage at the same time. They only read during
304    /// triage, so there is nothing to serialise.
305    pub parallel_triage: bool,
306    /// Ignore issues and pull requests numbered below this when spar is picking
307    /// for itself. 0 is no floor.
308    ///
309    /// A repository that has been going a while carries a tail of old issues
310    /// nobody is going to reach, and since spar takes the lowest numbered open
311    /// items it walks straight into them. A number you name explicitly is still
312    /// honoured: naming it is the point.
313    pub min_number: i64,
314    /// Waves of newly filed follow-ups to fold back into the same run, rather
315    /// than leaving them for the next one.
316    ///
317    /// Off by default because it multiplies what a run costs, and because each
318    /// wave can file follow-ups of its own. Every wave is triaged like any
319    /// other issue, so both agents still have to agree it is worth doing.
320    pub absorb_new_issues: u32,
321    /// Whether a pull request spar opens starts as a draft.
322    pub drafts: Drafts,
323    /// Extra instructions handed to both agents with every request.
324    ///
325    /// For what a person wants of this repository that the code cannot say and
326    /// spar has no setting for: how far to go, what not to touch, what not to
327    /// wait on. A CLI reads its own conventions file already, CLAUDE.md or
328    /// AGENTS.md, but each reads only its own, and two agents given different
329    /// standing instructions are not the pair this design rests on.
330    ///
331    /// Subordinate to the request and to the schema, which is said in the
332    /// header they arrive under: they change how the work is done, never what
333    /// was asked for or the shape of the answer.
334    pub instructions: String,
335    /// The most of one issue body that reaches a prompt.
336    ///
337    /// Sized so that no issue a person wrote is ever cut. It was 2000 for
338    /// triage and 6000 for implement, silently, and both were small enough to
339    /// clip an ordinary bug report: an agent given half an issue judges and
340    /// implements the half it saw and has no way to know the rest existed.
341    /// When this does fire it is said out loud, in the log and in the prompt.
342    pub max_issue_chars: usize,
343    /// The most every issue body together may add to one triage prompt.
344    ///
345    /// Triage reads the whole queue at once, so the only unbounded thing here
346    /// is the queue. Past this, whole issues are left for the next run rather
347    /// than every issue being shortened: a verdict is posted on the issue and
348    /// can close it, so judging one on part of its body is worse than not
349    /// reaching it yet.
350    pub max_triage_chars: usize,
351    pub effort_schedule: EffortSchedule,
352}
353
354impl Default for LoopCfg {
355    fn default() -> Self {
356        Self {
357            max_rounds: 3,
358            auto_merge: false,
359            first_implementor: None,
360            base_branch: "main".into(),
361            worktrees: true,
362            keep_worktrees: false,
363            state_store: StateStore::Local,
364            branch_prefix: String::new(),
365            followups: Followups::Local,
366            file_non_blocking: false,
367            max_followups: 5,
368            file_nits: false,
369            close_skipped: true,
370            parallel_triage: true,
371            min_number: 0,
372            absorb_new_issues: 0,
373            drafts: Drafts::Never,
374            instructions: String::new(),
375            max_issue_chars: 60_000,
376            max_triage_chars: 200_000,
377            effort_schedule: EffortSchedule::default(),
378        }
379    }
380}
381
382#[derive(Debug, Clone, Serialize, Deserialize)]
383#[serde(default, deny_unknown_fields)]
384pub struct StyleCfg {
385    pub ban_em_dash: bool,
386    pub ban_ai_attribution: bool,
387    pub terse: bool,
388    pub max_detail_chars: usize,
389    pub max_summary_chars: usize,
390    pub max_body_chars: usize,
391    /// A filed issue's body. Far larger than a PR comment's on purpose: a
392    /// comment is read with the diff in front of you, an issue is picked up
393    /// cold months later by somebody who needs the whole story.
394    pub max_issue_body_chars: usize,
395    pub max_title_chars: usize,
396    pub pr_comments: PrComments,
397}
398
399impl Default for StyleCfg {
400    /// Taken from `Style`, which is where the budgets are decided, rather than
401    /// written out again here.
402    ///
403    /// They were written out again here, and they drifted. The functions
404    /// supplying them to serde were still named `d90`, `d200`, `d320`, `d900`
405    /// and `d4000` while returning 140, 2000, 6000, 8000 and 20000, and the
406    /// config `spar init` generated offered the old numbers as though they
407    /// were current. Uncommenting one of those lines to see what it did cut
408    /// every comment spar posts to a fifth of its length.
409    fn default() -> Self {
410        let style = Style::default();
411        Self {
412            ban_em_dash: style.ban_em_dash,
413            ban_ai_attribution: style.ban_ai_attribution,
414            terse: style.terse,
415            max_detail_chars: style.max_detail_chars,
416            max_summary_chars: style.max_summary_chars,
417            max_body_chars: style.max_body_chars,
418            max_issue_body_chars: style.max_issue_body_chars,
419            max_title_chars: style.max_title_chars,
420            pr_comments: style.pr_comments,
421        }
422    }
423}
424
425impl StyleCfg {
426    pub fn to_style(&self) -> Style {
427        Style {
428            ban_em_dash: self.ban_em_dash,
429            ban_ai_attribution: self.ban_ai_attribution,
430            terse: self.terse,
431            max_detail_chars: self.max_detail_chars,
432            max_summary_chars: self.max_summary_chars,
433            max_body_chars: self.max_body_chars,
434            max_issue_body_chars: self.max_issue_body_chars,
435            max_title_chars: self.max_title_chars,
436            pr_comments: self.pr_comments,
437        }
438    }
439}
440
441// ---------------------------------------------------------------------------
442// The whole config
443// ---------------------------------------------------------------------------
444
445#[derive(Debug, Clone)]
446pub struct Config {
447    /// In declaration order, which is what `first_implementor` defaults to.
448    pub agents: Vec<AgentSpec>,
449    pub loop_cfg: LoopCfg,
450    pub style: Style,
451    /// Resolved: never empty, always one of the configured agents.
452    pub first_implementor: String,
453    /// Where this config was read from, for error messages.
454    pub source: Option<PathBuf>,
455}
456
457impl Config {
458    pub fn agent_names(&self) -> Vec<String> {
459        self.agents.iter().map(|a| a.name.clone()).collect()
460    }
461
462    pub fn has_agent(&self, name: &str) -> bool {
463        self.agents.iter().any(|a| a.name == name)
464    }
465
466    pub fn spec(&self, name: &str) -> Result<&AgentSpec> {
467        self.agents.iter().find(|a| a.name == name).ok_or_else(|| {
468            spar_err!(
469                "no agent named '{name}' ({})",
470                self.agent_names().join(", ")
471            )
472        })
473    }
474
475    /// The other agent. With exactly two configured, custody alternates by
476    /// definition.
477    pub fn other(&self, name: &str) -> String {
478        let names = self.agent_names();
479        if names.first().map(String::as_str) == Some(name) {
480            names.get(1).cloned().unwrap_or_else(|| name.to_string())
481        } else {
482            names.first().cloned().unwrap_or_else(|| name.to_string())
483        }
484    }
485
486    /// Round 1 gets the deep pass; later rounds only see a small delta, and a
487    /// full ultra review of a three line delta is money on fire.
488    pub fn effort_for_round(&self, spec: &AgentSpec, round: u32) -> Option<String> {
489        let scheduled = if round <= 1 {
490            self.loop_cfg.effort_schedule.round_1.clone()
491        } else {
492            self.loop_cfg.effort_schedule.rest.clone()
493        };
494        scheduled
495            .filter(|s| !s.trim().is_empty())
496            .or_else(|| spec.effort.clone())
497    }
498
499    pub fn base_branch(&self) -> &str {
500        &self.loop_cfg.base_branch
501    }
502}
503
504#[derive(Debug, Deserialize)]
505#[serde(deny_unknown_fields)]
506struct RawConfig {
507    #[serde(default)]
508    agents: toml::Table,
509    #[serde(default)]
510    #[serde(rename = "loop")]
511    loop_cfg: Option<LoopCfg>,
512    #[serde(default)]
513    style: Option<StyleCfg>,
514}
515
516// ---------------------------------------------------------------------------
517// Presets
518// ---------------------------------------------------------------------------
519
520/// Directories searched for preset overrides, nearest first.
521///
522/// Deliberately *not* a bare `presets/`. spar runs from inside the user's own
523/// repository, where `presets/` is a perfectly ordinary directory name for
524/// something unrelated (sampler configs, prompt libraries, editor themes), and
525/// a stray `presets/claude.toml` shadowing the built in preset produces a
526/// baffling failure: `spar init` reports Claude Code as missing while it sits
527/// on PATH. Overrides live somewhere that names spar.
528pub fn preset_dirs() -> Vec<PathBuf> {
529    let mut dirs = Vec::new();
530    if let Some(custom) = std::env::var_os("SPAR_PRESET_DIR") {
531        dirs.push(PathBuf::from(custom));
532    }
533    dirs.push(PathBuf::from(".spar").join("presets"));
534    if let Some(home) = home_dir() {
535        dirs.push(home.join(".config").join("spar").join("presets"));
536    }
537    dirs
538}
539
540/// Every preset name available, built in and on disk, sorted.
541pub fn available_presets() -> Vec<String> {
542    let mut names: Vec<String> = BUILTIN_PRESETS.iter().map(|(n, _)| n.to_string()).collect();
543    for dir in preset_dirs() {
544        if let Ok(entries) = std::fs::read_dir(&dir) {
545            for entry in entries.flatten() {
546                let path = entry.path();
547                if path.extension().and_then(|e| e.to_str()) == Some("toml") {
548                    if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
549                        names.push(stem.to_string());
550                    }
551                }
552            }
553        }
554    }
555    names.sort();
556    names.dedup();
557    names
558}
559
560/// Parse a whole TOML document into a `Value`.
561///
562/// `"...".parse::<Value>()` parses a single TOML *value*, not a document, so it
563/// rejects the first comment line of every preset.
564fn parse_document(text: &str, what: &str) -> Result<Value> {
565    let table: toml::Table =
566        toml::from_str(text).map_err(|e| spar_err!("{what} is not valid TOML: {e}"))?;
567    Ok(Value::Table(table))
568}
569
570/// Load a preset. A file on disk wins over the built in copy of the same name,
571/// so a drifting CLI can be corrected without waiting for a release.
572pub fn load_preset(name: &str) -> Result<Value> {
573    for dir in preset_dirs() {
574        let path = dir.join(format!("{name}.toml"));
575        if path.is_file() {
576            let text = std::fs::read_to_string(&path)
577                .map_err(|e| spar_err!("could not read preset {}: {e}", path.display()))?;
578            return parse_document(&text, &format!("preset {}", path.display()));
579        }
580    }
581    for (builtin, text) in BUILTIN_PRESETS {
582        if *builtin == name {
583            return parse_document(text, &format!("built in preset {name}"));
584        }
585    }
586    Err(spar_err!(
587        "unknown preset '{name}'. Available: {}",
588        available_presets().join(", ")
589    ))
590}
591
592/// Deep merge, with `over` winning. Used so a config block can override one
593/// field of a preset without restating the whole command template.
594fn merge(base: &Value, over: &Value) -> Value {
595    match (base, over) {
596        (Value::Table(b), Value::Table(o)) => {
597            let mut out = b.clone();
598            for (key, value) in o {
599                let merged = match out.get(key) {
600                    Some(existing) => merge(existing, value),
601                    None => value.clone(),
602                };
603                out.insert(key.clone(), merged);
604            }
605            Value::Table(out)
606        }
607        _ => over.clone(),
608    }
609}
610
611fn build_spec(name: &str, raw: &Value) -> Result<AgentSpec> {
612    let table = raw
613        .as_table()
614        .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
615
616    let merged = match table.get("preset").and_then(Value::as_str) {
617        Some(preset) => merge(&load_preset(preset)?, raw),
618        None => raw.clone(),
619    };
620
621    let mut merged_table = merged
622        .as_table()
623        .cloned()
624        .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
625    merged_table.remove("preset");
626    // Lifted out before the spec is deserialized: a fallback is a whole agent,
627    // preset and all, and only this function knows how to resolve a preset.
628    let fallback_raw = merged_table.remove("fallback");
629
630    if !merged_table.contains_key("command") {
631        bail!(
632            "agent '{name}' has no command and no preset. Set one of them, or pick a preset: {}",
633            available_presets().join(", ")
634        );
635    }
636
637    let mut spec: AgentSpec = Value::Table(merged_table)
638        .try_into()
639        .map_err(|e| spar_err!("agent '{name}': {e}"))?;
640    spec.name = name.to_string();
641
642    if spec.command.is_empty() {
643        bail!("agent '{name}' has an empty command");
644    }
645    if matches!(spec.command.first(), Some(CommandPart::Group(_))) {
646        bail!("agent '{name}': the first command element must be the program name, not a group");
647    }
648    if spec.output == OutputMode::Jsonl && spec.message_path.as_deref().unwrap_or("").is_empty() {
649        bail!(
650            "agent '{name}': output = \"jsonl\" needs a message_path saying where the answer lives"
651        );
652    }
653
654    if let Some(raw) = fallback_raw {
655        if !raw.is_table() {
656            bail!(
657                "agent '{name}': fallback is a whole agent, so write it as a table:\n                   [agents.{name}.fallback]\n  preset = \"cursor\""
658            );
659        }
660        // Named for the env override it answers to, SPAR_<NAME>_FALLBACK_BIN,
661        // and so a log line says which agent stood in for which.
662        let backup = build_spec(&format!("{name}-fallback"), &raw)?;
663        if backup.fallback.is_some() {
664            bail!(
665                "agent '{name}': a fallback may not have a fallback of its own. Each one costs \
666                 another full timeout on a call that has already failed once."
667            );
668        }
669        spec.fallback = Some(Box::new(backup));
670    }
671
672    Ok(spec)
673}
674
675// ---------------------------------------------------------------------------
676// Loading
677// ---------------------------------------------------------------------------
678
679/// One option the parser accepts, with the value it takes when unset.
680#[derive(Debug, Clone)]
681pub struct OptionInfo {
682    pub section: &'static str,
683    pub key: String,
684    pub default: String,
685}
686
687/// Every option a config file may set, with its default.
688///
689/// Derived from the defaults themselves rather than written out by hand, so an
690/// option added to the code cannot go missing here. That is what lets `doctor`
691/// tell somebody upgrading which settings are new since they wrote their file.
692pub fn known_options() -> Vec<OptionInfo> {
693    fn lines<T: Serialize>(section: &'static str, value: &T) -> Vec<OptionInfo> {
694        toml::to_string(value)
695            .unwrap_or_default()
696            .lines()
697            .filter_map(|line| line.split_once(" = "))
698            .map(|(key, default)| OptionInfo {
699                section,
700                key: key.trim().to_string(),
701                default: default.trim().to_string(),
702            })
703            .collect()
704    }
705    let mut out = lines("loop", &LoopCfg::default());
706    out.extend(lines("style", &StyleCfg::default()));
707    out.extend(lines(
708        "loop.effort_schedule",
709        &EffortSchedule {
710            round_1: Some("high".into()),
711            rest: Some("low".into()),
712        },
713    ));
714    out
715}
716
717/// Whether a config file mentions an option at all, set or commented out.
718pub fn mentions(config_text: &str, key: &str) -> bool {
719    config_text.lines().any(|line| {
720        let bare = line.trim_start().trim_start_matches('#').trim_start();
721        bare.starts_with(&format!("{key} ")) || bare.starts_with(&format!("{key}="))
722    })
723}
724
725/// Options this config file has never heard of, which is what somebody who
726/// upgraded wants to know.
727pub fn unmentioned_options(config_text: &str) -> Vec<OptionInfo> {
728    known_options()
729        .into_iter()
730        .filter(|o| !mentions(config_text, &o.key))
731        .collect()
732}
733
734pub const CONFIG_NAMES: &[&str] = &["spar.toml", ".spar.toml"];
735
736/// Find a config: an explicit path, then the working directory, then
737/// `~/.config/spar/spar.toml`.
738pub fn find_config(explicit: Option<&Path>) -> Result<Option<PathBuf>> {
739    if let Some(path) = explicit {
740        if !path.is_file() {
741            bail!("config not found: {}", path.display());
742        }
743        return Ok(Some(path.to_path_buf()));
744    }
745    for name in CONFIG_NAMES {
746        let path = PathBuf::from(name);
747        if path.is_file() {
748            return Ok(Some(path));
749        }
750    }
751    if let Some(home) = home_dir() {
752        let path = home.join(".config").join("spar").join("spar.toml");
753        if path.is_file() {
754            return Ok(Some(path));
755        }
756    }
757    Ok(None)
758}
759
760pub fn load(explicit: Option<&Path>) -> Result<Config> {
761    let Some(path) = find_config(explicit)? else {
762        bail!(
763            "no spar.toml found. Run `spar init` to generate one from the CLIs you have installed."
764        );
765    };
766    let text = std::fs::read_to_string(&path)
767        .map_err(|e| spar_err!("could not read {}: {e}", path.display()))?;
768    let mut cfg = parse(&text).map_err(|e| spar_err!("{}: {e}", path.display()))?;
769    cfg.source = Some(path);
770    Ok(cfg)
771}
772
773pub fn parse(text: &str) -> Result<Config> {
774    let raw: RawConfig = toml::from_str(text)?;
775
776    if raw.agents.len() != 2 {
777        bail!(
778            "spar needs exactly two agents, found {}. The whole design is one reviewing the other.",
779            raw.agents.len()
780        );
781    }
782
783    let mut agents = Vec::new();
784    for (name, value) in raw.agents.iter() {
785        agents.push(build_spec(name, value)?);
786    }
787
788    let loop_cfg = raw.loop_cfg.unwrap_or_default();
789    let style = raw.style.unwrap_or_default().to_style();
790
791    if loop_cfg.max_rounds == 0 {
792        bail!("max_rounds must be at least 1");
793    }
794    // A draft cannot be merged, so merging one means promoting it first, which
795    // is the one thing `always` asks spar not to do. Refusing is better than
796    // picking a winner: either setting alone is coherent and only somebody who
797    // set both can say which they meant.
798    if loop_cfg.auto_merge && loop_cfg.drafts == Drafts::Always {
799        bail!(
800            "auto_merge cannot be on with drafts = \"always\": merging a draft means marking it \
801             ready, which is what \"always\" asks spar not to do. Use drafts = \"until_approved\" \
802             to have it promoted when the review converges, or turn auto_merge off."
803        );
804    }
805
806    let first = match &loop_cfg.first_implementor {
807        Some(name) if !name.trim().is_empty() => name.trim().to_string(),
808        _ => agents[0].name.clone(),
809    };
810    if !agents.iter().any(|a| a.name == first) {
811        bail!(
812            "first_implementor '{first}' is not a configured agent ({})",
813            agents
814                .iter()
815                .map(|a| a.name.as_str())
816                .collect::<Vec<_>>()
817                .join(", ")
818        );
819    }
820
821    Ok(Config {
822        agents,
823        loop_cfg,
824        style,
825        first_implementor: first,
826        source: None,
827    })
828}
829
830/// Resolve a configured search path, expanding a leading `~`.
831pub fn resolve_search_path(raw: &str) -> PathBuf {
832    expand_tilde(raw)
833}
834
835#[cfg(test)]
836mod tests {
837    use super::*;
838
839    const TWO_AGENTS: &str = r#"
840[agents.claude]
841preset = "claude"
842model = "fable"
843
844[agents.codex]
845preset = "codex"
846model = "gpt-5.6-sol"
847"#;
848
849    // -- fallback --------------------------------------------------------
850
851    #[test]
852    fn a_fallback_is_a_whole_agent_with_its_own_preset() {
853        let text = format!(
854            "{TWO_AGENTS}\n[agents.codex.fallback]\npreset = \"cursor\"\nmodel = \"kimi-k3\"\n"
855        );
856        let cfg = parse(&text).expect("parses");
857        // Still a pair. A backup is not a third opinion.
858        assert_eq!(2, cfg.agents.len());
859        let codex = cfg.spec("codex").expect("codex");
860        let backup = codex.fallback.as_ref().expect("fallback");
861        assert_eq!("codex-fallback", backup.name);
862        assert_eq!(Some("kimi-k3"), backup.model.as_deref());
863        assert_eq!(
864            Some(&CommandPart::One("cursor-agent".into())),
865            backup.command.first()
866        );
867    }
868
869    #[test]
870    fn the_agent_without_a_fallback_does_not_grow_one() {
871        let cfg = parse(TWO_AGENTS).expect("parses");
872        assert!(cfg.agents.iter().all(|a| a.fallback.is_none()));
873    }
874
875    #[test]
876    fn a_fallback_may_not_have_one_of_its_own() {
877        let text = format!(
878            "{TWO_AGENTS}\n[agents.codex.fallback]\npreset = \"cursor\"\n\
879             [agents.codex.fallback.fallback]\npreset = \"gemini\"\n"
880        );
881        let err = parse(&text).expect_err("rejected");
882        assert!(err.message().contains("may not have a fallback"), "{err}");
883    }
884
885    #[test]
886    fn a_fallback_written_as_a_string_says_what_it_should_be() {
887        let text = "[agents.claude]\npreset = \"claude\"\n\n\
888                    [agents.codex]\npreset = \"codex\"\nfallback = \"cursor\"\n";
889        let err = parse(text).expect_err("rejected");
890        assert!(err.message().contains("[agents.codex.fallback]"), "{err}");
891    }
892
893    /// A block that names one setting keeps the defaults for every setting it
894    /// did not name. That is what the container level serde default buys: each
895    /// field used to carry its own default function repeating a number that
896    /// also lived in `Default`, and the two copies stopped agreeing.
897    #[test]
898    fn a_partial_block_keeps_the_defaults_it_did_not_name() {
899        let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 9\n\n[style]\nterse = false\n");
900        let cfg = parse(&text).expect("parses");
901
902        assert_eq!(9, cfg.loop_cfg.max_rounds);
903        assert_eq!(LoopCfg::default().followups, cfg.loop_cfg.followups);
904        assert_eq!(LoopCfg::default().close_skipped, cfg.loop_cfg.close_skipped);
905
906        assert!(!cfg.style.terse);
907        assert_eq!(Style::default().max_body_chars, cfg.style.max_body_chars);
908        assert_eq!(Style::default().max_title_chars, cfg.style.max_title_chars);
909    }
910
911    /// The budgets are decided in `Style` and read from there by the config
912    /// layer. When they were written out in both places they drifted, and the
913    /// generated config offered the older set for months.
914    #[test]
915    fn the_config_layer_does_not_keep_its_own_copy_of_the_budgets() {
916        assert_eq!(Style::default(), StyleCfg::default().to_style());
917    }
918
919    // -- drafts ------------------------------------------------------------
920
921    #[test]
922    fn pull_requests_are_not_drafts_unless_asked_for() {
923        assert_eq!(Drafts::Never, parse(TWO_AGENTS).unwrap().loop_cfg.drafts);
924    }
925
926    #[test]
927    fn each_draft_setting_parses() {
928        for (text, want) in [
929            ("never", Drafts::Never),
930            ("until_approved", Drafts::UntilApproved),
931            ("always", Drafts::Always),
932        ] {
933            let cfg = parse(&format!("{TWO_AGENTS}\n[loop]\ndrafts = \"{text}\"\n"))
934                .unwrap_or_else(|e| panic!("{text}: {e}"));
935            assert_eq!(want, cfg.loop_cfg.drafts, "{text}");
936        }
937    }
938
939    /// Merging a draft means marking it ready, which is the one thing `always`
940    /// asks spar not to do. Either setting alone is coherent, so refusing beats
941    /// picking a winner between them.
942    #[test]
943    fn auto_merge_and_a_permanent_draft_are_refused_together() {
944        let text = format!("{TWO_AGENTS}\n[loop]\nauto_merge = true\ndrafts = \"always\"\n");
945        let err = parse(&text).expect_err("refused");
946        assert!(err.message().contains("auto_merge"), "{err}");
947        assert!(
948            err.message().contains("until_approved"),
949            "says the way out: {err}"
950        );
951    }
952
953    /// The pairing that does make sense: the draft clears when the review
954    /// converges, and then it can merge.
955    #[test]
956    fn auto_merge_is_fine_with_a_draft_that_clears() {
957        let text =
958            format!("{TWO_AGENTS}\n[loop]\nauto_merge = true\ndrafts = \"until_approved\"\n");
959        assert!(parse(&text).is_ok());
960    }
961
962    #[test]
963    fn every_builtin_preset_parses() {
964        for (name, _) in BUILTIN_PRESETS {
965            let value = load_preset(name).unwrap_or_else(|e| panic!("{name}: {e}"));
966            assert!(value.get("command").is_some(), "{name} has no command");
967        }
968    }
969
970    #[test]
971    fn every_builtin_preset_builds_a_spec() {
972        for (name, _) in BUILTIN_PRESETS {
973            let raw = parse_document(&format!("preset = \"{name}\""), "test").unwrap();
974            build_spec(name, &raw).unwrap_or_else(|e| panic!("{name}: {e}"));
975        }
976    }
977
978    /// `--allowedTools` is variadic, so the separate form swallows the
979    /// following positional prompt unless another flag happens to sit between
980    /// them. The equals form is not cosmetic.
981    #[test]
982    fn claude_preset_uses_the_equals_form_for_allowed_tools() {
983        let spec = build_spec(
984            "claude",
985            &parse_document("preset = \"claude\"", "test").unwrap(),
986        )
987        .unwrap();
988        let flat: Vec<&String> = spec.command.iter().flat_map(|p| p.args()).collect();
989        assert!(flat.iter().any(|a| a.starts_with("--allowedTools=")));
990        assert!(!flat.iter().any(|a| a.as_str() == "--allowedTools"));
991    }
992
993    #[test]
994    fn codex_preset_declares_where_its_answer_lives() {
995        let spec = build_spec(
996            "codex",
997            &parse_document("preset = \"codex\"", "test").unwrap(),
998        )
999        .unwrap();
1000        assert_eq!(OutputMode::Jsonl, spec.output);
1001        assert_eq!(Some("item.text"), spec.message_path.as_deref());
1002        assert!(!spec.message_match.is_empty());
1003    }
1004
1005    #[test]
1006    fn agent_order_follows_declaration_order() {
1007        let cfg = parse(TWO_AGENTS).unwrap();
1008        assert_eq!(vec!["claude", "codex"], cfg.agent_names());
1009        assert_eq!("claude", cfg.first_implementor);
1010    }
1011
1012    #[test]
1013    fn other_alternates() {
1014        let cfg = parse(TWO_AGENTS).unwrap();
1015        assert_eq!("codex", cfg.other("claude"));
1016        assert_eq!("claude", cfg.other("codex"));
1017    }
1018
1019    #[test]
1020    fn a_config_block_overrides_one_preset_field() {
1021        let cfg = parse(TWO_AGENTS).unwrap();
1022        let claude = cfg.spec("claude").unwrap();
1023        assert_eq!(Some("fable"), claude.model.as_deref());
1024        assert!(claude.command.len() > 1, "the preset command survived");
1025    }
1026
1027    #[test]
1028    fn exactly_two_agents_are_required() {
1029        let one = "[agents.claude]\npreset = \"claude\"\n";
1030        assert!(parse(one).unwrap_err().to_string().contains("exactly two"));
1031    }
1032
1033    #[test]
1034    fn an_unknown_agent_option_is_named() {
1035        let text = "[agents.a]\ncommand = [\"x\"]\nwidget = 3\n[agents.b]\ncommand = [\"y\"]\n";
1036        let err = parse(text).unwrap_err().to_string();
1037        assert!(err.contains("widget"), "{err}");
1038    }
1039
1040    #[test]
1041    fn an_unknown_loop_option_is_named() {
1042        let text = format!("{TWO_AGENTS}\n[loop]\nmax_round = 4\n");
1043        let err = parse(&text).unwrap_err().to_string();
1044        assert!(err.contains("max_round"), "{err}");
1045    }
1046
1047    #[test]
1048    fn an_agent_with_no_command_and_no_preset_is_rejected() {
1049        let text = "[agents.a]\nmodel = \"x\"\n[agents.b]\ncommand = [\"y\"]\n";
1050        let err = parse(text).unwrap_err().to_string();
1051        assert!(err.contains("no command and no preset"), "{err}");
1052    }
1053
1054    #[test]
1055    fn jsonl_without_a_message_path_is_rejected() {
1056        let text =
1057            "[agents.a]\ncommand = [\"x\"]\noutput = \"jsonl\"\n[agents.b]\ncommand = [\"y\"]\n";
1058        let err = parse(text).unwrap_err().to_string();
1059        assert!(err.contains("message_path"), "{err}");
1060    }
1061
1062    #[test]
1063    fn first_implementor_must_name_a_configured_agent() {
1064        let text = format!("{TWO_AGENTS}\n[loop]\nfirst_implementor = \"nobody\"\n");
1065        let err = parse(&text).unwrap_err().to_string();
1066        assert!(err.contains("not a configured agent"), "{err}");
1067    }
1068
1069    #[test]
1070    fn defaults_are_the_conservative_ones() {
1071        let cfg = parse(TWO_AGENTS).unwrap();
1072        assert!(
1073            !cfg.loop_cfg.auto_merge,
1074            "auto_merge must be off by default"
1075        );
1076        assert!(cfg.loop_cfg.worktrees);
1077        assert!(
1078            !cfg.loop_cfg.file_nits,
1079            "a filed nit is somebody else's triage queue"
1080        );
1081        assert_eq!(3, cfg.loop_cfg.max_rounds);
1082        assert_eq!(
1083            Followups::Local,
1084            cfg.loop_cfg.followups,
1085            "the tracker is somebody's queue; the default must not write to it"
1086        );
1087        assert!(
1088            !cfg.loop_cfg.file_non_blocking,
1089            "a suggestion is not a tracker item"
1090        );
1091        assert_eq!(StateStore::Local, cfg.loop_cfg.state_store);
1092        assert!(cfg.style.terse);
1093    }
1094
1095    #[test]
1096    fn effort_schedule_splits_round_one_from_the_rest() {
1097        let text =
1098            format!("{TWO_AGENTS}\n[loop.effort_schedule]\nround_1 = \"ultra\"\nrest = \"high\"\n");
1099        let cfg = parse(&text).unwrap();
1100        let spec = cfg.spec("claude").unwrap();
1101        assert_eq!(Some("ultra".into()), cfg.effort_for_round(spec, 1));
1102        assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 2));
1103        assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 9));
1104    }
1105
1106    #[test]
1107    fn effort_falls_back_to_the_agents_own_setting() {
1108        let text = format!("{TWO_AGENTS}effort = \"low\"\n");
1109        let cfg = parse(&text).unwrap();
1110        let spec = cfg.spec("codex").unwrap();
1111        assert_eq!(Some("low".into()), cfg.effort_for_round(spec, 1));
1112    }
1113
1114    #[test]
1115    fn an_unset_model_and_an_empty_model_normalise_the_same() {
1116        let a = AgentSpec {
1117            name: "a".into(),
1118            command: vec![CommandPart::One("x".into())],
1119            model: None,
1120            effort: None,
1121            output: OutputMode::Text,
1122            message_match: BTreeMap::new(),
1123            message_path: None,
1124            search_paths: vec![],
1125            system_via: SystemVia::Prompt,
1126            timeout: 60,
1127            fallback: None,
1128            models: vec![],
1129            efforts: vec![],
1130            options_note: None,
1131        };
1132        let b = AgentSpec {
1133            model: Some("  ".into()),
1134            ..a.clone()
1135        };
1136        assert_eq!(a.model_key(), b.model_key());
1137    }
1138
1139    #[test]
1140    fn max_rounds_zero_is_rejected() {
1141        let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 0\n");
1142        assert!(parse(&text).is_err());
1143    }
1144
1145    #[test]
1146    fn an_inline_command_needs_no_preset() {
1147        let text = r#"
1148[agents.custom]
1149command = ["mytool", ["-m", "{model}"], "--prompt", "{prompt}"]
1150output = "text"
1151
1152[agents.other]
1153command = ["othertool", "{prompt}"]
1154"#;
1155        let cfg = parse(text).unwrap();
1156        assert_eq!(4, cfg.spec("custom").unwrap().command.len());
1157    }
1158
1159    #[test]
1160    fn style_budgets_are_configurable() {
1161        let text = format!("{TWO_AGENTS}\n[style]\nterse = false\nmax_detail_chars = 40\n");
1162        let cfg = parse(&text).unwrap();
1163        assert!(!cfg.style.terse);
1164        assert_eq!(40, cfg.style.max_detail_chars);
1165    }
1166}