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.ci.requirements_inputs

Requirements index · View definition

evidence Valid

Requirement

For a requirements input, requirements MUST be a definition selection, and Habeas MUST match it against all defined requirements and named examples. It MUST recompute the matches during validation, sort their full names, and compare them with matches. It MUST take each match’s complete raw fenced declaration, including its opening and closing lines, concatenate those declarations in full-name order with one blank line between them, and compare the resulting raw lines with text. It MUST retain every match’s current source file and inclusive line range for display and reference coverage. A selection matching no definitions MUST be invalid. Adding, removing, renaming, or changing a matched definition MUST invalidate the stored input; moving an unchanged declaration within the book MUST NOT. Errors MUST identify the selection and affected definitions when available.

Rationale

The reviewed tests cover each obligation in requirements.ci.requirements_inputs. I found no gap that would justify rejecting them.

Obligations and the tests that cover them

  • Selection must be a valid definition selection. src/evidence.rs#mod[tests]/fn[requirements_inputs_track_matched_declarations_in_full_name_order] writes the invalid globs foo.[a].bar and "". It asserts exactly one error for each, naming inputs[0], the quoted glob and the specific problem. Valid globs and exact names are used as accepted inputs in tests/definitions.rs (via the requirements helper) and in src/index.rs#mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group].
  • Match against all requirements and named examples, recomputed at validation. The same test uses foo.*.bar. * crosses dots, and it matches both the example foo.a.b.bar and the requirement foo.a.bar. Because the match list is recomputed from the book on each validate_repository call, the add, remove and rename steps below each produce a fresh result.
  • Sort full names and compare with matches. The recorded matches are ["foo.a.b.bar","foo.a.bar"], which is sorted order. The book declares them in the opposite order (bar before nested), so an implementation that kept file order would fail the “no errors” assertion.
  • Concatenate raw fenced declarations in full-name order with one blank line, and compare with text. The valid case stores the example’s opening line, body and closing :::, then "", then the requirement’s three lines. It must validate with no errors. src/evidence.rs#mod[tests]/fn[requirements_inputs_omit_option_lines] checks the raw lines of a declaration that has an option line. It asserts raw_lines equals the opening line, body and closing line, and that the resolved input text equals raw_lines. tests/definitions.rs#fn[declaration] and fn[requirements] build the expected text for the integration tests.
  • Retain each match’s source file and inclusive range for display and reference coverage. src/index.rs#mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group] asserts each match’s file and inclusive range for rules.base and rules.ready, listed in sorted order before the recorded text. src/evidence.rs#mod[tests]/fn[requirements_inputs_omit_option_lines] asserts the declaration’s inclusive line range. src/evidence.rs#fn[evidence_input_ranges] takes its coverage ranges from the same resolved.ranges that the display test checks. No test covers a reference with only a requirements input, but the ranges that coverage consumes are the ones the display test checks.
  • A selection matching nothing is invalid. The test uses foo.*.none and asserts the exact error requirements glob "foo.*.none" matches no requirement or example.
  • Changing a definition invalidates the input. Editing Bar. to Changed. gives an error that names the selection and the changed definition foo.a.bar, and shows the diff - Bar. / + Changed..
  • Adding a definition invalidates the input. Adding foo.z.bar gives added ["foo.z.bar"], removed []. src/evidence.rs#mod[tests]/fn[cited_example_with_a_test_and_matching_evidence_validates] repeats the check for rules.* and rules.added.
  • Removing and renaming invalidate the input. Removing the example gives removed ["foo.a.b.bar"]. Renaming a.bar to c.bar gives added foo.c.bar and removed foo.a.bar.
  • Moving an unchanged declaration must not invalidate. The test reorders the declarations and inserts prose between them, which shifts line numbers. It asserts there are still no errors.
  • Errors identify the selection and the affected definitions. The assertions above check this for the change, add, remove, rename and no-match cases.

Remaining observations

  • No test moves a declaration to a different file. I treat this as an untested variation of the same input class, since the requirement says the retained file is the current one and the moved declaration’s text is unchanged.
  • No test stores an unsorted matches list. The sorted-order checks above would catch an implementation that did not sort.

No {fixme} acknowledgments apply, and none are needed.

Inputs

Tests

