Skip to content

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

75.6 KB
Raw Blame
//! The obligation registry: the static inventory of what the original offers (exports, commands,
//! flags, routes, environment variables, error paths), read from the source code and not from
//! the recordings. A feature that nobody recorded is listed all the same.
//!
//! The registry fails closed. Everything that can be named is an obligation; what exists without
//! being nameable is an unenumerated site, and a family that has one stays open (`partial` or
//! `unknown`).
//!
//! The registry does not certify what it cannot prove. Only the `export` family can be
//! `complete`: its items are read in full from the syntax. Commands, flags, routes and
//! environment variables are declared in ways that no detector knows all of; these families are
//! at best `enumerated` (what the detectors recognise is listed, nothing unknown was seen) or
//! `none-found`, and a person attests that there is nothing else.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::fmt::Write as _;
use std::path::Path;
use std::sync::LazyLock;

use anyhow::{Context, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};

use crate::lang::Lang;
use crate::ts::discover::{FileKind, Workspace};
use crate::walk::Canonical;

mod closure;
pub mod evidence;
mod facts;
mod gaps;
mod py_file;
mod python;
pub mod source;
pub mod standing;
pub mod surface;
mod ts;
mod ts_file;

use facts::FileFacts;
use surface::{Found, Surface};

/// Version of the registry format.
pub const SCHEMA: &str = "rust-anything/obligations@1";
/// Where `--write` puts the registry, from the root of the repository.
pub const LEDGER_FILE: &str = "rust/OBLIGATIONS.json";

/// Maximum length, in characters, of the "statement" part of an error id.
const SLUG_LENGTH: usize = 60;
/// Number of unenumerated sites shown in the text; the JSON lists them all.
const SHOWN_UNRESOLVED: usize = 50;

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Family {
    Export,
    Command,
    Flag,
    Route,
    Env,
    ErrorPath,
}

impl Family {
    /// The families in registry order.
    pub const ALL: [Self; 6] = [
        Self::Export,
        Self::Command,
        Self::Flag,
        Self::Route,
        Self::Env,
        Self::ErrorPath,
    ];

    /// The name written in the JSON and in the text.
    pub fn label(self) -> &'static str {
        match self {
            Self::Export => "export",
            Self::Command => "command",
            Self::Flag => "flag",
            Self::Route => "route",
            Self::Env => "env",
            Self::ErrorPath => "error-path",
        }
    }

    /// The name used in a sentence.
    fn noun(self) -> &'static str {
        match self {
            Self::Export => "export",
            Self::Command => "command",
            Self::Flag => "flag",
            Self::Route => "route",
            Self::Env => "environment variable",
            Self::ErrorPath => "error path",
        }
    }
}

impl std::str::FromStr for Family {
    type Err = String;

    /// Reads the name written by `label`; the error lists the valid names.
    fn from_str(s: &str) -> Result<Self, String> {
        Self::ALL
            .into_iter()
            .find(|f| f.label() == s)
            .ok_or_else(|| {
                let names: Vec<&str> = Self::ALL.iter().map(|f| f.label()).collect();
                format!("unknown family `{s}` (one of {})", names.join(", "))
            })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Completeness {
    /// Everything the family contains is listed, with proof: a complete reading of the syntax.
    /// Only the `export` family can be this.
    Complete,
    /// What the detectors recognise is listed and they saw nothing they could not name. This is
    /// not proof: a form they do not know stays invisible, and a person attests the family.
    Enumerated,
    /// Part of it is listed; some sites could not be.
    Partial,
    /// It is not known what the family contains.
    Unknown,
    /// The detectors found nothing and nothing signals this surface. Not proof either: a person
    /// attests that the application has none.
    NoneFound,
}

impl std::str::FromStr for Completeness {
    type Err = String;

    /// Reads the name written by `label`; the error lists the valid names.
    fn from_str(s: &str) -> Result<Self, String> {
        [
            Self::Complete,
            Self::Enumerated,
            Self::Partial,
            Self::Unknown,
            Self::NoneFound,
        ]
        .into_iter()
        .find(|c| c.label() == s)
        .ok_or_else(|| {
            format!(
                "unknown state `{s}` (one of complete, enumerated, partial, unknown, none-found)"
            )
        })
    }
}

impl Completeness {
    pub fn label(self) -> &'static str {
        match self {
            Self::Complete => "complete",
            Self::Enumerated => "enumerated",
            Self::Partial => "partial",
            Self::Unknown => "unknown",
            Self::NoneFound => "none-found",
        }
    }

    /// The registry knows that the family holds items it does not list.
    pub fn is_open(self) -> bool {
        matches!(self, Self::Partial | Self::Unknown)
    }

    /// Nothing unknown was seen, but nothing proves it: a person's attestation is needed.
    pub fn needs_attestation(self) -> bool {
        matches!(self, Self::Enumerated | Self::NoneFound)
    }
}

/// The detail of a flag that is a positional argument.
pub const POSITIONAL: &str = "positional";
/// The detail of a positional that may swallow the options written after it
/// (`argparse.REMAINDER`, `"..."`, `argparse.PARSER`, or an `nargs` the detector cannot read).
pub const POSITIONAL_REMAINDER: &str = "positional remainder";
/// The detail segment of an option that takes the rest of the line (`nargs=argparse.REMAINDER`,
/// `"..."`, `PARSER`, or an `nargs` the detector cannot read): the options written after it may
/// belong to it. It follows the aliases, separated by `; `.
pub const OPTION_REMAINDER: &str = "takes the rest of the line";

/// A thing the original offers and that a port must carry over or set aside knowingly.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Obligation {
    /// Stable from one run to the next: holds no line number.
    pub id: String,
    pub family: Family,
    pub name: String,
    /// `path/from/the/root.ts:12`, relative to the repository, `/` separators.
    pub site: String,
    /// The `analyze` unit that contains the file, when there is one.
    pub unit: Option<String>,
    /// A flag's alias, a route's handler, the statement that raises an error...
    pub detail: Option<String>,
}

impl Obligation {
    /// A positional argument, whether or not it swallows the options that follow it.
    pub fn is_positional(&self) -> bool {
        matches!(
            self.detail.as_deref(),
            Some(POSITIONAL | POSITIONAL_REMAINDER)
        )
    }

    /// A positional that may swallow the options written after it.
    pub fn is_remainder(&self) -> bool {
        self.detail.as_deref() == Some(POSITIONAL_REMAINDER)
    }

    /// An option that may swallow the options written after it (see `OPTION_REMAINDER`).
    pub fn is_remainder_option(&self) -> bool {
        self.detail
            .as_deref()
            .is_some_and(|d| d.split("; ").any(|s| s.trim() == OPTION_REMAINDER))
    }
}

/// A place where surface exists without having been enumerated.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Unresolved {
    pub family: Family,
    pub site: String,
    pub reason: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FamilyReport {
    pub family: Family,
    pub completeness: Completeness,
    pub count: usize,
    pub reason: Option<String>,
    /// The detectors that read this family: what produced its enumeration.
    #[serde(default)]
    pub detectors: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ledger {
    pub schema: String,
    pub language: Lang,
    /// `cli`, `server` or `library`, as in `analyze --whole-app`.
    pub shape: String,
    pub families: Vec<FamilyReport>,
    pub obligations: Vec<Obligation>,
    pub unresolved: Vec<Unresolved>,
}

/// An obligation with its place in the sources, to sort it and remove duplicates.
struct Draft {
    file: String,
    line: u32,
    obligation: Obligation,
}

/// An unenumerated site, with its place as numbers to sort it in line order.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Site {
    family: Family,
    file: String,
    line: u32,
    reason: String,
}

impl Site {
    fn into_unresolved(self) -> Unresolved {
        Unresolved {
            family: self.family,
            site: format!("{}:{}", self.file, self.line),
            reason: self.reason,
        }
    }
}

/// What reading the files gathered.
#[derive(Default)]
struct Inventory {
    exports: Vec<Draft>,
    errors: Vec<Draft>,
    /// The functions whose error paths are looked for by reading lines (languages without tree
    /// reading): (name, file, line).
    raisers: Vec<(String, String, u32)>,
    surface: Vec<Draft>,
    sites: Vec<Site>,
    /// The relative re-exports without a rename: (file, line, specifier).
    reexports: Vec<(String, u32, String)>,
    recognised: BTreeSet<(Family, String)>,
    /// The packages that the detector of the last file read cannot classify: (package, line).
    /// The closure takes them up at once, with the file's imports.
    pending_packages: Vec<(String, u32)>,
}

/// The reason for an unknown-package site, after `package <name> `.
const UNKNOWN_PACKAGE: &str = "is not one rust-anything knows: it may declare commands, flags or \
                               routes, or read the environment";

