use super::node::{FallbackPolicy, MeshNode};
use crate::domains;
use crate::lenses::clarity::ClarityLens;
use crate::lenses::focus::FocusLens;
use crate::lenses::narrow::NarrowLens;
use crate::lenses::{LensContext, LensOutput};
use crate::recipe::loader;

/// Commands that produce streaming / interactive output and must never be compressed.
static PASSTHROUGH_PREFIXES: &[&str] = &[
    // JS/TS dev servers
    "next dev",
    "next start",
    "vite dev",
    "vite preview",
    "vite ",
    "nuxt dev",
    "astro dev",
    "webpack serve",
    "webpack-dev-server",
    "gatsby develop",
    "remix dev",
    "wrangler dev",
    "hugo server",
    "jekyll serve",
    "ember serve",
    // Package script runners (dev servers)
    "npm run dev",
    "npm run start",
    "npm run serve",
    "npm run watch",
    "npm run preview",
    "npm start",
    "pnpm run dev",
    "pnpm run start",
    "pnpm dev",
    "pnpm start",
    "yarn dev",
    "yarn start",
    "yarn serve",
    "yarn watch",
    "bun run dev",
    "bun run start",
    "bun start",
    "deno task dev",
    "deno task start",
    "deno run --watch",
    // Node watchers
    "nodemon",
    "ts-node-dev",
    "concurrently",
    "pm2 logs",
    "pm2 start",
    // Test watchers
    "vitest watch",
    "jest --watch",
    "jest --watchAll",
    "npm run test:watch",
    "pnpm run test:watch",
    // Docker streaming
    "docker compose up",
    "docker-compose up",
    "docker compose logs",
    "docker-compose logs",
    "docker logs -f",
    "docker attach",
    "docker exec -it",
    "docker stats",
    // Kubernetes streaming
    "kubectl logs -f",
    "kubectl port-forward",
    "kubectl exec -it",
    "kubectl attach",
    "kubectl proxy",
    // System monitors
    "top",
    "htop",
    "btop",
    "bpytop",
    "glances",
    "watch ",
    "tail -f",
    "journalctl -f",
    "journalctl -fu",
    // Build watchers
    "cargo watch",
    "watchexec",
    "entr",
    // Misc interactive
    "ssh ",
    "sftp ",
    "ftp ",
    "telnet ",
];

pub struct FilterMesh {
    nodes: Vec<MeshNode>,
    /// Node names (from recipes) that have `scan_secrets = false`.
    no_redact_nodes: std::collections::HashSet<String>,
}

impl FilterMesh {
    pub fn new() -> Self {
        Self {
            nodes: Vec::new(),
            no_redact_nodes: std::collections::HashSet::new(),
        }
    }

    pub fn register(&mut self, node: MeshNode) {
        self.nodes.push(node);
    }

    /// Number of domain compressor nodes currently registered. Authoritative count
    /// for "how many built-in patterns does bctx ship with" (used by `bctx patterns`).
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Names of all registered nodes, in registration order.
    pub fn node_names(&self) -> Vec<&str> {
        self.nodes.iter().map(|n| n.name.as_str()).collect()
    }

    /// Prepend recipe-derived nodes so they take priority over built-ins.
    fn prepend_nodes(&mut self, nodes: Vec<MeshNode>) {
        let existing = std::mem::take(&mut self.nodes);
        self.nodes = nodes;
        self.nodes.extend(existing);
    }

    /// Load recipes from `{root}/.bctx/recipes/` and `~/.config/bctx/recipes/`
    /// and prepend them to this mesh so they override built-in nodes.
    pub fn with_project_recipes(mut self, root: &std::path::Path) -> Self {
        let compiled = loader::load_all_recipes(root);
        for c in &compiled {
            if !c.recipe.scan_secrets {
                self.no_redact_nodes.insert(c.recipe.name.clone());
            }
        }
        if !compiled.is_empty() {
            let nodes: Vec<MeshNode> = compiled.into_iter().map(|r| r.to_mesh_node()).collect();
            self.prepend_nodes(nodes);
        }
        self
    }

    pub fn find(&self, program: &str, args: &[String]) -> Option<&MeshNode> {
        self.nodes.iter().find(|n| (n.matcher)(program, args))
    }

    /// Returns `false` if the recipe that handles this command has opted out of
    /// secret scanning (`scan_secrets = false`). Returns `true` for all built-in
    /// nodes and when no node matches.
    pub fn scan_secrets_enabled(&self, program: &str, args: &[String]) -> bool {
        match self.find(program, args) {
            Some(node) => !self.no_redact_nodes.contains(&node.name),
            None => true,
        }
    }

    pub fn apply(
        &self,
        program: &str,
        args: &[String],
        input: &str,
        ctx: &LensContext,
    ) -> LensOutput {
        // Check passthrough list first (streaming commands → no compression)
        let full_cmd = format!("{} {}", program, args.join(" ")).trim().to_string();
        if is_passthrough(&full_cmd) {
            return LensOutput::passthrough(input);
        }

        match self.find(program, args) {
            Some(node) => {
                let enriched = if ctx.subcmd.is_empty() {
                    let mut c = ctx.clone();
                    c.subcmd = args.join(" ");
                    std::borrow::Cow::Owned(c)
                } else {
                    std::borrow::Cow::Borrowed(ctx)
                };
                node.apply(input, &enriched)
            }
            None => LensOutput::passthrough(input),
        }
    }

