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 👇

27.6 KB
Raw Blame
// ©AngelaMos | 2026
// surface.rs

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use crate::complexity::{self, CallGraph, Sources};
use crate::extract::{self, Declared, Language, ParseOptions};
use crate::harness::{self, Harness};
use crate::headers::{self, HeaderError, HeaderSet};
use crate::ladder::{self, Ladder};
use crate::rank::{self, Complexity, Function, Ranking, Weights};

pub const SOURCE_EXTENSIONS: &[&str] = &["c", "cc", "cpp", "cxx"];
pub const MAX_DEPTH: usize = 12;
pub const REFUSAL_NUMERATOR: usize = 1;
pub const REFUSAL_DENOMINATOR: usize = 2;
pub const MIN_PLAUSIBLE_SURFACE: usize = 32;

#[derive(Debug, thiserror::Error)]
pub enum SurfaceError {
    #[error("header discovery failed: {0}")]
    Headers(#[from] HeaderError),
    #[error("harness discovery failed: {0}")]
    Harness(#[from] harness::HarnessError),
    #[error(
        "no header under {root} yielded a declaration; {refused} of {total} were refused. \
         first refusal: {first}. if this project generates a config header at build time, \
         run `lisdex build` and pass the build directory it reports with --include \
         (the generated header is written into the build tree, not installed anywhere)"
    )]
    NothingDeclared {
        root: PathBuf,
        refused: usize,
        total: usize,
        first: String,
    },
    #[error(
        "{refused} of {total} headers under {root} were refused, so the {declared} declaration(s) \
         that did parse are not a usable surface. first refusal: {first}. if this project \
         generates a config header at build time, run `lisdex build` and pass the build \
         directory it reports with --include (the generated header is written into the build \
         tree, not installed anywhere)"
    )]
    MostlyRefused {
        root: PathBuf,
        refused: usize,
        total: usize,
        declared: usize,
        first: String,
    },
    #[error(
        "{count} file(s) under {root} resolved a header this library owns to a copy outside the \
         source tree, so this ranking would describe a different build of the library. first: \
         {first}. build the target and pass the build directory it reports with --include, or \
         drop the stray copy off the include path"
    )]
    ForeignEnvironment {
        root: PathBuf,
        count: usize,
        first: String,
    },
    #[error(
        "not one of the {declared} function(s) these headers declare appears among the {symbols} \
         text symbol(s) the given library defines, so the two do not describe the same build and \
         every entry point would be reported as internal. the usual causes are a library from a \
         different project, a build that renames symbols (a Magma target prefixes every one with \
         MAGMA_), and a C++ library whose symbols are mangled. pass the matching library or drop \
         --library to rank on the headers alone"
    )]
    LibraryMismatch { declared: usize, symbols: usize },
}

#[derive(Debug, Clone)]
pub struct SurfaceOptions {
    pub source: PathBuf,
    pub install: Option<PathBuf>,
    pub includes: Vec<PathBuf>,
    pub defines: Vec<String>,
    pub language: Language,
    pub weights: Weights,
    pub ignore_harnesses: bool,
    pub oss_fuzz: Option<PathBuf>,
    pub library_symbols: Option<BTreeSet<String>>,
}

impl SurfaceOptions {
    #[must_use]
    pub fn new(source: impl Into<PathBuf>) -> Self {
        Self {
            source: source.into(),
            install: None,
            includes: Vec::new(),
            defines: Vec::new(),
            language: Language::default(),
            weights: Weights::default(),
            ignore_harnesses: true,
            oss_fuzz: None,
            library_symbols: None,
        }
    }