Input 2: outline src/evidence.rs mod[tests]/fn[requirements_inputs_track_matched_declarations_in_full_name_order]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[requirements_inputs_track_matched_declarations_in_full_name_order]
  • Kind: fn
  • src/evidence.rs:2857–2975
    // {test}`requirements.ci.requirements_inputs`
    // {test}`requirements.references.definition_glob_cases`
    // {test}`requirements.references.definition_globs`
    #[test]
    fn requirements_inputs_track_matched_declarations_in_full_name_order() {
        let temp = fixture();
        let bar = ":::{req} a.bar\nBar.\n:::\n";
        let nested = ":::{example} a.b.bar\nNested. {cite}`foo.a.bar`\n:::\n";
        let other = ":::{req} other\nOther.\n:::\n";
        let write = |declarations: &[&str]| {
            fs::write(
                temp.path().join("md/foo.md"),
                format!("# Foo\n\n{}", declarations.join("\n")),
            )
            .unwrap();
        };
        let lines = |declaration: &str| declaration.lines().map(str::to_owned).collect::<Vec<_>>();
        let mut text = lines(nested);
        text.push(String::new());
        text.extend(lines(bar));
        let record = |glob: &str| {
            json!({
                "requirement": "Other.",
                "determination": true,
                "rationale": "Both matches were examined.",
                "inputs": [{
                    "requirements": glob,
                    "matches": ["foo.a.b.bar", "foo.a.bar"],
                    "text": text,
                }]
            })
            .to_string()
        };
        fs::write(
            temp.path().join("evidence/foo.other.json"),
            record("foo.*.bar"),
        )
        .unwrap();
        let errors = || {
            validate_repository(temp.path())
                .unwrap()
                .errors
                .into_iter()
                .filter(|error| error.starts_with("evidence/foo.other.json"))
                .collect::<Vec<_>>()
        };

        // `*` crosses dots, the example sorts before the requirement by full
        // name, and the stored text is both complete fenced declarations.
        write(&[bar, nested, other]);
        assert!(errors().is_empty(), "{:?}", errors());
        // Moving unchanged declarations does not invalidate the input.
        write(&[other, "Some prose.\n", nested, "More prose.\n", bar]);
        assert!(errors().is_empty(), "{:?}", errors());

        write(&[&bar.replace("Bar.", "Changed."), nested, other]);
        let changed = errors().join("\n");
        assert!(
            changed.contains(
                "inputs[0]: input text changed for Requirements { requirements: \"foo.*.bar\" }; changed definitions [\"foo.a.bar\"]\n- Bar.\n+ Changed."
            ),
            "{changed}"
        );

        let added = ":::{req} z.bar\nAdded.\n:::\n";
        write(&[bar, nested, other, added]);
        assert!(
            errors().join("\n").contains(
                "inputs[0]: requirements glob \"foo.*.bar\" matches changed; added [\"foo.z.bar\"], removed []"
            ),
            "{:?}",
            errors()
        );
        write(&[bar, other]);
        assert!(
            errors().join("\n").contains(
                "requirements glob \"foo.*.bar\" matches changed; added [], removed [\"foo.a.b.bar\"]"
            ),
            "{:?}",
            errors()
        );
        write(&[&bar.replace("a.bar", "c.bar"), nested, other]);
        assert!(
            errors().join("\n").contains(
                "requirements glob \"foo.*.bar\" matches changed; added [\"foo.c.bar\"], removed [\"foo.a.bar\"]"
            ),
            "{:?}",
            errors()
        );

        write(&[bar, nested, other]);
        fs::write(
            temp.path().join("evidence/foo.other.json"),
            record("foo.*.none"),
        )
        .unwrap();
        assert_eq!(
            errors(),
            [
                "evidence/foo.other.json: inputs[0]: requirements glob \"foo.*.none\" matches no requirement or example"
            ]
        );

        // A selection that is not a valid definition glob is rejected.
        for (glob, problem) in [
            ("foo.[a].bar", "unsupported character '['"),
            ("", "definition glob must not be empty"),
        ] {
            fs::write(temp.path().join("evidence/foo.other.json"), record(glob)).unwrap();
            let found = errors();
            assert!(
                found.len() == 1
                    && found[0].contains("inputs[0]")
                    && found[0].contains(&format!("requirements glob {glob:?}"))
                    && found[0].contains(problem),
                "{glob:?}: {found:?}"
            );
        }
    }
