build.rs

//! Embeds the rule packs under rules/, the Markdown that explains each rule, and the agent
//! skills under skills/ into the binary.
//!
//! Each folder `rules/<module>/` is the pack for the Python library imported as `<module>`, or
//! for Python itself when its manifest says `everyFile: true`.
//! `pack.yml` is the pack's manifest, `<rule id>.yml` holds the documents of one rule, and
//! `<rule id>.md` explains a rule or a package check of the manifest. `pack.md` introduces the
//! pack and lists each of its rules once under a heading, and the folder `utils/` holds
//! `<utility id>.yml`, one utility rule that every rule of the pack can name with `matches`.
//! The folder `rules/xpd/` holds the Markdown of xpd's own rule, `xpd/unused-suppression`, and
//! in `playbooks/` xpd's own recipes, which join the search index. This script writes `OUT_DIR/packs.rs`, which src/pack.rs includes, so a new rule or
//! a new pack needs no Rust change. It also writes `OUT_DIR/skills.rs`, which src/skills.rs
//! includes.

use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail, ensure};
use ast_grep_config::UNUSED_SUPPRESSION_ID;
use pack_names::{
    OWN_PACK, RuleSymbol, TransformerMethods, is_module_name, public_module, transformer_methods,
};
use serde_json::Value;

#[path = "src/pack_names.rs"]
mod pack_names;
#[path = "src/search.rs"]
mod search;
#[expect(
    dead_code,
    reason = "build.rs reads WorkflowId metadata without calling every runtime policy helper"
)]
#[path = "src/ledger/workflow_registry.rs"]
mod workflow_registry;
#[expect(
    dead_code,
    reason = "build.rs uses WorkflowRole parsing and search terms without calling every CLI helper"
)]
#[path = "src/workflow_role.rs"]
mod workflow_role;

/// The file in a pack folder that is the manifest and not a rule.
const MANIFEST: &str = "pack.yml";
/// The file in a pack folder that introduces the pack and groups its rules.
const PACK_PAGE: &str = "pack.md";
/// Workflow-internal packs under `rules/` that are not Python libraries and carry no API index.
const NON_LIBRARY_PACKS: &[&str] = &["feature-engineering", "time-series"];
/// The folder in `rules/xpd/` that holds the playbooks, which are xpd's own recipes.
const PLAYBOOKS: &str = "playbooks";
/// Where the source of a playbook can be read.
const REPOSITORY: &str = "https://git.cafe/dynd/xpd";
/// The folder in a pack folder that holds the pack's shared utility rules.
const UTILS: &str = "utils";
/// The manifest of the plugin that this repository is. Claude Code and Codex both read it.
const PLUGIN: &str = ".claude-plugin/plugin.json";
/// The plugin's file that starts xpd with `uvx xpd@VERSION`.
const PLUGIN_MCP: &str = "mcp.json";
/// The vector of each index record, by the record's name. `xpd find --write-vectors` writes it.
const VECTORS: &str = "indexes/vectors.bin";
use search::{
    DIMENSIONS, TAG_ARRAY, TAG_FALSE, TAG_NULL, TAG_OBJECT, TAG_STRING, TAG_TRUE, VECTORS_HEADER,
};

fn text_hash(name: &str, summary: &str) -> u64 {
    name.bytes()
        .chain([0])
        .chain(summary.bytes())
        .fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
            (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
        })
}
/// Fails the build when the plugin names another version than the crate, so a release
/// cannot ship skills under an old version or start an old xpd.
fn plugin_version() -> Result<()> {
    let version = env::var("CARGO_PKG_VERSION").context("cargo sets CARGO_PKG_VERSION")?;
    let manifest = fs::read_to_string(PLUGIN).with_context(|| format!("cannot read {PLUGIN}"))?;
    if !manifest.contains(&format!("\"version\": \"{version}\"")) {
        bail!("{PLUGIN} must have \"version\": \"{version}\", as Cargo.toml does");
    }
    let servers =
        fs::read_to_string(PLUGIN_MCP).with_context(|| format!("cannot read {PLUGIN_MCP}"))?;
    if !servers.contains(&format!("\"xpd@{version}\"")) {
        bail!("{PLUGIN_MCP} must start \"xpd@{version}\", as Cargo.toml does");
    }
    Ok(())
}

fn git_path(arg: &str) -> Option<PathBuf> {
    std::process::Command::new("git")
        .args(["rev-parse", "--git-path", arg])
        .output()
        .ok()
        .filter(|out| out.status.success())
        .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_owned())
        .filter(|s| !s.is_empty())
        .map(PathBuf::from)
}

/// Emits `XPD_BUILD_SHA` and `XPD_BUILD_VERSION` so `xpd --version` and `fact_cache` always
/// identify the exact commit when built from a git checkout.
fn stamp_git_version() -> Result<()> {
    let version = env::var("CARGO_PKG_VERSION").context("cargo sets CARGO_PKG_VERSION")?;
    if let Some(git_head) = git_path("HEAD").filter(|p| p.is_file()) {
        println!("cargo:rerun-if-changed={}", git_head.display());
        if let Ok(head_text) = fs::read_to_string(&git_head)
            && let Some(ref_path) = head_text.trim().strip_prefix("ref: ")
        {
            if let Some(full_ref) = git_path(ref_path) {
                println!("cargo:rerun-if-changed={}", full_ref.display());
            }
            if let Some(packed) = git_path("packed-refs").filter(|p| p.is_file()) {
                println!("cargo:rerun-if-changed={}", packed.display());
            }
        }
    }
    let sha = std::process::Command::new("git")
        .args(["rev-parse", "--short=8", "HEAD"])
        .output()
        .ok()
        .filter(|out| out.status.success())
        .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_owned())
        .filter(|s| !s.is_empty());
    if let Some(sha) = sha {
        println!("cargo:rustc-env=XPD_BUILD_SHA={sha}");
        println!("cargo:rustc-env=XPD_BUILD_VERSION={version} ({sha})");
    } else {
        println!("cargo:rustc-env=XPD_BUILD_SHA=release");
        println!("cargo:rustc-env=XPD_BUILD_VERSION={version}");
    }
    Ok(())
}

fn main() -> Result<()> {
    stamp_git_version()?;
    let out =
        PathBuf::from(env::var_os("OUT_DIR").context("cargo sets OUT_DIR for build scripts")?);
    let root = Path::new("rules");
    println!("cargo:rerun-if-changed={}", root.display());
    println!("cargo:rerun-if-changed=skills");
    println!("cargo:rerun-if-changed={PLUGIN}");
    println!("cargo:rerun-if-changed={PLUGIN_MCP}");
    plugin_version()?;
    verify_workflows()?;
    println!("cargo:rerun-if-changed=indexes");
    let mut packs = Vec::new();
    let mut docs = BTreeMap::new();
    let mut library_packs = BTreeSet::new();
    let mut own = None;
    let mut owners = BTreeMap::new();
    let mut workflow_packs: BTreeMap<workflow_registry::WorkflowId, Vec<String>> = BTreeMap::new();
    let mut rules_digest: u64 = 0xcbf2_9ce4_8422_2325;
    for pack in sorted_entries(root)?.iter().filter(|path| path.is_dir()) {
        let module = utf8_name(pack)?;
        if module == OWN_PACK {
            let ids = [UNUSED_SUPPRESSION_ID.to_owned()];
            own = Some(doc_sources(&rule_markdown(pack, &ids)?));
            continue;
        }
        let built = pack_source(pack, &mut owners, &mut workflow_packs)?;
        rules_digest = text_hash(&format!("{rules_digest:016x}:{module}"), &built.source);
        packs.push(built.source);
        docs.insert(module.to_owned(), built.docs);
        if built.requires_index {
            library_packs.insert(module.to_owned());
        }
    }
    let own = own.with_context(|| format!("rules/{OWN_PACK} is missing"))?;
    discovery_source(&out, &docs, &library_packs)?;
    write(&out.join("packs.rs"), &format!("&[\n{}]", packs.concat()))?;
    write(
        &out.join("rules_digest.rs"),
        &format!("\"{rules_digest:016x}\""),
    )?;
    write(
        &out.join("pack_workflows.rs"),
        &pack_workflows_source(&workflow_packs),
    )?;
    write(&out.join("own_docs.rs"), &format!("&[\n{own}]"))?;
    compress_manimgx_index(&out)?;
    write(&out.join("skills.rs"), &skills_source(Path::new("skills"))?)
}

