Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Implementation contracts and evidence

Implementation contracts

A structured unit contains its reviewed text directly. It rejects mdBook include, playground, and rustdoc-include directives, including those in literal samples. It also rejects nested legacy source-citation blocks. Related source selections belong in separate units connected by explicit dependencies.

For each chapter received by the Dada preprocessor, the ordered unit IDs and raw structured-unit text must match that chapter’s original source. Earlier content preprocessing may not add, remove, or change units within that chapter. This rejects an include even if mdBook has already expanded it before this boundary.

The comparison covers received chapters at this preprocessing stage. It does not check whether a whole chapter was omitted or whether later output processing changes the generated page.

mdbook-dada/src/units.rs:parse_block
#![allow(unused)]
fn main() {
fn parse_block(
    source: &str,
    path: &str,
    range: Range<usize>,
    info: &str,
) -> Result<Option<SpecUnit>> {
    let (directive, argument) = info.split_once(char::is_whitespace).unwrap_or((info, ""));
    let Some(kind) = UnitKind::parse(directive) else {
        return Ok(None);
    };
    // Legacy directives carry path:declaration on their opening line. Keep their
    // interpretation, but never mistake them for reviewed structured units.
    if argument.contains(':') {
        ensure!(
            kind != UnitKind::FutureNote,
            "future notes cannot have formalization citations; use a stable unit ID"
        );
        return Ok(None);
    }
    let id = argument.trim();
    if kind.is_math() && id.is_empty() {
        bail!(
            "{directive} requires a stable unit ID, a :lean: citation, and an authored LaTeX body"
        );
    }
    ensure!(
        valid_id(id),
        "expected one stable unit ID after {directive}"
    );
    let raw = &source[range.clone()];
    let opening_end = raw
        .find('\n')
        .context("unit has no body or closing fence")?
        + 1;
    let closing_start = raw
        .trim_end_matches(['\n', '\r'])
        .rfind('\n')
        .context("unit has no closing fence")?
        + 1;
    let opening = raw[..opening_end].trim_start();
    let marker = opening
        .chars()
        .next()
        .context("unit has no opening fence")?;
    let width = opening.chars().take_while(|c| *c == marker).count();
    let closing = raw[closing_start..].trim();
    ensure!(
        matches!(marker, '`' | '~')
            && closing.chars().all(|c| c == marker)
            && closing.len() >= width,
        "structured unit must have an explicit matching closing fence"
    );
    let contents = &raw[opening_end..closing_start];
    let mut unit = SpecUnit {
        id: id.to_owned(),
        kind,
        draft: false,
        source_path: path.to_owned(),
        range,
        body: String::new(),
        raw: raw.to_owned(),
        lean: vec![],
        rust: vec![],
        tests: vec![],
        uses: vec![],
    };
    let mut seen = BTreeSet::new();
    let mut body_start = 0;
    for line in contents.split_inclusive('\n') {
        let line_text = line.trim_end_matches(['\n', '\r']);
        if !line_text.starts_with(':') {
            break;
        }
        let (option, value) = line_text[1..]
            .split_once(':')
            .context("unit option must have the form :name: value")?;
        ensure!(seen.insert(option), "duplicate :{option}: option");
        let values: Vec<_> = value.split_whitespace().map(str::to_owned).collect();
        ensure!(!values.is_empty(), ":{option}: must not be empty");
        if option == "status" {
            ensure!(
                values == ["draft"],
                ":status: only accepts `draft`; omit it for units ready for correspondence review"
            );
            unit.draft = true;
            body_start += line.len();
            continue;
        }
        let target = match option {
            "lean" => &mut unit.lean,
            "rust" => &mut unit.rust,
            "tests" => &mut unit.tests,
            "uses" => &mut unit.uses,
            _ => bail!("unknown unit option :{option}:"),
        };
        let unique: BTreeSet<_> = values.iter().collect();
        ensure!(
            unique.len() == values.len(),
            "duplicate value in :{option}:"
        );
        *target = values;
        body_start += line.len();
    }
    unit.body = contents[body_start..].trim_matches(['\n', '\r']).to_owned();
    // mdBook expands these even inside fenced code. The packet must contain
    // exactly the authored content, not untracked external substitutions.
    let includes = regex::Regex::new(r"\{\{\s*#(?:include|rustdoc_include|playground)\b")?;
    ensure!(
        !includes.is_match(&unit.raw),
        "mdBook include, rustdoc_include, and playground directives are unsupported inside structured units; write the content directly or cite another unit"
    );
    for event in Parser::new(&unit.body) {
        if let Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(info))) = event {
            let (directive, argument) = info.split_once(char::is_whitespace).unwrap_or((&info, ""));
            ensure!(
                UnitKind::parse(directive).is_none() || !argument.contains(':'),
                "legacy citation directives cannot nest inside structured units; create a separate unit with :lean: and refer to it with :uses:"
            );
        }
    }
    ensure!(
        !unit.body.trim().is_empty(),
        "unit requires an authored body"
    );
    ensure!(
        !unit.body.starts_with(':'),
        "unit options must immediately follow the opening fence, before the blank line and body"
    );
    if kind == UnitKind::FutureNote {
        ensure!(
            unit.lean.is_empty() && unit.rust.is_empty() && unit.tests.is_empty(),
            "future notes cannot have formalization citations (:lean:, :rust:, or :tests:); use a specification unit for formalized content"
        );
        ensure!(!unit.draft, "future notes cannot have :status: draft; they are exploratory notes, not unfinished specification units");
    }
    ensure!(
        kind == UnitKind::FutureNote || unit.draft || !unit.lean.is_empty() || !unit.rust.is_empty(),
        "unit requires :lean: or :rust: citations; use :status: draft while its formalization is pending"
    );
    ensure!(
        unit.tests.is_empty() || !unit.rust.is_empty(),
        ":tests: requires a :rust: implementation citation"
    );
    ensure!(
        unit.lean.is_empty() || unit.rust.is_empty(),
        "a unit cannot mix :lean: and :rust: citations"
    );
    ensure!(
        !matches!(kind, UnitKind::Theorem | UnitKind::Lemma)
            || !unit.lean.is_empty()
            || (unit.draft && unit.rust.is_empty()),
        "theorem and lemma units require a Lean theorem; Rust tests are not proofs"
    );
    ensure!(
        !matches!(
            kind,
            UnitKind::Judgment
                | UnitKind::Rule
                | UnitKind::Theorem
                | UnitKind::Lemma
                | UnitKind::Example
        ) || unit.lean.is_empty()
            || unit.lean.len() == 1,
        "{} requires exactly one Lean citation",
        kind.label()
    );
    for dependency in &unit.uses {
        ensure!(valid_id(dependency), "invalid dependency ID `{dependency}`");
        ensure!(dependency != id, "unit cannot depend on itself");
    }
    ensure!(
        parse(&unit.body, path)?.is_empty(),
        "named units cannot nest; cite the other unit with :uses: or a link"
    );
    Ok(Some(unit))
}
}
mdbook-dada/src/configuration.rs:SourceConfiguration::validate_chapters
#![allow(unused)]
fn main() {
/// Check original chapters even if mdBook's links preprocessor has already
    /// expanded an include. Also prevent preprocessing from adding, deleting,
    /// or changing a reviewed unit behind the inventory's back.
    pub fn validate_chapters(&self, root: &Path, book: &Value) -> Result<()> {
        let source_root = self.markdown_root(root)?;
        let key = if book.get("items").is_some_and(Value::is_array) {
            "items"
        } else {
            "sections"
        };
        crate::walk(&book[key], &mut |chapter| {
            let path = chapter["source_path"]
                .as_str()
                .or_else(|| chapter["path"].as_str())
                .context("chapter has no source path")?;
            let source_path = source_root.join(path);
            let name = inventory::relative_path(root, &source_path)?;
            let source_path = inventory::input_path(root, &name)?;
            let original = fs::read_to_string(source_path)?;
            let authored = units::parse(&original, &name)?;
            let processed = units::parse(
                chapter["content"]
                    .as_str()
                    .context("chapter has no content")?,
                &name,
            )?;
            ensure!(authored.iter().map(|unit| (&unit.id, &unit.raw)).eq(
                processed.iter().map(|unit| (&unit.id, &unit.raw))),
                "{name}: preprocessing changed structured units; includes and other external substitutions cannot supply or alter reviewed content");
            Ok(())
        })
    }
}
mdbook-dada/tests/units.rs:structured_units_reject_includes_and_nested_legacy_citations
#![allow(unused)]
fn main() {
#[test]
fn structured_units_reject_includes_and_nested_legacy_citations() {
    let files = Sources::new();
    for body in [
        "{{#include details.txt}}",
        "{{ #rustdoc_include example.rs }}",
        "```rust\n{{#playground example.rs}}\n```",
        "```{grammar} Model:Thing\nt ::= empty\n```",
        "```{judgment} Model:Step\nt \\to t\n```",
        "```{rule} Model:Step.same\nt \\to t\n```",
    ] {
        for citation in [":lean: Model:initial", ":rust: tool.rs:check"] {
            let source = format!("````{{definition}} model.unit\n{citation}\n\n{body}\n````");
            assert!(units::parse(&source, "md/model.md").is_err(), "{source}");
            assert!(render(&source, &files.lean()).is_err(), "{source}");
        }
    }
    // Existing citation-first authoring outside reviewed units remains supported.
    render(
        "````{definition} Model:initial\nText.\n\n```{grammar} Model:Thing\nt ::= empty\n```\n````",
        &files.lean(),
    )
    .unwrap();
}
}
mdbook-dada/tests/evidence_validation.rs:authored_includes_and_nested_citations_cannot_acquire_evidence
#![allow(unused)]
fn main() {
#[test]
fn authored_includes_and_nested_citations_cannot_acquire_evidence() {
    let fixture = Fixture::new();
    for body in [
        "{{#include details.txt}}",
        "{{#rustdoc_include example.rs}}",
        "{{#playground example.rs}}",
        "```{grammar} Fixture:Variable\nx ::= Nat\n```",
    ] {
        fixture.write("md/model.md", &format!("````{{definition}} model.value\n:rust: mdbook-dada/src/lib.rs:validate\n\n{body}\n````\n"));
        assert!(Inventory::load(&fixture.0).is_err(), "{body}");
    }
}
}
mdbook-dada/tests/evidence_validation.rs:preexpanded_includes_cannot_bypass_original_source_validation
#![allow(unused)]
fn main() {
#[test]
fn preexpanded_includes_cannot_bypass_original_source_validation() {
    let fixture = Fixture::new();
    let raw =
        "```{definition} model.variable\n:lean: Fixture:Variable\n\n{{#include details.txt}}\n```";
    fixture.write("md/model.md", raw);
    let expanded = raw.replace("{{#include details.txt}}", "The value is two.");
    let mut book = chapter(&expanded);
    let error = mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book)
        .unwrap_err();
    assert!(format!("{error:#}").contains("directives are unsupported"));
    // An include outside a unit cannot introduce a new unit unknown to the inventory.
    fixture.write("md/model.md", "{{#include units.txt}}\n");
    let mut book = chapter(MODEL);
    let error = mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book)
        .unwrap_err();
    assert!(format!("{error:#}").contains("preprocessing changed structured units"));
    // Other preprocessors also cannot rewrite claims while leaving evidence current.
    fixture.write("md/model.md", MODEL);
    let mut book = chapter(&MODEL.replace("natural number", "Boolean"));
    assert!(
        mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book).is_err()
    );
}
}
mdbook-dada/tests/evidence_validation.rs:actual_mdbook_pipeline_rejects_includes_in_reviewed_content
#![allow(unused)]
fn main() {
#[test]
#[ignore = "requires the mdbook executable; run with --ignored after installing book tools"]
fn actual_mdbook_pipeline_rejects_includes_in_reviewed_content() {
    let fixture = Fixture::new();
    fixture.write("md/SUMMARY.md", "# Summary\n\n- [Model](model.md)\n");
    fixture.write("md/details.txt", "The value is one.\n");
    fixture.write("md/model.md", "```{definition} model.variable\n:lean: Fixture:Variable\n\n{{#include details.txt}}\n```\n");
    let command =
        serde_json::to_string(&format!("\"{}\"", env!("CARGO_BIN_EXE_mdbook-dada"))).unwrap();
    fixture.write("book.toml", &format!("[book]\nsrc = \"md\"\n[preprocessor.dada]\ncommand = {command}\nafter = [\"links\"]\nlean-source = \"lean\"\n"));
    for contents in ["The value is one.", "The value is two."] {
        fixture.write("md/details.txt", contents);
        let output = std::process::Command::new("mdbook")
            .arg("build")
            .arg(&fixture.0)
            .output()
            .expect("install mdbook before running this test");
        assert!(!output.status.success());
        let error = String::from_utf8_lossy(&output.stderr);
        assert!(
            error.contains("directives are unsupported inside structured units"),
            "{error}"
        );
    }
}
}

