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.test-coverage.check.exceptions.author

Requirements index · View definition

evidence Valid

Requirement

The habeas author workflow MUST support authoring and refreshing exception evidence under cite requirements.test-coverage.check.exceptions. Assessment inputs MUST include the current file or function source, the built-in’s fixed text, and its citation commentary under cite requirements.references.citation_review.

Justifications and their assessment evidence MUST be retainable in Git independently of the disposable coverage artifacts under cite requirements.test-coverage.storage. Raw profiles, coverage reports, and captured source snapshots MUST NOT be required in Git to validate an exception against freshly collected coverage.

Rationale

The two marked tests cover the obligations of requirements.test-coverage.check.exceptions.author. I found no adequacy gap.

1. Authoring and refreshing exception evidence under the standard citation review.

  • src/authoring/mod.rs#mod[tests]/fn[coverage_explanations_use_standard_citation_authoring_and_freshness] authors citations:src/lib.rs#fn[helper] for a habeas:coverage fenced explanation. It asserts the resulting record has determination true and a citation named habeas:coverage.
  • The same test then edits the explanation (“inaccessible” to “reachable”) and runs validate_review. It asserts a “citations changed” error, so the review goes stale and needs refreshing.
  • src/execution_coverage/check.rs#mod[tests]/fn[standard_inline_doc_and_fenced_commentary_reviews_track_their_explanations] covers the exception side for both explanation forms: an inline /// doc comment plus {cite}, and a fenced :::{cite} block. In both cases an accepted review gives accepted true with no errors, and editing the explanation makes the exception not accepted and reports errors. The fenced case asserts the “citations changed” message.

2. Assessment inputs must include the current source, the built-in’s fixed text and the commentary.

  • The authoring test asserts the first mandatory input has item equal to fn[helper], text containing fn helper() {}, and a 64-character hash.
  • It asserts a mandatory input with builtin equal to habeas:coverage whose text contains “difficulty alone”, which is the built-in’s fixed text.
  • It asserts the initial prompt contains the commentary (“Defensive invariant abort”) and the built-in citation guidance (“For a built-in citation”, “MUST NOT submit a FIXME”).
  • It asserts the recorded inputs contain the file, selector and hash of the item, and no builtin entries.
  • The requirement’s “file or function source” wording could also cover a file-root subject. That path goes through the same prepare_citation and root-selector handling as a function, and I found no separate branch for it. Other tests in src/execution_coverage/check.rs also use file-level //! explanations, though they are not marked for this requirement.

3. Evidence must be retainable in Git without disposable coverage artifacts.

  • The last section of the check.rs test copies only evidence/citations/code.rs/fn[a].json into a fresh fixture directory, as a different checkout. It asserts the exception is accepted there with no errors.
  • No coverage runs, profiles or source snapshots are present in that directory. Acceptance therefore needs only the Git-tracked source comment and the review JSON.
  • The same test shows identities are project-relative rather than tied to a checkout path.

The check_saved handling of fresh coverage is delegated to other requirements (check.exceptions, check.exceptions.reviews). The cited requirements citation_review and storage are context only and were not reassessed.

Inputs

Implementation