/// Writes `OUT_DIR/manimgx.json.deflate`, the specialized `ManimGX` index compressed. The JSON
/// is 8 MB and only `xpd animate catalog` and lookups in the `manimgx` package read it, so the
/// binary carries it at a fifth of its size and inflates it on first use.
fn compress_manimgx_index(out: &Path) -> Result<()> {
    let source = Path::new("indexes/specialized/manimgx.json");
    let json = fs::read(source).with_context(|| format!("cannot read {}", source.display()))?;
    fs::write(
        out.join("manimgx.json.deflate"),
        miniz_oxide::deflate::compress_to_vec(&json, 9),
    )
    .context("cannot write manimgx.json.deflate")
}

fn pack_workflows_source(
    workflow_packs: &BTreeMap<workflow_registry::WorkflowId, Vec<String>>,
) -> String {
    let mut grouped: BTreeMap<&[String], Vec<workflow_registry::WorkflowId>> = BTreeMap::new();
    for &id in workflow_registry::WorkflowId::ALL {
        let packs = workflow_packs.get(&id).map_or(&[][..], Vec::as_slice);
        grouped.entry(packs).or_default().push(id);
    }
    let mut out = String::from("match workflow {\n");
    for (packs, ids) in grouped {
        let patterns: Vec<String> = ids
            .iter()
            .map(|id| format!("crate::ledger::WorkflowId::{id:?}"))
            .collect();
        let items: Vec<String> = packs.iter().map(|pack| format!("{pack:?}")).collect();
        let _ = writeln!(
            out,
            "    {} => &[{}],",
            patterns.join(" | "),
            items.join(", ")
        );
    }
    out.push('}');
    out
}

fn record_pack_workflows(
    module: &str,
    data: &Value,
    workflow_packs: &mut BTreeMap<workflow_registry::WorkflowId, Vec<String>>,
) -> Result<()> {
    let Some(workflows) = data.get("workflows") else {
        return Ok(());
    };
    let list = workflows.as_array().with_context(|| {
        format!("rules/{module}/{MANIFEST}: `workflows` must be an array of workflow slugs")
    })?;
    let mut seen_workflows = BTreeSet::new();
    for entry in list {
        let slug = entry.as_str().with_context(|| {
            format!("rules/{module}/{MANIFEST}: each `workflows` entry must be a string")
        })?;
        let workflow: workflow_registry::WorkflowId = slug.parse().with_context(|| {
            format!("rules/{module}/{MANIFEST}: unknown workflow `{slug}` in `workflows`")
        })?;
        ensure!(
            seen_workflows.insert(workflow),
            "rules/{module}/{MANIFEST}: duplicate workflow `{slug}` in `workflows`"
        );
        workflow_packs
            .entry(workflow)
            .or_default()
            .push(module.to_owned());
    }
    Ok(())
}

fn write(target: &Path, source: &str) -> Result<()> {
    fs::write(target, source).with_context(|| format!("cannot write {}", target.display()))
}

struct BuiltPack {
    source: String,
    docs: BTreeMap<String, String>,
    requires_index: bool,
}

/// The `PackSource` literal for one pack folder, the Markdown of each of its rules and package
/// checks by id, and whether the pack represents a Python library requiring `indexes/<module>.json`.
fn pack_source<'a>(
    pack: &'a Path,
    owners: &mut BTreeMap<String, &'a str>,
    workflow_packs: &mut BTreeMap<workflow_registry::WorkflowId, Vec<String>>,
) -> Result<BuiltPack> {
    let module = utf8_name(pack)?;
    ensure!(
        NON_LIBRARY_PACKS.contains(&module)
            || (is_module_name(module) && !module.bytes().any(|byte| byte.is_ascii_uppercase())),
        "rules/{module}: the folder name must be a Python module name"
    );
    let mut manifest = String::from("None");
    let mut header = Value::Null;
    let mut rules = Vec::new();
    let mut ids = Vec::new();
    let mut selectors = Vec::new();
    let utils_dir = pack.join(UTILS);
    let (utils, pack_utils) = if utils_dir.is_dir() {
        util_sources(module, &utils_dir)?
    } else {
        (Vec::new(), BTreeMap::new())
    };
    for file in sorted_entries(pack)? {
        let name = utf8_name(&file)?;
        if name.starts_with('.') || is_markdown(&file) {
            continue;
        }
        if name == UTILS && file.is_dir() {
            continue;
        }
        let include = include(&format!("/rules/{module}/{name}"));
        let yaml =
            fs::read_to_string(&file).with_context(|| format!("cannot read {}", file.display()))?;
        if name == MANIFEST {
            manifest = format!("Some({include})");
            header = parse_manifest(
                module,
                &file,
                &yaml,
                owners,
                workflow_packs,
                &mut selectors,
                &mut ids,
            )?;
        } else {
            let id = name.strip_suffix(".yml").with_context(|| {
                format!("rules/{module}/{name}: a pack holds {MANIFEST}, {PACK_PAGE}, <rule id>.yml and <rule id>.md files")
            })?;
            let documents: Vec<Value> = ast_grep_config::from_multiple(&yaml)
                .with_context(|| file.display().to_string())?;
            ensure!(
                !documents.is_empty() && documents.iter().all(|doc| yaml_id(doc) == Some(id)),
                "rules/{module}/{name}: every rule document in the file must have the id {id:?}"
            );
            let path = format!("rules/{module}/{name}");
            let public_id = |doc: &Value| {
                doc["metadata"]["publicId"]
                    .as_str()
                    .unwrap_or(id)
                    .to_owned()
            };
            let public = public_id(&documents[0]);
            ensure!(
                documents.iter().all(|doc| public_id(doc) == public),
                "rules/{module}/{name}: publicId must agree across documents"
            );
            let has_error = documents
                .iter()
                .any(|doc| doc["severity"].as_str() == Some("error"));
            selectors.push(rule_selector(&documents, &public, &path)?);
            let offsets = document_offsets(&yaml, &documents);
            let doc_tokens = doc_tokens_literal(&documents, &pack_utils);
            rules.push(format!(
                "            RuleSource {{ document_offsets: &[{offsets}], doc_tokens: &[{doc_tokens}], public_id: {public:?}, has_error: {has_error}, path: {path:?}, yaml: {include} }},\n"
            ));
            if let Some(first) = owners.insert(id.to_owned(), module) {
                bail!("rules/{module}: the id {id} is also a rule of rules/{first}");
            }
            ids.push(public);
        }
    }
    ensure!(!rules.is_empty(), "rules/{module}: the pack has no rules");
    ensure!(
        ids.iter().collect::<BTreeSet<_>>().len() == ids.len(),
        "rules/{module}: duplicate public rule ID"
    );
    let docs = rule_markdown(pack, &ids)?;
    let selectors = selectors.join(", ");
    let every_file = header["everyFile"].as_bool().unwrap_or(false);
    let header = pack_header(module, &header);
    let source = format!(
        "    PackSource {{\n        module: {module:?},\n        manifest: {manifest},\n        selectors: &[{selectors}], every_file: {every_file}, {header}\n        rules: &[\n{}        ],\n        utils: &[\n{}        ],\n        docs: &[\n{}        ],\n    }},\n",
        rules.concat(),
        utils.concat(),
        doc_sources(&docs)
    );
    let requires_index = !every_file && !NON_LIBRARY_PACKS.contains(&module);
    Ok(BuiltPack {
        source,
        docs,
        requires_index,
    })
}

