Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

90.5 KB
Raw Blame
// ©AngelaMos | 2026
// main.rs

use std::error::Error;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;

use clap::{Parser, Subcommand};
use lisdex_build::artifact;
use lisdex_build::instrument::{Instrumentation, SanitizerSet};
use lisdex_build::ladder::{self, BuildOptions};
use lisdex_build::layout::{BuildLayout, VARIANT_AFL, VARIANT_BENCH};
use lisdex_build::verify::{self, Requirements};
use lisdex_core::campaign::{Campaign, CampaignId, CampaignStatus, TreeProvenance};
use lisdex_core::config::{
    DEFAULT_MINIMIZE_EXEC_TIMEOUT_MS, DEFAULT_PARALLEL_JOBS, DEFAULT_REPRODUCE_TIMEOUT_MS,
    DEFAULT_TRIALS, LlmTier,
};
use lisdex_core::crash::Crash;
use lisdex_core::dedup;
use lisdex_core::report::SanitizerReport;
use lisdex_core::store::Store;
use lisdex_fuzz::bench;
use lisdex_fuzz::corpus;
use lisdex_fuzz::dictionary;
use lisdex_fuzz::interrupt::Interrupt;
use lisdex_fuzz::minimize::{self, Outcome, TminInvocation};
use lisdex_fuzz::plot;
use lisdex_fuzz::runner::{self, AflOptions};
use lisdex_harness::coverage::EdgeSet;
use lisdex_harness::emit;
use lisdex_harness::search;
use lisdex_harness::synth;
use lisdex_harness::verify::{Bench, Corpus, Toolchain, Verdict};
use lisdex_ingest::acquire::{self, Source};
use lisdex_ingest::detect;
use lisdex_monitor::snapshot::Source as MonitorSource;
use lisdex_report::advisory::Advisory;
use lisdex_report::bundle::{self, Reproducer};
use lisdex_report::{json, markdown};
use lisdex_surface::eval;
use lisdex_surface::extract::{self, Language};
use lisdex_surface::headers;
use lisdex_surface::surface::{self, SurfaceOptions};
use lisdex_triage::classify::classify;

const UNKNOWN_TARGET: &str = "unknown";
const UNPARSED_KIND: &str = "unparsed";
const UNCLASSIFIED_SEVERITY: &str = "UNCLASSIFIED";
const NON_SECURITY_MARKER: &str = "/non-security";
const NO_STACK_HASH: &str = "none";
const UNKEYED_MARKER: &str = "unkeyed";
const STACK_HASH_SHORT_LEN: usize = 16;
const BENCH_ARMS: usize = 2;
const ORIGINAL_SUFFIX: &str = ".orig";
const MINIMIZED_SUFFIX: &str = ".min";
const MARKDOWN_SUFFIX: &str = ".md";
const JSON_SUFFIX: &str = ".json";
const NOT_DISCLOSABLE_MARKER: &str = " NOT DISCLOSABLE";
const BENCHMARK_TREE_WARNING: &str = "warning: this target links magma canary symbols, so its tree is a benchmark carrying \
     forward-ported historical CVEs. Every finding from this campaign is recorded NOT \
     DISCLOSABLE regardless of what its stack shows.";
const UNKNOWN_TREE_WARNING: &str = "warning: the target's symbols could not be read, so whether its tree is a benchmark is \
     unknown. Disclosability falls back to stack frames alone, which cannot see a \
     forward-ported bug that misses the canary.";
const DISPLAYED_FRAMES: usize = 6;
const SOURCES_DIR: &str = "sources";
const BUILDS_DIR: &str = "builds";
const DEFAULT_SURFACE_TOP: usize = 20;
const MAX_SKIPPED_SHOWN: usize = 10;
const CANDIDATES_DIR: &str = "candidates";
const ORACLE_WORK_DIR: &str = "oracle";
const CONFIGURE_SCRATCH: &str = "surface-configure";
const CONFIGURE_VARIANT: &str = "configure";
const NO_SEEDS: &str = "--seeds is required: the harness oracles run the candidate against a \
                        valid corpus, and without one lisdex cannot tell a working harness from \
                        one that reads nothing. Pass --no-verify to emit an unchecked harness \
                        anyway";
const NO_ARCHIVE: &str = "--archive is required: the harness has to link against the \
                          instrumented library that `lisdex build` produced";
const UNVERIFIED_BANNER: &str = "UNVERIFIED: no oracle was run against this harness. It may not \
                                 compile, may crash on valid input, or may read none of it.";
const LLM_PROBE_SUBJECT: &str = "is the parameter src a byte buffer or a nul-terminated string";
const LLM_PROBE_EVIDENCE: &str =
    "int LZ4_decompress_safe(const char *src, char *dst, int compressedSize, int dstCapacity);";
const LLM_PROBE_BALLOT: [&str; 2] = ["byte_buffer", "nul_terminated_string"];
const SAMPLE_CSV_HEADER: &str =
    "relative_time,corpus_count,edges_found,execs_per_sec,total_execs,saved_crashes,map_size_pct";

#[derive(clap::Args)]
struct RankEvalArgs {
    #[arg(help = "source tree of the target library, repeatable")]
    sources: Vec<PathBuf>,
    #[arg(long = "include", help = "extra include directory, repeatable")]
    includes: Vec<PathBuf>,
    #[arg(long = "define", help = "extra preprocessor define, repeatable")]
    defines: Vec<String>,
    #[arg(long, help = "parse headers as C++ instead of C")]
    cpp: bool,
    #[arg(
        long = "at",
        help = "cutoff to report precision and recall at, repeatable"
    )]
    cutoffs: Vec<usize>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
enum MetricChoice {
    Edges,
    Crashes,
    TimeToFirstCrash,
}

impl From<MetricChoice> for bench::Metric {
    fn from(choice: MetricChoice) -> Self {
        match choice {
            MetricChoice::Edges => bench::Metric::Edges,
            MetricChoice::Crashes => bench::Metric::Crashes,
            MetricChoice::TimeToFirstCrash => bench::Metric::TimeToFirstCrash,
        }
    }
}

#[derive(clap::Args)]
struct BenchArgs {
    #[arg(
        long = "arm",
        help = "an instrumented harness to compare, as name=path, given exactly twice"
    )]
    arms: Vec<String>,
    #[arg(
        long,
        help = "directory of seed inputs, shared by every arm so the comparison measures the build and not the corpus"
    )]
    seeds: PathBuf,
    #[arg(long, help = "scratch directory for per-trial findings")]
    work: PathBuf,
    #[arg(long, default_value_t = DEFAULT_TRIALS, help = "trials per arm")]
    trials: usize,
    #[arg(long, help = "wall-clock limit per trial in seconds")]
    duration: u64,
    #[arg(
        long,
        value_enum,
        default_value_t = MetricChoice::Edges,
        help = "which measurement to compare the arms on"
    )]
    metric: MetricChoice,
    #[arg(long, help = "stop each trial as soon as it finds its first crash")]
    until_crash: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
enum SanitizerChoice {
    AddressUndefined,
    Memory,
    Off,
}

impl From<SanitizerChoice> for SanitizerSet {
    fn from(choice: SanitizerChoice) -> Self {
        match choice {
            SanitizerChoice::AddressUndefined => SanitizerSet::AddressUndefined,
            SanitizerChoice::Memory => SanitizerSet::Memory,
            SanitizerChoice::Off => SanitizerSet::Off,
        }
    }
}

#[derive(Parser)]
#[command(
    name = "lisdex",
    version,
    about = "keyless local zero-day parser fuzzer"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    #[command(about = "auto-build a target under sanitizers with no hand-written build script")]
    Build(BuildArgs),
    #[command(about = "run an AFL++ campaign against an instrumented harness")]
    Fuzz(FuzzArgs),
    #[command(about = "rank the parser entry points of a source tree")]
    Surface(SurfaceArgs),
    #[command(about = "synthesize a fuzz harness for a ranked entry point, with no LLM")]
    Harness(HarnessArgs),
    #[command(about = "run the four harness oracles against one harness source file")]
    Verify(VerifyArgs),
    #[command(about = "list the crashes persisted for a campaign")]
    Crashes(CrashesArgs),
    #[command(
        about = "read a findings directory an earlier campaign left on disk and persist its crashes"
    )]
    Import(ImportArgs),
    #[command(
        about = "minimize one reproducer per distinct bug, rejecting any that changes identity"
    )]
    Minimize(MinimizeArgs),
    #[command(about = "report which LLM booster tier is configured and whether it answers")]
    Llm(LlmArgs),
    #[command(
        about = "draft a coordinated-disclosure advisory for each distinct bug in a campaign"
    )]
    Advisory(AdvisoryArgs),
    #[command(
        about = "write a self-contained reproducer bundle per distinct bug: advisory, PoC, report, repro script"
    )]
    Bundle(BundleArgs),
    #[command(about = "report the coverage curve a campaign recorded, over time")]
    Coverage(CoverageArgs),
    #[command(about = "distil a corpus to the smallest set that still reaches the same edges")]
    Corpus(CorpusArgs),
    #[command(
        about = "compare two builds over repeated trials, with a Mann-Whitney U test and an effect size"
    )]
    Bench(BenchArgs),
    #[command(
        about = "score the cold-start ranking against the entry points this project's own fuzz harnesses call"
    )]
    RankEval(RankEvalArgs),
    #[command(about = "watch a campaign live in a terminal dashboard")]
    Tui(TuiArgs),
    #[command(about = "serve a local web console over the same campaign state")]
    Serve(ServeArgs),
}

#[derive(clap::Args)]
struct ServeArgs {
    #[arg(long, help = "sqlite database a campaign is writing to")]
    db: PathBuf,
    #[arg(long, help = "afl-fuzz output directory the campaign is writing to")]
    findings: PathBuf,
    #[arg(
        long,
        help = "campaign id to serve; defaults to the most recent one in the store"
    )]
    campaign: Option<i64>,
    #[arg(
        long,
        default_value_t = lisdex_dashboard::DEFAULT_PORT,
        help = "port to bind"
    )]
    port: u16,
    #[arg(
        long,
        default_value_t = lisdex_dashboard::DEFAULT_HOST,
        help = "address to bind; the default keeps the console on this machine, and anything else publishes unfixed vulnerabilities to whoever can reach it"
    )]
    host: std::net::IpAddr,
}

#[derive(clap::Args)]
struct TuiArgs {
    #[arg(long, help = "sqlite database a campaign is writing to")]
    db: PathBuf,
    #[arg(long, help = "afl-fuzz output directory the campaign is writing to")]
    findings: PathBuf,
    #[arg(
        long,
        help = "campaign id to watch; defaults to the most recent one in the store"
    )]
    campaign: Option<i64>,
    #[arg(
        long,
        default_value_t = lisdex_tui::app::DEFAULT_REFRESH_MS,
        help = "milliseconds between re-reads of the campaign's state"
    )]
    refresh: u64,
    #[arg(
        long,
        help = "render one frame as plain text and exit, for scripting and for terminals that are not interactive"
    )]
    once: bool,
    #[arg(
        long,
        default_value_t = lisdex_tui::ONCE_WIDTH,
        help = "columns to render at with --once"
    )]
    width: u16,
    #[arg(
        long,
        default_value_t = lisdex_tui::ONCE_HEIGHT,
        help = "rows to render at with --once"
    )]
    height: u16,
    #[arg(
        long,
        value_enum,
        default_value_t = PanelArg::Overview,
        help = "which panel to open on"
    )]
    panel: PanelArg,
}

