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.references.rust_item_coverage

Requirements index · View definition

evidence Valid

Requirement

During repository validation, Habeas MUST parse every first-party Rust source file: every .rs file among the sources reference discovery considers under cite requirements.references.discovery, except those under the project-root vendor directory. Each explicitly declared function or method, including trait methods and test helpers, and each struct, enum, and union is an item that can be covered. An item is covered when it has a valid {impl}, {cite}, or {test} reference to a defined requirement or named example, or a valid citation of the built-in habeas:util under cite requirements.references.util, in a Rust comment attached to it or within its body; or when its outline node, or an outline node containing it, is recorded with its current hash as an outline input of an evidence record, a citation review, or a site review. Outline inputs recorded from selected search snippets under cite requirements.authoring.finish_search.inputs MUST count alongside mandatory inputs and additional reads. Comments belong to items under cite requirements.references.outline_comments; a comment before a field, variant, or attribute inside an item belongs to that item. A named example MUST reference a requirement under cite requirements.examples.definition. A reference in a string literal, on an enclosing module or impl block, or only in an evidence input MUST NOT count for the items it encloses. Habeas MUST report a Rust parse failure instead of silently skipping the file. Only cite requirements.references.coverage.tests and cite requirements.references.coverage.examples make an uncovered item a validation error; other items without recent coverage are warned about under cite requirements.references.coverage.report.

Rationale

I judge the tests adequate. Each obligation in requirements.references.rust_item_coverage maps to at least one test with assertions that enforce the stated outcome.

  • Parsing every first-party .rs file, with only the project-root vendor excluded.
    • src/rust_coverage.rs#mod[tests]/fn[reports_all_files_and_parse_failures] checks that src/lib.rs, src/evidence/check.rs and tests/broken.rs are scanned.
    • It checks that target, evidence, .git, book and root vendor are skipped. It checks that src/vendor and src/book are still covered, so the exclusion applies only at the project root.
    • tests/references.rs#fn[disallowed_paths_are_skipped_and_projects_outside_git_scan_every_file] and fn[untracked_sources_are_not_validated_until_staged_and_status_lists_them] check discovery. They cover Git-index versus non-Git behaviour, configured disallows, and vendor files whose references are found but whose items are not covered.
  • Reporting a parse failure instead of skipping the file. The broken.rs case in fn[reports_all_files_and_parse_failures] asserts a “cannot parse Rust source” error. tests/authoring_batch.rs#fn[discovery_errors_fail_before_configuration_or_inference] asserts the same through the CLI.
  • Which items can be covered.
    • fn[checks_trait_test_helper_and_nested_functions_separately] covers trait methods, test helpers, nested functions and #[test] functions.
    • fn[finds_uncited_functions_without_using_enclosing_or_string_references] covers impl methods.
    • fn[structs_enums_and_unions_need_references_attached_or_inside] covers structs, enums and unions, including a nested struct.
    • It also checks that a reference before a field or variant inside an item covers that item.
  • What counts as a valid reference.
    • fn[an_example_counts_only_when_it_references_a_requirement] checks that an example counts only if it references a requirement. It rejects an orphan example, an example that cites only another example, one that cites only a term, and {impl} of a term.
    • fn[a_test_reference_to_an_example_counts_only_when_it_references_a_requirement] checks the same for #[test] functions, so an uncovered test function is reported.
    • Unknown names are rejected in fn[finds_uncited_functions_without_using_enclosing_or_string_references].
    • tests/references.rs#fn[fenced_references_in_comments_and_built_in_rules_are_validated] and fn[habeas_util_citations_cover_their_item_without_a_citation_review] check that habeas:util covers its item only when cited. A fenced citation covers its item. {impl} or {test} of habeas:util is an error and does not cover. Unknown built-ins do not cover.
    • fn[a_fixme_does_not_count_as_an_items_reference] checks that a {fixme} does not cover its item.
  • Comment placement and what does not count.
    • fn[finds_uncited_functions_without_using_enclosing_or_string_references] checks that a reference on an enclosing module or impl block does not count. It checks that references inside string and raw-string literals do not count.
    • It checks that a comment run belongs to the next item across a blank line. It checks that a trailing comment forms its own run and does not cover the following item. It checks that an inner doc comment belongs to its container and does not cover a following function. An outer doc comment covers the function it precedes.
    • A reference inside a body counts.
    • fn[locates_functions_after_unicode_text] adds the unicode and block-comment positioning cases.
    • The evidence/fixture.rs file in fn[reports_all_files_and_parse_failures] is skipped. This covers the clause about evidence inputs not counting as references.
  • Coverage by outline inputs with the current hash, including containing nodes.
    • fn[a_read_covers_an_item_only_with_its_current_hash] covers the matching and stale hash cases.
    • fn[a_containing_read_covers_nested_items_only_with_its_current_hash] checks that a containing impl read covers its method. It checks that a stale hash does not cover, and that an unrelated item or another file is not covered.
    • tests/authoring_cli.rs#fn[replacing_a_record_that_stops_reading_an_item_warns_until_it_is_covered] checks the whole flow through the CLI, from covered to warned to covered by reference.
    • tests/references.rs#fn[items_named_by_recent_evidence_have_recent_coverage_whatever_their_hash] covers an ordinary record, a citation review, and a site review.
    • That integration test accepts a stale hash. The accepted hash comes from requirements.references.coverage.history, which says a recorded hash MUST NOT matter for recent coverage. That requirement governs the warning, and the subject’s “current hash” rule governs being covered. The unit tests check the subject’s rule directly, so the two do not conflict.
  • Error versus warning split. fn[reports_all_files_and_parse_failures] asserts that only the parse failure is an error and that uncovered items go to the warning list. tests/commands.rs#fn[status_preserves_repository_wide_rust_findings_in_every_form] checks the warning count, with detail shown only under --coverage.