fn parse_manifest<'a>(
    module: &'a str,
    file: &Path,
    yaml: &str,
    owners: &mut BTreeMap<String, &'a str>,
    workflow_packs: &mut BTreeMap<workflow_registry::WorkflowId, Vec<String>>,
    selectors: &mut Vec<String>,
    ids: &mut Vec<String>,
) -> Result<Value> {
    let data: Value =
        ast_grep_config::from_str(yaml).with_context(|| file.display().to_string())?;
    record_pack_workflows(module, &data, workflow_packs)?;
    for id in data
        .get("packages")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(yaml_id)
    {
        if let Some(first) = owners.insert(id.to_owned(), module) {
            bail!("rules/{module}: the id {id} is also a rule of rules/{first}");
        }
        selectors.push(format!("({id:?}, &[(None, None)])"));
        ids.push(id.to_owned());
    }
    Ok(data)
}

fn pack_header(module: &str, header: &Value) -> String {
    let import_tokens: Vec<_> = std::iter::once(module)
        .chain(
            header["alsoImports"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(Value::as_str),
        )
        .collect();
    let has_also_on = !header["alsoOn"].is_null();
    let also_on_tokens: &[&str] = if module == "plotly"
        && header["alsoOn"]["setting"]["matches"] == "pandas-draws-with-plotly"
    {
        &["plotly"]
    } else {
        &[]
    };
    let has_unconditional_package_checks = header["packages"]
        .as_array()
        .is_some_and(|checks| checks.iter().any(|check| check["onlyWhere"].is_null()));
    format!(
        "import_tokens: &{import_tokens:?}, has_also_on: {has_also_on}, also_on_tokens: &{also_on_tokens:?}, has_unconditional_package_checks: {has_unconditional_package_checks},"
    )
}

/// Independent slices for parallel compilation, only when parsing each slice yields the original document.
fn document_offsets(yaml: &str, documents: &[Value]) -> String {
    if documents.len() < 2 {
        return String::new();
    }
    let offsets: Vec<_> = std::iter::once(0)
        .chain(yaml.match_indices("\n---\n").map(|(index, _)| index + 1))
        .chain(std::iter::once(yaml.len()))
        .collect();
    if offsets.len() == documents.len() + 1
        && offsets.windows(2).zip(documents).all(|(range, expected)| {
            ast_grep_config::from_str::<Value>(&yaml[range[0]..range[1]])
                .is_ok_and(|doc| &doc == expected)
        })
    {
        offsets
            .iter()
            .map(|offset| {
                if *offset < 1000 {
                    offset.to_string()
                } else {
                    format!("{}_{:03}", offset / 1000, offset % 1000)
                }
            })
            .collect::<Vec<_>>()
            .join(", ")
    } else {
        String::new()
    }
}

fn rule_selector(documents: &[Value], public: &str, path: &str) -> Result<String> {
    let versions: BTreeSet<_> = documents
        .iter()
        .filter(|doc| doc["severity"].as_str() != Some("off"))
        .map(|doc| {
            (
                doc["metadata"]["since"].as_str(),
                doc["metadata"]["until"].as_str(),
            )
        })
        .collect();
    ensure!(
        documents.iter().all(|doc| doc["language"] == "python"),
        "{path}: bundled file collection expects Python rules"
    );
    let versions: Vec<_> = versions.into_iter().collect();
    Ok(format!("({public:?}, &{versions:?})"))
}

/// The text of `<id>.md` in the pack folder for each id in `ids`, trimmed at the end. Fails when
/// a rule has no Markdown file, when a Markdown file names no rule, and when `pack.md` does not
/// list every id once.
fn rule_markdown(pack: &Path, ids: &[String]) -> Result<BTreeMap<String, String>> {
    let module = utf8_name(pack)?;
    let mut docs = BTreeMap::new();
    let mut page = None;
    for file in sorted_entries(pack)? {
        let name = utf8_name(&file)?;
        let Some(id) = file
            .file_stem()
            .and_then(|stem| stem.to_str())
            .filter(|_| is_markdown(&file) && !name.starts_with('.'))
        else {
            continue;
        };
        let text =
            fs::read_to_string(&file).with_context(|| format!("cannot read {}", file.display()))?;
        if name == PACK_PAGE {
            page = Some(text);
        } else {
            ensure!(
                ids.iter().any(|known| known == id),
                "rules/{module}/{name} names no rule or package check of the pack"
            );
            docs.insert(id.to_owned(), text.trim_end().to_owned());
        }
    }
    for id in ids {
        ensure!(
            docs.contains_key(id),
            "rules/{module}: {id} has no rules/{module}/{id}.md, which xpd rules, xpd find, the editor hover and the site show"
        );
    }
    let page = page.with_context(|| format!("rules/{module} has no {PACK_PAGE}"))?;
    let mut listed = BTreeSet::new();
    let mut in_code = false;
    for line in page.lines() {
        if line.trim_start().starts_with("```") {
            in_code = !in_code;
        }
        let Some(item) = line.strip_prefix("- ").filter(|item| {
            !in_code
                && item
                    .bytes()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
        }) else {
            continue;
        };
        ensure!(
            docs.contains_key(item),
            "rules/{module}/{PACK_PAGE} lists {item}, which is no rule or package check of the pack"
        );
        ensure!(
            listed.insert(item),
            "rules/{module}/{PACK_PAGE} lists {item} twice"
        );
    }
    if let Some(id) = ids.iter().find(|id| !listed.contains(id.as_str())) {
        bail!("rules/{module}/{PACK_PAGE} lists no `- {id}` under a heading");
    }
    Ok(docs)
}

/// The `DocSource` literals of the Markdown of a pack.
fn doc_sources(docs: &BTreeMap<String, String>) -> String {
    docs.iter().fold(String::new(), |mut out, (id, text)| {
        let _ = writeln!(
            out,
            "            DocSource {{ id: {id:?}, text: {text:?} }},"
        );
        out
    })
}

/// Whether `path` is a Markdown file, which explains a rule and is no rule itself.
fn is_markdown(path: &Path) -> bool {
    path.extension().is_some_and(|extension| extension == "md")
}

/// The `RuleSource` literals and parsed rules for the utility rules in `utils`.
fn util_sources(module: &str, utils: &Path) -> Result<(Vec<String>, BTreeMap<String, Value>)> {
    let mut sources = Vec::new();
    let mut parsed = BTreeMap::new();
    for file in sorted_entries(utils)? {
        let name = utf8_name(&file)?;
        if name.starts_with('.') {
            continue;
        }
        let path = format!("rules/{module}/{UTILS}/{name}");
        let id = name
            .strip_suffix(".yml")
            .with_context(|| format!("{path}: the folder holds <utility id>.yml files"))?;
        let yaml =
            fs::read_to_string(&file).with_context(|| format!("cannot read {}", file.display()))?;
        let documents: Vec<Value> =
            ast_grep_config::from_multiple(&yaml).with_context(|| file.display().to_string())?;
        ensure!(
            matches!(documents.as_slice(), [document] if yaml_id(document) == Some(id)),
            "{path}: the file must hold one utility rule with the id {id:?}"
        );
        if let Some(rule) = documents[0].get("rule") {
            parsed.insert(id.to_owned(), rule.clone());
        }
        let include = include(&format!("/{path}"));
        sources.push(format!(
            "            RuleSource {{ document_offsets: &[], doc_tokens: &[], public_id: \"\", has_error: false, path: {path:?}, yaml: {include} }},\n"
        ));
    }
    Ok((sources, parsed))
}

fn doc_tokens_literal(documents: &[Value], pack_utils: &BTreeMap<String, Value>) -> String {
    documents
        .iter()
        .map(|doc| {
            let groups = extract_doc_groups(doc, pack_utils);
            let rendered: Vec<String> = groups
                .iter()
                .map(|group| {
                    let items: Vec<String> = group.iter().map(|tok| format!("{tok:?}")).collect();
                    format!("&[{}]", items.join(", "))
                })
                .collect();
            format!("&[{}]", rendered.join(", "))
        })
        .collect::<Vec<_>>()
        .join(", ")
}

fn extract_doc_groups(doc: &Value, pack_utils: &BTreeMap<String, Value>) -> Vec<Vec<String>> {
    let Some(rule) = doc.get("rule") else {
        return Vec::new();
    };
    let own_utils = doc.get("utils").and_then(Value::as_object);
    let constraints = doc.get("constraints").and_then(Value::as_object);
    let mut seen = BTreeSet::new();
    let mut groups = extract_rule_groups(rule, own_utils, pack_utils, constraints, &mut seen);
    normalize_groups(&mut groups);
    groups
}

fn normalize_groups(groups: &mut Vec<Vec<String>>) {
    for group in groups.iter_mut() {
        group.sort();
        group.dedup();
    }
    groups.retain(|g| !g.is_empty());
    groups.sort_by_key(|group| {
        let min_len = group.iter().map(String::len).min().unwrap_or(0);
        let generic = usize::from(group.len() == 1 && is_generic_token(&group[0]));
        (
            generic,
            group.len().min(8),
            usize::MAX - min_len,
            group.len(),
        )
    });
    groups.dedup();
    groups.truncate(4);
}

fn is_generic_token(token: &str) -> bool {
    matches!(
        token,
        "in" | "is"
            | "or"
            | "as"
            | "if"
            | "for"
            | "not"
            | "and"
            | "def"
            | "from"
            | "import"
            | "return"
            | "with"
            | "True"
            | "False"
            | "None"
            | "self"
            | "df"
            | "np"
            | "pd"
            | "plt"
            | "fig"
            | "ax"
            | "fit"
            | "get"
            | "set"
            | "len"
            | "str"
            | "int"
            | "list"
            | "dict"
            | "range"
    )
}

fn extract_rule_groups<'a>(
    node: &'a Value,
    own_utils: Option<&'a serde_json::Map<String, Value>>,
    pack_utils: &'a BTreeMap<String, Value>,
    constraints: Option<&'a serde_json::Map<String, Value>>,
    seen: &mut BTreeSet<&'a str>,
) -> Vec<Vec<String>> {
    let Some(obj) = node.as_object() else {
        return Vec::new();
    };
    let mut groups: Vec<Vec<String>> = Vec::new();
    if let Some(pat) = obj.get("pattern").and_then(Value::as_str) {
        for ident in pattern_required_idents(pat) {
            groups.push(vec![ident]);
        }
        if let Some(constraints) = constraints {
            for mv in single_metavars(pat) {
                if let Some(constraint) = constraints.get(mv) {
                    groups.extend(extract_rule_groups(
                        constraint, own_utils, pack_utils, None, seen,
                    ));
                }
            }
        }
    }
    if let Some(rx) = obj.get("regex").and_then(Value::as_str) {
        groups.extend(regex_required_groups(rx));
    }
    for key in ["has", "inside", "precedes", "follows"] {
        if let Some(sub) = obj.get(key) {
            groups.extend(extract_rule_groups(
                sub,
                own_utils,
                pack_utils,
                constraints,
                seen,
            ));
        }
    }
    if let Some(name) = obj.get("matches").and_then(Value::as_str)
        && seen.insert(name)
    {
        let util = own_utils
            .and_then(|map| map.get(name))
            .or_else(|| pack_utils.get(name));
        if let Some(util) = util {
            groups.extend(extract_rule_groups(
                util,
                own_utils,
                pack_utils,
                constraints,
                seen,
            ));
        }
        seen.remove(name);
    }
    if let Some(items) = obj.get("all").and_then(Value::as_array) {
        for sub in items {
            groups.extend(extract_rule_groups(
                sub,
                own_utils,
                pack_utils,
                constraints,
                seen,
            ));
        }
    }
    if let Some(items) = obj.get("any").and_then(Value::as_array)
        && !items.is_empty()
    {
        let mut branch_groups: Vec<Vec<Vec<String>>> = Vec::with_capacity(items.len());
        let mut all_guarded = true;
        for sub in items {
            let mut sub_groups = extract_rule_groups(sub, own_utils, pack_utils, constraints, seen);
            normalize_groups(&mut sub_groups);
            if sub_groups.is_empty() {
                all_guarded = false;
                break;
            }
            branch_groups.push(sub_groups);
        }
        if all_guarded {
            if let Some(first) = branch_groups.first() {
                for shared in first {
                    if branch_groups[1..].iter().all(|b| b.contains(shared)) {
                        groups.push(shared.clone());
                    }
                }
            }
            let mut union = BTreeSet::new();
            let mut ok = true;
            for branch in &branch_groups {
                if let Some(best) = branch.first() {
                    union.extend(best.iter().cloned());
                    if union.len() > 256 {
                        ok = false;
                        break;
                    }
                }
            }
            if ok && !union.is_empty() {
                groups.push(union.into_iter().collect());
            }
        }
    }
    groups
}