#[derive(Clone, Copy, clap::ValueEnum)]
enum PanelArg {
    Overview,
    Findings,
    Instances,
}

impl From<PanelArg> for lisdex_tui::app::Tab {
    fn from(value: PanelArg) -> Self {
        match value {
            PanelArg::Overview => lisdex_tui::app::Tab::Overview,
            PanelArg::Findings => lisdex_tui::app::Tab::Findings,
            PanelArg::Instances => lisdex_tui::app::Tab::Instances,
        }
    }
}

#[derive(clap::Args)]
struct CorpusArgs {
    #[arg(
        long,
        help = "the instrumented harness the corpus will be fuzzed against"
    )]
    target: PathBuf,
    #[arg(long, help = "directory of inputs to distil")]
    input: PathBuf,
    #[arg(long, help = "directory to write the distilled corpus to")]
    output: PathBuf,
    #[arg(
        long,
        help = "parallel cmin workers (defaults to the machine's available parallelism)"
    )]
    workers: Option<usize>,
}

#[derive(clap::Args)]
struct CoverageArgs {
    #[arg(
        long,
        help = "afl-fuzz output directory written by a previous campaign"
    )]
    findings: PathBuf,
    #[arg(
        long,
        help = "print every sample as CSV instead of a summary, for plotting"
    )]
    samples: bool,
}

#[derive(clap::Args)]
struct BundleArgs {
    #[arg(long, help = "sqlite database written by a previous campaign")]
    db: PathBuf,
    #[arg(long, help = "campaign id whose bugs to bundle")]
    campaign: i64,
    #[arg(
        long,
        help = "directory to write one bundle directory per distinct bug"
    )]
    out: PathBuf,
    #[arg(
        long,
        help = "directory written by `lisdex minimize`; its verified .min reproducers are preferred over the original crashing inputs"
    )]
    minimized: Option<PathBuf>,
    #[arg(
        long,
        help = "the library as it is distributed; defaults to the campaign's fuzz target, which is usually the harness name rather than the package name"
    )]
    package: Option<String>,
}

#[derive(Clone, Copy, clap::ValueEnum)]
enum AdvisoryFormat {
    Markdown,
    Json,
}

#[derive(clap::Args)]
struct AdvisoryArgs {
    #[arg(long, help = "sqlite database written by a previous campaign")]
    db: PathBuf,
    #[arg(long, help = "campaign id whose bugs to draft advisories for")]
    campaign: i64,
    #[arg(
        long,
        value_enum,
        default_value_t = AdvisoryFormat::Markdown,
        help = "render a human advisory or the machine-readable form"
    )]
    format: AdvisoryFormat,
    #[arg(
        long,
        help = "directory to write one advisory per distinct bug; omit to print to stdout"
    )]
    out: Option<PathBuf>,
    #[arg(
        long,
        help = "the library as it is distributed; defaults to the campaign's fuzz target, which is usually the harness name rather than the package name"
    )]
    package: Option<String>,
}

#[derive(clap::Args)]
struct LlmArgs {
    #[arg(
        long,
        value_enum,
        default_value_t = TierArg::Local,
        help = "booster tier to report on"
    )]
    tier: TierArg,
    #[arg(
        long,
        help = "put the configured tier to a live question instead of only describing it"
    )]
    ask: bool,
}

#[derive(Clone, Copy, clap::ValueEnum)]
enum TierArg {
    None,
    Local,
    Api,
}

impl From<TierArg> for LlmTier {
    fn from(value: TierArg) -> Self {
        match value {
            TierArg::None => LlmTier::None,
            TierArg::Local => LlmTier::Local,
            TierArg::Api => LlmTier::Api,
        }
    }
}

#[derive(clap::Args)]
#[expect(clippy::struct_excessive_bools)]
struct BuildArgs {
    #[arg(help = "git URL or local path of the target library")]
    target: String,
    #[arg(long, help = "scratch directory for sources, builds and logs")]
    work: PathBuf,
    #[arg(long, help = "git reference to check out when the target is a URL")]
    reference: Option<String>,
    #[arg(long, help = "name for this target (defaults to the source name)")]
    label: Option<String>,
    #[arg(long, default_value = VARIANT_AFL, help = "build variant name")]
    variant: String,
    #[arg(long, help = "parallel build jobs")]
    jobs: Option<usize>,
    #[arg(long, help = "build a cmplog-instrumented variant")]
    cmplog: bool,
    #[arg(
        long = "no-oracle-bench",
        help = "skip the PCGUARD archive the harness oracles compare coverage against"
    )]
    no_oracle_bench: bool,
    #[arg(long, help = "build in the source tree instead of copying it first")]
    in_place: bool,
    #[arg(long, help = "reuse an already acquired source tree")]
    reuse: bool,
    #[arg(long = "cflag", help = "extra compiler flag, repeatable")]
    cflags: Vec<String>,
    #[arg(long, help = "require magma canary symbols in the built artifacts")]
    require_canaries: bool,
    #[arg(
        long,
        value_enum,
        default_value_t = SanitizerChoice::AddressUndefined,
        help = "sanitizer set for this build; memory is a SEPARATE second build and cannot be combined with address"
    )]
    sanitizer: SanitizerChoice,
}

#[derive(clap::Args)]
struct FuzzArgs {
    #[arg(long, help = "instrumented harness binary to fuzz")]
    target: PathBuf,
    #[arg(long, help = "cmplog-instrumented build of the same harness")]
    cmplog: Option<PathBuf>,
    #[arg(long, help = "directory of seed inputs")]
    seeds: PathBuf,
    #[arg(long, help = "afl-fuzz output directory")]
    findings: PathBuf,
    #[arg(long, help = "sqlite database to persist the campaign and crashes")]
    db: PathBuf,
    #[arg(long, help = "campaign wall-clock limit in seconds")]
    duration: Option<u64>,
    #[arg(long, help = "campaign label (defaults to the target file name)")]
    label: Option<String>,
    #[arg(long, help = "stop as soon as the first crash is found")]
    until_crash: bool,
    #[arg(
        long,
        action = clap::ArgAction::Set,
        default_value_t = true,
        help = "skip afl-fuzz deterministic stages"
    )]
    skip_deterministic: bool,
    #[arg(
        long,
        help = "dictionary file, repeatable; overrides the automatic selection made from the seed corpus"
    )]
    dict: Vec<PathBuf>,
    #[arg(
        long,
        help = "directory of format dictionaries to select from (defaults to the ones AFL++ ships)"
    )]
    dict_dir: Option<PathBuf>,
    #[arg(
        long,
        default_value_t = DEFAULT_PARALLEL_JOBS,
        help = "parallel afl-fuzz instances sharing one findings directory: one main and the rest secondaries"
    )]
    jobs: usize,
    #[arg(
        long,
        help = "continue a previous campaign in this findings directory instead of starting from the seeds"
    )]
    resume: bool,
}

#[derive(clap::Args)]
struct CrashesArgs {
    #[arg(long, help = "sqlite database written by a previous campaign")]
    db: PathBuf,
    #[arg(long, help = "campaign id to list")]
    campaign: i64,
}

#[derive(clap::Args)]
struct ImportArgs {
    #[arg(
        long,
        help = "findings directory a previous campaign wrote, whose crashes were never persisted"
    )]
    findings: PathBuf,
    #[arg(
        long,
        help = "the instrumented harness that produced them; each input is re-run against it to obtain a report"
    )]
    target: PathBuf,
    #[arg(long, help = "sqlite database to write the recovered campaign into")]
    db: PathBuf,
    #[arg(long, help = "campaign label (defaults to the target file name)")]
    label: Option<String>,
}

#[derive(clap::Args)]
struct MinimizeArgs {
    #[arg(long, help = "sqlite database written by a previous campaign")]
    db: PathBuf,
    #[arg(long, help = "campaign id whose crashes to minimize")]
    campaign: i64,
    #[arg(long, help = "the instrumented harness the campaign ran against")]
    target: PathBuf,
    #[arg(
        long,
        help = "directory to write one verified reproducer per distinct bug"
    )]
    out: PathBuf,
}

#[derive(clap::Args)]
struct OracleArgs {
    #[arg(
        long,
        help = "directory of valid inputs the oracles run the harness against"
    )]
    seeds: Option<PathBuf>,
    #[arg(
        long = "invalid-seeds",
        help = "directory of malformed inputs for the valid-versus-invalid differential"
    )]
    invalid_seeds: Option<PathBuf>,
    #[arg(
        long = "archive",
        help = "instrumented library archive to link against, repeatable"
    )]
    archives: Vec<PathBuf>,
    #[arg(
        long = "link-arg",
        allow_hyphen_values = true,
        help = "extra linker argument, repeatable"
    )]
    link_args: Vec<String>,
    #[arg(
        long = "cflag",
        allow_hyphen_values = true,
        help = "extra compiler flag, repeatable"
    )]
    cflags: Vec<String>,
    #[arg(long, help = "libAFLDriver.a to link the harness against")]
    driver: Option<PathBuf>,
    #[arg(long, help = "scratch directory for oracle binaries and coverage maps")]
    work: Option<PathBuf>,
}

impl OracleArgs {
    fn toolchain(&self, includes: Vec<PathBuf>, defines: Vec<String>) -> Toolchain {
        let mut toolchain = Toolchain {
            includes,
            defines,
            cflags: self.cflags.clone(),
            archives: self.archives.clone(),
            link_args: self.link_args.clone(),
            ..Toolchain::default()
        };
        if let Some(driver) = &self.driver {
            toolchain.driver.clone_from(driver);
        }
        toolchain
    }

    fn bench(
        &self,
        includes: Vec<PathBuf>,
        defines: Vec<String>,
        fallback: &std::path::Path,
    ) -> Result<Bench, Box<dyn Error>> {
        let Some(seeds) = &self.seeds else {
            return Err(NO_SEEDS.into());
        };
        if self.archives.is_empty() {
            return Err(NO_ARCHIVE.into());
        }
        let toolchain = self.toolchain(includes, defines);
        // A missing archive or driver surfaces as an undefined-symbol wall from the linker
        // and every candidate is then rejected as CompileFailed for the wrong reason.
        for archive in &toolchain.archives {
            if !archive.is_file() {
                return Err(format!("--archive {} is not a file", archive.display()).into());
            }
        }
        if !toolchain.driver.is_file() {
            return Err(format!(
                "the AFL driver {} is not a file; pass --driver with the path to libAFLDriver.a",
                toolchain.driver.display()
            )
            .into());
        }
        let corpus = Corpus::read(seeds, self.invalid_seeds.as_deref())?;
        let work = self
            .work
            .clone()
            .unwrap_or_else(|| fallback.join(ORACLE_WORK_DIR));
        Ok(Bench::new(work, corpus, toolchain))
    }
}