Input 7: outline src/execution_coverage/check.rs fn[exceptions]
// {impl}`requirements.test-coverage.check.exceptions.reviews`
// {impl}`requirements.test-coverage.check.exceptions.binding`
// {impl}`requirements.test-coverage.check.exceptions.author`
fn exceptions(
    root: &Path,
    outlines: &OutlineCache,
    errors: &mut Vec<String>,
) -> io::Result<BTreeMap<(String, String), Exception>> {
    let references = crate::evidence::collect_references(root, errors);
    let definitions = match crate::evidence::load_definitions(root) {
        Ok(definitions) => definitions,
        Err(error) => {
            errors.push(error.to_string());
            return Ok(BTreeMap::new());
        }
    };
    let items = citation_items(root, &definitions, &references, outlines);
    let mut accepted = BTreeMap::new();
    for (key, item) in items {
        if !item
            .citations
            .iter()
            .any(|citation| citation.name == "habeas:coverage")
        {
            continue;
        }
        let mut findings = Vec::new();
        let path = item.review_path();
        if root.join(&path).is_file() {
            validate_review(root, &path, &item, &definitions, outlines, &mut findings);
        } else {
            findings.push(format!(
                "{path}: missing citation review; run `habeas author {}`",
                crate::citations::subject_label(&item.file, &item.item)
            ));
        }
        let justification = outlines.parse(root, &item.file);
        let docs = justification
            .as_ref()
            .as_ref()
            .ok()
            .and_then(|parsed| {
                parsed
                    .resolve(&item.file, &item.item)
                    .ok()
                    .map(|node| super::notes::doc_comments(parsed, node))
            })
            .unwrap_or_default();
        let commentary = item
            .citations
            .iter()
            .filter(|citation| citation.name == "habeas:coverage")
            .map(|citation| citation.commentary.trim())
            .filter(|text| !text.is_empty())
            .collect::<Vec<_>>()
            .join("\n\n");
        accepted.insert(
            key,
            Exception {
                accepted: findings.is_empty(),
                review_missing: root
                    .join(&path)
                    .symlink_metadata()
                    .is_err_and(|error| error.kind() == io::ErrorKind::NotFound),
                justification: [commentary, docs]
                    .into_iter()
                    .filter(|text| !text.trim().is_empty())
                    .collect::<Vec<_>>()
                    .join("\n\n"),
                findings: findings.clone(),
            },
        );
        errors.extend(findings);
    }
    Ok(accepted)
}

Tests

Input 5: outline src/authoring/mod.rs mod[tests]/fn[coverage_explanations_use_standard_citation_authoring_and_freshness]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[coverage_explanations_use_standard_citation_authoring_and_freshness]
  • Kind: fn
  • src/authoring/mod.rs:4170–4259
    // {test}`requirements.test-coverage.check.exceptions.author`
    // {test}`requirements.references.citation_review`
    // {test}`requirements.authoring.citation_prompt`
    #[tokio::test]
    async fn coverage_explanations_use_standard_citation_authoring_and_freshness() {
        let project = inputs::tests::project();
        let source = "// :::{cite} habeas:coverage\n// Defensive invariant abort, inaccessible through the API.\n// :::\nfn helper() {}\n";
        fs::write(project.path().join("src/lib.rs"), source).unwrap();
        let subject = AuthoringSubject::parse("citations:src/lib.rs#fn[helper]");
        let mut sources = subject.sources(project.path()).unwrap();
        let mandatory = sources.mandatory_inputs().to_vec();
        assert_eq!(mandatory[0]["item"], "fn[helper]");
        assert!(
            mandatory[0]["text"].to_string().contains("fn helper() {}"),
            "{mandatory:?}"
        );
        assert!(
            mandatory[0]["hash"]
                .as_str()
                .is_some_and(|hash| hash.len() == 64),
            "{mandatory:?}"
        );
        assert!(mandatory.iter().any(|input| {
            input["builtin"] == "habeas:coverage"
                && input["text"][0]
                    .as_str()
                    .unwrap()
                    .contains("difficulty alone")
        }));
        let prompt = initial_prompt(&sources).unwrap().joined();
        assert!(prompt.contains("Defensive invariant abort"));
        assert!(prompt.contains("For a built-in citation"));
        assert!(prompt.contains("MUST NOT submit a FIXME"));
        let state = tempfile::tempdir().unwrap();
        let mut usage = UsageLog::start(state.path(), project.path(), &subject.label()).unwrap();
        let provider = RecordingProvider::new(vec![judgment(
            json!(true),
            "The supplied source and explanation support the citation.",
        )]);
        let (_, record) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        assert_eq!(record["determination"], true);
        assert_eq!(record["citations"][0]["name"], "habeas:coverage");
        assert!(
            record["inputs"]
                .as_array()
                .unwrap()
                .iter()
                .any(|input| input["file"] == "src/lib.rs"
                    && input["item"] == "fn[helper]"
                    && input["hash"] == mandatory[0]["hash"]),
            "{record:?}"
        );
        assert!(
            record["inputs"]
                .as_array()
                .unwrap()
                .iter()
                .all(|input| input.get("builtin").is_none())
        );
        let path = subject.evidence_path(project.path());
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, serde_json::to_vec(&record).unwrap()).unwrap();
        fs::write(
            project.path().join("src/lib.rs"),
            source.replace("inaccessible", "reachable"),
        )
        .unwrap();
        let definitions = crate::evidence::load_definitions(project.path()).unwrap();
        let mut errors = Vec::new();
        let references = crate::evidence::collect_references(project.path(), &mut errors);
        let outlines = crate::inputs::OutlineCache::default();
        let item =
            crate::citations::citation_items(project.path(), &definitions, &references, &outlines)
                .remove(&("src/lib.rs".into(), "fn[helper]".into()))
                .unwrap();
        crate::citations::validate_review(
            project.path(),
            &item.review_path(),
            &item,
            &definitions,
            &outlines,
            &mut errors,
        );
        assert!(
            errors
                .iter()
                .any(|error| error.contains("citations changed")),
            "{errors:?}"
        );
    }