The requirement text has no finish_search obligation of its own. That obligation, that selected snippets are recorded as outline inputs, sits in requirements.authoring.finish_search.inputs. Coverage reads those records through the same evidence-record path the tests exercise, so I count it as delegated and report no gap.

Inputs

Tests

Input 10: outline src/rust_coverage.rs mod[tests]/fn[a_read_covers_an_item_only_with_its_current_hash]
    // {test}`requirements.references.rust_item_coverage`
    #[test]
    fn a_read_covers_an_item_only_with_its_current_hash() {
        let source = "fn read() {}\n";
        let outline = crate::outline::parse_with(&crate::outline::RUST_PROFILE, source).unwrap();
        let index = outline
            .nodes
            .iter()
            .position(|node| node.selector == "fn[read]")
            .unwrap();
        let record = |hash: &str| serde_json::json!({"inputs": [{"file": "src/lib.rs", "item": "fn[read]", "hash": hash}]});
        let mut current = super::EvidenceReads::default();
        current.add_record(&record(&outline.nodes[index].structural_hash));
        assert!(current.covers("src/lib.rs", &outline, index));
        let mut stale = super::EvidenceReads::default();
        stale.add_record(&record(&"0".repeat(64)));
        assert!(!stale.covers("src/lib.rs", &outline, index));
    }
Input 11: outline src/rust_coverage.rs mod[tests]/fn[a_containing_read_covers_nested_items_only_with_its_current_hash]
  • File: src/rust_coverage.rs
  • Selector: mod[tests]/fn[a_containing_read_covers_nested_items_only_with_its_current_hash]
  • Kind: fn
  • src/rust_coverage.rs:685–708
    // {test}`requirements.references.rust_item_coverage`
    #[test]
    fn a_containing_read_covers_nested_items_only_with_its_current_hash() {
        let outline = crate::outline::parse_with(
            &crate::outline::RUST_PROFILE,
            "struct Thing; impl Thing { fn run(&self) {} } fn unrelated() {}",
        )
        .unwrap();
        let parent = outline.resolve("impl[Thing]").unwrap();
        let child = outline.resolve("impl[Thing]/fn[run]").unwrap();
        let unrelated = outline.resolve("fn[unrelated]").unwrap();
        for (hash, covered) in [
            (outline.nodes[parent].structural_hash.clone(), true),
            ("0".repeat(64), false),
        ] {
            let mut reads = super::EvidenceReads::default();
            reads.add_record(&serde_json::json!({"inputs": [{
                "file": "src/lib.rs", "item": "impl[Thing]", "hash": hash
            }]}));
            assert_eq!(reads.covers("src/lib.rs", &outline, child), covered);
            assert!(!reads.covers("src/lib.rs", &outline, unrelated));
            assert!(!reads.covers("other.rs", &outline, child));
        }
    }
Input 12: outline src/rust_coverage.rs mod[tests]/fn[a_test_reference_to_an_example_counts_only_when_it_references_a_requirement]
  • File: src/rust_coverage.rs
  • Selector: mod[tests]/fn[a_test_reference_to_an_example_counts_only_when_it_references_a_requirement]
  • Kind: fn
  • src/rust_coverage.rs:740–765
    // {test}`requirements.references.coverage.tests`
    // {test}`requirements.references.rust_item_coverage`
    #[test]
    fn a_test_reference_to_an_example_counts_only_when_it_references_a_requirement() {
        let mut definitions = definitions();
        definitions.insert(
            "requirements.orphan".to_owned(),
            Declaration {
                kind: DefinitionKind::Example,
                text: "No requirement.".to_owned(),
                ..definitions["requirements.case"].clone()
            },
        );
        let source = concat!(
            "// {test}`requirements.case`\n#[test]\nfn traced() {}\n\n",
            "// {test}`requirements.orphan`\n#[test]\nfn orphan() {}\n",
        );
        let outline = crate::outline::parse_with(&crate::outline::RUST_PROFILE, source).unwrap();
        let names: Vec<String> = super::untested_tests(source, &outline, &definitions)
            .into_iter()
            .map(|(_, _, name)| name)
            .collect();
        assert_eq!(names, ["orphan"]);
        let missing = missing_function_references(source, &definitions).unwrap();
        assert_eq!(missing, [(7, "function", "orphan".to_owned())]);
    }
Input 13: outline src/rust_coverage.rs mod[tests]/fn[finds_uncited_functions_without_using_enclosing_or_string_references]
  • File: src/rust_coverage.rs
  • Selector: mod[tests]/fn[finds_uncited_functions_without_using_enclosing_or_string_references]
  • Kind: fn
  • src/rust_coverage.rs:848–913
    // {test}`requirements.references.rust_item_coverage`
    // {test}`requirements.references.outline_comments`
    #[test]
    fn finds_uncited_functions_without_using_enclosing_or_string_references() {
        let source = r##"
// {impl}`requirements.example`
mod feature {
    // {impl}`requirements.example`
    impl Widget {
        fn missing_method() {}
    }

    struct Widget;
    impl Widget {
        // {impl}`requirements.example`
        fn cited_method() {}
    }

    fn containing_string() {
        let _ = "// {impl}`requirements.example`";
        let _ = r#"/* {impl}`requirements.example` */"#;
        let _ = '/';
    }

    fn unknown_reference() {
        // {impl}`requirements.unknown`
    }

    fn body_reference() {
        /* {impl}`requirements.example` */
    }

    // A comment run belongs to the next item even across a blank line.
    // {impl}`requirements.example`

    fn after_blank_line() {}

    // {impl}`requirements.example`
    fn previous() {} // {impl}`requirements.example`
    fn after_trailing_comment() {}
}

mod inner_docs {
    //! {impl}`requirements.example`
    fn after_inner_doc() {}
}

/// {impl}`requirements.example`
fn cited_by_outer_doc() {}
"##;
        let missing = missing_function_references(source, &definitions()).unwrap();
        assert_eq!(
            missing
                .into_iter()
                .map(|(_, _, name)| name)
                .collect::<Vec<_>>(),
            [
                "missing_method",
                "Widget",
                "containing_string",
                "unknown_reference",
                "after_trailing_comment",
                "after_inner_doc"
            ]
        );
    }