#[derive(clap::Args)]
struct VerifyArgs {
    #[arg(help = "harness source file to judge")]
    source: PathBuf,
    #[arg(long = "include", help = "extra include directory, repeatable")]
    includes: Vec<PathBuf>,
    #[arg(long = "define", help = "extra preprocessor define, repeatable")]
    defines: Vec<String>,
    #[command(flatten)]
    oracle: OracleArgs,
}

#[derive(clap::Args)]
struct HarnessArgs {
    #[arg(help = "source tree of the target library")]
    source: PathBuf,
    #[arg(long, help = "install prefix from a previous build, if one exists")]
    install: Option<PathBuf>,
    #[arg(long = "include", help = "extra include directory, repeatable")]
    includes: Vec<PathBuf>,
    #[arg(long = "define", help = "extra preprocessor define, repeatable")]
    defines: Vec<String>,
    #[arg(long, help = "parse headers as C++ instead of C")]
    cpp: bool,
    #[arg(
        long = "oss-fuzz",
        help = "checkout of google/oss-fuzz, read for the call order of libraries that ship no fuzz target of their own"
    )]
    oss_fuzz: Option<PathBuf>,
    #[arg(
        long = "library",
        help = "built .a or .so of this target, repeatable; restricts entry points to the functions the library actually defines instead of trusting the headers alone"
    )]
    libraries: Vec<PathBuf>,
    #[arg(long, default_value_t = DEFAULT_SURFACE_TOP, help = "how many ranked entry points to try")]
    top: usize,
    #[arg(long, help = "directory to write the synthesized harness into")]
    out: PathBuf,
    #[arg(
        long = "no-verify",
        help = "emit the first candidate that plans without running any oracle against it"
    )]
    no_verify: bool,
    #[arg(
        long = "plan-only",
        help = "report what every ranked candidate plans or is refused for, and write nothing"
    )]
    plan_only: bool,
    #[command(flatten)]
    oracle: OracleArgs,
}

#[derive(clap::Args)]
#[allow(clippy::struct_excessive_bools)]
struct SurfaceArgs {
    #[arg(help = "source tree of the target library")]
    source: PathBuf,
    #[arg(long, help = "install prefix from a previous build, if one exists")]
    install: Option<PathBuf>,
    #[arg(long = "include", help = "extra include directory, repeatable")]
    includes: Vec<PathBuf>,
    #[arg(long = "define", help = "extra preprocessor define, repeatable")]
    defines: Vec<String>,
    #[arg(long, help = "parse headers as C++ instead of C")]
    cpp: bool,
    #[arg(
        long,
        help = "rank the unreached frontier: what to fuzz next given the in-tree harnesses that already exist"
    )]
    frontier: bool,
    #[arg(
        long = "oss-fuzz",
        help = "checkout of google/oss-fuzz, read for the call order of libraries that ship no fuzz target of their own"
    )]
    oss_fuzz: Option<PathBuf>,
    #[arg(
        long = "library",
        help = "built .a or .so of this target, repeatable; restricts entry points to the functions the library actually defines instead of trusting the headers alone"
    )]
    libraries: Vec<PathBuf>,
    #[arg(long, default_value_t = DEFAULT_SURFACE_TOP, help = "how many ranked entry points to print")]
    top: usize,
    #[arg(long, help = "emit the full ranking as json")]
    json: bool,
    #[arg(long, help = "explain the score of every printed entry point")]
    explain: bool,
}

fn main() -> ExitCode {
    match dispatch() {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("lisdex: {err}");
            ExitCode::FAILURE
        }
    }
}

fn dispatch() -> Result<(), Box<dyn Error>> {
    match &Cli::parse().command {
        Command::Build(args) => build(args),
        Command::Fuzz(args) => fuzz(args),
        Command::Surface(args) => surface(args),
        Command::Harness(args) => harness(args),
        Command::Verify(args) => verify(args),
        Command::Crashes(args) => crashes(args),
        Command::Import(args) => import(args),
        Command::Advisory(args) => advisories(args),
        Command::Bundle(args) => bundles(args),
        Command::Coverage(args) => coverage(args),
        Command::Corpus(args) => distil_corpus(args),
        Command::Minimize(args) => minimize_campaign(args),
        Command::Llm(args) => llm(args),
        Command::Bench(args) => run_bench(args),
        Command::RankEval(args) => rank_eval(args),
        Command::Tui(args) => tui(args),
        Command::Serve(args) => serve(args),
    }
}

fn serve(args: &ServeArgs) -> Result<(), Box<dyn Error>> {
    lisdex_dashboard::serve(
        MonitorSource {
            db: args.db.clone(),
            findings: args.findings.clone(),
            campaign: args.campaign,
        },
        std::net::SocketAddr::new(args.host, args.port),
    )?;
    Ok(())
}

fn tui(args: &TuiArgs) -> Result<(), Box<dyn Error>> {
    let source = MonitorSource {
        db: args.db.clone(),
        findings: args.findings.clone(),
        campaign: args.campaign,
    };
    if args.once {
        let frame = lisdex_tui::render_once(source, args.panel.into(), args.width, args.height)?;
        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        if let Err(err) = write!(out, "{frame}") {
            return finish_stream(&err);
        }
        return Ok(());
    }
    lisdex_tui::run(source, Duration::from_millis(args.refresh))?;
    Ok(())
}

fn llm(args: &LlmArgs) -> Result<(), Box<dyn Error>> {
    let tier = LlmTier::from(args.tier);
    let booster = lisdex_llm::select(tier);
    println!("tier: {}", booster.describe());
    if !args.ask {
        return Ok(());
    }
    let ask = lisdex_llm::Ask::new(LLM_PROBE_SUBJECT, LLM_PROBE_EVIDENCE, probe_ballot())?;
    match booster.propose(&ask) {
        lisdex_llm::Outcome::Proposed(proposal) => {
            println!(
                "answered {:?} in {:.1}s",
                proposal.choice,
                proposal.elapsed.as_secs_f64()
            );
        }
        lisdex_llm::Outcome::Declined(declined) => println!("declined: {declined}"),
    }
    Ok(())
}

fn probe_ballot() -> Vec<String> {
    LLM_PROBE_BALLOT
        .iter()
        .map(|option| (*option).to_owned())
        .collect()
}

fn library_vocabulary(
    analysis: &surface::Surface,
    parse: &lisdex_surface::extract::ParseOptions,
) -> lisdex_surface::extract::Vocabulary {
    // Mined across every header that declared a candidate, not just the one the candidate
    // lives in: a constructor or destructor in a sibling header is invisible otherwise, and
    // then a heap-produced record reads as a stack context and an allocation goes unpaired.
    let mut merged = lisdex_surface::extract::Vocabulary::default();
    let mut seen = std::collections::BTreeSet::new();
    for candidate in &analysis.ranking.candidates {
        if !seen.insert(candidate.header.clone()) {
            continue;
        }
        match extract::parse_vocabulary(&candidate.header, parse) {
            Ok(vocabulary) => merged.absorb(vocabulary),
            Err(err) => eprintln!(
                "warning: no vocabulary from {}: {err}",
                candidate.header.display()
            ),
        }
    }
    merged
}

#[allow(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss
)]
fn report_tree(
    label: &str,
    evaluation: &eval::Evaluation,
    hits: &mut [usize],
    baseline_hits: &mut [f64],
) {
    println!(
        "  {label:<12} candidates={:<5} labels={:<4} reached ranking={:<4} first={:<5}",
        evaluation.ordered,
        evaluation.labels.len(),
        evaluation.ranked.len(),
        evaluation
            .first_rank
            .map_or_else(|| "none".to_owned(), |rank| rank.to_string()),
    );
    print!(
        "  {:<12}   lisdex  rr={:.3}",
        "", evaluation.reciprocal_rank
    );
    for (index, cutoff) in evaluation.cutoffs.iter().enumerate() {
        let hit = (cutoff.recall * evaluation.labels.len() as f64).round() as usize;
        hits[index] += hit;
        print!("  hits@{}={hit}", cutoff.k);
    }
    println!();
    print!(
        "  {:<12} shuffled  rr={:.3}",
        "", evaluation.baseline_reciprocal_rank
    );
    for (index, cutoff) in evaluation.cutoffs.iter().enumerate() {
        print!("  hits@{}={:.2}", cutoff.k, evaluation.baseline_hits[index]);
        baseline_hits[index] += evaluation.baseline_hits[index];
    }
    println!();
    if !evaluation.dropped.is_empty() {
        let mut dropped: Vec<&str> = evaluation.dropped.iter().map(String::as_str).collect();
        dropped.sort_unstable();
        println!(
            "  {:<12} dropped before ranking: {}",
            "",
            dropped.join(", ")
        );
    }
}

fn rank_eval(args: &RankEvalArgs) -> Result<(), Box<dyn Error>> {
    if args.sources.is_empty() {
        return Err("name at least one source tree to score".into());
    }
    let cutoffs: Vec<usize> = if args.cutoffs.is_empty() {
        eval::DEFAULT_CUTOFFS.to_vec()
    } else {
        args.cutoffs.clone()
    };

    let mut scored = 0usize;
    let mut reciprocal_total = 0.0_f64;
    let mut label_total = 0usize;
    let mut ranked_total = 0usize;
    let mut hits: Vec<usize> = vec![0; cutoffs.len()];
    let mut baseline_hits: Vec<f64> = vec![0.0; cutoffs.len()];
    let mut baseline_total = 0.0_f64;

    for source in &args.sources {
        let mut options = SurfaceOptions::new(source);
        options.includes.clone_from(&args.includes);
        options.defines.clone_from(&args.defines);
        options.language = if args.cpp { Language::Cpp } else { Language::C };
        // Cold start on purpose. With ignore_harnesses the reachability seed set is empty,
        // so the ranking never sees the harnesses the labels are drawn from. Scoring a
        // warm ranking against harness-derived labels would be measuring the ranker
        // against its own input.
        options.ignore_harnesses = true;

        let label = source.file_name().map_or_else(
            || source.display().to_string(),
            |name| name.to_string_lossy().into_owned(),
        );
        let analysis = match analyze_configuring_if_needed(&options) {
            Ok(analysis) => analysis,
            Err(err) => {
                println!("  {label:<12} NOT ANALYSED {err}");
                continue;
            }
        };
        match eval::evaluate(&analysis, &cutoffs) {
            Ok(evaluation) => {
                scored += 1;
                reciprocal_total += evaluation.reciprocal_rank;
                label_total += evaluation.labels.len();
                ranked_total += evaluation.ranked.len();
                baseline_total += evaluation.baseline_reciprocal_rank;
                report_tree(&label, &evaluation, &mut hits, &mut baseline_hits);
            }
            Err(reason) => println!("  {label:<12} NOT SCORED {reason}"),
        }
    }

    if scored == 0 {
        return Err("no tree could be scored, so there is no ranking measurement".into());
    }

    #[allow(clippy::cast_precision_loss)]
    {
        let mrr = reciprocal_total / scored as f64;
        let baseline_mrr = baseline_total / scored as f64;
        println!(
            "\ntrees scored {scored}  labels {label_total}  reached ranking {ranked_total}  \
             selection recall {:.3}",
            ranked_total as f64 / label_total as f64
        );
        let lift = if baseline_mrr > 0.0 && mrr > 0.0 {
            format!("{:.2}x", mrr / baseline_mrr)
        } else {
            "n/a (nothing was found by either ordering)".to_owned()
        };
        println!("  MRR   lisdex {mrr:.3}   shuffled {baseline_mrr:.3}   lift {lift}");
        for (index, k) in cutoffs.iter().enumerate() {
            println!(
                "  hits@{k}  lisdex {} ({:.3} of {label_total})   shuffled {:.2} ({:.3})",
                hits[index],
                hits[index] as f64 / label_total as f64,
                baseline_hits[index],
                baseline_hits[index] / label_total as f64
            );
        }
        println!(
            "\nprecision@k is deliberately NOT reported as a quality number: a project's own\n\
             harness calls its setup and teardown too, so most labels are not entry points.\n\
             The shuffled baseline faces the SAME labels, so the lift is the comparable figure."
        );
    }
    Ok(())
}