Input 6: outline src/execution_coverage/check.rs mod[tests]/fn[standard_inline_doc_and_fenced_commentary_reviews_track_their_explanations]
    // {test}`requirements.test-coverage.check.exceptions.reviews`
    // {test}`requirements.test-coverage.check.exceptions.author`
    // {test}`requirements.test-coverage.check.exceptions`
    #[test]
    fn standard_inline_doc_and_fenced_commentary_reviews_track_their_explanations() {
        let source = "/// Defensive invariant abort, inaccessible through the API.\n// {cite}`habeas:coverage`\nfn a() {}\n";
        let temp = fixture(source);
        let root = temp.path();
        reviews(root, json!(true));
        let mut errors = Vec::new();
        assert!(
            exceptions(root, &OutlineCache::default(), &mut errors)
                .unwrap()
                .values()
                .all(|exception| exception.accepted)
        );
        assert!(errors.is_empty());
        fs::write(
            root.join("code.rs"),
            source.replace("inaccessible", "reachable"),
        )
        .unwrap();
        let mut errors = Vec::new();
        assert!(
            exceptions(root, &OutlineCache::default(), &mut errors)
                .unwrap()
                .values()
                .all(|exception| !exception.accepted)
        );
        assert!(!errors.is_empty());
        let source = "// :::{cite} habeas:coverage\n// A protected rationale.\n// :::\nfn a() {}\n";
        fs::write(root.join("code.rs"), source).unwrap();
        reviews(root, json!(true));
        fs::write(root.join("code.rs"), source.replace("protected", "changed")).unwrap();
        let mut errors = Vec::new();
        assert!(
            exceptions(root, &OutlineCache::default(), &mut errors)
                .unwrap()
                .values()
                .all(|exception| !exception.accepted)
        );
        assert!(
            errors
                .iter()
                .any(|error| error.contains("citations changed"))
        );
        // Exception evidence uses project-relative identities in another checkout.
        fs::write(root.join("code.rs"), source).unwrap();
        reviews(root, json!(true));
        let other = fixture(source);
        let path = "evidence/citations/code.rs/fn[a].json";
        fs::create_dir_all(other.path().join("evidence/citations/code.rs")).unwrap();
        fs::copy(root.join(path), other.path().join(path)).unwrap();
        let mut errors = Vec::new();
        assert!(
            exceptions(other.path(), &OutlineCache::default(), &mut errors)
                .unwrap()
                .values()
                .all(|exception| exception.accepted)
        );
        assert!(errors.is_empty());
    }

Referenced definitions

Input 2: requirements selection requirements.test-coverage.check.exceptions
:::{req} check.exceptions
An unmet file threshold or an unexecuted or not-measured function MAY satisfy
the coverage policy only
through current, accepted, independently assessed evidence explaining why its
coverage is incomplete. An exception MUST be attached to the source file or
function whose incomplete coverage it justifies. A file-threshold exception
MUST NOT automatically excuse untested functions.
An exception MUST NOT excuse another source item's incomplete coverage.
Changes to the source item, justification, or other inputs
of its citation review MUST invalidate the affected exception under
{cite}`requirements.references.citation_review`.

