spock-cli 0.4.0

A model checker for specs that read like Rust: TLA's logic of actions, checked on every core in machine code
//! `spock skill` and the skill it prints, `SKILL.md`: its frontmatter is what agents read to
//! know when to use it, its example spec checks, and each `spock` command in it prints what
//! the skill shows, but for how long it took.

use std::{fs, path::Path, process::Command};

const SKILL: &str = include_str!("../SKILL.md");

struct Run {
    code: i32,
    stdout: String,
}

fn spock(dir: &Path, args: &[&str]) -> Run {
    let output = Command::new(env!("CARGO_BIN_EXE_spock"))
        .current_dir(dir)
        .env("SPOCK_CACHE_DIR", dir.join("cache"))
        .env("NO_COLOR", "1")
        .args(args)
        .output()
        .expect("spock runs");
    Run {
        code: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
    }
}

/// The text of each block fenced as `lang` in the skill, in order.
fn blocks(lang: &str) -> Vec<&'static str> {
    let fence = format!("```{lang}\n");
    SKILL
        .split(fence.as_str())
        .skip(1)
        .map(|rest| &rest[..rest.find("```\n").expect("a closing fence")])
        .collect()
}

/// `text` without how long a check took: "(13 generated in 0.01 s)" reads "in T s)".
fn untimed(text: &str) -> String {
    text.lines()
        .map(|line| match line.rfind(" generated in ") {
            Some(at) if line.ends_with(" s)") => format!("{} generated in T s)", &line[..at]),
            _ => line.to_owned(),
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// `spec` without its line `line`, which it has once.
fn without(spec: &str, line: &str) -> String {
    assert_eq!(spec.matches(line).count(), 1, "{line}");
    spec.replacen(line, "", 1)
}

#[test]
fn spock_skill_prints_the_skill_anywhere() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    let run = spock(dir.path(), &["skill"]);
    assert_eq!(run.code, 0);
    assert_eq!(run.stdout, SKILL);
}

#[test]
fn the_skill_says_what_it_is_and_when_to_use_it() {
    let (front, _) = SKILL
        .strip_prefix("---\n")
        .and_then(|rest| rest.split_once("\n---\n"))
        .expect("YAML frontmatter");
    let lines: Vec<&str> = front.lines().collect();
    assert_eq!(lines.len(), 2, "{front}");
    assert_eq!(lines[0], "name: spock");
    let description = lines[1].strip_prefix("description: ").expect("a description");
    // A plain YAML scalar: no ": " or " #" in it, and one line. Agents read 1,024 characters.
    assert!(!description.contains(": ") && !description.contains(" #"), "{description}");
    assert!(description.len() <= 1024, "{}", description.len());
    assert!(description.contains("Use when"), "{description}");
}

#[test]
fn each_command_in_the_skill_prints_what_it_shows() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    let jobs = blocks("rust")
        .into_iter()
        .find(|block| block.starts_with("// Workers take jobs"))
        .expect("the example spec");
    // The two changes the skill describes.
    let bug = without(jobs, "        require self.status[w] == Idle;\n");
    let unfair = without(jobs, "    fairness = [weakly_fair(|s: State| s.next())];\n");
    let [run] = blocks("json")[..] else { panic!("one JSON block, the trace") };
    for (name, text) in [
        ("jobs.spock", jobs),
        ("jobs_bug.spock", &bug),
        ("jobs_unfair.spock", &unfair),
        ("run.jsonl", run),
    ] {
        fs::write(dir.path().join(name), text).unwrap();
    }
    let mut codes = Vec::new();
    for block in blocks("console") {
        // Each command, then what it prints, up to the next command.
        let mut commands: Vec<(&str, String)> = Vec::new();
        for line in block.lines() {
            match line.strip_prefix("$ ") {
                Some(command) => commands.push((command, String::new())),
                None => {
                    let (_, shown) = commands.last_mut().expect("a command first");
                    shown.push_str(line);
                    shown.push('\n');
                }
            }
        }
        for (command, shown) in commands {
            let Some(args) = command.strip_prefix("spock ") else {
                assert_eq!(command, "cargo install --locked spock-cli");
                continue;
            };
            let args: Vec<&str> = args.split_whitespace().collect();
            let run = spock(dir.path(), &args);
            assert_eq!(untimed(&run.stdout), untimed(&shown), "$ {command}");
            codes.push(run.code);
        }
    }
    // The example's models hold, the bug breaks an invariant, the model without fairness a
    // property, and no behavior matches the trace.
    assert_eq!(codes, [0, 0, 12, 13, 14]);
}