// B26. A tree whose PUBLIC headers include a header its build generates cannot be parsed
// on a fresh clone. Compiling it to find out what it declares costs minutes; running only
// the configure step costs seconds, and the tree itself says which headers are generated
// because it ships their templates. So: try the analysis first, and only when it fails
// AND the tree declares a generated header that nothing has produced, configure and retry
// once. A tree that parses on the first attempt pays nothing.
fn analyze_configuring_if_needed(
    options: &SurfaceOptions,
) -> Result<surface::Surface, Box<dyn Error>> {
    let refusal = match surface::analyze(options) {
        Ok(analysis) => return Ok(analysis),
        Err(refusal) => refusal,
    };

    let missing = headers::missing_generated(&options.source, &options.includes);
    if missing.is_empty() {
        return Err(refusal.into());
    }
    let names: Vec<String> = missing
        .iter()
        .filter_map(|path| path.file_name())
        .map(|name| name.to_string_lossy().into_owned())
        .collect();
    eprintln!(
        "this tree generates {} at build time; running its configure step only",
        names.join(", ")
    );

    let detected = detect::detect(&options.source)?;
    let work = lisdex_core::scratch::unclaimed_path(CONFIGURE_SCRATCH);
    let layout = BuildLayout::validated(&detected.root, &work)?;
    let instrumentation = Instrumentation::uninstrumented();
    let build_options = ladder::BuildOptions::new(
        CONFIGURE_VARIANT,
        std::thread::available_parallelism().map_or(1, std::num::NonZero::get),
    );
    let configured =
        match ladder::configure_only(&detected, &layout, &instrumentation, &build_options) {
            Ok(configured) => configured,
            Err(err) => {
                eprintln!("configure did not run: {err}");
                return Err(refusal.into());
            }
        };

    let mut retry = options.clone();
    retry
        .includes
        .extend(generated_include_dirs(&configured.build_dir, &names));
    match surface::analyze(&retry) {
        Ok(analysis) => {
            eprintln!(
                "configured with {} and re-read the headers",
                configured.system.as_str()
            );
            Ok(analysis)
        }
        // The ORIGINAL refusal, not the retry's. It is the one that names the remedy, and
        // reporting a second failure against a build directory the user never asked for
        // would point them at a path that is about to be deleted.
        Err(_) => Err(refusal.into()),
    }
}

// cmake writes a generated header beside the source directory that declared it, so the
// build tree mirrors the source tree and the header can sit several levels down.
fn generated_include_dirs(build_dir: &Path, names: &[String]) -> Vec<PathBuf> {
    let mut found = vec![build_dir.to_path_buf()];
    let mut stack = vec![build_dir.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if path
                .file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| names.iter().any(|wanted| wanted == name))
                && let Some(parent) = path.parent()
            {
                found.push(parent.to_path_buf());
            }
        }
    }
    found.sort();
    found.dedup();
    found
}

fn parse_arm(spec: &str) -> Result<(String, PathBuf), Box<dyn Error>> {
    let (name, path) = spec
        .split_once('=')
        .ok_or_else(|| format!("--arm wants name=path, got {spec:?}"))?;
    if name.trim().is_empty() || path.trim().is_empty() {
        return Err(format!("--arm {spec:?} has an empty name or path").into());
    }
    Ok((name.to_owned(), PathBuf::from(path)))
}

fn run_bench(args: &BenchArgs) -> Result<(), Box<dyn Error>> {
    if args.arms.len() != BENCH_ARMS {
        return Err(format!(
            "a comparison needs exactly {BENCH_ARMS} arms, got {}; one arm is a measurement, not a comparison",
            args.arms.len()
        )
        .into());
    }
    let metric = bench::Metric::from(args.metric);
    let mut targets = Vec::new();
    for spec in &args.arms {
        let (name, target) = parse_arm(spec)?;
        if !target.is_file() {
            return Err(format!("arm {name}: {} is not a file", target.display()).into());
        }
        targets.push((name, target));
    }
    let mut arms: Vec<bench::Arm> = targets
        .iter()
        .map(|(name, _)| bench::Arm::new(name))
        .collect();

    // A bench is many campaigns back to back, so it is the run most likely to be interrupted.
    // Arming here keeps the trial that was in flight from being killed mid-write.
    let interrupt = Interrupt::arm()?;

    // Interleaved on purpose. Running every trial of one arm and then every trial of the
    // other lets any drift in machine state - page cache, thermal, a neighbour's load -
    // land entirely on the second arm and be read as an effect of the build. Measured on
    // 3-second trials with BOTH arms pointing at the same binary: sequential execution
    // reported a12=0.6987 and "significant", which is a false positive against a build
    // compared with itself.
    for trial in 0..args.trials {
        for (index, (name, target)) in targets.iter().enumerate() {
            let findings = args.work.join(name).join(format!("trial-{trial:03}"));
            let _ = std::fs::remove_dir_all(&findings);
            std::fs::create_dir_all(&findings)?;
            let options = AflOptions {
                target: target.clone(),
                cmplog: None,
                seeds: args.seeds.clone(),
                findings: findings.clone(),
                duration: Some(Duration::from_secs(args.duration)),
                bench_until_crash: args.until_crash,
                skip_deterministic: true,
                dictionaries: Vec::new(),
                instance: None,
                resume: false,
            };
            let outcome = runner::run(&options, &interrupt)?;
            let curve = runner::read_curve(&findings).ok();
            arms[index].trials.push(bench::Trial {
                edges: outcome.stats.edges_found,
                crashes: outcome.stats.saved_crashes,
                time_to_first_crash: curve
                    .as_ref()
                    .and_then(plot::CoverageCurve::time_to_first_crash),
            });
            println!(
                "  {name} trial {}/{}: edges {} crashes {}",
                trial + 1,
                args.trials,
                outcome.stats.edges_found,
                outcome.stats.saved_crashes
            );
        }
    }

    let report = bench::compare(metric, arms);
    print!("{}", report.render());
    if !report.has_verdict() {
        return Err(
            "no comparative claim is available from this run; see the NO VERDICT line above".into(),
        );
    }
    Ok(())
}

fn library_symbols(
    libraries: &[PathBuf],
) -> Result<Option<std::collections::BTreeSet<String>>, Box<dyn Error>> {
    if libraries.is_empty() {
        return Ok(None);
    }
    let mut symbols = std::collections::BTreeSet::new();
    for library in libraries {
        symbols.extend(verify::defined_functions(library)?);
    }
    Ok(Some(symbols))
}

fn harness(args: &HarnessArgs) -> Result<(), Box<dyn Error>> {
    let mut options = SurfaceOptions::new(&args.source);
    options.install.clone_from(&args.install);
    options.includes.clone_from(&args.includes);
    options.defines.clone_from(&args.defines);
    options.language = if args.cpp { Language::Cpp } else { Language::C };
    options.ignore_harnesses = true;
    options.oss_fuzz.clone_from(&args.oss_fuzz);
    options.library_symbols = library_symbols(&args.libraries)?;

    let analysis = analyze_configuring_if_needed(&options)?;
    report_ladder(&analysis.ladder);
    let root = std::fs::canonicalize(&analysis.header_root)
        .unwrap_or_else(|_| analysis.header_root.clone());
    let parse = options.parse_options(&root, &analysis.headers);

    let vocabulary = library_vocabulary(&analysis, &parse);

    if args.plan_only {
        plan_only(&analysis, &root, &vocabulary, args.top);
        return Ok(());
    }

    let sequence = authored_sequence(&analysis);
    let sequences = authored_sequences(&analysis);
    let ranked = ladder_ordered(&analysis);
    let attempts: Vec<search::Attempt> = ranked
        .into_iter()
        .take(args.top)
        .map(|candidate| {
            let include = include_of(candidate, &root);
            match synth::plan_candidate_with(candidate, &include, &vocabulary, sequence) {
                Ok(variants) => search::Attempt::Planned {
                    name: candidate.name.clone(),
                    variants,
                    steps: synth::upward_steps(candidate, &vocabulary, &sequences),
                },
                Err(refusal) => search::Attempt::Refused {
                    name: candidate.name.clone(),
                    refusal,
                },
            }
        })
        .collect();

    // Created before either branch: `--no-verify` writes the promoted harness straight into it
    // and used to depend on the candidates directory being made first for it to exist at all.
    std::fs::create_dir_all(&args.out)?;

    if args.no_verify {
        println!("{UNVERIFIED_BANNER}");
        return unverified(&attempts, &args.out);
    }
    let bench = args
        .oracle
        .bench(parse.includes.clone(), parse.defines.clone(), &args.out)?;

    let candidates = args.out.join(CANDIDATES_DIR);
    // Stale variants from an earlier run are indistinguishable from this run's evidence.
    let _ = std::fs::remove_dir_all(&candidates);
    std::fs::create_dir_all(&candidates)?;

    let outcome = search::accumulate(&attempts, &bench, &candidates)?;
    for survivor in &outcome.survivors {
        promote(
            &survivor.plan,
            &survivor.name,
            &args.out,
            survivor.variants,
            Some(&survivor.verdict),
            survivor.judged_against,
            survivor.steps,
        )?;
    }
    report_rejections(&outcome.rejected);
    if outcome.survivors.is_empty() {
        println!("no candidate in the top {} survived the oracles:", args.top);
        return Err("no harness synthesized".into());
    }
    report_survivors(
        &outcome.survivors,
        outcome.accepted.len(),
        comparable_numbering(&args.oracle.archives),
    );
    Ok(())
}