Rendering and evidence read the same book and Lean source roots from book.toml. Runtime overrides that disagree with those roots are rejected. Roots remain inside the project. Rust citations use the project root, even when the Lean root is nested several directories below it.

The configuration is a review input. Changing it makes existing evidence stale; a new packet selects declarations and context from the newly configured root.

mdbook-dada/src/configuration.rs:SourceConfiguration::load
#![allow(unused)]
fn main() {
pub fn load(root: &Path) -> Result<Self> {
        let configuration = toml::from_str(
            &fs::read_to_string(root.join("book.toml")).context("reading book.toml")?,
        )
        .context("parsing book.toml source configuration")?;
        Ok(configuration)
    }
}
mdbook-dada/src/configuration.rs:SourceConfiguration::lean_root
#![allow(unused)]
fn main() {
pub fn lean_root(&self, root: &Path) -> Result<PathBuf> {
        inventory::input_path(root, &self.preprocessor.dada.lean_source)
    }
}
mdbook-dada/src/configuration.rs:SourceConfiguration::markdown_root
#![allow(unused)]
fn main() {
pub fn markdown_root(&self, root: &Path) -> Result<PathBuf> {
        inventory::input_path(root, &self.book.src)
    }
}
mdbook-dada/src/configuration.rs:SourceConfiguration::check_context
#![allow(unused)]
fn main() {
/// Runtime overrides may not make the renderer select different source
    /// trees from the book.toml snapshot used by the evidence inventory.
    pub fn check_context(&self, context: &Value) -> Result<()> {
        let effective: Self = serde_json::from_value(context["config"].clone())
            .context("reading mdBook source configuration")?;
        ensure!(self == &effective,
            "mdBook source configuration differs from book.toml; update book.toml rather than overriding book.src or preprocessor.dada.lean-source");
        Ok(())
    }
}
mdbook-dada/src/lib.rs:process_configured
#![allow(unused)]
fn main() {
/// Production mdBook boundary. Raw source checks precede rendering so already
/// expanded includes cannot bypass structured-unit restrictions.
pub fn process_configured(context: &Value, book: &mut Value) -> Result<()> {
    let root = Path::new(
        context["root"]
            .as_str()
            .context("mdBook context has no root")?,
    )
    .canonicalize()
    .context("resolving mdBook root")?;
    let configuration = configuration::SourceConfiguration::load(&root)?;
    configuration.check_context(context)?;
    configuration.validate_chapters(&root, book)?;
    if root.join("spec.json").exists() {
        inventory::Inventory::load(&root)?;
    }
    let lean_root = configuration.lean_root(&root)?;
    process_with_roots(book, Some(&lean_root), Some(&root))
}
}
mdbook-dada/src/inventory.rs:Inventory::inputs
#![allow(unused)]
fn main() {
/// Derive required snapshots from current sources, never from a review record.
    pub fn inputs(&self, id: &str) -> Result<Vec<Input>> {
        if crate::link_audit::is_subject(id) {
            return crate::link_audit::inputs(self, id);
        }
        let mut inputs = BTreeMap::new();
        self.add_unit(id, &mut inputs, &mut BTreeSet::new())?;
        for input in self.common_inputs()? {
            inputs.insert(input.key.clone(), input);
        }
        if inputs.keys().any(|key| key.starts_with("lean:")) {
            let lean_root = self.source_configuration.lean_root(&self.root)?;
            for path in files(&self.root, &lean_root, "lean")? {
                let name = relative_path(&self.root, &path)?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
            for path in ["lean-toolchain", "lakefile.toml", "lake-manifest.json"] {
                let name = relative_path(&self.root, &lean_root.join(path))?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
        }
        Ok(inputs.into_values().collect())
    }
}
mdbook-dada/tests/evidence_validation.rs:configured_lean_root_is_shared_by_rendering_and_evidence
#![allow(unused)]
fn main() {
#[test]
fn configured_lean_root_is_shared_by_rendering_and_evidence() {
    let fixture = Fixture::new();
    fixture.complete_reviews();
    let original = fixture.bundle();
    assert!(original
        .inputs
        .iter()
        .any(|input| input.key == "tool:book.toml"));
    for file in [
        "Fixture.lean",
        "lean-toolchain",
        "lakefile.toml",
        "lake-manifest.json",
    ] {
        fixture.write(
            &format!("formal/model/{file}"),
            &fs::read_to_string(fixture.0.join("lean").join(file)).unwrap(),
        );
    }
    fixture.write(
        "formal/model/Fixture.lean",
        "abbrev Variable := Nat\ndef empty : List Variable := [2]\n",
    );
    fixture.write(
        "book.toml",
        "[book]\nsrc = \"md\"\n[preprocessor.dada]\nlean-source = \"formal/model\"\n",
    );
    let inventory = fixture.inventory();
    assert!(!evidence::check(&inventory).unwrap().is_ok());
    let bundle = fixture.bundle();
    let selected = bundle
        .inputs
        .iter()
        .find(|input| input.key == "lean:Fixture:empty")
        .unwrap();
    assert_eq!(selected.path, "formal/model/Fixture.lean");
    assert!(selected.content.contains(":= [2]"));
    assert!(bundle
        .inputs
        .iter()
        .any(|input| input.key == "context:formal/model/Fixture.lean"));
    assert!(!bundle
        .inputs
        .iter()
        .any(|input| input.path.starts_with("lean/")));
    let mut book = chapter(MODEL);
    mdbook_dada::process_configured(&configured_context(&fixture, "formal/model"), &mut book)
        .unwrap();
    assert!(book.to_string().contains(":= [2]"));
    let mut book = chapter(MODEL);
    assert!(
        mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book).is_err()
    );
    // Rust selections use the project root, not the parent of the Lean directory.
    let rust =
        "```{definition} meta.check\n:rust: mdbook-dada/src/lib.rs:validate\n\nValidation.\n```";
    fixture.write("md/model.md", rust);
    let mut book = chapter(rust);
    mdbook_dada::process_configured(&configured_context(&fixture, "formal/model"), &mut book)
        .unwrap();
    assert!(book.to_string().contains("pub fn validate"));
}
}

An exact source selection contains the complete declaration or constructor named by a citation, excluding neighboring declarations.

A rule citation selects one constructor of its named inductive declaration. Unsupported indented sibling commands are rejected rather than treated as part of that declaration. A constructor from a sibling type cannot satisfy the citation.

Top-level mutual groups of named inductives are supported in the documented column-zero form. A citation selects the complete named member; the full enclosing source remains an evidence input. Nested, malformed, or other kinds of mutual groups are rejected.

Selection preserves literal tokens, including a final string or character index and quoted identifiers. It may omit a following standalone comment; it may not truncate the constructor’s type. These are textual source-selection checks, not Lean elaboration or a proof that the authored mathematical rule has the same meaning.

mdbook-dada/src/lean.rs:select
#![allow(unused)]
fn main() {
/// Resolve a citation with the same declaration-kind checks as the renderer.
pub fn select(root: &Path, target: &str, kind: crate::units::UnitKind) -> Result<LeanSelection> {
    use crate::units::UnitKind;
    ensure!(
        kind != UnitKind::FutureNote,
        "future notes cannot have formalization citations"
    );
    let (source, name) = read_source(root, target)?;
    let selected = match kind {
        UnitKind::FutureNote => unreachable!("rejected above"),
        UnitKind::Definition => extract_definition(&source, &name),
        UnitKind::Theorem | UnitKind::Lemma => extract_theorem(&source, &name),
        UnitKind::Example => extract_example(&source, &name),
        UnitKind::Grammar => extract(&source, &name),
        UnitKind::Judgment => extract(&source, &name).and_then(|declaration| {
            ensure!(
                declaration.starts_with("inductive "),
                "judgment citation must select an inductive declaration"
            );
            Ok(declaration)
        }),
        UnitKind::Rule => {
            let (name, case) = name
                .rsplit_once('.')
                .context("rule expects path:Judgment.constructor")?;
            extract(&source, name).and_then(|declaration| extract_case(&declaration, case))
        }
    }
    .with_context(|| target.to_owned())?;
    let (file, _) = target
        .rsplit_once(':')
        .context("expected path:Declaration")?;
    let mut relative = std::path::PathBuf::from(file);
    if relative.extension().is_none() {
        relative.set_extension("lean");
    }
    // read_source already checks canonical containment, including symlinks.
    let path = root.join(relative).canonicalize()?;
    Ok(LeanSelection {
        path,
        source,
        selected,
    })
}
}
mdbook-dada/src/lean.rs:extract_declaration
#![allow(unused)]
fn main() {
fn extract_declaration(source: &str, name: &str, selection: Selection) -> Result<String> {
    let simple_name = |component: &str| {
        !component.is_empty() && component.chars().all(|c| c.is_alphanumeric() || c == '_')
    };
    if selection != Selection::Type {
        ensure!(
            name.split('.').all(simple_name),
            "use a declaration name with nonempty identifier components separated by single dots"
        );
    } else {
        ensure!(
            simple_name(name),
            "use a simple unqualified declaration name"
        );
    }
    let masked = mask(source)?;
    validate_mutual_groups(&masked)?;
    let mut found = Vec::new();
    let mut offset = 0;
    let lines: Vec<_> = masked
        .split_inclusive('\n')
        .map(|line| {
            let start = offset;
            offset += line.len();
            (start, line)
        })
        .collect();
    let structure_field = regex::Regex::new(r"^[ \t]+[A-Za-z_][A-Za-z0-9_']*[ \t]*:(?:[^:=]|$)")?;
    for (i, &(start, line)) in lines.iter().enumerate() {
        let words: Vec<_> = line.split_whitespace().collect();
        if selection == Selection::Definition {
            let declaration: Vec<_> = words
                .iter()
                .copied()
                .skip_while(|word| {
                    matches!(
                        *word,
                        "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
                    )
                })
                .collect();
            // Literal names are intentionally not resolved through namespaces.
            // A same-named declaration of the wrong kind must not disappear
            // from an otherwise ambiguous citation.
            if declaration.get(1) == Some(&name)
                && matches!(
                    declaration.first(),
                    Some(
                        &"def"
                            | &"abbrev"
                            | &"structure"
                            | &"inductive"
                            | &"theorem"
                            | &"lemma"
                            | &"axiom"
                            | &"opaque"
                            | &"constant"
                            | &"class"
                    )
                )
            {
                ensure!(
                    declaration.len() == words.len(),
                    "declaration modifiers are unsupported"
                );
                ensure!(
                    matches!(declaration.first(), Some(&"def" | &"abbrev" | &"structure" | &"inductive")),
                    "definition citations must select def, abbrev, structure, or inductive declarations"
                );
            }
        }
        if words.get(1) != Some(&name) {
            continue;
        }
        let supported = match selection {
            Selection::Theorem => words.first() == Some(&"theorem"),
            Selection::Type => {
                matches!(words.first(), Some(&"inductive" | &"structure" | &"abbrev"))
            }
            Selection::Definition => matches!(
                words.first(),
                Some(&"def" | &"inductive" | &"structure" | &"abbrev")
            ),
        };
        if !supported {
            continue;
        }
        ensure!(
            !line.starts_with(char::is_whitespace),
            "selected Lean declarations must begin at column zero"
        );
        if let Some((_, previous)) = lines[..i].iter().rev().find(|(_, l)| !l.trim().is_empty()) {
            ensure!(
                !previous.trim_start().starts_with("@["),
                "declaration attributes are unsupported"
            );
        }
        if let Some((_, boundary)) = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
        {
            let mut words = boundary.split_whitespace();
            let first = words.next().unwrap_or("");
            let mut word = first;
            while matches!(
                word,
                "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
            ) {
                word = words.next().unwrap_or("");
            }
            ensure!(
                (word == first
                    || matches!(
                        word,
                        "inductive" | "structure" | "abbrev" | "def" | "theorem" | "instance"
                    ))
                    && matches!(
                        word,
                        "inductive"
                            | "structure"
                            | "abbrev"
                            | "def"
                            | "theorem"
                            | "lemma"
                            | "example"
                            | "instance"
                            | "end"
                            | "namespace"
                            | "section"
                            | "mutual"
                            | "variable"
                            | "open"
                            | "#check"
                    ),
                "unsupported declaration boundary `{}`; continuation lines must be indented",
                boundary.trim()
            );
        }
        let end = lines[i + 1..]
            .iter()
            .find(|(_, l)| !l.trim().is_empty() && !l.starts_with(char::is_whitespace))
            .map(|(n, _)| *n)
            .unwrap_or(source.len());
        let body = &source[start..end];
        let text = &body[..scan(body)?.content_end];
        {
            let code = &masked[start..end];
            // A structure field such as `variables : Store` is not a command.
            // Only exempt a bare, indented field name followed by a type colon;
            // `variable (x : Nat)` and `def sibling := ...` remain commands.
            let commands = command_pattern()?
                .find_iter(code)
                .filter(|command| {
                    words[0] != "structure"
                        || !structure_field
                            .is_match(code[command.start()..].lines().next().unwrap_or(""))
                })
                .count();
            ensure!(
                commands == 1,
                "selected declaration must contain no other commands, even when indented"
            );
        }
        if selection == Selection::Theorem {
            ensure!(
                has_definition_body(&masked[start..end]),
                "theorem must include its proof body (`:=`)"
            );
        } else if selection == Selection::Definition && words[0] == "def" {
            ensure!(
                has_named_definition_body(&masked[start..end])?,
                "definition must include a body (`:=`, `where`, or indented equations with `=>`)"
            );
        } else if words[0] != "abbrev" {
            ensure!(
                line.contains("where"),
                "declaration header must contain `where` on its first line"
            );
        } else {
            if selection == Selection::Definition {
                ensure!(
                    has_definition_body(&masked[start..end]),
                    "abbreviation must include a body (`:=`)"
                );
            } else {
                ensure!(line.contains(":="), "abbreviation header must contain `:=`");
            }
        }
        found.push(text.to_owned());
    }
    ensure!(
        found.len() == 1,
        "expected one supported declaration `{name}`, found {}",
        found.len()
    );
    Ok(found.remove(0))
}
}
mdbook-dada/src/lean.rs:validate_mutual_groups
#![allow(unused)]
fn main() {
fn validate_mutual_groups(masked: &str) -> Result<()> {
    let commands = command_pattern()?;
    let mut open = None;
    let mut members = HashSet::new();
    let mut previous = "";
    for (index, line) in masked.lines().enumerate() {
        let number = index + 1;
        let text = line.trim();
        if text.is_empty() {
            continue;
        }
        let words: Vec<_> = text.split_whitespace().collect();
        let command = words.iter().copied().find(|word| {
            !matches!(
                *word,
                "private" | "protected" | "noncomputable" | "unsafe" | "partial" | "nonrec"
            )
        });
        if command == Some("mutual") {
            ensure!(
                open.is_none(),
                "nested mutual groups are unsupported at line {number}"
            );
            ensure!(
                text == "mutual" && !line.starts_with(char::is_whitespace),
                "mutual must stand alone at column zero at line {number}"
            );
            ensure!(
                !previous.starts_with("@["),
                "attributes on mutual groups are unsupported at line {number}"
            );
            open = Some(number);
            members.clear();
        } else if open.is_some() {
            if words.first() == Some(&"end") {
                ensure!(
                    text == "end" && !line.starts_with(char::is_whitespace),
                    "mutual groups must close with a standalone column-zero `end` at line {number}"
                );
                ensure!(
                    !members.is_empty(),
                    "empty mutual group ending at line {number}"
                );
                open = None;
            } else if line.starts_with(char::is_whitespace) {
                ensure!(
                    !members.is_empty() && !commands.is_match(line),
                    "mutual inductive bodies cannot contain indented commands at line {number}"
                );
            } else {
                ensure!(
                    words.first() == Some(&"inductive"),
                    "mutual groups support only column-zero named inductive declarations; unsupported member at line {number}"
                );
                let name = words
                    .get(1)
                    .context("mutual inductive declaration needs a name")?;
                ensure!(
                    *name != "where"
                        && name.split('.').all(|part| !part.is_empty()
                            && part.chars().all(|c| c.is_alphanumeric() || c == '_')),
                    "unsupported mutual inductive name at line {number}"
                );
                ensure!(
                    words.last() == Some(&"where"),
                    "mutual inductive headers must end with `where` on their first line at line {number}"
                );
                ensure!(
                    members.insert(*name),
                    "duplicate mutual inductive `{name}` at line {number}"
                );
            }
        }
        previous = text;
    }
    ensure!(
        open.is_none(),
        "unterminated mutual group beginning at line {}",
        open.unwrap_or(0)
    );
    Ok(())
}
}
mdbook-dada/src/lean.rs:extract_case
#![allow(unused)]
fn main() {
fn extract_case(declaration: &str, case: &str) -> Result<String> {
    ensure!(
        !case.is_empty() && case.chars().all(|c| c.is_alphanumeric() || c == '_'),
        "use a simple constructor name"
    );
    let masked = mask(declaration)?;
    let header = declaration
        .lines()
        .next()
        .context("missing declaration header")?;
    ensure!(
        header.starts_with("inductive "),
        "rule citation must select an inductive constructor"
    );
    let mut offset = 0;
    let mut candidates = Vec::new();
    for line in masked.split_inclusive('\n') {
        let trimmed = line.trim_start();
        let indent = line.len() - trimmed.len();
        if let Some(row) = trimmed.strip_prefix('|') {
            let name = row
                .trim_start()
                .split(|c: char| c.is_whitespace() || matches!(c, ':' | '(' | '{' | '['))
                .next()
                .unwrap_or("");
            candidates.push((offset, indent, name));
        }
        offset += line.len();
    }
    let indent = candidates
        .iter()
        .map(|(_, indent, _)| *indent)
        .min()
        .context("inductive has no constructors")?;
    let cases: Vec<_> = candidates
        .into_iter()
        .filter(|(_, i, _)| *i == indent)
        .collect();
    let found: Vec<_> = cases
        .iter()
        .enumerate()
        .filter(|(_, (_, _, n))| *n == case)
        .collect();
    ensure!(
        found.len() == 1,
        "expected one constructor `{case}`, found {}",
        found.len()
    );
    let (index, (start, _, _)) = found[0];
    let end = cases
        .get(index + 1)
        .map(|(start, _, _)| *start)
        .unwrap_or(declaration.len());
    // A comment introducing the next declaration is not part of this case.
    let selected = &declaration[*start..end];
    let selected = &selected[..scan(selected)?.content_end];
    Ok(format!("{header}\n{selected}"))
}
}
mdbook-dada/src/lean.rs:scan
#![allow(unused)]
fn main() {
fn scan(source: &str) -> Result<Scanned> {
    let bytes = source.as_bytes();
    let mut output = bytes.to_vec();
    let mut comments = Vec::new();
    let mut content_end = 0;
    let mut i = 0;
    while i < bytes.len() {
        let start = i;
        let mut comment = false;
        if bytes.get(i..i + 2) == Some(b"/-") {
            comment = true;
            i += 2;
            let mut depth = 1;
            while i < bytes.len() && depth > 0 {
                match bytes.get(i..i + 2) {
                    Some(b"/-") => {
                        depth += 1;
                        i += 2;
                    }
                    Some(b"-/") => {
                        depth -= 1;
                        i += 2;
                    }
                    _ => i += 1,
                }
            }
            ensure!(depth == 0, "unterminated Lean comment");
        } else if bytes.get(i..i + 2) == Some(b"--") {
            comment = true;
            comments.push(i);
            i = source[i..].find('\n').map_or(bytes.len(), |n| i + n);
        } else if let Some((quote, hashes)) = raw_string_start(source, i) {
            let closing = format!("\"{}", "#".repeat(hashes));
            let tail = quote + 1;
            i = tail
                + source[tail..]
                    .find(&closing)
                    .context("unterminated Lean raw string")?
                + closing.len();
        } else if let Some(end) = character_end(source, i) {
            i = end;
        } else if source[i..].starts_with('«') {
            i += source[i..]
                .find('»')
                .context("unterminated Lean quoted identifier")?
                + '»'.len_utf8();
        } else if bytes[i] == b'"' {
            i += 1;
            loop {
                ensure!(i < bytes.len(), "unterminated Lean string");
                match bytes[i] {
                    b'"' => {
                        i += 1;
                        break;
                    }
                    b'\\' => i += 2,
                    _ => i += 1,
                }
            }
        } else {
            // Keep UTF-8 boundaries for the character-literal lookahead below.
            let c = source[i..].chars().next().unwrap();
            i += c.len_utf8();
            if !c.is_whitespace() {
                content_end = i;
            }
            continue;
        }
        if !comment || !source[content_end..start].contains('\n') {
            // Keep comments beginning on the final code line, including a
            // block comment continuing onto later lines. Standalone comments
            // after the body belong to neither the selected declaration nor
            // its source extent. Comments before later code remain intact.
            content_end = i;
        }
        for byte in &mut output[start..i] {
            if *byte != b'\n' {
                *byte = b' ';
            }
        }
    }
    Ok(Scanned {
        code: String::from_utf8(output)?,
        line_comments: comments,
        content_end,
    })
}
}
mdbook-dada/tests/units.rs:rule_citations_cannot_select_an_indented_siblings_constructor
#![allow(unused)]
fn main() {
#[test]
fn rule_citations_cannot_select_an_indented_siblings_constructor() {
    let files = Sources::new();
    std::fs::write(files.lean().join("Sibling.lean"), "inductive First where\n  | first\n  inductive Second where\n  | second\n#check Second.second\n").unwrap();
    for kind in [UnitKind::Grammar, UnitKind::Judgment, UnitKind::Definition] {
        let error = lean::select(&files.lean(), "Sibling:First", kind).unwrap_err();
        assert!(format!("{error:#}").contains("no other commands"));
    }
    let error = lean::select(&files.lean(), "Sibling:First.second", UnitKind::Rule).unwrap_err();
    assert!(format!("{error:#}").contains("no other commands"));
    assert!(render(
        "```{rule} model.invalid\n:lean: Sibling:First.second\n\nP\n```",
        &files.lean()
    )
    .is_err());
    assert!(render("```{rule} Sibling:First.second\nP\n```", &files.lean()).is_err());
}
}
mdbook-dada/tests/units.rs:rule_selections_preserve_final_literal_tokens
#![allow(unused)]
fn main() {
#[test]
fn rule_selections_preserve_final_literal_tokens() {
    let files = Sources::new();
    for (ty, term) in [
        ("String", r#""zero""#),
        ("String", "r#\"raw -- /- «text»\"#"),
        ("Char", "'α'"),
        ("Char", "'\\n'"),
        ("Nat", "«some index»"),
    ] {
        let header = format!("inductive Indexed : {ty} → Type where");
        let case = format!("  | zero : Indexed {term}");
        for ending in [
            "\n",
            " -- attached\n",
            "\n  -- next constructor\n  | next : Indexed default\n",
        ] {
            std::fs::write(
                files.lean().join("Indexed.lean"),
                format!("{header}\n{case}{ending}"),
            )
            .unwrap();
            let selected =
                lean::select(&files.lean(), "Indexed:Indexed.zero", UnitKind::Rule).unwrap();
            assert!(
                selected.selected.starts_with(&format!("{header}\n{case}")),
                "{}",
                selected.selected
            );
            assert_eq!(
                selected.selected.contains("-- attached"),
                ending.contains("-- attached")
            );
            assert!(!selected.selected.contains("next constructor"));
            assert!(!selected.selected.contains("| next"));
            let output = render(
                "```{rule} model.literal\n:lean: Indexed:Indexed.zero\n\nP\n```",
                &files.lean(),
            )
            .unwrap();
            assert!(output.contains(&mdbook_dada::escape(term)), "{output}");
        }
    }
}
}
mdbook-dada/src/lean.rs:tests::selects_mutual_inductive_members_and_surrounding_declarations
#![allow(unused)]
fn main() {
#[test]
    fn selects_mutual_inductive_members_and_surrounding_declarations() {
        let source = include_str!("../tests/fixtures/lean/Mutual.lean");
        let eval = "inductive Eval : Nat → Prop where\n  | arguments {n : Nat} : Args n → Eval n";
        let args = "inductive Args : Nat → Prop where\n  | nil : Args 0\n  | cons {n : Nat} : Eval n → Args n";
        for (name, expected) in [("Eval", eval), ("Args", args)] {
            assert_eq!(extract(source, name).unwrap(), expected);
            assert_eq!(extract_definition(source, name).unwrap(), expected);
            assert!(extract_theorem(source, name).is_err());
        }
        assert_eq!(
            extract(source, "Token").unwrap(),
            "inductive Token where\n  | token"
        );
        assert_eq!(
            extract(source, "Step").unwrap(),
            "inductive Step : Prop where\n  | evaluated : Eval 0 → Step"
        );
        assert_eq!(
            extract_theorem(source, "finished").unwrap(),
            "theorem finished : True := by\n  trivial"
        );

        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/lean");
        for kind in [
            crate::units::UnitKind::Definition,
            crate::units::UnitKind::Grammar,
            crate::units::UnitKind::Judgment,
        ] {
            let selection = select(&root, "Mutual:Eval", kind).unwrap();
            assert_eq!(selection.selected, eval);
            assert_eq!(selection.source, source);
        }
        let rule = select(&root, "Mutual:Args.cons", crate::units::UnitKind::Rule).unwrap();
        assert_eq!(
            rule.selected,
            "inductive Args : Nat → Prop where\n  | cons {n : Nat} : Eval n → Args n"
        );
        assert_eq!(rule.source, source);
        assert!(select(&root, "Mutual:Eval", crate::units::UnitKind::Theorem).is_err());
        assert!(select(&root, "Mutual:finished", crate::units::UnitKind::Definition).is_err());
    }
}
mdbook-dada/src/lean.rs:tests::mutual_validation_ignores_comment_and_literal_decoys
#![allow(unused)]
fn main() {
#[test]
    fn mutual_validation_ignores_comment_and_literal_decoys() {
        let source = format!(
            r###"/- mutual
/- mutual -/
def fake := 0
end
-/
def text := r##"
mutual
def fake := "end"
"##
def «mutual» := 0
-- mutual
{}
"###,
            include_str!("../tests/fixtures/lean/Mutual.lean")
        );
        assert!(extract(&source, "Eval")
            .unwrap()
            .contains("Args n → Eval n"));
        let comments = "mutual -- start\n/- group comment -/\ninductive First where -- header\n  | first -- end\n-- mutual\ninductive Second where\n  | second\nend -- close\n";
        assert_eq!(
            extract(comments, "Second").unwrap(),
            "inductive Second where\n  | second"
        );
        assert!(extract(comments, "First")
            .unwrap()
            .ends_with("  | first -- end"));
    }
}
mdbook-dada/src/lean.rs:tests::rejects_unsupported_or_incomplete_mutual_groups_before_any_selection
#![allow(unused)]
fn main() {
#[test]
    fn rejects_unsupported_or_incomplete_mutual_groups_before_any_selection() {
        for (group, message) in [
            (
                "mutual\ndef member := 0\nend",
                "only column-zero named inductive",
            ),
            (
                "mutual\ntheorem member : True := by trivial\nend",
                "only column-zero named inductive",
            ),
            (
                "mutual\nstructure Member where\n  field : Nat\nend",
                "only column-zero named inductive",
            ),
            (
                "mutual\ninductive Member where\n  | member\nmutual\nend\nend",
                "nested mutual",
            ),
            (
                "mutual\n  inductive Member where\n    | member\nend",
                "indented commands",
            ),
            (
                "mutual\ninductive Member where\n  | member\n  def hidden := 0\nend",
                "indented commands",
            ),
            (
                "mutual\ninductive Member where\n  | member\n  #check Nat\nend",
                "indented commands",
            ),
            (
                "mutual\ninductive Member where\n  | member\nend Member",
                "standalone column-zero `end`",
            ),
            (
                "mutual\ninductive Member where\n  | member\n  end",
                "standalone column-zero `end`",
            ),
            (
                "mutual\ninductive Member where\n  | member",
                "unterminated mutual",
            ),
            ("mutual\nend", "empty mutual"),
            (
                "mutual extra\ninductive Member where\n  | member\nend",
                "mutual must stand alone",
            ),
            (
                "private mutual\ninductive Member where\n  | member\nend",
                "mutual must stand alone",
            ),
            (
                "  mutual\ninductive Member where\n  | member\nend",
                "mutual must stand alone",
            ),
            (
                "@[expose]\nmutual\ninductive Member where\n  | member\nend",
                "attributes on mutual",
            ),
            (
                "mutual\ninductive Member\n  where\n  | member\nend",
                "headers must end with `where`",
            ),
            (
                "mutual\ninductive «Member» where\n  | member\nend",
                "unsupported mutual inductive name",
            ),
            (
                "mutual\ninductive Member where\n  | one\ninductive Member where\n  | two\nend",
                "duplicate mutual inductive",
            ),
        ] {
            let source = format!("inductive Selected where\n  | selected\n{group}\n");
            let error = extract(&source, "Selected").expect_err(group).to_string();
            assert!(error.contains(message), "{group}: {error}");
        }
        let duplicate = format!(
            "{}\ninductive Eval where\n  | another\n",
            include_str!("../tests/fixtures/lean/Mutual.lean")
        );
        assert!(extract(&duplicate, "Eval")
            .unwrap_err()
            .to_string()
            .contains("found 2"));
    }
}

Recording a review rechecks its inputs against current sources. A later decision may explicitly supersede an earlier decision for the same unit; the earlier record remains available. Every active decision must concern current inputs and conclude correspondence for that specification unit’s check to pass. Future notes assert no correspondence and cannot be prepared or recorded for correspondence review.

An independent positive decision cannot conceal an active mismatch, inconclusive review, or stale decision. If a replacement becomes stale, checking fails rather than falling back to the old positive review. Draft units fail validation and cannot receive affirmative correspondence decisions.

mdbook-dada/src/evidence.rs:record
#![allow(unused)]
fn main() {
/// Record a review only after checking the same current input set used by check.
/// Recording a mismatch is permitted and will cause required review checks to fail.
pub fn record(
    inventory: &Inventory,
    bundle: &ReviewBundle,
    review: &ReviewRecord,
) -> Result<PathBuf> {
    let current = Inventory::load(&inventory.root)?;
    let inventory = &current;
    if !link_audit::is_subject(&bundle.unit) {
        ensure!(
            inventory.unit(&bundle.unit)?.kind != UnitKind::FutureNote,
            "cannot record correspondence for a future note: it has no formalization"
        );
    }
    let mut errors = validate_bundle(inventory, bundle)?;
    errors.extend(validate_review(bundle, review));
    ensure!(
        errors.is_empty(),
        "cannot record review: {}",
        errors.join("; ")
    );
    ensure!(
        link_audit::is_subject(&bundle.unit) || !inventory.unit(&bundle.unit)?.draft,
        "cannot record review for draft unit {}: complete its formalization and matching citations, remove :status: draft, then prepare and review a new bundle",
        bundle.unit
    );
    for previous in &review.supersedes {
        ensure!(valid_digest(previous), "invalid superseded review digest");
        let old: ReviewRecord = read_json(
            &inventory
                .root
                .join("evidence/records")
                .join(&bundle.unit)
                .join(format!("{previous}.json")),
        )?;
        ensure!(
            old.digest()? == *previous,
            "superseded review contents differ"
        );
        let prior: ReviewBundle = read_json(
            &inventory
                .root
                .join("evidence/bundles")
                .join(format!("{}.json", old.bundle)),
        )?;
        ensure!(
            prior.unit == bundle.unit,
            "superseded review must concern the same unit"
        );
    }
    save_bundle(inventory, bundle)?;
    write_immutable(
        &inventory.root,
        &PathBuf::from("evidence/records")
            .join(&bundle.unit)
            .join(format!("{}.json", review.digest()?)),
        review,
    )
}
}
mdbook-dada/src/evidence.rs:check
#![allow(unused)]
fn main() {
/// Check all required units, including record presence, minimum inputs and freshness.
/// Neither the review's conclusion nor a passing result establishes a Lean proof.
pub fn check(inventory: &Inventory) -> Result<Report> {
    let mut report = Report::default();
    if let Err(error) = crate::mechanical::records(&inventory.root) {
        report.issues.push(Issue {
            unit: None,
            message: "malformed mechanical execution evidence".into(),
            details: vec![format!("{error:#}")],
        });
    }
    let mut bundles = BTreeMap::new();
    for path in json_files(&inventory.root, &inventory.root.join("evidence/bundles"))? {
        match read_json::<ReviewBundle>(&path) {
            Ok(bundle) => {
                let errors = bundle.integrity_errors();
                let name = path
                    .file_stem()
                    .and_then(|name| name.to_str())
                    .unwrap_or("");
                if !errors.is_empty() || name != bundle.digest {
                    report.issues.push(Issue {
                        unit: inventory
                            .units
                            .contains_key(&bundle.unit)
                            .then_some(bundle.unit.clone()),
                        message: format!("invalid evidence bundle {}", path.display()),
                        details: errors,
                    });
                } else {
                    bundles.insert(bundle.digest.clone(), bundle);
                }
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed evidence bundle".into(),
                details: vec![format!("{error:#}")],
            }),
        }
    }
    let audits = AuditInventory::build(inventory)?;
    // Parse every saved decision, including retired subjects. Removing a link or
    // unit retires its obligation, not the integrity checks on its history.
    let mut all_records: BTreeMap<String, BTreeMap<String, ReviewRecord>> = BTreeMap::new();
    let records_root = inventory.root.join("evidence/records");
    for path in json_tree(&inventory.root, &records_root)? {
        let parsed = (|| -> Result<(String, String, ReviewRecord)> {
            let review: ReviewRecord = read_json(&path)?;
            let digest = review.digest()?;
            ensure!(
                path.file_stem().and_then(|name| name.to_str()) == Some(&digest),
                "record filename does not match contents"
            );
            let bundle = bundles
                .get(&review.bundle)
                .context("record's bundle is missing or malformed")?;
            ensure!(
                path == records_root
                    .join(&bundle.unit)
                    .join(format!("{digest}.json")),
                "record filed under wrong subject"
            );
            let errors = validate_review(bundle, &review);
            ensure!(errors.is_empty(), "invalid review: {}", errors.join("; "));
            Ok((bundle.unit.clone(), digest, review))
        })();
        match parsed {
            Ok((subject, digest, review)) => {
                all_records
                    .entry(subject)
                    .or_default()
                    .insert(digest, review);
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed stored review".into(),
                details: vec![format!("{}: {error:#}", path.display())],
            }),
        }
    }
    for (id, records) in &all_records {
        for review in records.values() {
            for previous in &review.supersedes {
                if !records.contains_key(previous) {
                    report.issues.push(Issue {
                        unit: Some(id.clone()),
                        message: "review supersedes absent or unrelated evidence".into(),
                        details: vec![previous.clone()],
                    });
                }
            }
        }
    }
    let required_subjects: BTreeSet<_> = inventory
        .required
        .iter()
        .chain(audits.manifests.keys())
        .cloned()
        .collect();
    let mut current_active = BTreeMap::new();
    for id in &required_subjects {
        // Derive inputs even for drafts: malformed
        // citations never disappear because a formalization is unfinished.
        let required = match if link_audit::is_subject(id) {
            audits.inputs(inventory, id)
        } else {
            inventory.inputs(id)
        } {
            Ok(inputs) => inputs,
            Err(error) => {
                report.issues.push(Issue {
                    unit: Some(id.clone()),
                    message: "cannot resolve required evidence inputs".into(),
                    details: vec![format!("{error:#}")],
                });
                report.statuses.push(UnitStatus {
                    unit: id.clone(),
                    evidence: "invalid sources",
                    correspondence: "not checked",
                });
                continue;
            }
        };
        if inventory
            .units
            .get(id)
            .is_some_and(|unit| unit.kind == UnitKind::FutureNote)
        {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "future note",
                correspondence: "not applicable",
            });
            continue;
        }
        if inventory.units.get(id).is_some_and(|unit| unit.draft) {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "draft",
                correspondence: "not asserted",
            });
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("draft unit {id} requires formalization"),
                details: vec![
                    "draft status preserves the unit's semantic kind but cannot count as completed correspondence evidence".into(),
                ],
            });
            continue;
        }
        let mut current = BTreeSet::new();
        let mut stale = Vec::new();
        for bundle in bundles.values().filter(|bundle| &bundle.unit == id) {
            // Historical bundles compare with one independently derived current
            // manifest. Re-reading all sources for each past review made the
            // ordinary evidence test grow with the entire review history.
            let errors = validate_bundle_against(inventory, bundle, required.clone())?;
            if errors.is_empty() {
                current.insert(bundle.digest.clone());
            } else {
                stale.extend(errors);
            }
        }
        let empty_records = BTreeMap::new();
        let records = all_records.get(id).unwrap_or(&empty_records);
        let superseded: BTreeSet<_> = records
            .values()
            .flat_map(|review| review.supersedes.iter().cloned())
            .collect();
        let stale_active = records.iter().any(|(digest, review)| {
            !superseded.contains(digest) && !current.contains(&review.bundle)
        });
        let active: Vec<_> = records
            .iter()
            .filter(|(digest, review)| {
                current.contains(&review.bundle) && !superseded.contains(*digest)
            })
            .map(|(_, review)| review)
            .collect();
        // Cross-review order decisions may rely only on an entirely current,
        // positive subject; a conflicting or stale active record blocks it.
        if !stale_active
            && !active.is_empty()
            && active
                .iter()
                .all(|review| review.conclusion == Conclusion::Corresponds)
        {
            current_active.insert(
                id.clone(),
                active.iter().map(|review| (*review).clone()).collect(),
            );
        }
        let evidence = if stale_active {
            "stale"
        } else if !current.is_empty() {
            "current"
        } else if !stale.is_empty() {
            "stale"
        } else {
            "missing"
        };
        let correspondence = if stale_active {
            "stale decision"
        } else if active.is_empty() {
            "missing"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Mismatch)
        {
            "mismatch"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Inconclusive)
        {
            "inconclusive"
        } else {
            "corresponds"
        };
        report.statuses.push(UnitStatus {
            unit: id.clone(),
            evidence,
            correspondence,
        });
        if correspondence != "corresponds" {
            let mut details = if evidence == "stale" {
                stale
            } else {
                Vec::new()
            };
            details.sort();
            details.dedup();
            if evidence == "current" && active.is_empty() {
                details.push("preparing a bundle does not record a completed review".into());
            }
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("{evidence} evidence for {id}: correspondence {correspondence}"),
                details,
            });
        }
    }
    for (unit, message) in link_audit::cross_validate(&audits, &current_active) {
        report.issues.push(Issue {
            unit: Some(unit),
            message,
            details: Vec::new(),
        });
    }
    Ok(report)
}
}
mdbook-dada/tests/evidence_validation.rs:recording_rechecks_sources_even_with_an_existing_inventory
#![allow(unused)]
fn main() {
#[test]
fn recording_rechecks_sources_even_with_an_existing_inventory() {
    let fixture = Fixture::new();
    let inventory = fixture.inventory();
    let bundle = ReviewBundle::prepare(&inventory, "model.empty", &[]).unwrap();
    fixture.write(
        "md/model.md",
        &MODEL.replace("has no variables", "has one variable"),
    );
    assert!(
        evidence::record(&inventory, &bundle, &review(&bundle)).is_err(),
        "record accepted a changed authored source through a cached inventory"
    );
}
}
mdbook-dada/tests/evidence_validation.rs:mismatch_and_inconclusive_reviews_never_count_as_correspondence
#![allow(unused)]
fn main() {
#[test]
fn mismatch_and_inconclusive_reviews_never_count_as_correspondence() {
    for conclusion in [Conclusion::Mismatch, Conclusion::Inconclusive] {
        let fixture = Fixture::new();
        fixture.complete_reviews();
        let inventory = fixture.inventory();
        let bundle = fixture.bundle();
        let mut negative = review(&bundle);
        negative.conclusion = conclusion;
        evidence::record(&inventory, &bundle, &negative).unwrap();
        let report = evidence::check(&inventory).unwrap();
        assert!(
            !report.is_ok(),
            "negative review was hidden by a positive one"
        );
        let status = report
            .statuses
            .iter()
            .find(|status| status.unit == "model.empty")
            .unwrap();
        assert_ne!(status.correspondence, "corresponds");
    }
}
}
mdbook-dada/tests/evidence_validation.rs:revised_review_can_supersede_same_unit_after_consulting_more_context
#![allow(unused)]
fn main() {
#[test]
fn revised_review_can_supersede_same_unit_after_consulting_more_context() {
    let fixture = Fixture::new();
    fixture.complete_reviews();
    let inventory = fixture.inventory();
    let initial = fixture.bundle();
    let mut unresolved = review(&initial);
    unresolved.conclusion = Conclusion::Inconclusive;
    unresolved.rationale = "Fixture review requests additional context before deciding.".into();
    let old_path = evidence::record(&inventory, &initial, &unresolved).unwrap();
    let old_bytes = fs::read(&old_path).unwrap();
    assert!(!evidence::check(&inventory).unwrap().is_ok());

    fixture.write(
        "additional-context.txt",
        "Additional context resolves the fixture question.\n",
    );
    let revised = ReviewBundle::prepare(
        &inventory,
        "model.empty",
        &["additional-context.txt".into()],
    )
    .unwrap();
    assert_ne!(initial.digest, revised.digest);
    let mut resolved = review(&revised);
    resolved.rationale = "Fixture review now accounts for the additional context.".into();
    resolved.supersedes = vec![unresolved.digest().unwrap()];
    evidence::record(&inventory, &revised, &resolved).unwrap();
    let report = evidence::check(&inventory).unwrap();
    assert!(report.is_ok(), "{}", report.render(&inventory));
    assert_eq!(
        fs::read(&old_path).unwrap(),
        old_bytes,
        "supersession must retain the original evidence"
    );

    let other = ReviewBundle::prepare(&inventory, "model.variable", &[]).unwrap();
    let other_review = review(&other);
    let mut wrong_unit = resolved;
    wrong_unit.supersedes = vec![other_review.digest().unwrap()];
    assert!(
        evidence::record(&inventory, &revised, &wrong_unit).is_err(),
        "a review cannot supersede another unit's evidence"
    );
}
}
mdbook-dada/tests/evidence_validation.rs:stale_supersession_cannot_fall_back_to_an_independent_positive_review
#![allow(unused)]
fn main() {
#[test]
fn stale_supersession_cannot_fall_back_to_an_independent_positive_review() {
    let fixture = Fixture::new();
    // This positive review will remain current throughout the scenario.
    fixture.complete_reviews();
    let inventory = fixture.inventory();
    let initial = fixture.bundle();
    let mut mismatch = review(&initial);
    mismatch.conclusion = Conclusion::Mismatch;
    mismatch.rationale = "The fixture reviewer reports a mismatch.".into();
    evidence::record(&inventory, &initial, &mismatch).unwrap();

    fixture.write(
        "resolution.txt",
        "Extra context justifies the revised fixture conclusion.\n",
    );
    let revised =
        ReviewBundle::prepare(&inventory, "model.empty", &["resolution.txt".into()]).unwrap();
    let mut resolved = review(&revised);
    resolved.supersedes = vec![mismatch.digest().unwrap()];
    evidence::record(&inventory, &revised, &resolved).unwrap();
    assert!(evidence::check(&inventory).unwrap().is_ok());

    fixture.write(
        "resolution.txt",
        "The justification changed and needs a new review.\n",
    );
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(!report.is_ok(), "a stale superseding review hid the mismatch while the checker fell back to another positive review");
    let diagnostic = report.render(&fixture.inventory());
    assert!(diagnostic.contains("stale"), "{diagnostic}");
    assert!(diagnostic.contains("resolution.txt"), "{diagnostic}");
}
}