/// The families that an unknown package may declare or read.
const SURFACE_FAMILIES: [Family; 4] = [Family::Command, Family::Flag, Family::Route, Family::Env];

/// The reason for the site of an unknown package imported by `files` files.
fn unknown_package_reason(package: &str, files: usize) -> String {
    if files > 1 {
        format!("package {package} {UNKNOWN_PACKAGE} (imported by {files} files)")
    } else {
        format!("package {package} {UNKNOWN_PACKAGE}")
    }
}

/// The package name of a specifier, as the detectors normalise it (`@scope/pkg` or `pkg` in TS,
/// top-level module in Python); `None` for a relative import.
fn package_of(lang: Lang, spec: &str) -> Option<&str> {
    match lang {
        Lang::Ts if !(spec.starts_with("./") || spec.starts_with("../")) => {
            Some(crate::ts::deps::package_name(spec))
        }
        Lang::Python if !spec.starts_with('.') => spec.split('.').next(),
        _ => None,
    }
}

/// The surface detector of a file: `(path, text)`.
pub type Detector<'a> = &'a dyn Fn(&str, &str) -> Surface;

/// The obligation registry of the repository `root`. `lang` forces the language; otherwise
/// `rust/obligations-source.toml` does, or it is detected.
pub fn ledger(root: &Path, lang: Option<Lang>) -> Result<Ledger> {
    build(root, lang, None)
}

/// Like `ledger`, with a surface detector supplied (for tests): it reads every source file,
/// whatever the language.
pub fn ledger_with(root: &Path, lang: Option<Lang>, detector: Detector) -> Result<Ledger> {
    build(root, lang, Some(detector))
}

fn build(root: &Path, lang: Option<Lang>, injected: Option<Detector>) -> Result<Ledger> {
    let root = crate::walk::resolve_root(root)?;
    let declared_source = source::read(&root)?;
    let lang = lang.or(declared_source.lang);
    // `analyze` recurses into the files: on the calling thread, a file with a chain of tens of
    // thousands of links overflows the stack. So the analysis runs on a thread whose stack
    // follows the biggest file of the repository; nothing is written before the end.
    let biggest = declared_source
        .entries
        .iter()
        .filter_map(|e| std::fs::metadata(root.join(e)).ok())
        .map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX))
        .fold(gaps::largest_file(&root, lang), usize::max);
    let (report, app) = facts::on_stack_of(biggest, &|| {
        let report = match lang {
            Some(lang) => crate::analyze::analyze_lang(&root, lang),
            None => crate::analyze::analyze(&root),
        }?;
        let app = crate::whole_app::whole_app(&root, &report);
        Ok::<_, anyhow::Error>((report, app))
    })?;
    let lang = report.language;
    let units: HashMap<&str, &str> = report
        .units
        .iter()
        .flat_map(|u| u.files.iter().map(|f| (f.as_str(), u.id.as_str())))
        .collect();

    crate::profile::use_project_types(&root, lang);
    let workspace = discover(&root, lang)?;
    let mut sources: Vec<String> = workspace
        .files
        .iter()
        .filter(|f| f.kind == FileKind::Source)
        .map(|f| f.path.clone())
        .collect();
    sources.sort_unstable();
    sources.dedup();
    let inventoried: HashSet<String> = sources.iter().cloned().collect();
    let mut known: HashSet<String> = workspace.files.iter().map(|f| f.path.clone()).collect();

    let default: Option<Detector> = match lang {
        Lang::Ts => Some(&ts::surface),
        Lang::Python => Some(&python::surface),
        _ => None,
    };
    let detector = injected.or(default);

    // The package names of the repository: a folder that contains an `__init__.py`.
    let own: HashSet<String> = known
        .iter()
        .filter_map(|p| p.strip_suffix("/__init__.py"))
        .filter_map(|dir| dir.rsplit('/').next())
        .map(str::to_string)
        .collect();
    let repo = gaps::repo_files(&root, lang).files;
    let bases: Vec<String> = std::iter::once(String::new())
        .chain(workspace.packages.iter().map(|p| p.src_root.clone()))
        .chain(closure::package_roots(&root, lang, &repo))
        .collect::<BTreeSet<String>>()
        .into_iter()
        .collect();
    let declared: HashSet<String> = workspace
        .packages
        .iter()
        .flat_map(|p| {
            std::iter::once(p.name.clone())
                .chain(p.deps.iter().cloned())
                .chain(p.dev_deps.iter().cloned())
        })
        .collect();
    let own_packages: HashSet<String> = workspace.packages.iter().map(|p| p.name.clone()).collect();
    let resolver = closure::Resolver {
        root: &root,
        lang,
        bases: &bases,
        declared: &declared,
        workspace: &own_packages,
        has_dependencies: workspace
            .packages
            .iter()
            .any(|p| !p.deps.is_empty() || !p.dev_deps.is_empty()),
        aliases: std::cell::RefCell::new(HashMap::new()),
    };

    // Python: the scripts and commands that the manifests declare, and the scripts with a shebang.
    let entries = if lang == Lang::Python {
        python::manifest::entries(&root, &workspace, &repo, &app.entry_points)
    } else {
        python::manifest::Entries::default()
    };

    let mut inventory = Inventory::default();
    let reader = Reader {
        root: &root,
        real_root: root.canonicalize().ok(),
        lang,
        detector,
        own: &own,
    };
    // The discovery inventory, then the closure of its literal imports: a file that discovery
    // skips (`*.config.ts`, a `testing` subpackage) but that a file already read imports is read
    // too.
    let mut read: HashSet<String> = inventoried.clone();
    let mut queue: VecDeque<(String, Depth)> =
        sources.iter().map(|s| (s.clone(), Depth::Whole)).collect();
    for entry in &declared_source.entries {
        if read.insert(entry.clone()) {
            known.insert(entry.clone());
            queue.push_back((entry.clone(), Depth::Entry));
        } else if let Some(queued) = queue.iter_mut().find(|(p, _)| p == entry) {
            queued.1 = Depth::Entry;
        }
    }
    let mut configs_queued = false;
    // The external packages unknown to the detectors, (package, file, line), and the packages
    // with an import that is already an "is not followed" site.
    let mut foreign: Vec<(String, String, u32)> = Vec::new();
    let mut unfollowed: HashSet<String> = HashSet::new();
    loop {
        let Some((path, depth)) = queue.pop_front() else {
            // The configuration files that discovery skips by name and that the closure did not
            // reach: they do run (`next.config.js`), so the surface detectors read them, once the
            // closure of the inventory is done.
            if configs_queued {
                break;
            }
            configs_queued = true;
            for config in gaps::config_files(&root, lang, &repo, &read) {
                read.insert(config.clone());
                queue.push_back((config, Depth::Surface));
            }
            for script in &entries.files {
                if read.insert(script.clone()) {
                    queue.push_back((script.clone(), Depth::Surface));
                }
            }
            continue;
        };
        let unit = units.get(path.as_str()).copied();
        let imports = reader.read(&mut inventory, &path, unit, depth);
        let mut by_package: HashMap<&str, Vec<&str>> = HashMap::new();
        for spec in imports.iter().map(|i| i.specifier.as_str()) {
            if let Some(package) = package_of(lang, spec) {
                by_package.entry(package).or_default().push(spec);
            }
        }
        for (package, line) in std::mem::take(&mut inventory.pending_packages) {
            let specs = by_package
                .get(package.as_str())
                .cloned()
                .unwrap_or_default();
            // A package that the closure already makes a site stays here: `unknown_packages`
            // drops it once all the "is not followed" sites are known.
            if !resolver.owns(&path, &package, &specs) {
                foreign.push((package, path.clone(), line));
            }
        }
        for import in imports {
            match resolver.follow(&path, &import.specifier, import.type_only) {
                closure::Followed::File(target) => {
                    if read.insert(target.clone()) {
                        known.insert(target.clone());
                        queue.push_back((target, Depth::Whole));
                    }
                }
                closure::Followed::Ignored => {}
                closure::Followed::Unfollowed(reason) => {
                    if let Some(package) = package_of(lang, &import.specifier) {
                        unfollowed.insert(package.to_string());
                    }
                    inventory.site_at(depth, &path, import.line, &reason);
                }
            }
        }
    }
    inventory.unknown_packages(foreign, &unfollowed);
    inventory.resolve_reexports(lang, &known, &bases);
    inventory.add_gaps(gaps::find(&root, lang, &workspace, &inventoried, &read));
    inventory.add_gaps(entries.gaps);
    inventory.scan_lines(lang, &root, &units);
    inventory.declared_source(&declared_source);

    let has_cli = app.entry_points.iter().any(|e| e.kind == "cli")
        || (lang == Lang::Ts && gaps::declares_bin(&root, &workspace))
        || entries.cli
        || !declared_source.entries.is_empty();
    let has_server = app.entry_points.iter().any(|e| e.kind == "server");
    let shape = if app.shape == "library" && !declared_source.entries.is_empty() {
        "cli"
    } else {
        app.shape
    };
    let context = App {
        lang,
        shape: shape.to_string(),
        reader: detector.map(|_| surface_reader(lang)),
        has_cli,
        has_server,
    };
    Ok(assemble(inventory, &context))
}

