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

requirements.definitions.inputs

Requirements index · View definition

evidence Valid

Requirement

Evidence inputs MAY have a definition form containing exactly definition and text. definition MUST identify one named definition; text MUST contain its complete raw fenced declaration as source lines, including its phrase option and explanatory body.

Validation MUST reject missing definitions and changed snapshot text, identifying the definition and showing a compact diff when available. Moving an unchanged definition within its chapter MUST NOT invalidate its snapshot. Evidence displays MUST show the definition name, current source location, and recorded text.

Rationale

The reviewed tests cover each obligation in requirements.definitions.inputs.

I did not read declaration or the implementation. That declaration returns the complete fenced declaration is inferred from how record and the diff assertion use it.

Form: exactly definition and text

  • tests/definitions.rs#fn[definition_schema_deletion_and_literal_references_are_checked] adds an unexpected field to a definition input. It asserts an “unexpected field” error.
  • tests/definitions.rs#fn[changed_definition_snapshots_show_a_compact_diff_and_text_is_required] removes text, sets it to an empty array, and sets it to a string. It asserts each is rejected with an error from the evidence file that mentions text.

definition identifies one named definition

  • The same test adds definition inputs naming a requirement (rules.ready) and an example (rules.case). It asserts a “no matching named definition” error for each.
  • src/evidence.rs#mod[tests]/fn[configuration_and_dependency_failures_do_not_stop_later_checks] uses a nonexistent rules.gone. It asserts a “no matching named definition” error for that input.
  • tests/definitions.rs#fn[cyclic_dependencies_are_required_once_and_changes_require_review] removes one definition input and duplicates another. It asserts the “found 0” and “found 2” errors.

text holds the complete raw declaration, including the phrase option and body

  • The helper definition builds text from declaration. It is recorded by capture and validated cleanly.
  • Changing only the :phrase: line of glossary.b is detected as “input text changed” for that definition.
  • Changing the body of glossary.a is also detected.

Reject missing definitions and changed snapshot text

  • Deleting md/glossary.md yields a “no matching named definition” error naming glossary.a.
  • Each changed-text error names the definition.
  • The compact diff is asserted exactly. The test expects only the changed body line, as a removal line followed by an addition line.

Moving an unchanged definition must not invalidate the snapshot

  • cyclic_dependencies_are_required_once_and_changes_require_review prepends blank lines to glossary.md. This shifts every definition’s location. It asserts validation stays error-free.
  • The test shifts locations rather than reordering definitions. For a snapshot that stores only text, that is the distinction that matters, so I do not count it as a gap.

Evidence displays show name, current source location, and recorded text

  • src/index.rs#mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group] checks the rendered detail page for a definition input:
    • It asserts the definition rules.term label.
    • It asserts the location line for rules.term with its file and inclusive range.
    • It asserts the recorded text in a markdown block, and asserts their order.

All three tests carry the {test} reference to the requirement.

Inputs

Tests