fn single_metavars(pattern: &str) -> Vec<&str> {
    let bytes = pattern.as_bytes();
    let mut vars = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'$' {
            let dollars = bytes[i..].iter().take_while(|&&b| b == b'$').count();
            i += dollars;
            let start = i;
            while i < bytes.len()
                && (bytes[i].is_ascii_uppercase() || bytes[i].is_ascii_digit() || bytes[i] == b'_')
            {
                i += 1;
            }
            if dollars == 1 && i > start && bytes[start] != b'_' {
                vars.push(&pattern[start..i]);
            }
        } else {
            i += 1;
        }
    }
    vars
}

fn pattern_required_idents(pattern: &str) -> Vec<String> {
    let bytes = pattern.as_bytes();
    let mut i = 0;
    let mut found = BTreeSet::new();
    while i < bytes.len() {
        match bytes[i] {
            b'#' => {
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'\'' | b'"' => {
                let quote = bytes[i];
                let triple = bytes.get(i..i + 3) == Some(&[quote, quote, quote]);
                i += if triple { 3 } else { 1 };
                while i < bytes.len() {
                    if bytes[i] == b'\\' {
                        i = (i + 2).min(bytes.len());
                    } else if triple {
                        if bytes.get(i..i + 3) == Some(&[quote, quote, quote]) {
                            i += 3;
                            break;
                        }
                        i += 1;
                    } else if bytes[i] == quote {
                        i += 1;
                        break;
                    } else {
                        i += 1;
                    }
                }
            }
            b'$' => {
                while i < bytes.len() && bytes[i] == b'$' {
                    i += 1;
                }
                while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
                    i += 1;
                }
            }
            b if b.is_ascii_alphabetic() || b == b'_' => {
                let prev_digit = i > 0 && bytes[i - 1].is_ascii_digit();
                let start = i;
                i += 1;
                while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
                    i += 1;
                }
                let next_quote = matches!(bytes.get(i), Some(b'\'' | b'"'));
                if !prev_digit && !next_quote && i - start >= 2 {
                    found.insert(pattern[start..i].to_owned());
                }
            }
            _ => i += 1,
        }
    }
    found.into_iter().collect()
}