    pub fn default_mesh() -> Self {
        let mut mesh = Self::new();

        // ── VCS: git ─────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "git".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "git"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::vcs::git::compress_git(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── VCS: gh (GitHub CLI) ──────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "gh".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "gh"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::vcs::gh::compress_gh(&ctx.subcmd, raw)
            })),
        });

        // ── cargo build / check / clippy ──────────────────────────────────────
        mesh.register(MeshNode {
            name: "cargo-build".into(),
            matcher: Box::new(|prog, args| {
                prog_name(prog) == "cargo"
                    && args
                        .first()
                        .map(|s| matches!(s.as_str(), "build" | "b" | "check" | "c" | "clippy"))
                        .unwrap_or(false)
            }),
            lens_stack: vec![
                Box::new(ClarityLens),
                Box::new(FocusLens),
                Box::new(NarrowLens),
            ],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::cargo::compress_cargo(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── cargo test ────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "cargo-test".into(),
            matcher: Box::new(|prog, args| {
                prog_name(prog) == "cargo"
                    && args
                        .first()
                        .map(|s| matches!(s.as_str(), "test" | "t" | "nextest"))
                        .unwrap_or(false)
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::cargo::compress_test(raw, ctx.exit_code)
            })),
        });

        // ── cargo misc (tree/add/update/fmt/bench/doc/publish/run) ───────────
        mesh.register(MeshNode {
            name: "cargo-misc".into(),
            matcher: Box::new(|prog, args| {
                prog_name(prog) == "cargo"
                    && args
                        .first()
                        .map(|s| {
                            matches!(
                                s.as_str(),
                                "tree"
                                    | "add"
                                    | "remove"
                                    | "rm"
                                    | "update"
                                    | "fmt"
                                    | "bench"
                                    | "doc"
                                    | "publish"
                                    | "run"
                                    | "r"
                            )
                        })
                        .unwrap_or(false)
            }),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::cargo::compress_cargo(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── go build / test ───────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "go".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "go"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::go::compress_go(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── tsc / tsup / esbuild ──────────────────────────────────────────────
        // We default to `tsc` behaviour; tsup/esbuild get more specific handling
        // via their own output shapes in compress_typescript.
        mesh.register(MeshNode {
            name: "tsc".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "tsc"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::typescript::compress_tsc(raw, ctx.exit_code)
            })),
        });

        mesh.register(MeshNode {
            name: "tsup".into(),
            matcher: Box::new(|prog, _| {
                matches!(prog_name(prog), "tsup" | "unbuild" | "esbuild" | "swc")
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::build::typescript::compress_tsup(raw)
            })),
        });

        // ── gradle ────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "gradle".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "gradle" | "gradlew")),
            lens_stack: vec![
                Box::new(ClarityLens),
                Box::new(FocusLens),
                Box::new(NarrowLens),
            ],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::gradle::compress_gradle(raw, ctx.exit_code)
            })),
        });

        // ── maven ─────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "maven".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "mvn" | "mvnw")),
            lens_stack: vec![
                Box::new(ClarityLens),
                Box::new(FocusLens),
                Box::new(NarrowLens),
            ],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::gradle::compress_maven(raw, ctx.exit_code)
            })),
        });

        // ── make / cmake ──────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "make".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "make" | "gmake")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::make::compress_make(raw, ctx.exit_code)
            })),
        });

        mesh.register(MeshNode {
            name: "cmake".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "cmake" | "ctest")),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::build::make::compress_cmake(raw)
            })),
        });

        // ── docker ────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "docker".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "docker" | "docker-compose")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::docker::compress_docker(&ctx.subcmd, raw)
            })),
        });

        // ── kubectl ───────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "kubectl".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "kubectl" | "k")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::kubectl::compress_kubectl(&ctx.subcmd, raw)
            })),
        });

        // ── terraform ─────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "terraform".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "terraform"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::terraform::compress_terraform(&ctx.subcmd, raw)
            })),
        });

        // ── aws ───────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "aws".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "aws"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::aws::compress_aws(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "az".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "az"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::az::compress_az(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "gcloud".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "gcloud"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::gcloud::compress_gcloud(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "pulumi".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "pulumi"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::pulumi::compress_pulumi(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "wrangler".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "wrangler"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::wrangler::compress_wrangler(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "vercel".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "vercel"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::vercel::compress_vercel(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "fly".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "fly" | "flyctl")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::fly::compress_fly(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "supabase".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "supabase"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::supabase::compress_supabase(&ctx.subcmd, raw)
            })),
        });

        // ── Wave 8 Tier 2: cloud-native ops + data ───────────────────────────

        mesh.register(MeshNode {
            name: "argocd".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "argocd"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::argocd::compress_argocd(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "skaffold".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "skaffold"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::skaffold::compress_skaffold(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "dbt".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "dbt"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::data::dbt::compress_dbt(&ctx.subcmd, raw)
            })),
        });

        // ── Wave 8 Tier 3+4: migrations, mlflow, spark, linkerd ──────────────

        mesh.register(MeshNode {
            name: "alembic".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "alembic"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::data::alembic::compress_alembic(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "flyway".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "flyway"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::data::flyway::compress_flyway(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "mlflow".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "mlflow"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::ai::mlflow::compress_mlflow(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "spark-submit".into(),
            matcher: Box::new(|prog, _| {
                matches!(prog_name(prog), "spark-submit" | "spark-shell" | "pyspark")
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::data::spark::compress_spark(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "linkerd".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "linkerd"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::linkerd::compress_linkerd(&ctx.subcmd, raw)
            })),
        });

        // ── Wave 8 Tier 1: AI/ML + security scanners ─────────────────────────

        mesh.register(MeshNode {
            name: "ollama".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "ollama"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::ai::ollama::compress_ollama(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "grype".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "grype"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::grype::compress_grype(raw)
            })),
        });

        mesh.register(MeshNode {
            name: "syft".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "syft"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::syft::compress_syft(raw)
            })),
        });

        mesh.register(MeshNode {
            name: "cosign".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "cosign"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::lint::cosign::compress_cosign(&ctx.subcmd, raw)
            })),
        });

        // ── npm / yarn ────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "npm".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "npm" | "yarn")),
            lens_stack: vec![
                Box::new(ClarityLens),
                Box::new(FocusLens),
                Box::new(NarrowLens),
            ],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::npm::compress_npm(&ctx.subcmd, raw)
            })),
        });

        // ── pnpm ──────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "pnpm".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "pnpm"),
            lens_stack: vec![
                Box::new(ClarityLens),
                Box::new(FocusLens),
                Box::new(NarrowLens),
            ],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::pnpm::compress_pnpm(&ctx.subcmd, raw)
            })),
        });

        // ── bun ───────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "bun".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "bun" | "bunx")),
            lens_stack: vec![
                Box::new(ClarityLens),
                Box::new(FocusLens),
                Box::new(NarrowLens),
            ],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::bun::compress_bun(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── apt / apt-get (Debian/Ubuntu) ──────────────────────────────────────
        mesh.register(MeshNode {
            name: "apt".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "apt" | "apt-get")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::apt::compress_apt(&ctx.subcmd, raw)
            })),
        });

        // ── brew (Homebrew) ─────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "brew".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "brew"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::brew::compress_brew(&ctx.subcmd, raw)
            })),
        });

        // ── pip / pip3 ────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "pip".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "pip" | "pip3")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::pip::compress_pip(&ctx.subcmd, raw)
            })),
        });

        // ── poetry / uv / conda ───────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "poetry".into(),
            matcher: Box::new(|prog, _| {
                matches!(
                    prog_name(prog),
                    "poetry" | "uv" | "conda" | "mamba" | "pipx"
                )
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::pkg::poetry::compress_poetry(raw)
            })),
        });

        // ── pytest ────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "pytest".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "pytest" | "py.test")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::test::pytest::compress_pytest(raw, ctx.exit_code)
            })),
        });

        // ── django manage.py ──────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "django".into(),
            matcher: Box::new(|prog, args| {
                // manage.py migrate / runserver / makemigrations / test / collectstatic
                let pn = prog_name(prog);
                pn == "manage.py"
                    || (pn == "django-admin")
                    || (pn == "python"
                        && args
                            .first()
                            .map(|a| a.ends_with("manage.py"))
                            .unwrap_or(false))
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::django::compress_django(&ctx.subcmd, raw)
            })),
        });

        // ── jest / mocha ──────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "jest".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "jest" | "mocha")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::test::jest::compress_jest(raw, ctx.exit_code)
            })),
        });

        // ── playwright ────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "playwright".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "playwright"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::test::playwright::compress_playwright(raw, ctx.exit_code)
            })),
        });

        // ── rspec / rake ──────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "rspec".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "rspec" | "rake" | "ruby")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::test::ruby::compress_ruby_test(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── ruff ──────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "ruff".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "ruff"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::ruff::compress_ruff_check(raw)
            })),
        });

        // ── mypy / dmypy ──────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "mypy".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "mypy" | "dmypy")),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::mypy::compress_mypy(raw)
            })),
        });

        // ── eslint / biome ────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "eslint".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "eslint" | "biome")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::eslint::compress_eslint(raw)
            })),
        });

        mesh.register(MeshNode {
            name: "stylelint".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "stylelint"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::stylelint::compress_stylelint(raw)
            })),
        });

        // ── rubocop / bundle-audit ────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "rubocop".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "rubocop"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::lint::rubocop::compress_rubocop(raw, ctx.exit_code)
            })),
        });

        mesh.register(MeshNode {
            name: "bundle-audit".into(),
            matcher: Box::new(|prog, _| {
                matches!(prog_name(prog), "bundle-audit" | "bundler-audit")
            }),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::rubocop::compress_bundle_audit(raw)
            })),
        });

        // ── golangci-lint ─────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "golangci-lint".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "golangci-lint" | "golangci")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::lint::golangci::compress_golangci(raw, ctx.exit_code)
            })),
        });

        // ── flake8 ───────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "flake8".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "flake8"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::flake8::compress_flake8(raw)
            })),
        });

        // ── pylint ───────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "pylint".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "pylint"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::pylint::compress_pylint(raw)
            })),
        });

        // ── cargo-deny ───────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "cargo-deny".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "cargo-deny"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::cargo_deny::compress_deny(raw)
            })),
        });

        // ── swiftlint (generic) ───────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "lint-generic".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "swiftlint"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::compress_lint_grouped(raw)
            })),
        });

        // ── curl ──────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "curl".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "curl"),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::sys::curl::compress_curl(&ctx.subcmd, raw)
            })),
        });

        // ── psql / sqlite3 ────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "psql".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "psql" | "sqlite3")),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| domains::db::compress_psql(raw))),
        });

        mesh.register(MeshNode {
            name: "mongosh".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "mongosh" | "mongo")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::db::mongosh::compress_mongosh(raw)
            })),
        });

        mesh.register(MeshNode {
            name: "redis-cli".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "redis-cli" | "redis")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::db::redis::compress_redis(raw)
            })),
        });

        // ── mysql / mariadb ───────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "mysql".into(),
            matcher: Box::new(|prog, _| {
                matches!(prog_name(prog), "mysql" | "mariadb" | "mycli" | "mysqldump")
            }),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                if ctx.subcmd == "mysqldump" {
                    domains::db::mysql::compress_mysqldump(raw)
                } else {
                    domains::db::mysql::compress_mysql(raw)
                }
            })),
        });

        // ── prisma ────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "prisma".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "prisma"),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::db::prisma::compress_prisma(&ctx.subcmd, raw)
            })),
        });

        // ── ls / find / grep / rg ────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "ls".into(),
            matcher: Box::new(|prog, _| {
                matches!(prog_name(prog), "ls" | "ll" | "la" | "exa" | "lsd")
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| domains::sys::compress_ls(raw, 200))),
        });

        mesh.register(MeshNode {
            name: "find".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "find" | "fd")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| domains::sys::compress_find(raw))),
        });

        mesh.register(MeshNode {
            name: "grep".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "grep" | "rg" | "ag" | "ack")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| domains::sys::compress_grep(raw))),
        });

        // ── env / printenv ────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "env".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "env" | "printenv" | "export")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| domains::sys::compress_env(raw))),
        });

        // ── jq ────────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "jq".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "jq" | "yq" | "fx")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| domains::sys::compress_jq_output(raw))),
        });

        // ── systemctl / journalctl ────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "systemd".into(),
            matcher: Box::new(|prog, _| {
                matches!(prog_name(prog), "systemctl" | "journalctl" | "service")
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                if ctx.subcmd.is_empty() || ctx.subcmd == "journalctl" {
                    domains::sys::systemd::compress_journalctl(raw)
                } else {
                    domains::sys::systemd::compress_systemctl(&ctx.subcmd, raw)
                }
            })),
        });

        // ── helm ──────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "helm".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "helm"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::helm::compress_helm(&ctx.subcmd, raw)
            })),
        });

        // ── ansible ───────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "ansible".into(),
            matcher: Box::new(|prog, _| {
                matches!(
                    prog_name(prog),
                    "ansible" | "ansible-playbook" | "ansible-galaxy" | "ansible-vault"
                )
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::infra::ansible::compress_ansible(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── dotnet ────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "dotnet".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "dotnet"),
            lens_stack: vec![
                Box::new(ClarityLens),
                Box::new(FocusLens),
                Box::new(NarrowLens),
            ],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::dotnet::compress_dotnet(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── swift ─────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "swift".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "swift"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::swift::compress_swift(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── zig ───────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "zig".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "zig"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::zig::compress_zig(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── flutter / dart ────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "flutter".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "flutter" | "dart")),
            lens_stack: vec![
                Box::new(ClarityLens),
                Box::new(FocusLens),
                Box::new(NarrowLens),
            ],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::flutter::compress_flutter(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── bazel ─────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "bazel".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "bazel" | "bazelisk" | "bb")),
            lens_stack: vec![
                Box::new(ClarityLens),
                Box::new(FocusLens),
                Box::new(NarrowLens),
            ],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::bazel::compress_bazel(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── composer / artisan ────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "composer".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "composer" | "artisan")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::composer::compress_composer(&ctx.subcmd, raw)
            })),
        });

        // ── mix (Elixir) ──────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "mix".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "mix"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::mix::compress_mix(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── deno ──────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "deno".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "deno"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::deno::compress_deno(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        // ── prettier ──────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "prettier".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "prettier"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::lint::prettier::compress_prettier(raw, ctx.exit_code)
            })),
        });

        // ── wget ──────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "wget".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "wget"),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| domains::sys::wget::compress_wget(raw))),
        });

        // ── ps / df / du / lsof / netstat / ss ───────────────────────────────
        mesh.register(MeshNode {
            name: "ps".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "ps"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::sys::sysinfo::compress_ps(raw)
            })),
        });

        mesh.register(MeshNode {
            name: "df".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "df"),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::sys::sysinfo::compress_df(raw)
            })),
        });

        mesh.register(MeshNode {
            name: "du".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "du"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::sys::sysinfo::compress_du(raw)
            })),
        });

        mesh.register(MeshNode {
            name: "lsof".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "lsof"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::sys::sysinfo::compress_lsof(raw)
            })),
        });

        mesh.register(MeshNode {
            name: "netstat".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "netstat" | "ss")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::sys::sysinfo::compress_netstat(raw)
            })),
        });

        // ── jj (Jujutsu VCS) ──────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "jj".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "jj"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::vcs::jj::compress_jj(&ctx.subcmd, raw)
            })),
        });

        // ── gem / bundler ─────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "gem".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "gem"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::gem::compress_gem(&ctx.subcmd, raw)
            })),
        });

        mesh.register(MeshNode {
            name: "bundle".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "bundle" | "bundler")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::gem::compress_bundle(&ctx.subcmd, raw)
            })),
        });

        // ── vite / next / turbo ───────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "vite".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "vite"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::vite::compress_vite(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        mesh.register(MeshNode {
            name: "next".into(),
            matcher: Box::new(|prog, args| {
                prog_name(prog) == "next"
                    || (prog_name(prog) == "npx"
                        && args.first().map(|s| s == "next").unwrap_or(false))
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::vite::compress_next(&ctx.subcmd, raw, ctx.exit_code)
            })),
        });

        mesh.register(MeshNode {
            name: "turbo".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "turbo" | "turborepo")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::build::turbo::compress_turbo(raw)
            })),
        });

        mesh.register(MeshNode {
            name: "nx".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "nx"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| domains::build::nx::compress_nx(raw))),
        });

        // ── vitest ────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "vitest".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "vitest"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::test::vitest::compress_vitest(raw, ctx.exit_code)
            })),
        });

        // ── npx / pnpm dlx ────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "npx".into(),
            matcher: Box::new(|prog, _| matches!(prog_name(prog), "npx" | "pnpm-dlx")),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| domains::pkg::npm::compress_npx(raw))),
        });

        // ── cargo nextest (higher priority than cargo-test) ───────────────────
        mesh.register(MeshNode {
            name: "cargo-nextest".into(),
            matcher: Box::new(|prog, args| {
                prog_name(prog) == "cargo" && args.first().map(|s| s.as_str()) == Some("nextest")
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::cargo::compress_nextest(raw, ctx.exit_code)
            })),
        });

        // ── cargo clippy (higher priority than cargo-misc) ────────────────────
        mesh.register(MeshNode {
            name: "cargo-clippy".into(),
            matcher: Box::new(|prog, args| {
                prog_name(prog) == "cargo" && args.first().map(|s| s.as_str()) == Some("clippy")
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::build::cargo::compress_clippy(raw)
            })),
        });

        // ── cargo fmt / rustfmt ───────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "cargo-fmt".into(),
            matcher: Box::new(|prog, args| {
                (prog_name(prog) == "cargo" && args.first().map(|s| s.as_str()) == Some("fmt"))
                    || prog_name(prog) == "rustfmt"
            }),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                let sub = if ctx.exit_code != 0 { "check" } else { "" };
                domains::build::rustfmt::compress_rustfmt(sub, raw)
            })),
        });

        // ── uv ────────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "uv".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "uv"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::pkg::uv::compress_uv(&ctx.subcmd, raw)
            })),
        });

        // ── docker compose (separate from docker build/pull/push) ─────────────
        mesh.register(MeshNode {
            name: "docker-compose".into(),
            matcher: Box::new(|prog, args| {
                prog_name(prog) == "docker-compose"
                    || (prog_name(prog) == "docker"
                        && args.first().map(|s| s.as_str()) == Some("compose"))
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                let sub = if ctx.subcmd.starts_with("compose ") {
                    ctx.subcmd.trim_start_matches("compose").trim()
                } else {
                    ctx.subcmd.as_str()
                };
                domains::infra::docker_compose::compress_compose(sub, raw)
            })),
        });

        // ── biome ─────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "biome".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "biome"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::lint::biome::compress_biome(&ctx.subcmd, raw)
            })),
        });

        // ── trivy ─────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "trivy".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "trivy"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::lint::trivy::compress_trivy(&ctx.subcmd, raw)
            })),
        });

        // ── buf ───────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "buf".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "buf"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::build::buf::compress_buf(&ctx.subcmd, raw)
            })),
        });

        // ── hadolint ──────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "hadolint".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "hadolint"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::hadolint::compress_hadolint(raw)
            })),
        });

        // ── semgrep ───────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "semgrep".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "semgrep"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::lint::semgrep::compress_semgrep(&ctx.subcmd, raw)
            })),
        });

        // ── mise ──────────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "mise".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "mise"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::sys::mise::compress_mise(&ctx.subcmd, raw)
            })),
        });

        // ── swiftlint ─────────────────────────────────────────────────────────
        mesh.register(MeshNode {
            name: "swiftlint".into(),
            matcher: Box::new(|prog, _| prog_name(prog) == "swiftlint"),
            lens_stack: vec![Box::new(ClarityLens), Box::new(FocusLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::lint::swiftlint::compress_swiftlint(raw)
            })),
        });

        // ── gh-run (higher priority than gh) ──────────────────────────────────
        mesh.register(MeshNode {
            name: "gh-run".into(),
            matcher: Box::new(|prog, args| {
                prog_name(prog) == "gh" && args.first().map(|s| s.as_str()) == Some("run")
            }),
            lens_stack: vec![Box::new(ClarityLens), Box::new(NarrowLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, ctx| {
                domains::vcs::gh::compress_gh(&ctx.subcmd, raw)
            })),
        });

        // ── gh-pr-checks (higher priority than gh) ────────────────────────────
        mesh.register(MeshNode {
            name: "gh-pr-checks".into(),
            matcher: Box::new(|prog, args| {
                prog_name(prog) == "gh"
                    && args.first().map(|s| s.as_str()) == Some("pr")
                    && args.get(1).map(|s| s.as_str()) == Some("checks")
            }),
            lens_stack: vec![Box::new(ClarityLens)],
            fallback: FallbackPolicy::Passthrough,
            preprocessor: Some(Box::new(|raw, _ctx| {
                domains::vcs::gh::compress_pr_checks(raw)
            })),
        });

        mesh
    }
}