/// The name of the reader that walked the files for the surface families.
fn surface_reader(lang: Lang) -> String {
    match lang {
        Lang::Ts => "oxc-surface".to_string(),
        Lang::Python => "tree-sitter-surface".to_string(),
        other => format!("{}-surface", other.name().to_lowercase()),
    }
}

fn discover(root: &Path, lang: Lang) -> Result<Workspace> {
    match lang {
        Lang::Ts => crate::ts::discover::discover(root),
        _ => crate::lang::discover(lang, root),
    }
}

/// What is known about the application when deciding whether its families are complete.
struct App {
    lang: Lang,
    shape: String,
    /// The surface reader that walked the files; `None` without a detector for the language.
    reader: Option<String>,
    has_cli: bool,
    has_server: bool,
}

/// The reason for the site left by a file whose links lead outside the repository.
const OUTSIDE: &str = "the file is a link that leaves the repository; it is not read";

/// Whether the file `path` of the repository is still under `root` once its links are resolved. A
/// missing file counts as inside: it will not be opened.
pub(crate) fn stays_inside(root: &Path, path: &str) -> bool {
    root.canonicalize()
        .map_or(true, |real| resolves_under(&real, root, path))
}

/// The text of the file `path` of the repository, if it can be read and stays under `root` once
/// its links are resolved. Manifests go through here: a link that leaves the repository is not
/// opened.
pub(crate) fn read_inside(root: &Path, path: &str) -> Option<String> {
    stays_inside(root, path)
        .then(|| std::fs::read_to_string(root.join(path)).ok())
        .flatten()
}

/// `stays_inside` when the resolved root `real` is already known.
fn resolves_under(real: &Path, root: &Path, path: &str) -> bool {
    root.join(path)
        .canonicalize()
        .map_or(true, |full| full.starts_with(real))
}

/// What the registry reads of a file.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Depth {
    /// Everything: exports, error paths and surface. The inventory's files and those that a file
    /// already read imports.
    Whole,
    /// Surface only: a configuration file that discovery skips by name. What it exports or
    /// raises is a tool's configuration, not a function of the application; what it reads from
    /// the environment counts.
    Surface,
    /// An executable named in `rust/obligations-source.toml`: its surface and its error paths.
    /// Its functions are not exports: nobody calls them from outside the program.
    Entry,
}

struct Reader<'a> {
    root: &'a Path,
    /// The root once its links are resolved, to judge where each file leads.
    real_root: Option<std::path::PathBuf>,
    lang: Lang,
    detector: Option<Detector<'a>>,
    /// The names of the repository's Python packages (a folder that contains `__init__.py`).
    own: &'a HashSet<String>,
}

impl Reader<'_> {
    /// Reads a file and returns the specifiers of its imports, for the closure.
    fn read(
        &self,
        inv: &mut Inventory,
        path: &str,
        unit: Option<&str>,
        depth: Depth,
    ) -> Vec<Import> {
        // Every file of the registry is opened here: a link that leads outside the repository is
        // not followed, wherever it comes from (an import, a manifest, discovery).
        if self
            .real_root
            .as_deref()
            .is_some_and(|real| !resolves_under(real, self.root, path))
        {
            inv.site_at(depth, path, 1, OUTSIDE);
            return Vec::new();
        }
        let Ok(text) = std::fs::read_to_string(self.root.join(path)) else {
            inv.site_at(depth, path, 1, "the file could not be read as text");
            return Vec::new();
        };
        let facts = match self.lang {
            Lang::Ts => ts_file::read(path, &text),
            Lang::Python => py_file::read(path, &text, self.own),
            lang => other_facts(lang, path, &text),
        };
        if facts.parse_errors > 0 {
            inv.site_at(
                depth,
                path,
                1,
                &format!(
                    "{} syntax error(s): what this file offers may be missing",
                    facts.parse_errors
                ),
            );
        }
        for (line, reason) in &facts.unreadable {
            inv.site_at(depth, path, *line, reason);
        }
        if depth != Depth::Surface {
            self.record(inv, path, unit, facts, depth == Depth::Whole);
        }
        if let Some(detect) = self.detector {
            self.surface(inv, path, unit, detect(path, &text));
        }
        self.imports(path, &text)
    }

    /// The specifiers, literal or not, that the file imports, read by the existing scanner.
    fn imports(&self, path: &str, text: &str) -> Vec<Import> {
        let lang = self.lang;
        let scanned = match lang {
            Lang::Ts | Lang::Python => facts::on_stack_for(text, &|| match lang {
                Lang::Ts => crate::ts::scan::scan(path, text),
                _ => crate::lang::scan(Lang::Python, path, text),
            }),
            // The other languages have no closure (`Resolver::follow` ignores them): their files
            // are all in the discovery inventory, and `export_limit` says what reading them
            // leaves out.
            _ => return Vec::new(),
        };
        let needles: Vec<&str> = scanned
            .imports
            .iter()
            .map(|i| i.specifier.as_str())
            .collect();
        let lines = first_lines_with(text, &needles);
        scanned
            .imports
            .into_iter()
            .zip(lines)
            .map(|(i, line)| Import {
                line,
                specifier: i.specifier,
                type_only: i.type_only,
            })
            .collect()
    }

    /// Records what the file offers; its exports only when `exports` (an executable's functions
    /// are not called from outside, but their error paths count).
    fn record(
        &self,
        inv: &mut Inventory,
        path: &str,
        unit: Option<&str>,
        facts: FileFacts,
        exports: bool,
    ) {
        let ast = ast_errors(self.lang);
        for n in facts.named {
            if exports {
                inv.exports.push(draft(
                    Family::Export,
                    export_id(path, &n.name),
                    &n.name,
                    path,
                    n.line,
                    unit,
                    n.detail.clone(),
                ));
            }
            if !ast {
                inv.raisers.push((n.name, path.to_string(), n.line));
            }
        }
        if exports {
            for (line, reason) in facts.unresolved {
                inv.site(Family::Export, path, line, &reason);
            }
        }
        for (line, spec) in facts.relative_reexports {
            inv.reexports.push((path.to_string(), line, spec));
        }
        for r in facts.raises {
            inv.errors.push(draft(
                Family::ErrorPath,
                error_id(path, &r.owner, &r.statement),
                &r.owner,
                path,
                r.line,
                unit,
                Some(r.statement),
            ));
        }
    }

    fn surface(&self, inv: &mut Inventory, path: &str, unit: Option<&str>, surface: Surface) {
        for found in &surface.found {
            if let Some(id) = surface_id(found, path) {
                inv.surface.push(draft(
                    found.family,
                    id,
                    &found.name,
                    path,
                    found.line,
                    unit,
                    found.detail.clone(),
                ));
            }
        }
        for u in &surface.unresolved {
            inv.site(u.family, path, u.line, &u.reason);
        }
        inv.recognised.extend(surface.recognised);
        inv.pending_packages.extend(surface.unknown_packages);
    }
}

/// An import read in a file, for the closure.
struct Import {
    specifier: String,
    type_only: bool,
    /// The first line that contains the specifier (1 by default).
    line: u32,
}

fn first_lines_with(text: &str, needles: &[&str]) -> Vec<u32> {
    let mut lines = vec![1; needles.len()];
    let Ok(automaton) = aho_corasick::AhoCorasick::new(needles) else {
        return needles
            .iter()
            .map(|needle| {
                text.lines()
                    .position(|l| l.contains(needle))
                    .map_or(1, |i| u32::try_from(i + 1).unwrap_or(1))
            })
            .collect();
    };
    let starts: Vec<usize> = std::iter::once(0)
        .chain(text.match_indices('\n').map(|(i, _)| i + 1))
        .collect();
    let mut seen = vec![false; needles.len()];
    for found in automaton.find_overlapping_iter(text) {
        let p = found.pattern().as_usize();
        if !seen[p] {
            seen[p] = true;
            lines[p] = u32::try_from(starts.partition_point(|&s| s <= found.start())).unwrap_or(1);
        }
    }
    lines
}