Input 14: outline src/rust_coverage.rs mod[tests]/fn[checks_trait_test_helper_and_nested_functions_separately]
  • File: src/rust_coverage.rs
  • Selector: mod[tests]/fn[checks_trait_test_helper_and_nested_functions_separately]
  • Kind: fn
  • src/rust_coverage.rs:915–945
    // {test}`requirements.references.rust_item_coverage`
    #[test]
    fn checks_trait_test_helper_and_nested_functions_separately() {
        let source = r#"
trait Work {
    fn uncited_trait_method(&self);
    // {impl}`requirements.example`
    fn cited_trait_method(&self);
}
fn outer() {
    // {impl}`requirements.example`
    fn inner() {}
    inner();
}
// {test}`requirements.example`
#[test]
fn tagged_test() {}
// {test}`requirements.case`
#[test]
fn named_example_test() {}
fn test_helper() {}
"#;
        let missing = missing_function_references(source, &definitions()).unwrap();
        assert_eq!(
            missing
                .into_iter()
                .map(|(_, _, name)| name)
                .collect::<Vec<_>>(),
            ["uncited_trait_method", "outer", "test_helper"]
        );
    }
Input 15: outline src/rust_coverage.rs mod[tests]/fn[an_example_counts_only_when_it_references_a_requirement]
    // {test}`requirements.references.rust_item_coverage`
    #[test]
    fn an_example_counts_only_when_it_references_a_requirement() {
        let mut definitions = definitions();
        let example = |text: &str| Declaration {
            kind: DefinitionKind::Example,
            text: text.to_owned(),
            source: "md/requirements.md:9".to_owned(),
            file: "md/requirements.md".to_owned(),
            line_start: 9,
            line_end: 9,
            raw_lines: vec![],
            anchors: vec![],
        };
        definitions.insert(
            "requirements.tested".to_owned(),
            example("A tested case. {test}`requirements.example`"),
        );
        definitions.insert("requirements.orphan".to_owned(), example("No requirement."));
        definitions.insert(
            "requirements.chained".to_owned(),
            example("Only another example. {cite}`requirements.case`"),
        );
        definitions.insert(
            "terms.word".to_owned(),
            Declaration {
                kind: DefinitionKind::Term,
                ..example("A word.")
            },
        );
        definitions.insert(
            "requirements.termed".to_owned(),
            example("Only a term. {cite}`terms.word`"),
        );
        let source = r#"
// {test}`requirements.case`
fn cites_example() {}
// {test}`requirements.tested`
fn tests_example() {}
// {test}`requirements.orphan`
fn orphan_example() {}
// {test}`requirements.chained`
fn chained_example() {}
// {test}`requirements.termed`
fn termed_example() {}
// {impl}`terms.word`
fn names_a_term() {}
"#;
        let missing = missing_function_references(source, &definitions).unwrap();
        assert_eq!(
            missing
                .into_iter()
                .map(|(_, _, name)| name)
                .collect::<Vec<_>>(),
            [
                "orphan_example",
                "chained_example",
                "termed_example",
                "names_a_term"
            ]
        );
    }
Input 16: outline src/rust_coverage.rs mod[tests]/fn[locates_functions_after_unicode_text]
    // {test}`requirements.references.rust_item_coverage`
    #[test]
    fn locates_functions_after_unicode_text() {
        let source = r#"
// {impl}`requirements.example`
fn outer() {
    let _ = "é";
    /* {impl}`requirements.example` */ fn cited_inner() {}
    fn missing_inner() {}
}
"#;
        let missing = missing_function_references(source, &definitions()).unwrap();
        assert_eq!(missing, [(6, "function", "missing_inner".to_owned())]);
    }
Input 17: outline src/rust_coverage.rs mod[tests]/fn[reports_all_files_and_parse_failures]
    // {test}`requirements.references.rust_item_coverage`
    #[test]
    fn reports_all_files_and_parse_failures() {
        let project = TempDir::new().unwrap();
        fs::create_dir_all(project.path().join("src")).unwrap();
        fs::create_dir_all(project.path().join("src/evidence")).unwrap();
        fs::create_dir_all(project.path().join("tests")).unwrap();
        fs::create_dir_all(project.path().join("target")).unwrap();
        fs::create_dir_all(project.path().join("evidence")).unwrap();
        fs::write(project.path().join("src/lib.rs"), "fn uncited() {}\n").unwrap();
        fs::write(
            project.path().join("src/evidence/check.rs"),
            "fn nested_source() {}\n",
        )
        .unwrap();
        fs::write(project.path().join("tests/broken.rs"), "fn unfinished( {\n").unwrap();
        fs::write(
            project.path().join("target/generated.rs"),
            "fn ignored() {}\n",
        )
        .unwrap();
        fs::write(
            project.path().join("evidence/fixture.rs"),
            "fn ignored() {}\n",
        )
        .unwrap();
        // Build output and repository metadata are skipped at any depth; the
        // book, evidence, and vendored sources only at the project root.
        for (file, source) in [
            ("crates/sub/target/debug/build.rs", "fn ignored() {}\n"),
            (".git/hooks/hook.rs", "fn ignored() {}\n"),
            ("vendor/dep/lib.rs", "fn ignored() {}\n"),
            ("book/listing.rs", "fn ignored() {}\n"),
            ("src/vendor/own.rs", "fn own_vendor() {}\n"),
            ("src/book/own.rs", "fn own_book() {}\n"),
        ] {
            let path = project.path().join(file);
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(path, source).unwrap();
        }

        let mut errors = Vec::new();
        let uncovered = validate_rust_functions(
            project.path(),
            &crate::evidence::discovered_files(project.path(), &mut Vec::new()),
            &definitions(),
            &super::EvidenceReads::default(),
            &mut errors,
            &mut Vec::new(),
            &mut |_| {},
        );
        // Uncovered items are reported; only the parse failure is an error.
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert_eq!(uncovered.len(), 4, "{uncovered:?}");
        let errors: Vec<String> = errors
            .into_iter()
            .chain(uncovered.into_iter().map(|item| item.error))
            .collect();
        for expected in [
            "src/vendor/own.rs:1: function own_vendor",
            "src/book/own.rs:1: function own_book",
        ] {
            assert!(
                errors.iter().any(|error| error.contains(expected)),
                "{expected}: {errors:?}"
            );
        }
        assert!(errors.iter().any(|error| {
            error.contains("src/lib.rs:1: function uncited has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it")
        }));
        assert!(errors.iter().any(|error| {
            error.contains(
                "src/evidence/check.rs:1: function nested_source has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
            )
        }));
        assert!(
            errors
                .iter()
                .any(|error| error.contains("tests/broken.rs:1: cannot parse Rust source"))
        );
    }