    #[must_use]
    pub fn parse_options(&self, header_root: &Path, tree_headers: &[PathBuf]) -> ParseOptions {
        let mut includes = vec![header_root.to_path_buf(), self.source.clone()];
        includes.extend(self.includes.iter().cloned());
        ParseOptions {
            includes,
            defines: self.defines.clone(),
            extra_args: Vec::new(),
            language: self.language,
            tree_headers: tree_headers.to_vec(),
            project: headers::project_of(&self.source),
        }
    }
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct SkippedHeader {
    pub header: PathBuf,
    pub reason: String,
    pub foreign: bool,
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct Surface {
    pub source: PathBuf,
    pub header_root: PathBuf,
    pub origin: headers::HeaderOrigin,
    pub headers_read: usize,
    pub headers: Vec<PathBuf>,
    pub skipped: Vec<SkippedHeader>,
    pub harnesses: Vec<Harness>,
    pub ladder: Ladder,
    pub declared: usize,
    pub defined: usize,
    pub skipped_sources: Vec<SkippedHeader>,
    pub ranking: Ranking,
}

fn is_source(path: &Path) -> bool {
    path.extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| SOURCE_EXTENSIONS.contains(&extension.to_lowercase().as_str()))
}

fn walk_sources(root: &Path, project: &str, depth: usize, found: &mut Vec<PathBuf>) {
    if depth > MAX_DEPTH {
        return;
    }
    let Ok(entries) = std::fs::read_dir(root) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().to_lowercase();
        if path.is_dir() {
            if !headers::is_excluded(&name) && !headers::is_vendored_tree(&path, project) {
                walk_sources(&path, project, depth + 1, found);
            }
        } else if is_source(&path) {
            found.push(path);
        }
    }
}

#[must_use]
pub fn library_sources(root: &Path) -> Vec<PathBuf> {
    let mut found = Vec::new();
    walk_sources(root, &headers::project_of(root), 0, &mut found);
    found.sort();
    found
}

fn refuse_library_mismatch(
    declared: &[Declared],
    library: Option<&BTreeSet<String>>,
) -> Result<(), SurfaceError> {
    let Some(symbols) = library else {
        return Ok(());
    };
    if symbols.is_empty()
        || declared.is_empty()
        || declared.iter().any(|item| symbols.contains(&item.name))
    {
        return Ok(());
    }
    Err(SurfaceError::LibraryMismatch {
        declared: declared.len(),
        symbols: symbols.len(),
    })
}

fn exported_by(name: &str, graph: &CallGraph, library: Option<&BTreeSet<String>>) -> bool {
    library.map_or_else(
        || graph.get(name).is_none_or(|node| node.exported),
        |symbols| symbols.contains(name),
    )
}

fn skipped_by(header: &Path, error: &extract::ExtractError) -> SkippedHeader {
    SkippedHeader {
        header: header.to_path_buf(),
        reason: error.to_string(),
        // Matched on the variant, never on the message: a reworded error must not be able
        // to silently turn a fatal environment fault back into one line of a skip list.
        foreign: matches!(error, extract::ExtractError::ForeignInclude { .. }),
    }
}

// A foreign include is a statement about the ENVIRONMENT, not about one header, so it can
// never be one line in a skip list. Measured: a single foreign header in libwebp dropped the
// surface 429 -> 183 declarations, replaced the top entry point with an encoder function, and
// still exited 0 under the old per-header handling.
fn refuse_foreign(root: &Path, skipped: &[SkippedHeader]) -> Result<(), SurfaceError> {
    let foreign: Vec<&SkippedHeader> = skipped.iter().filter(|item| item.foreign).collect();
    match foreign.first() {
        Some(first) => Err(SurfaceError::ForeignEnvironment {
            root: root.to_path_buf(),
            count: foreign.len(),
            first: first.reason.clone(),
        }),
        None => Ok(()),
    }
}

fn read_headers(
    set: &HeaderSet,
    options: &SurfaceOptions,
    owned: &[PathBuf],
) -> (Vec<Declared>, Vec<SkippedHeader>) {
    let parse = options.parse_options(&set.root, owned);
    let mut declared = Vec::new();
    let mut skipped = Vec::new();
    let mut seen = BTreeSet::new();

    for header in &set.headers {
        match extract::parse_header(header, &parse) {
            Ok(found) => {
                for item in found {
                    if seen.insert(item.name.clone()) {
                        declared.push(item);
                    }
                }
            }
            Err(error) => skipped.push(skipped_by(header, &error)),
        }
    }
    (declared, skipped)
}

// A source file that fails to parse silently truncates the call graph, and the call
// graph drives 55% of the score. Header refusals were already surfaced; source
// refusals were not, so a third of libarchive's translation units could vanish with
// no signal at all. Collect them and report them the same way.
fn read_sources(
    root: &Path,
    options: &SurfaceOptions,
    header_root: &Path,
    tree_headers: &[PathBuf],
) -> (Sources, Vec<SkippedHeader>) {
    let parse = options.parse_options(header_root, tree_headers);
    let mut sources = Sources::default();
    let mut skipped = Vec::new();
    let mut seen = BTreeSet::new();
    for source in library_sources(root) {
        match complexity::parse_source(&source, &parse) {
            Ok(found) => sources.absorb(found, &mut seen),
            Err(error) => skipped.push(skipped_by(&source, &error)),
        }
    }
    (sources, skipped)
}