Input 3: outline src/evidence.rs mod[tests]/fn[cited_example_with_a_test_and_matching_evidence_validates]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[cited_example_with_a_test_and_matching_evidence_validates]
  • Kind: fn
  • src/evidence.rs:3498–3632
    // {test}`requirements.examples.definition`
    // {test}`requirements.examples.evidence`
    // {test}`requirements.integration.report_api`
    // {test}`requirements.ci.schema`
    // {test}`requirements.references.evidence_coverage`
    // {test}`requirements.ci.requirements_inputs`
    // {test}`requirements.ci.orphans`
    #[test]
    fn cited_example_with_a_test_and_matching_evidence_validates() {
        let temp = fixture();
        let chapter = "# Rules\n\n:::{req} ready\nReady.\n:::\n\n:::{example} case\nGiven ready, it succeeds. {cite}`rules.ready` {test}`rules.ready`\n:::\n";
        fs::write(temp.path().join("md/rules.md"), chapter).unwrap();
        let test_source = "// {test}`rules.case`\n#[test]\nfn checks_case() { assert!(true); }\n";
        fs::write(temp.path().join("src/main.rs"), test_source).unwrap();
        fs::write(
            temp.path().join("evidence/rules.ready.json"),
            json!({
                "requirement": "Ready.",
                "determination": true,
                "rationale": "The example cites this rule.",
                "inputs": crate::inputs::outline_inputs_for_lines(temp.path(), "md/rules.md", 8, 8)
                    .unwrap()
            })
            .to_string(),
        )
        .unwrap();
        let example_path = temp.path().join("evidence/rules.case.json");
        fs::write(
            &example_path,
            json!({
                "example": "Given ready, it succeeds. {cite}`rules.ready` {test}`rules.ready`",
                "determination": true,
                "rationale": "checks_case sets up ready and asserts the result.",
                "inputs": [
                    outline(temp.path(), "src/main.rs", "fn[checks_case]"),
                    {
                        "requirements": "rules.*",
                        "matches": ["rules.case", "rules.ready"],
                        "text": [
                            chapter.lines().nth(6).unwrap(),
                            chapter.lines().nth(7).unwrap(),
                            chapter.lines().nth(8).unwrap(),
                            "",
                            chapter.lines().nth(2).unwrap(),
                            chapter.lines().nth(3).unwrap(),
                            chapter.lines().nth(4).unwrap()
                        ]
                    }
                ]
            })
            .to_string(),
        )
        .unwrap();

        let report = validate_repository(temp.path()).unwrap();
        assert_eq!(report.requirements, 1);
        assert_eq!(report.examples, 1);
        assert_eq!(report.evidence_files, 2);
        assert!(report.errors.is_empty(), "{:?}", report.errors);

        let ready_path = temp.path().join("evidence/rules.ready.json");
        let ready = fs::read_to_string(&ready_path).unwrap();
        let mut missing: Value = serde_json::from_str(&ready).unwrap();
        missing["inputs"] = json!([]);
        fs::write(&ready_path, missing.to_string()).unwrap();
        let errors = validate_repository(temp.path()).unwrap().errors;
        assert!(
            errors.iter().any(|error| error.contains("no input covers")
                && error.contains("{test}")
                && error.contains("rules.ready")
                && error.contains("md/rules.md:8")),
            "{errors:?}"
        );
        fs::write(ready_path, ready).unwrap();

        let old = fs::read_to_string(&example_path).unwrap();
        let mut uncovered: serde_json::Value = serde_json::from_str(&old).unwrap();
        uncovered["inputs"] = json!([]);
        fs::write(&example_path, uncovered.to_string()).unwrap();
        let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
        assert!(errors.contains("no input covers"), "{errors}");
        assert!(errors.contains("src/main.rs:1"), "{errors}");
        fs::write(&example_path, &old).unwrap();
        fs::write(
            temp.path().join("src/main.rs"),
            test_source.replace("assert!(true)", "assert!(false)"),
        )
        .unwrap();
        let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
        assert!(
            errors.contains(
                "outline input changed: src/main.rs fn[checks_case] (now lines 1-3) no longer has the recorded hash"
            ),
            "{errors}"
        );
        fs::write(temp.path().join("src/main.rs"), test_source).unwrap();
        fs::write(
            temp.path().join("md/rules.md"),
            format!("{chapter}\n:::{req} added\nAdded.\n:::\n", req = "{req}"),
        )
        .unwrap();
        let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
        assert!(
            errors.contains(
                "requirements glob \"rules.*\" matches changed; added [\"rules.added\"], removed []"
            ),
            "{errors}"
        );

        let mut evidence: serde_json::Value = serde_json::from_str(&old).unwrap();
        evidence["example"] = "Outdated.".into();
        fs::write(&example_path, evidence.to_string()).unwrap();
        let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
        assert!(errors.contains("example text changed"), "{errors}");
        assert!(errors.contains("- Outdated."), "{errors}");

        let mut wrong_field: serde_json::Value = serde_json::from_str(&old).unwrap();
        let example_text = wrong_field
            .as_object_mut()
            .unwrap()
            .remove("example")
            .unwrap();
        wrong_field["requirement"] = example_text;
        fs::write(&example_path, wrong_field.to_string()).unwrap();
        let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
        assert!(errors.contains("missing field \"example\""), "{errors}");
        assert!(
            errors.contains("unexpected field \"requirement\""),
            "{errors}"
        );

        fs::remove_file(&example_path).unwrap();
        let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
        assert!(errors.contains("missing for example"), "{errors}");
    }