// B80. Every number in the survivor summary that spans MORE THAN ONE harness - the novelty
// figure and the union total - rests on two separately linked binaries numbering the same edge
// the same way. That is the SAME question the bench asks when it picks a link scheme, so it is
// asked once and answered in one place: the scheme the bench could build under IS whether the
// resulting maps can be compared. Answering it twice is how the two drift apart.
//
// Note what this is not: it is not the absence of bitcode. An uninstrumented archive is not
// bitcode either, and against one every edge in the map belongs to the harness and moves with
// it. Renumbering can only INFLATE apparent novelty, so a rejection still stands - a harness
// that looks redundant even with scrambled IDs really is - but no cross-harness TOTAL may be
// printed as if it were measured.
fn comparable_numbering(archives: &[std::path::PathBuf]) -> bool {
    lisdex_harness::verify::link_scheme(archives) == lisdex_harness::compile::LinkScheme::PcGuard
}

// `--no-verify` promotes the first candidate that plans and stops. It cannot climb: an
// extension only earns its place against a parent that PASSED, and with no bench nothing has
// passed. Saying so is the whole content of the banner above.
fn unverified(attempts: &[search::Attempt], out: &std::path::Path) -> Result<(), Box<dyn Error>> {
    for attempt in attempts {
        if let search::Attempt::Planned {
            name,
            variants,
            steps: _,
        } = attempt
            && let Some(plan) = variants.first()
        {
            return promote(plan, name, out, variants.len(), None, 0, 0);
        }
    }
    Err("no harness synthesized".into())
}

fn report_survivors(survivors: &[search::Survivor], total: usize, comparable: bool) {
    let reach = if comparable {
        format!(", covering {total} edges in total")
    } else {
        String::new()
    };
    println!(
        "\n{} harness(es) survived the oracles{reach}:",
        survivors.len()
    );
    for survivor in survivors {
        let novelty = if survivor.judged_against == 0 {
            "first accepted, nothing to be novel against".to_owned()
        } else if comparable {
            format!(
                "{} edge(s) novel against the {} already accepted",
                survivor.novel, survivor.judged_against
            )
        } else {
            format!(
                "novelty against the {} already accepted NOT MEASURED - the target archive is \
                 LTO bitcode, so it is re-instrumented at every link and two harnesses do not \
                 number the same edge the same way; build the oracle bench against an archive \
                 whose instrumentation was fixed when the LIBRARY was built",
                survivor.judged_against
            )
        };
        let climbed = if survivor.steps == 0 {
            String::new()
        } else {
            format!(
                ", extended by {} author call(s): {}",
                survivor.steps,
                survivor.plan.extended.join(", ")
            )
        };
        println!(
            "  {} - {} edges, {novelty}{climbed}",
            survivor.name, survivor.edges
        );
    }
}

// The ladder RESCORES nothing. It reorders, and inside each group the surface's own rank
// order is untouched.
//
// Two rules, and the second one is the point. First, a candidate is hoisted only if the
// authors both CALL it and feed it the corpus: every one of libarchive's 25 fuzz targets
// calls `archive_read_support_format_rar5`, and hoisting on mention alone put seven such
// configurators above `archive_read_open_memory`.
//
// Second, those data-entry calls set a FLOOR. Nothing ranked below the authors' own
// entry points may substitute for them. That is the fall-through B46 named, still live:
// with every real lz4 decoder refused for an unrelated reason, the loop kept walking down
// the ranking and emitted `LZ4_loadDictHC` - the COMPRESSOR's dictionary loader - and
// brotli likewise emitted `BrotliDecoderAttachDictionary`. Once the library's authors have
// shown which call takes the bytes, a lower-ranked function that merely accepts a buffer is
// not an answer to the same question. Candidates ABOVE the floor stay eligible, so the
// unfuzzed frontier this whole tool is aimed at is untouched.
fn ladder_ordered(analysis: &surface::Surface) -> Vec<&lisdex_surface::rank::Candidate> {
    let ranked = &analysis.ranking.candidates;
    let authored = |candidate: &lisdex_surface::rank::Candidate| {
        analysis.ladder.contains(&candidate.name) && !synth::is_configurator(candidate)
    };
    let floor = ranked.iter().rposition(&authored);
    let eligible = floor.map_or(ranked.len(), |index| index + 1);
    let (entries, rest): (Vec<_>, Vec<_>) = ranked
        .iter()
        .take(eligible)
        .partition(|candidate| authored(candidate));
    entries.into_iter().chain(rest).collect()
}

fn authored_sequence(analysis: &surface::Surface) -> &[String] {
    analysis
        .ladder
        .chosen
        .as_ref()
        .map_or(&[][..], |sequence| sequence.names())
}

// B83. The setup replay works from the ONE sequence the ladder chose, because a harness is
// assembled in the shape of a single author's target. The tail is a different question - "did
// the authors ever call this, and what did they do next" - and answering it from the winner
// alone made `archive_read_open_memory` read as uncalled while `libarchive_roundtrip_fuzzer.cc`
// calls it directly. The chosen sequence stays FIRST so a candidate that already has a tail
// keeps exactly the one it had.
fn authored_sequences(analysis: &surface::Surface) -> Vec<&[String]> {
    let mut sequences = vec![authored_sequence(analysis)];
    sequences.extend(
        analysis
            .harnesses
            .iter()
            .map(|harness| harness.calls.as_slice()),
    );
    sequences
}

fn report_ladder(ladder: &lisdex_surface::ladder::Ladder) {
    match &ladder.chosen {
        Some(sequence) => println!(
            "call order: {} from {} ({} call(s), {} in-tree fuzz target(s), {} consumer(s))",
            sequence.tier.describe(),
            sequence.origin.display(),
            sequence.calls.len(),
            ladder.fuzz_targets,
            ladder.consumers
        ),
        None => println!(
            "call order: none - this tree ships no fuzz target and no consumer program, so \
             ranking alone decides what to synthesize"
        ),
    }
}

fn include_of(candidate: &lisdex_surface::rank::Candidate, root: &std::path::Path) -> String {
    candidate
        .header
        .strip_prefix(root)
        .unwrap_or(&candidate.header)
        .display()
        .to_string()
}

// The synthesizer returns on the FIRST candidate that plans, so the only way to see why the
// ones above it were refused was to bisect --top by hand. A fix cannot be sized against a
// decision nobody can read.
fn plan_only(
    analysis: &surface::Surface,
    root: &std::path::Path,
    vocabulary: &lisdex_surface::extract::Vocabulary,
    top: usize,
) {
    let sequence = authored_sequence(analysis);
    let sequences = authored_sequences(analysis);
    for (index, candidate) in ladder_ordered(analysis).into_iter().take(top).enumerate() {
        let include = include_of(candidate, root);
        let order = index + 1;
        let authored = if analysis.ladder.contains(&candidate.name) {
            "authored"
        } else {
            "        "
        };
        match synth::plan_candidate_with(candidate, &include, vocabulary, sequence) {
            Ok(plans) => {
                println!(
                    "{order:>3}. {authored} PLANS   {} ({} variant(s)), replaying {:?}",
                    candidate.name,
                    plans.len(),
                    plans.first().map_or(&[][..], |plan| &plan.replayed)
                );
                // On its own line, because the replay line is what the M3 gate asserts a
                // teardown never appears in, and a tail that legitimately contains one would
                // have turned that assertion red from the other side of the entry point.
                let steps = synth::upward_steps(candidate, vocabulary, &sequences);
                if !steps.is_empty() {
                    println!("                 extending {:?}", step_names(&steps));
                }
            }
            Err(refusal) => println!(
                "{order:>3}. {authored} refused {} - {refusal}",
                candidate.name
            ),
        }
    }
}

fn step_names(steps: &[lisdex_harness::synth::Extension]) -> Vec<&str> {
    steps.iter().map(|step| step.function.as_str()).collect()
}

fn report_rejections(rejected: &[String]) {
    // Printed on SUCCESS too: a libarchive user handed a date parser needs to see that the
    // archive readers above it were refused, not just the winner.
    if rejected.is_empty() {
        return;
    }
    println!("{} candidate(s) did not survive:", rejected.len());
    for line in rejected {
        println!("{line}");
    }
}

fn promote(
    plan: &lisdex_harness::plan::HarnessPlan,
    name: &str,
    out: &std::path::Path,
    variants: usize,
    verdict: Option<&Verdict>,
    judged_against: usize,
    steps: usize,
) -> Result<(), Box<dyn Error>> {
    // Rendered again rather than copied so the file header names the file it is in.
    let filename = format!("{name}.c");
    let path = out.join(&filename);
    std::fs::write(&path, emit::render(plan, &filename))?;
    println!(
        "synthesized {filename} for {name} ({variants} variant(s) planned) -> {}",
        path.display()
    );
    match verdict {
        Some(verdict) => {
            let reached = verdict.outcome.as_ref().map_or(0, EdgeSet::len);
            let observation = verdict.observation.as_ref();
            let invalid = observation.map_or(0, |o| o.invalid.len());
            println!(
                "accepted: {} edges over {} valid and {invalid} invalid seed(s), binary {}",
                reached,
                observation.map_or(0, |o| o.valid.len()),
                verdict.binary.display()
            );
            // Naming the oracles that actually ran, because saying "all four" was a lie
            // while two of D4's four could not discriminate. Oracle 4 discriminates from
            // the SECOND acceptance onward and oracle 3b only from the first upward step,
            // so what they did is a property of THIS verdict rather than of the build, and
            // both are reported per harness.
            println!(
                "oracles run: {}",
                oracles_run(invalid > 0, judged_against > 0, steps > 0)
            );
        }
        None => println!("{UNVERIFIED_BANNER}"),
    }
    Ok(())
}

fn oracles_run(differential: bool, novelty_discriminated: bool, climbed: bool) -> String {
    let mut ran = vec!["1 compilation", "2 execution", "3a inter-seed divergence"];
    if climbed {
        ran.push("3b non-linear delta");
    }
    if differential {
        ran.push("3c valid-vs-invalid differential");
    }
    if novelty_discriminated {
        ran.push("4 global novelty");
    }
    let mut line = ran.join(", ");
    if !differential {
        line.push_str("; 3c SKIPPED, no --invalid-seeds given");
    }
    if !novelty_discriminated {
        line.push_str(
            "; 4 global novelty could only reject a harness reaching nothing - this is the \
             first acceptance, so there was no accepted set to be novel against",
        );
    }
    if !climbed {
        line.push_str(
            "; 3b non-linear delta needs a call-sequence parent, which a single-call harness \
             does not have",
        );
    }
    line
}

fn verify(args: &VerifyArgs) -> Result<(), Box<dyn Error>> {
    let parent = args
        .source
        .parent()
        .map_or_else(|| PathBuf::from("."), std::path::Path::to_path_buf);
    let bench = args
        .oracle
        .bench(args.includes.clone(), args.defines.clone(), &parent)?;
    let label = args.source.file_stem().map_or_else(
        || UNKNOWN_TARGET.to_owned(),
        |stem| stem.to_string_lossy().into_owned(),
    );

    let verdict = bench.verify(&args.source, &label, None, &EdgeSet::new())?;
    match &verdict.outcome {
        Ok(reached) => {
            println!(
                "ACCEPTED {} - {} edges over {} valid and {} invalid seed(s)",
                args.source.display(),
                reached.len(),
                bench.corpus.valid.len(),
                bench.corpus.invalid.len()
            );
            Ok(())
        }
        Err(rejection) => {
            println!("REJECTED {} - {rejection}", args.source.display());
            Err("the harness did not survive the oracles".into())
        }
    }
}