/// What reading a file of a language without tree reading gives the registry: its exported
/// functions (and classes).
fn other_facts(lang: Lang, path: &str, text: &str) -> FileFacts {
    let (functions, classes) = crate::lang::exports(lang, path, text);
    let mut named: Vec<facts::Named> = functions
        .into_iter()
        .map(|f| facts::Named::new(f.name, f.line, None))
        .collect();
    for class in classes {
        if class.methods.is_empty() {
            named.push(facts::Named::new(
                class.name.clone(),
                class.line,
                Some("class"),
            ));
        }
        for m in class.methods {
            named.push(facts::Named::new(
                format!("{}.{}", class.name, m.name),
                m.line,
                None,
            ));
        }
    }
    FileFacts {
        parse_errors: crate::lang::scan(lang, path, text).parse_errors,
        named,
        ..FileFacts::default()
    }
}

/// The languages whose error paths are read from the syntax tree.
fn ast_errors(lang: Lang) -> bool {
    matches!(lang, Lang::Ts | Lang::Python)
}

impl Inventory {
    fn site(&mut self, family: Family, file: &str, line: u32, reason: &str) {
        self.sites.push(Site {
            family,
            file: file.to_string(),
            line,
            reason: reason.to_string(),
        });
    }

    /// A site that may hide any family.
    fn site_all(&mut self, file: &str, line: u32, reason: &str) {
        for family in Family::ALL {
            self.site(family, file, line, reason);
        }
    }

    /// A site on the families that reading at this depth covers.
    fn site_at(&mut self, depth: Depth, file: &str, line: u32, reason: &str) {
        match depth {
            Depth::Whole => self.site_all(file, line, reason),
            Depth::Entry => {
                for family in SURFACE_FAMILIES.into_iter().chain([Family::ErrorPath]) {
                    self.site(family, file, line, reason);
                }
            }
            Depth::Surface => {
                for family in SURFACE_FAMILIES {
                    self.site(family, file, line, reason);
                }
            }
        }
    }

    /// What `rust/obligations-source.toml` adds: a site on the commands and the flags of an entry
    /// where no detector saw any, unless a person listed them; then the commands and the flags
    /// that person listed, as obligations of the first entry (of the file itself without one).
    fn declared_source(&mut self, declared: &source::Source) {
        let from_file = |family: Family, file: &str, drafts: &[Draft], sites: &[Site]| {
            drafts
                .iter()
                .any(|d| d.obligation.family == family && d.file == file)
                || sites.iter().any(|s| s.family == family && s.file == file)
        };
        for entry in &declared.entries {
            for (family, listed, key) in [
                (Family::Command, !declared.commands.is_empty(), "commands"),
                (Family::Flag, !declared.flags.is_empty(), "flags"),
            ] {
                if listed || from_file(family, entry, &self.surface, &self.sites) {
                    continue;
                }
                let reason = format!(
                    "no {} was detected in this entry point: a dispatch the detectors cannot \
                     follow (a table of handlers, getattr, argv read by hand) hides them; list \
                     them under `{key}` in {}, or attest the family if it has none",
                    family.noun(),
                    source::SOURCE_FILE
                );
                self.site(family, entry, 1, &reason);
            }
        }
        let owner = declared
            .entries
            .first()
            .map_or(source::SOURCE_FILE, String::as_str);
        let detail = Some(format!("declared in {}", source::SOURCE_FILE));
        let commands = declared.commands.iter().map(|c| Found {
            family: Family::Command,
            name: c.clone(),
            line: 1,
            scope: None,
            detail: detail.clone(),
        });
        let flags = declared.flags.iter().map(|(scope, f)| Found {
            family: Family::Flag,
            name: f.clone(),
            line: 1,
            scope: scope.clone(),
            detail: detail.clone(),
        });
        for found in commands.chain(flags) {
            let Some(id) = surface_id(&found, owner) else {
                continue;
            };
            if !self.surface.iter().any(|d| d.obligation.id == id) {
                self.surface.push(draft(
                    found.family,
                    id,
                    &found.name,
                    owner,
                    found.line,
                    None,
                    found.detail.clone(),
                ));
                self.recognised
                    .insert((found.family, source::SOURCE_FILE.to_string()));
            }
        }
    }

    /// One site per unknown package and per surface family, at the first import in (path, line)
    /// order. `foreign`: (package, file, line) of the unknown external packages; `unfollowed`:
    /// the packages with an import that is already an "is not followed" site, which covers all
    /// the families.
    fn unknown_packages(
        &mut self,
        mut foreign: Vec<(String, String, u32)>,
        unfollowed: &HashSet<String>,
    ) {
        foreign.retain(|(package, _, _)| !unfollowed.contains(package));
        foreign.sort_by(|a, b| (&a.1, a.2, &a.0).cmp(&(&b.1, b.2, &b.0)));
        // Per package: the first site, and the distinct files that import it.
        let mut first: BTreeMap<&str, (&str, u32)> = BTreeMap::new();
        let mut importers: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
        for (package, file, line) in &foreign {
            first.entry(package).or_insert((file, *line));
            importers.entry(package).or_default().insert(file);
        }
        let sites: Vec<(String, u32, String)> = first
            .into_iter()
            .map(|(package, (file, line))| {
                let files = importers.get(package).map_or(1, BTreeSet::len);
                (
                    file.to_string(),
                    line,
                    unknown_package_reason(package, files),
                )
            })
            .collect();
        for (file, line, reason) in sites {
            for family in SURFACE_FAMILIES {
                self.site(family, &file, line, &reason);
            }
        }
    }

    fn add_gaps(&mut self, found: Vec<gaps::Gap>) {
        for gap in found {
            let (file, line) = gap
                .site
                .rsplit_once(':')
                .map_or((gap.site.as_str(), 1), |(f, l)| (f, l.parse().unwrap_or(1)));
            for family in gap.families {
                self.site(family, file, line, &gap.reason);
            }
        }
    }

    /// An `export * from './x'` hides nothing when `./x` is inventoried: its names are listed
    /// there.
    fn resolve_reexports(&mut self, lang: Lang, known: &HashSet<String>, bases: &[String]) {
        for (file, line, spec) in std::mem::take(&mut self.reexports) {
            let found = match lang {
                Lang::Python => python_modules(&file, &spec, bases)
                    .iter()
                    .any(|c| known.contains(c)),
                _ => ts_file::resolves(&file, &spec, known),
            };
            if !found {
                let reason =
                    format!("`{spec}` re-exports names from a file that is not in the inventory");
                self.site(Family::Export, &file, line, &reason);
            }
        }
    }

    /// The error paths of the languages read line by line.
    fn scan_lines(&mut self, lang: Lang, root: &Path, units: &HashMap<&str, &str>) {
        if ast_errors(lang) || self.raisers.is_empty() {
            return;
        }
        for site in crate::error_paths::raise_sites(lang, root, &self.raisers) {
            let statement = statement(&site.text);
            self.errors.push(draft(
                Family::ErrorPath,
                error_id(&site.file, &site.export, &statement),
                &site.export,
                &site.file,
                site.line,
                units.get(site.file.as_str()).copied(),
                Some(statement),
            ));
        }
    }
}

/// The files that a Python import may name, from most to least likely. A relative import (`.x`,
/// `..a.b`) starts from the file's folder; an absolute import is looked up under each root of
/// `bases` and beside the file.
fn python_modules(from: &str, module: &str, bases: &[String]) -> Vec<String> {
    let dots = module.chars().take_while(|c| *c == '.').count();
    let rest = module[dots..].replace('.', "/");
    let mut dir: Vec<&str> = from.split('/').collect();
    dir.pop();
    let join = |base: &str, tail: &str| match (base.is_empty(), tail.is_empty()) {
        (_, true) => base.to_string(),
        (true, false) => tail.to_string(),
        (false, false) => format!("{base}/{tail}"),
    };
    let targets: Vec<String> = if dots > 0 {
        for _ in 1..dots {
            if dir.pop().is_none() {
                return Vec::new();
            }
        }
        vec![join(&dir.join("/"), &rest)]
    } else if rest.is_empty() {
        return Vec::new();
    } else {
        let beside = dir.join("/");
        bases
            .iter()
            .map(String::as_str)
            .chain(std::iter::once(beside.as_str()))
            .map(|base| join(base, &rest))
            .collect()
    };
    let mut out = Vec::new();
    for target in targets {
        let init = if target.is_empty() {
            "__init__.py".to_string()
        } else {
            format!("{target}/__init__.py")
        };
        // `from . import x` (nothing after the dots) names the package, not a module of the same
        // name.
        if !rest.is_empty() {
            out.push(format!("{target}.py"));
        }
        out.push(init);
    }
    let mut seen = HashSet::new();
    out.retain(|c| seen.insert(c.clone()));
    out
}