Input 4: outline src/evidence.rs mod[tests]/fn[requirements_inputs_omit_option_lines]
    // {test}`requirements.references.anchors`
    // {test}`requirements.ci.requirements_inputs`
    #[test]
    fn requirements_inputs_omit_option_lines() {
        let temp = fixture();
        fs::write(
            temp.path().join("md/requirements.md"),
            "# Rules\n\n:::{req} ready\n:impl: src/main.rs\nReady MUST hold.\n:::\n",
        )
        .unwrap();
        let definitions = super::load_definitions(temp.path()).unwrap();
        let ready = &definitions["requirements.ready"];
        assert_eq!(ready.text, "Ready MUST hold.");
        assert_eq!((ready.line_start, ready.line_end), (3, 6));
        assert_eq!(
            ready.raw_lines,
            [":::{req} ready", "Ready MUST hold.", ":::"]
        );
        assert_eq!(
            ready.anchors,
            [super::Anchor {
                kind: crate::ReferenceKind::Impl,
                file: "src/main.rs".to_owned(),
                item: String::new(),
            }]
        );
        let resolved = crate::inputs::InputSelector::Requirements {
            requirements: "requirements.ready".to_owned(),
        }
        .resolve(
            &fs::canonicalize(temp.path()).unwrap(),
            &definitions,
            &crate::inputs::OutlineCache::default(),
        )
        .unwrap();
        assert_eq!(resolved.text, ready.raw_lines);
    }
Input 5: 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 6: outline tests/definitions.rs fn[declaration]
/// The raw fenced declaration of a fixture definition, as evidence records
/// it: `rules.ready` is the `ready` block in `md/rules.md`.
// {test}`requirements.ci.requirements_inputs`
fn declaration(root: &Path, name: &str) -> Vec<String> {
    let (file, local) = name.split_once('.').unwrap();
    let source = fs::read_to_string(root.join(format!("md/{file}.md"))).unwrap();
    let lines = source.lines().collect::<Vec<_>>();
    let start = lines
        .iter()
        .position(|line| line.starts_with(":::{") && line.ends_with(&format!("}} {local}")))
        .unwrap_or_else(|| panic!("no declaration of {name}"));
    let end = start
        + lines[start..]
            .iter()
            .position(|line| *line == ":::")
            .unwrap();
    lines[start..=end]
        .iter()
        .map(|line| (*line).to_owned())
        .collect()
}
Input 7: outline tests/definitions.rs fn[requirements]
/// A requirements input selecting `selection` and recording `matches`.
// {test}`requirements.ci.requirements_inputs`
fn requirements(root: &Path, selection: &str, matches: &[&str]) -> Value {
    let text = matches
        .iter()
        .map(|name| declaration(root, name))
        .collect::<Vec<_>>()
        .join(&String::new());
    json!({ "requirements": selection, "matches": matches, "text": text })
}

Referenced definitions

Input 8: definition requirements.references.definition_selection
:::{definition} definition_selection
:phrase: definition selection