fn surface(args: &SurfaceArgs) -> Result<(), Box<dyn Error>> {
    let mut options = SurfaceOptions::new(&args.source);
    options.install.clone_from(&args.install);
    options.includes.clone_from(&args.includes);
    options.defines.clone_from(&args.defines);
    options.language = if args.cpp { Language::Cpp } else { Language::C };
    options.ignore_harnesses = !args.frontier;
    options.oss_fuzz.clone_from(&args.oss_fuzz);
    options.library_symbols = library_symbols(&args.libraries)?;

    let analysis = analyze_configuring_if_needed(&options)?;

    if args.json {
        println!("{}", serde_json::to_string_pretty(&analysis)?);
        return Ok(());
    }

    println!(
        "surface: {} headers ({:?}), {} declared, {} defined, {} in-tree harnesses, mode {}",
        analysis.headers_read,
        analysis.origin,
        analysis.declared,
        analysis.defined,
        analysis.harnesses.len(),
        if args.frontier {
            "frontier"
        } else {
            "canonical"
        }
    );
    report_ladder(&analysis.ladder);
    if !analysis.skipped_sources.is_empty() {
        println!(
            "{} source file(s) did not parse; the call graph behind 55% of the score is \
             incomplete by that much:",
            analysis.skipped_sources.len()
        );
        for skipped in analysis.skipped_sources.iter().take(MAX_SKIPPED_SHOWN) {
            println!("  {} - {}", skipped.header.display(), skipped.reason);
        }
    }
    if !analysis.skipped.is_empty() {
        println!(
            "{} header(s) refused because they do not type check:",
            analysis.skipped.len()
        );
        for skipped in analysis.skipped.iter().take(MAX_SKIPPED_SHOWN) {
            println!("  {} - {}", skipped.header.display(), skipped.reason);
        }
    }

    println!("\nranked entry points:");
    for (position, candidate) in analysis
        .ranking
        .candidates
        .iter()
        .take(args.top)
        .enumerate()
    {
        println!(
            "{:>3}. {:<44} {:.4}  {:?}  undiscovered={} accumulated={}{}",
            position + 1,
            candidate.name,
            candidate.score,
            candidate.fuzzability,
            candidate.complexity.undiscovered,
            candidate.complexity.accumulated,
            if candidate.reachable_from_harness {
                "  [harnessed]"
            } else {
                ""
            }
        );
        if args.explain {
            for reason in &candidate.reasons {
                println!("       {reason}");
            }
        }
    }

    println!(
        "\n{} candidates, {} excluded",
        analysis.ranking.candidates.len(),
        analysis.ranking.excluded.len()
    );
    Ok(())
}

fn build(args: &BuildArgs) -> Result<(), Box<dyn Error>> {
    let source = Source::parse(&args.target).at(args.reference.clone());
    let label = args.label.clone().unwrap_or_else(|| source.label());

    let root = if let (Source::Local(path), true) = (&source, args.in_place) {
        path.clone()
    } else {
        let dest = args.work.join(SOURCES_DIR).join(&label);
        let acquired = acquire::acquire(&source, &dest, args.reuse)?;
        println!(
            "acquired {label} at {}{}",
            acquired.root.display(),
            acquired
                .revision
                .map(|rev| format!(" ({rev})"))
                .unwrap_or_default()
        );
        acquired.root
    };

    let detected = detect::detect(&root)?;
    println!(
        "detected {} candidate build system(s): {}",
        detected.candidates.len(),
        detected
            .candidates
            .iter()
            .map(|system| system.as_str())
            .collect::<Vec<&str>>()
            .join(", ")
    );

    let sanitizers = SanitizerSet::from(args.sanitizer);
    let instrumentation = Instrumentation::instrumented()
        .with_sanitizers(sanitizers)
        .with_cmplog(args.cmplog)
        .with_extra_cflags(args.cflags.clone());

    let layout = BuildLayout::validated(&detected.root, args.work.join(BUILDS_DIR).join(&label))?;
    let requirements = Requirements::for_sanitizers(sanitizers)
        .with_cmplog(args.cmplog)
        .with_magma_canaries(args.require_canaries);
    let options = BuildOptions::new(
        &args.variant,
        args.jobs.unwrap_or_else(|| {
            std::thread::available_parallelism().map_or(1, std::num::NonZero::get)
        }),
    )
    .with_requirements(requirements);

    let outcome = ladder::build(&detected, &layout, &instrumentation, &options)?;

    for system in &outcome.unplanned {
        eprintln!(
            "note: {} detected; lisdex plans no {} build",
            system.as_str(),
            system.as_str()
        );
    }

    for line in &outcome.degradation {
        eprintln!("degraded: {line}");
    }

    if !outcome.succeeded() {
        return Err(format!(
            "no instrumented build of {label} was produced; {} attempt(s) failed",
            outcome.attempts.len()
        )
        .into());
    }

    let system = outcome.system.map_or("unknown", |system| system.as_str());
    let tier = outcome.tier.map_or("unknown", ladder::Tier::as_str);
    println!("built {label} with {system} via {tier}");
    let coverage = if outcome.counts.afl == 0 && outcome.lto_bitcode {
        "deferred-to-link(lto-bitcode)".to_owned()
    } else {
        outcome.counts.afl.to_string()
    };
    println!(
        "artifacts {} asan {} ubsan {} coverage {coverage} cmplog {} canaries {}",
        outcome.artifacts.len(),
        outcome.counts.asan,
        outcome.counts.ubsan,
        outcome.counts.cmplog,
        outcome.counts.magma
    );
    for artifact in &outcome.artifacts {
        println!("  {} {}", artifact.kind.as_str(), artifact.path.display());
    }

    if !args.no_oracle_bench {
        oracle_bench(&detected, &layout, args, &options);
    }

    Ok(())
}

// B80. The fuzzing archive is LTO, and an LTO archive is re-instrumented at every link - so two
// harnesses built against it do not number the same edge the same way and no coverage figure
// spanning both can be published. This second pass builds the SAME library with PCGUARD, whose
// guards are baked into the objects, and it is the archive `lisdex harness --archive` should be
// pointed at. It is not the fuzzing target: PCGUARD is the slower instrumentation, which is why
// both exist rather than one replacing the other.
//
// A failure here is degradation, never an error. The fuzzing artifact is already built and
// valid at this point, and a tree that will not build twice still fuzzes perfectly well - it
// only loses the cross-harness numbers, which is exactly the state that ships today.
fn oracle_bench(
    detected: &lisdex_ingest::detect::Detection,
    layout: &BuildLayout,
    args: &BuildArgs,
    options: &BuildOptions,
) {
    let instrumentation = Instrumentation::oracle_bench().with_extra_cflags(args.cflags.clone());
    let options = BuildOptions::new(VARIANT_BENCH, options.jobs)
        .with_requirements(Requirements::library().with_magma_canaries(args.require_canaries));
    let outcome = match ladder::build(detected, layout, &instrumentation, &options) {
        Ok(outcome) => outcome,
        Err(error) => {
            eprintln!("degraded: no oracle-bench archive: {error}");
            return;
        }
    };
    if !outcome.succeeded() {
        eprintln!(
            "degraded: no oracle-bench archive; {} attempt(s) failed, so cross-harness \
             coverage numbers stay unpublishable",
            outcome.attempts.len()
        );
        return;
    }
    // Reported by the property rather than by the variant name, because "the bench pass ran"
    // and "the bench pass produced something the oracles can compare" are different claims and
    // only the second one is worth printing. A shared library is not an archive `--archive`
    // takes, and an archive with no guard sections of its own is the state this pass exists to
    // avoid - so both are counted out here rather than discovered later by the guard.
    let comparable: Vec<&artifact::Artifact> = outcome
        .artifacts
        .iter()
        .filter(|found| found.kind == artifact::ArtifactKind::StaticLib)
        .filter(|found| lisdex_harness::coverage::is_pcguard_archive(&found.path))
        .collect();
    if comparable.is_empty() {
        eprintln!(
            "degraded: the oracle-bench pass built, but no archive it produced carries a \
             numbering of its own, so cross-harness coverage numbers stay unpublishable"
        );
        return;
    }
    println!(
        "oracle bench: {} archive(s) with a numbering fixed at library-build time",
        comparable.len()
    );
    for library in &comparable {
        println!("  {} {}", library.kind.as_str(), library.path.display());
    }
}

fn campaign_tree(target: &Path) -> TreeProvenance {
    let tree = match verify::inspect(target) {
        Ok(counts) if counts.magma > 0 => TreeProvenance::Benchmark,
        Ok(_) => TreeProvenance::Field,
        Err(_) => TreeProvenance::Unknown,
    };
    match tree {
        TreeProvenance::Benchmark => eprintln!("{BENCHMARK_TREE_WARNING}"),
        TreeProvenance::Unknown => eprintln!("{UNKNOWN_TREE_WARNING}"),
        TreeProvenance::Field => {}
    }
    tree
}

// B5's recovery half. A campaign that was killed outright - by a signal lisdex could not catch,
// an OOM, a lost session - leaves its crash files on disk with nothing able to read them back.
// This runs the SAME `runner::harvest` and the same insert loop the live campaign runs, so an
// imported crash is indistinguishable from one harvested in place rather than a second,
// weaker ingestion path that could disagree with it.
fn import(args: &ImportArgs) -> Result<(), Box<dyn Error>> {
    if !args.findings.is_dir() {
        return Err(format!(
            "no findings directory at {}; import reads what a campaign already wrote",
            args.findings.display()
        )
        .into());
    }

    let label = args.label.clone().unwrap_or_else(|| {
        args.target
            .file_name()
            .map_or(UNKNOWN_TARGET.to_owned(), |name| {
                name.to_string_lossy().into_owned()
            })
    });

    if let Some(parent) = args
        .db
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        std::fs::create_dir_all(parent)?;
    }
    let store = Store::open(&args.db)?;
    let mut campaign = Campaign::new(label.clone(), campaign_tree(&args.target));
    let campaign_id = store.insert_campaign(&campaign)?;
    for status in [CampaignStatus::Building, CampaignStatus::Fuzzing] {
        campaign.advance(status)?;
        store.update_campaign_status(campaign_id, status)?;
    }

    println!("campaign {} target {label}", campaign_id.0);
    println!("importing from     {}", args.findings.display());

    let (harvested, problems) = match runner::harvest(campaign_id, &args.target, &args.findings) {
        Ok(result) => result,
        Err(err) => {
            fail_campaign(&store, &mut campaign, campaign_id);
            return Err(err.into());
        }
    };

    let mut persisted = 0usize;
    let mut store_problems = Vec::new();
    for crash in &harvested {
        match store.insert_crash(crash) {
            Ok(_) => persisted += 1,
            Err(err) => store_problems.push(format!("crash not persisted: {err}")),
        }
    }

    println!("crashes_persisted  {persisted}");
    print_triaged_crashes(&harvested);

    for problem in problems.iter().chain(store_problems.iter()) {
        eprintln!("warning: {problem}");
    }

    if !store_problems.is_empty() {
        fail_campaign(&store, &mut campaign, campaign_id);
        return Err(format!("campaign {} marked failed", campaign_id.0).into());
    }

    // An import that found nothing is not an error - an empty findings directory is a legitimate
    // answer - but it must not be reported as a recovery either.
    if harvested.is_empty() {
        eprintln!(
            "warning: no crash inputs under {}; nothing was imported",
            args.findings.display()
        );
    }

    campaign.advance(CampaignStatus::Completed)?;
    store.update_campaign_status(campaign_id, CampaignStatus::Completed)?;
    Ok(())
}