Input 2: outline src/evidence.rs mod[tests]/fn[configuration_and_dependency_failures_do_not_stop_later_checks]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[configuration_and_dependency_failures_do_not_stop_later_checks]
  • Kind: fn
  • src/evidence.rs:2977–3068
    // {test}`requirements.ci.errors`
    // {test}`requirements.definitions.inputs`
    #[test]
    fn configuration_and_dependency_failures_do_not_stop_later_checks() {
        let temp = fixture();
        fs::write(
            temp.path().join("md/rules.md"),
            ":::{req} ready\nUse {term}`rules.missing` and {term}`rules.absent`.\n:::\n\n:::{req} other\nOther.\n:::\n",
        )
        .unwrap();
        fs::write(
            temp.path().join("evidence/rules.ready.json"),
            json!({
                "requirement": "Use {term}`rules.missing` and {term}`rules.absent`.",
                "determination": true,
                "rationale": "Examined.",
                "inputs": [{"definition": "rules.gone", "text": ["x"]}]
            })
            .to_string(),
        )
        .unwrap();
        // Every unresolvable term is reported, and the record's other checks
        // and other records' checks still run.
        let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
        for detail in [
            "evidence/rules.ready.json: definition dependencies: term rules.absent: no matching named definition",
            "evidence/rules.ready.json: definition dependencies: term rules.missing: no matching named definition",
            "evidence/rules.ready.json: inputs[0]: rules.gone: no matching named definition",
            "evidence/rules.other.json: missing for requirement",
        ] {
            assert!(errors.contains(detail), "missing {detail:?} in:\n{errors}");
        }

        // Invalid workspace and book configuration are each reported, and
        // checks that do not depend on them still run.
        fs::write(temp.path().join("habeas.toml"), "version = 2\n").unwrap();
        fs::write(temp.path().join("book.toml"), "[book]\nsrc = 'md'\n[").unwrap();
        fs::write(temp.path().join("evidence/ghost.json"), "{").unwrap();
        let unknown = "{impl}`missing.name`".to_owned();
        fs::write(temp.path().join("src/main.rs"), format!("// {unknown}\n")).unwrap();
        let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
        for detail in [
            "habeas.toml: version: expected version = 1".to_owned(),
            "book.toml: invalid TOML".to_owned(),
            "evidence/ghost.json: invalid JSON".to_owned(),
            format!("src/main.rs:1: {unknown} has no matching requirement"),
        ] {
            assert!(errors.contains(&detail), "missing {detail:?} in:\n{errors}");
        }

        assert_eq!(
            errors
                .matches("habeas.toml: version: expected version = 1")
                .count(),
            1,
            "{errors}"
        );
        assert_eq!(
            errors.matches("book.toml: invalid TOML").count(),
            1,
            "{errors}"
        );

        // Coverage setup and coverage-history configuration failures must
        // also leave independent later evidence and reference checks running.
        fs::write(temp.path().join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
        let (path, valid) = crate::execution_coverage::configure(temp.path()).unwrap();
        for (configuration, nextest, expected) in [
            ("version = 1\n", "[", ".config/nextest.toml"),
            (
                "version = 1\n[coverage]\nreauthorings = 0\n",
                "",
                "coverage.reauthorings",
            ),
        ] {
            fs::write(temp.path().join("habeas.toml"), configuration).unwrap();
            fs::write(&path, if nextest.is_empty() { &valid } else { nextest }).unwrap();
            let errors = validate_repository(temp.path()).unwrap().errors;
            for detail in [
                expected.to_owned(),
                "evidence/ghost.json: invalid JSON".to_owned(),
                format!("src/main.rs:1: {unknown} has no matching requirement"),
            ] {
                assert!(
                    errors.iter().any(|error| error.contains(&detail)),
                    "missing {detail:?} in:\n{errors:?}"
                );
            }
            let unique = errors.iter().collect::<std::collections::BTreeSet<_>>();
            assert_eq!(errors.len(), unique.len(), "{errors:?}");
        }
    }
Input 3: outline src/index.rs mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group]
  • File: src/index.rs
  • Selector: mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group]
  • Kind: fn
  • src/index.rs:2210–2314
    // {test}`requirements.index.detail_format`
    // {test}`requirements.definitions.inputs`
    // {test}`requirements.ci.requirements_inputs`
    // {test}`requirements.index.source_links`
    #[test]
    fn detail_page_shows_recorded_text_locations_and_first_matching_group() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        for dir in ["md", "evidence", "src"] {
            fs::create_dir_all(root.join(dir)).unwrap();
        }
        fs::write(root.join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
        let source = ":::{req} ready\nReady uses {term}`rules.term`.\n:::\n\n:::{req} base\nBase.\n:::\n\n:::{definition} term\n:phrase: term\n\nA term.\n:::\n".to_owned();
        fs::write(root.join("md/rules.md"), &source).unwrap();
        fs::write(
            root.join("src/lib.rs"),
            "// {impl}`rules.ready`\n// {test}`rules.ready`\nfn both() {}\n",
        )
        .unwrap();
        let inputs = json!([
            {"requirements": "rules.*", "matches": ["rules.base", "rules.ready"], "text": ["recorded base", "", "recorded ready"]},
            {"definition": "rules.term", "text": ["recorded term"]},
            {"requirements": "missing.*", "matches": ["missing.x"], "text": ["recorded missing"]},
            crate::inputs::outline_input(root, "src/lib.rs", "fn[both]").unwrap(),
        ]);
        fs::write(
            root.join("evidence/rules.ready.json"),
            json!({
                "requirement": "Ready uses {term}`rules.term`.",
                "determination": true,
                "rationale": "Checked.",
                "inputs": inputs,
            })
            .to_string(),
        )
        .unwrap();

        let mut book = Book::new();
        book.push_item(Chapter::new("Rules", source, "rules.md", Vec::new()));
        book.push_item(Chapter::new(
            "Index",
            ":::{requirements-index}\n:::\n".into(),
            "requirements-index.md",
            Vec::new(),
        ));
        preprocess_book(&mut book, root).unwrap();
        let page = book
            .chapters()
            .find(|chapter| chapter.name == "rules.ready")
            .unwrap();
        let content = &page.content;
        let position = |needle: &str| {
            content
                .find(needle)
                .unwrap_or_else(|| panic!("missing {needle:?} in:\n{content}"))
        };

        // The state badge has alt text naming the state.
        let badge =
            position("<img class=\"habeas-shield\" src=\"https://img.shields.io/badge/evidence-");
        assert!(
            content[badge..].contains("alt=\"evidence Invalid\""),
            "{content}"
        );

        // A requirements input lists each match's name, file, and inclusive
        // range, then its recorded text.
        let selection = position("<code>requirements selection rules.*</code>");
        let base = position("- <code>rules.base</code>: <code>md/rules.md:5–7</code>\n");
        let ready = position("- <code>rules.ready</code>: <code>md/rules.md:1–3</code>\n");
        let recorded = position("```markdown\nrecorded base\n\nrecorded ready\n```");
        assert!(
            selection < base && base < ready && ready < recorded,
            "{content}"
        );

        // A definition input shows its name, location, and recorded text.
        let definition = position("<code>definition rules.term</code>");
        let location = position("- <code>rules.term</code>: <code>md/rules.md:9–13</code>\n");
        let text = position("```markdown\nrecorded term\n```");
        assert!(definition < location && location < text, "{content}");
        let referenced = position("style=\"display: inline\">Referenced definitions</h3>");
        let other = position("style=\"display: inline\">Other sources</h3>");
        assert!(referenced < definition && definition < other, "{content}");

        // An unresolved selector is reported and its recorded text kept.
        let unresolved = position("Unresolved selector: ");
        let missing = position("```markdown\nrecorded missing\n```");
        assert!(unresolved < missing, "{content}");

        // A source reached by both an implementation and a test edge appears
        // once, in the first group that applies.
        let implementation = position("style=\"display: inline\">Implementation</h3>");
        let both = position("<code>outline src/lib.rs fn[both]</code>");
        assert!(implementation < both, "{content}");
        assert!(
            !content.contains("style=\"display: inline\">Tests</h3>"),
            "{content}"
        );
        assert_eq!(
            content.matches("outline src/lib.rs fn[both]").count(),
            1,
            "{content}"
        );
    }
