larakiln 0.4.2

Port Laravel PHP apps to a new Laravel runtime (Laravel Rust today) and check nothing was lost: audit, plan, codegen, route parity
//! Scores each inventory item green / yellow / red. Green only for mappings verified against
//! laravel-rust 0.1.4–0.2.0 docs or the spike; anything unknown is yellow (needs a human) or red (no mapping).

use std::fs;
use std::path::Path;

use serde_json::{Value, json};

const SECTIONS: &[&str] = &[
    "routes", "models", "requests", "views", "jobs", "mail", "notifications", "events", "listeners", "observers",
    "commands", "policies", "middleware", "schedule", "packages", "data_risks", "tests",
];

pub fn run(path: &Path) -> Result<(), String> {
    let mut inv = load(path)?;
    score_all(&mut inv);
    fs::write(path, serde_json::to_string_pretty(&inv).unwrap()).map_err(|e| e.to_string())?;
    print!("{}", report(&inv));
    Ok(())
}

pub fn load(path: &Path) -> Result<Value, String> {
    let raw = fs::read_to_string(path).map_err(|e| format!("{}: {e} (run `larakiln audit` first)", path.display()))?;
    serde_json::from_str(&raw).map_err(|e| e.to_string())
}

/// Writes `status` and `reason` into every item.
pub fn score_all(inv: &mut Value) {
    for section in SECTIONS {
        if let Some(items) = inv[*section].as_array_mut() {
            for item in items {
                let (status, reason) = score(section, item);
                item["status"] = json!(status);
                item["reason"] = json!(reason);
            }
        }
    }
}

fn score(section: &str, item: &Value) -> (&'static str, String) {
    match section {
        "routes" => route(item),
        "models" => model(item),
        "requests" => request(item),
        "views" => view(item),
        "packages" => package(item),
        "data_risks" => match item["kind"].as_str() {
            Some("serialized-encrypt") => ("yellow", "Crypt::encrypt() stores PHP serialize() text Rust can't parse; re-encrypt as JSON before cutover".into()),
            Some("sanctum-tokens") => ("yellow", "keep tokens with the Sanctum-compatible RequestGuard (auth-sessions.md)".into()),
            _ => ("green", "PHP encrypted casts decrypt in Rust (Encrypted<T>)".into()),
        },
        "events" => ("green", "#[derive(Event)] struct (add Queueable if a queued listener handles it); dispatch with .dispatch().await? (verified: Chirper)".into()),
        "listeners" => ("green", "#[listener] fn; ShouldQueue → #[listener(queued)], models travel as keys (verified on the database queue: Chirper)".into()),
        "jobs" => ("yellow", "port as #[job]; drain the PHP queue before switching (serialized PHP payloads)".into()),
        "middleware" => ("yellow", "custom middleware: rewrite as async middleware".into()),
        "schedule" => ("green", "recurring tasks map one-to-one".into()),
        "tests" => ("green", "port as #[laravel::test]; doubles as a parity check".into()),
        "notifications" => notification(item),
        "mail" => ("green", "#[derive(Mailable)] with a view extending laravel::mail.message (verified: chirper-tdd)".into()),
        "observers" => ("green", "created/updated/deleted → #[listener] on Event<Created|Updated|Deleted<M>>; creating/updating/deleting → model hooks; saving, retrieved, restored have no event (verified: chirper-tdd)".into()),
        "policies" => ("green", "#[policy] impl in the model file".into()),
        _ => ("yellow", "no reference mapping verified yet".into()),
    }
}