fn fuzz(args: &FuzzArgs) -> Result<(), Box<dyn Error>> {
    let label = args.label.clone().unwrap_or_else(|| {
        args.target
            .file_name()
            .map_or(UNKNOWN_TARGET.to_owned(), |name| {
                name.to_string_lossy().into_owned()
            })
    });

    if let Some(parent) = args
        .db
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        std::fs::create_dir_all(parent)?;
    }
    let store = Store::open(&args.db)?;
    let mut campaign = Campaign::new(label.clone(), campaign_tree(&args.target));
    let campaign_id = store.insert_campaign(&campaign)?;

    for status in [CampaignStatus::Building, CampaignStatus::Fuzzing] {
        campaign.advance(status)?;
        store.update_campaign_status(campaign_id, status)?;
    }

    let dictionaries = campaign_dictionaries(args);

    let options = afl_options(args, dictionaries);

    println!("campaign {} target {label}", campaign_id.0);
    for instance in runner::instance_plan(args.jobs) {
        println!("instance           {}", instance.name());
    }
    println!("running {}", runner::AFL_FUZZ_BIN);

    // Armed before the first child exists, so no window remains where the default disposition
    // still applies and an early Ctrl-C kills lisdex with crashes already on disk.
    let interrupt = Interrupt::arm()?;

    let outcome = match runner::run_parallel(&options, args.jobs, &interrupt) {
        Ok(outcome) => outcome,
        Err(err) => {
            fail_campaign(&store, &mut campaign, campaign_id);
            return Err(err.into());
        }
    };

    let (harvested, problems) =
        match runner::harvest(campaign_id, &options.target, &options.findings) {
            Ok(result) => result,
            Err(err) => {
                fail_campaign(&store, &mut campaign, campaign_id);
                return Err(err.into());
            }
        };

    let mut persisted = 0usize;
    let mut store_problems = Vec::new();
    for crash in &harvested {
        match store.insert_crash(crash) {
            Ok(_) => persisted += 1,
            Err(err) => store_problems.push(format!("crash not persisted: {err}")),
        }
    }

    let persistent = check_persistent_mode(&options.findings, &args.target);

    let stats = &outcome.stats;
    println!("afl_version        {}", stats.afl_version);
    println!("persistent_mode    {persistent}");
    println!("clean_exit         {}", outcome.clean_exit);
    println!("interrupted        {}", outcome.interrupted);
    println!("execs_done         {}", stats.execs_done);
    println!("execs_per_sec      {:.2}", stats.execs_per_sec);
    println!(
        "edges              {} / {} ({:.2}%)",
        stats.edges_found, stats.total_edges, stats.bitmap_coverage_pct
    );
    println!("crashes_saved      {}", stats.saved_crashes);
    println!("crashes_persisted  {persisted}");

    print_coverage_curve(&options.findings);
    print_triaged_crashes(&harvested);

    for problem in problems.iter().chain(store_problems.iter()) {
        eprintln!("warning: {problem}");
    }

    if stats.saved_crashes > 0 && harvested.is_empty() {
        eprintln!(
            "warning: {} saved by {} but none harvested; check the instance layout under {}",
            stats.saved_crashes,
            runner::AFL_FUZZ_BIN,
            options.findings.display()
        );
    }

    // An interrupted campaign exits uncleanly BY CONSTRUCTION - afl-fuzz was asked to stop - so
    // the unclean exit only condemns the campaign when nobody asked for it. Everything above
    // this point already ran, which is the whole of B5: the crashes are harvested and persisted
    // before the exit status is judged.
    if (!outcome.clean_exit && !outcome.interrupted) || !store_problems.is_empty() {
        fail_campaign(&store, &mut campaign, campaign_id);
        return Err(format!(
            "{} exited uncleanly or crashes were lost; campaign {} marked failed",
            runner::AFL_FUZZ_BIN,
            campaign_id.0
        )
        .into());
    }
    if outcome.interrupted {
        eprintln!(
            "interrupted: {persisted} crash(es) were harvested before stopping, campaign {}",
            campaign_id.0
        );
    }

    campaign.advance(CampaignStatus::Completed)?;
    store.update_campaign_status(campaign_id, CampaignStatus::Completed)?;

    Ok(())
}

fn crash_line(crash: &Crash) -> String {
    let report = SanitizerReport::parse(crash.sanitizer_report());
    let classification = classify(crash.sanitizer_report());
    format!(
        "{}{} {} bytes {} {}",
        classification
            .as_ref()
            .map_or(UNCLASSIFIED_SEVERITY, |c| c.severity().as_str()),
        classification
            .as_ref()
            .map_or("", |c| if c.is_security_relevant() {
                ""
            } else {
                NON_SECURITY_MARKER
            }),
        crash.input().len(),
        classification.as_ref().map_or_else(
            || report.as_ref().map_or(UNPARSED_KIND, |r| r.kind()),
            |c| c.class()
        ),
        report
            .as_ref()
            .and_then(SanitizerReport::crash_site)
            .unwrap_or_default()
    )
}

fn afl_options(args: &FuzzArgs, dictionaries: Vec<PathBuf>) -> AflOptions {
    AflOptions {
        target: args.target.clone(),
        cmplog: args.cmplog.clone(),
        seeds: args.seeds.clone(),
        findings: args.findings.clone(),
        duration: args.duration.map(Duration::from_secs),
        bench_until_crash: args.until_crash,
        skip_deterministic: args.skip_deterministic,
        dictionaries,
        instance: None,
        resume: args.resume,
    }
}

fn campaign_dictionaries(args: &FuzzArgs) -> Vec<PathBuf> {
    if !args.dict.is_empty() {
        let chosen: Vec<PathBuf> = args
            .dict
            .iter()
            .take(dictionary::MAX_DICTIONARIES)
            .cloned()
            .collect();
        if args.dict.len() > chosen.len() {
            eprintln!(
                "warning: {} dictionaries given but {} accepts at most {}; the rest are dropped",
                args.dict.len(),
                runner::AFL_FUZZ_BIN,
                dictionary::MAX_DICTIONARIES
            );
        }
        for path in &chosen {
            println!("dictionary         {}", path.display());
        }
        return chosen;
    }

    let dir = args
        .dict_dir
        .clone()
        .unwrap_or_else(|| PathBuf::from(dictionary::DEFAULT_DICTIONARY_DIR));
    let selection = match dictionary::select(&args.seeds, &dir) {
        Ok(selection) => selection,
        Err(err) => {
            eprintln!("warning: no dictionary selected: {err}");
            return Vec::new();
        }
    };
    if selection.is_empty() {
        println!(
            "dictionary         none ({} of {} seeds recognised)",
            selection.seeds_recognised(),
            selection.seeds_read()
        );
        return Vec::new();
    }
    let names: Vec<&str> = selection
        .formats()
        .iter()
        .map(|format| format.as_str())
        .collect();
    println!(
        "dictionary         {} ({} of {} seeds recognised)",
        names.join(", "),
        selection.seeds_recognised(),
        selection.seeds_read()
    );
    if selection.formats_over_cap() > 0 {
        eprintln!(
            "warning: {} further format(s) in this corpus have dictionaries that did not fit under the {}-file limit",
            selection.formats_over_cap(),
            dictionary::MAX_DICTIONARIES
        );
    }
    selection.dictionaries().to_vec()
}

fn finish_stream(err: &std::io::Error) -> Result<(), Box<dyn Error>> {
    if err.kind() == std::io::ErrorKind::BrokenPipe {
        return Ok(());
    }
    Err(format!("writing to stdout: {err}").into())
}

fn coverage(args: &CoverageArgs) -> Result<(), Box<dyn Error>> {
    let curve = coverage_curve(&args.findings)?;
    if curve.is_empty() {
        return Err("the coverage curve is empty; the campaign wrote no sample".into());
    }
    if args.samples {
        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        if let Err(err) = writeln!(out, "{SAMPLE_CSV_HEADER}") {
            return finish_stream(&err);
        }
        for sample in curve.samples() {
            let written = writeln!(
                out,
                "{},{},{},{:.2},{},{},{:.2}",
                sample.relative_time,
                sample.corpus_count,
                sample.edges_found,
                sample.execs_per_sec,
                sample.total_execs,
                sample.saved_crashes,
                sample.map_size_pct
            );
            if let Err(err) = written {
                return finish_stream(&err);
            }
        }
        return Ok(());
    }
    print_coverage_curve(&args.findings);
    Ok(())
}

fn distil_corpus(args: &CorpusArgs) -> Result<(), Box<dyn Error>> {
    let workers = args
        .workers
        .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, std::num::NonZero::get));
    std::fs::create_dir_all(&args.output)?;
    let reduction = corpus::minimize_corpus(corpus::CminInvocation {
        target: &args.target,
        input: &args.input,
        output: &args.output,
        workers,
        timeout: Duration::from_millis(DEFAULT_REPRODUCE_TIMEOUT_MS),
    })?;
    println!("corpus_before      {}", reduction.before);
    println!("corpus_after       {}", reduction.after);
    println!("corpus_removed     {}", reduction.removed());
    if !reduction.is_reduction() {
        println!("the corpus was already minimal for this target's edges");
    }
    Ok(())
}

fn coverage_curve(findings: &std::path::Path) -> Result<plot::CoverageCurve, Box<dyn Error>> {
    Ok(runner::read_curve(findings)?)
}

fn print_coverage_curve(findings: &std::path::Path) {
    let curve = match coverage_curve(findings) {
        Ok(curve) => curve,
        Err(err) => {
            eprintln!("warning: no coverage curve recorded: {err}");
            return;
        }
    };
    let Some(last) = curve.last() else {
        eprintln!("warning: the coverage curve is empty; the campaign wrote no sample");
        return;
    };
    if let Ok(source) = runner::primary_instance(findings)
        && let Some(name) = source.file_name()
    {
        println!("curve_instance     {}", name.to_string_lossy());
    }
    println!("curve_samples      {}", curve.samples().len());
    println!("curve_seconds      {}", curve.duration_secs());
    println!("curve_peak_edges   {}", curve.peak_edges());
    println!("curve_corpus       {}", last.corpus_count);
    if !curve.edges_are_monotonic() {
        eprintln!(
            "warning: coverage fell during this campaign, so {} was resumed over or concatenated and any first-to-last delta understates it",
            plot::PLOT_FILE_NAME
        );
    }
}