Input 4: outline tests/definitions.rs fn[cyclic_dependencies_are_required_once_and_changes_require_review]
// {test}`requirements.definitions.transitive_cycle`
// {test}`requirements.definitions.reassessment`
// {test}`requirements.definitions.dependencies`
// {test}`requirements.definitions.inputs`
#[test]
fn cyclic_dependencies_are_required_once_and_changes_require_review() {
    let temp = fixture();
    let root = temp.path();
    capture(root);
    let path = root.join("evidence/rules.ready.json");
    approve(&path);
    let report = validate_repository(root).unwrap();
    assert!(report.errors.is_empty(), "{:?}", report.errors);
    let before = fs::read(&path).unwrap();

    let glossary = root.join("md/glossary.md");
    let original = fs::read_to_string(&glossary).unwrap();
    fs::write(&glossary, format!("\n\n{original}")).unwrap();
    assert!(validate_repository(root).unwrap().errors.is_empty());
    for (changed, definition) in [
        (
            original.replace(":phrase: beta", ":phrase: new beta"),
            "glossary.b",
        ),
        (
            original
                .replace("See TERM", "Read TERM")
                .replace("See {term}", "Read {term}"),
            "glossary.a",
        ),
        (
            original.replace("See {term}`glossary.a`.", "Read {term}`glossary.a`."),
            "glossary.b",
        ),
    ] {
        fs::write(&glossary, changed).unwrap();
        let report = validate_repository(root).unwrap();
        assert!(
            report
                .errors
                .iter()
                .any(|e| e.contains("input text changed") && e.contains(definition)),
            "{:?}",
            report.errors
        );
        assert_eq!(before, fs::read(&path).unwrap());
    }
    // Reassessment records the current snapshots.
    capture(root);
    let refreshed: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
    approve(&path);
    assert!(validate_repository(root).unwrap().errors.is_empty());

    let mut missing = refreshed.clone();
    missing["inputs"]
        .as_array_mut()
        .unwrap()
        .retain(|i| i.get("definition") != Some(&json!("glossary.b")));
    fs::write(&path, missing.to_string()).unwrap();
    assert!(
        validate_repository(root)
            .unwrap()
            .errors
            .iter()
            .any(|e| e.contains("glossary.b, found 0"))
    );
    let mut duplicate = refreshed;
    let input = duplicate["inputs"][1].clone();
    duplicate["inputs"].as_array_mut().unwrap().push(input);
    fs::write(&path, duplicate.to_string()).unwrap();
    assert!(
        validate_repository(root)
            .unwrap()
            .errors
            .iter()
            .any(|e| e.contains("found 2"))
    );
}
Input 5: outline tests/definitions.rs fn[changed_definition_snapshots_show_a_compact_diff_and_text_is_required]
  • File: tests/definitions.rs
  • Selector: fn[changed_definition_snapshots_show_a_compact_diff_and_text_is_required]
  • Kind: fn
  • tests/definitions.rs:668–753
