Skip to main content

speccoder_runtime/verify/
config.rs

1//! `speccoder.toml`: the checks a project declares.
2
3use std::time::Duration;
4
5use serde::Deserialize;
6
7/// The configuration file, at the project root.
8pub const FILE: &str = "speccoder.toml";
9
10const DEFAULT_TIMEOUT_SECS: u64 = 600;
11
12/// When a check runs.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum Tier {
16    /// Every task.
17    Fast,
18    /// Once after a run ticks the feature's last task, and with `speccoder verify`.
19    Full,
20}
21
22impl Tier {
23    /// Lowercase name.
24    #[must_use]
25    pub const fn as_str(self) -> &'static str {
26        match self {
27            Self::Fast => "fast",
28            Self::Full => "full",
29        }
30    }
31}
32
33#[derive(Debug, Deserialize)]
34#[serde(deny_unknown_fields)]
35struct RawCheck {
36    argv: Vec<String>,
37    cwd: Option<String>,
38    when_exists: Option<String>,
39    tier: Option<Tier>,
40    timeout_secs: Option<u64>,
41    junit: Option<String>,
42    list: Option<Vec<String>>,
43}
44
45/// One declared check.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Check {
48    /// Table name, e.g. `test` for `[checks.test]`.
49    pub name: String,
50    /// Program and arguments; run without a shell.
51    pub argv: Vec<String>,
52    /// Working directory relative to the root (`.` by default).
53    pub cwd: String,
54    /// Only applicable when this root-relative path exists.
55    pub when_exists: Option<String>,
56    /// `fast` (default) or `full`.
57    pub tier: Tier,
58    /// Deadline for the whole process group.
59    pub timeout: Duration,
60    /// Root-relative JUnit report the check writes.
61    pub junit: Option<String>,
62    /// A command listing the tests the check would run (one test id or
63    /// file path per line), for deciding which test files it collects.
64    pub list: Option<Vec<String>>,
65}
66
67/// The top-level sections of `speccoder.toml`.
68pub const SECTIONS: &[&str] = &[
69    "checks",
70    "model",
71    "budget",
72    "commands",
73    "git",
74    "acceptance",
75    "tests",
76    "monitor",
77    "converge",
78    "review",
79    "format",
80    "sandbox",
81    "mutation",
82    "executor",
83    "mcp",
84    "spec",
85    "approvals",
86    "attest",
87    "context",
88    "bug",
89];
90
91/// Parses the configuration text; checks keep their file order.
92pub fn parse(text: &str) -> Result<Vec<Check>, String> {
93    let table: toml::Table = toml::from_str(text).map_err(|e| e.to_string())?;
94    // A misspelled section would otherwise be silently ignored by every
95    // command; the other sections are read (and their keys checked) by the
96    // modules that own them.
97    // A person's UI settings are not the project's policy.
98    if table.contains_key("ui") {
99        return Err(format!(
100            "[ui] is a person's setting, not project policy; move it to {}",
101            crate::user_config::path().map_or_else(
102                || "~/.config/speccoder/config.toml".to_owned(),
103                |p| p.display().to_string()
104            )
105        ));
106    }
107    if let Some(unknown) = table.keys().find(|k| !SECTIONS.contains(&k.as_str())) {
108        return Err(format!(
109            "unknown section `[{unknown}]` (known: {})",
110            SECTIONS.join(", ")
111        ));
112    }
113    let Some(checks) = table.get("checks") else {
114        return Ok(Vec::new());
115    };
116    let checks = checks
117        .as_table()
118        .ok_or_else(|| "`checks` must be a table of [checks.<name>] tables".to_owned())?;
119    checks
120        .iter()
121        .map(|(name, value)| {
122            let raw: RawCheck = value
123                .clone()
124                .try_into()
125                .map_err(|e| format!("[checks.{name}]: {e}"))?;
126            if raw.argv.is_empty() || raw.argv[0].is_empty() {
127                return Err(format!("[checks.{name}]: `argv` must name a program"));
128            }
129            Ok(Check {
130                name: name.clone(),
131                argv: raw.argv,
132                cwd: raw.cwd.unwrap_or_else(|| ".".to_owned()),
133                when_exists: raw.when_exists,
134                tier: raw.tier.unwrap_or(Tier::Fast),
135                timeout: Duration::from_secs(raw.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS)),
136                junit: raw.junit,
137                list: raw
138                    .list
139                    .filter(|l| l.first().is_some_and(|p| !p.is_empty())),
140            })
141        })
142        .collect()
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn a_misspelled_section_is_an_error_not_ignored() {
151        let e = parse("[checks.t]\nargv = [\"true\"]\n[budgett]\nmax_turns = 3\n").unwrap_err();
152        assert!(e.contains("unknown section `[budgett]`"), "{e}");
153        assert!(parse("[checks.t]\nargv = [\"true\"]\n[sandbox]\nmode = \"off\"\n").is_ok());
154    }
155
156    #[test]
157    fn parses_checks_in_file_order_with_defaults() {
158        let checks = parse(
159            r#"
160[model]
161provider = "anthropic"
162
163[checks.test]
164argv = ["cargo", "nextest", "run"]
165junit = "target/nextest/speccoder/junit.xml"
166when_exists = "Cargo.toml"
167
168[checks.clippy]
169argv = ["cargo", "clippy"]
170tier = "full"
171timeout_secs = 30
172"#,
173        )
174        .unwrap();
175        let names: Vec<_> = checks.iter().map(|c| c.name.as_str()).collect();
176        assert_eq!(names, ["test", "clippy"]);
177        assert_eq!(checks[0].tier, Tier::Fast);
178        assert_eq!(checks[0].cwd, ".");
179        assert_eq!(checks[0].timeout, Duration::from_secs(600));
180        assert_eq!(checks[1].tier, Tier::Full);
181        assert_eq!(checks[1].timeout, Duration::from_secs(30));
182        assert_eq!(checks[0].list, None);
183        let listed = parse("[checks.t]\nargv = [\"x\"]\nlist = [\"x\", \"--list\"]\n").unwrap();
184        assert_eq!(
185            listed[0].list.as_deref(),
186            Some(&["x".to_owned(), "--list".to_owned()][..])
187        );
188    }
189
190    #[test]
191    fn rejects_unknown_keys_and_empty_argv() {
192        let e = parse("[checks.t]\nargv = [\"x\"]\nshell = true\n").unwrap_err();
193        assert!(e.contains("[checks.t]") && e.contains("shell"), "{e}");
194        assert!(
195            parse("[checks.t]\nargv = []\n")
196                .unwrap_err()
197                .contains("argv")
198        );
199    }
200}