Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

11.3 KB
Raw Blame
use std::path::Path;

fn read(path: &str) -> String {
    std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join(path)).unwrap()
}

#[test]
fn the_plugin_ships_the_same_skill_and_mcp_server() {
    let mut files = vec![
        "SKILL.md".to_string(),
        "whole-app.md".to_string(),
        "new-app.md".to_string(),
    ];
    for entry in std::fs::read_dir(
        Path::new(env!("CARGO_MANIFEST_DIR")).join("skills/rust-anything/languages"),
    )
    .unwrap()
    {
        let name = entry.unwrap().file_name().to_string_lossy().into_owned();
        files.push(format!("languages/{name}"));
    }
    for dir in ["plugin", "directory"] {
        for file in &files {
            let source = read(&format!("skills/rust-anything/{file}"));
            let expected = if dir == "directory" && file == "SKILL.md" {
                directory_skill(&source)
            } else {
                source
            };
            assert_eq!(
                read(&format!("{dir}/skills/rust-anything/{file}")),
                expected,
                "{dir}/skills/rust-anything/{file} differs from skills/rust-anything/{file}"
            );
        }
    }
    assert_eq!(read("plugin/.mcp.json"), read(".mcp.json"));
}

const DIRECTORY_TOOLS: &str = "Tools: the `rust-anything` CLI (`rust-anything --help` lists every command). `obligations waive`,
`obligations attest` and rust/obligations-bindings.toml hold the user's decisions: do not run or
write them yourself, see \"Rules\" in [whole-app.md](whole-app.md). If `rust-anything` is not
installed, ask the user to install it (`cargo install rust-anything`). When a step fails because a
runtime is missing or out of date, run `rust-anything doctor`: it checks each one and prints the
command that fixes it.";

fn directory_skill(source: &str) -> String {
    let start = source
        .find("Tools: the `rust-anything` CLI, or")
        .expect("the skill's Tools paragraph moved: update directory_skill");
    let end_marker = "prints the command that fixes it.";
    let end = start
        + source[start..]
            .find(end_marker)
            .expect("the skill's Tools paragraph moved: update directory_skill")
        + end_marker.len();
    let skill = format!("{}{DIRECTORY_TOOLS}{}", &source[..start], &source[end..]);
    assert!(
        skill.contains("rust-anything CLI or MCP tools,"),
        "the skill description moved: update directory_skill"
    );
    skill.replacen("rust-anything CLI or MCP tools,", "rust-anything CLI,", 1)
}

#[test]
fn the_directory_skill_never_asks_for_the_mcp_server() {
    let skill = read("directory/skills/rust-anything/SKILL.md");
    for needle in [
        "rust-anything mcp",
        "rust-anything setup",
        "MCP tools",
        "MCP server",
    ] {
        assert!(!skill.contains(needle), "directory skill mentions {needle}");
    }
    let plugin = read("directory/.claude-plugin/plugin.json");
    assert!(
        !plugin.contains("mcp"),
        "directory plugin.json mentions mcp"
    );
}

/// The help of a command of the binary, as a person reads it; `None` if it does not exist.
fn help(args: &[&str]) -> Option<String> {
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_rust-anything"))
        .args(args)
        .arg("--help")
        .output()
        .unwrap();
    out.status
        .success()
        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}

/// `--option` written as a whole word in the help: `--repo` is not found in `--repository`.
fn has_option(help: &str, option: &str) -> bool {
    let pattern = format!(
        r"(^|[^A-Za-z0-9-]){}([^A-Za-z0-9-]|$)",
        regex::escape(option)
    );
    regex::Regex::new(&pattern).unwrap().is_match(help)
}

/// Each `rust-anything ...` command written between backticks in a text of the skill (even when
/// split by a line break; code blocks, which carry comments and commands of the ported project,
/// are left out).
fn cited_commands(text: &str) -> Vec<Vec<String>> {
    let spans = regex::Regex::new(r"`([^`]+)`").unwrap();
    text.split("```")
        .step_by(2)
        .flat_map(|prose| {
            spans
                .captures_iter(prose)
                .map(|c| c[1].split_whitespace().map(str::to_string).collect())
                .collect::<Vec<Vec<String>>>()
        })
        .filter(|words| words.first().map(String::as_str) == Some("rust-anything"))
        .collect()
}

#[test]
fn every_command_and_option_the_skill_cites_exists_as_a_whole_word_in_the_binarys_help() {
    let mut checked = 0;
    let name = regex::Regex::new(r"^[a-z][a-z-]*$").unwrap();
    for file in ["SKILL.md", "whole-app.md"] {
        for words in cited_commands(&read(&format!("skills/rust-anything/{file}"))) {
            let shown = words.join(" ");
            // The subcommand, and the sub-subcommand when there is one (`app lift`).
            let mut path: Vec<&str> = Vec::new();
            let mut rest = words[1..].iter().map(String::as_str).peekable();
            while let Some(word) = rest.peek().copied() {
                if !name.is_match(word) {
                    break;
                }
                let mut tried = path.clone();
                tried.push(word);
                if help(&tried).is_some() {
                    path = tried;
                    rest.next();
                } else {
                    break;
                }
            }
            if words.len() > 1 {
                assert!(
                    !path.is_empty(),
                    "{file}: `{shown}` does not start with a subcommand of the binary"
                );
            }
            let Some(text) = help(&path) else { continue };
            for word in rest.take_while(|w| *w != "--") {
                if word.starts_with("--") {
                    let option = word.trim_end_matches([',', '.', ';', ')']);
                    assert!(
                        has_option(&text, option),
                        "{file}: `{shown}` cites {option}, which `rust-anything {} --help` does not list",
                        path.join(" ")
                    );
                    checked += 1;
                }
            }
        }
    }
    assert!(
        checked >= 8,
        "only {checked} options checked: the extraction found too little"
    );
}