// {test}`requirements.definitions.inputs`
#[test]
fn changed_definition_snapshots_show_a_compact_diff_and_text_is_required() {
    let temp = fixture();
    let root = temp.path();
    capture(root);
    let path = root.join("evidence/rules.ready.json");
    approve(&path);
    assert!(validate_repository(root).unwrap().errors.is_empty());
    let glossary = root.join("md/glossary.md");
    let original = fs::read_to_string(&glossary).unwrap();
    fs::write(
        &glossary,
        original.replace("See {term}`glossary.b`.", "See {term}`glossary.b` again."),
    )
    .unwrap();
    let errors = validate_repository(root).unwrap().errors;
    let changed = errors
        .iter()
        .find(|error| error.contains("input text changed") && error.contains("glossary.a"))
        .unwrap_or_else(|| panic!("{errors:?}"));
    // Only the changed body line is shown, as a removal and an addition.
    let diff: Vec<_> = changed.lines().skip(1).collect();
    assert_eq!(
        diff,
        [
            "- See {term}`glossary.b`.",
            "+ See {term}`glossary.b` again."
        ],
        "{changed}"
    );
    fs::write(&glossary, &original).unwrap();

    // A definition input must carry a nonempty text array.
    let record: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
    for text in [None, Some(json!([])), Some(json!("not lines"))] {
        let mut broken = record.clone();
        let input = broken["inputs"]
            .as_array_mut()
            .unwrap()
            .iter_mut()
            .find(|input| input["definition"] == "glossary.a")
            .unwrap();
        match &text {
            None => {
                input.as_object_mut().unwrap().remove("text");
            }
            Some(text) => input["text"] = text.clone(),
        }
        fs::write(&path, broken.to_string()).unwrap();
        let errors = validate_repository(root).unwrap().errors;
        assert!(
            errors
                .iter()
                .any(|error| error.starts_with("evidence/rules.ready.json")
                    && error.contains("text")),
            "{text:?}: {errors:?}"
        );
    }
    let rules = root.join("md/rules.md");
    fs::write(
        &rules,
        format!(
            "{}\n:::{{example}} case\nAn example. {{cite}}`rules.ready`\n:::\n",
            fs::read_to_string(&rules).unwrap()
        ),
    )
    .unwrap();
    for name in ["rules.ready", "rules.case"] {
        let mut broken = record.clone();
        broken["inputs"]
            .as_array_mut()
            .unwrap()
            .push(definition(root, name));
        fs::write(&path, broken.to_string()).unwrap();
        let errors = validate_repository(root).unwrap().errors;
        assert!(
            errors
                .iter()
                .any(|error| error.starts_with("evidence/rules.ready.json")
                    && error.contains(name)
                    && error.contains("no matching named definition")),
            "{name}: {errors:?}"
        );
    }
}
Input 6: outline tests/definitions.rs fn[definition_schema_deletion_and_literal_references_are_checked]
// {test}`requirements.definitions.inputs`
// {test}`requirements.definitions.references`
// {test}`requirements.definitions.dependencies`
#[test]
fn definition_schema_deletion_and_literal_references_are_checked() {
    let temp = fixture();
    let root = temp.path();
    capture(root);
    let path = root.join("evidence/rules.ready.json");
    approve(&path);
    let original: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
    let mut invalid = original.clone();
    invalid["inputs"][1]["unexpected"] = json!(true);
    fs::write(&path, invalid.to_string()).unwrap();
    assert!(
        validate_repository(root)
            .unwrap()
            .errors
            .iter()
            .any(|e| e.contains("unexpected field"))
    );
    fs::write(&path, original.to_string()).unwrap();
    fs::remove_file(root.join("md/glossary.md")).unwrap();
    assert!(
        validate_repository(root)
            .unwrap()
            .errors
            .iter()
            .any(|e| e.contains("glossary.a") && e.contains("no matching named definition"))
    );

    let temp = fixture();
    let root = temp.path();
    let body = "Literal `{term}`missing.name``.\n\n```text\n{term}`missing.name`\n```\n\n\\{term}`missing.name`";
    fs::write(
        root.join("md/rules.md"),
        format!(":::{{req}} ready\n{body}\n:::\n"),
    )
    .unwrap();
    // Literal and escaped references require no definition inputs.
    let path = record(
        root,
        "rules.ready",
        vec![requirements(root, "rules.*", &["rules.ready"])],
    );
    approve(&path);
    let report = validate_repository(root).unwrap();
    assert!(report.errors.is_empty(), "{:?}", report.errors);
}