impl Default for FilterMesh {
    fn default() -> Self {
        Self::default_mesh()
    }
}

fn prog_name(prog: &str) -> &str {
    prog.split('/').next_back().unwrap_or(prog)
}

/// Passthrough check: command starts with any known streaming prefix.
fn is_passthrough(full_cmd: &str) -> bool {
    let lc = full_cmd.to_ascii_lowercase();
    PASSTHROUGH_PREFIXES.iter().any(|p| lc.starts_with(p))
}

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

    #[test]
    fn mesh_routes_apt_install() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "Reading package lists... Done\nBuilding dependency tree... Done\n0 upgraded, 1 newly installed, 0 to remove and 3 not upgraded.\nGet:1 http://deb.debian.org/debian bookworm/main amd64 curl amd64 7.88.1 [315 kB]\nUnpacking curl (7.88.1) ...\nSetting up curl (7.88.1) ...\n";
        let out = mesh.apply(
            "apt-get",
            &["install".to_string(), "curl".to_string()],
            raw,
            &ctx,
        );
        assert!(
            !out.content.contains("Reading package lists"),
            "{}",
            out.content
        );
        assert!(!out.content.contains("Get:1"), "{}", out.content);
        assert!(out.content.contains("newly installed"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_brew_install() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "==> Downloading https://example.com/foo.bottle.tar.gz\n######################################################################## 100.0%\n==> Installing foo\n🍺  /opt/homebrew/Cellar/foo/1.2.3: 123 files\n";
        let out = mesh.apply(
            "brew",
            &["install".to_string(), "foo".to_string()],
            raw,
            &ctx,
        );
        assert!(!out.content.contains("Downloading"), "{}", out.content);
        assert!(!out.content.contains("100.0%"), "{}", out.content);
        assert!(
            out.content.contains("==> Installing foo"),
            "{}",
            out.content
        );
    }

    #[test]
    fn node_count_matches_names_and_marketing_claim() {
        // Keep in sync with the "110 CLI patterns" claim on betterctx.com / docs.
        // If you add or remove a compressor, update the site + docs to match.
        let mesh = FilterMesh::default_mesh();
        assert_eq!(mesh.node_count(), mesh.node_names().len());
        assert_eq!(
            mesh.node_count(),
            110,
            "domain compressor count drifted from the advertised 110; got {}",
            mesh.node_count()
        );
    }

    #[test]
    fn passthrough_dev_server() {
        assert!(is_passthrough("next dev --port 3000"));
        assert!(is_passthrough("npm run dev"));
        assert!(is_passthrough("docker compose up"));
        assert!(is_passthrough("kubectl logs -f my-pod"));
    }

    #[test]
    fn passthrough_does_not_match_build() {
        assert!(!is_passthrough("npm run build"));
        assert!(!is_passthrough("docker build ."));
        assert!(!is_passthrough("kubectl get pods"));
    }

    #[test]
    fn mesh_routes_git() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "On branch main\nnothing to commit, working tree clean\n";
        let out = mesh.apply("git", &["status".to_string()], raw, &ctx);
        // Compressed output should be shorter or equal
        assert!(out.tokens_after <= out.tokens_before + 5);
    }

    #[test]
    fn mesh_routes_cargo() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw =
            "   Compiling foo v0.1.0\n   Compiling bar v0.2.0\nerror[E0412]: type not found\n";
        let out = mesh.apply("cargo", &["build".to_string()], raw, &ctx);
        assert!(!out.content.contains("Compiling foo"), "{}", out.content);
        assert!(out.content.contains("error"));
    }

    #[test]
    fn mesh_routes_docker_pull() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "abc123: Pull complete\ndef456: Pull complete\nStatus: Downloaded newer image for ubuntu:22.04\n";
        let out = mesh.apply(
            "docker",
            &["pull".to_string(), "ubuntu:22.04".to_string()],
            raw,
            &ctx,
        );
        assert!(!out.content.contains("Pull complete"), "{}", out.content);
        assert!(out.content.contains("Downloaded newer image") || out.content.contains("ubuntu"));
    }

    #[test]
    fn mesh_routes_npm_install() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "npm verb cli /usr/bin/node\nnpm info timing npm Completed in 2000ms\nadded 42 packages in 3s\n";
        let out = mesh.apply("npm", &["install".to_string()], raw, &ctx);
        assert!(!out.content.contains("npm verb"), "{}", out.content);
        assert!(out.content.contains("added 42 packages"));
    }

    // ── Wave 7 Tier 1 routing ─────────────────────────────────────────────────

    #[test]
    fn mesh_routes_turbo() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "• Remote caching disabled\napp:build: cache miss, executing abc123\napp:build: ✓ Compiled successfully\n\nTasks:    1 successful, 1 total\n";
        let out = mesh.apply(
            "turbo",
            &["run".to_string(), "build".to_string()],
            raw,
            &ctx,
        );
        assert!(!out.content.contains("Remote caching"), "{}", out.content);
        assert!(out.content.contains("Tasks:"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_nx() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = " >  NX  Running target build for 2 projects:\n\n   ✔  nx run app:build  [existing outputs match the cache, left as is]\n\n >  NX   Successfully ran target build for 2 projects\n";
        let out = mesh.apply("nx", &["run-many".to_string()], raw, &ctx);
        assert!(
            !out.content.contains("Running target build for"),
            "{}",
            out.content
        );
        assert!(
            out.content.contains("cached") || out.content.contains("Successfully"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_gcloud() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "Updated property [core/project].\nUpdated property [compute/zone].\nNAME  ZONE  MACHINE_TYPE  STATUS\n";
        let out = mesh.apply(
            "gcloud",
            &[
                "compute".to_string(),
                "instances".to_string(),
                "list".to_string(),
            ],
            raw,
            &ctx,
        );
        assert!(!out.content.contains("Updated property"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_az() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw =
            "{\n  \"name\": \"my-rg\",\n  \"etag\": \"W/\\\"abc\\\"\",\n  \"systemData\": {}\n}\n";
        let out = mesh.apply("az", &["group".to_string(), "show".to_string()], raw, &ctx);
        assert!(!out.content.contains("\"etag\":"), "{}", out.content);
        assert!(!out.content.contains("\"systemData\":"), "{}", out.content);
        assert!(out.content.contains("my-rg"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_pulumi() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "Downloading provider: registry.pulumi.com/pulumi/aws@6.0.0\nPreviewing update (dev):\n\nResources:\n    + 2 to create\n";
        let out = mesh.apply("pulumi", &["preview".to_string()], raw, &ctx);
        assert!(
            !out.content.contains("Downloading provider"),
            "{}",
            out.content
        );
        assert!(out.content.contains("Resources:"), "{}", out.content);
    }

    // ── Wave 7 Tier 2 routing ─────────────────────────────────────────────────

    #[test]
    fn mesh_routes_wrangler() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "⛅️ wrangler 3.40.0\nBundling with esbuild...\nTotal Upload: 42 KiB / gzip: 12 KiB\nPublished my-worker (0.5 sec)\n  https://my-worker.example.workers.dev\n";
        let out = mesh.apply("wrangler", &["deploy".to_string()], raw, &ctx);
        assert!(!out.content.contains("Bundling"), "{}", out.content);
        assert!(out.content.contains("workers.dev"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_vercel() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "Vercel CLI 33.4.0\nQueued\nBuilding\n✅  Build Completed [30s]\nProduction: https://my-app.vercel.app\n";
        let out = mesh.apply(
            "vercel",
            &["deploy".to_string(), "--prod".to_string()],
            raw,
            &ctx,
        );
        assert!(!out.content.contains("Vercel CLI 33"), "{}", out.content);
        assert!(!out.content.contains("Queued"), "{}", out.content);
        assert!(out.content.contains("vercel.app"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_fly() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "#1 [internal] load build definition\n#1 CACHED\n==> Deploying\nhttps://my-app.fly.dev\n";
        let out = mesh.apply("fly", &["deploy".to_string()], raw, &ctx);
        assert!(!out.content.contains("#1 [internal]"), "{}", out.content);
        assert!(out.content.contains("fly.dev"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_supabase() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "a1b2c3d4e5f6: Pull complete\nDigest: sha256:abc\nApplying migration 20240101_init.sql...\nApplied 1 migration\n";
        let out = mesh.apply(
            "supabase",
            &["db".to_string(), "push".to_string()],
            raw,
            &ctx,
        );
        assert!(!out.content.contains("Pull complete"), "{}", out.content);
        assert!(out.content.contains("migration"), "{}", out.content);
    }

    // ── Wave 7 Tier 3 routing ─────────────────────────────────────────────────

    #[test]
    fn mesh_routes_mongosh() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "{ _id: ObjectId('507f1f77bcf86cd799439011'), name: 'Alice' }\n";
        let out = mesh.apply("mongosh", &[], raw, &ctx);
        // Routed to mongosh compressor (not psql fallback)
        assert!(!out.content.contains("ObjectId('"), "{}", out.content);
        assert!(out.content.contains("Alice"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_redis_cli() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "# Server\nredis_version:7.2.0\nos:Linux 5.15.0\narch_bits:64\n# Clients\nconnected_clients:10\nblocked_clients:0\n";
        let out = mesh.apply("redis-cli", &["info".to_string()], raw, &ctx);
        assert!(out.content.contains("redis_version"), "{}", out.content);
        assert!(!out.content.contains("arch_bits"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_cargo_deny() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "Gathered 142 crates\n  serde v1.0.195 (MIT OR Apache-2.0)\nadvisories ok\nlicenses ok\nbans ok\n";
        let out = mesh.apply("cargo-deny", &["check".to_string()], raw, &ctx);
        assert!(!out.content.contains("serde v1"), "{}", out.content);
        assert!(out.content.contains("ok"), "{}", out.content);
    }

    // ── Wave 7 Tier 4 routing ─────────────────────────────────────────────────

    #[test]
    fn mesh_routes_stylelint() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "src/main.css\n  1:5  ✕  Expected indentation of 2 spaces  indentation\n\n1 problem (1 error, 0 warnings)\n";
        let out = mesh.apply("stylelint", &["src/**/*.css".to_string()], raw, &ctx);
        // Routed to stylelint (not eslint fallback)
        assert!(
            out.content.contains("main.css") || out.content.contains("indentation"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_flake8() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "src/main.py:10:5: E302 expected 2 blank lines, found 1\nsrc/main.py:3:1: F401 'os' imported but unused\n";
        let out = mesh.apply("flake8", &[], raw, &ctx);
        assert!(
            out.content.contains("E302") || out.content.contains("F401"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_pylint() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "************* Module mymod\nmymod.py:5:0: W0611: Unused import os (unused-import)\nYour code has been rated at 9.00/10\n";
        let out = mesh.apply("pylint", &["mymod.py".to_string()], raw, &ctx);
        assert!(!out.content.contains("Module mymod"), "{}", out.content);
        assert!(
            out.content.contains("W0611") || out.content.contains("9.00/10"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_django_manage() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "Performing system checks...\n\nSystem check identified no issues (0 silenced).\n\nRunning migrations:\n  Applying myapp.0001_initial... OK\n";
        let out = mesh.apply(
            "python",
            &["manage.py".to_string(), "migrate".to_string()],
            raw,
            &ctx,
        );
        assert!(
            !out.content.contains("System check identified"),
            "{}",
            out.content
        );
        assert!(out.content.contains("0001_initial"), "{}", out.content);
    }

    // ── Wave 8 Tier 2/3/4 routing tests ──────────────────────────────────────

    #[test]
    fn mesh_routes_argocd_sync() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "time=\"2024-01-01T00:00:00Z\" msg=\"Syncing\" app=my-app\nWaiting for app to become healthy...\nWaiting for app to become healthy...\ndeployment.apps/my-app  Synced  Healthy\n";
        let out = mesh.apply(
            "argocd",
            &["app".to_string(), "sync".to_string(), "my-app".to_string()],
            raw,
            &ctx,
        );
        assert!(!out.content.contains("Waiting for app"), "{}", out.content);
        assert!(
            out.content.contains("Synced") || out.content.contains("Healthy"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_skaffold_build() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "#1 [internal] load build definition\n#1 CACHED\n#2 CACHED\nBuilding [my-app]...\nSuccessfully built abc123\n";
        let out = mesh.apply("skaffold", &["build".to_string()], raw, &ctx);
        assert!(!out.content.contains("#1 CACHED"), "{}", out.content);
        assert!(
            out.content.contains("Successfully built") || out.content.contains("Building"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_dbt_run() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "Running with dbt=1.7.0\nFound 3 models\n12:00:00  1 of 3 OK created sql table model dbt_dev.stg_orders [OK in 1.23s]\n12:00:01  2 of 3 ERROR creating sql table model dbt_dev.bad [ERROR in 0.1s]\nDone. PASS=1 ERROR=1\n";
        let out = mesh.apply("dbt", &["run".to_string()], raw, &ctx);
        assert!(!out.content.contains("Running with dbt"), "{}", out.content);
        assert!(
            out.content.contains("ERROR") || out.content.contains("OK"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_alembic() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.\nINFO  [alembic.runtime.migration] Running upgrade  -> abc123, add users table\n";
        let out = mesh.apply(
            "alembic",
            &["upgrade".to_string(), "head".to_string()],
            raw,
            &ctx,
        );
        assert!(!out.content.contains("INFO  [alembic"), "{}", out.content);
        assert!(
            out.content.contains("add users table") || out.content.contains("->"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_flyway() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "Flyway Community Edition 9.22.3 by Redgate\nDatabase: jdbc:postgresql://localhost:5432/mydb\nSuccessfully applied 1 migration to schema \"public\"\n";
        let out = mesh.apply("flyway", &["migrate".to_string()], raw, &ctx);
        assert!(
            !out.content.contains("Flyway Community Edition"),
            "{}",
            out.content
        );
        assert!(!out.content.contains("jdbc:postgresql"), "{}", out.content);
        assert!(
            out.content.contains("Successfully applied"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_mlflow() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "INFO mlflow.tracking.fluent: Autologging enabled.\nRun ID: abc123\nLogged metrics: loss=0.245\n";
        let out = mesh.apply("mlflow", &["run".to_string(), ".".to_string()], raw, &ctx);
        assert!(!out.content.contains("INFO mlflow"), "{}", out.content);
        assert!(
            out.content.contains("abc123") || out.content.contains("loss"),
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_spark_submit() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "SLF4J: Class path contains multiple SLF4J bindings.\n24/01/01 12:00:00 INFO SparkContext: Running Spark version 3.4.1\nHello from Spark!\n24/01/01 12:00:01 INFO SparkContext: Successfully stopped SparkContext\n";
        let out = mesh.apply("spark-submit", &["my_job.py".to_string()], raw, &ctx);
        assert!(!out.content.contains("SLF4J:"), "{}", out.content);
        assert!(
            !out.content.contains("INFO SparkContext"),
            "{}",
            out.content
        );
        assert!(out.content.contains("Hello from Spark"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_linkerd_check() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "√ control plane Namespace exists\n‼ gap in control plane version\n× certificate is expiring soon: cert expires in 3 days\n";
        let out = mesh.apply("linkerd", &["check".to_string()], raw, &ctx);
        assert!(!out.content.contains('‼'), "{}", out.content);
        assert!(
            out.content.contains("expiring") || out.content.contains("passed"),
            "{}",
            out.content
        );
    }

    // ── Wave 8 Tier 1 routing tests ───────────────────────────────────────────

    #[test]
    fn mesh_routes_ollama_pull() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "pulling manifest\npulling layer sha256:abc123\n[=====>   ] 34%\nverifying sha256 digest\nwriting manifest\nsuccess\n";
        let out = mesh.apply(
            "ollama",
            &["pull".to_string(), "llama3".to_string()],
            raw,
            &ctx,
        );
        assert!(!out.content.contains("pulling manifest"), "{}", out.content);
        assert!(!out.content.contains("verifying sha256"), "{}", out.content);
        assert!(
            out.content.contains("success") || out.content == "pulled successfully",
            "{}",
            out.content
        );
    }

    #[test]
    fn mesh_routes_grype() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = " ✔ Loaded image\n ✔ Cataloged packages\nNAME       INSTALLED  FIXED-IN  TYPE  VULNERABILITY   SEVERITY\nlog4j-core  2.14.0    2.17.0   java  CVE-2021-44228  Critical\n\n1 vulnerability found\n";
        let out = mesh.apply("grype", &["my-image:latest".to_string()], raw, &ctx);
        assert!(!out.content.contains("Loaded image"), "{}", out.content);
        assert!(out.content.contains("CVE-2021-44228"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_syft() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = " ✔ Loaded image\n ✔ Cataloged packages\nNAME     VERSION  TYPE\nopenssl  3.0.2    deb\ncurl     7.81.0   deb\n";
        let out = mesh.apply("syft", &["my-image:latest".to_string()], raw, &ctx);
        assert!(!out.content.contains("Loaded image"), "{}", out.content);
        assert!(out.content.contains("openssl"), "{}", out.content);
    }

    #[test]
    fn mesh_routes_cosign() {
        let mesh = FilterMesh::default_mesh();
        let ctx = LensContext::new(4000);
        let raw = "Verification for gcr.io/my-project/my-image:latest:\n-----BEGIN CERTIFICATE-----\nMIIBvzCCAWag\n-----END CERTIFICATE-----\nSubject: https://github.com/my-org/my-repo\nIssuer: https://token.actions.githubusercontent.com\n";
        let out = mesh.apply(
            "cosign",
            &[
                "verify".to_string(),
                "gcr.io/my-project/my-image:latest".to_string(),
            ],
            raw,
            &ctx,
        );
        assert!(
            !out.content.contains("BEGIN CERTIFICATE"),
            "{}",
            out.content
        );
        assert!(
            out.content.contains("Subject") || out.content.contains("Issuer"),
            "{}",
            out.content
        );
    }

    // ── scan_secrets_enabled ──────────────────────────────────────────────────

    fn write_recipe_file(dir: &std::path::Path, name: &str, content: &str) {
        use std::io::Write;
        let mut f = std::fs::File::create(dir.join(name)).unwrap();
        f.write_all(content.as_bytes()).unwrap();
    }

    #[test]
    fn scan_secrets_enabled_true_for_builtin_node() {
        // Built-in MeshNodes (e.g. "git") have no recipe → scanning is always on.
        let mesh = FilterMesh::default_mesh();
        assert!(mesh.scan_secrets_enabled("git", &["log".into()]));
        assert!(mesh.scan_secrets_enabled("cargo", &["build".into()]));
    }

    #[test]
    fn scan_secrets_enabled_true_for_unmatched_command() {
        // When no node handles the command, scanning defaults to true.
        let mesh = FilterMesh::default_mesh();
        assert!(mesh.scan_secrets_enabled("some-unknown-tool", &[]));
    }

    #[test]
    fn scan_secrets_enabled_false_for_opted_out_recipe() {
        let tmp = tempfile::TempDir::new().unwrap();
        let bctx_dir = tmp.path().join(".bctx").join("recipes");
        std::fs::create_dir_all(&bctx_dir).unwrap();
        write_recipe_file(
            &bctx_dir,
            "deploy.toml",
            "name = \"deploy-script\"\nmatch_command = \"^deploy\"\nscan_secrets = false\n",
        );
        let mesh = FilterMesh::default_mesh().with_project_recipes(tmp.path());
        assert!(!mesh.scan_secrets_enabled("deploy", &["prod".into()]));
    }

    #[test]
    fn scan_secrets_enabled_true_for_opted_in_recipe() {
        let tmp = tempfile::TempDir::new().unwrap();
        let bctx_dir = tmp.path().join(".bctx").join("recipes");
        std::fs::create_dir_all(&bctx_dir).unwrap();
        write_recipe_file(
            &bctx_dir,
            "my-tool.toml",
            "name = \"my-tool\"\nmatch_command = \"^my-tool\"\nscan_secrets = true\n",
        );
        let mesh = FilterMesh::default_mesh().with_project_recipes(tmp.path());
        assert!(mesh.scan_secrets_enabled("my-tool", &["build".into()]));
    }

    #[test]
    fn scan_secrets_enabled_true_for_recipe_without_field() {
        // `scan_secrets` defaults to true when omitted from TOML.
        let tmp = tempfile::TempDir::new().unwrap();
        let bctx_dir = tmp.path().join(".bctx").join("recipes");
        std::fs::create_dir_all(&bctx_dir).unwrap();
        write_recipe_file(
            &bctx_dir,
            "no-field.toml",
            "name = \"no-field-tool\"\nmatch_command = \"^no-field-tool\"\n",
        );
        let mesh = FilterMesh::default_mesh().with_project_recipes(tmp.path());
        assert!(mesh.scan_secrets_enabled("no-field-tool", &[]));
    }
}