Input 18: outline src/rust_coverage.rs mod[tests]/fn[structs_enums_and_unions_need_references_attached_or_inside]
    // {test}`requirements.references.rust_item_coverage`
    #[test]
    fn structs_enums_and_unions_need_references_attached_or_inside() {
        let source = r##"
// {impl}`requirements.example`
#[derive(Debug)]
struct Attached {
    field: u8,
}

struct Inside {
    // {impl}`requirements.example`
    #[allow(dead_code)]
    field: u8,
}

enum Variants {
    // {cite}`requirements.example`
    One,
}

struct Missing;

enum MissingEnum {
    One,
}

union MissingUnion {
    value: u8,
}

// {impl}`requirements.example`
fn outer() {
    struct Nested;
}
"##;
        let missing = missing_function_references(source, &definitions()).unwrap();
        assert_eq!(
            missing,
            vec![
                (19, "struct", "Missing".to_owned()),
                (21, "enum", "MissingEnum".to_owned()),
                (25, "union", "MissingUnion".to_owned()),
                (31, "struct", "Nested".to_owned()),
            ]
        );
    }
Input 19: outline tests/authoring_batch.rs fn[discovery_errors_fail_before_configuration_or_inference]
// {test}`requirements.authoring.batch`
// {test}`requirements.ci.definition_errors`
// {test}`requirements.references.rust_item_coverage`
#[test]
fn discovery_errors_fail_before_configuration_or_inference() {
    for (declarations, source, location, diagnostic) in [
        ("", "fn broken(", "src/lib.rs", "cannot parse Rust source"),
        (
            ":::{req} unclosed\nThis MUST be valid.\n",
            "",
            "md/requirements.md",
            "missing a closing colon fence",
        ),
    ] {
        let fixture = Fixture::new("http://127.0.0.1:9", None);
        fs::write(fixture.project.join("md/requirements.md"), declarations).unwrap();
        fs::write(fixture.project.join("src/lib.rs"), source).unwrap();
        fs::remove_file(&fixture.config).unwrap();
        let output = fixture.run(&["author", "--all"]);
        assert!(!output.status.success());
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains(location), "{stderr}");
        assert!(stderr.contains(diagnostic), "{stderr}");
        assert!(!stderr.contains("no authoring configuration"), "{stderr}");
        assert!(!fixture.state.exists());
        assert!(!fixture.project.join("evidence").exists());
    }
}
Input 20: outline tests/authoring_cli.rs fn[replacing_a_record_that_stops_reading_an_item_warns_until_it_is_covered]
// {test}`requirements.references.rust_item_coverage`
#[test]
fn replacing_a_record_that_stops_reading_an_item_warns_until_it_is_covered() {
    let server = Server::start(vec![reply(vec![call(
        "submit",
        "submit_judgment",
        json!({"determination": true, "rationale": "Ready is implemented."}),
    )])]);
    let fixture = Fixture::new(&server.endpoint);
    fs::write(
        fixture.project.join("src/helper.rs"),
        "fn helper() {}\n\nfn other() {}\n",
    )
    .unwrap();
    // The record being replaced read `helper`, so it was covered.
    let read = habeas::outline_input(&fixture.project, "src/helper.rs", "fn[helper]").unwrap();
    fs::write(
        &fixture.evidence,
        json!({"requirement": REQUIREMENT, "determination": false,
            "rationale": "PREVIOUS_RATIONALE relied on helper.", "inputs": [read]})
        .to_string(),
    )
    .unwrap();
    let uncovered = "src/helper.rs:1: function helper has no recent coverage";
    let status = fixture.run(&["status", "--coverage"]);
    let text = String::from_utf8_lossy(&status.stdout).into_owned();
    assert!(!text.contains(uncovered), "{text}");

    let output = fixture.run(&["author", SUBJECT]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    // Authoring runs one conversation, for the subject alone.
    assert_eq!(server.finish().len(), 1);
    // The new record does not read the item...
    let evidence = fs::read_to_string(&fixture.evidence).unwrap();
    assert!(!evidence.contains("helper"), "{evidence}");

    // ...so status warns about it...
    let status = fixture.run(&["status", "--coverage"]);
    let text = String::from_utf8_lossy(&status.stdout).into_owned();
    assert!(
        text.contains(&format!(
            "{uncovered}: it has no requirement or example reference, and no recent evidence record or review read it"
        )),
        "{text}"
    );
    // ...until the item is covered again.
    fs::write(
        fixture.project.join("src/helper.rs"),
        "// {impl}`requirements.ready`\nfn helper() {}\n\nfn other() {}\n",
    )
    .unwrap();
    let status = fixture.run(&["status", "--coverage"]);
    let text = String::from_utf8_lossy(&status.stdout).into_owned();
    assert!(!text.contains(uncovered), "{text}");
}
Input 21: outline tests/commands.rs fn[status_preserves_repository_wide_rust_findings_in_every_form]
  • File: tests/commands.rs
  • Selector: fn[status_preserves_repository_wide_rust_findings_in_every_form]
  • Kind: fn
  • tests/commands.rs:460–513
// {test}`requirements.cli.status`
// {test}`requirements.references.rust_item_coverage`
// {test}`requirements.references.definition_globs`
// {test}`requirements.references.coverage.report`
#[test]
fn status_preserves_repository_wide_rust_findings_in_every_form() {
    let temp = fixture();
    let nested = temp.path().join("src/nested");
    // `main` is read by an evidence record; this item is read by none.
    fs::write(temp.path().join("src/extra.rs"), "fn unread() {}\n").unwrap();
    for flags in [
        [].as_slice(),
        ["--all"].as_slice(),
        ["--verbose"].as_slice(),
        ["--all", "--verbose"].as_slice(),
    ] {
        for selection in [None, Some("requirements.ready")] {
            for coverage in [false, true] {
                let mut args = vec!["status"];
                args.extend_from_slice(flags);
                args.extend(selection);
                if coverage {
                    args.push("--coverage");
                }
                let output = habeas(&nested, &args);
                assert!(output.status.success(), "{args:?}: {output:?}");
                let text = String::from_utf8(output.stdout).unwrap();
                if coverage {
                    assert!(text.contains("## Coverage warnings"), "{args:?}: {text}");
                    assert!(
                    text.contains(
                        "src/extra.rs:1: function unread has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it"
                    ),
                    "{args:?}: {text}"
                );
                } else {
                    assert!(
                        text.contains(
                            "1 nodes have coverage warnings. Use `status --coverage` to see them."
                        ),
                        "{args:?}: {text}"
                    );
                    assert!(!text.contains("has no recent coverage"), "{args:?}: {text}");
                    assert!(!text.contains("## Coverage warnings"), "{args:?}: {text}");
                }
                assert!(
                    !text.contains("function main has no recent coverage"),
                    "{args:?}: {text}"
                );
                assert!(!text.contains("attestation"), "{args:?}: {text}");
            }
        }
    }
}
Input 22: outline tests/references.rs fn[fenced_references_in_comments_and_built_in_rules_are_validated]
  • File: tests/references.rs
  • Selector: fn[fenced_references_in_comments_and_built_in_rules_are_validated]
  • Kind: fn
  • tests/references.rs:72–129
// {test}`requirements.references.roles`
// {test}`requirements.references.builtin_definitions`
// {test}`requirements.references.rust_item_coverage`
// {test}`requirements.references.procedure`
// {test}`requirements.references.util`
#[test]
fn fenced_references_in_comments_and_built_in_rules_are_validated() {
    let temp = project();
    let root = temp.path();
    let cr = role("cite");
    let source = format!(
        "// :::{cr} habeas:util\n// Glue that formats output.\n// :::\nfn glue() {{}}\n\n\
         // {cr}`habeas:none`\nfn inline() {{}}\n\n\
         // :::{cr} habeas:util\n// {cr}`rules.ready`\n// :::\nfn empty() {{}}\n\n\
         // :::{im} habeas:util\n// Wrong role.\n// :::\nfn wrong_role() {{}}\n\n\
         // :::{cr} habeas:other\n// Unknown.\n// :::\nfn unknown() {{}}\n\n\
         // :::{cr} rules.ready\n// never closed\n\n// :::\nfn unclosed() {{}}\n\n\
         // :::{cr} habeas:none\n// Formats output.\n// :::\nfn fenced_none() {{}}\n",
        im = role("impl"),
    );
    fs::write(root.join("src/lib.rs"), source).unwrap();
    let errors = errors(root);
    for expected in [
        // `habeas:none` was removed: it is an unknown name in either form.
        "src/lib.rs:6: {cite}`habeas:none` has no matching built-in definition",
        "src/lib.rs:30: {cite}`habeas:none` has no matching built-in definition",
        "src/lib.rs:14: built-in habeas:util may only be referenced with {cite}",
        "src/lib.rs:19: {cite}`habeas:other` has no matching built-in definition",
        "src/lib.rs:24: fenced {cite} reference to rules.ready has no closing fence",
        "src/lib.rs:7: function inline has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
        "src/lib.rs:17: function wrong_role has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
        "src/lib.rs:22: function unknown has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
        "src/lib.rs:28: function unclosed has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
        "src/lib.rs:33: function fenced_none has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
    ] {
        assert!(has(&errors, expected), "missing {expected:?}: {errors:#?}");
    }
    // A fenced citation of habeas:util covers its function, as does an
    // inline reference in a fence body.
    assert!(!has(&errors, "function glue"), "{errors:#?}");
    assert!(!has(&errors, "function empty"), "{errors:#?}");
    // Only valid citations other than habeas:util need reviews.
    assert!(has(
        &errors,
        "missing citation review for src/lib.rs fn[empty]"
    ));
    for item in ["glue", "inline", "fenced_none"] {
        assert!(
            !has(
                &errors,
                &format!("missing citation review for src/lib.rs fn[{item}]")
            ),
            "{errors:#?}"
        );
    }
    // Built-ins need no evidence.
    assert!(!has(&errors, "evidence/habeas:"), "{errors:#?}");
}
Input 23: outline tests/references.rs fn[habeas_util_citations_cover_their_item_without_a_citation_review]
  • File: tests/references.rs
  • Selector: fn[habeas_util_citations_cover_their_item_without_a_citation_review]
  • Kind: fn
  • tests/references.rs:131–185
// {test}`requirements.references.util`
// {test}`requirements.references.citation_review`
// {test}`requirements.references.rust_item_coverage`
#[test]
fn habeas_util_citations_cover_their_item_without_a_citation_review() {
    let temp = project();
    let root = temp.path();
    let cr = role("cite");
    let source = format!(
        "// {cr}`habeas:util`\nfn inline() {{}}\n\n\
         // :::{cr} habeas:util\n// Formats output for its caller.\n// :::\nfn fenced() {{}}\n\n\
         // :::{cr} habeas:util\n// :::\nfn bare() {{}}\n\n\
         // {cr}`habeas:util`\n// {cr}`rules.ready`\nfn mixed() {{}}\n\n\
         // {im}`habeas:util`\nfn implemented() {{}}\n\n\
         // {te}`habeas:util`\nfn tested() {{}}\n",
        im = role("impl"),
        te = role("test"),
    );
    fs::write(root.join("src/lib.rs"), source).unwrap();
    let errors = errors(root);
    // Inline and fenced citations, with or without commentary, cover their
    // item and need no citation review.
    for item in ["inline", "fenced", "bare"] {
        assert!(!has(&errors, &format!("function {item} ")), "{errors:#?}");
        assert!(
            !has(
                &errors,
                &format!("missing citation review for src/lib.rs fn[{item}]")
            ),
            "{errors:#?}"
        );
    }
    // Another citation on the same item still needs its review.
    assert!(
        has(&errors, "missing citation review for src/lib.rs fn[mixed]"),
        "{errors:#?}"
    );
    // Only {cite} may reference it.
    for line in [17, 20] {
        let expected = format!(
            "src/lib.rs:{line}: built-in habeas:util may only be referenced with {}",
            role("cite")
        );
        assert!(has(&errors, &expected), "missing {expected:?}: {errors:#?}");
    }
    assert!(
        has(&errors, "function implemented has no recent coverage"),
        "{errors:#?}"
    );
    assert!(
        has(&errors, "function tested has no recent coverage"),
        "{errors:#?}"
    );
    assert!(!has(&errors, "evidence/habeas:util"), "{errors:#?}");
}
Input 24: outline tests/references.rs fn[a_fixme_does_not_count_as_an_items_reference]
// {test}`requirements.references.procedure`
// {test}`requirements.references.rust_item_coverage`
// {test}`requirements.references.roles`
#[test]
fn a_fixme_does_not_count_as_an_items_reference() {
    let temp = project();
    let root = temp.path();
    let fx = role("fixme");
    fs::write(
        root.join("src/lib.rs"),
        format!(
            "// :::{fx} rules.ready\n// The gap.\n// :::\nfn gap() {{}}\n\n\
             // :::{fx}\n// :github: example/rules#1\n// :::\nfn tracked() {{}}\n\n\
             // {}`rules.ready`\n// :::{fx} rules.ready\n// Another gap.\n// :::\nfn implemented() {{}}\n",
            role("impl")
        ),
    )
    .unwrap();
    let errors = errors(root);
    for expected in [
        "src/lib.rs:4: function gap has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
        "src/lib.rs:9: function tracked has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it",
    ] {
        assert!(has(&errors, expected), "missing {expected:?}: {errors:#?}");
    }
    assert!(!has(&errors, "function implemented"), "{errors:#?}");
}
Input 25: outline tests/references.rs fn[untracked_sources_are_not_validated_until_staged_and_status_lists_them]
  • File: tests/references.rs
  • Selector: fn[untracked_sources_are_not_validated_until_staged_and_status_lists_them]
  • Kind: fn
  • tests/references.rs:702–746
// {test}`requirements.references.discovery`
// {test}`requirements.references.rust_item_coverage`
// {test}`requirements.cli.status`
#[test]
fn untracked_sources_are_not_validated_until_staged_and_status_lists_them() {
    let temp = project();
    let root = temp.path();
    let source = format!(
        "// {}`rules.missing`\nfn referenced() {{}}\n\nfn uncited() {{}}\n",
        role("impl")
    );
    fs::write(root.join("src/extra.rs"), &source).unwrap();
    // An untracked file without references needs no reminder.
    fs::write(root.join("notes.txt"), "No references here.\n").unwrap();
    git(root, &["init", "--quiet"]);
    git(root, &["add", "md", "book.toml", "Cargo.toml"]);

    let untracked = errors(root);
    assert!(!has(&untracked, "src/extra.rs"), "{untracked:#?}");
    let status = habeas::status_markdown(root, false).unwrap();
    let section = &status[status
        .find("## Untracked files with references")
        .unwrap_or_else(|| panic!("{status}"))..];
    assert!(section.contains("git add"), "{status}");
    assert!(section.contains("- `src/extra.rs`"), "{status}");
    assert!(!section.contains("notes.txt"), "{status}");

    // Staging the new file brings its references and items back.
    git(root, &["add", "src/extra.rs"]);
    let errors = errors(root);
    assert!(has(&errors, "src/extra.rs:1"), "{errors:#?}");
    assert!(has(&errors, "rules.missing"), "{errors:#?}");
    assert!(
        has(
            &errors,
            "src/extra.rs:4: function uncited has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it"
        ),
        "{errors:#?}"
    );
    let status = habeas::status_markdown(root, false).unwrap();
    assert!(
        !status.contains("Untracked files with references"),
        "{status}"
    );
}
Input 26: outline tests/references.rs fn[disallowed_paths_are_skipped_and_projects_outside_git_scan_every_file]
  • File: tests/references.rs
  • Selector: fn[disallowed_paths_are_skipped_and_projects_outside_git_scan_every_file]
  • Kind: fn
  • tests/references.rs:748–799
// {test}`requirements.references.discovery`
// {test}`requirements.references.rust_item_coverage`
// {test}`requirements.configuration.evidence_paths`
#[test]
fn disallowed_paths_are_skipped_and_projects_outside_git_scan_every_file() {
    let temp = project();
    let root = temp.path();
    let source = format!("// {}`rules.missing`\nfn uncited() {{}}\n", role("impl"));
    for file in [
        "private/hidden.rs",
        "src/secret.rs",
        "notes/other.rs",
        "vendor/dep/lib.rs",
        "crates/sub/target/out.rs",
        "book/out.rs",
    ] {
        let path = root.join(file);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, &source).unwrap();
    }
    fs::write(
        root.join("habeas.toml"),
        "version = 1\n\n[evidence]\ndisallow = [\"private\", \"src/secret.rs\"]\n",
    )
    .unwrap();
    let errors = errors(root);
    for skipped in [
        "private/hidden.rs",
        "src/secret.rs",
        "crates/sub/target/out.rs",
        "book/out.rs",
    ] {
        assert!(!has(&errors, skipped), "{skipped}: {errors:#?}");
    }
    // Outside Git every other project file is considered, untracked or not;
    // vendored Rust sources still carry references but are not covered.
    assert!(has(&errors, "notes/other.rs:1"), "{errors:#?}");
    assert!(
        has(&errors, "notes/other.rs:2: function uncited"),
        "{errors:#?}"
    );
    assert!(has(&errors, "vendor/dep/lib.rs:1"), "{errors:#?}");
    assert!(
        !has(&errors, "vendor/dep/lib.rs:2: function uncited"),
        "{errors:#?}"
    );
    let status = habeas::status_markdown(root, false).unwrap();
    assert!(
        !status.contains("Untracked files with references"),
        "{status}"
    );
}
Input 27: outline tests/references.rs fn[items_named_by_recent_evidence_have_recent_coverage_whatever_their_hash]
  • File: tests/references.rs
  • Selector: fn[items_named_by_recent_evidence_have_recent_coverage_whatever_their_hash]
  • Kind: fn
  • tests/references.rs:801–862
