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    "ask",
79    "ladder",
80    "review",
81    "format",
82    "sandbox",
83    "mutation",
84    "executor",
85    "mcp",
86    "spec",
87    "approvals",
88    "attest",
89    "context",
90    "bug",
91    "worktree",
92];
93
94/// Parses the configuration text; checks keep their file order.
95pub fn parse(text: &str) -> Result<Vec<Check>, String> {
96    let table: toml::Table = toml::from_str(text).map_err(|e| e.to_string())?;
97    // A misspelled section would otherwise be silently ignored by every
98    // command; the other sections are read (and their keys checked) by the
99    // modules that own them.
100    // A person's UI settings are not the project's policy.
101    if table.contains_key("ui") {
102        return Err(format!(
103            "[ui] is a person's setting, not project policy; move it to {}",
104            crate::user_config::path().map_or_else(
105                || "~/.config/speccoder/config.toml".to_owned(),
106                |p| p.display().to_string()
107            )
108        ));
109    }
110    if let Some(unknown) = table.keys().find(|k| !SECTIONS.contains(&k.as_str())) {
111        return Err(format!(
112            "unknown section `[{unknown}]` (known: {})",
113            SECTIONS.join(", ")
114        ));
115    }
116    let Some(checks) = table.get("checks") else {
117        return Ok(Vec::new());
118    };
119    let checks = checks
120        .as_table()
121        .ok_or_else(|| "`checks` must be a table of [checks.<name>] tables".to_owned())?;
122    checks
123        .iter()
124        .map(|(name, value)| {
125            let raw: RawCheck = value
126                .clone()
127                .try_into()
128                .map_err(|e| format!("[checks.{name}]: {e}"))?;
129            if raw.argv.is_empty() || raw.argv[0].is_empty() {
130                return Err(format!("[checks.{name}]: `argv` must name a program"));
131            }
132            Ok(Check {
133                name: name.clone(),
134                argv: raw.argv,
135                cwd: raw.cwd.unwrap_or_else(|| ".".to_owned()),
136                when_exists: raw.when_exists,
137                tier: raw.tier.unwrap_or(Tier::Fast),
138                timeout: Duration::from_secs(raw.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS)),
139                junit: raw.junit,
140                list: raw
141                    .list
142                    .filter(|l| l.first().is_some_and(|p| !p.is_empty())),
143            })
144        })
145        .collect()
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn a_misspelled_section_is_an_error_not_ignored() {
154        let e = parse("[checks.t]\nargv = [\"true\"]\n[budgett]\nmax_turns = 3\n").unwrap_err();
155        assert!(e.contains("unknown section `[budgett]`"), "{e}");
156        assert!(parse("[checks.t]\nargv = [\"true\"]\n[sandbox]\nmode = \"off\"\n").is_ok());
157    }
158
159    #[test]
160    fn parses_checks_in_file_order_with_defaults() {
161        let checks = parse(
162            r#"
163[model]
164provider = "anthropic"
165
166[checks.test]
167argv = ["cargo", "nextest", "run"]
168junit = "target/nextest/speccoder/junit.xml"
169when_exists = "Cargo.toml"
170
171[checks.clippy]
172argv = ["cargo", "clippy"]
173tier = "full"
174timeout_secs = 30
175"#,
176        )
177        .unwrap();
178        let names: Vec<_> = checks.iter().map(|c| c.name.as_str()).collect();
179        assert_eq!(names, ["test", "clippy"]);
180        assert_eq!(checks[0].tier, Tier::Fast);
181        assert_eq!(checks[0].cwd, ".");
182        assert_eq!(checks[0].timeout, Duration::from_secs(600));
183        assert_eq!(checks[1].tier, Tier::Full);
184        assert_eq!(checks[1].timeout, Duration::from_secs(30));
185        assert_eq!(checks[0].list, None);
186        let listed = parse("[checks.t]\nargv = [\"x\"]\nlist = [\"x\", \"--list\"]\n").unwrap();
187        assert_eq!(
188            listed[0].list.as_deref(),
189            Some(&["x".to_owned(), "--list".to_owned()][..])
190        );
191    }
192
193    #[test]
194    fn rejects_unknown_keys_and_empty_argv() {
195        let e = parse("[checks.t]\nargv = [\"x\"]\nshell = true\n").unwrap_err();
196        assert!(e.contains("[checks.t]") && e.contains("shell"), "{e}");
197        assert!(
198            parse("[checks.t]\nargv = []\n")
199                .unwrap_err()
200                .contains("argv")
201        );
202    }
203}