fn regex_required_groups(rx: &str) -> Vec<Vec<String>> {
    if !rx.is_ascii() || rx.contains("(?i") {
        return Vec::new();
    }
    if let Some(groups) = from_import_regex_groups(rx) {
        return groups;
    }
    let Some(body) = rx
        .strip_prefix(r"(^|\.)")
        .or_else(|| rx.strip_prefix('^'))
        .or_else(|| rx.strip_prefix(r"\b"))
    else {
        return Vec::new();
    };
    let Some(body) = body
        .strip_suffix(r"(\.|$)")
        .or_else(|| body.strip_suffix('$'))
        .or_else(|| body.strip_suffix(r"\b"))
    else {
        return Vec::new();
    };
    if let (Some(open), Some(close)) = (body.find('('), body.rfind(')'))
        && open < close
    {
        let prefix = &body[..open];
        let inner = &body[open + 1..close];
        let suffix = &body[close + 1..];
        if !inner.contains('(')
            && !inner.contains(')')
            && !prefix.contains('|')
            && !suffix.contains('|')
        {
            let inner_stripped = inner.strip_prefix("?:").unwrap_or(inner);
            let mut out = Vec::new();
            if prefix.is_empty() && suffix.is_empty() {
                if let Some(tokens) = ident_alternatives(inner_stripped) {
                    out.push(tokens);
                }
                return out;
            }
            if is_escaped_dotted(prefix) && is_escaped_dotted(suffix) {
                if prefix.ends_with(r"\.")
                    && let Some(seg) = longest_ident_segment(prefix)
                {
                    out.push(vec![seg]);
                }
                if suffix.starts_with(r"\.")
                    && let Some(seg) = longest_ident_segment(suffix)
                {
                    out.push(vec![seg]);
                }
                let mut expanded = BTreeSet::new();
                let mut all_valid = true;
                for alt in inner_stripped.split('|') {
                    let combined = format!("{prefix}{alt}{suffix}");
                    let Some(seg) = longest_ident_segment(&combined) else {
                        all_valid = false;
                        break;
                    };
                    expanded.insert(seg);
                    if expanded.len() > 256 {
                        all_valid = false;
                        break;
                    }
                }
                if all_valid && !expanded.is_empty() {
                    out.push(expanded.into_iter().collect());
                }
                return out;
            }
        }
        return Vec::new();
    }
    if body.contains('(') || body.contains(')') || body.contains('|') {
        return Vec::new();
    }
    ident_alternatives(body).into_iter().collect()
}

fn is_escaped_dotted(escaped: &str) -> bool {
    let unescaped = escaped.replace(r"\.", ".");
    unescaped
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.')
}

fn from_import_regex_groups(rx: &str) -> Option<Vec<Vec<String>>> {
    let rest = rx.strip_prefix(r"^from\s+")?;
    let bytes = rest.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' {
            i += 1;
        } else if bytes.get(i..i + 2) == Some(br"\.") {
            i += 2;
        } else {
            break;
        }
    }
    let prefix = &rest[..i];
    let after = &rest[i..];
    let mut out = Vec::new();
    if let Some(seg) = longest_ident_segment(prefix) {
        out.push(vec![seg]);
    }
    if after.starts_with('(')
        && let Some(close) = after.find(')')
    {
        let group = after[1..close]
            .strip_prefix("?:")
            .unwrap_or(&after[1..close]);
        let tail = &after[close + 1..];
        if !group.contains('(')
            && (tail.starts_with(r"\s") || tail.starts_with(r"\b") || tail.starts_with(r"\."))
            && let Some(tokens) = ident_alternatives(group)
        {
            out.push(tokens);
            return Some(out);
        }
    }
    if (after.starts_with(r"\s") || after.starts_with(r"\b")) && !out.is_empty() {
        return Some(out);
    }
    None
}

fn ident_alternatives(group: &str) -> Option<Vec<String>> {
    let mut out = BTreeSet::new();
    for alt in group.split('|') {
        let seg = longest_ident_segment(alt)?;
        out.insert(seg);
        if out.len() > 256 {
            return None;
        }
    }
    (!out.is_empty()).then(|| out.into_iter().collect())
}

fn longest_ident_segment(escaped: &str) -> Option<String> {
    let unescaped = escaped.replace(r"\.", ".");
    if unescaped.is_empty()
        || !unescaped
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.')
    {
        return None;
    }
    unescaped
        .split('.')
        .filter(|seg| {
            seg.len() >= 2
                && seg
                    .as_bytes()
                    .first()
                    .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_')
        })
        .max_by_key(|seg| seg.len())
        .map(str::to_owned)
}

/// The `SkillSource` list for every skill folder under `root`, each with all of its files.
fn skills_source(root: &Path) -> Result<String> {
    let mut skills = Vec::new();
    for skill in sorted_entries(root)? {
        let name = utf8_name(&skill)?;
        if !skill.is_dir() || name.starts_with('.') {
            continue;
        }
        let paths = files_below(&skill)?
            .iter()
            .map(|file| {
                let parts = file.strip_prefix(&skill)?.components().map(|part| {
                    part.as_os_str()
                        .to_str()
                        .context("a skill file has no UTF-8 name")
                });
                Ok(parts.collect::<Result<Vec<&str>>>()?.join("/"))
            })
            .collect::<Result<Vec<String>>>()?;
        ensure!(
            paths.iter().any(|path| path == "SKILL.md"),
            "skills/{name}: a skill folder needs a SKILL.md"
        );
        let files: Vec<String> = paths
            .iter()
            .map(|path| {
                let text = include(&format!("/skills/{name}/{path}"));
                format!("            SkillFile {{ path: {path:?}, text: {text} }},\n")
            })
            .collect();
        skills.push(format!(
            "    SkillSource {{\n        name: {name:?},\n        files: &[\n{}        ],\n    }},\n",
            files.concat()
        ));
    }
    Ok(format!("&[\n{}]", skills.concat()))
}

/// Every file below `dir`, in name order, without hidden files and folders.
fn files_below(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    for entry in sorted_entries(dir)? {
        if utf8_name(&entry)?.starts_with('.') {
            continue;
        }
        if entry.is_dir() {
            files.extend(files_below(&entry)?);
        } else {
            files.push(entry);
        }
    }
    Ok(files)
}

/// An `include_str!` of the file at `path` below the crate root.
fn include(path: &str) -> String {
    format!("include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), {path:?}))")
}

/// The entries of `dir` in name order, so the binary does not depend on the file system's order.
fn sorted_entries(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut entries: Vec<PathBuf> = fs::read_dir(dir)
        .and_then(|entries| entries.map(|entry| entry.map(|e| e.path())).collect())
        .with_context(|| format!("cannot list {}", dir.display()))?;
    entries.sort();
    Ok(entries)
}

fn utf8_name(path: &Path) -> Result<&str> {
    path.file_name()
        .and_then(|name| name.to_str())
        .with_context(|| format!("{} has no UTF-8 name", path.display()))
}

fn yaml_id(value: &Value) -> Option<&str> {
    value.get("id").and_then(Value::as_str)
}

const WORKFLOW_ROLES: &str = "indexes/coverage/workflow-roles.json";