A source comment or unassessed justification alone MUST NOT count as accepted
exception evidence. Function and gap identities MUST remain portable between
equivalent local and CI checkouts rather than depend on checkout paths,
run identifiers, timestamps, or process identifiers.
:::
Input 3: requirements selection requirements.references.citation_review
:::{req} citation_review
Every source item outside the book that carries at least one `{cite}` reference
other than a citation of `habeas:util` under {cite}`requirements.references.util`
MUST have a citation review: an assessment of that item's citations, recorded at
`evidence/citations/<file>/<selector>.json`, where `<file>` is the item's
project-relative path, `<selector>` is its outline selector with every `/` and
`%` percent-encoded, and the root node uses `_root`. The review MUST use the
prompt defined by {cite}`requirements.authoring.citation_prompt`. For citations
of project requirements and examples, the reviewer MUST assess whether the item
should be re-checked or kept in sync when the cited definition changes, and
whether the reference procedure of
{cite}`requirements.references.procedure` calls for `{impl}` or `{test}` instead.
For citations of built-ins, the reviewer MUST check the permitted reference
roles and forms and any citation-review criteria stated in the built-in's fixed
text, using the item's source and commentary. A permitted citation role alone
MUST NOT suffice when the fixed text states additional criteria. Mandatory inputs,
under {cite}`requirements.authoring.mandatory_inputs`, MUST be the item's outline
node, each cited declaration or built-in text, and the citations' commentary. The record MUST contain the item's file and selector,
its citations by role, name, and commentary, `determination`, `rationale`, and
`inputs`, with determinations under {cite}`requirements.ci.outcomes`. Validation
MUST require a current, accepted review for every such item and report stale,
missing, or orphaned reviews; a review MUST become stale when the item's hash,
a cited declaration, or its citations or their commentary change. Authoring with
`--all` MUST include citation reviews, and `habeas author citations:<file>#<selector>`
MUST author the review of the one item it names, under
{cite}`requirements.authoring.refresh`, where omitting `#<selector>`
names the file's root node. A citation in a requirement or example
declaration is reviewed as part of that definition's own assessment instead.
:::
Input 4: requirements selection requirements.test-coverage.storage
:::{req} storage
Coverage runs MUST be stored as disposable build artifacts under
`habeas/coverage/` in the project's Cargo target directory
(`target/habeas/coverage/` with default Cargo settings), retaining earlier runs
until those artifacts are removed. Each run record MUST identify the run,
capture time, command, and test selection, and, when available, the source
revision and whether the source had uncommitted changes.
:::

Other sources

Input 1: requirements selection requirements.test-coverage.check.exceptions.author
:::{req} check.exceptions.author
The `habeas author` workflow MUST support authoring and refreshing exception
evidence under {cite}`requirements.test-coverage.check.exceptions`. Assessment
inputs MUST include the current file or function source, the built-in's fixed
text, and its citation commentary under
{cite}`requirements.references.citation_review`.

Justifications and their assessment evidence MUST be retainable in Git
independently of the disposable coverage artifacts under
{cite}`requirements.test-coverage.storage`. Raw profiles, coverage reports, and
captured source snapshots MUST NOT be required in Git to validate an exception
against freshly collected coverage.
:::
Input 8: outline src/authoring/mod.rs impl[AuthoringSubject]/fn[sources]
    /// Prepares the subject's sources and mandatory inputs.
    // {impl}`requirements.authoring.mandatory_inputs`
    fn sources(&self, root: &Path) -> io::Result<AssessmentSources> {
        match self {
            Self::Definition(name) => AssessmentSources::prepare(root, name),
            Self::Citation { file, item } => AssessmentSources::prepare_citation(root, file, item),
            Self::Site {
                requirement,
                file,
                item,
            } => AssessmentSources::prepare_site(root, requirement, file, item),
        }
    }