A full requirement or example name, or a definition glob, identifying the
requirements and named examples it matches under
{cite}`requirements.references.definition_globs`. A name without `*` selects
exactly that definition.
:::

Other sources

Input 1: requirements selection requirements.ci.requirements_inputs
:::{req} requirements_inputs
For a requirements input, `requirements` MUST be a {term}`requirements.references.definition_selection`, and Habeas MUST match it against all defined requirements and named examples. It MUST recompute the matches during validation, sort their full names, and compare them with `matches`. It MUST take each match's complete raw fenced declaration, including its opening and closing lines, concatenate those declarations in full-name order with one blank line between them, and compare the resulting raw lines with `text`. It MUST retain every match's current source file and inclusive line range for display and reference coverage. A selection matching no definitions MUST be invalid. Adding, removing, renaming, or changing a matched definition MUST invalidate the stored input; moving an unchanged declaration within the book MUST NOT. Errors MUST identify the selection and affected definitions when available.
:::
Input 9: outline src/evidence.rs mod[tests]/fn[source_references_are_covered_by_evidence_inputs]
    // {test}`requirements.references.evidence_coverage`
    // {test}`requirements.references.markdown_literals`
    #[test]
    fn source_references_are_covered_by_evidence_inputs() {
        let temp = fixture();
        fs::write(
            temp.path().join("md/reqs/foo/bar.md"),
            "# Requirements\n\n:::{req} ready\nReady.\n:::\n",
        )
        .unwrap();
        let implementation = "{impl}`foo.bar.ready`".to_owned();
        let citation = "{cite}`foo.bar.ready`".to_owned();
        let test = "{test}`foo.bar.ready`".to_owned();
        let example = "{cite}`missing.example`".to_owned();
        let source = format!("// {implementation}\n// {citation}\n");
        let notes = format!("# Notes\n\n{test}\n\n`{example}`\n\n```text\n{example}\n```\n");
        fs::write(temp.path().join("src/main.rs"), &source).unwrap();
        fs::write(temp.path().join("md/notes.md"), &notes).unwrap();
        fs::write(
            temp.path().join("evidence/foo.bar.ready.json"),
            json!({
                "requirement": "Ready.",
                "determination": true,
                "rationale": "The source and notes were examined.",
                "inputs": [
                    outline(temp.path(), "src/main.rs", ""),
                    crate::inputs::outline_inputs_for_lines(temp.path(), "md/notes.md", 3, 3)
                        .unwrap()[0]
                ]
            })
            .to_string(),
        )
        .unwrap();

        let errors = without_citation_reviews(validate_repository(temp.path()).unwrap().errors);
        assert!(errors.is_empty(), "{errors:?}");
    }