// {test}`requirements.references.rust_item_coverage`
// {test}`requirements.references.coverage.history`
// {test}`requirements.references.procedure`
#[test]
fn items_named_by_recent_evidence_have_recent_coverage_whatever_their_hash() {
    let temp = project();
    let root = temp.path();
    let source = "fn read_directly() {}\n\nstruct Thing;\n\nimpl Thing {\n    fn method(&self) {}\n}\n\nfn changed() {}\n\nfn unread() {}\n";
    fs::write(root.join("src/lib.rs"), source).unwrap();
    let input = |item: &str| habeas::outline_input(root, "src/lib.rs", item).unwrap();
    let mut stale = input("fn[changed]");
    stale["hash"] = json!("0".repeat(64));
    // An ordinary record reads one item; a citation review reads the impl
    // block containing a method; a site review records a stale hash.
    fs::write(
        root.join("evidence/rules.ready.json"),
        json!({"inputs": [input("fn[read_directly]")]}).to_string(),
    )
    .unwrap();
    fs::create_dir_all(root.join("evidence/citations/src/lib.rs")).unwrap();
    fs::write(
        root.join("evidence/citations/src/lib.rs/struct[Thing].json"),
        json!({"inputs": [input("impl[Thing]"), input("struct[Thing]")]}).to_string(),
    )
    .unwrap();
    fs::create_dir_all(root.join("evidence/sites/rules.ready/src/lib.rs")).unwrap();
    fs::write(
        root.join("evidence/sites/rules.ready/src/lib.rs/fn[changed].json"),
        json!({"inputs": [stale]}).to_string(),
    )
    .unwrap();
    let uncovered = |errors: &[String]| {
        errors
            .iter()
            .filter(|error| error.contains(" has no recent coverage: "))
            .map(|error| error.split(':').take(3).collect::<Vec<_>>().join(":"))
            .collect::<Vec<_>>()
    };
    // Recent coverage names a node by file and selector, whatever hash a
    // record gave it: a stale hash still covers it.
    let found = errors(root);
    assert_eq!(
        uncovered(&found),
        ["src/lib.rs:11: function unread has no recent coverage"],
        "{found:#?}"
    );
    // Editing a read item, or a method inside a read impl block, keeps it
    // covered while some recent version of an evidence file names it.
    fs::write(
        root.join("src/lib.rs"),
        source
            .replace("fn read_directly() {}", "fn read_directly() { 1; }")
            .replace("fn method(&self) {}", "fn method(&self) { 2; }"),
    )
    .unwrap();
    let found = errors(root);
    assert_eq!(
        uncovered(&found),
        ["src/lib.rs:11: function unread has no recent coverage"],
        "{found:#?}"
    );
}

