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/// Whose comments `spar checkin` will act on.
262///
263/// The default is not timidity. Acting on a comment means a commit pushed to a
264/// branch because somebody typed a sentence, and `authorAssociation` is one
265/// field GitHub already returns on every comment endpoint that says whether
266/// they can write to this repository at all. Everybody is still answered in
267/// words either way; this governs only whether a comment can produce a commit.
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "lowercase")]
270pub enum Trust {
271    /// Anybody GitHub says can write here: OWNER, MEMBER, COLLABORATOR.
272    Write,
273    /// Anybody at all. Both agents still have to agree before anything changes.
274    Anyone,
275}
276
277impl std::fmt::Display for Trust {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.write_str(match self {
280            Trust::Write => "write",
281            Trust::Anyone => "anyone",
282        })
283    }
284}
285
286impl Trust {
287    /// Whether a comment from somebody with this association may produce a
288    /// commit.
289    pub fn may_act_on(self, association: &str) -> bool {
290        match self {
291            Trust::Anyone => true,
292            Trust::Write => matches!(
293                association.trim().to_uppercase().as_str(),
294                "OWNER" | "MEMBER" | "COLLABORATOR"
295            ),
296        }
297    }
298}
299
300#[derive(Debug, Clone, Default, Serialize, Deserialize)]
301#[serde(deny_unknown_fields)]
302pub struct EffortSchedule {
303    /// The deep first review.
304    pub round_1: Option<String>,
305    /// Later rounds only see a small delta.
306    pub rest: Option<String>,
307}
308
309/// Every field takes its value from `LoopCfg::default()` when a config does not
310/// mention it, rather than from a per-field function saying the same thing in a
311/// second place. Two places is how a default goes stale.
312#[derive(Debug, Clone, Serialize, Deserialize)]
313#[serde(default, deny_unknown_fields)]
314pub struct LoopCfg {
315    pub max_rounds: u32,
316    pub auto_merge: bool,
317    pub first_implementor: Option<String>,
318    pub base_branch: String,
319    pub worktrees: bool,
320    pub keep_worktrees: bool,
321    pub state_store: StateStore,
322    pub branch_prefix: String,
323    pub followups: Followups,
324    /// File a non-blocking finding as a follow-up.
325    ///
326    /// Off by default, and this is the setting that stops a run breeding. A
327    /// thorough reviewer always finds improvements, and turning each one into a
328    /// tracker item made a single issue spawn ten, which spawned more: mean
329    /// offspring above one never terminates. Not gating a merge is not the same
330    /// as being worth somebody's triage queue.
331    pub file_non_blocking: bool,
332    /// Most follow-ups one run may record before it stops and says what it
333    /// dropped. A backstop, not a target.
334    pub max_followups: usize,
335    /// Nits stay in the PR thread by default. A filed nit is somebody else's
336    /// notification: a run on a production codebase once opened an issue titled
337    /// "Log wording".
338    pub file_nits: bool,
339    /// Close an issue that both agents independently declined, after posting
340    /// the shared reasoning. One agent's opinion is never enough.
341    pub close_skipped: bool,
342    /// Ask both agents to triage at the same time. They only read during
343    /// triage, so there is nothing to serialise.
344    pub parallel_triage: bool,
345    /// Ignore issues and pull requests numbered below this when spar is picking
346    /// for itself. 0 is no floor.
347    ///
348    /// A repository that has been going a while carries a tail of old issues
349    /// nobody is going to reach, and since spar takes the lowest numbered open
350    /// items it walks straight into them. A number you name explicitly is still
351    /// honoured: naming it is the point.
352    pub min_number: i64,
353    /// Waves of newly filed follow-ups to fold back into the same run, rather
354    /// than leaving them for the next one.
355    ///
356    /// Off by default because it multiplies what a run costs, and because each
357    /// wave can file follow-ups of its own. Every wave is triaged like any
358    /// other issue, so both agents still have to agree it is worth doing.
359    pub absorb_new_issues: u32,
360    /// Whether a pull request spar opens starts as a draft.
361    pub drafts: Drafts,
362    /// Extra instructions handed to both agents with every request.
363    ///
364    /// For what a person wants of this repository that the code cannot say and
365    /// spar has no setting for: how far to go, what not to touch, what not to
366    /// wait on. A CLI reads its own conventions file already, CLAUDE.md or
367    /// AGENTS.md, but each reads only its own, and two agents given different
368    /// standing instructions are not the pair this design rests on.
369    ///
370    /// Subordinate to the request and to the schema, which is said in the
371    /// header they arrive under: they change how the work is done, never what
372    /// was asked for or the shape of the answer.
373    pub instructions: String,
374    /// The most of one issue body that reaches a prompt.
375    ///
376    /// Sized so that no issue a person wrote is ever cut. It was 2000 for
377    /// triage and 6000 for implement, silently, and both were small enough to
378    /// clip an ordinary bug report: an agent given half an issue judges and
379    /// implements the half it saw and has no way to know the rest existed.
380    /// When this does fire it is said out loud, in the log and in the prompt.
381    pub max_issue_chars: usize,
382    /// The most every issue body together may add to one triage prompt.
383    ///
384    /// Triage reads the whole queue at once, so the only unbounded thing here
385    /// is the queue. Past this, whole issues are left for the next run rather
386    /// than every issue being shortened: a verdict is posted on the issue and
387    /// can close it, so judging one on part of its body is worse than not
388    /// reaching it yet.
389    pub max_triage_chars: usize,
390    /// Whose comments `spar checkin` will act on.
391    pub checkin_trust: Trust,
392    /// Mark a review thread resolved when spar made the change it asked for.
393    ///
394    /// A thread spar disagreed with is left open whatever this says: the person
395    /// who raised it has not had their say yet, and it is their thread.
396    pub checkin_resolve: bool,
397    /// Most unanswered comments spar answers on one pull request in a run.
398    ///
399    /// A backstop against a long argument being read back to somebody, not a
400    /// target. What it held back is said out loud.
401    pub max_checkin_comments: usize,
402    pub effort_schedule: EffortSchedule,
403}
404
405impl Default for LoopCfg {
406    fn default() -> Self {
407        Self {
408            max_rounds: 3,
409            auto_merge: false,
410            first_implementor: None,
411            base_branch: "main".into(),
412            worktrees: true,
413            keep_worktrees: false,
414            state_store: StateStore::Local,
415            branch_prefix: String::new(),
416            followups: Followups::Local,
417            file_non_blocking: false,
418            max_followups: 5,
419            file_nits: false,
420            close_skipped: true,
421            parallel_triage: true,
422            min_number: 0,
423            absorb_new_issues: 0,
424            drafts: Drafts::Never,
425            instructions: String::new(),
426            max_issue_chars: 60_000,
427            max_triage_chars: 200_000,
428            checkin_trust: Trust::Write,
429            checkin_resolve: true,
430            max_checkin_comments: 20,
431            effort_schedule: EffortSchedule::default(),
432        }
433    }
434}
435
436#[derive(Debug, Clone, Serialize, Deserialize)]
437#[serde(default, deny_unknown_fields)]
438pub struct StyleCfg {
439    pub ban_em_dash: bool,
440    pub ban_ai_attribution: bool,
441    pub terse: bool,
442    pub max_detail_chars: usize,
443    pub max_summary_chars: usize,
444    pub max_body_chars: usize,
445    /// A filed issue's body. Far larger than a PR comment's on purpose: a
446    /// comment is read with the diff in front of you, an issue is picked up
447    /// cold months later by somebody who needs the whole story.
448    pub max_issue_body_chars: usize,
449    pub max_title_chars: usize,
450    pub pr_comments: PrComments,
451}
452
453impl Default for StyleCfg {
454    /// Taken from `Style`, which is where the budgets are decided, rather than
455    /// written out again here.
456    ///
457    /// They were written out again here, and they drifted. The functions
458    /// supplying them to serde were still named `d90`, `d200`, `d320`, `d900`
459    /// and `d4000` while returning 140, 2000, 6000, 8000 and 20000, and the
460    /// config `spar init` generated offered the old numbers as though they
461    /// were current. Uncommenting one of those lines to see what it did cut
462    /// every comment spar posts to a fifth of its length.
463    fn default() -> Self {
464        let style = Style::default();
465        Self {
466            ban_em_dash: style.ban_em_dash,
467            ban_ai_attribution: style.ban_ai_attribution,
468            terse: style.terse,
469            max_detail_chars: style.max_detail_chars,
470            max_summary_chars: style.max_summary_chars,
471            max_body_chars: style.max_body_chars,
472            max_issue_body_chars: style.max_issue_body_chars,
473            max_title_chars: style.max_title_chars,
474            pr_comments: style.pr_comments,
475        }
476    }
477}
478
479impl StyleCfg {
480    pub fn to_style(&self) -> Style {
481        Style {
482            ban_em_dash: self.ban_em_dash,
483            ban_ai_attribution: self.ban_ai_attribution,
484            terse: self.terse,
485            max_detail_chars: self.max_detail_chars,
486            max_summary_chars: self.max_summary_chars,
487            max_body_chars: self.max_body_chars,
488            max_issue_body_chars: self.max_issue_body_chars,
489            max_title_chars: self.max_title_chars,
490            pr_comments: self.pr_comments,
491        }
492    }
493}
494
495// ---------------------------------------------------------------------------
496// The whole config
497// ---------------------------------------------------------------------------
498
499#[derive(Debug, Clone)]
500pub struct Config {
501    /// In declaration order, which is what `first_implementor` defaults to.
502    pub agents: Vec<AgentSpec>,
503    pub loop_cfg: LoopCfg,
504    pub style: Style,
505    /// Resolved: never empty, always one of the configured agents.
506    pub first_implementor: String,
507    /// Where this config was read from, for error messages.
508    pub source: Option<PathBuf>,
509}
510
511impl Config {
512    pub fn agent_names(&self) -> Vec<String> {
513        self.agents.iter().map(|a| a.name.clone()).collect()
514    }
515
516    pub fn has_agent(&self, name: &str) -> bool {
517        self.agents.iter().any(|a| a.name == name)
518    }
519
520    pub fn spec(&self, name: &str) -> Result<&AgentSpec> {
521        self.agents.iter().find(|a| a.name == name).ok_or_else(|| {
522            spar_err!(
523                "no agent named '{name}' ({})",
524                self.agent_names().join(", ")
525            )
526        })
527    }
528
529    /// The other agent. With exactly two configured, custody alternates by
530    /// definition.
531    pub fn other(&self, name: &str) -> String {
532        let names = self.agent_names();
533        if names.first().map(String::as_str) == Some(name) {
534            names.get(1).cloned().unwrap_or_else(|| name.to_string())
535        } else {
536            names.first().cloned().unwrap_or_else(|| name.to_string())
537        }
538    }
539
540    /// Round 1 gets the deep pass; later rounds only see a small delta, and a
541    /// full ultra review of a three line delta is money on fire.
542    pub fn effort_for_round(&self, spec: &AgentSpec, round: u32) -> Option<String> {
543        let scheduled = if round <= 1 {
544            self.loop_cfg.effort_schedule.round_1.clone()
545        } else {
546            self.loop_cfg.effort_schedule.rest.clone()
547        };
548        scheduled
549            .filter(|s| !s.trim().is_empty())
550            .or_else(|| spec.effort.clone())
551    }
552
553    pub fn base_branch(&self) -> &str {
554        &self.loop_cfg.base_branch
555    }
556}
557
558#[derive(Debug, Deserialize)]
559#[serde(deny_unknown_fields)]
560struct RawConfig {
561    #[serde(default)]
562    agents: toml::Table,
563    #[serde(default)]
564    #[serde(rename = "loop")]
565    loop_cfg: Option<LoopCfg>,
566    #[serde(default)]
567    style: Option<StyleCfg>,
568}
569
570// ---------------------------------------------------------------------------
571// Presets
572// ---------------------------------------------------------------------------
573
574/// Directories searched for preset overrides, nearest first.
575///
576/// Deliberately *not* a bare `presets/`. spar runs from inside the user's own
577/// repository, where `presets/` is a perfectly ordinary directory name for
578/// something unrelated (sampler configs, prompt libraries, editor themes), and
579/// a stray `presets/claude.toml` shadowing the built in preset produces a
580/// baffling failure: `spar init` reports Claude Code as missing while it sits
581/// on PATH. Overrides live somewhere that names spar.
582pub fn preset_dirs() -> Vec<PathBuf> {
583    let mut dirs = Vec::new();
584    if let Some(custom) = std::env::var_os("SPAR_PRESET_DIR") {
585        dirs.push(PathBuf::from(custom));
586    }
587    dirs.push(PathBuf::from(".spar").join("presets"));
588    if let Some(home) = home_dir() {
589        dirs.push(home.join(".config").join("spar").join("presets"));
590    }
591    dirs
592}
593
594/// Every preset name available, built in and on disk, sorted.
595pub fn available_presets() -> Vec<String> {
596    let mut names: Vec<String> = BUILTIN_PRESETS.iter().map(|(n, _)| n.to_string()).collect();
597    for dir in preset_dirs() {
598        if let Ok(entries) = std::fs::read_dir(&dir) {
599            for entry in entries.flatten() {
600                let path = entry.path();
601                if path.extension().and_then(|e| e.to_str()) == Some("toml") {
602                    if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
603                        names.push(stem.to_string());
604                    }
605                }
606            }
607        }
608    }
609    names.sort();
610    names.dedup();
611    names
612}
613
614/// Parse a whole TOML document into a `Value`.
615///
616/// `"...".parse::<Value>()` parses a single TOML *value*, not a document, so it
617/// rejects the first comment line of every preset.
618fn parse_document(text: &str, what: &str) -> Result<Value> {
619    let table: toml::Table =
620        toml::from_str(text).map_err(|e| spar_err!("{what} is not valid TOML: {e}"))?;
621    Ok(Value::Table(table))
622}
623
624/// Load a preset. A file on disk wins over the built in copy of the same name,
625/// so a drifting CLI can be corrected without waiting for a release.
626pub fn load_preset(name: &str) -> Result<Value> {
627    for dir in preset_dirs() {
628        let path = dir.join(format!("{name}.toml"));
629        if path.is_file() {
630            let text = std::fs::read_to_string(&path)
631                .map_err(|e| spar_err!("could not read preset {}: {e}", path.display()))?;
632            return parse_document(&text, &format!("preset {}", path.display()));
633        }
634    }
635    for (builtin, text) in BUILTIN_PRESETS {
636        if *builtin == name {
637            return parse_document(text, &format!("built in preset {name}"));
638        }
639    }
640    Err(spar_err!(
641        "unknown preset '{name}'. Available: {}",
642        available_presets().join(", ")
643    ))
644}
645
646/// Deep merge, with `over` winning. Used so a config block can override one
647/// field of a preset without restating the whole command template.
648fn merge(base: &Value, over: &Value) -> Value {
649    match (base, over) {
650        (Value::Table(b), Value::Table(o)) => {
651            let mut out = b.clone();
652            for (key, value) in o {
653                let merged = match out.get(key) {
654                    Some(existing) => merge(existing, value),
655                    None => value.clone(),
656                };
657                out.insert(key.clone(), merged);
658            }
659            Value::Table(out)
660        }
661        _ => over.clone(),
662    }
663}
664
665fn build_spec(name: &str, raw: &Value) -> Result<AgentSpec> {
666    let table = raw
667        .as_table()
668        .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
669
670    let merged = match table.get("preset").and_then(Value::as_str) {
671        Some(preset) => merge(&load_preset(preset)?, raw),
672        None => raw.clone(),
673    };
674
675    let mut merged_table = merged
676        .as_table()
677        .cloned()
678        .ok_or_else(|| spar_err!("agent '{name}' must be a table"))?;
679    merged_table.remove("preset");
680    // Lifted out before the spec is deserialized: a fallback is a whole agent,
681    // preset and all, and only this function knows how to resolve a preset.
682    let fallback_raw = merged_table.remove("fallback");
683
684    if !merged_table.contains_key("command") {
685        bail!(
686            "agent '{name}' has no command and no preset. Set one of them, or pick a preset: {}",
687            available_presets().join(", ")
688        );
689    }
690
691    let mut spec: AgentSpec = Value::Table(merged_table)
692        .try_into()
693        .map_err(|e| spar_err!("agent '{name}': {e}"))?;
694    spec.name = name.to_string();
695
696    if spec.command.is_empty() {
697        bail!("agent '{name}' has an empty command");
698    }
699    if matches!(spec.command.first(), Some(CommandPart::Group(_))) {
700        bail!("agent '{name}': the first command element must be the program name, not a group");
701    }
702    if spec.output == OutputMode::Jsonl && spec.message_path.as_deref().unwrap_or("").is_empty() {
703        bail!(
704            "agent '{name}': output = \"jsonl\" needs a message_path saying where the answer lives"
705        );
706    }
707
708    if let Some(raw) = fallback_raw {
709        if !raw.is_table() {
710            bail!(
711                "agent '{name}': fallback is a whole agent, so write it as a table:\n                   [agents.{name}.fallback]\n  preset = \"cursor\""
712            );
713        }
714        // Named for the env override it answers to, SPAR_<NAME>_FALLBACK_BIN,
715        // and so a log line says which agent stood in for which.
716        let backup = build_spec(&format!("{name}-fallback"), &raw)?;
717        if backup.fallback.is_some() {
718            bail!(
719                "agent '{name}': a fallback may not have a fallback of its own. Each one costs \
720                 another full timeout on a call that has already failed once."
721            );
722        }
723        spec.fallback = Some(Box::new(backup));
724    }
725
726    Ok(spec)
727}
728
729// ---------------------------------------------------------------------------
730// Loading
731// ---------------------------------------------------------------------------
732
733/// One option the parser accepts, with the value it takes when unset.
734#[derive(Debug, Clone)]
735pub struct OptionInfo {
736    pub section: &'static str,
737    pub key: String,
738    pub default: String,
739}
740
741/// Every option a config file may set, with its default.
742///
743/// Derived from the defaults themselves rather than written out by hand, so an
744/// option added to the code cannot go missing here. That is what lets `doctor`
745/// tell somebody upgrading which settings are new since they wrote their file.
746pub fn known_options() -> Vec<OptionInfo> {
747    fn lines<T: Serialize>(section: &'static str, value: &T) -> Vec<OptionInfo> {
748        toml::to_string(value)
749            .unwrap_or_default()
750            .lines()
751            .filter_map(|line| line.split_once(" = "))
752            .map(|(key, default)| OptionInfo {
753                section,
754                key: key.trim().to_string(),
755                default: default.trim().to_string(),
756            })
757            .collect()
758    }
759    let mut out = lines("loop", &LoopCfg::default());
760    out.extend(lines("style", &StyleCfg::default()));
761    out.extend(lines(
762        "loop.effort_schedule",
763        &EffortSchedule {
764            round_1: Some("high".into()),
765            rest: Some("low".into()),
766        },
767    ));
768    out
769}
770
771/// Whether a config file mentions an option at all, set or commented out.
772pub fn mentions(config_text: &str, key: &str) -> bool {
773    config_text.lines().any(|line| {
774        let bare = line.trim_start().trim_start_matches('#').trim_start();
775        bare.starts_with(&format!("{key} ")) || bare.starts_with(&format!("{key}="))
776    })
777}
778
779/// Options this config file has never heard of, which is what somebody who
780/// upgraded wants to know.
781pub fn unmentioned_options(config_text: &str) -> Vec<OptionInfo> {
782    known_options()
783        .into_iter()
784        .filter(|o| !mentions(config_text, &o.key))
785        .collect()
786}
787
788pub const CONFIG_NAMES: &[&str] = &["spar.toml", ".spar.toml"];
789
790/// Find a config: an explicit path, then the working directory, then
791/// `~/.config/spar/spar.toml`.
792pub fn find_config(explicit: Option<&Path>) -> Result<Option<PathBuf>> {
793    if let Some(path) = explicit {
794        if !path.is_file() {
795            bail!("config not found: {}", path.display());
796        }
797        return Ok(Some(path.to_path_buf()));
798    }
799    for name in CONFIG_NAMES {
800        let path = PathBuf::from(name);
801        if path.is_file() {
802            return Ok(Some(path));
803        }
804    }
805    if let Some(home) = home_dir() {
806        let path = home.join(".config").join("spar").join("spar.toml");
807        if path.is_file() {
808            return Ok(Some(path));
809        }
810    }
811    Ok(None)
812}
813
814pub fn load(explicit: Option<&Path>) -> Result<Config> {
815    let Some(path) = find_config(explicit)? else {
816        bail!(
817            "no spar.toml found. Run `spar init` to generate one from the CLIs you have installed."
818        );
819    };
820    let text = std::fs::read_to_string(&path)
821        .map_err(|e| spar_err!("could not read {}: {e}", path.display()))?;
822    let mut cfg = parse(&text).map_err(|e| spar_err!("{}: {e}", path.display()))?;
823    cfg.source = Some(path);
824    Ok(cfg)
825}
826
827pub fn parse(text: &str) -> Result<Config> {
828    let raw: RawConfig = toml::from_str(text)?;
829
830    if raw.agents.len() != 2 {
831        bail!(
832            "spar needs exactly two agents, found {}. The whole design is one reviewing the other.",
833            raw.agents.len()
834        );
835    }
836
837    let mut agents = Vec::new();
838    for (name, value) in raw.agents.iter() {
839        agents.push(build_spec(name, value)?);
840    }
841
842    let loop_cfg = raw.loop_cfg.unwrap_or_default();
843    let style = raw.style.unwrap_or_default().to_style();
844
845    if loop_cfg.max_rounds == 0 {
846        bail!("max_rounds must be at least 1");
847    }
848    // A draft cannot be merged, so merging one means promoting it first, which
849    // is the one thing `always` asks spar not to do. Refusing is better than
850    // picking a winner: either setting alone is coherent and only somebody who
851    // set both can say which they meant.
852    if loop_cfg.auto_merge && loop_cfg.drafts == Drafts::Always {
853        bail!(
854            "auto_merge cannot be on with drafts = \"always\": merging a draft means marking it \
855             ready, which is what \"always\" asks spar not to do. Use drafts = \"until_approved\" \
856             to have it promoted when the review converges, or turn auto_merge off."
857        );
858    }
859
860    let first = match &loop_cfg.first_implementor {
861        Some(name) if !name.trim().is_empty() => name.trim().to_string(),
862        _ => agents[0].name.clone(),
863    };
864    if !agents.iter().any(|a| a.name == first) {
865        bail!(
866            "first_implementor '{first}' is not a configured agent ({})",
867            agents
868                .iter()
869                .map(|a| a.name.as_str())
870                .collect::<Vec<_>>()
871                .join(", ")
872        );
873    }
874
875    Ok(Config {
876        agents,
877        loop_cfg,
878        style,
879        first_implementor: first,
880        source: None,
881    })
882}
883
884/// Resolve a configured search path, expanding a leading `~`.
885pub fn resolve_search_path(raw: &str) -> PathBuf {
886    expand_tilde(raw)
887}
888
889#[cfg(test)]
890mod tests {
891    use super::*;
892
893    const TWO_AGENTS: &str = r#"
894[agents.claude]
895preset = "claude"
896model = "fable"
897
898[agents.codex]
899preset = "codex"
900model = "gpt-5.6-sol"
901"#;
902
903    // -- fallback --------------------------------------------------------
904
905    #[test]
906    fn a_fallback_is_a_whole_agent_with_its_own_preset() {
907        let text = format!(
908            "{TWO_AGENTS}\n[agents.codex.fallback]\npreset = \"cursor\"\nmodel = \"kimi-k3\"\n"
909        );
910        let cfg = parse(&text).expect("parses");
911        // Still a pair. A backup is not a third opinion.
912        assert_eq!(2, cfg.agents.len());
913        let codex = cfg.spec("codex").expect("codex");
914        let backup = codex.fallback.as_ref().expect("fallback");
915        assert_eq!("codex-fallback", backup.name);
916        assert_eq!(Some("kimi-k3"), backup.model.as_deref());
917        assert_eq!(
918            Some(&CommandPart::One("cursor-agent".into())),
919            backup.command.first()
920        );
921    }
922
923    #[test]
924    fn the_agent_without_a_fallback_does_not_grow_one() {
925        let cfg = parse(TWO_AGENTS).expect("parses");
926        assert!(cfg.agents.iter().all(|a| a.fallback.is_none()));
927    }
928
929    #[test]
930    fn a_fallback_may_not_have_one_of_its_own() {
931        let text = format!(
932            "{TWO_AGENTS}\n[agents.codex.fallback]\npreset = \"cursor\"\n\
933             [agents.codex.fallback.fallback]\npreset = \"gemini\"\n"
934        );
935        let err = parse(&text).expect_err("rejected");
936        assert!(err.message().contains("may not have a fallback"), "{err}");
937    }
938
939    #[test]
940    fn a_fallback_written_as_a_string_says_what_it_should_be() {
941        let text = "[agents.claude]\npreset = \"claude\"\n\n\
942                    [agents.codex]\npreset = \"codex\"\nfallback = \"cursor\"\n";
943        let err = parse(text).expect_err("rejected");
944        assert!(err.message().contains("[agents.codex.fallback]"), "{err}");
945    }
946
947    /// A block that names one setting keeps the defaults for every setting it
948    /// did not name. That is what the container level serde default buys: each
949    /// field used to carry its own default function repeating a number that
950    /// also lived in `Default`, and the two copies stopped agreeing.
951    #[test]
952    fn a_partial_block_keeps_the_defaults_it_did_not_name() {
953        let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 9\n\n[style]\nterse = false\n");
954        let cfg = parse(&text).expect("parses");
955
956        assert_eq!(9, cfg.loop_cfg.max_rounds);
957        assert_eq!(LoopCfg::default().followups, cfg.loop_cfg.followups);
958        assert_eq!(LoopCfg::default().close_skipped, cfg.loop_cfg.close_skipped);
959
960        assert!(!cfg.style.terse);
961        assert_eq!(Style::default().max_body_chars, cfg.style.max_body_chars);
962        assert_eq!(Style::default().max_title_chars, cfg.style.max_title_chars);
963    }
964
965    /// The budgets are decided in `Style` and read from there by the config
966    /// layer. When they were written out in both places they drifted, and the
967    /// generated config offered the older set for months.
968    #[test]
969    fn the_config_layer_does_not_keep_its_own_copy_of_the_budgets() {
970        assert_eq!(Style::default(), StyleCfg::default().to_style());
971    }
972
973    // -- drafts ------------------------------------------------------------
974
975    #[test]
976    fn pull_requests_are_not_drafts_unless_asked_for() {
977        assert_eq!(Drafts::Never, parse(TWO_AGENTS).unwrap().loop_cfg.drafts);
978    }
979
980    #[test]
981    fn each_draft_setting_parses() {
982        for (text, want) in [
983            ("never", Drafts::Never),
984            ("until_approved", Drafts::UntilApproved),
985            ("always", Drafts::Always),
986        ] {
987            let cfg = parse(&format!("{TWO_AGENTS}\n[loop]\ndrafts = \"{text}\"\n"))
988                .unwrap_or_else(|e| panic!("{text}: {e}"));
989            assert_eq!(want, cfg.loop_cfg.drafts, "{text}");
990        }
991    }
992
993    /// Merging a draft means marking it ready, which is the one thing `always`
994    /// asks spar not to do. Either setting alone is coherent, so refusing beats
995    /// picking a winner between them.
996    #[test]
997    fn auto_merge_and_a_permanent_draft_are_refused_together() {
998        let text = format!("{TWO_AGENTS}\n[loop]\nauto_merge = true\ndrafts = \"always\"\n");
999        let err = parse(&text).expect_err("refused");
1000        assert!(err.message().contains("auto_merge"), "{err}");
1001        assert!(
1002            err.message().contains("until_approved"),
1003            "says the way out: {err}"
1004        );
1005    }
1006
1007    /// The pairing that does make sense: the draft clears when the review
1008    /// converges, and then it can merge.
1009    #[test]
1010    fn auto_merge_is_fine_with_a_draft_that_clears() {
1011        let text =
1012            format!("{TWO_AGENTS}\n[loop]\nauto_merge = true\ndrafts = \"until_approved\"\n");
1013        assert!(parse(&text).is_ok());
1014    }
1015
1016    #[test]
1017    fn every_builtin_preset_parses() {
1018        for (name, _) in BUILTIN_PRESETS {
1019            let value = load_preset(name).unwrap_or_else(|e| panic!("{name}: {e}"));
1020            assert!(value.get("command").is_some(), "{name} has no command");
1021        }
1022    }
1023
1024    #[test]
1025    fn every_builtin_preset_builds_a_spec() {
1026        for (name, _) in BUILTIN_PRESETS {
1027            let raw = parse_document(&format!("preset = \"{name}\""), "test").unwrap();
1028            build_spec(name, &raw).unwrap_or_else(|e| panic!("{name}: {e}"));
1029        }
1030    }
1031
1032    /// `--allowedTools` is variadic, so the separate form swallows the
1033    /// following positional prompt unless another flag happens to sit between
1034    /// them. The equals form is not cosmetic.
1035    #[test]
1036    fn claude_preset_uses_the_equals_form_for_allowed_tools() {
1037        let spec = build_spec(
1038            "claude",
1039            &parse_document("preset = \"claude\"", "test").unwrap(),
1040        )
1041        .unwrap();
1042        let flat: Vec<&String> = spec.command.iter().flat_map(|p| p.args()).collect();
1043        assert!(flat.iter().any(|a| a.starts_with("--allowedTools=")));
1044        assert!(!flat.iter().any(|a| a.as_str() == "--allowedTools"));
1045    }
1046
1047    #[test]
1048    fn codex_preset_declares_where_its_answer_lives() {
1049        let spec = build_spec(
1050            "codex",
1051            &parse_document("preset = \"codex\"", "test").unwrap(),
1052        )
1053        .unwrap();
1054        assert_eq!(OutputMode::Jsonl, spec.output);
1055        assert_eq!(Some("item.text"), spec.message_path.as_deref());
1056        assert!(!spec.message_match.is_empty());
1057    }
1058
1059    #[test]
1060    fn agent_order_follows_declaration_order() {
1061        let cfg = parse(TWO_AGENTS).unwrap();
1062        assert_eq!(vec!["claude", "codex"], cfg.agent_names());
1063        assert_eq!("claude", cfg.first_implementor);
1064    }
1065
1066    #[test]
1067    fn other_alternates() {
1068        let cfg = parse(TWO_AGENTS).unwrap();
1069        assert_eq!("codex", cfg.other("claude"));
1070        assert_eq!("claude", cfg.other("codex"));
1071    }
1072
1073    #[test]
1074    fn a_config_block_overrides_one_preset_field() {
1075        let cfg = parse(TWO_AGENTS).unwrap();
1076        let claude = cfg.spec("claude").unwrap();
1077        assert_eq!(Some("fable"), claude.model.as_deref());
1078        assert!(claude.command.len() > 1, "the preset command survived");
1079    }
1080
1081    #[test]
1082    fn exactly_two_agents_are_required() {
1083        let one = "[agents.claude]\npreset = \"claude\"\n";
1084        assert!(parse(one).unwrap_err().to_string().contains("exactly two"));
1085    }
1086
1087    #[test]
1088    fn an_unknown_agent_option_is_named() {
1089        let text = "[agents.a]\ncommand = [\"x\"]\nwidget = 3\n[agents.b]\ncommand = [\"y\"]\n";
1090        let err = parse(text).unwrap_err().to_string();
1091        assert!(err.contains("widget"), "{err}");
1092    }
1093
1094    #[test]
1095    fn an_unknown_loop_option_is_named() {
1096        let text = format!("{TWO_AGENTS}\n[loop]\nmax_round = 4\n");
1097        let err = parse(&text).unwrap_err().to_string();
1098        assert!(err.contains("max_round"), "{err}");
1099    }
1100
1101    #[test]
1102    fn an_agent_with_no_command_and_no_preset_is_rejected() {
1103        let text = "[agents.a]\nmodel = \"x\"\n[agents.b]\ncommand = [\"y\"]\n";
1104        let err = parse(text).unwrap_err().to_string();
1105        assert!(err.contains("no command and no preset"), "{err}");
1106    }
1107
1108    #[test]
1109    fn jsonl_without_a_message_path_is_rejected() {
1110        let text =
1111            "[agents.a]\ncommand = [\"x\"]\noutput = \"jsonl\"\n[agents.b]\ncommand = [\"y\"]\n";
1112        let err = parse(text).unwrap_err().to_string();
1113        assert!(err.contains("message_path"), "{err}");
1114    }
1115
1116    #[test]
1117    fn first_implementor_must_name_a_configured_agent() {
1118        let text = format!("{TWO_AGENTS}\n[loop]\nfirst_implementor = \"nobody\"\n");
1119        let err = parse(&text).unwrap_err().to_string();
1120        assert!(err.contains("not a configured agent"), "{err}");
1121    }
1122
1123    #[test]
1124    fn defaults_are_the_conservative_ones() {
1125        let cfg = parse(TWO_AGENTS).unwrap();
1126        assert!(
1127            !cfg.loop_cfg.auto_merge,
1128            "auto_merge must be off by default"
1129        );
1130        assert!(cfg.loop_cfg.worktrees);
1131        assert!(
1132            !cfg.loop_cfg.file_nits,
1133            "a filed nit is somebody else's triage queue"
1134        );
1135        assert_eq!(3, cfg.loop_cfg.max_rounds);
1136        assert_eq!(
1137            Followups::Local,
1138            cfg.loop_cfg.followups,
1139            "the tracker is somebody's queue; the default must not write to it"
1140        );
1141        assert!(
1142            !cfg.loop_cfg.file_non_blocking,
1143            "a suggestion is not a tracker item"
1144        );
1145        assert_eq!(StateStore::Local, cfg.loop_cfg.state_store);
1146        assert!(cfg.style.terse);
1147    }
1148
1149    #[test]
1150    fn effort_schedule_splits_round_one_from_the_rest() {
1151        let text =
1152            format!("{TWO_AGENTS}\n[loop.effort_schedule]\nround_1 = \"ultra\"\nrest = \"high\"\n");
1153        let cfg = parse(&text).unwrap();
1154        let spec = cfg.spec("claude").unwrap();
1155        assert_eq!(Some("ultra".into()), cfg.effort_for_round(spec, 1));
1156        assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 2));
1157        assert_eq!(Some("high".into()), cfg.effort_for_round(spec, 9));
1158    }
1159
1160    #[test]
1161    fn effort_falls_back_to_the_agents_own_setting() {
1162        let text = format!("{TWO_AGENTS}effort = \"low\"\n");
1163        let cfg = parse(&text).unwrap();
1164        let spec = cfg.spec("codex").unwrap();
1165        assert_eq!(Some("low".into()), cfg.effort_for_round(spec, 1));
1166    }
1167
1168    #[test]
1169    fn an_unset_model_and_an_empty_model_normalise_the_same() {
1170        let a = AgentSpec {
1171            name: "a".into(),
1172            command: vec![CommandPart::One("x".into())],
1173            model: None,
1174            effort: None,
1175            output: OutputMode::Text,
1176            message_match: BTreeMap::new(),
1177            message_path: None,
1178            search_paths: vec![],
1179            system_via: SystemVia::Prompt,
1180            timeout: 60,
1181            fallback: None,
1182            models: vec![],
1183            efforts: vec![],
1184            options_note: None,
1185        };
1186        let b = AgentSpec {
1187            model: Some("  ".into()),
1188            ..a.clone()
1189        };
1190        assert_eq!(a.model_key(), b.model_key());
1191    }
1192
1193    #[test]
1194    fn max_rounds_zero_is_rejected() {
1195        let text = format!("{TWO_AGENTS}\n[loop]\nmax_rounds = 0\n");
1196        assert!(parse(&text).is_err());
1197    }
1198
1199    #[test]
1200    fn an_inline_command_needs_no_preset() {
1201        let text = r#"
1202[agents.custom]
1203command = ["mytool", ["-m", "{model}"], "--prompt", "{prompt}"]
1204output = "text"
1205
1206[agents.other]
1207command = ["othertool", "{prompt}"]
1208"#;
1209        let cfg = parse(text).unwrap();
1210        assert_eq!(4, cfg.spec("custom").unwrap().command.len());
1211    }
1212
1213    #[test]
1214    fn style_budgets_are_configurable() {
1215        let text = format!("{TWO_AGENTS}\n[style]\nterse = false\nmax_detail_chars = 40\n");
1216        let cfg = parse(&text).unwrap();
1217        assert!(!cfg.style.terse);
1218        assert_eq!(40, cfg.style.max_detail_chars);
1219    }
1220}