#[test]
fn an_option_renamed_to_a_longer_one_is_not_found_by_the_whole_word_check() {
    assert!(has_option("  --repo <REPO>  where", "--repo"));
    assert!(!has_option("  --repository <REPO>  where", "--repo"));
    assert!(!has_option("  --no-repo  where", "--repo"));
}

#[test]
fn the_skill_names_the_registry_commands_files_variable_and_tools_of_the_binary() {
    let guide = read("skills/rust-anything/whole-app.md");
    let one_line = guide.split_whitespace().collect::<Vec<_>>().join(" ");
    for sub in ["waive", "attest", "fallbacks"] {
        assert!(
            one_line.contains(&format!("obligations {sub}")),
            "the guide does not cite `obligations {sub}`"
        );
    }
    // The journal variable and the files are those of the code, not copies.
    assert!(guide.contains(rust_anything::app::JOURNAL_ENV));
    assert!(guide.contains(rust_anything::obligations::evidence::BINDINGS_FILE));
    for file in [
        "rust/obligations-decisions.toml",
        "rust/obligations-fallbacks.jsonl",
    ] {
        assert!(guide.contains(file), "the guide no longer cites {file}");
    }
    // The three MCP tools of the registry, as `tools/list` names them.
    let skill = read("skills/rust-anything/SKILL.md");
    for tool in ["obligations", "obligations_check", "obligations_fallbacks"] {
        assert!(
            skill.contains(&format!("`{tool}`")),
            "SKILL.md omits {tool}"
        );
    }
    // What a binding is: the three keys that the file's reader requires.
    for key in ["`obligation`", "`cases`", "`reason`", "[[bind]]"] {
        assert!(guide.contains(key), "the guide does not describe {key}");
    }
}

#[test]
fn each_of_the_four_rules_is_pinned_on_the_sentence_that_forbids() {
    let guide = read("skills/rust-anything/whole-app.md");
    let rules = guide
        .split("\n## Rules\n")
        .nth(1)
        .expect("the guide has a Rules section");
    let numbered = regex::Regex::new(r"(?m)^\d\. ").unwrap();
    let items: Vec<String> = numbered
        .split(rules)
        .skip(1)
        .map(|r| r.split_whitespace().collect::<Vec<_>>().join(" "))
        .collect();
    assert_eq!(items.len(), 4, "{items:#?}");
    let pins: [&[&str]; 4] = [
        &[
            "Never declare the port finished",
            "lists a blocker or fails",
            "the items waived, the families attested and the obligations bound by hand",
        ],
        &[
            "Never run `rust-anything obligations waive` or `obligations attest` on your own initiative",
            "never write a binding on your own either",
        ],
        &[
            "Never delete or hand-edit `rust/obligations-decisions.toml`, `rust/obligations-fallbacks.jsonl`",
            "never to a case that fails or does not reach the obligation",
        ],
        &["Never change a recorded case to make a port match"],
    ];
    for (n, (item, phrases)) in items.iter().zip(pins).enumerate() {
        for phrase in phrases {
            assert!(item.contains(phrase), "rule {}: `{phrase}` is gone", n + 1);
        }
    }
}

#[test]
fn the_skill_description_names_every_language_the_crate_does() {
    let skill = read("skills/rust-anything/SKILL.md");
    let languages = env!("CARGO_PKG_DESCRIPTION").rsplit_once(". ").unwrap().1;
    assert!(
        skill.contains(languages),
        "the skill description is missing {languages}"
    );
}

#[test]
fn the_plugin_version_is_the_crate_version() {
    for dir in ["plugin", "directory"] {
        let plugin: serde_json::Value =
            serde_json::from_str(&read(&format!("{dir}/.claude-plugin/plugin.json"))).unwrap();
        assert_eq!(plugin["version"], env!("CARGO_PKG_VERSION"), "{dir}");
    }
}

#[test]
fn plugin_install_docs_use_marketplace_id_not_flag() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let mut paths = vec![root.join("docs/install.md")];
    for entry in std::fs::read_dir(root.join("website/pages")).unwrap() {
        let lang = entry.unwrap().path();
        if !lang.is_dir() {
            continue;
        }
        for page in ["install.md", "agents.md"] {
            let p = lang.join("docs/introduction").join(page);
            if p.exists() {
                paths.push(p);
            }
        }
    }
    assert!(
        paths.len() > 1,
        "expected website/pages/*/docs/introduction/{{install,agents}}.md"
    );
    for path in paths {
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(
            !text.contains("--marketplace"),
            "{} still contains --marketplace",
            path.display()
        );
        let install_lines: Vec<&str> = text
            .lines()
            .filter(|line| line.contains("plugin install "))
            .collect();
        assert!(
            !install_lines.is_empty(),
            "{} has no `plugin install` line",
            path.display()
        );
        for line in install_lines {
            assert!(
                line.contains("rust-anything@rust-anything"),
                "{}: unexpected plugin install line: {line}",
                path.display()
            );
        }
    }
}