Referenced definitions

Input 2: requirements selection requirements.references.discovery
:::{req} discovery
Habeas MUST find the references of {cite}`requirements.references.roles`
in project source files, where {cite}`requirements.references.reference_contexts`
says they count, and MUST fail with the source file and line if a
name has no matching `{req}` or `{example}` definition. In Markdown, escaped
roles and roles in code examples MUST remain literal. Reference discovery MUST
consider exactly the project sources that source-access policy permits under
{cite}`requirements.authoring.source_tools`: in a Git worktree, files present in
the Git index, including staged new files; outside Git, all project files; in
both cases excluding the project-root `book` and `evidence` directories, `.git`
and `target` directories at any depth, and paths disallowed by
{cite}`requirements.configuration.evidence_paths`. Evidence snapshots and
generated build output MUST therefore not be counted as source references.
:::
Input 3: requirements selection requirements.references.util
:::{req} util
Habeas MUST provide the built-in `habeas:util` under
{cite}`requirements.references.builtin_definitions`, with this text:

> Cite this on an item that serves other code, including code outside the
> project such as a library calling a trait implementation it requires, and
> carries out no requirement or example itself: it has no obligations and no
> end-user-observable behavior of its own. A review that reaches it from a root judges what it does
> as part of that root.

Only `{cite}` MAY reference it, inline or fenced, with or without commentary. An
item whose only citations are of `habeas:util` MUST NOT need a citation review
under {cite}`requirements.references.citation_review`. A citation of
`habeas:util` MUST cover its item under
{cite}`requirements.references.rust_item_coverage`.
:::
Input 4: requirements selection requirements.authoring.finish_search.inputs
:::{req} finish_search.inputs
For each tag selected by a valid `finish_search` call, the harness MUST record
its `file`, `item`, and structural hash as an outline input under
{cite}`requirements.ci.outline_inputs` before acknowledging that call.
:::
Input 5: requirements selection requirements.references.outline_comments
:::{req} outline_comments
Each documented profile defines which grammar nodes are comments; the Markdown
profile's comments are HTML comment blocks, so an inline HTML comment within a
paragraph is text of its section. In every supported language, comments on consecutive lines with no other source
between them MUST form one comment run. A comment that follows other source on
the same line, including another comment, MUST form a run by itself and MUST belong to the innermost outline node
containing that line. Any other run MUST belong to the next outline node that
starts after it within the smallest node containing it; when that container has
no such node, the run MUST belong to the container, which is the root node at top
level. A profile MAY bind a comment kind to its container
instead: such a run MUST belong to the smallest node containing it. The Rust
profile MUST bind inner doc comments (`//!`, `/*!`) to their container, so a
file-level inner doc comment belongs to the root node. A reference in a comment MUST count for the node its run belongs to under
{cite}`requirements.references.rust_item_coverage` and
{cite}`requirements.references.authoring_inputs`.
:::
Input 6: requirements selection requirements.examples.definition
:::{req} definition
An mdBook chapter MAY define an example with an opening fence of at least three colons immediately followed by `{example} <name>` and a closing colon-only fence of at least the opening length. The full name MUST use the same chapter-derived namespace and valid-name rules as `{req}`. The body MUST include all Markdown between the fences, excluding surrounding whitespace and the header option lines of {cite}`requirements.references.anchors`, and MUST describe a concrete case with expected behavior. An example MUST contain at least one valid `{cite}` or `{test}` reference to a requirement it illustrates; `{cite}` makes the requirement an input to the example's assessment, and `{test}` makes the example an input to the requirement's assessment, under {cite}`requirements.references.roles`. An example MAY use both. An example directive inside a fenced code block MUST remain literal.
:::
Input 7: requirements selection requirements.references.coverage.tests
:::{req} coverage.tests
Every Rust function carrying a test attribute, `#[test]` or an attribute whose
path ends in `test` such as `#[tokio::test]`, including those in Cargo
integration-test targets, MUST carry a `{test}` reference to a requirement or
named example under {cite}`requirements.references.roles`, in a comment
attached to it or within its body. A test function without one MUST be a
validation error naming its file, line, and name.
:::
Input 8: requirements selection requirements.references.coverage.examples
:::{req} coverage.examples
Every Cargo example target, each `.rs` file directly under the package's
`examples/` directory, each `examples/<name>/main.rs`, and each `[[example]]`
`path` in `Cargo.toml`, MUST `{cite}` a named example of the book under
{cite}`requirements.examples.definition` in a comment in that file. An example
target without one MUST be a validation error naming the file.
:::
Input 9: requirements selection requirements.references.coverage.report
:::{req} coverage.report
`habeas status`, and `habeas author` after it finishes, MUST report the number
of nodes without recent coverage under
{cite}`requirements.references.coverage.history`, except items inside a module
named `tests`, using the following summary:

