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