Other sources

Input 1: requirements selection requirements.definitions.inputs
:::{req} inputs
Evidence inputs MAY have a definition form containing exactly `definition` and `text`. `definition` MUST identify one named definition; `text` MUST contain its complete raw fenced declaration as source lines, including its phrase option and explanatory body.

Validation MUST reject missing definitions and changed snapshot text, identifying the definition and showing a compact diff when available. Moving an unchanged definition within its chapter MUST NOT invalidate its snapshot. Evidence displays MUST show the definition name, current source location, and recorded text.
:::
Input 7: outline tests/definitions.rs fn[fixture]
fn fixture() -> TempDir {
    let temp = tempfile::tempdir().unwrap();
    fs::create_dir_all(temp.path().join("md")).unwrap();
    fs::create_dir_all(temp.path().join("src")).unwrap();
    fs::create_dir_all(temp.path().join("evidence")).unwrap();
    fs::write(temp.path().join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
    fs::write(
        temp.path().join("Cargo.toml"),
        "[package]\nname = 'fixture'\n",
    )
    .unwrap();
    fs::write(temp.path().join("md/SUMMARY.md"), "# Summary\n").unwrap();
    fs::write(
        temp.path().join("md/rules.md"),
        ":::{req} ready\nUse {term}`glossary.a`.\n:::\n",
    )
    .unwrap();
    fs::write(temp.path().join("md/glossary.md"), ":::{definition} a\n:phrase: alpha\n\nSee {term}`glossary.b`.\n:::\n\n:::{definition} b\n:phrase: beta\n\nSee {term}`glossary.a`.\n:::\n").unwrap();
    common::coverage_setup(temp.path());
    temp
}
Input 8: outline tests/definitions.rs fn[definition]
fn definition(root: &Path, name: &str) -> Value {
    json!({ "definition": name, "text": declaration(root, name) })
}
Input 9: outline tests/definitions.rs fn[record]
// {cite}`habeas:util`
/// Writes a pending evidence record for the requirement or example `name`
/// containing exactly `inputs`, and returns its path.
fn record(root: &Path, name: &str, inputs: Vec<Value>) -> PathBuf {
    let lines = declaration(root, name);
    let kind = if lines[0].starts_with(":::{example}") {
        "example"
    } else {
        "requirement"
    };
    let body = lines[1..lines.len() - 1].join("\n");
    let path = root.join(format!("evidence/{name}.json"));
    let record = json!({
        kind: body.trim(),
        "determination": false,
        "rationale": "Review pending.",
        "references": habeas::reference_set_digest_for(root, name).unwrap(),
        "inputs": inputs,
    });
    fs::write(&path, serde_json::to_string_pretty(&record).unwrap()).unwrap();
    path
}
Input 10: outline tests/definitions.rs fn[capture]
/// Records the fixture requirement with its selection and the complete
/// definition cycle it depends on.
fn capture(root: &Path) {
    record(
        root,
        "rules.ready",
        vec![
            requirements(root, "rules.*", &["rules.ready"]),
            definition(root, "glossary.a"),
            definition(root, "glossary.b"),
        ],
    );
}