requirements.ci.coverage
Requirements index · View definition
Requirement
Repository validation MUST check that every requirement defined by a fenced
{req}directive in a chapter under the configured mdBook source directory has an evidence file namedevidence/<full-requirement-name>.json, and MUST report each requirement whose evidence file is missing. The full name MUST use the chapter’s path-derived namespace followed by the directive name; for example, a directive namedcheckinmd/requirements.mdhas the full namerequirements.check.
Rationale
I found no gaps. Each obligation maps to code reachable from the {impl} item, and each has a test.
Obligations
- Every requirement defined by a fenced
{req}directive under the configured book source directory is checked for an evidence fileevidence/<full-name>.json. - Each requirement whose evidence file is missing is reported.
- The full name is the chapter’s path-derived namespace followed by the directive name.
Code
- Impl item:
src/evidence.rs#fn[inspect_repository_with_progress]carries the{impl}reference. It resolves the book source withbook_source_dirand builds the definitions withcollect_definitions. It records which names have an evidence file in thepresentset. It then loops overdefinitions. For each non-term definition not inpresent, it pushes the errorevidence/{name}.json: missing for requirement at <source>. This covers the obligation to report each missing file. - Definitions:
src/evidence.rs#fn[collect_definitions]walks the.mdchapters under the configured source directory and skipsSUMMARY.md. It parses{req}and{example}blocks withdefinition_blocks, which scans colon-fenced directives and ignores code blocks. This code is reachable from the impl item. - Full name: The name is
full_requirement_name(&chapter_namespace(relative), &block.name). Insrc/lib.rs,chapter_namespacedrops the.mdextension. It joins the path components with.. It strips a leadingreqsand a trailingindexorREADMEwhen the path is nested. Formd/requirements.mdthe result isrequirements.check, as the text’s example requires. - Examples: The same loop also reports missing evidence for examples. That behavior is specified by
requirements.examples.evidence, which the same code marks with{impl}, so it is not an unspecified gap.
Tests
src/evidence.rs#mod[tests]/fn[validates_full_names_requirement_text_and_input_lines]has a{test}reference. It definesreadyinmd/reqs/foo/bar.mdand suppliesevidence/foo.bar.ready.json. It asserts there are no errors, so the path-derived full name matches the evidence file name. The test also puts a{req}role inside a code block, so that case is exercised too.src/evidence.rs#mod[tests]/fn[collects_missing_orphan_format_false_and_changed_line_errors]has a{test}reference. It defines requirementstwoandemptyinmd/requirements.mdwith no evidence files. It asserts the report containsmissing for requirement, which covers the missing-evidence reporting path.
Inputs
Implementation
Input 2: outline src/evidence.rs fn[inspect_repository_with_progress]
- File:
src/evidence.rs - Selector:
fn[inspect_repository_with_progress] - Kind:
fn src/evidence.rs:185–386
// {impl}`requirements.ci.errors`
// {impl}`requirements.examples.evidence`
// {impl}`requirements.configuration.workspace_location`
// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.ci.book_source`
// {impl}`requirements.definitions.declaration`
// {impl}`requirements.references.builtin_definitions`
// {impl}`requirements.ci.determination`
pub(crate) fn inspect_repository_with_progress(
root: &Path,
mut progress: impl FnMut(InspectionProgress),
) -> io::Result<RepositoryInspection> {
let root = fs::canonicalize(root)?;
progress(InspectionProgress {
stage: "discovering requirements",
completed: 0,
total: None,
});
let mut errors = Vec::new();
if let Err(error) = crate::config::load_workspace_evidence(&root) {
errors.push(error.to_string());
}
let md_root = book_source_dir(&root, &mut errors);
let definitions = collect_definitions(&root, &md_root, &mut errors);
let mut discovery_errors = errors.clone();
// {impl}`requirements.test-coverage.setup.validation`
// {impl}`requirements.test-coverage.setup.validation.static`
if let Err(error) = crate::execution_coverage::validate_setup(&root) {
errors.push(error.to_string());
}
// Only the coverage report uses `[coverage]`, so an invalid table is a
// finding but not a discovery failure, and authoring still proceeds.
if let Some(error) = crate::config::coverage_error(&root) {
errors.push(error.to_string());
}
let evidence_root = root.join("evidence");
let listing_errors = errors.len();
let evidence_files = if evidence_root.is_dir() {
files_with_extension(&root, &evidence_root, "json", &mut errors)
} else {
Vec::new()
};
let evidence_listed = errors.len() == listing_errors;
let mut present = BTreeSet::new();
let outlines = OutlineCache::default();
// Citation reviews are validated against their source items below.
let (review_files, ordinary_files): (Vec<_>, Vec<_>) = evidence_files
.iter()
.partition(|file| crate::citations::is_review_path(&evidence_root, file));
let review_files: Vec<PathBuf> = review_files.into_iter().cloned().collect();
// Site reviews are validated against the sites of their requirements.
// {impl}`requirements.ci.orphans`
let (site_files, ordinary_files): (Vec<_>, Vec<_>) = ordinary_files
.into_iter()
.partition(|file| crate::sites::is_review_path(&evidence_root, file));
let site_files: Vec<PathBuf> = site_files.into_iter().cloned().collect();
// {impl}`requirements.ci.orphans`
for (completed, file) in ordinary_files.iter().enumerate() {
progress(InspectionProgress {
stage: "evidence files",
completed,
total: Some(ordinary_files.len()),
});
let relative = file
.strip_prefix(&evidence_root)
.expect("evidence file is inside evidence directory");
let label = display_path(&root, file);
let name = if relative.components().count() == 1 {
relative
.file_name()
.and_then(|part| part.to_str())
.and_then(|part| part.strip_suffix(".json"))
} else {
None
};
let expected = name
.and_then(|name| definitions.get(name))
.filter(|d| d.kind != DefinitionKind::Term);
if let Some(name) = name.filter(|_| expected.is_some()) {
present.insert(name.to_owned());
} else {
errors.push(format!("{label}: no matching requirement or example"));
}
validate_evidence_file(&root, file, expected, &definitions, &outlines, &mut errors);
}
progress(InspectionProgress {
stage: "evidence files",
completed: ordinary_files.len(),
total: Some(ordinary_files.len()),
});
// {impl}`requirements.ci.coverage`
// Missing evidence is reported as a validation error; inspection never
// starts authoring.
// {impl}`requirements.authoring.deterministic_validation`
for (name, definition) in &definitions {
if definition.kind != DefinitionKind::Term && !present.contains(name) {
errors.push(format!(
"evidence/{name}.json: missing for {} at {}",
definition.kind.noun(),
definition.source
));
}
}
// Unreadable reference sources are discovery failures: a batch must not
// treat a partial scan as complete.
let scanned = errors.len();
progress(InspectionProgress {
stage: "discovering source references",
completed: 0,
total: None,
});
let files = discovered_files(&root, &mut errors);
let references = collect_references_with_progress(&root, &files, &mut errors, &mut progress);
discovery_errors.extend(errors[scanned..].iter().cloned());
validate_committed_credentials(&root, &mut errors);
// {impl}`requirements.references.distributed`
let sites = crate::sites::discover(
&root,
&definitions,
&files,
&outlines,
&mut errors,
&mut discovery_errors,
);
validate_references(
&root,
&definitions,
&references,
&sites,
&outlines,
&mut errors,
&mut progress,
);
crate::citations::validate(
&root,
&definitions,
&references,
&outlines,
&review_files,
&mut errors,
&mut progress,
);
crate::sites::validate(
&root,
&definitions,
&references,
&sites,
&outlines,
&site_files,
&mut errors,
&mut progress,
);
crate::rust_coverage::validate_cargo_examples(
&root,
&files,
&definitions,
&references,
&mut errors,
);
// An item an evidence record or review read is covered.
// {impl}`requirements.references.rust_item_coverage`
let reads = crate::rust_coverage::EvidenceReads::load(&evidence_files);
let uncovered = crate::rust_coverage::validate_rust_functions(
&root,
&files,
&definitions,
&reads,
&mut errors,
&mut discovery_errors,
&mut progress,
);
let examples = definitions
.values()
.filter(|definition| definition.kind == DefinitionKind::Example)
.count();
let requirements = definitions
.values()
.filter(|definition| definition.kind == DefinitionKind::Requirement)
.count();
Ok(RepositoryInspection {
root: root.clone(),
report: EvidenceReport {
requirements,
examples,
evidence_files: evidence_files.len(),
errors,
},
definitions,
references,
sites,
uncovered,
evidence_files,
evidence_listed,
discovery_errors,
})
}
Tests
Input 3: outline src/evidence.rs mod[tests]/fn[validates_full_names_requirement_text_and_input_lines]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[validates_full_names_requirement_text_and_input_lines] - Kind:
fn src/evidence.rs:2533–2564
// {test}`requirements.integration.report_api`
// {test}`requirements.ci.book_source`
// {test}`requirements.ci.coverage`
// {test}`requirements.ci.requirement_text`
// {test}`requirements.ci.outline_inputs`
// {test}`requirements.ci.identifiers`
// {test}`requirements.ci.span`
#[test]
fn validates_full_names_requirement_text_and_input_lines() {
let temp = fixture();
fs::write(
temp.path().join("md/reqs/foo/bar.md"),
"# Requirements\n\n:::{req} ready\n\n The check MUST pass.\n\n```text\n{req}`example`\n```\n:::\n",
)
.unwrap();
fs::write(
temp.path().join("evidence/foo.bar.ready.json"),
json!({
"requirement": "The check MUST pass.\n\n```text\n{req}`example`\n```",
"determination": true,
"rationale": "The inspected file has the expected lines.",
"inputs": [outline(temp.path(), "src/main.rs", "")]
})
.to_string(),
)
.unwrap();
let report = validate_repository(temp.path()).unwrap();
assert_eq!(report.requirements, 1);
assert_eq!(report.evidence_files, 1);
assert!(report.errors.is_empty(), "{:?}", report.errors);
}
Input 4: outline src/evidence.rs mod[tests]/fn[collects_missing_orphan_format_false_and_changed_line_errors]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[collects_missing_orphan_format_false_and_changed_line_errors] - Kind:
fn src/evidence.rs:2566–2667
// {test}`requirements.integration.report_api`
// {test}`requirements.ci.errors`
// {test}`requirements.ci.diagnostics`
// {test}`requirements.ci.input_containment`
// {test}`requirements.ci.definition_errors`
// {test}`requirements.ci.orphans`
// {test}`requirements.ci.coverage`
// {test}`requirements.ci.determination`
// {test}`requirements.ci.outline_inputs`
// {test}`requirements.ci.requirement_text`
// {test}`requirements.ci.schema`
#[test]
fn collects_missing_orphan_format_false_and_changed_line_errors() {
let temp = fixture();
fs::write(
temp.path().join("md/requirements.md"),
"# Requirements\n\n:::{req} one\nFirst.\n:::\n\n:::{req} two\nSecond.\n:::\n\n:::{req} three\nThird.\n:::\n\n:::{req} one\nDuplicate.\n:::\n\n:::{req} empty\n \n:::\n",
)
.unwrap();
fs::write(
temp.path().join("evidence/requirements.one.json"),
json!({
"requirement": "Old text.",
"determination": false,
"rationale": "Work remains.",
"inputs": [
{
"file": "src/main.rs",
"item": "",
"hash": "0".repeat(64)
},
{
"file": "",
"item": 0,
"hash": "ABC"
},
{
"file": "src/main.rs",
"item": "fn[missing]",
"hash": "0".repeat(64)
},
{
"file": "src/main.rs",
"line_start": 1,
"line_end": 1,
"text": ["// first line"]
},
{
"requirements": "requirements.two",
"matches": ["requirements.two"],
"text": [1]
}
]
})
.to_string(),
)
.unwrap();
fs::write(
temp.path().join("evidence/requirements.three.json"),
json!({"requirement": 3, "inputs": {}}).to_string(),
)
.unwrap();
fs::write(
temp.path().join("evidence/ghost.json"),
json!({
"requirement": "Ghost.",
"determination": true,
"rationale": "A valid but orphaned file.",
"inputs": []
})
.to_string(),
)
.unwrap();
fs::write(temp.path().join("evidence/broken.json"), "{").unwrap();
let report = validate_repository(temp.path()).unwrap();
let errors = report.errors.join("\n");
for detail in [
"no matching requirement",
"invalid JSON",
"missing for requirement",
"requirement text changed",
"- Old text.",
"+ First.",
"determination is false",
"inputs[0]: outline input changed: src/main.rs <root> (now lines 1-2) no longer has the recorded hash",
"inputs[1]: file must be a nonempty path",
"inputs[1]: item must be a string",
"inputs[1]: hash must be a lowercase hexadecimal SHA-256 digest",
"inputs[2]: src/main.rs: no outline node matches \"fn[missing]\"",
"inputs[3]: unexpected field \"line_start\"",
"inputs[3]: missing field \"item\"",
"inputs[4]: text[0] must be a string",
"requirement must be a string",
"missing field \"determination\"",
"inputs must be an array",
"duplicate requirement requirements.one; first declared at md/requirements.md:3",
"requirement requirements.empty has no text",
] {
assert!(errors.contains(detail), "missing {detail:?} in:\n{errors}");
}
}
Other sources
Input 1: requirements selection requirements.ci.coverage
requirements.ci.coverage:md/requirements/ci.md:3–5
:::{req} coverage
Repository validation MUST check that every requirement defined by a fenced `{req}` directive in a chapter under the configured mdBook source directory has an evidence file named `evidence/<full-requirement-name>.json`, and MUST report each requirement whose evidence file is missing. The full name MUST use the chapter's path-derived namespace followed by the directive name; for example, a directive named `check` in `md/requirements.md` has the full name `requirements.check`.
:::
Input 5: outline src/evidence.rs fn[collect_definitions]
- File:
src/evidence.rs - Selector:
fn[collect_definitions] - Kind:
fn src/evidence.rs:442–593
// {impl}`requirements.examples.definition`
// {impl}`requirements.ci.requirements_inputs`
// {impl}`requirements.ci.errors`
// {impl}`requirements.ci.identifiers`
// {impl}`requirements.definitions.declaration`
fn collect_definitions(
root: &Path,
md_root: &Path,
errors: &mut Vec<String>,
) -> BTreeMap<String, Declaration> {
let mut definitions = BTreeMap::new();
for file in files_with_extension(root, md_root, "md", errors) {
let relative = file
.strip_prefix(md_root)
.expect("chapter file is inside md directory");
if relative == Path::new("SUMMARY.md") {
continue;
}
let label = display_path(root, &file);
let content = match fs::read_to_string(&file) {
Ok(content) => content,
Err(error) => {
errors.push(format!("{label}: cannot read chapter: {error}"));
continue;
}
};
let namespace = chapter_namespace(relative);
let blocks = definition_blocks(&content);
crate::sites::validate_query_placement(&label, &content, &blocks, errors);
for block in &blocks {
let line = content[..block.start]
.bytes()
.filter(|byte| *byte == b'\n')
.count()
+ 1;
let source = format!("{label}:{line}");
let name = full_requirement_name(&namespace, &block.name);
// An invalid name declares nothing, but the checks of the
// declaration's fence, options, and text still run.
let named = if name.starts_with("habeas:") || block.name.starts_with("habeas:") {
errors.push(format!(
"{source}: invalid {} name {name:?}: names beginning with habeas: are reserved for built-in definitions",
block.kind.noun()
));
false
} else if !valid_name(&name) {
errors.push(format!(
"{source}: invalid {} name {name:?}",
block.kind.noun()
));
false
} else {
true
};
if !block.closed {
errors.push(format!(
"{source}: {} {name} is missing a closing colon fence",
block.kind.noun()
));
}
// {impl}`requirements.ci.span`
// {impl}`requirements.ci.requirement_text`
let text = crate::without_options(&content, block.body_start..block.body_end, &blocks)
.trim()
.to_owned();
let mut anchors = Vec::new();
for option in &block.options {
let kind = match (block.kind, option.name.as_str()) {
(DefinitionKind::Requirement, "impl") => ReferenceKind::Impl,
(DefinitionKind::Requirement | DefinitionKind::Example, "test") => {
ReferenceKind::Test
}
_ => {
errors.push(format!(
"{label}:{}: {} {name} has unsupported option :{}:",
option.line,
block.kind.noun(),
option.name
));
continue;
}
};
if option.value.is_empty() {
errors.push(format!(
"{label}:{}: {} {name} has an :{}: option without a file path",
option.line,
block.kind.noun(),
option.name
));
continue;
}
anchors.push(Anchor::parse(kind, &option.value));
}
if text.is_empty() {
errors.push(format!(
"{source}: {} {name} has no text",
block.kind.noun()
));
}
if block.kind == DefinitionKind::Term
&& let Err(error) = crate::terms::declaration(&text)
{
errors.push(format!("{source}: definition {name}: {error}"));
}
if !named {
continue;
}
match definitions.entry(name.clone()) {
Entry::Vacant(slot) => {
let raw_lines =
crate::without_options(&content, block.start..block.end, &blocks)
.lines()
.map(|line| line.strip_suffix('\r').unwrap_or(line).to_owned())
.collect::<Vec<_>>();
let line_count = content[block.start..block.end].lines().count();
slot.insert(Declaration {
kind: block.kind,
text,
source,
file: label.clone(),
line_start: line,
line_end: line + line_count.saturating_sub(1),
raw_lines,
anchors,
});
}
Entry::Occupied(previous) => errors.push(format!(
"{source}: duplicate {} {name}; first declared at {}",
block.kind.noun(),
previous.get().source
)),
}
}
}
for (name, definition) in &definitions {
if definition.kind == DefinitionKind::Example
&& !example_references_requirement(definition, &definitions)
{
errors.push(format!(
"{}: example {name} must reference at least one requirement with {{cite}} or {{test}}",
definition.source
));
}
}
definitions
}