fn draft(
    family: Family,
    id: String,
    name: &str,
    file: &str,
    line: u32,
    unit: Option<&str>,
    detail: Option<String>,
) -> Draft {
    Draft {
        file: file.to_string(),
        line,
        obligation: Obligation {
            id,
            family,
            name: name.to_string(),
            site: format!("{file}:{line}"),
            unit: unit.map(str::to_string),
            detail,
        },
    }
}

pub(crate) fn export_id(file: &str, name: &str) -> String {
    format!("export:{file}#{name}")
}

/// The id of a command, flag, route or variable; `None` for the families that do not come from a
/// surface detector. A command, flag and route carry the file that declares them, not a package:
/// two files may have the same command, and the path does not change when a package is added. An
/// environment variable is global.
fn surface_id(found: &Found, file: &str) -> Option<String> {
    let name = &found.name;
    match (found.family, &found.scope) {
        (Family::Command, _) => Some(format!("command:{file}#{name}")),
        (Family::Flag, Some(command)) => Some(format!("flag:{file}#{command}/{name}")),
        (Family::Flag, None) => Some(format!("flag:{file}#{name}")),
        (Family::Route, _) => Some(format!("route:{file}#{name}")),
        (Family::Env, _) => Some(format!("env:{name}")),
        (Family::Export | Family::ErrorPath, _) => None,
    }
}

static RAISING: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b(?:throw|raise)\b").expect("valid regex"));

/// The statement that raises the error in a line read without a tree: from the keyword on,
/// whitespace collapsed to one space.
fn statement(line: &str) -> String {
    let from = RAISING.find(line).map_or(0, |m| m.start());
    facts::collapse(&line[from..])
}

fn error_id(file: &str, owner: &str, statement: &str) -> String {
    let slug: String = statement.chars().take(SLUG_LENGTH).collect();
    format!("error:{file}#{owner}:{slug}")
}

/// Keeps one obligation per id: the first in source order.
fn dedupe(mut drafts: Vec<Draft>) -> Vec<Draft> {
    drafts.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
    let mut seen = HashSet::new();
    drafts.retain(|d| seen.insert(d.obligation.id.clone()));
    drafts
}

/// The surface obligations: an environment variable has a single id (the first read in source
/// order is its site); the others merge only when it is the same declaration of the same file
/// (same id, same line). Two distinct declarations with the same name in one file stay two
/// obligations, `~2`, `~3`...
fn dedupe_surface(mut drafts: Vec<Draft>) -> Vec<Draft> {
    drafts.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
    let mut env = HashSet::new();
    let mut declared = HashSet::new();
    drafts.retain(|d| {
        if d.obligation.family == Family::Env {
            env.insert(d.obligation.id.clone())
        } else {
            declared.insert((d.obligation.id.clone(), d.line))
        }
    });
    disambiguate(drafts)
}

/// Makes the ids unique by suffixing the later ones `~2`, `~3`..., in source order. Two identical
/// statements of one function are two obligations.
fn disambiguate(mut drafts: Vec<Draft>) -> Vec<Draft> {
    drafts.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
    let mut seen: HashMap<String, usize> = HashMap::new();
    for d in &mut drafts {
        let n = seen.entry(d.obligation.id.clone()).or_insert(0);
        *n += 1;
        if *n > 1 {
            d.obligation.id = format!("{}~{n}", d.obligation.id);
        }
    }
    drafts
}

fn assemble(inventory: Inventory, context: &App) -> Ledger {
    let recognised = inventory.recognised;
    let mut obligations: Vec<Obligation> = dedupe(inventory.exports)
        .into_iter()
        .chain(dedupe_surface(inventory.surface))
        .chain(disambiguate(inventory.errors))
        .map(|d| d.obligation)
        .collect();
    obligations.sort_by(|a, b| a.family.cmp(&b.family).then_with(|| a.id.cmp(&b.id)));

    let mut sites = inventory.sites;
    sites.sort();
    sites.dedup();
    let unresolved: Vec<Unresolved> = sites.into_iter().map(Site::into_unresolved).collect();

    let families = Family::ALL
        .iter()
        .map(|&family| family_report(family, context, &recognised, &obligations, &unresolved))
        .collect();
    Ledger {
        schema: SCHEMA.to_string(),
        language: context.lang,
        shape: context.shape.clone(),
        families,
        obligations,
        unresolved,
    }
}

/// The detectors that read a family.
fn detectors(
    family: Family,
    context: &App,
    recognised: &BTreeSet<(Family, String)>,
) -> Vec<String> {
    let lang = context.lang.name().to_lowercase();
    match family {
        Family::Export => vec![match context.lang {
            Lang::Ts => "oxc-exports".to_string(),
            Lang::Python => "tree-sitter-exports".to_string(),
            _ => format!("{lang}-function-exports"),
        }],
        Family::ErrorPath => match context.lang {
            Lang::Ts => vec!["oxc-throw".to_string()],
            Lang::Python => vec!["tree-sitter-raise".to_string()],
            lang if crate::error_paths::reads_raises(lang) => vec!["line-scan-raise".to_string()],
            _ => Vec::new(),
        },
        // The reader that walked the files, then the recognised libraries.
        _ => context
            .reader
            .iter()
            .cloned()
            .chain(libraries(family, recognised))
            .collect(),
    }
}

/// The libraries recognised in use for a family.
fn libraries(family: Family, recognised: &BTreeSet<(Family, String)>) -> Vec<String> {
    recognised
        .iter()
        .filter(|(f, _)| *f == family)
        .map(|(_, name)| name.clone())
        .collect()
}

fn family_report(
    family: Family,
    context: &App,
    recognised: &BTreeSet<(Family, String)>,
    obligations: &[Obligation],
    unresolved: &[Unresolved],
) -> FamilyReport {
    let own: Vec<&Unresolved> = unresolved.iter().filter(|u| u.family == family).collect();
    let detectors = detectors(family, context, recognised);
    let libraries = libraries(family, recognised);
    let evidence = Evidence {
        recognised: &libraries,
        lang: context.lang,
        shape: &context.shape,
        has_detector: context.reader.is_some(),
        has_cli: context.has_cli,
        has_server: context.has_server,
        found: obligations.iter().filter(|o| o.family == family).count(),
        unresolved: own.len(),
        first_unresolved: own.first().map(|u| u.site.as_str()),
    };
    let (completeness, reason) = completeness(family, &evidence);
    let count = evidence.found;
    FamilyReport {
        family,
        completeness,
        count,
        reason,
        detectors,
    }
}

/// What is known about a family when deciding whether it is complete.
struct Evidence<'a> {
    lang: Lang,
    shape: &'a str,
    /// A surface detector read the files.
    has_detector: bool,
    /// A command entry point exists (manifest or code).
    has_cli: bool,
    has_server: bool,
    /// What read the family. For commands and flags: the argument parsers seen in use, whether
    /// or not they declare anything.
    recognised: &'a [String],
    /// The family's obligations.
    found: usize,
    /// Unenumerated sites that concern the family, and the first of them in line order.
    unresolved: usize,
    first_unresolved: Option<&'a str>,
}

fn plural(n: usize, one: &str, many: &str) -> String {
    format!("{n} {}", if n == 1 { one } else { many })
}

/// `partial` (or `unknown` when nothing was found) when sites could not be enumerated.
fn from_unresolved(e: &Evidence, what: &str) -> Option<(Completeness, Option<String>)> {
    if e.unresolved == 0 {
        return None;
    }
    let completeness = if e.found > 0 {
        Completeness::Partial
    } else {
        Completeness::Unknown
    };
    let first = e.first_unresolved.unwrap_or("?");
    Some((
        completeness,
        Some(format!(
            "{} {what} (first at {first})",
            plural(e.unresolved, "site", "sites")
        )),
    ))
}

/// What reading the exports of a language without tree reading leaves out. `None`: the reading
/// covers everything the language exports.
fn export_limit(lang: Lang) -> Option<&'static str> {
    match lang {
        Lang::Ts | Lang::Python => None,
        Lang::C => Some(
            "the C scan lists non-static function definitions in .c files; global variables, \
             macros, types and header declarations are not listed",
        ),
        Lang::Csharp => Some(
            "the C# scan lists public static methods of public classes; instance methods, \
             properties, constants and types are not listed",
        ),
        Lang::Go => Some(
            "the Go scan lists exported top-level functions; methods, types, constants and \
             variables are not listed",
        ),
        Lang::Java => Some(
            "the Java scan lists public static methods of public top-level classes; instance \
             methods, constructors, fields and nested types are not listed",
        ),
        Lang::Kotlin => Some(
            "the Kotlin scan lists JVM-visible functions; classes, properties and objects are \
             not listed",
        ),
        Lang::Php => Some(
            "the PHP scan lists functions and public static methods; instance methods, \
             constants and classes are not listed",
        ),
        Lang::Powershell => Some(
            "the PowerShell scan lists functions; variables, aliases and classes are not listed",
        ),
        Lang::Ruby => Some(
            "the Ruby scan lists module functions (`def self.x`, `module_function`); instance \
             methods, constants and classes are not listed",
        ),
        Lang::Swift => Some(
            "the Swift scan lists top-level functions that are not `private` or `fileprivate`; \
             methods, functions in an `extension`, properties and types are not listed",
        ),
    }
}