Required inputs

For a review bundle, validation derives its required inputs from the current specification inventory. The bundle must contain the complete authored unit and every exact cited Lean declaration, together with required context, policy, and tooling snapshots. Tooling snapshots include the renderer’s Lean test fixtures and the theme’s JavaScript and CSS, so edits to those files invalidate existing reviews. A complete Lean source file does not substitute for a missing exact declaration selection.

Validation reports missing required inputs, changed or substituted input contents or paths, and inconsistent snapshot hashes. Additional consulted files are included as explicit extra inputs and checked against their current contents. This is a check of input identity and completeness; it does not decide whether the mathematical explanation corresponds to Lean.

mdbook-dada/src/evidence.rs:validate_bundle
#![allow(unused)]
fn main() {
/// Compare against the independently derived inventory, not a self-declared
/// checklist. Extra inputs are allowed only as current project file snapshots.
pub fn validate_bundle(inventory: &Inventory, bundle: &ReviewBundle) -> Result<Vec<String>> {
    validate_bundle_against(inventory, bundle, inventory.inputs(&bundle.unit)?)
}
}
mdbook-dada/src/inventory.rs:Inventory::inputs
#![allow(unused)]
fn main() {
/// Derive required snapshots from current sources, never from a review record.
    pub fn inputs(&self, id: &str) -> Result<Vec<Input>> {
        if crate::link_audit::is_subject(id) {
            return crate::link_audit::inputs(self, id);
        }
        let mut inputs = BTreeMap::new();
        self.add_unit(id, &mut inputs, &mut BTreeSet::new())?;
        for input in self.common_inputs()? {
            inputs.insert(input.key.clone(), input);
        }
        if inputs.keys().any(|key| key.starts_with("lean:")) {
            let lean_root = self.source_configuration.lean_root(&self.root)?;
            for path in files(&self.root, &lean_root, "lean")? {
                let name = relative_path(&self.root, &path)?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
            for path in ["lean-toolchain", "lakefile.toml", "lake-manifest.json"] {
                let name = relative_path(&self.root, &lean_root.join(path))?;
                let input = self.file_input(format!("context:{name}"), &name)?;
                inputs.insert(input.key.clone(), input);
            }
        }
        Ok(inputs.into_values().collect())
    }
}
mdbook-dada/tests/evidence_validation.rs:rejects_missing_or_substituted_required_inputs
#![allow(unused)]
fn main() {
#[test]
fn rejects_missing_or_substituted_required_inputs() {
    let fixture = Fixture::new();
    let inventory = fixture.inventory();
    let original = fixture.bundle();
    assert!(original
        .inputs
        .iter()
        .any(|input| input.key == "context:lean/Fixture.lean"));
    for key in [
        "unit:model.empty",
        "lean:Fixture:empty",
        "unit:model.variable",
        "lean:Fixture:Variable",
        "policy:policy.md",
        "context:context.txt",
        "tool:Cargo.lock",
        "context:lean/lean-toolchain",
    ] {
        let mut reduced = original.clone();
        reduced.inputs.retain(|input| input.key != key);
        repack(&mut reduced);
        let errors = evidence::validate_bundle(&inventory, &reduced).unwrap();
        assert!(
            errors
                .iter()
                .any(|error| error == &format!("missing required input {key}")),
            "missing {key} escaped validation: {errors:?}"
        );
        assert!(
            !errors.iter().any(|error| error.contains("digest")),
            "attack manifest should remain internally consistent"
        );
    }

    let mut substituted = original;
    let input = substituted
        .inputs
        .iter_mut()
        .find(|input| input.key == "lean:Fixture:empty")
        .unwrap();
    input.content = "def other : List Variable := [1]".into();
    input.sha256 = hash(input.content.as_bytes());
    repack(&mut substituted);
    let errors = evidence::validate_bundle(&inventory, &substituted).unwrap();
    assert!(
        errors
            .iter()
            .any(|error| error == "stale or substituted input lean:Fixture:empty"),
        "{errors:?}"
    );
}
}
mdbook-dada/tests/evidence_validation.rs:renderer_lean_fixtures_are_required_freshness_inputs
#![allow(unused)]
fn main() {
#[test]
fn renderer_lean_fixtures_are_required_freshness_inputs() {
    let fixture = Fixture::new();
    let path = "mdbook-dada/tests/fixtures/lean/Renderer.lean";
    let key = format!("tool:{path}");
    fixture.write(path, "abbrev Sample := Nat\n");
    fixture.complete_reviews();
    let bundle = fixture.bundle();
    let input = bundle.inputs.iter().find(|input| input.key == key).unwrap();
    assert_eq!(input.content, "abbrev Sample := Nat\n");

    let mut reduced = bundle.clone();
    reduced.inputs.retain(|input| input.key != key);
    repack(&mut reduced);
    let errors = evidence::validate_bundle(&fixture.inventory(), &reduced).unwrap();
    assert!(errors.contains(&format!("missing required input {key}")));

    fixture.write(path, "abbrev Sample := String\n");
    let inventory = fixture.inventory();
    assert!(evidence::record(&inventory, &bundle, &review(&bundle)).is_err());
    let report = evidence::check(&inventory).unwrap();
    assert!(!report.is_ok());
    assert!(report.render(&inventory).contains(&key));
}
}
mdbook-dada/tests/evidence_validation.rs:theme_assets_are_required_freshness_inputs
#![allow(unused)]
fn main() {
#[test]
fn theme_assets_are_required_freshness_inputs() {
    let fixture = Fixture::new();
    fixture.write("theme/mathjax.js", "const version = 'first';\n");
    fixture.write("theme/dada.css", "figure { display: block; }\n");
    let bundle = fixture.bundle();
    for path in ["theme/mathjax.js", "theme/dada.css"] {
        let key = format!("tool:{path}");
        assert!(bundle.inputs.iter().any(|input| input.key == key));
        let mut reduced = bundle.clone();
        reduced.inputs.retain(|input| input.key != key);
        repack(&mut reduced);
        let errors = evidence::validate_bundle(&fixture.inventory(), &reduced).unwrap();
        assert!(errors.contains(&format!("missing required input {key}")));
    }
    fixture.write("theme/mathjax.js", "const version = 'second';\n");
    let errors = evidence::validate_bundle(&fixture.inventory(), &bundle).unwrap();
    assert!(errors
        .iter()
        .any(|error| error.contains("stale or substituted input tool:theme/mathjax.js")));
    fixture.write("theme/extra.css", "figure { color: red; }\n");
    let errors = evidence::validate_bundle(&fixture.inventory(), &bundle).unwrap();
    assert!(errors.contains(&"missing required input tool:theme/extra.css".to_owned()));
}
}

Finite maps

A finite map associates a key with at most one value. Write \(M : K \rightharpoonup T\) for a finite map from keys in \(K\) to values in \(T\). Its finite list of entries contains pairs \((k,v)\), and no key occurs twice. The list records an order; the unique-key condition does not impose an order on the keys themselves.

definitionevidence.map.empty_definition The empty map \(\varnothing\) has no entries.

Common/FiniteMap:FiniteMap
structure FiniteMap (Key Value : Type) where
  entries : List (Key × Value)
  uniqueKeys : (entries.map Prod.fst).Nodup
Common/FiniteMap:FiniteMap.empty
def FiniteMap.empty : FiniteMap Key Value where
  entries := []
  uniqueKeys := List.nodup_nil

For any refevidence.map \(M\), key \(k\), and values \(v,w\), if both \((k,v)\) and \((k,w)\) are entries of \(M\), then \(v=w\). This holds for any key and value types; no ordering or decidable equality on keys is assumed.

Common/FiniteMap:FiniteMap.value_unique
theorem FiniteMap.value_unique (map : FiniteMap Key Value)
    {key : Key} {value value' : Value}
    (member : (key, value) ∈ map.entries)
    (member' : (key, value') ∈ map.entries) : value = value' := by
  obtain ⟨i, hi, entry⟩ := List.getElem_of_mem member
  obtain ⟨j, hj, entry'⟩ := List.getElem_of_mem member'
  have same_index : i = j := map.uniqueKeys.eq_of_getElem_eq
    (by simpa using hi) (by simpa using hj) (by simp [entry, entry'])
  subst j
  have same_entry : (key, value) = (key, value') := entry.symm.trans entry'
  exact (Prod.mk.inj same_entry).2

Choose natural numbers as both keys and values. The empty map has the empty entry list \([]\). There is no key-value pair stored in this example.

Common/FiniteMapExamples:empty_map
example : (FiniteMap.empty : FiniteMap Nat Nat).entries = [] := by
  rfl

Mechanical execution records

A mechanical execution receipt records a named check from spec-checks.json. Only an explicit run-check command executes it. The receipt retains the exact profile, working directory, command and tool-version outputs as bytes, exit statuses, local timing, and declared source snapshots before and after execution. The profile and runner sources are mandatory inputs; directory snapshots record membership, including empty directories. Source symlinks and generated input roots are rejected. The fixed generated-directory exclusions are .git, .lake, target, book, and evidence.

A recorded pass requires a successful command, successful identical version probes, and identical before/after snapshots. Failed commands, failed launches, and failed recapture remain recorded failures. Saved input hashes, membership, profile identity, receipt contents, and filenames are checked independently of correspondence decisions. Missing declared roots, runner/configuration roots, or members listed in directory snapshots are invalid, even when the remaining hashes have been recomputed.

Status uses the latest local finish time for each check. Any failure or stale receipt tied at that time prevents a reported pass; an older success cannot conceal it. Source or profile changes make receipts stale. Syntactic evidence validation reads these records without running checks or requiring recorded success. This keeps a Cargo test from depending on a receipt of its own run.

The receipt covers its declared sources and observed outputs. It is not a hermetic execution trace or authentication of the runner. Generated artifacts, review records, ambient environment, and installed dependencies are outside the source snapshot; edits restored between snapshots can escape detection. A separate Lean assumptions command reports dependencies for its explicitly named theorems after rebuilding imports. These observations do not establish the meaning of a theorem or constitute a correspondence judgment.

mdbook-dada/src/mechanical.rs:run
#![allow(unused)]
fn main() {
/// Execute only an explicitly selected configured check. Preserve failures as well
/// as successes; endpoint snapshots do not provide filesystem isolation.
pub fn run(root: &Path, name: &str) -> Result<PathBuf> {
    let root = root.canonicalize()?;
    let config = Configuration::load(&root)?;
    let check = config
        .checks
        .get(name)
        .with_context(|| format!("unknown mechanical check {name}"))?
        .clone();
    let cwd = working_directory(&root, &check.cwd)?;
    let before = snapshot(&root, &check)?;
    let started_unix_ms = now()?;
    let timer = Instant::now();
    let version_before = execute(&check.version, &cwd);
    let command = version_before
        .succeeded()
        .then(|| execute(&check.command, &cwd));
    let version_after = execute(&check.version, &cwd);
    let (after, after_error) = match snapshot(&root, &check) {
        Ok(inputs) => (Some(inputs), None),
        Err(error) => (None, Some(format!("{error:#}"))),
    };
    let mut receipt = Execution {
        schema: SCHEMA,
        name: name.into(),
        check,
        host_os: std::env::consts::OS.into(),
        host_arch: std::env::consts::ARCH.into(),
        started_unix_ms,
        finished_unix_ms: now()?,
        elapsed_ms: timer.elapsed().as_millis(),
        before,
        after,
        after_error,
        version_before,
        command,
        version_after,
        digest: String::new(),
    };
    receipt.digest = receipt.content_digest()?;
    receipt.validate()?;
    write_immutable(
        &root,
        &PathBuf::from(RECORDS).join(format!("{}.json", receipt.digest)),
        &receipt,
    )
}
}
mdbook-dada/src/mechanical.rs:snapshot
#![allow(unused)]
fn main() {
/// Capture directory membership and complete UTF-8 source contents, in path order.
/// Versioned profiles and runner sources are always included independently of inputs.
pub fn snapshot(root: &Path, check: &Check) -> Result<Vec<Input>> {
    let mut inputs = BTreeMap::new();
    for relative in check
        .inputs
        .iter()
        .map(String::as_str)
        .chain([CONFIG, "mdbook-dada/src"])
    {
        let path = input_path(root, relative)?;
        ensure!(
            !generated(path.strip_prefix(root)?),
            "generated output cannot be a mechanical input"
        );
        // Inspect the lexical path as well, so a selected symlink is not followed.
        let mut lexical = root.to_owned();
        for component in Path::new(relative).components() {
            lexical.push(component);
            ensure!(
                !fs::symlink_metadata(&lexical)?.file_type().is_symlink(),
                "mechanical input uses a symbolic link"
            );
        }
        collect(root, &path, &mut inputs)?;
    }
    Ok(inputs.into_values().collect())
}
}
mdbook-dada/src/mechanical.rs:Execution::validate
#![allow(unused)]
fn main() {
pub fn validate(&self) -> Result<()> {
        ensure!(
            self.schema == SCHEMA && self.content_digest()? == self.digest,
            "execution digest or schema is invalid"
        );
        validate_check(&self.check)?;
        ensure!(!self.before.is_empty(), "execution has no input snapshots");
        ensure!(
            self.after.is_some() != self.after_error.is_some(),
            "execution needs an after snapshot or an error"
        );
        ensure!(
            self.command.is_some() == self.version_before.succeeded(),
            "execution command/version results are inconsistent"
        );
        for inputs in std::iter::once(&self.before).chain(self.after.iter()) {
            validate_snapshot(inputs, &self.check)?;
        }
        let config_input = self
            .before
            .iter()
            .find(|input| input.path == CONFIG)
            .context("missing check configuration")?;
        let config: Configuration = serde_json::from_str(&config_input.content)?;
        ensure!(
            config.schema == SCHEMA && config.checks.get(&self.name) == Some(&self.check),
            "recorded check differs from its configuration snapshot"
        );
        for outcome in [&self.version_before, &self.version_after]
            .into_iter()
            .chain(self.command.iter())
        {
            if let Some(error) = &outcome.launch_error {
                ensure!(
                    !error.is_empty()
                        && outcome.exit_code.is_none()
                        && outcome.stdout.is_empty()
                        && outcome.stderr.is_empty(),
                    "launch error has process output or exit code"
                );
            }
        }
        Ok(())
    }
}
mdbook-dada/src/mechanical.rs:status
#![allow(unused)]
fn main() {
/// Report the latest receipt per configured check. A later failure or stale run
/// cannot be hidden by an older success. Local receipt timestamps are provenance,
/// not an authenticated clock.
pub fn status(root: &Path) -> Result<Vec<Status>> {
    let records = records(root)?;
    if !root.join(CONFIG).exists() {
        if records.is_empty() {
            return Ok(Vec::new());
        }
        bail!("execution receipts exist without {CONFIG}");
    }
    let config = Configuration::load(root)?;
    config
        .checks
        .into_iter()
        .map(|(name, check)| {
            let latest_time = records
                .iter()
                .filter(|r| r.name == name)
                .map(|r| r.finished_unix_ms)
                .max();
            let latest: Vec<_> = records
                .iter()
                .filter(|r| r.name == name && Some(r.finished_unix_ms) == latest_time)
                .collect();
            let current = snapshot(root, &check)?;
            let state = if latest.is_empty() {
                "not recorded"
            } else if latest
                .iter()
                .any(|r| r.check != check || r.before != current)
            {
                "stale"
            } else if latest.iter().any(|r| !r.succeeded()) {
                "recorded failure"
            } else {
                "recorded pass"
            };
            let responsible = latest
                .iter()
                .filter(|r| match state {
                    "stale" => r.check != check || r.before != current,
                    "recorded failure" => !r.succeeded(),
                    _ => true,
                })
                .min_by_key(|r| &r.digest);
            Ok(Status {
                name,
                state,
                receipt: responsible.map(|r| r.digest.clone()),
            })
        })
        .collect()
}
}
mdbook-dada/src/mechanical.rs:records
#![allow(unused)]
fn main() {
/// Validate retained receipts without executing any commands, including historical
/// failures and receipts for checks no longer configured.
pub fn records(root: &Path) -> Result<Vec<Execution>> {
    let directory = root.join(RECORDS);
    if !directory.exists() {
        return Ok(Vec::new());
    }
    ensure!(
        directory.canonicalize()?.starts_with(root),
        "execution directory escapes project"
    );
    let mut records = Vec::new();
    for entry in fs::read_dir(directory)? {
        let path = entry?.path();
        ensure!(
            !fs::symlink_metadata(&path)?.file_type().is_symlink(),
            "execution receipt is a symbolic link"
        );
        if path.extension().is_some_and(|s| s == "json") {
            records.push(load(&path)?);
        }
    }
    Ok(records)
}
}
mdbook-dada/src/evidence.rs:check
#![allow(unused)]
fn main() {
/// Check all required units, including record presence, minimum inputs and freshness.
/// Neither the review's conclusion nor a passing result establishes a Lean proof.
pub fn check(inventory: &Inventory) -> Result<Report> {
    let mut report = Report::default();
    if let Err(error) = crate::mechanical::records(&inventory.root) {
        report.issues.push(Issue {
            unit: None,
            message: "malformed mechanical execution evidence".into(),
            details: vec![format!("{error:#}")],
        });
    }
    let mut bundles = BTreeMap::new();
    for path in json_files(&inventory.root, &inventory.root.join("evidence/bundles"))? {
        match read_json::<ReviewBundle>(&path) {
            Ok(bundle) => {
                let errors = bundle.integrity_errors();
                let name = path
                    .file_stem()
                    .and_then(|name| name.to_str())
                    .unwrap_or("");
                if !errors.is_empty() || name != bundle.digest {
                    report.issues.push(Issue {
                        unit: inventory
                            .units
                            .contains_key(&bundle.unit)
                            .then_some(bundle.unit.clone()),
                        message: format!("invalid evidence bundle {}", path.display()),
                        details: errors,
                    });
                } else {
                    bundles.insert(bundle.digest.clone(), bundle);
                }
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed evidence bundle".into(),
                details: vec![format!("{error:#}")],
            }),
        }
    }
    let audits = AuditInventory::build(inventory)?;
    // Parse every saved decision, including retired subjects. Removing a link or
    // unit retires its obligation, not the integrity checks on its history.
    let mut all_records: BTreeMap<String, BTreeMap<String, ReviewRecord>> = BTreeMap::new();
    let records_root = inventory.root.join("evidence/records");
    for path in json_tree(&inventory.root, &records_root)? {
        let parsed = (|| -> Result<(String, String, ReviewRecord)> {
            let review: ReviewRecord = read_json(&path)?;
            let digest = review.digest()?;
            ensure!(
                path.file_stem().and_then(|name| name.to_str()) == Some(&digest),
                "record filename does not match contents"
            );
            let bundle = bundles
                .get(&review.bundle)
                .context("record's bundle is missing or malformed")?;
            ensure!(
                path == records_root
                    .join(&bundle.unit)
                    .join(format!("{digest}.json")),
                "record filed under wrong subject"
            );
            let errors = validate_review(bundle, &review);
            ensure!(errors.is_empty(), "invalid review: {}", errors.join("; "));
            Ok((bundle.unit.clone(), digest, review))
        })();
        match parsed {
            Ok((subject, digest, review)) => {
                all_records
                    .entry(subject)
                    .or_default()
                    .insert(digest, review);
            }
            Err(error) => report.issues.push(Issue {
                unit: None,
                message: "malformed stored review".into(),
                details: vec![format!("{}: {error:#}", path.display())],
            }),
        }
    }
    for (id, records) in &all_records {
        for review in records.values() {
            for previous in &review.supersedes {
                if !records.contains_key(previous) {
                    report.issues.push(Issue {
                        unit: Some(id.clone()),
                        message: "review supersedes absent or unrelated evidence".into(),
                        details: vec![previous.clone()],
                    });
                }
            }
        }
    }
    let required_subjects: BTreeSet<_> = inventory
        .required
        .iter()
        .chain(audits.manifests.keys())
        .cloned()
        .collect();
    let mut current_active = BTreeMap::new();
    for id in &required_subjects {
        // Derive inputs even for drafts: malformed
        // citations never disappear because a formalization is unfinished.
        let required = match if link_audit::is_subject(id) {
            audits.inputs(inventory, id)
        } else {
            inventory.inputs(id)
        } {
            Ok(inputs) => inputs,
            Err(error) => {
                report.issues.push(Issue {
                    unit: Some(id.clone()),
                    message: "cannot resolve required evidence inputs".into(),
                    details: vec![format!("{error:#}")],
                });
                report.statuses.push(UnitStatus {
                    unit: id.clone(),
                    evidence: "invalid sources",
                    correspondence: "not checked",
                });
                continue;
            }
        };
        if inventory
            .units
            .get(id)
            .is_some_and(|unit| unit.kind == UnitKind::FutureNote)
        {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "future note",
                correspondence: "not applicable",
            });
            continue;
        }
        if inventory.units.get(id).is_some_and(|unit| unit.draft) {
            report.statuses.push(UnitStatus {
                unit: id.clone(),
                evidence: "draft",
                correspondence: "not asserted",
            });
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("draft unit {id} requires formalization"),
                details: vec![
                    "draft status preserves the unit's semantic kind but cannot count as completed correspondence evidence".into(),
                ],
            });
            continue;
        }
        let mut current = BTreeSet::new();
        let mut stale = Vec::new();
        for bundle in bundles.values().filter(|bundle| &bundle.unit == id) {
            // Historical bundles compare with one independently derived current
            // manifest. Re-reading all sources for each past review made the
            // ordinary evidence test grow with the entire review history.
            let errors = validate_bundle_against(inventory, bundle, required.clone())?;
            if errors.is_empty() {
                current.insert(bundle.digest.clone());
            } else {
                stale.extend(errors);
            }
        }
        let empty_records = BTreeMap::new();
        let records = all_records.get(id).unwrap_or(&empty_records);
        let superseded: BTreeSet<_> = records
            .values()
            .flat_map(|review| review.supersedes.iter().cloned())
            .collect();
        let stale_active = records.iter().any(|(digest, review)| {
            !superseded.contains(digest) && !current.contains(&review.bundle)
        });
        let active: Vec<_> = records
            .iter()
            .filter(|(digest, review)| {
                current.contains(&review.bundle) && !superseded.contains(*digest)
            })
            .map(|(_, review)| review)
            .collect();
        // Cross-review order decisions may rely only on an entirely current,
        // positive subject; a conflicting or stale active record blocks it.
        if !stale_active
            && !active.is_empty()
            && active
                .iter()
                .all(|review| review.conclusion == Conclusion::Corresponds)
        {
            current_active.insert(
                id.clone(),
                active.iter().map(|review| (*review).clone()).collect(),
            );
        }
        let evidence = if stale_active {
            "stale"
        } else if !current.is_empty() {
            "current"
        } else if !stale.is_empty() {
            "stale"
        } else {
            "missing"
        };
        let correspondence = if stale_active {
            "stale decision"
        } else if active.is_empty() {
            "missing"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Mismatch)
        {
            "mismatch"
        } else if active
            .iter()
            .any(|review| review.conclusion == Conclusion::Inconclusive)
        {
            "inconclusive"
        } else {
            "corresponds"
        };
        report.statuses.push(UnitStatus {
            unit: id.clone(),
            evidence,
            correspondence,
        });
        if correspondence != "corresponds" {
            let mut details = if evidence == "stale" {
                stale
            } else {
                Vec::new()
            };
            details.sort();
            details.dedup();
            if evidence == "current" && active.is_empty() {
                details.push("preparing a bundle does not record a completed review".into());
            }
            report.issues.push(Issue {
                unit: Some(id.clone()),
                message: format!("{evidence} evidence for {id}: correspondence {correspondence}"),
                details,
            });
        }
    }
    for (unit, message) in link_audit::cross_validate(&audits, &current_active) {
        report.issues.push(Issue {
            unit: Some(unit),
            message,
            details: Vec::new(),
        });
    }
    Ok(report)
}
}
mdbook-dada/tests/mechanical.rs:execution_preserves_success_failure_and_non_utf8_output
#![allow(unused)]
fn main() {
#[test]
fn execution_preserves_success_failure_and_non_utf8_output() {
    let successful = Fixture::new("printf done; printf diagnostic >&2");
    let (_, receipt) = successful.run();
    assert!(receipt.succeeded());
    let output = receipt.command.unwrap();
    assert_eq!(output.stdout, b"done");
    assert_eq!(output.stderr, b"diagnostic");
    assert_eq!(output.exit_code, Some(0));
    assert_eq!(successful.state(), "recorded pass");

    let failing = Fixture::new("printf '\\377\\000ok'; printf '\\376err' >&2; exit 7");
    let (path, receipt) = failing.run();
    assert!(path.is_file(), "failure must leave an inspectable receipt");
    assert!(!receipt.succeeded());
    let output = receipt.command.unwrap();
    assert_eq!(output.stdout, [255, 0, b'o', b'k']);
    assert_eq!(output.stderr, [254, b'e', b'r', b'r']);
    assert_eq!(output.exit_code, Some(7));
    assert_eq!(failing.state(), "recorded failure");
}
}
mdbook-dada/tests/mechanical.rs:execution_retains_source_mutations_additions_and_deletions
#![allow(unused)]
fn main() {
#[test]
fn execution_retains_source_mutations_additions_and_deletions() {
    for script in [
        "printf changed > sources/model.txt",
        "printf added > sources/added.txt",
        "rm sources/model.txt",
    ] {
        let fixture = Fixture::new(script);
        let (_, receipt) = fixture.run();
        assert_eq!(receipt.command.as_ref().unwrap().exit_code, Some(0));
        assert!(!receipt.succeeded(), "input changes escaped: {script}");
        assert_ne!(receipt.after.as_ref(), Some(&receipt.before));
        assert_eq!(fixture.state(), "stale");
    }
}
}
mdbook-dada/tests/mechanical.rs:failed_after_snapshot_and_launch_failures_are_retained
#![allow(unused)]
fn main() {
#[test]
fn failed_after_snapshot_and_launch_failures_are_retained() {
    let deleted = Fixture::new("rm sources/model.txt");
    let mut check = deleted.check();
    check.inputs = vec!["sources/model.txt".into()];
    deleted.configure(check);
    let (_, receipt) = deleted.run();
    assert!(receipt.after.is_none());
    assert!(receipt.after_error.is_some());
    assert!(!receipt.succeeded());
    assert_eq!(mechanical::records(&deleted.0).unwrap().len(), 1);

    let missing_command = Fixture::new("exit 0");
    let mut check = missing_command.check();
    check.command = vec![missing_command
        .0
        .join("absent-program")
        .display()
        .to_string()];
    missing_command.configure(check);
    let (_, receipt) = missing_command.run();
    assert!(receipt.command.unwrap().launch_error.is_some());
    assert_eq!(missing_command.state(), "recorded failure");

    let failed_version = Fixture::new("touch should-not-run");
    let mut check = failed_version.check();
    check.version = vec!["sh".into(), "-c".into(), "exit 3".into()];
    failed_version.configure(check);
    let (_, receipt) = failed_version.run();
    assert!(receipt.command.is_none());
    assert_eq!(receipt.version_before.exit_code, Some(3));
    assert!(!failed_version.0.join("should-not-run").exists());
}
}
mdbook-dada/tests/mechanical.rs:status_and_record_validation_never_execute_profile_commands
#![allow(unused)]
fn main() {
#[test]
fn status_and_record_validation_never_execute_profile_commands() {
    let fixture = Fixture::new("printf called >> invocations");
    assert_eq!(fixture.state(), "not recorded");
    assert!(!fixture.0.join("invocations").exists());
    fixture.run();
    for _ in 0..3 {
        assert_eq!(fixture.state(), "recorded pass");
        assert_eq!(mechanical::records(&fixture.0).unwrap().len(), 1);
    }
    assert_eq!(fs::read(fixture.0.join("invocations")).unwrap(), b"called");
}
}
mdbook-dada/tests/mechanical.rs:source_or_profile_changes_stale_receipts_without_corrupting_history
#![allow(unused)]
fn main() {
#[test]
fn source_or_profile_changes_stale_receipts_without_corrupting_history() {
    let fixture = Fixture::new("exit 0");
    let (path, _) = fixture.run();
    fixture.write("sources/model.txt", "changed\n");
    assert_eq!(fixture.state(), "stale");
    assert!(mechanical::load(&path).unwrap().succeeded());
    fixture.write("sources/model.txt", "original source\n");
    let mut check = fixture.check();
    check.description.push_str(" with revised scope");
    fixture.configure(check);
    assert_eq!(fixture.state(), "stale");
    assert_eq!(mechanical::records(&fixture.0).unwrap().len(), 1);
}
}
mdbook-dada/tests/mechanical.rs:later_failures_and_tied_failures_cannot_be_hidden_by_success
#![allow(unused)]
fn main() {
#[test]
fn later_failures_and_tied_failures_cannot_be_hidden_by_success() {
    let fixture = Fixture::new("if test -f fail-now; then exit 8; fi");
    let (pass_path, mut passed) = fixture.run();
    fixture.write("fail-now", "");
    let (fail_path, mut failed) = fixture.run();
    fs::remove_file(pass_path).unwrap();
    fs::remove_file(fail_path).unwrap();

    // Give the failed fixture receipt a strictly later timestamp first.
    failed.finished_unix_ms = passed.finished_unix_ms + 1;
    failed.started_unix_ms = passed.started_unix_ms;
    let fail_path = save_repacked(&fixture.0, failed.clone());
    let pass_path = save_repacked(&fixture.0, passed.clone());
    assert_eq!(fixture.state(), "recorded failure");
    fs::remove_file(pass_path).unwrap();
    fs::remove_file(fail_path).unwrap();

    // Timestamps are not unique. Choose a success digest that sorts after the
    // failure, so digest tie-breaking cannot accidentally hide that failure.
    passed.finished_unix_ms = failed.finished_unix_ms;
    repack(&mut failed);
    for nonce in 0..10_000 {
        passed.host_os = format!("synthetic-test-host-{nonce}");
        repack(&mut passed);
        if passed.digest > failed.digest {
            break;
        }
    }
    assert!(passed.digest > failed.digest);
    let failed_digest = failed.digest.clone();
    save_repacked(&fixture.0, passed);
    save_repacked(&fixture.0, failed);
    assert_eq!(fixture.state(), "recorded failure");
    assert_eq!(
        mechanical::status(&fixture.0).unwrap()[0].receipt,
        Some(failed_digest),
        "a failure status must identify the failing receipt"
    );
}
}
mdbook-dada/tests/mechanical.rs:receipt_validation_rejects_tampering_and_profile_substitution
#![allow(unused)]
fn main() {
#[test]
fn receipt_validation_rejects_tampering_and_profile_substitution() {
    let fixture = Fixture::new("exit 0");
    let (path, receipt) = fixture.run();
    let mut tampered = receipt.clone();
    tampered.command.as_mut().unwrap().stdout.push(42);
    fs::write(&path, serde_json::to_vec(&tampered).unwrap()).unwrap();
    assert!(mechanical::load(&path).is_err());
    fs::remove_file(path).unwrap();

    let mut substituted = receipt;
    substituted.check.command = vec!["made-up-check".into()];
    let path = save_repacked(&fixture.0, substituted);
    assert!(
        mechanical::load(&path).is_err(),
        "embedded check must agree with snapshotted configuration"
    );
}
}
mdbook-dada/tests/mechanical.rs:receipt_validation_requires_selected_sources_and_runner_snapshots
#![allow(unused)]
fn main() {
#[test]
fn receipt_validation_requires_selected_sources_and_runner_snapshots() {
    let fixture = Fixture::new("exit 0");
    let (original_path, receipt) = fixture.run();
    fs::remove_file(original_path).unwrap();
    for missing in [
        "sources/model.txt",
        "mdbook-dada/src/lib.rs",
        "spec-checks.json",
    ] {
        let mut reduced = receipt.clone();
        reduced.before.retain(|input| input.path != missing);
        reduced
            .after
            .as_mut()
            .unwrap()
            .retain(|input| input.path != missing);
        let path = save_repacked(&fixture.0, reduced);
        assert!(
            mechanical::load(&path).is_err(),
            "a self-consistently rehashed missing input escaped: {missing}"
        );
        fs::remove_file(path).unwrap();
    }
}
}
mdbook-dada/tests/mechanical.rs:snapshots_record_empty_directories_and_ignore_generated_outputs
#![allow(unused)]
fn main() {
#[test]
fn snapshots_record_empty_directories_and_ignore_generated_outputs() {
    let fixture = Fixture::new("exit 0");
    fs::create_dir(fixture.0.join("sources/empty")).unwrap();
    let original = mechanical::snapshot(&fixture.0, &fixture.check()).unwrap();
    assert!(original
        .iter()
        .any(|input| input.key == "directory:sources/empty"));
    for output in [
        "sources/.lake/cache",
        "sources/target/debug/output",
        "sources/book/page.html",
        "sources/evidence/record.json",
    ] {
        fixture.write(output, "generated");
    }
    assert_eq!(
        original,
        mechanical::snapshot(&fixture.0, &fixture.check()).unwrap()
    );
    let mut check = fixture.check();
    check.inputs = vec!["sources/target".into()];
    assert!(mechanical::snapshot(&fixture.0, &check).is_err());
}
}
mdbook-dada/tests/mechanical.rs:snapshots_and_records_reject_symbolic_links
#![allow(unused)]
fn main() {
#[test]
fn snapshots_and_records_reject_symbolic_links() {
    use std::os::unix::fs::symlink;

    let fixture = Fixture::new("exit 0");
    symlink("model.txt", fixture.0.join("sources/alias.txt")).unwrap();
    assert!(mechanical::snapshot(&fixture.0, &fixture.check()).is_err());
    let mut selected_link = fixture.check();
    selected_link.inputs = vec!["sources/alias.txt".into()];
    assert!(mechanical::snapshot(&fixture.0, &selected_link).is_err());
    fs::remove_file(fixture.0.join("sources/alias.txt")).unwrap();
    let (path, _) = fixture.run();
    symlink(path, fixture.0.join("evidence/executions/alias.json")).unwrap();
    assert!(mechanical::records(&fixture.0).is_err());
}
}
mdbook-dada/tests/evidence_validation.rs:workspace_validation_rejects_malformed_execution_receipts
#![allow(unused)]
fn main() {
#[test]
fn workspace_validation_rejects_malformed_execution_receipts() {
    let fixture = Fixture::new();
    fixture.complete_reviews();
    fixture.write("evidence/executions/invalid.json", "{}");
    let report = evidence::check(&fixture.inventory()).unwrap();
    assert!(!report.is_ok());
    assert!(report
        .issues
        .iter()
        .any(|issue| issue.message == "malformed mechanical execution evidence"));
}
}