cargo-tops 0.5.0

init / check / gate for the Rust-TOPS protocol. Orchestrates existing Cargo tools; does not replace them.
//! Canonical JSON of `TopsConfig` for every bundled profile.
//!
//! Recorded from main `968c390` by decoding with serde_yaml 0.9.34 into this
//! struct (free-form fields as `serde_json::Value`) and sorting object keys.
//! `crate.msrv` is not a field, so it is absent. The templates match that
//! commit; `rust-tops.yaml` there differs from this branch in `msrv` and in
//! what [`without_kit_drop_in`] checks and undoes.
//!
//! `RUST_TOPS_BLESS` rewrites these files for a local re-record.
//! CI does not set it.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
use std::fs;
use std::path::PathBuf;

use super::config::TopsConfig;
use super::{check, load_config};

const CLASSES: &[&str] = &[
    "library-core",
    "parser-codec",
    "no-std-embedded",
    "unsafe-kernel",
    "binary-cli",
];

fn golden_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden/config")
}

fn canonical(value: serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::Array(items) => {
            serde_json::Value::Array(items.into_iter().map(canonical).collect())
        }
        serde_json::Value::Object(map) => {
            let mut keys: Vec<String> = map.keys().cloned().collect();
            keys.sort();
            let mut out = serde_json::Map::new();
            for key in keys {
                #[expect(
                    clippy::indexing_slicing,
                    reason = "already in this crate when the strict table was turned on"
                )]
                let child = canonical(map[&key].clone());
                out.insert(key, child);
            }
            serde_json::Value::Object(out)
        }
        other => other,
    }
}

fn config_json(cfg: &TopsConfig) -> serde_json::Value {
    canonical(serde_json::to_value(cfg).expect("config serializes to json"))
}

fn load_yaml(label: &str, yaml: &str) -> TopsConfig {
    let dir = std::env::temp_dir().join(format!("cargo-tops-parse-{label}-{}", std::process::id()));
    #[expect(
        clippy::let_underscore_must_use,
        reason = "already in this crate when the strict table was turned on"
    )]
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap_or_else(|err| panic!("mkdir {label}: {err}"));
    fs::write(dir.join("rust-tops.yaml"), yaml)
        .unwrap_or_else(|err| panic!("write {label}: {err}"));
    let cfg = load_config(&dir).unwrap_or_else(|err| panic!("parse {label}: {err:#}"));
    check(&cfg).unwrap_or_else(|err| panic!("check {label}: {err:#}"));
    #[expect(
        clippy::let_underscore_must_use,
        reason = "already in this crate when the strict table was turned on"
    )]
    let _ = fs::remove_dir_all(&dir);
    cfg
}

/// Protocol 1.1.0 changed the bundled template in two places: it moved
/// `protocol.version` and added a `laws` layer, which the drop-in pack turned
/// off (D3: adopters opt in). Protocol 1.2.0 moved the version again, 1.3.0 once more, and 1.4.0 again. Check
/// both, then undo them so the rest still compares to the `968c390`
/// serde_yaml oracle.
fn without_protocol_1_1(mut value: serde_json::Value) -> serde_json::Value {
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_idx_86_16 = value["protocol"]["version"].clone();
    assert_eq!(tops_idx_86_16, "1.4.0");
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_slot_90 = &mut value["protocol"]["version"];
    *tops_slot_90 = serde_json::Value::from("1.0.0");
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let layers = value["layers"].as_array_mut().expect("layers array");
    let laws: Vec<serde_json::Value> = layers
        .iter()
        .filter(|layer| layer["id"] == "laws")
        .cloned()
        .collect();
    assert_eq!(
        laws,
        [serde_json::json!({"enabled": false, "id": "laws", "runner": "bend", "tier": 0})],
        "template must carry one disabled tier-0 laws layer"
    );
    layers.retain(|layer| layer["id"] != "laws");
    value
}

/// The floors pack types the keys the gate now judges. The oracle typed
/// none of them, so drop them and the rest still compares to `968c390`.
fn without_judged_floors(mut value: serde_json::Value) -> serde_json::Value {
    let keys: [(&str, &[&str]); 2] = [
        (
            "/gates/coverage",
            &["region_min_pct", "per_file_line_min_pct", "exclude_globs"],
        ),
        (
            "/gates/crap",
            &["threshold_production", "fail_on", "baseline"],
        ),
    ];
    for (pointer, names) in keys {
        let map = value
            .pointer_mut(pointer)
            .and_then(serde_json::Value::as_object_mut)
            .expect("the config has the gate");
        for name in names {
            map.remove(*name);
        }
    }
    value
}