```text
N nodes have coverage warnings. Use `status --coverage` to see them.
```

The summary MUST report zero when no nodes have warnings. Default output MUST
NOT list individual coverage warnings or coverage-history details, including
with `status --all` or `status --verbose`.
`habeas status --coverage` MUST list every warning, naming its file, line, kind,
and name, and report incomplete coverage history when applicable.
A warning MUST NOT fail validation, and repository validation MUST NOT read
Git history.
:::

Other sources

Input 1: requirements selection requirements.references.rust_item_coverage
:::{req} rust_item_coverage
During repository validation, Habeas MUST parse every first-party Rust source file: every `.rs` file among the sources reference discovery considers under {cite}`requirements.references.discovery`, except those under the project-root `vendor` directory. Each explicitly declared function or method, including trait methods and test helpers, and each struct, enum, and union is an item that can be covered. An item is covered when it has a valid `{impl}`, `{cite}`, or `{test}` reference to a defined requirement or named example, or a valid citation of the built-in `habeas:util` under {cite}`requirements.references.util`, in a Rust comment attached to it or within its body; or when its outline node, or an outline node containing it, is recorded with its current hash as an outline input of an evidence record, a citation review, or a site review. Outline inputs recorded from selected search snippets under {cite}`requirements.authoring.finish_search.inputs` MUST count alongside mandatory inputs and additional reads. Comments belong to items under {cite}`requirements.references.outline_comments`; a comment before a field, variant, or attribute inside an item belongs to that item. A named example MUST reference a requirement under {cite}`requirements.examples.definition`. A reference in a string literal, on an enclosing module or impl block, or only in an evidence input MUST NOT count for the items it encloses. Habeas MUST report a Rust parse failure instead of silently skipping the file. Only {cite}`requirements.references.coverage.tests` and {cite}`requirements.references.coverage.examples` make an uncovered item a validation error; other items without recent coverage are warned about under {cite}`requirements.references.coverage.report`.
:::
Input 28: requirements selection requirements.references.coverage.history
:::{req} coverage.history
{impl}`requirements.configuration.feature_sections`
An item has recent coverage when it has a reference that covers it under
{cite}`requirements.references.rust_item_coverage`, or when its outline node, or
an outline node containing it, is named by file and selector in the inputs of
any version of an existing evidence record, citation review, or site review in
its coverage window. A file's coverage window MUST be its current contents on
disk, committed or not, together with its contents in each of the last N
commits in its Git history that changed it, read through a Git library rather
than by running `git`. A recorded hash MUST NOT matter here: an earlier version
names the node, whatever its code was then. N MUST be the workspace
`[coverage]` setting `reauthorings`, a positive integer, and 3 when it is not
set. When the history is unavailable, such as outside Git or in a shallow clone
missing those commits, the window MUST be the commits that are available, and
`habeas status --coverage` MUST say that coverage history is incomplete.
:::