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}
43
44/// One declared check.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct Check {
47    /// Table name, e.g. `test` for `[checks.test]`.
48    pub name: String,
49    /// Program and arguments; run without a shell.
50    pub argv: Vec<String>,
51    /// Working directory relative to the root (`.` by default).
52    pub cwd: String,
53    /// Only applicable when this root-relative path exists.
54    pub when_exists: Option<String>,
55    /// `fast` (default) or `full`.
56    pub tier: Tier,
57    /// Deadline for the whole process group.
58    pub timeout: Duration,
59    /// Root-relative JUnit report the check writes.
60    pub junit: Option<String>,
61}
62
63/// The top-level sections of `speccoder.toml`.
64pub const SECTIONS: &[&str] = &[
65    "checks",
66    "model",
67    "budget",
68    "commands",
69    "git",
70    "acceptance",
71    "tests",
72    "monitor",
73    "converge",
74    "review",
75    "format",
76    "sandbox",
77    "mutation",
78    "executor",
79    "mcp",
80    "spec",
81    "approvals",
82    "attest",
83    "context",
84    "bug",
85];
86
87/// Parses the configuration text; checks keep their file order.
88pub fn parse(text: &str) -> Result<Vec<Check>, String> {
89    let table: toml::Table = toml::from_str(text).map_err(|e| e.to_string())?;
90    // A misspelled section would otherwise be silently ignored by every
91    // command; the other sections are read (and their keys checked) by the
92    // modules that own them.
93    // A person's UI settings are not the project's policy.
94    if table.contains_key("ui") {
95        return Err(format!(
96            "[ui] is a person's setting, not project policy; move it to {}",
97            crate::user_config::path().map_or_else(
98                || "~/.config/speccoder/config.toml".to_owned(),
99                |p| p.display().to_string()
100            )
101        ));
102    }
103    if let Some(unknown) = table.keys().find(|k| !SECTIONS.contains(&k.as_str())) {
104        return Err(format!(
105            "unknown section `[{unknown}]` (known: {})",
106            SECTIONS.join(", ")
107        ));
108    }
109    let Some(checks) = table.get("checks") else {
110        return Ok(Vec::new());
111    };
112    let checks = checks
113        .as_table()
114        .ok_or_else(|| "`checks` must be a table of [checks.<name>] tables".to_owned())?;
115    checks
116        .iter()
117        .map(|(name, value)| {
118            let raw: RawCheck = value
119                .clone()
120                .try_into()
121                .map_err(|e| format!("[checks.{name}]: {e}"))?;
122            if raw.argv.is_empty() || raw.argv[0].is_empty() {
123                return Err(format!("[checks.{name}]: `argv` must name a program"));
124            }
125            Ok(Check {
126                name: name.clone(),
127                argv: raw.argv,
128                cwd: raw.cwd.unwrap_or_else(|| ".".to_owned()),
129                when_exists: raw.when_exists,
130                tier: raw.tier.unwrap_or(Tier::Fast),
131                timeout: Duration::from_secs(raw.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS)),
132                junit: raw.junit,
133            })
134        })
135        .collect()
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn a_misspelled_section_is_an_error_not_ignored() {
144        let e = parse("[checks.t]\nargv = [\"true\"]\n[budgett]\nmax_turns = 3\n").unwrap_err();
145        assert!(e.contains("unknown section `[budgett]`"), "{e}");
146        assert!(parse("[checks.t]\nargv = [\"true\"]\n[sandbox]\nmode = \"off\"\n").is_ok());
147    }
148
149    #[test]
150    fn parses_checks_in_file_order_with_defaults() {
151        let checks = parse(
152            r#"
153[model]
154provider = "anthropic"
155
156[checks.test]
157argv = ["cargo", "nextest", "run"]
158junit = "target/nextest/speccoder/junit.xml"
159when_exists = "Cargo.toml"
160
161[checks.clippy]
162argv = ["cargo", "clippy"]
163tier = "full"
164timeout_secs = 30
165"#,
166        )
167        .unwrap();
168        let names: Vec<_> = checks.iter().map(|c| c.name.as_str()).collect();
169        assert_eq!(names, ["test", "clippy"]);
170        assert_eq!(checks[0].tier, Tier::Fast);
171        assert_eq!(checks[0].cwd, ".");
172        assert_eq!(checks[0].timeout, Duration::from_secs(600));
173        assert_eq!(checks[1].tier, Tier::Full);
174        assert_eq!(checks[1].timeout, Duration::from_secs(30));
175    }
176
177    #[test]
178    fn rejects_unknown_keys_and_empty_argv() {
179        let e = parse("[checks.t]\nargv = [\"x\"]\nshell = true\n").unwrap_err();
180        assert!(e.contains("[checks.t]") && e.contains("shell"), "{e}");
181        assert!(
182            parse("[checks.t]\nargv = []\n")
183                .unwrap_err()
184                .contains("argv")
185        );
186    }
187}