/// The unmapped-layers pack turned `acceptance` off in the bundled template:
/// it has no command, and an enabled layer with none fails the gate. Check
/// that, then undo it so the rest still compares to the `968c390` oracle.
fn with_acceptance_restored(mut value: serde_json::Value) -> serde_json::Value {
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let layers = value["layers"].as_array_mut().expect("layers array");
    let acceptance = layers
        .iter_mut()
        .find(|layer| layer["id"] == "acceptance")
        .expect("template has an acceptance layer");
    assert_eq!(
        acceptance["enabled"], false,
        "template must write acceptance off"
    );
    acceptance["enabled"] = serde_json::Value::from(true);
    value
}

/// The profiles pack writes each class's CRAP numbers from `profiles/`. Of
/// the oracle classes only binary-cli moved: agent 6 to 8 (PROTOCOL.md §4).
/// Check that, then undo it so the rest still compares to the `968c390` oracle.
fn with_template_crap(class: &str, mut value: serde_json::Value) -> serde_json::Value {
    if class == "binary-cli" {
        #[expect(
            clippy::indexing_slicing,
            reason = "already in this crate when the strict table was turned on"
        )]
        let agent = &mut value["gates"]["crap"]["threshold_agent"];
        assert_eq!(*agent, serde_json::json!(8.0), "binary-cli agent CRAP");
        *agent = serde_json::json!(6.0);
    }
    value
}

/// The drop-in pack fixed the kit's own `rust-tops.yaml` (K5): protocol
/// 1.1.0 (1.4.0 since the honest pack), `laws` on, `acceptance` off, no `release_profile`, and no
/// `src/generated/**` exemption. Check that, then undo it so the rest still
/// compares to the `968c390` oracle.
#[expect(clippy::too_many_lines, reason = "over the kit line threshold")]
fn without_kit_drop_in(mut value: serde_json::Value) -> serde_json::Value {
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_idx_158_16 = value["protocol"]["version"].clone();
    assert_eq!(tops_idx_158_16, "1.4.0");
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_slot_161 = &mut value["protocol"]["version"];
    *tops_slot_161 = serde_json::Value::from("1.0.0");
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let layers = value["layers"].as_array_mut().expect("layers array");
    let laws: Vec<serde_json::Value> = layers
        .iter()
        .filter(|layer| layer["id"] == "laws")
        .cloned()
        .collect();
    assert_eq!(
        laws,
        [serde_json::json!({"enabled": true, "id": "laws", "runner": "bend", "tier": 0})],
        "the kit must judge its own laws"
    );
    layers.retain(|layer| layer["id"] != "laws");
    let mut value = with_acceptance_restored(value);
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_idx_187_9 = value["performance"].clone();
    assert_eq!(
        tops_idx_187_9.get("release_profile"),
        None,
        "Cargo.toml has no [profile.release]"
    );
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_slot_192 = &mut value["performance"]["release_profile"];
    *tops_slot_192 = serde_json::json!({
        "codegen-units": 1, "debug": 0, "lto": "thin", "opt-level": 3, "panic": "abort",
    });
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_idx_203_16 = value["exemptions"].clone();
    assert_eq!(tops_idx_203_16, serde_json::json!([]));
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_slot_204 = &mut value["exemptions"];
    *tops_slot_204 = serde_json::json!([{
        "expires": "2027-09-24", "layer": "crap", "owner": "platform",
        "path": "src/generated/**",
        "reason": "generated protobuf; public decode roundtrip is the oracle",
    }]);
    value
}

fn expect_value(name: &str, value: serde_json::Value) {
    let path = golden_dir().join(format!("{name}.json"));
    if std::env::var_os("RUST_TOPS_BLESS").is_some() {
        fs::create_dir_all(golden_dir()).unwrap_or_else(|err| panic!("mkdir golden: {err}"));
        #[expect(
            clippy::string_add,
            reason = "already in this crate when the strict table was turned on"
        )]
        let pretty = serde_json::to_string_pretty(&value).expect("pretty json") + "\n";
        fs::write(&path, pretty).unwrap_or_else(|err| panic!("write {}: {err}", path.display()));
        return;
    }
    let expected = fs::read_to_string(&path)
        .unwrap_or_else(|err| panic!("missing golden {}: {err}", path.display()));
    let expected_value: serde_json::Value =
        serde_json::from_str(&expected).unwrap_or_else(|err| panic!("golden {name} json: {err}"));
    assert_eq!(
        value, expected_value,
        "bundled profile {name} no longer parses to the pre-migration config"
    );
}