/// The rule that decides whether a family is complete, without reading a single file.
fn completeness(family: Family, e: &Evidence) -> (Completeness, Option<String>) {
    match family {
        Family::Export => export_family(e),
        Family::ErrorPath => error_family(e),
        Family::Command | Family::Flag | Family::Route | Family::Env => surface_family(family, e),
    }
}

fn export_family(e: &Evidence) -> (Completeness, Option<String>) {
    let gap = from_unresolved(e, "could not be enumerated");
    match (gap, export_limit(e.lang)) {
        (Some((c, Some(reason))), Some(limit)) => (c, Some(format!("{reason}; {limit}"))),
        (Some(gap), _) => gap,
        (None, Some(limit)) => {
            let c = if e.found > 0 {
                Completeness::Partial
            } else {
                Completeness::Unknown
            };
            (c, Some(limit.to_string()))
        }
        (None, None) => (Completeness::Complete, None),
    }
}

/// What reading the error paths of a language read from the tree leaves out.
const ERROR_PATH_LIMIT: &str = concat!(
    "explicit failure statements of every inventoried file (throw/raise, exit calls, ",
    "rejected promises); errors raised by called code, error callbacks and HTTP error ",
    "responses are not followed"
);

fn error_family(e: &Evidence) -> (Completeness, Option<String>) {
    if !crate::error_paths::reads_raises(e.lang) {
        return (
            Completeness::Unknown,
            Some(format!("no error-path detector for {} yet", e.lang.name())),
        );
    }
    if let Some(gap) = from_unresolved(e, "could not be scanned, so error paths may be missing") {
        return gap;
    }
    if ast_errors(e.lang) {
        // Never `complete`: what calls, error callbacks and HTTP responses raise cannot be read
        // in a statement.
        return (Completeness::Partial, Some(ERROR_PATH_LIMIT.to_string()));
    }
    (
        Completeness::Partial,
        Some(
            "a line scan of the exported functions: errors raised elsewhere or by called \
             code are not followed"
                .to_string(),
        ),
    )
}

/// Why `enumerated` is not `complete`.
const NOT_A_PROOF: &str =
    "what the detectors recognise is listed; another way of declaring one would not be seen";

/// Never `complete`: what the family contains cannot be read in full from the syntax.
fn surface_family(family: Family, e: &Evidence) -> (Completeness, Option<String>) {
    if !e.has_detector {
        return (
            Completeness::Unknown,
            Some(format!(
                "no {} detector for {} yet",
                family.noun(),
                e.lang.name()
            )),
        );
    }
    if let Some(found) = from_unresolved(e, "could not be enumerated") {
        return found;
    }
    if e.found > 0 {
        return (Completeness::Enumerated, Some(NOT_A_PROOF.to_string()));
    }
    // Nothing found, but an argument parser was read in full with no unenumerated site: it
    // declares nothing visible. A CLI with no subcommand or no flag is common. There is no
    // equivalent rule for routes: a framework with no recognised route is more often a way of
    // declaring them that the detector does not read.
    if matches!(family, Family::Command | Family::Flag) && !e.recognised.is_empty() {
        return (
            Completeness::NoneFound,
            Some(format!(
                "{} declares no {}",
                e.recognised.join(", "),
                family.noun()
            )),
        );
    }
    // Otherwise the absence reads as `none-found` only if the entry point that would carry this
    // surface was not seen either.
    let (app, present, none_found) = match family {
        Family::Command | Family::Flag => ("CLI", e.has_cli, "no argument parser was recognised"),
        Family::Route => ("server", e.has_server, "no route was recognised"),
        _ => {
            return (
                Completeness::NoneFound,
                Some("no inventoried file reads the environment".to_string()),
            );
        }
    };
    if present {
        (
            Completeness::Unknown,
            Some(format!("the app has a {app} entry point but {none_found}")),
        )
    } else {
        (
            Completeness::NoneFound,
            Some(format!(
                "no {app} entry point in the manifests or the code (shape {})",
                e.shape
            )),
        )
    }
}

/// Writes the registry to `rust/OBLIGATIONS.json` of the repository `root` (indented JSON, final
/// newline) and returns the path written.
pub fn write(root: &Path, ledger: &Ledger) -> Result<std::path::PathBuf> {
    let root = root
        .canonical()
        .with_context(|| format!("finding {}", root.display()))?;
    let json = serde_json::to_string_pretty(ledger)?;
    standing::write_in_repo(&root, LEDGER_FILE, &format!("{json}\n"))?;
    Ok(root.join(LEDGER_FILE))
}

/// The report for a human: one line per family, the unenumerated sites, a summary.
pub fn text(ledger: &Ledger) -> String {
    let mut out = String::new();
    let _ = render(&mut out, ledger);
    out
}