pub fn analyze(options: &SurfaceOptions) -> Result<Surface, SurfaceError> {
    let roots = headers::candidates(&options.source, options.install.as_deref())?;
    let harnesses = harness::discover(&options.source)?;

    // B68. A header root that declares NOTHING is not this library's surface, and discovery
    // cannot know that without parsing. libtiff's root holds one intentionally-empty
    // `placeholder.h` - present so pre-3.11 CMake would accept `add_library()` - and no
    // `include/` directory, so the shallow-root rule chose that single file and the library
    // read as having no API. Parsing the next candidate finds the real headers under
    // `libtiff/`. A tree that already works never reaches this loop's second turn, because its
    // first candidate declares something.
    //
    // The foreign-header refusal is NOT retried past: a stray copy of a header the library owns
    // means the ranking would describe a different build, and that is true of every root in the
    // tree rather than an accident of which one was chosen.
    let mut chosen = None;
    let mut first_failure = None;
    for set in roots {
        let mut owned = set.headers.clone();
        owned.extend(headers::generated_headers(&options.source));
        let (declared, skipped) = read_headers(&set, options, &owned);
        refuse_foreign(&set.root, &skipped)?;
        if !declared.is_empty() {
            chosen = Some((set, declared, skipped, owned));
            break;
        }
        if first_failure.is_none() {
            first_failure = Some(SurfaceError::NothingDeclared {
                root: set.root.clone(),
                refused: skipped.len(),
                total: set.headers.len(),
                first: skipped
                    .first()
                    .map_or_else(|| "none recorded".to_owned(), |item| item.reason.clone()),
            });
        }
    }
    let Some((set, declared, skipped, owned)) = chosen else {
        return Err(first_failure.unwrap_or(SurfaceError::NothingDeclared {
            root: options.source.clone(),
            refused: 0,
            total: 0,
            first: "none recorded".to_owned(),
        }));
    };
    if skipped.len() * REFUSAL_DENOMINATOR > set.headers.len() * REFUSAL_NUMERATOR
        && declared.len() < MIN_PLAUSIBLE_SURFACE
    {
        return Err(SurfaceError::MostlyRefused {
            root: set.root.clone(),
            refused: skipped.len(),
            total: set.headers.len(),
            declared: declared.len(),
            first: skipped
                .first()
                .map_or_else(|| "none recorded".to_owned(), |item| item.reason.clone()),
        });
    }

    // After the headers on purpose: a mined call list is raw text, so the only way to tell
    // one of the library's own calls from libc is to ask what the library declares.
    let ladder = ladder::select(
        &options.source,
        &harnesses,
        options.oss_fuzz.as_deref(),
        &headers::project_of(&options.source),
        &declared.iter().map(|item| item.name.clone()).collect(),
    )?;

    let (sources, skipped_sources) = read_sources(&options.source, options, &set.root, &owned);
    refuse_foreign(&set.root, &skipped_sources)?;
    let defined_count = sources.defined.len();
    let graph = CallGraph::from(sources);

    let seeds: Vec<String> = if options.ignore_harnesses {
        Vec::new()
    } else {
        harness::reached_functions(&harnesses).into_iter().collect()
    };
    let reached = graph.reachable_from(&seeds);
    let directly_called: BTreeSet<String> = seeds.into_iter().collect();

    let library = options.library_symbols.as_ref();
    refuse_library_mismatch(&declared, library)?;

    let functions: Vec<Function> = declared
        .iter()
        .map(|item| Function {
            name: item.name.clone(),
            params: item.params.clone(),
            result: item.result.clone(),
            header: item.header.clone(),
            line: item.line,
            exported: exported_by(&item.name, &graph, library),
            complexity: Complexity {
                danger: graph.danger(&item.name),
                accumulated: graph.accumulated_danger(&item.name),
                undiscovered: graph.undiscovered_danger(&item.name, &reached),
            },
            reachable_from_harness: graph.reaches(&reached, &item.name)
                || directly_called.contains(&item.name),
        })
        .collect();

    Ok(Surface {
        source: options.source.clone(),
        header_root: set.root.clone(),
        origin: set.origin,
        headers_read: set.headers.len(),
        headers: set.headers.clone(),
        skipped,
        harnesses,
        ladder,
        declared: declared.len(),
        defined: defined_count,
        skipped_sources,
        ranking: rank::rank(functions, &options.weights),
    })
}

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

    fn tree(label: &str, files: &[(&str, &str)]) -> PathBuf {
        let root = lisdex_core::scratch::path(&format!("surface-{label}"));
        let _ = std::fs::remove_dir_all(&root);
        for (path, body) in files {
            let full = root.join(path);
            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
            std::fs::write(&full, body).unwrap();
        }
        root
    }

    const HEADER: &str = "\
#include <stddef.h>
struct ctx;
typedef void (*read_fn)(struct ctx *, unsigned char *, unsigned long);
void ctx_set_read(struct ctx *c, void *user, read_fn fn);
int ctx_read_header(struct ctx *c);
int quick_sig_cmp(const unsigned char *sig, size_t start, size_t len);
struct ctx *ctx_create(void);
void ctx_destroy(struct ctx *c);
";

    const SOURCE: &str = "\
#include \"lib.h\"
struct ctx { int state; };
static int chunk_parse(struct ctx *c, int tag) {
  if (tag == 1) { return 1; }
  if (tag == 2) { return 2; }
  for (int i = 0; i < tag; i++) { c->state += i; }
  while (c->state > 100) { c->state--; }
  switch (tag) {
  case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107:
  case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115:
  case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123:
  case 124: case 125: case 126: case 127: case 128: case 129: case 130: case 131:
  case 132: case 133: case 134: case 135: case 136: case 137: case 138: case 139:
  case 140: case 141: case 142: case 143: case 144: case 145: case 146: case 147:
  case 148: case 149: case 150: case 151: case 152: case 153: case 154: case 155:
  case 156: case 157: case 158: case 159: case 160: case 161: case 162: case 163:
  case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171:
  case 172: case 173: case 174: case 175: case 176: case 177: case 178: case 179:
    return tag;
  case 9: return 9;
  case 8: return 8;
  }
  return 0;
}
int ctx_read_header(struct ctx *c) {
  if (!c) { return -1; }
  return chunk_parse(c, c->state);
}
int quick_sig_cmp(const unsigned char *sig, size_t start, size_t len) {
  return sig[start] == len;
}
void ctx_set_read(struct ctx *c, void *user, read_fn fn) { (void)c; (void)user; (void)fn; }
";

    fn fixture(label: &str, extra: &[(&str, &str)]) -> PathBuf {
        let mut files = vec![("include/lib.h", HEADER), ("src/lib.c", SOURCE)];
        files.extend_from_slice(extra);
        tree(label, &files)
    }

    #[test]
    fn a_built_library_decides_which_declared_functions_are_really_exported() {
        let root = fixture("intersection", &[]);
        let exported_of = |surface: &Surface, name: &str| {
            surface
                .ranking
                .candidates
                .iter()
                .find(|candidate| candidate.name == name)
                .map(|candidate| (candidate.exported, candidate.score))
        };

        let headers_only = analyze(&SurfaceOptions::new(&root)).unwrap();
        let (reader_alone, _) = exported_of(&headers_only, "ctx_read_header").unwrap();
        let (compare_alone, compare_score_alone) =
            exported_of(&headers_only, "quick_sig_cmp").unwrap();
        assert!(reader_alone && compare_alone, "headers alone trust both");

        let mut options = SurfaceOptions::new(&root);
        options.library_symbols = Some(
            ["ctx_read_header".to_owned(), "ctx_set_read".to_owned()]
                .into_iter()
                .collect(),
        );
        let intersected = analyze(&options).unwrap();
        let (reader, _) = exported_of(&intersected, "ctx_read_header").unwrap();
        let (compare, compare_score) = exported_of(&intersected, "quick_sig_cmp").unwrap();

        assert!(reader, "a name the library defines stays exported");
        assert!(
            !compare,
            "a header-declared name absent from the library is not part of F_lib"
        );
        assert!(
            compare_score < compare_score_alone,
            "losing export status must cost score: {compare_score} vs {compare_score_alone}"
        );
    }

    #[test]
    fn a_library_that_shares_no_name_with_the_headers_is_refused_not_believed() {
        let root = fixture("mismatch", &[]);
        let mut options = SurfaceOptions::new(&root);
        options.library_symbols = Some(
            [
                "MAGMA_ctx_read_header".to_owned(),
                "MAGMA_ctx_set_read".to_owned(),
            ]
            .into_iter()
            .collect(),
        );
        let refused = analyze(&options);
        assert!(
            matches!(refused, Err(SurfaceError::LibraryMismatch { .. })),
            "a prefixed build shares no bare name, so reporting every entry point internal \
             would be a silent false negative: {refused:?}"
        );
    }

    #[test]
    fn a_context_only_reader_outranks_a_trivial_buffer_comparator() {
        let root = fixture("ranked", &[]);
        let surface = analyze(&SurfaceOptions::new(&root)).unwrap();
        let order: Vec<&str> = surface
            .ranking
            .candidates
            .iter()
            .map(|candidate| candidate.name.as_str())
            .collect();
        assert_eq!(
            order.first(),
            Some(&"ctx_read_header"),
            "the function that drives the parser must win: {order:?}"
        );
        assert!(
            order.iter().position(|name| *name == "ctx_read_header")
                < order.iter().position(|name| *name == "quick_sig_cmp"),
            "{order:?}"
        );
    }

    #[test]
    fn constructors_and_destructors_never_reach_the_candidate_list() {
        let root = fixture("excluded", &[]);
        let surface = analyze(&SurfaceOptions::new(&root)).unwrap();
        let excluded: Vec<&str> = surface
            .ranking
            .excluded
            .iter()
            .map(|item| item.name.as_str())
            .collect();
        assert!(excluded.contains(&"ctx_create"), "{excluded:?}");
        assert!(excluded.contains(&"ctx_destroy"), "{excluded:?}");
    }

    #[test]
    fn accumulated_complexity_reaches_through_static_helpers() {
        let root = fixture("accumulated", &[]);
        let surface = analyze(&SurfaceOptions::new(&root)).unwrap();
        let reader = surface
            .ranking
            .candidates
            .iter()
            .find(|candidate| candidate.name == "ctx_read_header")
            .unwrap();
        assert!(
            reader.complexity.accumulated > reader.complexity.danger,
            "chunk_parse is static and must still be counted: {:?}",
            reader.complexity
        );
    }

    #[test]
    fn an_in_tree_harness_marks_what_it_already_reaches() {
        let root = fixture(
            "reached",
            &[(
                "fuzz/f.c",
                "int LLVMFuzzerTestOneInput(const unsigned char *d, unsigned long n) {\n\
                   ctx_read_header(0); return 0;\n\
                 }\n",
            )],
        );
        let mut options = SurfaceOptions::new(&root);
        options.ignore_harnesses = false;
        let surface = analyze(&options).unwrap();
        assert_eq!(surface.harnesses.len(), 1);
        let reader = surface
            .ranking
            .candidates
            .iter()
            .find(|candidate| candidate.name == "ctx_read_header")
            .unwrap();
        assert!(reader.reachable_from_harness);
    }

    #[test]
    fn a_surface_built_from_a_minority_of_headers_is_refused_not_reported() {
        let mut files = vec![(
            "include/helper.h",
            "int util_decode(const unsigned char *d, unsigned long n);\n",
        )];
        for name in [
            "include/a.h",
            "include/b.h",
            "include/c.h",
            "include/d.h",
            "include/e.h",
        ] {
            files.push((
                name,
                "#include \"generated_config.h\"\nint f(MISSING_T *p);\n",
            ));
        }
        let root = tree("mostlyrefused", &files);
        let error = analyze(&SurfaceOptions::new(&root)).unwrap_err();
        assert!(
            matches!(error, SurfaceError::MostlyRefused { .. }),
            "a partial surface from a handful of parseable helper headers is worse than \
             an error, because it looks like a complete answer: {error:?}"
        );
    }

    #[test]
    fn a_tree_with_no_headers_is_an_error_not_an_empty_ranking() {
        let root = tree("noheaders", &[("src/lib.c", "int main(void){return 0;}")]);
        assert!(analyze(&SurfaceOptions::new(&root)).is_err());
    }

    // B68, and this is libtiff exactly. It ships `placeholder.h` at its root - contents
    // "This file is intentionally empty", present so pre-3.11 CMake would accept an
    // `add_library()` call - and has no `include/` directory, so the shallow-root rule chose
    // that one file and the library read as having NO API AT ALL. 0 declarations from a
    // 200-declaration library.
    #[test]
    fn a_root_header_that_declares_nothing_does_not_become_the_whole_surface() {
        let root = tree(
            "placeholder",
            &[
                ("placeholder.h", "/* intentionally empty */\n"),
                ("placeholder/lib.h", HEADER),
                ("placeholder/lib.c", SOURCE),
            ],
        );
        let surface = analyze(&SurfaceOptions::new(&root)).unwrap();
        assert!(
            surface.declared >= 4,
            "the real headers were never reached: {} declared",
            surface.declared
        );
    }

    // The isolating control. A root header that DOES declare something is still the surface,
    // and the fallback never runs - otherwise "try the next candidate" would quietly become
    // "scan the whole tree", which is a different and much noisier answer.
    //
    // The deeper header sits in `internal/` rather than `vendor/`, and that is the whole
    // control: `vendor` is in EXCLUDED_DIRS, so a first version of this test put its marker
    // somewhere the tree walk never looks and the assertion could not fire under any gut.
    // Both roots also report the SOURCE as `header_root`, so only the CONTENT distinguishes
    // them.
    #[test]
    fn a_root_header_that_declares_something_is_still_the_surface() {
        let root = tree(
            "shallowwins",
            &[
                ("lib.h", HEADER),
                ("lib.c", SOURCE),
                (
                    "internal/other.h",
                    "int deeper_only_symbol(void *p, unsigned long n);\n",
                ),
            ],
        );
        let surface = analyze(&SurfaceOptions::new(&root)).unwrap();
        assert_eq!(surface.header_root, root);
        let seen = surface
            .ranking
            .candidates
            .iter()
            .map(|item| item.name.as_str())
            .chain(
                surface
                    .ranking
                    .excluded
                    .iter()
                    .map(|item| item.name.as_str()),
            )
            .any(|name| name == "deeper_only_symbol");
        assert!(
            !seen,
            "the fallback ran when the shallow root already had a surface"
        );
    }

    // B68. The advice these two errors carry pointed at `--install` and "its install prefix"
    // for as long as they existed, and `lisdex build` produces NO install prefix - the ladder
    // never runs an install step, so `install_dir` is referenced by nothing but its own test.
    // The remedy named a thing the tool cannot produce. The generated header is written into
    // the BUILD tree, and `--include` is the flag that reads it.
    #[test]
    fn the_config_header_advice_names_a_flag_that_does_something() {
        let errors = [
            SurfaceError::NothingDeclared {
                root: PathBuf::from("/src"),
                refused: 0,
                total: 1,
                first: "none recorded".to_owned(),
            },
            SurfaceError::MostlyRefused {
                root: PathBuf::from("/src"),
                refused: 7,
                total: 11,
                declared: 6,
                first: "'tiffconf.h' file not found".to_owned(),
            },
        ];
        for error in errors {
            let text = error.to_string();
            assert!(text.contains("--include"), "no usable remedy: {text}");
            assert!(
                !text.contains("install prefix"),
                "advice names a prefix `lisdex build` never produces: {text}"
            );
        }
    }

    // A tree where NO candidate declares anything still fails, and fails naming the first root
    // tried rather than the last - the first is the one the user can act on.
    #[test]
    fn a_tree_where_no_candidate_declares_anything_is_still_an_error() {
        let root = tree(
            "allempty",
            &[
                ("placeholder.h", "/* nothing */\n"),
                ("sub/also_empty.h", "/* nothing here either */\n"),
            ],
        );
        assert!(matches!(
            analyze(&SurfaceOptions::new(&root)).unwrap_err(),
            SurfaceError::NothingDeclared { .. }
        ));
    }

    #[test]
    fn fuzz_and_test_directories_are_not_mined_for_complexity() {
        let root = fixture("nofuzzsrc", &[]);
        let sources = library_sources(&root);
        assert!(sources.iter().any(|path| path.ends_with("lib.c")));
        let root = fixture(
            "nofuzzsrc2",
            &[("fuzz/harness.c", "int noise(void){return 0;}")],
        );
        let sources = library_sources(&root);
        assert!(
            !sources.iter().any(|path| path.ends_with("harness.c")),
            "{sources:?}"
        );
    }
}