Input 10: outline src/sites.rs mod[tests]/fn[a_fixme_inside_a_site_belongs_to_that_sites_review_only]
  • File: src/sites.rs
  • Selector: mod[tests]/fn[a_fixme_inside_a_site_belongs_to_that_sites_review_only]
  • Kind: fn
  • src/sites.rs:1398–1505
    // {test}`requirements.references.site_review`
    // {test}`requirements.references.evidence_coverage`
    // {test}`requirements.ci.reference_set`
    #[test]
    fn a_fixme_inside_a_site_belongs_to_that_sites_review_only() {
        let fixme = |issue: &str| {
            format!(
                "    // :::{{fixme}} requirements.rule\n    // :github: o/r#{issue}\n    // Panics instead of reporting.\n    // :::\n"
            )
        };
        let source = SOURCE
            .replace(
                "fn check_two() {}",
                &format!("fn check_two() {{\n{}}}", fixme("1")),
            )
            .replace(
                "fn other() { panic!(\"y\"); }",
                &format!("fn other() {{\n{}}}", fixme("2")),
            );
        let temp = project(RULE, &source);
        let root = temp.path();
        fs::write(
            root.join("evidence/requirements.rule.json"),
            json!({"requirement": "x", "determination": true, "rationale": "Fine.", "inputs": []})
                .to_string(),
        )
        .unwrap();
        crate::evidence::tests::stamp_reference_sets(root);
        write_review(
            root,
            "fn[check_two]",
            json!({"determination": {"FIXME": ["o/r#1"]}}),
        );
        let (errors, _) = inspect(root);
        let coverage = errors
            .iter()
            .filter(|error| error.contains("no input covers {fixme}"))
            .collect::<Vec<_>>();
        assert!(coverage.is_empty(), "{errors:#?}");
        let two = review_errors(&errors, "fn[check_two]").join("\n");
        assert!(
            two.contains("{fixme} references to requirements.rule inside src/lib.rs fn[check_two] changed: recorded [], now [{\"item\":\"fn[check_two]\",\"commentary\":\":github: o/r#1\\n Panics instead of reporting.\"}]"),
            "{two}"
        );
        assert!(!two.contains("FIXME entry"), "{two}");

        // Editing the in-site `{fixme}` leaves the requirement's reference
        // set unchanged; editing the other changes it.
        let digest = crate::evidence::reference_set_digest_for(root, "requirements.rule").unwrap();
        fs::write(
            root.join("src/lib.rs"),
            source.replacen("Panics instead", "Still panics instead", 1),
        )
        .unwrap();
        assert_eq!(
            crate::evidence::reference_set_digest_for(root, "requirements.rule").unwrap(),
            digest
        );
        fs::write(
            root.join("src/lib.rs"),
            source.replace(
                "// Panics instead of reporting.\n    // :::\n}\nmod",
                "// Edited.\n    // :::\n}\nmod",
            ),
        )
        .unwrap();
        assert_ne!(
            crate::evidence::reference_set_digest_for(root, "requirements.rule").unwrap(),
            digest
        );

        // A review recording the in-site `{fixme}` is current; reflowing its
        // body keeps it current, and changing its words makes it stale.
        fs::write(root.join("src/lib.rs"), &source).unwrap();
        crate::evidence::tests::stamp_reference_sets(root);
        write_review(
            root,
            "fn[check_two]",
            json!({
                "determination": {"FIXME": ["o/r#1"]},
                "fixmes": [{"item": "fn[check_two]", "commentary": ":github: o/r#1\n Panics instead of reporting."}],
            }),
        );
        let changed = |root: &Path| {
            let (errors, _) = inspect(root);
            review_errors(&errors, "fn[check_two]")
                .into_iter()
                .filter(|error| error.contains("{fixme} references"))
                .collect::<Vec<_>>()
        };
        assert_eq!(changed(root), Vec::<String>::new());
        fs::write(
            root.join("src/lib.rs"),
            source.replacen(
                "    // Panics instead of reporting.\n",
                "    // Panics instead\n    // of reporting.\n",
                1,
            ),
        )
        .unwrap();
        assert_eq!(changed(root), Vec::<String>::new());
        fs::write(
            root.join("src/lib.rs"),
            source.replacen("Panics instead", "Still panics instead", 1),
        )
        .unwrap();
        assert_eq!(changed(root).len(), 1);
    }
Input 11: outline src/evidence.rs fn[evidence_input_ranges]
// {impl}`requirements.references.evidence_coverage`
/// Unreadable records and unresolvable inputs contribute no ranges: their
/// own checks report them, and coverage checking continues.
fn evidence_input_ranges(
    root: &Path,
    path: &Path,
    definitions: &BTreeMap<String, Declaration>,
    outlines: &OutlineCache,
) -> Vec<InputRange> {
    let Some(inputs) = fs::read_to_string(path)
        .ok()
        .and_then(|content| serde_json::from_str::<Value>(&content).ok())
        .and_then(|value| value.get("inputs").and_then(Value::as_array).cloned())
    else {
        return Vec::new();
    };
    inputs
        .iter()
        .filter_map(InputSelector::from_input)
        .filter_map(|selector| selector.resolve(root, definitions, outlines).ok())
        .flat_map(|resolved| {
            let node = resolved.node;
            resolved
                .ranges
                .into_iter()
                .filter_map(|range| {
                    Some(InputRange {
                        file: fs::canonicalize(root.join(range.file)).ok()?,
                        line_start: range.line_start,
                        line_end: range.line_end,
                        node: node.clone(),
                    })
                })
                .collect::<Vec<_>>()
        })
        .collect()
}
Input 12: outline tests/outcomes.rs fn[editing_or_adding_a_fixme_makes_evidence_stale_without_requiring_source_reads]
  • File: tests/outcomes.rs
  • Selector: fn[editing_or_adding_a_fixme_makes_evidence_stale_without_requiring_source_reads]
  • Kind: fn
  • tests/outcomes.rs:529–572