#[test]
fn bundled_profile_templates_parse_to_pre_migration_config() {
    for class in CLASSES {
        let yaml = super::profiles::profile_yaml(class, "golden-crate").expect("profile merges");
        let cfg = load_yaml(class, &yaml);
        assert_eq!(cfg.crate_.name, "golden-crate");
        assert_eq!(cfg.crate_.class, *class);
        assert_eq!(cfg.protocol.id, "rust-tops");
        expect_value(
            class,
            with_template_crap(
                class,
                with_acceptance_restored(without_protocol_1_1(without_judged_floors(config_json(
                    &cfg,
                )))),
            ),
        );
    }
}

#[test]
fn workspace_instance_parses_to_pre_migration_config() {
    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
    let instance = root.join("rust-tops.yaml");
    assert!(
        instance.is_file(),
        "workspace golden requires {}",
        instance.display()
    );
    let cfg = load_config(&root).unwrap_or_else(|err| panic!("parse workspace instance: {err:#}"));
    check(&cfg).unwrap_or_else(|err| panic!("check workspace instance: {err:#}"));
    assert_eq!(cfg.crate_.name, "cargo-tops");
    assert_eq!(cfg.crate_.class, "binary-cli");
    // `unsafe_policy` is not a config field; the workspace forbids unsafe.
    let raw = fs::read_to_string(&instance).expect("read workspace instance");
    let doc = super::facts::parse_yaml(&raw).expect("workspace instance parses");
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_idx_277_16 = doc["crate"]["unsafe_policy"].clone();
    assert_eq!(tops_idx_277_16, "forbid");
    expect_value(
        "workspace",
        without_kit_drop_in(without_judged_floors(config_json(&cfg))),
    );
}

const YAML11_BOOL_WORDS: &[&str] = &["yes", "no", "on", "off", "y", "n"];

fn strict_bool_yaml() -> String {
    include_str!("../tests/golden/strict-bool/instance.yaml").to_string()
}

/// Pins `strict_booleans`. This file is the serde-saphyr decode, not the
/// `968c390` serde_yaml oracle above.
#[test]
fn strict_booleans_keep_yaml11_words_as_strings() {
    let path = PathBuf::from("strict-bool/rust-tops.yaml");
    let cfg = super::parse_config(&path, &strict_bool_yaml())
        .unwrap_or_else(|err| panic!("parse strict-bool: {err:#}"));
    let goals = config_json(&cfg)
        .get("goals")
        .cloned()
        .expect("goals present");
    let path =
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden/strict-bool/goals.json");
    let expected: serde_json::Value = serde_json::from_str(
        &fs::read_to_string(&path).unwrap_or_else(|err| panic!("read {}: {err}", path.display())),
    )
    .expect("strict-bool goals golden");
    assert_eq!(goals, expected);
    #[expect(
        clippy::indexing_slicing,
        reason = "already in this crate when the strict table was turned on"
    )]
    let tops_idx_309_13 = &cfg.layers[0];
    assert!(tops_idx_309_13.enabled);
}

#[test]
fn strict_booleans_reject_yaml11_words_on_typed_bool() {
    let base = strict_bool_yaml();
    for word in YAML11_BOOL_WORDS {
        let yaml = base.replace("enabled: true", &format!("enabled: {word}"));
        let dir =
            std::env::temp_dir().join(format!("cargo-tops-bool-{word}-{}", std::process::id()));
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap_or_else(|err| panic!("mkdir {word}: {err}"));
        fs::write(dir.join("rust-tops.yaml"), yaml)
            .unwrap_or_else(|err| panic!("write {word}: {err}"));
        let err = match load_config(&dir) {
            Err(err) => err,
            Ok(_) => panic!("typed bool accepted {word}"),
        };
        let message = format!("{err:#}");
        assert!(
            message.contains("invalid boolean"),
            "enabled: {word} did not reject as a strict bool: {message}"
        );
        #[expect(
            clippy::let_underscore_must_use,
            reason = "already in this crate when the strict table was turned on"
        )]
        let _ = fs::remove_dir_all(&dir);
    }
}