fn load_workflow_roles() -> Result<BTreeMap<String, workflow_role::WorkflowRole>> {
    let mut map = BTreeMap::new();
    let path = Path::new(WORKFLOW_ROLES);
    if !path.exists() {
        return Ok(map);
    }
    println!("cargo:rerun-if-changed={WORKFLOW_ROLES}");
    let doc: serde_json::Value = serde_json::from_str(
        &fs::read_to_string(path).with_context(|| format!("cannot read {WORKFLOW_ROLES}"))?,
    )?;
    let packages = doc["packages"]
        .as_object()
        .with_context(|| format!("{WORKFLOW_ROLES}: missing packages object"))?;
    for (package, info) in packages {
        let symbols = info["symbols"]
            .as_object()
            .with_context(|| format!("{WORKFLOW_ROLES}: missing symbols for {package}"))?;
        for (symbol, meta) in symbols {
            let slug = meta["role"]
                .as_str()
                .with_context(|| format!("{WORKFLOW_ROLES}: missing role for {symbol}"))?;
            let role = workflow_role::WorkflowRole::parse(slug)
                .with_context(|| format!("{WORKFLOW_ROLES}: unknown role {slug:?} for {symbol}"))?;
            ensure!(
                map.insert(symbol.clone(), role).is_none(),
                "{WORKFLOW_ROLES}: duplicate symbol {symbol}"
            );
        }
    }
    Ok(map)
}