fn render(out: &mut String, ledger: &Ledger) -> std::fmt::Result {
    writeln!(
        out,
        "Obligations of the original ({}, shape {})\n",
        ledger.language.name(),
        ledger.shape
    )?;
    for f in &ledger.families {
        let detectors = if f.detectors.is_empty() {
            "none".to_string()
        } else {
            f.detectors.join(", ")
        };
        let line = format!(
            "{:<10}  {:<14}  {:>5}  {}",
            f.family.label(),
            f.completeness.label(),
            f.count,
            f.reason.as_deref().unwrap_or_default()
        );
        writeln!(out, "{}", line.trim_end())?;
        writeln!(out, "{:<10}  detectors: {detectors}", "")?;
    }
    if !ledger.unresolved.is_empty() {
        writeln!(out, "\nNot enumerated:")?;
        // A site that hides several families is written once.
        let mut groups: Vec<((&str, &str), Vec<Family>)> = Vec::new();
        let mut index: BTreeMap<(&str, &str), usize> = BTreeMap::new();
        for u in &ledger.unresolved {
            let key = (u.site.as_str(), u.reason.as_str());
            match index.get(&key) {
                Some(&i) => groups[i].1.push(u.family),
                None => {
                    index.insert(key, groups.len());
                    groups.push((key, vec![u.family]));
                }
            }
        }
        for ((site, reason), families) in groups.iter().take(SHOWN_UNRESOLVED) {
            let who = if families.len() == Family::ALL.len() {
                "all".to_string()
            } else {
                families
                    .iter()
                    .map(|f| f.label())
                    .collect::<Vec<_>>()
                    .join(",")
            };
            writeln!(out, "  {who}  {site}  {reason}")?;
        }
        let more = groups.len().saturating_sub(SHOWN_UNRESOLVED);
        if more > 0 {
            writeln!(out, "  ... and {more} more (see --json)")?;
        }
    }
    let open = ledger
        .families
        .iter()
        .filter(|f| f.completeness.is_open())
        .count();
    let state = match open {
        0 => "no family has a site that could not be enumerated".to_string(),
        1 => "1 family is not fully enumerated".to_string(),
        n => format!("{n} families are not fully enumerated"),
    };
    writeln!(
        out,
        "\n{}; {state}",
        plural(ledger.obligations.len(), "obligation", "obligations")
    )?;
    let unproven: Vec<&str> = ledger
        .families
        .iter()
        .filter(|f| f.completeness.needs_attestation())
        .map(|f| f.family.label())
        .collect();
    if !unproven.is_empty() {
        writeln!(
            out,
            "{} rest on what the detectors recognise, which proves nothing about the rest: \
             a person attests them",
            unproven.join(", ")
        )?;
    }
    Ok(())
}

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

    fn evidence(lang: Lang, found: usize, unresolved: usize) -> Evidence<'static> {
        Evidence {
            lang,
            shape: "library",
            has_detector: matches!(lang, Lang::Ts | Lang::Python),
            has_cli: false,
            has_server: false,
            recognised: &[],
            found,
            unresolved,
            first_unresolved: (unresolved > 0).then_some("src/a.ts:3"),
        }
    }

    fn rule(family: Family, e: &Evidence) -> Completeness {
        completeness(family, e).0
    }

    #[test]
    fn a_language_without_a_detector_is_unknown_never_none_found() {
        for family in [Family::Command, Family::Flag, Family::Route, Family::Env] {
            let (c, reason) = completeness(family, &evidence(Lang::Go, 0, 0));
            assert_eq!(c, Completeness::Unknown);
            let reason = reason.unwrap();
            assert!(
                reason.contains("Go") && reason.contains(family.noun()),
                "{reason}"
            );
        }
    }

    #[test]
    fn unresolved_sites_make_a_family_partial_or_unknown() {
        for family in [Family::Command, Family::Flag, Family::Route, Family::Env] {
            let (c, reason) = completeness(family, &evidence(Lang::Ts, 2, 3));
            assert_eq!(c, Completeness::Partial);
            let reason = reason.unwrap();
            assert!(
                reason.contains("3 sites") && reason.contains("src/a.ts:3"),
                "{reason}"
            );
            assert_eq!(
                rule(family, &evidence(Lang::Python, 0, 1)),
                Completeness::Unknown
            );
        }
    }

    #[test]
    fn nothing_found_is_none_found_only_without_the_entry_point() {
        for lang in [Lang::Ts, Lang::Python] {
            assert_eq!(
                completeness(Family::Env, &evidence(lang, 0, 0)),
                (
                    Completeness::NoneFound,
                    Some("no inventoried file reads the environment".to_string())
                )
            );
            for family in [Family::Command, Family::Flag, Family::Route] {
                let (c, reason) = completeness(family, &evidence(lang, 0, 0));
                assert_eq!(c, Completeness::NoneFound);
                assert!(reason.unwrap().contains("entry point"));
            }
            let mut cli = evidence(lang, 0, 0);
            cli.has_cli = true;
            for family in [Family::Command, Family::Flag] {
                let (c, reason) = completeness(family, &cli);
                assert_eq!(c, Completeness::Unknown);
                assert!(
                    reason
                        .unwrap()
                        .contains("no argument parser was recognised")
                );
            }
            assert_eq!(rule(Family::Route, &cli), Completeness::NoneFound);
            let mut server = evidence(lang, 0, 0);
            server.has_server = true;
            let (c, reason) = completeness(Family::Route, &server);
            assert_eq!(c, Completeness::Unknown);
            assert!(reason.unwrap().contains("no route was recognised"));
            assert_eq!(rule(Family::Command, &server), Completeness::NoneFound);
        }
    }

    #[test]
    fn a_parser_seen_in_use_makes_nothing_found_none_found_not_unknown() {
        let parser = ["commander".to_string()];
        for lang in [Lang::Ts, Lang::Python] {
            for has_cli in [false, true] {
                let mut cli = evidence(lang, 0, 0);
                cli.has_cli = has_cli;
                cli.recognised = &parser;
                for family in [Family::Command, Family::Flag] {
                    let (c, reason) = completeness(family, &cli);
                    assert_eq!(c, Completeness::NoneFound);
                    let reason = reason.unwrap();
                    assert!(
                        reason.contains("commander declares no") && reason.contains(family.noun()),
                        "{reason}"
                    );
                }
            }
            // An unenumerated site wins over the recognised parser.
            let mut gap = evidence(lang, 0, 1);
            gap.has_cli = true;
            gap.recognised = &parser;
            assert_eq!(rule(Family::Flag, &gap), Completeness::Unknown);
            // A recognised framework with no route proves nothing.
            let mut server = evidence(lang, 0, 0);
            server.has_server = true;
            server.recognised = &parser;
            assert_eq!(rule(Family::Route, &server), Completeness::Unknown);
        }
    }

    #[test]
    fn a_surface_family_with_items_and_no_gap_is_enumerated_never_complete() {
        for family in [Family::Command, Family::Flag, Family::Route, Family::Env] {
            assert_eq!(
                completeness(family, &evidence(Lang::Ts, 4, 0)),
                (Completeness::Enumerated, Some(NOT_A_PROOF.to_string()))
            );
        }
    }

    /// No input evidence makes a surface family say `complete`: not the items found, not a
    /// recognised parser, not a missing entry point.
    #[test]
    fn no_evidence_makes_a_surface_family_complete() {
        let parser = ["commander".to_string()];
        for family in [Family::Command, Family::Flag, Family::Route, Family::Env] {
            for lang in [Lang::Ts, Lang::Python, Lang::Go] {
                for found in [0, 3] {
                    for unresolved in [0, 2] {
                        for (has_cli, has_server) in
                            [(false, false), (true, false), (false, true), (true, true)]
                        {
                            for recognised in [&[][..], &parser[..]] {
                                let mut e = evidence(lang, found, unresolved);
                                e.has_cli = has_cli;
                                e.has_server = has_server;
                                e.recognised = recognised;
                                let c = rule(family, &e);
                                assert_ne!(c, Completeness::Complete, "{family:?} {lang:?}");
                                assert_eq!(
                                    c.is_open(),
                                    unresolved > 0 || !e.has_detector || {
                                        found == 0
                                            && match family {
                                                Family::Command | Family::Flag => {
                                                    has_cli && recognised.is_empty()
                                                }
                                                Family::Route => has_server,
                                                _ => false,
                                            }
                                    },
                                    "{family:?} {lang:?} found {found} unresolved {unresolved}"
                                );
                            }
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn exports_are_complete_only_for_languages_read_in_full() {
        assert_eq!(
            completeness(Family::Export, &evidence(Lang::Ts, 5, 0)),
            (Completeness::Complete, None)
        );
        assert_eq!(
            completeness(Family::Export, &evidence(Lang::Python, 0, 0)),
            (Completeness::Complete, None)
        );
        assert_eq!(
            rule(Family::Export, &evidence(Lang::Ts, 5, 2)),
            Completeness::Partial
        );
        assert_eq!(
            rule(Family::Export, &evidence(Lang::Ts, 0, 2)),
            Completeness::Unknown
        );
        for lang in [
            Lang::C,
            Lang::Csharp,
            Lang::Go,
            Lang::Java,
            Lang::Kotlin,
            Lang::Php,
            Lang::Powershell,
            Lang::Ruby,
            Lang::Swift,
        ] {
            let (c, reason) = completeness(Family::Export, &evidence(lang, 3, 0));
            assert_eq!(c, Completeness::Partial, "{lang:?}");
            assert!(reason.unwrap().contains(lang.name()), "{lang:?}");
            // An unenumerated site is added to the language's limit instead of replacing it.
            let (_, both) = completeness(Family::Export, &evidence(lang, 3, 1));
            let both = both.unwrap();
            assert!(
                both.contains("first at") && both.contains("not listed"),
                "{both}"
            );
        }
    }

    #[test]
    fn error_paths_are_never_complete() {
        let (c, reason) = completeness(Family::ErrorPath, &evidence(Lang::C, 0, 0));
        assert_eq!(c, Completeness::Unknown);
        assert!(reason.unwrap().contains("C yet"));
        let (c, reason) = completeness(Family::ErrorPath, &evidence(Lang::Go, 3, 0));
        assert_eq!(c, Completeness::Partial);
        assert!(reason.unwrap().contains("line scan"));
        for lang in [Lang::Ts, Lang::Python] {
            // Never `complete`: at best `partial`, with the limit of the reading.
            let (c, reason) = completeness(Family::ErrorPath, &evidence(lang, 3, 0));
            assert_eq!(c, Completeness::Partial);
            assert!(reason.unwrap().contains("explicit failure statements"));
            assert_eq!(
                rule(Family::ErrorPath, &evidence(lang, 0, 0)),
                Completeness::Partial
            );
            let (c, reason) = completeness(Family::ErrorPath, &evidence(lang, 3, 1));
            assert_eq!(c, Completeness::Partial);
            assert!(reason.unwrap().contains("error paths may be missing"));
        }
    }

    fn found(family: Family, name: &str, scope: Option<&str>) -> Found {
        Found {
            family,
            name: name.to_string(),
            line: 1,
            scope: scope.map(str::to_string),
            detail: None,
        }
    }

    #[test]
    fn ids_carry_no_line_number_and_name_the_file_that_declares_them() {
        let id = |f: Found| surface_id(&f, "src/cli.ts").unwrap();
        assert_eq!(
            id(found(Family::Command, "build", None)),
            "command:src/cli.ts#build"
        );
        assert_eq!(
            id(found(Family::Flag, "--out", Some("build"))),
            "flag:src/cli.ts#build/--out"
        );
        assert_eq!(
            id(found(Family::Flag, "--verbose", None)),
            "flag:src/cli.ts#--verbose"
        );
        assert_eq!(
            id(found(Family::Route, "GET /users/:id", None)),
            "route:src/cli.ts#GET /users/:id"
        );
        // An environment variable is global: the file is not part of its id.
        assert_eq!(id(found(Family::Env, "HOME", None)), "env:HOME");
        assert!(surface_id(&found(Family::Export, "f", None), "a.ts").is_none());
        assert_eq!(
            export_id("src/a.ts", "Stack.push"),
            "export:src/a.ts#Stack.push"
        );
    }

    #[test]
    fn the_error_slug_is_the_raising_statement_cut_to_sixty_characters() {
        assert_eq!(
            statement("if (!s) {   throw new   Error('empty')  }"),
            "throw new Error('empty') }"
        );
        assert_eq!(
            statement("return 0, errors.New(\"x\")"),
            "return 0, errors.New(\"x\")"
        );
        let long = format!("raise ValueError('{}')", "x".repeat(100));
        let id = error_id("a.py", "parse", &statement(&long));
        let slug = id.strip_prefix("error:a.py#parse:").unwrap();
        assert_eq!(slug.chars().count(), SLUG_LENGTH);
        assert!(slug.starts_with("raise ValueError('xxx"));
    }

    fn at(file: &str, line: u32, id: &str) -> Draft {
        draft(
            Family::ErrorPath,
            id.to_string(),
            "f",
            file,
            line,
            None,
            None,
        )
    }

    fn ids(drafts: &[Draft]) -> Vec<(&str, u32, &str)> {
        drafts
            .iter()
            .map(|d| (d.file.as_str(), d.line, d.obligation.id.as_str()))
            .collect()
    }

    #[test]
    fn identical_ids_are_numbered_in_source_order() {
        let drafts = vec![
            at("b.ts", 1, "x"),
            at("a.ts", 9, "x"),
            at("a.ts", 10, "x"),
            at("a.ts", 2, "x"),
            at("a.ts", 5, "y"),
        ];
        let out = disambiguate(drafts);
        // Lines compare as numbers: 9 before 10.
        assert_eq!(
            ids(&out),
            [
                ("a.ts", 2, "x"),
                ("a.ts", 5, "y"),
                ("a.ts", 9, "x~2"),
                ("a.ts", 10, "x~3"),
                ("b.ts", 1, "x~4"),
            ]
        );
    }

    #[test]
    fn the_same_surface_item_found_twice_keeps_its_first_site() {
        let drafts = vec![
            at("b.ts", 1, "env:A"),
            at("a.ts", 20, "env:A"),
            at("a.ts", 3, "env:B"),
            at("a.ts", 7, "env:A"),
        ];
        let out = dedupe(drafts);
        assert_eq!(ids(&out), [("a.ts", 3, "env:B"), ("a.ts", 7, "env:A")]);
    }

    #[test]
    fn surface_declarations_merge_only_when_they_are_the_same_one() {
        let surface = |file: &str, line, id: &str, family| {
            draft(family, id.to_string(), "n", file, line, None, None)
        };
        let drafts = vec![
            // The same declaration seen twice: one obligation.
            surface("a.ts", 4, "command:a.ts#run", Family::Command),
            surface("a.ts", 4, "command:a.ts#run", Family::Command),
            // Two declarations with the same name in one file: two obligations.
            surface("a.ts", 9, "command:a.ts#run", Family::Command),
            // A variable read in two files: one obligation, at the first site.
            surface("b.ts", 2, "env:HOME", Family::Env),
            surface("a.ts", 30, "env:HOME", Family::Env),
        ];
        let out = dedupe_surface(drafts);
        assert_eq!(
            ids(&out),
            [
                ("a.ts", 4, "command:a.ts#run"),
                ("a.ts", 9, "command:a.ts#run~2"),
                ("a.ts", 30, "env:HOME"),
            ]
        );
    }

    #[test]
    fn sites_are_ordered_by_line_number_not_by_text() {
        let site = |line| Site {
            family: Family::Export,
            file: "a.ts".into(),
            line,
            reason: "r".into(),
        };
        let mut sites = [site(10), site(3), site(9)];
        sites.sort();
        let lines: Vec<u32> = sites.iter().map(|s| s.line).collect();
        assert_eq!(lines, [3, 9, 10]);
    }

    #[test]
    fn python_imports_name_the_files_they_may_mean() {
        let bases = vec![String::new(), "src".to_string()];
        assert_eq!(
            python_modules("pkg/a.py", ".b", &bases),
            ["pkg/b.py", "pkg/b/__init__.py"]
        );
        assert_eq!(python_modules("pkg/a.py", ".", &bases), ["pkg/__init__.py"]);
        assert_eq!(
            python_modules("pkg/a.py", "..top", &bases),
            ["top.py", "top/__init__.py"]
        );
        assert!(python_modules("top.py", "..x", &bases).is_empty());
        assert_eq!(
            python_modules("main.py", "pkg.mod", &bases),
            [
                "pkg/mod.py",
                "pkg/mod/__init__.py",
                "src/pkg/mod.py",
                "src/pkg/mod/__init__.py",
            ]
        );
    }

    fn sample(files: &[(&str, &str)], tag: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "rust-anything-obligations-{}-{tag}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        for (path, text) in files {
            let full = dir.join(path);
            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
            std::fs::write(full, text).unwrap();
        }
        dir
    }

    fn family(ledger: &Ledger, family: Family) -> &FamilyReport {
        ledger.families.iter().find(|f| f.family == family).unwrap()
    }

    #[test]
    fn a_ledger_is_deterministic_and_holds_no_absolute_path() {
        let dir = sample(
            &[
                ("package.json", "{\"name\":\"t\",\"version\":\"1.0.0\"}"),
                (
                    "src/a.ts",
                    "export function parse(s: string) {\n  if (!s) throw new Error('empty')\n  if (s === 'x') throw new Error('x')\n  return s\n}\nexport const VERSION = 3\n",
                ),
                ("src/b.ts", "export function ok(n: number) { return n }\n"),
            ],
            "determinism",
        );
        let first = serde_json::to_string_pretty(&ledger(&dir, None).unwrap()).unwrap();
        let second = serde_json::to_string_pretty(&ledger(&dir, None).unwrap()).unwrap();
        let again: Ledger = serde_json::from_str(&first).unwrap();
        let shown = dir.to_string_lossy().replace('\\', "/");
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(first, second);
        assert!(!first.contains(&shown) && !first.contains('\\'), "{first}");
        let ids: Vec<&str> = again.obligations.iter().map(|o| o.id.as_str()).collect();
        assert_eq!(
            ids,
            [
                "export:src/a.ts#VERSION",
                "export:src/a.ts#parse",
                "export:src/b.ts#ok",
                "error:src/a.ts#parse:throw new Error('empty')",
                "error:src/a.ts#parse:throw new Error('x')",
            ]
        );
        assert!(again.unresolved.is_empty(), "{:?}", again.unresolved);
        assert_eq!(
            family(&again, Family::Export).completeness,
            Completeness::Complete
        );
        assert_eq!(
            family(&again, Family::ErrorPath).completeness,
            Completeness::Partial
        );
    }

    #[test]
    fn an_injected_detector_feeds_the_whole_pipeline() {
        let dir = sample(
            &[
                ("package.json", "{\"name\":\"t\",\"version\":\"1.0.0\"}"),
                ("src/a.ts", "export function f() { return 1 }\n"),
            ],
            "injected",
        );
        let detector = |path: &str, _text: &str| {
            let mut surface = Surface::default();
            surface.found.push(Found {
                family: Family::Env,
                name: "TOKEN".into(),
                line: 1,
                scope: None,
                detail: None,
            });
            surface.found.push(Found {
                family: Family::Env,
                name: "TOKEN".into(),
                line: 9,
                scope: None,
                detail: None,
            });
            surface.unresolved.push(surface::UnresolvedInFile {
                family: Family::Route,
                line: 2,
                reason: format!("dynamic route in {path}"),
            });
            surface.recognised.insert((Family::Env, "fake".into()));
            surface
        };
        let out = ledger_with(&dir, None, &detector).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        let env: Vec<&str> = out
            .obligations
            .iter()
            .filter(|o| o.family == Family::Env)
            .map(|o| o.id.as_str())
            .collect();
        assert_eq!(env, ["env:TOKEN"]);
        let route = family(&out, Family::Route);
        assert_eq!(route.completeness, Completeness::Unknown);
        assert!(route.reason.as_deref().unwrap().contains("src/a.ts:2"));
        assert_eq!(family(&out, Family::Env).detectors, ["oxc-surface", "fake"]);
        assert_eq!(
            family(&out, Family::Env).completeness,
            Completeness::Enumerated
        );
    }
}