// {test}`requirements.ci.reference_set`
// {test}`requirements.references.evidence_coverage`
// {test}`requirements.authoring.fixme_inputs`
#[test]
fn editing_or_adding_a_fixme_makes_evidence_stale_without_requiring_source_reads() {
    let temp = fixture();
    let observed = temp.path().join("observed.rs");
    let source = fs::read_to_string(&observed).unwrap();
    // Comments do not change the input's hash, but the `{fixme}` body is
    // part of the reference set.
    fs::write(&observed, source.replace("are untested", "remain untested")).unwrap();
    let errors = habeas::validate_repository(temp.path()).unwrap().errors;
    assert!(
        errors.iter().any(
            |error| error.contains("evidence/requirements.timeout.json: reference set changed")
        ),
        "{errors:?}"
    );
    assert!(
        !errors
            .iter()
            .any(|error| error.contains("outline input changed")),
        "{errors:?}"
    );
    fs::write(&observed, &source).unwrap();
    fs::write(
        temp.path().join("other.rs"),
        fixme("requirements.timeout", &[], "Another gap."),
    )
    .unwrap();
    let errors = habeas::validate_repository(temp.path()).unwrap().errors;
    assert!(
        errors.iter().any(
            |error| error.contains("evidence/requirements.timeout.json: reference set changed")
        ),
        "{errors:?}"
    );
    assert!(
        !errors
            .iter()
            .any(|error| error.contains("no input covers {fixme}")),
        "{errors:?}"
    );
}
Input 13: outline tests/authoring_batch.rs fn[batch_reauthors_a_false_judgment_when_its_reference_set_changes]
/// A new test reference changes the reference set and requires its source
/// to be supplied on reassessment, even when the old assessment read no code.
// {test}`requirements.authoring.batch`
// {test}`requirements.ci.reference_set`
// {test}`requirements.authoring.refresh`
#[test]
fn batch_reauthors_a_false_judgment_when_its_reference_set_changes() {
    let server = Server::start(false, None);
    let fixture = Fixture::new(&server.endpoint, Some(2));
    let output = fixture.run(&["author", "--all"]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(server.subjects().len(), 6);
    for name in ["requirements.alpha", "requirements.delta"] {
        assert_eq!(
            fixture.evidence(name)["references"],
            habeas::reference_set_digest_for(&fixture.project, name).unwrap()
        );
    }
    let path = fixture.project.join("evidence/requirements.delta.json");
    let mut record = fixture.evidence("requirements.delta");
    record["determination"] = json!(false);
    record["rationale"] = json!("The behavior has no {test} reference.");
    fs::write(&path, serde_json::to_vec_pretty(&record).unwrap()).unwrap();

    let source = fixture.project.join("src/lib.rs");
    fs::write(
        &source,
        fs::read_to_string(&source).unwrap().replace(
            "pub fn delta() -> u8 { 4 }",
            "pub fn delta() -> u8 {\n    // {test}`requirements.delta`\n    4\n}",
        ),
    )
    .unwrap();
    let errors = habeas::validate_repository(&fixture.project)
        .unwrap()
        .errors;
    assert_eq!(errors.len(), 3, "{errors:?}");
    assert!(
        errors[0].starts_with("evidence/requirements.delta.json: determination is false")
            && errors[1].starts_with("evidence/requirements.delta.json: reference set changed"),
        "{errors:?}"
    );
    assert!(errors[2].contains("no input covers {test}"), "{errors:?}");

    let stale = fixture.run(&["author", "--all"]);
    assert!(
        stale.status.success(),
        "{}",
        String::from_utf8_lossy(&stale.stderr)
    );
    let subjects = server.subjects();
    assert_eq!(subjects.len(), 7, "{subjects:?}");
    assert_eq!(subjects[6], "requirement requirements.delta");
    assert_eq!(
        String::from_utf8_lossy(&stale.stdout).trim(),
        "1 authored; 5 skipped as current; 0 failed; policy once"
    );
    assert_eq!(
        fixture.evidence("requirements.delta")["references"],
        habeas::reference_set_digest_for(&fixture.project, "requirements.delta").unwrap()
    );
    let report = habeas::validate_repository(&fixture.project).unwrap();
    assert!(report.errors.is_empty(), "{:?}", report.errors);
}