/// Mail notifications are verified (chirper-tdd's queued ChirpCreated); other channels aren't.
fn notification(n: &Value) -> (&'static str, String) {
    let channels: Vec<&str> = n["channels"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
    let other: Vec<&str> = channels.iter().copied().filter(|c| *c != "mail").collect();
    if channels.is_empty() {
        ("yellow", "channels chosen at runtime (via() isn't a plain list); check each one".into())
    } else if other.is_empty() {
        ("green", "#[notification] with a mail() method; queue with notification::to(..).queue(..) (verified)".into())
    } else {
        ("yellow", format!("channel(s) without a verified mapping: {} (queues-mail-events.md)", other.join(", ")))
    }
}

fn route(r: &Value) -> (&'static str, String) {
    let action = r["action"].as_str().unwrap_or("");
    let uri = r["uri"].as_str().unwrap_or("");
    if action.starts_with("Livewire\\") || uri.starts_with("/livewire") {
        ("red", "Livewire route; no Rust equivalent".into())
    } else if action.starts_with("Laravel\\Fortify") && (uri.contains("passkey") || uri.contains("two-factor")) {
        ("yellow", "passkeys / two-factor: no verified Rust equivalent".into())
    } else if action.starts_with("Laravel\\Fortify") {
        ("green", "built-in auth (attempt, registration, verification, password reset); write the handler".into())
    } else if uri == "/up" {
        ("green", "health route: .health(\"/up\") is built in".into())
    } else if action.starts_with("Laravel\\Sanctum") || uri.starts_with("/storage/") || action.starts_with("Laravel\\") {
        ("yellow", "framework/vendor route; decide whether the Rust app needs it".into())
    } else if action == "Closure" {
        ("yellow", "closure route: port the body by hand".into())
    } else {
        ("green", "controller action → handler".into())
    }
}

fn model(m: &Value) -> (&'static str, String) {
    let unknown_casts: Vec<_> = m["casts"]
        .as_object()
        .into_iter()
        .flatten()
        .filter(|(_, t)| {
            let t = t.as_str().unwrap_or("");
            let base = t.split(':').next().unwrap_or("");
            !matches!(
                base,
                "hashed" | "encrypted" | "datetime" | "date" | "immutable_datetime" | "timestamp" | "boolean" | "bool"
                    | "integer" | "int" | "float" | "double" | "decimal" | "string" | "array" | "json" | "object"
                    | "collection"
            )
        })
        .map(|(k, t)| format!("{k}:{}", t.as_str().unwrap_or("")))
        .collect();
    let morphs = m["relations"].as_array().into_iter().flatten().any(|r| r["type"].as_str().is_some_and(|t| t.contains("morph")));
    if !unknown_casts.is_empty() {
        ("yellow", format!("casts need a manual type (enum or custom cast): {}", unknown_casts.join(", ")))
    } else if morphs {
        ("yellow", "polymorphic relations: map with #[morph_to] by hand".into())
    } else {
        ("green", "#[model] struct; columns from the live DB".into())
    }
}

/// PHP rule names with a documented Laravel Rust rule or type (validation.md, 0.1.4).
const KNOWN_RULES: &[&str] = &[
    "required", "string", "email", "url", "uuid", "ulid", "ip", "ipv4", "ipv6", "mac_address", "hex_color", "json",
    "date", "date_format", "timezone", "confirmed", "same", "different", "alpha", "alpha_num", "alpha_dash", "ascii",
    "lowercase", "uppercase", "starts_with", "ends_with", "doesnt_start_with", "doesnt_end_with", "accepted",
    "declined", "filled", "present", "missing", "prohibited", "file", "image", "mimes", "extensions", "digits",
    "digits_between", "min_digits", "max_digits", "decimal", "multiple_of", "between", "gt", "gte", "lt", "lte",
    "after", "after_or_equal", "before", "before_or_equal", "date_equals", "regex", "not_regex", "unique", "exists",
    "bail", "distinct", "required_if", "required_unless", "required_with", "required_with_all", "required_without",
    "required_without_all", "required_if_accepted", "required_if_declined", "prohibited_if", "prohibited_unless",
    "missing_if", "missing_unless", "missing_with", "missing_with_all", "present_if", "present_unless",
    "present_with", "present_with_all", "current_password",
    // Mapped through the field's type or a renamed rule:
    "nullable", "sometimes", "integer", "numeric", "boolean", "array", "in", "not_in", "max", "min",
    "Rule::unique", "Rule::exists", "Rule::in", "Rule::notIn", "Password::defaults", "Password::min",
];

fn request(r: &Value) -> (&'static str, String) {
    if r["rules"].is_null() {
        return ("yellow", "rules built at runtime (variable or method); port by hand".into());
    }
    let mut unknown: Vec<String> = r["rules"]
        .as_object()
        .into_iter()
        .flatten()
        .flat_map(|(_, rules)| rules.as_array().cloned().unwrap_or_default())
        .filter_map(|rule| {
            let rule = rule.as_str()?.to_string();
            if rule.ends_with("::class") {
                return None; // the table of 'unique:'.User::class, not a rule of its own
            }
            let name = if rule.contains("::") { rule.clone() } else { rule.split(':').next().unwrap_or("").to_string() };
            (!KNOWN_RULES.contains(&name.as_str())).then_some(name)
        })
        .collect();
    unknown.sort();
    unknown.dedup();
    if unknown.is_empty() {
        ("green", "every rule has a documented #[validate] equivalent".into())
    } else {
        ("yellow", format!("rules without a verified mapping: {}", unknown.join(", ")))
    }
}

/// Blade directives with a mapping verified in blade-to-jinja.md.
const KNOWN_DIRECTIVES: &[&str] = &[
    "@vite", "@inertia", "@inertiaHead", "@include",
    "@extends", "@section", "@endsection", "@yield", "@if", "@elseif", "@else", "@endif", "@unless", "@endunless",
    "@foreach", "@endforeach", "@csrf", "@method", "@error", "@enderror",
    "@auth", "@endauth", "@guest", "@endguest", "@isset", "@endisset", "@props",
];

fn view(v: &Value) -> (&'static str, String) {
    let list = |k: &str| v[k].as_array().cloned().unwrap_or_default().into_iter().filter_map(|x| x.as_str().map(String::from)).collect::<Vec<_>>();
    let directives = list("directives");
    let components = list("components");
    if directives.iter().any(|d| d.starts_with("@livewire")) || components.iter().any(|c| c.starts_with("livewire:")) {
        return ("red", "Livewire component; no Rust equivalent".into());
    }
    // `<x-..>` usages become macro calls (codegen, components.rs); a component's own `@php` logic stays yellow below.
    let mut todo: Vec<String> = directives.into_iter().filter(|d| !KNOWN_DIRECTIVES.contains(&d.as_str())).collect();
    if v["raw_echo"] == true {
        todo.push("{!! !!}".into());
    }
    if todo.is_empty() {
        ("green", "every directive is in the Blade → Jinja table".into())
    } else {
        ("yellow", format!("no verified Jinja mapping for {}", todo.join(", ")))
    }
}

/// Spatie's official Rust crates (`spatie-<name>` on crates.io, owner freekmurze), checked Dec 5, 2026.
/// Only these count: look-alike `laravel-*` crates from other accounts are never mapped.
const SPATIE_CRATES: &[&str] = &[
    "laravel-activitylog", "laravel-analytics", "laravel-backup", "laravel-csp", "laravel-feed", "laravel-health",
    "laravel-honeypot", "laravel-mailcoach-mailer", "laravel-mailcoach-sdk", "laravel-markdown", "laravel-medialibrary",
    "laravel-missing-page-redirector", "laravel-newsletter", "laravel-og-image", "laravel-package-tools", "laravel-pdf",
    "laravel-query-builder", "laravel-responsecache", "laravel-schedule-monitor", "laravel-site-search", "laravel-sitemap",
    "laravel-slack-alerts", "laravel-sluggable", "laravel-stripe-webhooks", "laravel-suspicious-login", "laravel-tags",
    "laravel-translatable", "laravel-webhook-client", "laravel-webhook-server",
];

fn package(p: &Value) -> (&'static str, String) {
    let name = p["name"].as_str().unwrap_or("");
    let dev = p["dev"] == true;
    let (status, reason): (&str, &str) = match name {
        "laravel/framework" => ("green", "the framework itself"),
        "laravel/tinker" => ("green", "not needed in Rust"),
        "inertiajs/inertia-laravel" => ("green", "built-in Inertia (React, Vue, Svelte, SSR)"),
        "laravel/socialite" => ("green", "built-in social login"),
        "laravel/scout" => ("green", "built-in search"),
        "laravel/reverb" => ("green", "built-in websockets (reverb feature)"),
        "laravel/pennant" => ("green", "built-in feature flags"),
        "laravel/breeze" | "laravel/fortify" => ("green", "built-in login, registration, verification, password reset"),
        "guzzlehttp/guzzle" => ("green", "built-in HTTP client (http-client.md)"),
        "fakerphp/faker" => ("green", "built-in Faker in model factories"),
        "predis/predis" => ("green", "redis feature"),
        "league/flysystem-aws-s3-v3" => ("green", "s3 feature"),
        "resend/resend-laravel" => ("green", "built-in Resend mailer"),
        "spatie/laravel-permission" => ("green", "official crate spatie-laravel-permission (Spatie): shares PHP's tables both ways; set #[model(morph = \"App\\\\Models\\\\User\")] (verified: PHP 6.25 ↔ crate 0.1.3)"),
        n if n.strip_prefix("spatie/").is_some_and(|rest| SPATIE_CRATES.contains(&rest)) => {
            return ("yellow", format!("official crate spatie-{} (Spatie, owner freekmurze) exists, not verified by LaraKiln yet: check its PHP-compatibility docs", &n[7..]));
        }
        "laravel/sanctum" => ("yellow", "no built-in API tokens; use the Sanctum-compatible guard"),
        "tightenco/ziggy" => ("yellow", "frontend route() helper: route names become handler paths"),
        "laravel/chisel" => ("green", "starter-kit install-time feature stripper; nothing runs at request time"),
        "laravel/wayfinder" => ("yellow", "generated TypeScript route helpers: regenerate them from the Rust routes, or hard-code the URLs"),
        "livewire/livewire" | "livewire/volt" => ("red", "PHP-only UI stack; rewrite the UI in Inertia or Jinja"),
        "laravel/nova" => ("red", "Nova is not supported (commercial, closed source); keep the Nova panel in PHP under your own licence"),
        n if n.starts_with("filament/") => ("red", "PHP-only UI stack; rewrite the UI in Inertia or Jinja"),
        _ if dev => ("green", "dev-only package; not shipped"),
        _ => ("red", "no known Rust mapping (never guessed): add one to packages.md or drop the feature"),
    };
    (status, reason.into())
}

fn report(inv: &Value) -> String {
    let mut out = String::new();
    let app = &inv["app"];
    out += &format!(
        "# Porting feasibility: {}\n\nLaravel {} · PHP {} · DB {} · frontend {}\n\n",
        app["path"].as_str().unwrap_or("?"),
        app["laravel"].as_str().unwrap_or("?"),
        app["php"].as_str().unwrap_or("?"),
        app["db"].as_str().unwrap_or("?"),
        app["frontend"].as_str().unwrap_or("?"),
    );

    let (mut g, mut y, mut r) = (0, 0, 0);
    let mut rows = String::new();
    let mut flagged = Vec::new();
    for section in SECTIONS {
        let items = inv[*section].as_array().cloned().unwrap_or_default();
        if items.is_empty() {
            continue;
        }
        let count = |s: &str| items.iter().filter(|i| i["status"] == s).count();
        let (sg, sy, sr) = (count("green"), count("yellow"), count("red"));
        (g, y, r) = (g + sg, y + sy, r + sr);
        rows += &format!("| {section} | {} | {sg} | {sy} | {sr} |\n", items.len());
        flagged.extend(items.into_iter().filter(|i| i["status"] != "green"));
    }

    let verdict = if inv["app"]["frontend"] == "livewire" || r > 0 {
        "**Red: blockers found.** The app can't be fully ported until each red item is resolved."
    } else if y > 0 {
        "**Yellow: portable, with items that need a human.**"
    } else {
        "**Green: every item has a verified mapping.**"
    };
    out += &format!("{verdict}\n\n| Section | Items | Green | Yellow | Red |\n| --- | --- | --- | --- | --- |\n{rows}| **Total** | {} | {g} | {y} | {r} |\n\n", g + y + r);

    for status in ["red", "yellow"] {
        let items: Vec<_> = flagged.iter().filter(|i| i["status"] == status).collect();
        if !items.is_empty() {
            out += &format!("## {} ({})\n\n", if status == "red" { "Blockers" } else { "Needs a human" }, items.len());
            for i in items {
                out += &format!("- `{}`: {}\n", i["id"].as_str().unwrap_or("?"), i["reason"].as_str().unwrap_or(""));
            }
            out += "\n";
        }
    }
    for note in inv["notes"].as_array().into_iter().flatten() {
        out += &format!("> Note: {}\n", note.as_str().unwrap_or(""));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unknown_packages_are_red_dev_tools_green() {
        assert_eq!(package(&json!({"name": "pestphp/pest", "dev": true})).0, "green");
        assert_eq!(package(&json!({"name": "livewire/livewire", "dev": false})).0, "red");
        assert_eq!(package(&json!({"name": "spatie/laravel-permission", "dev": false})).0, "green");
        assert_eq!(package(&json!({"name": "spatie/laravel-medialibrary", "dev": false})).0, "yellow");
        assert_eq!(package(&json!({"name": "spatie/laravel-not-a-crate", "dev": false})).0, "red");
    }

    #[test]
    fn events_and_listeners_are_green() {
        assert_eq!(score("events", &json!({"id": "event:ChirpCreated"})).0, "green");
        assert_eq!(score("listeners", &json!({"id": "listener:SendChirpCreatedNotifications"})).0, "green");
    }

    #[test]
    fn observers_map_to_model_event_listeners() {
        let (status, reason) = score("observers", &json!({"id": "observer:ChirpObserver"}));
        assert_eq!(status, "green");
        assert!(reason.contains("#[listener]"));
    }

    #[test]
    fn rules_outside_the_docs_are_yellow() {
        let r = json!({"rules": {"message": ["required", "string", "max:255"]}});
        assert_eq!(request(&r).0, "green");
        let r = json!({"rules": {"n": ["required", "size:3"]}});
        assert_eq!(request(&r), ("yellow", "rules without a verified mapping: size".into()));
    }
}