fn entry_workflow_role(
    entry: &serde_json::Value,
    role_map: &BTreeMap<String, workflow_role::WorkflowRole>,
) -> Option<workflow_role::WorkflowRole> {
    if entry["kind"] != "symbol" {
        return None;
    }
    let name = entry["name"].as_str().unwrap_or_default();
    role_map.get(name).copied().or_else(|| {
        entry["aliases"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(serde_json::Value::as_str)
            .find_map(|alias| role_map.get(alias).copied())
    })
}

fn discovery_source(
    out: &Path,
    docs: &BTreeMap<String, BTreeMap<String, String>>,
    library_packs: &BTreeSet<String>,
) -> Result<()> {
    let role_map = load_workflow_roles()?;
    let mut entries = Vec::<serde_json::Value>::new();
    let mut indexed_symbols = BTreeMap::<String, usize>::new();
    for path in sorted_entries(Path::new("indexes"))? {
        if path.extension().is_none_or(|e| e != "json") || path.ends_with("questions.json") {
            continue;
        }
        let stem = path
            .file_stem()
            .and_then(|stem| stem.to_str())
            .with_context(|| format!("{} has no UTF-8 stem", path.display()))?;
        let index: serde_json::Value = serde_json::from_str(&fs::read_to_string(&path)?)?;
        let index_entries = index["entries"].as_array().context("index entries")?;
        let symbols = index_entries
            .iter()
            .filter(|entry| entry["kind"] == "symbol")
            .count();
        indexed_symbols.insert(stem.to_owned(), symbols);
        entries.extend(index_entries.iter().cloned());
    }
    for module in library_packs {
        let Some(&symbols) = indexed_symbols.get(module) else {
            bail!(
                "rules/{module}: bundled library pack is missing indexes/{module}.json. Build it with `uv run --no-project --with griffe==2.4.1 cargo xtask index <site-packages> --package {module}`."
            );
        };
        ensure!(
            symbols > 0,
            "rules/{module}: indexes/{module}.json contains no public symbols"
        );
    }
    write(&out.join("rule_modules.rs"), &rule_modules(&entries)?)?;
    entries.extend(playbooks(docs)?);
    for (package, sections) in docs {
        for (id, doc) in sections {
            entries.push(serde_json::json!({"kind":"rule","package":package,"name":format!("{package}/{id}"),"callable":null,"parameters":[],"summary":doc.trim(),"members":[],"rules":[]}));
        }
    }
    let mut records = String::from("&[\n");
    let mut strings = BTreeMap::new();
    let mut data = Vec::new();
    for entry in &entries {
        let name = entry["name"].as_str().context("entry name")?;
        let package = entry["package"].as_str().context("entry package")?;
        let kind = match entry["kind"].as_str() {
            Some("rule") => "Rule",
            Some("recipe") => "Recipe",
            _ => "Symbol",
        };
        let summary = entry["summary"].as_str().unwrap_or_default();
        let aliases: Vec<_> = entry["aliases"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(serde_json::Value::as_str)
            .collect();
        let transformer = indexed_transformer(entry);
        let role = entry_workflow_role(entry, &role_map);
        let role_expr = role.map_or_else(
            || "None".to_owned(),
            |r| format!("Some(WorkflowRole::{r:?})"),
        );
        let text = text_hash(name, summary);
        let mut output = entry.clone();
        let obj = output.as_object_mut().context("entry object")?;
        obj.remove("keywords");
        if let Some(r) = role {
            obj.insert(
                "workflow_role".to_owned(),
                serde_json::Value::String(r.as_slug().to_owned()),
            );
        }
        let start = data.len();
        encode(&output, &mut strings, &mut data)?;
        let len = u32::try_from(data.len() - start)?;
        writeln!(
            records,
            "Stored {{name:{name:?},aliases:&{aliases:?},package:{package:?},kind:Kind::{kind},summary:{summary:?},transformer:TransformerMethods::{transformer:?},workflow_role:{role_expr},text:0x{:04x}_{:04x}_{:04x}_{:04x},start:0x{:04x}_{:04x},len:{len}}},",
            text >> 48,
            (text >> 32) & 0xffff,
            (text >> 16) & 0xffff,
            text & 0xffff,
            start >> 16,
            start & 0xffff
        )?;
    }
    records.push(']');
    fs::write(out.join("entries.bin"), data)?;
    let mut ordered = vec![""; strings.len()];
    for (text, id) in &strings {
        ordered[usize::try_from(*id)?] = text;
    }
    write(&out.join("strings.rs"), &format!("&{ordered:?}"))?;
    write(&out.join("records.rs"), &records)?;
    vectors_source(out, &entries)?;
    search_source(out, &entries, &role_map)
}

fn indexed_transformer(entry: &serde_json::Value) -> TransformerMethods {
    if entry["callable"] != "class" {
        return TransformerMethods::Absent;
    }
    transformer_methods(
        entry["members"]
            .as_array()
            .into_iter()
            .flatten()
            .filter(|member| member["property"] != true)
            .filter_map(|member| member["name"].as_str()),
    )
}

/// Keep the reverse links available to rule commands without decoding the API catalog.
fn rule_modules(entries: &[serde_json::Value]) -> Result<String> {
    let mut links = BTreeMap::<&str, BTreeSet<RuleSymbol<'_>>>::new();
    for entry in entries.iter().filter(|entry| entry["kind"] == "symbol") {
        let package = entry["package"].as_str().context("entry package")?;
        let symbol = entry["name"].as_str().context("entry name")?;
        let module = public_module(package, symbol);
        let transformer = indexed_transformer(entry);
        for rule in entry["rules"].as_array().into_iter().flatten() {
            let id = rule.as_str().context("qualified guard rule ID")?;
            links
                .entry(id)
                .or_default()
                .insert((package, symbol, module, transformer));
        }
    }
    let mut source = String::from("&[\n");
    for (id, modules) in links {
        writeln!(source, "({id:?}, &[")?;
        for (package, symbol, module, transformer) in modules {
            writeln!(
                source,
                "({package:?}, {symbol:?}, {module:?}, TransformerMethods::{transformer:?}),"
            )?;
        }
        writeln!(source, "]),")?;
    }
    source.push(']');
    Ok(source)
}

/// The playbooks under `rules/xpd/playbooks`, each as a recipe of the `xpd` package named
/// `xpd/recipe/<file name>`. A playbook is a Markdown file with a title, a first paragraph and
/// the sections `Asks`, `Code`, `Commands` and `Rules`. Its asks are in the summary, which the
/// keyword search and the embedding model both read, so a loose ask finds its playbook. `docs`
/// holds the rule ids of each pack, and a playbook that names another rule fails the build.
fn playbooks(docs: &BTreeMap<String, BTreeMap<String, String>>) -> Result<Vec<serde_json::Value>> {
    let version = env::var("CARGO_PKG_VERSION").context("cargo sets CARGO_PKG_VERSION")?;
    let mut entries = Vec::new();
    for file in sorted_entries(&Path::new("rules").join(OWN_PACK).join(PLAYBOOKS))? {
        let name = utf8_name(&file)?;
        let Some(stem) = name.strip_suffix(".md") else {
            continue;
        };
        let text =
            fs::read_to_string(&file).with_context(|| format!("cannot read {}", file.display()))?;
        let mut sections = BTreeMap::<&str, Vec<&str>>::new();
        let mut section = "";
        let mut in_code = false;
        for line in text.lines() {
            if line.starts_with("```") {
                in_code = !in_code;
            } else if let Some(heading) = line.strip_prefix("## ").filter(|_| !in_code) {
                section = heading.trim();
            } else {
                sections.entry(section).or_default().push(line);
            }
        }
        let lines = |section: &str| sections.get(section).cloned().unwrap_or_default();
        let items = |section: &str| -> Vec<String> {
            (lines(section).iter())
                .filter_map(|line| line.split_once(' '))
                .filter(|(mark, _)| *mark == "-" || mark.ends_with('.'))
                .map(|(_, item)| item.trim().to_owned())
                .collect()
        };
        let intro = lines("");
        let title = (intro.iter())
            .find_map(|line| line.strip_prefix("# "))
            .with_context(|| format!("{}: a playbook starts with a `# ` title", file.display()))?;
        let about: Vec<&str> = (intro.iter().copied())
            .filter(|line| !line.starts_with("# ") && !line.trim().is_empty())
            .collect();
        let (asks, commands, rules) = (items("Asks"), items("Commands"), items("Rules"));
        let code = format!("{}\n", lines("Code").join("\n").trim());
        ensure!(
            !about.is_empty() && !asks.is_empty() && !commands.is_empty() && code.trim() != "",
            "{}: a playbook has a first paragraph and the sections Asks, Code and Commands",
            file.display()
        );
        for rule in &rules {
            let known = rule
                .split_once('/')
                .is_some_and(|(pack, id)| docs.get(pack).is_some_and(|ids| ids.contains_key(id)));
            ensure!(known, "{}: {rule} is no rule of a pack", file.display());
        }
        let summary = format!(
            "{title}. {}\n\nIt answers asks such as: {}.",
            about.join(" "),
            asks.join(", ")
        );
        entries.push(serde_json::json!({
            "kind": "recipe",
            "package": OWN_PACK,
            "name": format!("{OWN_PACK}/recipe/{stem}"),
            "callable": null,
            "parameters": [],
            "summary": summary,
            "keywords": asks,
            "members": [],
            "rules": rules,
            "recipe": {
                "title": title,
                "symbols": [],
                "source": format!("{REPOSITORY}/blob/v{version}/rules/{OWN_PACK}/{PLAYBOOKS}/{name}"),
                "code": code,
                "license": "MIT OR Apache-2.0",
                "modified": false,
                "asks": asks,
                "commands": commands,
            },
        }));
    }
    Ok(entries)
}

/// Writes `OUT_DIR/vectors.bin`, the vector of each entry in the order of the entries. An entry
/// gets zeros when `VECTORS` has no vector for it, or has one made from another text, and
/// `xpd find --check` fails on it.
fn vectors_source(out: &Path, entries: &[serde_json::Value]) -> Result<()> {
    let bytes = if Path::new(VECTORS).exists() {
        fs::read(VECTORS).with_context(|| format!("cannot read {VECTORS}"))?
    } else {
        VECTORS_HEADER.to_vec()
    };
    let mut rest = bytes
        .strip_prefix(VECTORS_HEADER)
        .with_context(|| format!("{VECTORS} does not start with {VECTORS_HEADER:?}"))?;
    let mut found = BTreeMap::new();
    while let Some((length, tail)) = rest.split_first_chunk::<2>() {
        let (name, tail) = tail
            .split_at_checked(usize::from(u16::from_le_bytes(*length)))
            .with_context(|| format!("{VECTORS} ends inside a name"))?;
        let (hash, tail) = tail
            .split_first_chunk::<8>()
            .with_context(|| format!("{VECTORS} ends inside a text hash"))?;
        let (vector, tail) = tail
            .split_at_checked(DIMENSIONS)
            .with_context(|| format!("{VECTORS} ends inside a vector"))?;
        found.insert(
            std::str::from_utf8(name)?,
            (u64::from_le_bytes(*hash), vector),
        );
        rest = tail;
    }
    ensure!(rest.is_empty(), "{VECTORS} ends inside a name length");
    let mut data = Vec::with_capacity(entries.len() * DIMENSIONS);
    for entry in entries {
        let name = entry["name"].as_str().context("entry name")?;
        let summary = entry["summary"].as_str().unwrap_or_default();
        match found.get(name) {
            Some((hash, vector)) if *hash == text_hash(name, summary) => {
                data.extend_from_slice(vector);
            }
            _ => data.resize(data.len() + DIMENSIONS, 0),
        }
    }
    fs::write(out.join("vectors.bin"), data)?;
    Ok(())
}

fn role_search_terms(role: workflow_role::WorkflowRole) -> &'static str {
    use workflow_role::WorkflowRole;
    match role {
        WorkflowRole::Splitters => "splitter cross validation fold",
        WorkflowRole::HyperparameterSearch => "hyperparameter search tuner",
        WorkflowRole::Scalers => "scaler scaling standardization",
        WorkflowRole::FeatureEngineering => "feature engineering transformer",
        WorkflowRole::MetaEstimators => "meta estimator wrapper",
        WorkflowRole::LinearModels => "linear glm",
        WorkflowRole::Regression => "regressor",
        WorkflowRole::Classification => "classifier",
        WorkflowRole::Cleaning => "cleaning imputer",
        WorkflowRole::FeatureSelection => "feature selection",
        WorkflowRole::Unsupervised => "unsupervised clustering anomaly",
        WorkflowRole::Calibration => "calibration conformal",
        WorkflowRole::Explanation => "feature explanation interpretability",
        WorkflowRole::Forecasting => "forecasting horizon",
        WorkflowRole::Evaluation => "evaluation diagnostic report",
    }
}

fn search_source(
    out: &Path,
    entries: &[serde_json::Value],
    role_map: &BTreeMap<String, workflow_role::WorkflowRole>,
) -> Result<()> {
    let documents = entries
        .iter()
        .map(|e| {
            let name = e["name"].as_str().unwrap_or_default();
            let role_terms = entry_workflow_role(e, role_map)
                .map(role_search_terms)
                .unwrap_or_default();
            let keywords = if role_terms.is_empty() {
                e["keywords"].to_string()
            } else {
                format!("{} {role_terms}", e["keywords"])
            };
            [
                name.rsplit('.').next().unwrap_or(name).to_owned(),
                name.to_owned(),
                e["summary"].as_str().unwrap_or_default().to_owned(),
                e["parameters"].to_string(),
                keywords,
                e["members"].as_array().map_or_default(|members| {
                    members
                        .iter()
                        .filter_map(|m| m["summary"].as_str())
                        .collect::<Vec<_>>()
                        .join(" ")
                }),
            ]
        })
        .collect::<Vec<_>>();
    let table = search::weights(&documents);
    let mut source = String::from("&[\n");
    let mut bytes = Vec::new();
    for (word, postings) in table {
        let start = bytes.len();
        for (i, score) in postings {
            bytes.extend(u16::try_from(i)?.to_le_bytes());
            let quantized = format!("{:.0}", score * 256.0).parse::<u16>()?;
            bytes.extend(quantized.to_le_bytes());
        }
        let end = bytes.len();
        writeln!(
            source,
            "({word:?}, 0x{:04x}_{:04x}, 0x{:04x}_{:04x}),",
            start >> 16,
            start & 0xffff,
            end >> 16,
            end & 0xffff
        )?;
    }
    source.push(']');
    fs::write(out.join("postings.bin"), bytes)?;
    write(&out.join("search.rs"), &source)
}

fn intern(text: &str, strings: &mut BTreeMap<String, u32>, data: &mut Vec<u8>) -> Result<()> {
    let next = u32::try_from(strings.len())?;
    data.extend(strings.entry(text.to_owned()).or_insert(next).to_le_bytes());
    Ok(())
}

fn encode(
    value: &serde_json::Value,
    strings: &mut BTreeMap<String, u32>,
    data: &mut Vec<u8>,
) -> Result<()> {
    use serde_json::Value;
    match value {
        Value::Null => data.push(TAG_NULL),
        Value::Bool(false) => data.push(TAG_FALSE),
        Value::Bool(true) => data.push(TAG_TRUE),
        Value::String(text) => {
            data.push(TAG_STRING);
            intern(text, strings, data)?;
        }
        Value::Array(items) => {
            data.push(TAG_ARRAY);
            data.extend(u16::try_from(items.len())?.to_le_bytes());
            for item in items {
                encode(item, strings, data)?;
            }
        }
        Value::Object(fields) => {
            data.push(TAG_OBJECT);
            data.extend(u16::try_from(fields.len())?.to_le_bytes());
            for (key, value) in fields {
                intern(key, strings, data)?;
                encode(value, strings, data)?;
            }
        }
        Value::Number(_) => bail!("discovery entries contain no numeric fields"),
    }
    Ok(())
}

/// Verifies that every `WorkflowId` variant is listed in `WorkflowId::ALL`, round-trips through
/// `spec()` and `FromStr`, and ships its companion catalog, skill, and (in git checkouts) command
/// documentation page.
fn verify_workflows() -> Result<()> {
    let registry_path = "src/ledger/workflow_registry.rs";
    println!("cargo:rerun-if-changed={registry_path}");
    let command_docs = Path::new("website/reference/commands");
    if command_docs.exists() {
        println!("cargo:rerun-if-changed={}", command_docs.display());
    }

    let source = fs::read_to_string(registry_path)
        .with_context(|| format!("cannot read {registry_path}"))?;
    let declared = parse_workflow_variants(&source)?;
    let mut registered = BTreeSet::new();
    for &id in workflow_registry::WorkflowId::ALL {
        let variant = format!("{id:?}");
        ensure!(
            registered.insert(variant.clone()),
            "{registry_path}: duplicate WorkflowId::{variant} entry in WorkflowId::ALL"
        );
    }
    for variant in &declared {
        ensure!(
            registered.contains(variant),
            "{registry_path}: WorkflowId::{variant} is missing from WorkflowId::ALL"
        );
    }

    let xpd_skill = verify_bundled_skills()?;

    let check_website_docs = Path::new(".git").exists() || Path::new("website").exists();
    for &id in workflow_registry::WorkflowId::ALL {
        let spec = id.spec();
        ensure!(
            spec.id == id,
            "{registry_path}: WorkflowId::{id:?}.spec().id does not match"
        );
        ensure!(
            spec.cli_name == id.as_str(),
            "{registry_path}: WorkflowId::{id:?}.spec().cli_name does not match as_str()"
        );
        let parsed: workflow_registry::WorkflowId = id.as_str().parse().with_context(|| {
            format!(
                "{registry_path}: WorkflowId::from_str({:?}) failed",
                id.as_str()
            )
        })?;
        ensure!(
            parsed == id,
            "{registry_path}: WorkflowId::from_str({:?}) returned {parsed:?}, expected {id:?}",
            id.as_str()
        );

        let slug = id.as_str();
        let catalog_path = PathBuf::from(format!("rules/xpd/{slug}.yml"));
        let catalog = fs::read_to_string(&catalog_path).with_context(|| {
            format!(
                "missing workflow catalog {} for WorkflowId::{id:?}",
                catalog_path.display()
            )
        })?;
        ensure!(
            !catalog.trim().is_empty(),
            "empty workflow catalog {} for WorkflowId::{id:?}",
            catalog_path.display()
        );

        let route_token = format!("`{slug}`");
        ensure!(
            xpd_skill.contains(&route_token),
            "unified skill skills/xpd/SKILL.md must route `{slug}` for WorkflowId::{id:?}",
        );

        if check_website_docs {
            let doc_slug = id.cli_path().replace(' ', "/");
            let doc_path = command_docs.join(format!("{doc_slug}.md"));
            let doc = fs::read_to_string(&doc_path).with_context(|| {
                format!(
                    "missing command documentation {} for WorkflowId::{id:?}",
                    doc_path.display()
                )
            })?;
            ensure!(
                !doc.trim().is_empty(),
                "empty command documentation {} for WorkflowId::{id:?}",
                doc_path.display()
            );
        }
    }
    Ok(())
}

/// Checks that the bundled skills exist and declare their frontmatter names,
/// returning the unified `skills/xpd/SKILL.md` contents for workflow-router checks.
fn verify_bundled_skills() -> Result<String> {
    let xpd_skill_path = Path::new("skills/xpd/SKILL.md");
    let xpd_skill = fs::read_to_string(xpd_skill_path).with_context(|| {
        format!(
            "missing unified xpd workflow skill {}",
            xpd_skill_path.display()
        )
    })?;
    ensure!(
        !xpd_skill.trim().is_empty(),
        "empty unified xpd workflow skill {}",
        xpd_skill_path.display()
    );
    ensure!(
        xpd_skill.contains("name: xpd"),
        "unified skill {} must declare `name: xpd`",
        xpd_skill_path.display()
    );
    for (cluster, expected_name) in [
        ("skills/xpd-animate/SKILL.md", "name: xpd-animate"),
        ("skills/xpd-enhance/SKILL.md", "name: xpd-enhance"),
        ("skills/xpd-look/SKILL.md", "name: xpd-look"),
        ("skills/xpd-quest/SKILL.md", "name: xpd-quest"),
    ] {
        let text = fs::read_to_string(cluster)
            .with_context(|| format!("missing bundled skill {cluster}"))?;
        ensure!(
            text.contains(expected_name),
            "bundled skill {cluster} must declare `{expected_name}`"
        );
    }
    Ok(xpd_skill)
}

/// Extracts declared variant identifiers from `enum WorkflowId { ... }` in `source`.
fn parse_workflow_variants(source: &str) -> Result<Vec<String>> {
    let start = source
        .find("enum WorkflowId")
        .context("src/ledger/workflow_registry.rs does not declare `enum WorkflowId`")?;
    let after_header = &source[start..];
    let open = after_header
        .find('{')
        .context("src/ledger/workflow_registry.rs: `enum WorkflowId` has no `{`")?;
    let body = &after_header[open + 1..];
    let close = body
        .find('}')
        .context("src/ledger/workflow_registry.rs: `enum WorkflowId` has no `}`")?;
    let mut variants = Vec::new();
    for line in body[..close].lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with("///") || trimmed.starts_with("#[") {
            continue;
        }
        for part in trimmed.split(',') {
            let candidate = part.trim();
            if candidate.is_empty() {
                continue;
            }
            let ident = candidate
                .split(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_'))
                .next()
                .unwrap_or("");
            if !ident.is_empty() {
                variants.push(ident.to_owned());
            }
        }
    }
    ensure!(
        !variants.is_empty(),
        "src/ledger/workflow_registry.rs: `enum WorkflowId` declares no variants"
    );
    Ok(variants)
}