fn print_triaged_crashes(harvested: &[Crash]) {
    let grouping = dedup::group_crashes(harvested);
    println!("distinct_bugs      {}", grouping.keyed_bugs());
    println!("unkeyed_crashes    {}", grouping.unkeyed_crashes());

    for group in grouping.groups() {
        if let Some(crash) = group.representative() {
            println!(
                "  {} x{} {}",
                short_hash(crash.stack_hash()),
                group.len(),
                crash_line(crash)
            );
        }
    }

    for crash in grouping.unkeyed() {
        println!("  {NO_STACK_HASH} {UNKEYED_MARKER} {}", crash_line(crash));
    }
}

fn check_persistent_mode(findings: &std::path::Path, target: &std::path::Path) -> bool {
    // A harness that also defines main links silently against the driver's weak main and
    // then fuzzes nothing at 1,597 execs/sec instead of 241,807.
    let persistent = runner::read_stats_text(findings)
        .is_ok_and(|text| lisdex_harness::compile::drives_persistent_mode(&text));
    if !persistent {
        eprintln!(
            "warning: {} is not running in persistent shmem_testcase deferred mode; the harness \
             may define its own main, which shadows the driver and fuzzes nothing",
            target.display()
        );
    }
    persistent
}

fn fail_campaign(store: &Store, campaign: &mut Campaign, campaign_id: CampaignId) {
    if campaign.advance(CampaignStatus::Failed).is_err() {
        return;
    }
    if let Err(err) = store.update_campaign_status(campaign_id, CampaignStatus::Failed) {
        eprintln!("warning: could not record failed status: {err}");
    }
}

fn short_hash(hash: Option<&str>) -> String {
    match hash {
        Some(value) => value
            .char_indices()
            .nth(STACK_HASH_SHORT_LEN)
            .map_or(value, |(at, _)| &value[..at])
            .to_owned(),
        None => NO_STACK_HASH.to_owned(),
    }
}

fn minimize_campaign(args: &MinimizeArgs) -> Result<(), Box<dyn Error>> {
    let store = Store::open(&args.db)?;
    let campaign_id = CampaignId(args.campaign);
    store
        .get_campaign(campaign_id)?
        .ok_or("no such campaign in store")?;

    let crashes = store.crashes_for_campaign(campaign_id)?;
    let grouping = dedup::group_crashes(&crashes);
    std::fs::create_dir_all(&args.out)?;

    println!("distinct_bugs      {}", grouping.keyed_bugs());
    println!("unkeyed_crashes    {}", grouping.unkeyed_crashes());

    let reproduce_timeout = Duration::from_millis(DEFAULT_REPRODUCE_TIMEOUT_MS);
    let exec_timeout = Duration::from_millis(DEFAULT_MINIMIZE_EXEC_TIMEOUT_MS);

    for group in grouping.groups() {
        let Some(crash) = group.representative() else {
            continue;
        };
        let stem = short_hash(crash.stack_hash());
        let original = args.out.join(format!("{stem}{ORIGINAL_SUFFIX}"));
        let minimized = args.out.join(format!("{stem}{MINIMIZED_SUFFIX}"));
        std::fs::write(&original, crash.input())?;

        let outcome = minimize::minimize(
            TminInvocation {
                target: &args.target,
                input: &original,
                output: &minimized,
                timeout: exec_timeout,
            },
            reproduce_timeout,
        );
        match outcome {
            Ok(Outcome::Minimized {
                bytes_before,
                bytes_after,
                ..
            }) => println!(
                "  {stem} x{} {bytes_before} -> {bytes_after} bytes, identity verified",
                group.len()
            ),
            Ok(Outcome::RejectedForIdentity { produced, .. }) => println!(
                "  {stem} x{} NOT minimized: the reduced input proves {}, so only the original is a reproducer",
                group.len(),
                produced.as_deref().unwrap_or(NO_STACK_HASH)
            ),
            Ok(Outcome::RefusedUnkeyed) => println!(
                "  {stem} x{} NOT minimized: no dedup key, so identity cannot be shown to survive",
                group.len()
            ),
            Err(err) => println!("  {stem} x{} NOT minimized: {err}", group.len()),
        }
    }

    Ok(())
}

fn advisories(args: &AdvisoryArgs) -> Result<(), Box<dyn Error>> {
    let store = Store::open(&args.db)?;
    let campaign_id = CampaignId(args.campaign);
    let campaign = store
        .get_campaign(campaign_id)?
        .ok_or("no such campaign in store")?;

    let crashes = store.crashes_for_campaign(campaign_id)?;
    let grouping = dedup::group_crashes(&crashes);

    let mut drafted: Vec<(String, Advisory)> = Vec::new();
    for group in grouping.groups() {
        let Some(crash) = group.representative() else {
            continue;
        };
        let stem = short_hash(crash.stack_hash());
        let package = args.package.as_deref().unwrap_or_else(|| campaign.target());
        match Advisory::draft(package, group, campaign.tree()) {
            Some(advisory) => drafted.push((stem, advisory)),
            None => eprintln!(
                "warning: bug {stem} has no dedup key, so its crashes are not known to be one bug and no advisory names them"
            ),
        }
    }

    if grouping.unkeyed_crashes() > 0 {
        eprintln!(
            "warning: {} crashes carry no dedup key and are in no advisory",
            grouping.unkeyed_crashes()
        );
    }

    let Some(dir) = &args.out else {
        return print_advisories(args.format, &drafted);
    };

    std::fs::create_dir_all(dir)?;
    println!("advisories         {}", drafted.len());
    for (stem, advisory) in &drafted {
        let (text, suffix) = match args.format {
            AdvisoryFormat::Markdown => (markdown::render(advisory, None), MARKDOWN_SUFFIX),
            AdvisoryFormat::Json => (json::render_string(advisory), JSON_SUFFIX),
        };
        let path = dir.join(format!("{stem}{suffix}"));
        std::fs::write(&path, text)?;
        println!(
            "  {stem} x{} {}{}",
            advisory.crash_count(),
            path.display(),
            if advisory.is_disclosable() {
                ""
            } else {
                NOT_DISCLOSABLE_MARKER
            }
        );
    }
    Ok(())
}

fn bundles(args: &BundleArgs) -> Result<(), Box<dyn Error>> {
    let store = Store::open(&args.db)?;
    let campaign_id = CampaignId(args.campaign);
    let campaign = store
        .get_campaign(campaign_id)?
        .ok_or("no such campaign in store")?;

    let crashes = store.crashes_for_campaign(campaign_id)?;
    let grouping = dedup::group_crashes(&crashes);
    std::fs::create_dir_all(&args.out)?;

    println!("distinct_bugs      {}", grouping.keyed_bugs());
    println!("unkeyed_crashes    {}", grouping.unkeyed_crashes());

    for group in grouping.groups() {
        let Some(crash) = group.representative() else {
            continue;
        };
        let stem = short_hash(crash.stack_hash());
        let package = args.package.as_deref().unwrap_or_else(|| campaign.target());
        let Some(advisory) = Advisory::draft(package, group, campaign.tree()) else {
            eprintln!(
                "warning: bug {stem} has no dedup key, so no advisory names it and no bundle is written"
            );
            continue;
        };

        let minimized = args
            .minimized
            .as_ref()
            .map(|dir| dir.join(format!("{stem}{MINIMIZED_SUFFIX}")))
            .filter(|path| path.is_file());
        let (input, reproducer) = match &minimized {
            Some(path) => (std::fs::read(path)?, Reproducer::Minimized),
            None => (crash.input().to_vec(), Reproducer::Original),
        };

        let dir = args.out.join(&stem);
        let written = bundle::write(&dir, &advisory, &input, reproducer)?;
        println!(
            "  {stem} x{} {} files {} bytes {}{}",
            group.len(),
            written.len(),
            input.len(),
            dir.display(),
            if advisory.is_disclosable() {
                ""
            } else {
                NOT_DISCLOSABLE_MARKER
            }
        );
    }

    if args.minimized.is_none() {
        eprintln!(
            "warning: no --minimized directory given, so every bundle ships the original crashing input rather than a reduced one"
        );
    }

    Ok(())
}

fn print_advisories(
    format: AdvisoryFormat,
    drafted: &[(String, Advisory)],
) -> Result<(), Box<dyn Error>> {
    match format {
        AdvisoryFormat::Markdown => {
            for (_, advisory) in drafted {
                println!("{}", markdown::render(advisory, None));
            }
        }
        AdvisoryFormat::Json => {
            let documents: Vec<serde_json::Value> = drafted
                .iter()
                .map(|(_, advisory)| json::render(advisory))
                .collect();
            println!("{}", serde_json::to_string_pretty(&documents)?);
        }
    }
    Ok(())
}

fn crashes(args: &CrashesArgs) -> Result<(), Box<dyn Error>> {
    let store = Store::open(&args.db)?;
    let campaign_id = CampaignId(args.campaign);
    let campaign = store
        .get_campaign(campaign_id)?
        .ok_or("no such campaign in store")?;

    println!(
        "campaign {} target {} status {:?}",
        campaign_id.0,
        campaign.target(),
        campaign.status()
    );

    for crash in store.crashes_for_campaign(campaign_id)? {
        let report = SanitizerReport::parse(crash.sanitizer_report());
        let classification = classify(crash.sanitizer_report());
        println!(
            "  stack_hash {} input {} bytes kind {} severity {}{} class {}",
            crash.stack_hash().unwrap_or(NO_STACK_HASH),
            crash.input().len(),
            report.as_ref().map_or(UNPARSED_KIND, |r| r.kind()),
            classification
                .as_ref()
                .map_or(UNCLASSIFIED_SEVERITY, |c| c.severity().as_str()),
            classification
                .as_ref()
                .map_or("", |c| if c.is_security_relevant() {
                    ""
                } else {
                    NON_SECURITY_MARKER
                }),
            classification.as_ref().map_or(UNPARSED_KIND, |c| c.class())
        );
        if let Some(report) = report {
            for frame in report.frames().iter().take(DISPLAYED_FRAMES) {
                println!("      {frame}");
            }
        }
    }

    Ok(())
}

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

    fn fuzz_args(extra: &[&str]) -> FuzzArgs {
        let mut argv = vec![
            "lisdex",
            "fuzz",
            "--target",
            "/t",
            "--seeds",
            "/s",
            "--findings",
            "/f",
            "--db",
            "/d",
        ];
        argv.extend_from_slice(extra);
        match Cli::try_parse_from(argv).unwrap().command {
            Command::Fuzz(parsed) => parsed,
            _ => panic!("argv names the fuzz subcommand"),
        }
    }

    #[test]
    fn the_job_count_default_is_the_one_named_constant_and_not_a_second_copy() {
        assert_eq!(fuzz_args(&[]).jobs, DEFAULT_PARALLEL_JOBS);
    }

    #[test]
    fn a_campaign_given_no_duration_reaches_afl_fuzz_unbounded() {
        assert_eq!(afl_options(&fuzz_args(&[]), Vec::new()).duration, None);
        assert_eq!(
            afl_options(&fuzz_args(&["--duration", "90"]), Vec::new()).duration,
            Some(Duration::from_secs(90))
        );
    }
}