requirements.ci.errors
Requirements index · View definition
Requirement
Repository validation MUST continue after a failed check and report every failed check it finds in one run, each as a validation error. This is a convention for every validation error; the requirement for each check states which conditions that check reports. A file that cannot be parsed, such as a malformed
habeas.toml,book.toml, or evidence file, is one failed check: its error MAY report only the first parse or decoding problem in that file, and checks that do not depend on its contents MUST still run.
- :::{sites} error_accumulators
language: rust paths: [src] exclude: [src/authoring/inputs.rs, src/authoring/tools.rs] rule: kind: function_item has: stopBy: { kind: function_item } any: - kind: parameter has: { field: pattern, regex: "^errors$" } - kind: let_declaration has: { field: pattern, regex: "^errors$" } not: inside: stopBy: end kind: mod_item has: { field: name, regex: "^tests$" } match: - "fn check(value: &str, errors: &mut Vec<String>) {}" - | fn run() { let mut errors: BTreeSet<String> = BTreeSet::new(); check("", &mut errors); } no_match: - "fn check(value: &str, discovery_errors: &mut Vec<String>) {}" - | fn run() { let mut problems = Vec::new(); check("", &mut problems); } - | mod tests { fn check(errors: &mut Vec<String>) {} }
- ::::
- :::{violations} early_exits
language: rust paths: [src] within: error_accumulators rule: any: - kind: try_expression - kind: return_expression - kind: continue_expression - kind: break_expression match: - | fn check(v: &Value, errors: &mut Vec<String>) -> Option<u8> { let n = v.as_u64()?; if v.is_null() { errors.push("null".into()); } Some(n as u8) } - | fn check(items: &[Value], errors: &mut Vec<String>) { for item in items { if !item.is_object() { errors.push("object".into()); continue; } if item.is_null() { errors.push("null".into()); } } } - | fn check(v: &Value, errors: &mut Vec<String>) { if !v.is_object() { errors.push("object".into()); return; } if v.is_null() { errors.push("null".into()); } } - | fn check(items: &[Value], errors: &mut Vec<String>) { for item in items { if !item.is_object() { errors.push("object".into()); break; } } if items.is_empty() { errors.push("empty".into()); } } no_match: - | fn parse(v: &Value) -> Option<u8> { let n = v.as_u64()?; Some(n as u8) }::::
Rationale
Obligations and where they are checked
- Continue after a failed check and report every failure in one run. This is the sequencing in
src/evidence.rs#fn[inspect_repository_with_progress]. These tests cover it:failed_checks_do_not_hide_later_independent_checkscombines several independent failures and asserts that all of their messages appear. The failures are an invalid chapter name, an empty requirement, a badtext,matchesandhashin evidence inputs, a missing file, and misplaced and empty{fixme}references.collects_missing_orphan_format_false_and_changed_line_errorsasserts a long list of independent errors from one run.inspection_progress_preserves_validation_and_finishes_each_phaseasserts that invalid JSON, an unparsable Rust file, and an uncovered item are all reported in one run. The uncovered item is not reported as a validation error.
- A file that cannot be parsed counts as one failed check, and independent checks still run.
configuration_and_dependency_failures_do_not_stop_later_checkscovers a badhabeas.toml, a malformedbook.toml([), a malformed evidence file ({), a bad.config/nextest.toml, and an invalid coverage setting. After each failure it asserts that the independent evidence and reference errors are still reported.status_loads_nearest_workspace_file_without_validating_authoringcovers a malformedhabeas.toml(version = [) and an invalid-version one. It asserts that the malformed-evidence error still appears throughstatusandinfo.- The MAY on reporting only the first parse problem imposes nothing to test.
- A failure is not reported twice. These tests assert it:
failed_checks_do_not_hide_later_independent_checkssorts and dedups the error list and compares lengths.configuration_and_dependency_failures_do_not_stop_later_checkscounts each message and compares the error list with its set.git_index_failure_is_reported_once_and_later_checks_still_runcounts the discovery error.an_unlistable_review_directory_is_reported_oncecounts the listing error.an_unreadable_record_is_reported_onceinsrc/index.rschecks that a record reported by validation is not reported again when it is loaded.accepted_exceptions_cannot_waive_invalid_measurement_and_checks_still_collect_errorsinsrc/execution_coverage/check.rsasserts no duplicate lines. It also asserts that parse failures and a badbook.srcare still reported alongside the coverage failures.
- Later checks in the same loop iteration, and not reporting twice, at each accumulator. The text assigns these to each site’s own review, so they need no test here. The tests above also exercise several of them: the chapter loop in
collect_definitions, the evidence loop,validate_input, andclose_dependencies. Further evidence isunclosed_fences_still_report_unknown_namesandcitation_reviews_are_required_current_and_not_orphanedintests/. validation_errorform. This is the convention for each message and is not a separate obligation here.
Site query error_accumulators
I ran it by name and scanned the matches. It selects functions that take or declare errors. Examples are DiscoverySources::files and walk, citations::validate, validate_review, parse_citation, and the many src/evidence.rs validators including inspect_repository_with_progress. Others are terms::close_dependencies, rust_coverage::validate_*, sites::discover, sites::validate_queries, sites::validate, execution_coverage::check_saved, execution_coverage::check::exceptions, and github::add_issue_findings.
- Overreach.
LoadedDetailEvidence::load_pathhas a localerrors. The text says any function with such a variable is a site, so this is not outside scope. Test modules are excluded, and the excluded authoring filesinputs.rsandtools.rshold abort-only collectors. - Misses. I searched
srcfor other accumulator forms. Names such asfailures,problems,findingsanddiagnosticsdo not fall under the text’s naming rule. I found nomut errorsparameter, no tuple destructuring in non-test code, and no non-test.errors.pushon a field outside the query. The only unmatchederrorsbindings are in test code, such as thelet (errors, _)tuple insrc/refactor/tests.rs. I found no place the query misses and no place outside the stated scope. - Snippets. The match snippets cover a parameter and a
letwith a non-Vectype. Theno_matchsnippets cover a differently named parameter (discovery_errors), a differently named local (problems), and a function insidemod tests. Together they exercise each condition of the rule.
Violation query early_exits
Its match snippets cover ?, continue, return, and break inside an accumulator function. The no_match snippet is a function without errors. Missing constructs would not be a gap anyway.
I found no gap in the tests or in the queries.
Inputs
Implementation
Input 16: outline src/terms.rs fn[close_dependencies]
- File:
src/terms.rs - Selector:
fn[close_dependencies] - Kind:
fn src/terms.rs:149–179
/// Expands referenced terms to a fixed point. Returns the resolvable
/// definitions and one problem per unresolvable term, continuing past each
/// problem so every one is found.
// {impl}`requirements.ci.errors`
fn close_dependencies(
declarations: &BTreeMap<String, Declaration>,
mut pending: BTreeSet<String>,
) -> (BTreeSet<String>, Vec<String>) {
let mut visited = BTreeSet::new();
let mut required = BTreeSet::new();
let mut errors = Vec::new();
while let Some(name) = pending.pop_first() {
if !visited.insert(name.clone()) {
continue;
}
let Some(definition) = declarations
.get(&name)
.filter(|d| d.kind == DefinitionKind::Term)
else {
errors.push(format!("term {name}: no matching named definition"));
// Without a definition there is no body whose terms to expand.
continue;
};
match declaration(&definition.text) {
Ok((_, body)) => referenced_terms(body, true, &mut pending),
Err(problem) => errors.push(problem),
}
required.insert(name);
}
(required, errors)
}
Input 17: outline src/authoring/access.rs impl[DiscoverySources]/fn[files]
- File:
src/authoring/access.rs - Selector:
impl[DiscoverySources]/fn[files] - Kind:
fn src/authoring/access.rs:250–274
/// Every considered file, sorted. In a Git worktree these are the indexed
/// files; outside Git, every file under the project root. Symlinks are not
/// followed, so no source is counted twice through an alias.
// {impl}`requirements.ci.errors`
pub(crate) fn files(&self, errors: &mut Vec<String>) -> Vec<PathBuf> {
let mut files: Vec<PathBuf> = match &self.tracked {
Some(tracked) => tracked
.iter()
.filter(|path| {
// An indexed file deleted from the worktree has no
// content to scan; an uninspectable one is kept so that
// reading it reports the failure.
fs::symlink_metadata(path).map_or_else(
|error| error.kind() != io::ErrorKind::NotFound,
|metadata| metadata.is_file(),
)
})
.filter(|path| self.considers(path, false))
.cloned()
.collect(),
None => self.walk(errors),
};
files.sort();
files
}
Input 18: outline src/authoring/access.rs impl[DiscoverySources]/fn[walk]
- File:
src/authoring/access.rs - Selector:
impl[DiscoverySources]/fn[walk] - Kind:
fn src/authoring/access.rs:329–385
/// Lists every file outside Git, skipping excluded and disallowed
/// directories without descending into them.
// {impl}`requirements.ci.errors`
fn walk(&self, errors: &mut Vec<String>) -> Vec<PathBuf> {
let root = &self.root;
let label = |path: &Path| {
path.strip_prefix(root)
.unwrap_or(path)
.display()
.to_string()
};
let mut stack = vec![root.clone()];
let mut files = Vec::new();
while let Some(directory) = stack.pop() {
let entries = match fs::read_dir(&directory) {
Ok(entries) => entries,
Err(error) => {
errors.push(format!(
"{}: cannot scan references: {error}",
label(&directory)
));
continue;
}
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(error) => {
errors.push(format!(
"{}: cannot scan directory entry: {error}",
label(&directory)
));
continue;
}
};
let path = entry.path();
let kind = match entry.file_type() {
Ok(kind) => kind,
Err(error) => {
errors.push(format!(
"{}: cannot inspect reference source: {error}",
label(&path)
));
continue;
}
};
if kind.is_dir() {
if self.considers(&path, true) {
stack.push(path);
}
} else if kind.is_file() && self.considers(&path, false) {
files.push(path);
}
}
}
files
}
Input 19: outline src/citations.rs fn[validate]
- File:
src/citations.rs - Selector:
fn[validate] - Kind:
fn src/citations.rs:206–267
/// Validates citation reviews: each current item needs a current, accepted
/// review, and every review file must belong to a current item. `files` are
/// the review files already listed with the rest of `evidence/`, so a listing
/// failure there is reported once.
/// Reports progress as the "citation reviews" phase: an activity display
/// while items are discovered, then one check per item and review file.
// {impl}`requirements.ci.outcomes`
// {impl}`requirements.ci.determination`
// {impl}`requirements.ci.errors`
pub(crate) fn validate(
root: &Path,
definitions: &BTreeMap<String, Declaration>,
references: &[SourceReference],
outlines: &OutlineCache,
files: &[PathBuf],
errors: &mut Vec<String>,
progress: &mut impl FnMut(InspectionProgress),
) {
progress(InspectionProgress {
stage: CITATION_STAGE,
completed: 0,
total: None,
});
let items = citation_items(root, definitions, references, outlines);
let total = items.len() + files.len();
let mut completed = 0;
let mut advance = |progress: &mut dyn FnMut(InspectionProgress)| {
progress(InspectionProgress {
stage: CITATION_STAGE,
completed,
total: Some(total),
});
completed += 1;
};
advance(progress);
let mut expected = BTreeSet::new();
for item in items.values() {
let path = item.review_path();
expected.insert(root.join(&path));
if root.join(&path).exists() {
validate_review(root, &path, item, definitions, outlines, errors);
} else {
errors.push(format!(
"{path}: missing citation review for {} {} at {}:{}",
item.file,
item.selector_label(),
item.file,
item.line
));
}
advance(progress);
}
for file in files {
if !expected.contains(file) {
errors.push(format!(
"{}: orphaned citation review: no source item outside the book with {{cite}} references matches it",
display_path(root, file)
));
}
advance(progress);
}
}
Input 20: outline src/citations.rs fn[validate_review]
- File:
src/citations.rs - Selector:
fn[validate_review] - Kind:
fn src/citations.rs:269–423
/// Validates one review file against its current item.
// {impl}`requirements.ci.errors`
pub(crate) fn validate_review(
root: &Path,
label: &str,
item: &CitationItem,
definitions: &BTreeMap<String, Declaration>,
outlines: &OutlineCache,
errors: &mut Vec<String>,
) {
let content = match fs::read_to_string(root.join(label)) {
Ok(content) => content,
Err(error) => {
errors.push(format!("{label}: cannot read citation review: {error}"));
return;
}
};
let value: Value = match serde_json::from_str(&content) {
Ok(value) => value,
Err(error) => {
errors.push(format!("{label}: invalid JSON: {error}"));
return;
}
};
let Some(object) = value.as_object() else {
errors.push(format!("{label}: expected a JSON object"));
return;
};
check_keys(
object,
&[
"file",
"item",
"citations",
"determination",
"rationale",
"inputs",
],
label,
errors,
);
if let Some(file) = string_field(object, "file", label, errors)
&& file != item.file
{
errors.push(format!("{label}: file must be {:?}", item.file));
}
if let Some(selector) = string_field(object, "item", label, errors)
&& selector != item.item
{
errors.push(format!("{label}: item must be {:?}", item.item));
}
if let Some(recorded) = array_field(object, "citations", label, errors) {
let parsed = recorded
.iter()
.enumerate()
.map(|(index, citation)| {
parse_citation(citation, &format!("{label}: citations[{index}]"), errors)
})
.collect::<Vec<_>>()
.into_iter()
.collect::<Option<Vec<_>>>();
if let Some(parsed) = parsed
&& !same_citations(&parsed, &item.citations)
{
errors.push(format!(
"{label}: citations changed for {} {}: recorded {}, now {}",
item.file,
item.selector_label(),
Value::Array(parsed.iter().map(Citation::to_value).collect()),
item.citations_value()
));
}
}
let determination = match object.get("determination") {
Some(value) => match Judgment::from_value(value) {
Ok(judgment) => Some(judgment),
Err(error) => {
errors.push(format!("{label}: determination: {error}"));
None
}
},
None => {
errors.push(format!("{label}: missing field \"determination\""));
None
}
};
let rationale = string_field(object, "rationale", label, errors);
if rationale.is_some_and(|text| text.trim().is_empty()) {
errors.push(format!("{label}: rationale must not be empty"));
}
// A citation review judges citations, which no `{fixme}` acknowledges.
if matches!(determination, Some(Judgment::Fixme(_))) {
errors.push(format!(
"{label}: determination is FIXME, but a citation review cannot accept a {{fixme}}; it must be true or false"
));
}
if determination == Some(Judgment::False) {
errors.push(format!(
"{label}: determination is false{}",
rationale
.filter(|text| !text.trim().is_empty())
.map_or(String::new(), |text| format!(": {}", text.trim()))
));
}
let Some(inputs) = array_field(object, "inputs", label, errors) else {
return;
};
let mut selects_item = false;
let mut cited = BTreeSet::new();
for (index, input) in inputs.iter().enumerate() {
validate_input(
root,
definitions,
outlines,
input,
&format!("{label}: inputs[{index}]"),
errors,
);
match InputSelector::from_input(input) {
Some(InputSelector::Outline {
file,
item: selector,
}) => {
selects_item |= file == item.file && selector == item.item;
}
Some(InputSelector::Requirements { .. }) => {
cited.extend(
input
.get("matches")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned),
);
}
_ => {}
}
}
if !selects_item {
errors.push(format!(
"{label}: inputs must select the reviewed item {} {}",
item.file,
item.selector_label()
));
}
for citation in &item.citations {
if crate::builtins::builtin(&citation.name).is_none() && !cited.contains(&citation.name) {
errors.push(format!(
"{label}: inputs must include the cited declaration {}",
citation.name
));
}
}
}
Input 21: outline src/citations.rs fn[parse_citation]
- File:
src/citations.rs - Selector:
fn[parse_citation] - Kind:
fn src/citations.rs:425–450
/// Parses one recorded citation.
// {impl}`requirements.ci.errors`
fn parse_citation(value: &Value, label: &str, errors: &mut Vec<String>) -> Option<Citation> {
let Some(object) = value.as_object() else {
errors.push(format!("{label}: expected a JSON object"));
return None;
};
check_keys(object, &["role", "name", "commentary"], label, errors);
let role = string_field(object, "role", label, errors).and_then(|role| match role {
"cite" => Some("cite"),
"impl" => Some("impl"),
"test" => Some("test"),
other => {
errors.push(format!("{label}: unknown role {other:?}"));
None
}
});
// Every field is checked, so one record reports each malformed field.
let name = string_field(object, "name", label, errors);
let commentary = string_field(object, "commentary", label, errors);
Some(Citation {
role: role?,
name: name?.to_owned(),
commentary: commentary?.to_owned(),
})
}
Input 22: 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,
})
}
Input 29: outline src/sites.rs fn[discover]
- File:
src/sites.rs - Selector:
fn[discover] - Kind:
fn src/sites.rs:246–298
/// Validates every requirement's query directives and finds each
/// distributed requirement's sites. A query that is malformed, or whose
/// `within` query is, finds no sites.
// {impl}`requirements.ci.errors`
pub(crate) fn discover(
root: &Path,
definitions: &BTreeMap<String, Declaration>,
files: &[PathBuf],
outlines: &OutlineCache,
errors: &mut Vec<String>,
incomplete: &mut Vec<String>,
) -> Sites {
let mut sites = Sites::new();
for (name, declaration) in definitions {
if declaration.kind != DefinitionKind::Requirement
|| !crate::structural::has_query_directive(declaration)
{
continue;
}
let (queries, problems) = crate::structural::parse_queries(declaration);
errors.extend(problems);
let runnable = validate_queries(name, declaration, &queries, errors);
let mut matches = Vec::new();
for query in runnable {
let location = format!("{}:{}", declaration.file, query.line);
match crate::structural::query_matches(root, files, outlines, &queries, &query.name) {
Ok(found) => {
if query.kind == QueryKind::Sites && found.is_empty() {
errors.push(format!(
"{location}: site query {} of {name} matches nothing in the project",
query.name
));
}
matches.push((query, found));
}
// A query that cannot run leaves its sites unknown: the
// scan is incomplete, so authoring must not treat the
// missing sites' reviews as orphans.
// {impl}`requirements.authoring.batch`
Err(error) => {
let error = format!(
"{location}: query {} of {name} cannot run: {error}",
query.name
);
incomplete.push(error.clone());
errors.push(error);
}
}
}
sites.insert(name.clone(), collect_sites(root, name, outlines, matches));
}
sites
}
Tests
Input 2: outline src/evidence.rs mod[tests]/fn[inspection_progress_preserves_validation_and_finishes_each_phase]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[inspection_progress_preserves_validation_and_finishes_each_phase] - Kind:
fn src/evidence.rs:2309–2407
// {test}`requirements.authoring.progress`
// {test}`requirements.integration.report_api`
// {test}`requirements.ci.errors`
#[test]
fn inspection_progress_preserves_validation_and_finishes_each_phase() {
let temp = fixture();
let root = temp.path();
fs::write(
root.join("md/requirements.md"),
":::{req} ready\nThe check MUST pass.\n:::\n",
)
.unwrap();
fs::write(
root.join("evidence/requirements.ready.json"),
json!({
"requirement": "The check MUST pass.",
"determination": true,
"rationale": "The inspected file has the expected lines.",
"inputs": [outline(root, "src/main.rs", "")]
})
.to_string(),
)
.unwrap();
for invalid in [false, true] {
if invalid {
fs::write(root.join("evidence/broken.json"), "{").unwrap();
fs::write(root.join("src/broken.rs"), "fn {").unwrap();
fs::write(root.join("src/lib.rs"), "fn retained() {}\n").unwrap();
fs::write(root.join("src/binary.dat"), [0xff]).unwrap();
}
stamp_reference_sets(root);
let expected = super::inspect_repository(root).unwrap();
let mut updates = Vec::new();
let inspected =
super::inspect_repository_with_progress(root, |update| updates.push(update))
.unwrap();
assert_eq!(inspected.report.requirements, expected.report.requirements);
assert_eq!(inspected.report.examples, expected.report.examples);
assert_eq!(
inspected.report.evidence_files,
expected.report.evidence_files
);
assert_eq!(inspected.report.errors, expected.report.errors);
assert_eq!(inspected.discovery_errors, expected.discovery_errors);
assert_eq!(
inspected.definitions.keys().collect::<Vec<_>>(),
expected.definitions.keys().collect::<Vec<_>>()
);
assert_eq!(inspected.report.requirements, 1);
assert_eq!(inspected.report.examples, 0);
if invalid {
let errors = inspected.report.errors.join("\n");
for error in ["invalid JSON", "cannot parse Rust source"] {
assert!(errors.contains(error), "missing {error:?}: {errors}");
}
// An uncovered item is reported, not a validation error.
assert!(!errors.contains("retained"), "{errors}");
assert!(
inspected.uncovered.iter().any(|item| item
.error
.starts_with("src/lib.rs:1: function retained has no recent coverage")),
"{:?}",
inspected.uncovered
);
let discovery = inspected.discovery_errors.join("\n");
assert!(
discovery.contains("src/broken.rs")
&& discovery.contains("cannot parse Rust source"),
"{discovery}"
);
assert!(!discovery.contains("retained"), "{discovery}");
} else {
assert!(inspected.report.errors.is_empty());
}
assert!(updates.iter().any(|update| update.total.is_none()));
assert!(updates.iter().all(|update| {
update
.total
.map_or(update.completed == 0, |total| update.completed <= total)
}));
let expected_counts = [
("evidence files", if invalid { 2 } else { 1 }),
("reference source files", if invalid { 8 } else { 5 }),
("reference coverage", 1),
];
for (stage, total) in expected_counts {
let completed: Vec<_> = updates
.iter()
.filter(|update| update.stage == stage && update.total.is_some())
.map(|update| {
assert_eq!(update.total, Some(total), "{stage}");
update.completed
})
.collect();
assert_eq!(completed, (0..=total).collect::<Vec<_>>(), "{stage}");
}
}
}
Input 3: 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}");
}
}
Input 4: outline src/evidence.rs mod[tests]/fn[failed_checks_do_not_hide_later_independent_checks]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[failed_checks_do_not_hide_later_independent_checks] - Kind:
fn src/evidence.rs:2669–2736
// {test}`requirements.ci.errors`
#[test]
fn failed_checks_do_not_hide_later_independent_checks() {
let temp = fixture();
let root = temp.path();
let fixme = "{fixme}`requirements.missing`".to_owned();
fs::create_dir_all(root.join("md/bad dir")).unwrap();
// Invalid and reserved names still have their fence and text checked.
fs::write(root.join("md/bad dir/rules.md"), ":::{req} good\n:::\n").unwrap();
fs::write(
root.join("md/requirements.md"),
format!(
":::{{req}} habeas:none\n:::\n\n:::{{req}} one\nFirst.\n:::\n\nSee {fixme}.\n\n:::{{fixme}} requirements.one\n:::\n"
),
)
.unwrap();
fs::write(
root.join("evidence/requirements.one.json"),
json!({
"requirement": "First.",
"determination": true,
"rationale": "Checked.",
"inputs": [
{"definition": "requirements.missing", "text": [1, 2]},
{"requirements": "requirements.none", "matches": ["requirements.one", "requirements.one", 3], "text": ["x"]},
{"file": "src/gone.rs", "item": "", "hash": "ABC"},
]
})
.to_string(),
)
.unwrap();
let errors = validate_repository(root).unwrap().errors;
let all = errors.join("\n");
for detail in [
"md/bad dir/rules.md:1: invalid requirement name \"bad dir.rules.good\"",
"md/bad dir/rules.md:1: requirement bad dir.rules.good has no text",
"md/requirements.md:1: invalid requirement name \"requirements.habeas:none\": names beginning with habeas: are reserved",
"md/requirements.md:1: requirement requirements.habeas:none has no text",
// Every element of `text` is checked, and the definition is
// still resolved.
"inputs[0]: text[0] must be a string",
"inputs[0]: text[1] must be a string",
"inputs[0]: requirements.missing: no matching named definition",
// Duplicate matches are reported beside a non-string entry, and
// the selection is still resolved.
"inputs[1]: matches[2] must be a string",
"inputs[1]: matches must have distinct definition names",
"inputs[1]: requirements glob \"requirements.none\" matches no requirement",
// A malformed hash does not hide a missing file.
"inputs[2]: hash must be a lowercase hexadecimal SHA-256 digest",
"inputs[2]: cannot open src/gone.rs",
// An inline `{fixme}` in the book is reported for its form, its
// placement, and its unknown name.
"md/requirements.md:8: inline {fixme} reference to requirements.missing must use the fenced form",
"md/requirements.md:8: a named {fixme} to requirements.missing must appear in a source outside the book",
&format!("md/requirements.md:8: {fixme} has no matching requirement or example"),
// A misplaced named `{fixme}` still has its body checked.
"md/requirements.md:10: a named {fixme} to requirements.one must appear in a source outside the book",
"md/requirements.md:10: {fixme} to requirements.one has an empty body",
] {
assert!(all.contains(detail), "missing {detail:?} in:\n{all}");
}
// No failure is reported twice.
let mut unique = errors.clone();
unique.sort();
unique.dedup();
assert_eq!(unique.len(), errors.len(), "{all}");
}
Input 5: outline src/evidence.rs mod[tests]/fn[configuration_and_dependency_failures_do_not_stop_later_checks]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[configuration_and_dependency_failures_do_not_stop_later_checks] - Kind:
fn src/evidence.rs:2977–3068
// {test}`requirements.ci.errors`
// {test}`requirements.definitions.inputs`
#[test]
fn configuration_and_dependency_failures_do_not_stop_later_checks() {
let temp = fixture();
fs::write(
temp.path().join("md/rules.md"),
":::{req} ready\nUse {term}`rules.missing` and {term}`rules.absent`.\n:::\n\n:::{req} other\nOther.\n:::\n",
)
.unwrap();
fs::write(
temp.path().join("evidence/rules.ready.json"),
json!({
"requirement": "Use {term}`rules.missing` and {term}`rules.absent`.",
"determination": true,
"rationale": "Examined.",
"inputs": [{"definition": "rules.gone", "text": ["x"]}]
})
.to_string(),
)
.unwrap();
// Every unresolvable term is reported, and the record's other checks
// and other records' checks still run.
let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
for detail in [
"evidence/rules.ready.json: definition dependencies: term rules.absent: no matching named definition",
"evidence/rules.ready.json: definition dependencies: term rules.missing: no matching named definition",
"evidence/rules.ready.json: inputs[0]: rules.gone: no matching named definition",
"evidence/rules.other.json: missing for requirement",
] {
assert!(errors.contains(detail), "missing {detail:?} in:\n{errors}");
}
// Invalid workspace and book configuration are each reported, and
// checks that do not depend on them still run.
fs::write(temp.path().join("habeas.toml"), "version = 2\n").unwrap();
fs::write(temp.path().join("book.toml"), "[book]\nsrc = 'md'\n[").unwrap();
fs::write(temp.path().join("evidence/ghost.json"), "{").unwrap();
let unknown = "{impl}`missing.name`".to_owned();
fs::write(temp.path().join("src/main.rs"), format!("// {unknown}\n")).unwrap();
let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
for detail in [
"habeas.toml: version: expected version = 1".to_owned(),
"book.toml: invalid TOML".to_owned(),
"evidence/ghost.json: invalid JSON".to_owned(),
format!("src/main.rs:1: {unknown} has no matching requirement"),
] {
assert!(errors.contains(&detail), "missing {detail:?} in:\n{errors}");
}
assert_eq!(
errors
.matches("habeas.toml: version: expected version = 1")
.count(),
1,
"{errors}"
);
assert_eq!(
errors.matches("book.toml: invalid TOML").count(),
1,
"{errors}"
);
// Coverage setup and coverage-history configuration failures must
// also leave independent later evidence and reference checks running.
fs::write(temp.path().join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
let (path, valid) = crate::execution_coverage::configure(temp.path()).unwrap();
for (configuration, nextest, expected) in [
("version = 1\n", "[", ".config/nextest.toml"),
(
"version = 1\n[coverage]\nreauthorings = 0\n",
"",
"coverage.reauthorings",
),
] {
fs::write(temp.path().join("habeas.toml"), configuration).unwrap();
fs::write(&path, if nextest.is_empty() { &valid } else { nextest }).unwrap();
let errors = validate_repository(temp.path()).unwrap().errors;
for detail in [
expected.to_owned(),
"evidence/ghost.json: invalid JSON".to_owned(),
format!("src/main.rs:1: {unknown} has no matching requirement"),
] {
assert!(
errors.iter().any(|error| error.contains(&detail)),
"missing {detail:?} in:\n{errors:?}"
);
}
let unique = errors.iter().collect::<std::collections::BTreeSet<_>>();
assert_eq!(errors.len(), unique.len(), "{errors:?}");
}
}
Input 6: outline src/evidence.rs mod[tests]/fn[git_index_failure_is_reported_once_and_later_checks_still_run]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[git_index_failure_is_reported_once_and_later_checks_still_run] - Kind:
fn src/evidence.rs:3070–3100
// {test}`requirements.ci.errors`
#[test]
fn git_index_failure_is_reported_once_and_later_checks_still_run() {
let temp = fixture();
fs::write(
temp.path().join("md/rules.md"),
":::{req} ready\nReady.\n:::\n",
)
.unwrap();
// A `.git` file naming a missing Git directory makes the Git index
// unreadable, so reference discovery fails.
fs::write(
temp.path().join(".git"),
format!("gitdir: {}\n", temp.path().join("missing").display()),
)
.unwrap();
fs::write(temp.path().join("evidence/ghost.json"), "{").unwrap();
let errors = validate_repository(temp.path()).unwrap().errors;
let discovery = errors
.iter()
.filter(|error| error.starts_with("cannot discover reference sources:"))
.count();
assert_eq!(discovery, 1, "{errors:#?}");
let errors = errors.join("\n");
for detail in [
"evidence/rules.ready.json: missing for requirement",
"evidence/ghost.json: invalid JSON",
] {
assert!(errors.contains(detail), "missing {detail:?} in:\n{errors}");
}
}
Input 7: outline src/execution_coverage/check.rs mod[tests]/fn[accepted_exceptions_cannot_waive_invalid_measurement_and_checks_still_collect_errors]
- File:
src/execution_coverage/check.rs - Selector:
mod[tests]/fn[accepted_exceptions_cannot_waive_invalid_measurement_and_checks_still_collect_errors] - Kind:
fn src/execution_coverage/check.rs:1676–1774
// {test}`requirements.test-coverage.check.measurement`
// {test}`requirements.ci.errors`
#[test]
fn accepted_exceptions_cannot_waive_invalid_measurement_and_checks_still_collect_errors() {
let source = "//! :::{cite} habeas:coverage\n//! File rationale.\n//! :::\n// :::{cite} habeas:coverage\n// Function rationale.\n// :::\nfn a() {}\n";
for failure in [
"absent",
"missing profile",
"legacy",
"corrupt counters",
"stale",
"corrupt history",
"empty lines",
] {
let temp = fixture(source);
let root = temp.path();
reviews(root, json!(true));
if failure != "absent" {
record(root, "a", 1, "same", vec![process(root, &[(7, 1)], 1)]);
let mut p = process(root, &[(7, 0)], 0);
if failure == "legacy" {
p.functions = None;
}
if failure == "corrupt counters" {
p.functions.as_mut().unwrap()[0].line = 0;
}
if failure == "empty lines" {
p.lines.clear();
}
let newest = record(root, "a", 2, "same", vec![p]);
match failure {
"missing profile" => fs::remove_file(newest.join("profile.profraw")).unwrap(),
"stale" => fs::write(
root.join("code.rs"),
format!("{source}\n// changed build input\n"),
)
.unwrap(),
"corrupt history" => fs::write(
newest.parent().unwrap().parent().unwrap().join("run.json"),
"{",
)
.unwrap(),
_ => {}
}
}
let result = report(root);
assert!(!result.passed, "{failure}: {}", result.text);
assert!(
!result.text.contains("accepted exception"),
"{failure}: {}",
result.text
);
assert!(
!result.text.contains("0/1 (0.0%)"),
"{failure}: {}",
result.text
);
if failure == "legacy" {
assert!(
result
.text
.contains("recollect coverage with this Habeas version")
);
}
if failure == "corrupt counters" {
assert!(result.text.contains("corrupt function attribution"));
}
if failure == "empty lines" {
assert!(result.text.contains("No usable instrumented lines"));
}
fs::remove_file(root.join("evidence/citations/code.rs/fn[a].json")).unwrap();
let result = report(root);
assert!(
result.text.contains("missing citation review"),
"{failure}: {}",
result.text
);
let mut seen = std::collections::BTreeSet::new();
for line in result.text.lines().filter(|line| line.starts_with("- ")) {
assert!(seen.insert(line), "duplicate finding: {line}");
}
fs::write(root.join("broken.rs"), "fn malformed(").unwrap();
fs::write(root.join("book.toml"), "[book]\nsrc = 7\n").unwrap();
let result = report(root);
assert!(
result
.text
.to_lowercase()
.contains("cannot parse rust source"),
"{}",
result.text
);
assert!(
result.text.contains("book.src must be a string"),
"{}",
result.text
);
}
}
Input 8: outline src/index.rs mod[tests]/fn[an_unreadable_record_is_reported_once]
- File:
src/index.rs - Selector:
mod[tests]/fn[an_unreadable_record_is_reported_once] - Kind:
fn src/index.rs:1308–1339
// {test}`requirements.ci.errors`
// {test}`requirements.index.invalid_detail`
#[test]
fn an_unreadable_record_is_reported_once() {
let temp = tempfile::tempdir().unwrap();
// A directory where the record belongs cannot be read as one.
fs::create_dir_all(temp.path().join("evidence/requirements.ready.json")).unwrap();
let reading = |reported: Vec<String>| {
let report = crate::EvidenceReport {
requirements: 1,
examples: 0,
evidence_files: 1,
errors: reported,
};
let loaded =
super::LoadedDetailEvidence::load(temp.path(), "requirements.ready", &report);
assert!(loaded.state == EvidenceState::Invalid);
loaded
.errors
.iter()
.filter(|error| error.contains("cannot read evidence"))
.count()
};
assert_eq!(reading(Vec::new()), 1);
// Validation already reported it.
assert_eq!(
reading(vec![
"evidence/requirements.ready.json: cannot read evidence: Is a directory".into()
]),
1
);
}
Input 9: outline tests/commands.rs fn[status_loads_nearest_workspace_file_without_validating_authoring]
- File:
tests/commands.rs - Selector:
fn[status_loads_nearest_workspace_file_without_validating_authoring] - Kind:
fn tests/commands.rs:223–269
// {test}`requirements.configuration.workspace_location`
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.configuration.workspace_structure`
// {test}`requirements.configuration.loading`
// {test}`requirements.authoring.deterministic_validation`
// {test}`requirements.cli.status`
// {test}`requirements.ci.errors`
#[test]
fn status_loads_nearest_workspace_file_without_validating_authoring() {
let temp = fixture();
let nested = temp.path().join("src/nested");
fs::write(temp.path().join("habeas.toml"), "version = 99\n").unwrap();
fs::write(
nested.join("habeas.toml"),
"version = 1\n[authoring]\nconfigs = 'invalid but unused'\n",
)
.unwrap();
let output = habeas(&nested, &["status"]);
assert!(output.status.success(), "{output:?}");
// An invalid workspace file is one validation finding: `status` and
// `info` still run and report the checks that do not depend on it.
for args in [["status"].as_slice(), ["info", "requirements.*"].as_slice()] {
let output = habeas(temp.path(), args);
assert!(output.status.success(), "{args:?}: {output:?}");
let text = String::from_utf8(output.stdout).unwrap();
assert!(
text.contains("habeas.toml: version: expected version = 1"),
"{args:?}: {text}"
);
assert!(
text.contains("evidence/requirements.malformed.json: invalid JSON"),
"{args:?}: {text}"
);
}
fs::write(temp.path().join("habeas.toml"), "version = 1\n").unwrap();
fs::write(nested.join("habeas.toml"), "version = [\n").unwrap();
let output = habeas(&nested, &["status"]);
assert!(output.status.success(), "{output:?}");
let text = String::from_utf8(output.stdout).unwrap();
assert!(
text.contains(&nested.join("habeas.toml").display().to_string())
&& text.contains("evidence/requirements.malformed.json: invalid JSON"),
"{text}"
);
}
Input 10: outline tests/evidence_boundaries.rs fn[an_unlistable_review_directory_is_reported_once]
- File:
tests/evidence_boundaries.rs - Selector:
fn[an_unlistable_review_directory_is_reported_once] - Kind:
fn tests/evidence_boundaries.rs:297–319
// {test}`requirements.ci.errors`
#[cfg(unix)]
#[test]
fn an_unlistable_review_directory_is_reported_once() {
use std::os::unix::fs::PermissionsExt;
let temp = fixture();
let root = temp.path().join("project");
let locked = root.join("evidence/citations/src");
fs::create_dir_all(&locked).unwrap();
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
let errors = validate_repository(&root).unwrap().errors;
// A privileged user can list the directory regardless of its mode.
let unlistable = fs::read_dir(&locked).is_err();
fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).unwrap();
if unlistable {
let listing = errors
.iter()
.filter(|error| error.starts_with("evidence/citations/src: cannot list directory"))
.count();
assert_eq!(listing, 1, "{errors:#?}");
}
}
Input 11: outline tests/references.rs fn[unclosed_fences_still_report_unknown_names]
- File:
tests/references.rs - Selector:
fn[unclosed_fences_still_report_unknown_names] - Kind:
fn tests/references.rs:48–70
// {test}`requirements.ci.errors`
#[test]
fn unclosed_fences_still_report_unknown_names() {
let temp = project();
let root = temp.path();
let cr = role("cite");
fs::write(
root.join("src/lib.rs"),
format!(
"// :::{cr} rules.missing\n// never closed\n\n// :::{cr} habeas:other\n// never closed\n"
),
)
.unwrap();
let errors = errors(root);
for expected in [
"src/lib.rs:1: fenced {cite} reference to rules.missing has no closing fence".to_owned(),
format!("src/lib.rs:1: {cr}`rules.missing` has no matching requirement or example"),
"src/lib.rs:4: fenced {cite} reference to habeas:other has no closing fence".to_owned(),
format!("src/lib.rs:4: {cr}`habeas:other` has no matching built-in definition"),
] {
assert!(has(&errors, &expected), "missing {expected:?}: {errors:#?}");
}
}
Input 12: outline tests/references.rs fn[citation_reviews_are_required_current_and_not_orphaned]
- File:
tests/references.rs - Selector:
fn[citation_reviews_are_required_current_and_not_orphaned] - Kind:
fn tests/references.rs:469–642
// {test}`requirements.references.citation_review`
// {test}`requirements.ci.outcomes`
// {test}`requirements.ci.orphans`
// {test}`requirements.ci.errors`
#[test]
fn citation_reviews_are_required_current_and_not_orphaned() {
let temp = project();
let root = temp.path();
let cr = role("cite");
let helper = |body: &str| {
format!(
"// {cr}`rules.ready`\n// :::{cr} habeas:util\n// {body}\n// :::\nfn helper() {{\n work();\n}}\n"
)
};
fs::write(root.join("src/lib.rs"), helper("Formats output.")).unwrap();
fs::write(root.join("notes.txt"), format!("See {cr}`rules.ready`.\n")).unwrap();
// Citations in the book are reviewed with their declaration instead.
fs::write(
root.join("md/guide.md"),
format!("# Guide\n\nSee {cr}`rules.ready`.\n"),
)
.unwrap();
let path = "evidence/citations/src/lib.rs/fn[helper].json";
let errors_for = |prefix: &str| {
errors(root)
.into_iter()
.filter(|error| error.starts_with(prefix))
.collect::<Vec<_>>()
};
let missing = errors_for("evidence/citations/");
assert!(
has(
&missing,
"evidence/citations/src/lib.rs/fn[helper].json: missing citation review for src/lib.rs fn[helper] at src/lib.rs:1"
),
"{missing:#?}"
);
assert!(
has(
&missing,
"evidence/citations/notes.txt/_root.json: missing citation review for notes.txt <root>"
),
"{missing:#?}"
);
assert!(!has(&missing, "md/guide.md"), "{missing:#?}");
let citations = json!([
{"role": "cite", "name": "rules.ready", "commentary": ""},
{"role": "cite", "name": "habeas:util", "commentary": "Formats output."}
]);
fs::create_dir_all(root.join("evidence/citations/src/lib.rs")).unwrap();
let write = |record: Value| fs::write(root.join(path), record.to_string()).unwrap();
write(review(root, citations.clone(), json!(true)));
assert_eq!(errors_for(path), Vec::<String>::new());
write(review(
root,
json!([null, {"role": "broken", "name": 7, "commentary": 8}]),
json!(true),
));
let malformed = errors_for(path);
assert!(
has(&malformed, "citations[0]: expected a JSON object"),
"{malformed:?}"
);
assert!(
has(&malformed, "citations[1]: unknown role"),
"{malformed:?}"
);
assert!(
has(&malformed, "citations[1]: name must be a string"),
"{malformed:?}"
);
assert!(
has(&malformed, "citations[1]: commentary must be a string"),
"{malformed:?}"
);
// A citation review cannot accept a `{fixme}`, so FIXME is reported; a
// false review is reported with its rationale.
write(review(
root,
citations.clone(),
json!({"FIXME": ["example/rules#4"]}),
));
assert!(
has(
&errors_for(path),
"determination is FIXME, but a citation review cannot accept a"
),
"{:#?}",
errors_for(path)
);
write(review(root, citations.clone(), json!(false)));
assert!(
has(
&errors_for(path),
"determination is false: The citations are sensible."
),
"{:#?}",
errors_for(path)
);
// Changed commentary or citations make the review stale; reflowing does not.
write(review(root, citations.clone(), json!(true)));
fs::write(root.join("src/lib.rs"), helper("Formats output.")).unwrap();
assert_eq!(errors_for(path), Vec::<String>::new());
fs::write(root.join("src/lib.rs"), helper("Formats all output.")).unwrap();
assert!(
has(&errors_for(path), "citations changed"),
"{:#?}",
errors_for(path)
);
fs::write(root.join("src/lib.rs"), helper("Formats output.")).unwrap();
// So do an edited item and an edited cited declaration.
fs::write(
root.join("src/lib.rs"),
helper("Formats output.").replace("work()", "rest()"),
)
.unwrap();
assert!(
has(&errors_for(path), "outline input changed"),
"{:#?}",
errors_for(path)
);
fs::write(root.join("src/lib.rs"), helper("Formats output.")).unwrap();
fs::write(
root.join("md/rules.md"),
":::{req} ready\nReady now.\n:::\n",
)
.unwrap();
assert!(
has(&errors_for(path), "input text changed"),
"{:#?}",
errors_for(path)
);
fs::write(root.join("md/rules.md"), ":::{req} ready\nReady.\n:::\n").unwrap();
// The item and each cited declaration must be inputs.
let mut record = review(root, citations.clone(), json!(true));
record["inputs"] = json!([]);
write(record);
let found = errors_for(path);
assert!(
has(&found, "inputs must select the reviewed item"),
"{found:#?}"
);
assert!(
has(
&found,
"inputs must include the cited declaration rules.ready"
),
"{found:#?}"
);
let mut record = review(root, citations.clone(), json!(true));
record["extra"] = json!(1);
write(record);
assert!(has(&errors_for(path), "unexpected field \"extra\""));
// Removing the citations orphans the review.
write(review(root, citations, json!(true)));
fs::write(
root.join("src/lib.rs"),
format!("// {}`rules.ready`\nfn helper() {{}}\n", role("impl")),
)
.unwrap();
assert!(
has(&errors_for(path), "orphaned citation review"),
"{:#?}",
errors_for(path)
);
// The review is not mistaken for misplaced definition evidence.
assert!(!has(&errors(root), "no matching requirement or example"));
}
Referenced definitions
Input 13: definition requirements.ci.validation_error
requirements.ci.validation_error:md/requirements/ci.md:189–197
:::{definition} validation_error
:phrase: validation error
One message in a repository validation report, describing a single failed check.
It begins with the affected evidence file, requirement, or source location, names
the failed check, and states the specific missing, invalid, or changed value,
with the expected value when available. It is concise because agents are its
primary readers.
:::
Other sources
Input 1: requirements selection requirements.ci.errors
requirements.ci.errors:md/requirements/ci.md:199–301
:::::{req} errors
Repository validation MUST continue after a failed check and report every failed
check it finds in one run, each as a {term}`requirements.ci.validation_error`.
This is a convention for every validation error; the requirement for each check
states which conditions that check reports. A file that cannot be parsed, such as
a malformed `habeas.toml`, `book.toml`, or evidence file, is one failed check:
its error MAY report only the first parse or decoding problem in that file, and
checks that do not depend on its contents MUST still run.
The code that sequences the repository's checks carries out the first paragraph.
A repository-validation function that collects validation errors MUST hold them
in a parameter or local variable named `errors`, and a function with such a
variable is a site below; authoring code that collects errors only to abort is
not one. After one of its checks fails, a site MUST still run every later check
that does not depend on the failed check's result, including later checks in the
same loop iteration, and MUST NOT report one failure twice.
::::{sites} error_accumulators
```yaml
language: rust
paths: [src]
exclude: [src/authoring/inputs.rs, src/authoring/tools.rs]
rule:
kind: function_item
has:
stopBy: { kind: function_item }
any:
- kind: parameter
has: { field: pattern, regex: "^errors$" }
- kind: let_declaration
has: { field: pattern, regex: "^errors$" }
not:
inside:
stopBy: end
kind: mod_item
has: { field: name, regex: "^tests$" }
match:
- "fn check(value: &str, errors: &mut Vec<String>) {}"
- |
fn run() {
let mut errors: BTreeSet<String> = BTreeSet::new();
check("", &mut errors);
}
no_match:
- "fn check(value: &str, discovery_errors: &mut Vec<String>) {}"
- |
fn run() {
let mut problems = Vec::new();
check("", &mut problems);
}
- |
mod tests {
fn check(errors: &mut Vec<String>) {}
}
```
::::
::::{violations} early_exits
```yaml
language: rust
paths: [src]
within: error_accumulators
rule:
any:
- kind: try_expression
- kind: return_expression
- kind: continue_expression
- kind: break_expression
match:
- |
fn check(v: &Value, errors: &mut Vec<String>) -> Option<u8> {
let n = v.as_u64()?;
if v.is_null() { errors.push("null".into()); }
Some(n as u8)
}
- |
fn check(items: &[Value], errors: &mut Vec<String>) {
for item in items {
if !item.is_object() { errors.push("object".into()); continue; }
if item.is_null() { errors.push("null".into()); }
}
}
- |
fn check(v: &Value, errors: &mut Vec<String>) {
if !v.is_object() { errors.push("object".into()); return; }
if v.is_null() { errors.push("null".into()); }
}
- |
fn check(items: &[Value], errors: &mut Vec<String>) {
for item in items {
if !item.is_object() { errors.push("object".into()); break; }
}
if items.is_empty() { errors.push("empty".into()); }
}
no_match:
- |
fn parse(v: &Value) -> Option<u8> {
let n = v.as_u64()?;
Some(n as u8)
}
```
::::
:::::
Input 14: outline src/github.rs fn[add_issue_findings]
- File:
src/github.rs - Selector:
fn[add_issue_findings] - Kind:
fn src/github.rs:575–687
/// Adds the findings that depend on issue states: each `{fixme}` naming a
/// closed or nonexistent issue and the item containing it, and each FIXME
/// record an acknowledging `{fixme}` of which names one, which is stale.
/// Issues that cannot be read count as open.
// {impl}`requirements.authoring.github_reads`
pub(crate) fn add_issue_findings(inspection: &mut RepositoryInspection, github: &GithubIssues) {
let root = inspection.root.clone();
let fixmes = fixme_issues(&inspection.references);
if fixmes.is_empty() {
return;
}
let reads = github.read_all(fixmes.iter().flat_map(|(_, issues)| issues.iter().cloned()));
let not_open = |issue: &String| reads.get(issue).and_then(IssueRead::not_open);
let outlines = crate::inputs::OutlineCache::default();
let mut errors = BTreeSet::new();
for (reference, issues) in &fixmes {
let file = display_path(&root, &reference.file);
for issue in issues {
let Some(reason) = not_open(issue) else {
continue;
};
errors.insert(format!(
"{file}:{}: {{fixme}} names {issue}, which {reason}",
reference.line
));
let (line, item) = containing_item(inspection, &outlines, &file, reference);
errors.insert(format!(
"{file}:{line}: {item} fails: its {{fixme}} at line {} names {issue}, which {reason}",
reference.line
));
}
}
for (name, definition) in &inspection.definitions {
if definition.kind == crate::DefinitionKind::Term {
continue;
}
let relative = format!("evidence/{name}.json");
let Some(entries) = fs::read_to_string(root.join(&relative))
.ok()
.and_then(|content| serde_json::from_str::<Value>(&content).ok())
.and_then(|value| {
crate::judgment::Judgment::from_value(value.get("determination")?).ok()
})
.map(|judgment| judgment.fixme_entries().to_vec())
.filter(|entries| !entries.is_empty())
else {
continue;
};
for (reference, issues) in &fixmes {
// A `{fixme}` inside one of the requirement's sites belongs to
// that site's review.
if reference.name != *name
|| !reference.is_fixme_edge()
|| crate::sites::in_own_site(&root, &inspection.sites, reference)
{
continue;
}
let body = FixmeBody::parse(reference.commentary.as_deref().unwrap_or(""));
if !body
.acknowledgments()
.iter()
.any(|acknowledgment| entries.contains(acknowledgment))
{
continue;
}
for issue in issues {
if let Some(reason) = not_open(issue) {
errors.insert(format!(
"{relative}: stale: issue {issue}, named by the acknowledging {{fixme}} to {name} at {}:{}, {reason}; reassess the record",
display_path(&root, &reference.file),
reference.line
));
}
}
}
}
// A site review's FIXME record is stale when an issue a `{fixme}` inside
// the site names is closed or missing.
for site in inspection.sites.values().flatten() {
let relative = site.review_path();
let fixme = fs::read_to_string(root.join(&relative))
.ok()
.and_then(|content| serde_json::from_str::<Value>(&content).ok())
.and_then(|value| {
crate::judgment::Judgment::from_value(value.get("determination")?).ok()
})
.is_some_and(|judgment| !judgment.fixme_entries().is_empty());
if !fixme {
continue;
}
for (reference, issues) in &fixmes {
if !site
.fixmes(&root, &inspection.references)
.iter()
.any(|inside| inside.file == reference.file && inside.line == reference.line)
{
continue;
}
for issue in issues {
if let Some(reason) = not_open(issue) {
errors.insert(format!(
"{relative}: stale: issue {issue}, named by the {{fixme}} to {} inside the site at {}:{}, {reason}; reassess the review",
site.requirement,
display_path(&root, &reference.file),
reference.line
));
}
}
}
}
inspection.report.errors.extend(errors);
}
Input 15: outline src/index.rs impl[LoadedDetailEvidence]/fn[load_path]
- File:
src/index.rs - Selector:
impl[LoadedDetailEvidence]/fn[load_path] - Kind:
fn src/index.rs:160–220
/// Loads the record at a project-relative path, with the validation
/// errors reported for it, such as a citation review.
// {impl}`requirements.index.state`
pub(crate) fn load_path(root: &Path, relative: &str, report: &EvidenceReport) -> Self {
let evidence_path = root.join(relative);
let prefix = format!("{relative}:");
let mut errors = report
.errors
.iter()
.filter(|error| error.starts_with(&prefix))
.cloned()
.collect::<Vec<_>>();
// {impl}`requirements.index.invalid_detail`
let record = match fs::read_to_string(&evidence_path) {
Ok(record) => Some(record),
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => {
// Validation usually reported the same failure already.
let failure = format!("{prefix} cannot read evidence:");
if !errors.iter().any(|reported| reported.starts_with(&failure)) {
errors.push(format!("{failure} {error}"));
}
None
}
};
let judgment = record
.as_deref()
.and_then(|record| serde_json::from_str::<Value>(record).ok())
.and_then(|record| {
record
.get("determination")
.and_then(|value| crate::judgment::Judgment::from_value(value).ok())
});
let fixme_entries = judgment
.as_ref()
.map(|judgment| judgment.fixme_entries().to_vec())
.unwrap_or_default();
let state = if record.is_none() && !evidence_path.exists() {
EvidenceState::Missing
} else if errors.is_empty() {
match judgment {
Some(crate::judgment::Judgment::True) => EvidenceState::Valid,
Some(crate::judgment::Judgment::False) => EvidenceState::DeterminationFalse,
Some(crate::judgment::Judgment::Fixme(_)) => EvidenceState::Fixme,
None => EvidenceState::Invalid,
}
} else if errors
.iter()
.all(|error| error.starts_with(&format!("{prefix} determination is false")))
{
EvidenceState::DeterminationFalse
} else {
EvidenceState::Invalid
};
Self {
state,
record,
errors,
fixme_entries,
}
}
Input 23: outline src/authoring/inputs.rs impl[AssessmentSources]/fn[prepare]
- File:
src/authoring/inputs.rs - Selector:
impl[AssessmentSources]/fn[prepare] - Kind:
fn src/authoring/inputs.rs:65–296
// {impl}`requirements.authoring.invocation`
// {impl}`requirements.authoring.mandatory_inputs`
// {impl}`requirements.authoring_input`
// {impl}`requirements.examples.authoring_inputs`
// {impl}`requirements.examples.definition`
// {impl}`requirements.references.authoring_inputs`
// {impl}`requirements.definitions.authoring_inputs`
// {impl}`requirements.authoring.source_tools`
// {impl}`requirements.references.anchors`
// {impl}`requirements.ci.reference_set`
// {impl}`requirements.references.builtin_definitions`
// {impl}`requirements.references.site_review`
pub(crate) fn prepare(root: &Path, subject_name: &str) -> io::Result<Self> {
let root = fs::canonicalize(root)?;
let access = SourceAccess::load(&root)?;
let definitions = load_definitions(&root)?;
let subject = definitions
.get(subject_name)
.filter(|definition| definition.kind != DefinitionKind::Term)
.ok_or_else(|| {
io::Error::other(format!(
"{subject_name}: no matching requirement or named example"
))
})?;
let mut selectors = vec![InputSelector::Requirements {
requirements: subject_name.to_owned(),
}];
let mut builtins = Vec::new();
for (kind, name) in crate::text_references(&subject.text, true) {
// A `{fixme}` in a declaration is a validation error when named
// and is not an edge when unnamed.
if matches!(kind, ReferenceKind::Term | ReferenceKind::Fixme) {
continue;
}
// A built-in has no declaration; its fixed text is supplied instead.
if let Some(builtin) = crate::builtins::builtin(&name) {
if kind == ReferenceKind::Cite && !builtins.contains(&builtin.name) {
builtins.push(builtin.name);
}
continue;
}
if !definitions
.get(&name)
.is_some_and(|definition| definition.kind != DefinitionKind::Term)
{
return Err(io::Error::other(format!(
"{subject_name}: referenced subject {name} does not exist"
)));
}
// Only `{cite}` leaves the subject; its `{impl}` and `{test}`
// references point into it from the definitions it implements or tests.
if kind != ReferenceKind::Cite {
continue;
}
insert_selector(
&mut selectors,
InputSelector::Requirements { requirements: name },
);
}
let outlines = OutlineCache::default();
let mut errors = Vec::new();
let files = discovered_files(&root, &mut errors);
let references = crate::evidence::collect_references_with_progress(
&root,
&files,
&mut errors,
&mut |_| {},
);
if !errors.is_empty() {
return Err(io::Error::other(errors.join("\n")));
}
let sites =
crate::evidence::definition_sites(&root, subject_name, subject, &files, &outlines)?;
// The same edges determine the reference contributions below.
let reference_set = crate::evidence::reference_set_digest(
&root,
&outlines,
subject_name,
subject,
&references,
&sites,
);
// Tests contribute source. Refining declarations contribute their text;
// implementation references outside declarations only locate code.
for reference in references.iter().filter(|reference| {
reference.name == subject_name
&& matches!(reference.kind, ReferenceKind::Impl | ReferenceKind::Test)
}) {
// Generated evidence, including symlink aliases, is omitted by
// default rather than denied.
if access.omit_generated_evidence(&root, &reference.file) {
continue;
}
let selector = reference_selector(&root, &definitions, &outlines, reference)?;
if reference.kind == ReferenceKind::Test
|| matches!(selector, InputSelector::Requirements { .. })
{
access.file(&root, &reference.file)?;
insert_selector(&mut selectors, selector);
}
}
// {impl}`requirements.references.anchors`
for anchor in &subject.anchors {
if access.omit_generated_evidence(&root, Path::new(&anchor.file)) {
continue;
}
let selector = access
.file(&root, Path::new(&anchor.file))
.and_then(|_| {
anchor
.resolve(&root, &outlines)
.map(|_| anchor.selector())
.map_err(io::Error::other)
})
.map_err(|error| {
io::Error::new(
error.kind(),
format!(
"{subject_name}: cannot read :{}: anchor {}: {error}",
anchor.kind.label(),
anchor.label()
),
)
})?;
if anchor.kind == ReferenceKind::Test {
insert_selector(&mut selectors, selector);
}
}
// {impl}`requirements.authoring.fixme_inputs`
let mut acknowledgments = crate::evidence::fixme_acknowledgments(
&root,
&outlines,
references.iter().filter(|reference| {
reference.name == subject_name
&& !crate::sites::in_own_site(&root, &sites, reference)
&& !access.omit_generated_evidence(&root, &reference.file)
}),
)
.map_err(io::Error::other)?;
for acknowledgment in &acknowledgments {
access.file(&root, Path::new(acknowledgment["file"].as_str().unwrap()))?;
}
// Existing evidence only decides whether to reassess; its inputs are
// not carried forward.
let mut mandatory = Vec::new();
for selector in selectors {
if !generated_evidence_selector(&root, &access, &selector) {
mandatory.push(source_input(
&root,
&access,
&definitions,
&outlines,
&selector,
)?);
}
}
// The dependency collector receives bodies separately so Markdown and
// non-Markdown reference-literal rules keep their source semantics.
let dependencies = crate::terms::dependencies(
&root,
&definitions,
&outlines,
json!({"inputs": mandatory, "acknowledgments": acknowledgments})
.as_object()
.unwrap(),
Some(&subject.text),
)
.map_err(io::Error::other)?;
for definition in dependencies {
let input = source_input(
&root,
&access,
&definitions,
&outlines,
&InputSelector::Definition { definition },
)?;
if !mandatory.contains(&input) {
mandatory.push(input);
}
}
mandatory.extend(builtins.into_iter().map(builtin_input));
let github = GithubIssues::from_env(&root);
let issue_states = crate::github::input_issue_states(
&root,
&github,
&references,
&definitions,
&mandatory,
);
let issue_names = acknowledgments.iter().flat_map(|acknowledgment| {
crate::fixme::FixmeBody::parse(acknowledgment["body"].as_str().unwrap()).issues
});
let issues = github.read_all(issue_names);
for acknowledgment in &mut acknowledgments {
let parsed = crate::fixme::FixmeBody::parse(acknowledgment["body"].as_str().unwrap());
let mut seen = std::collections::BTreeSet::new();
acknowledgment["issues"] = parsed
.issues
.into_iter()
.filter(|issue| seen.insert(issue.clone()))
.map(|reference| {
let state = issues
.get(&reference)
.map_or("open", crate::github::IssueRead::state);
json!({"reference": reference, "state": state})
})
.collect();
}
Ok(Self {
root,
access,
subject_name: subject_name.to_owned(),
has_applicable_fixme: !acknowledgments.is_empty(),
subject_kind: AssessmentKind::Definition(
subject.kind,
crate::structural::has_query_directive(subject),
),
subject_text: subject.text.clone(),
outlines,
reference_set,
acknowledgments,
mandatory,
issue_states,
github,
recorded: Vec::new(),
})
}
Input 24: outline src/authoring/tools.rs fn[references]
- File:
src/authoring/tools.rs - Selector:
fn[references] - Kind:
fn src/authoring/tools.rs:481–612
// {impl}`requirements.references.definition_globs`
// {impl}`requirements.references.anchors`
// {impl}`requirements.authoring.no_line_numbers`
// {impl}`requirements.references.authoring_inputs`
fn references(sources: &AssessmentSources, args: &Map<String, Value>) -> io::Result<Listing> {
check_keys(args, &["selection", "roles"])?;
let roles = match args.get("roles") {
None => vec![
crate::ReferenceKind::Impl,
crate::ReferenceKind::Cite,
crate::ReferenceKind::Test,
],
Some(Value::Array(roles)) => roles
.iter()
.map(|role| match role.as_str() {
Some("impl") => Ok(crate::ReferenceKind::Impl),
Some("cite") => Ok(crate::ReferenceKind::Cite),
Some("test") => Ok(crate::ReferenceKind::Test),
_ => Err(io::Error::other(format!(
"invalid reference role {role}; expected impl, cite, or test"
))),
})
.collect::<io::Result<Vec<_>>>()?,
Some(_) => {
return Err(io::Error::other(
"roles must be an array of impl, cite, or test",
));
}
};
let selection = if args.contains_key("selection") {
let selection = string(args, "selection")?;
crate::definition_glob::validate(selection).map_err(io::Error::other)?;
Some(selection)
} else {
None
};
let definitions = crate::evidence::load_definitions(&sources.root)?;
let selected: Vec<_> = definitions
.iter()
.filter(|(name, definition)| {
definition.kind != crate::DefinitionKind::Term
&& selection
.is_none_or(|selection| crate::definition_glob::matches(selection, name))
})
.map(|(name, definition)| json!({"name": name, "kind": definition.kind.noun()}))
.collect();
let Some(selection) = selection else {
return Ok(Listing::object(
REFERENCE_ARRAYS,
vec![selected, Vec::new()],
));
};
if selected.is_empty() {
return Err(io::Error::other(format!(
"selection {selection:?} matches no requirement or named example"
)));
}
let mut errors = Vec::new();
let mut found = crate::evidence::collect_references(&sources.root, &mut errors);
// A considered source that cannot be read would silently drop its sites.
if !errors.is_empty() {
return Err(io::Error::other(format!(
"cannot list reference sites because reference discovery failed; fix or restore the named source before retrying:\n{}",
errors.join("\n")
)));
}
found.retain(|reference| {
// Only `{impl}`, `{cite}`, and `{test}` references are sites; a
// `{fixme}` acknowledges a gap rather than locating the definition.
roles.contains(&reference.kind)
// A fence that never closes is a validation error, not a site.
&& reference.closed
&& crate::definition_glob::matches(selection, &reference.name)
&& definitions
.get(&reference.name)
.is_some_and(|definition| definition.kind != crate::DefinitionKind::Term)
});
let mut sites = Vec::new();
for reference in &found {
let file = relative_path(&sources.root, &reference.file)?;
let parsed = sources.outlines.parse(&sources.root, &file);
let item = parsed.as_ref().as_ref().ok().map(|parsed| {
let index = parsed.outline.owner_at_line(reference.line);
parsed.outline.nodes[index].selector.clone()
});
sites.push((
reference.name.clone(),
file,
Some(reference.line),
json!({
"name": reference.name,
"role": reference.kind.label(),
"file": relative_path(&sources.root, &reference.file)?,
"item": item,
}),
));
}
// {impl}`requirements.references.anchors`
for (name, definition) in &definitions {
if definition.kind == crate::DefinitionKind::Term
|| !crate::definition_glob::matches(selection, name)
{
continue;
}
for anchor in &definition.anchors {
if !roles.contains(&anchor.kind) {
continue;
}
// Discovery omits excluded sources rather than aborting.
let Ok(path) = sources.access.file(&sources.root, Path::new(&anchor.file)) else {
continue;
};
let file = relative_path(&sources.root, &path)?;
sites.push((
name.clone(),
file.clone(),
None,
json!({
"name": name,
"role": anchor.kind.label(),
"file": file,
"item": (!anchor.item.is_empty()).then_some(&anchor.item),
}),
));
}
}
sites.sort_by(|a, b| (&a.0, &a.1, a.2).cmp(&(&b.0, &b.1, b.2)));
Ok(Listing::object(
REFERENCE_ARRAYS,
vec![selected, sites.into_iter().map(|site| site.3).collect()],
))
}
Input 25: outline src/authoring/tools.rs fn[referencing]
- File:
src/authoring/tools.rs - Selector:
fn[referencing] - Kind:
fn src/authoring/tools.rs:979–1121
/// The regions an optional `referencing` argument selects: the sources that
/// carry a reference in one of its roles to a requirement or example its
/// selection matches, including declaration anchors, as referencing nodes or
/// whole files by its scope.
// {impl}`requirements.references.definition_globs`
// {impl}`requirements.references.anchors`
fn referencing(
sources: &AssessmentSources,
args: &Map<String, Value>,
) -> io::Result<Option<ReferenceRegions>> {
let Some(scope) = args.get("referencing") else {
return Ok(None);
};
let scope = scope
.as_object()
.ok_or_else(|| io::Error::other("referencing must be an object"))?;
for key in scope.keys() {
if !["selection", "roles", "scope"].contains(&key.as_str()) {
return Err(io::Error::other(format!(
"unexpected referencing argument {key:?}"
)));
}
}
let selection = scope
.get("selection")
.and_then(Value::as_str)
.ok_or_else(|| io::Error::other("referencing.selection must be a string"))?;
crate::definition_glob::validate(selection).map_err(io::Error::other)?;
let roles = match scope.get("roles") {
None => vec![
crate::ReferenceKind::Impl,
crate::ReferenceKind::Test,
crate::ReferenceKind::Cite,
],
Some(Value::Array(roles)) => roles
.iter()
.map(|role| match role.as_str() {
Some("impl") => Ok(crate::ReferenceKind::Impl),
Some("test") => Ok(crate::ReferenceKind::Test),
Some("cite") => Ok(crate::ReferenceKind::Cite),
Some("fixme") => Ok(crate::ReferenceKind::Fixme),
_ => Err(io::Error::other(format!(
"unknown referencing role {role}; expected impl, test, cite, or fixme"
))),
})
.collect::<io::Result<_>>()?,
Some(_) => {
return Err(io::Error::other(
"referencing.roles must be an array of roles",
));
}
};
let whole_files = match scope.get("scope") {
None => true,
Some(value) => match value.as_str() {
Some("file") => true,
Some("node") => false,
_ => {
return Err(io::Error::other(format!(
"unknown referencing scope {value}; expected \"node\" or \"file\""
)));
}
},
};
let definitions = crate::evidence::load_definitions(&sources.root)?;
let selected = |name: &str| {
crate::definition_glob::matches(selection, name)
&& definitions
.get(name)
.is_some_and(|definition| definition.kind != crate::DefinitionKind::Term)
};
if !definitions.keys().any(|name| selected(name)) {
return Err(io::Error::other(format!(
"referencing selection {selection:?} matches no requirement or named example"
)));
}
let mut errors = Vec::new();
let found = crate::evidence::collect_references(&sources.root, &mut errors);
// A considered source that cannot be read would silently drop its sources.
if !errors.is_empty() {
return Err(io::Error::other(format!(
"cannot restrict the search to referencing sources because reference discovery failed; fix or restore the named source before retrying:\n{}",
errors.join("\n")
)));
}
let mut regions = ReferenceRegions(BTreeMap::new());
for reference in found {
if !reference.closed
|| !reference.is_fixme_edge()
|| !roles.contains(&reference.kind)
|| !selected(&reference.name)
{
continue;
}
let file = relative_path(&sources.root, &reference.file)?;
let lines = if whole_files {
None
} else {
let parsed = sources.outlines.parse(&sources.root, &file);
match parsed.as_ref() {
Ok(parsed) => {
let node = &parsed.outline.nodes[parsed.outline.owner_at_line(reference.line)];
Some((node.line_start, node.line_end))
}
Err(_) => None,
}
};
regions.add(file, lines);
}
for (name, definition) in &definitions {
if !selected(name) {
continue;
}
for anchor in &definition.anchors {
if !roles.contains(&anchor.kind) {
continue;
}
// Discovery omits excluded sources rather than aborting.
let Ok(path) = sources.access.file(&sources.root, Path::new(&anchor.file)) else {
continue;
};
let file = relative_path(&sources.root, &path)?;
let lines = if whole_files || anchor.item.is_empty() {
None
} else {
let parsed = sources.outlines.parse(&sources.root, &file);
match parsed.as_ref() {
Ok(parsed) => match parsed.outline.resolve(&anchor.item) {
Ok(index) => {
let node = &parsed.outline.nodes[index];
Some((node.line_start, node.line_end))
}
// An anchor that no longer resolves names no node.
Err(_) => continue,
},
Err(_) => None,
}
};
regions.add(file, lines);
}
}
Ok(Some(regions))
}
Input 26: outline src/authoring/tools.rs fn[declared_query]
- File:
src/authoring/tools.rs - Selector:
fn[declared_query] - Kind:
fn src/authoring/tools.rs:1189–1250
/// Runs a query a distributed requirement declares, named
/// `<full-name>/<query-name>`, as validation runs it, returning each match's
/// site as a search entry with the matched lines.
// {impl}`requirements.references.distributed`
fn declared_query(sources: &AssessmentSources, query: &str) -> io::Result<Listing> {
let (requirement, name) = query.rsplit_once('/').ok_or_else(|| {
io::Error::other(format!(
"query {query:?} must have the form <full-name>/<query-name>"
))
})?;
let definitions = crate::evidence::load_definitions(&sources.root)?;
let declaration = definitions
.get(requirement)
.filter(|definition| definition.kind == crate::DefinitionKind::Requirement)
.ok_or_else(|| {
io::Error::other(format!("query {query:?} names no declared requirement"))
})?;
let queries = crate::structural::declared_queries(declaration).map_err(io::Error::other)?;
if !queries.iter().any(|declared| declared.name == name) {
return Err(io::Error::other(format!(
"requirement {requirement} declares no query named {name:?}"
)));
}
let mut errors = Vec::new();
let files = crate::evidence::discovered_files(&sources.root, &mut errors);
if !errors.is_empty() {
return Err(io::Error::other(format!(
"cannot run query {query} because reference discovery failed:\n{}",
errors.join("\n")
)));
}
let found =
crate::structural::query_matches(&sources.root, &files, &sources.outlines, &queries, name)
.map_err(|error| io::Error::other(format!("query {query}: {error}")))?;
// Matches arrive in path and source order; each site is one entry.
let mut by_file = BTreeMap::<String, BTreeMap<String, SearchMatchLines>>::new();
for found in found {
by_file
.entry(found.site.file)
.or_default()
.entry(found.site.item)
.or_default()
.push(found.line_start..=found.line_end);
}
let mut entries = Vec::new();
for (file, items) in by_file {
let parsed = sources.parse_file(&file)?;
let parsed = parsed
.as_ref()
.as_ref()
.map_err(|error| io::Error::other(error.clone()))?;
let mut nodes = SearchNodes::default();
for (item, lines) in items {
let index = parsed.resolve(&file, &item).map_err(io::Error::other)?;
for lines in lines {
nodes.add(index, lines.clone(), lines);
}
}
entries.extend(nodes.entries(&file, parsed));
}
Ok(Listing::object(&["matches"], vec![entries]))
}
Input 27: outline src/authoring/tools.rs mod[tests]/fn[ast_grep_queries_run_declared_queries_and_return_their_sites]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[ast_grep_queries_run_declared_queries_and_return_their_sites] - Kind:
fn src/authoring/tools.rs:4872–4957
// {test}`requirements.authoring.structural_search`
// {test}`requirements.references.distributed`
#[test]
fn ast_grep_queries_run_declared_queries_and_return_their_sites() {
let root = project();
fs::write(
root.path().join("md/requirements.md"),
concat!(
":::{req} ready\nThe project MUST be ready.\n:::\n\n",
"::::{req} errors\nAccumulating functions MUST keep going.\n\n",
":::{sites} accumulators\n```yaml\nlanguage: rust\npaths: [src]\nexclude: [src/skip.rs]\n",
"rule:\n kind: function_item\n has:\n stopBy: end\n kind: identifier\n regex: \"^errors$\"\n",
"match: [\"fn f(errors: u8) {}\"]\nno_match: [\"fn f() {}\"]\n```\n:::\n\n",
":::{violations} exits\n```yaml\nlanguage: rust\nwithin: accumulators\n",
"rule:\n kind: return_expression\n",
"match: [\"fn f(errors: u8) { return; }\"]\nno_match: [\"fn f() { return; }\"]\n```\n:::\n",
"::::\n\n",
"::::{req} broken\nBroken.\n\n:::{sites} bad\nNo code block.\n:::\n::::\n",
),
)
.unwrap();
fs::write(
root.path().join("md/terms.md"),
":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
)
.unwrap();
fs::write(
root.path().join("src/lib.rs"),
format!(
"fn check(errors: &mut Vec<String>) {{\n // {}\n if errors.is_empty() {{\n return;\n }}\n}}\n\nfn helper() {{\n return;\n}}\n\nmod inner {{\n fn nested(errors: u8) {{}}\n}}\n",
role("term", "terms.value")
),
)
.unwrap();
fs::write(
root.path().join("src/skip.rs"),
"fn skipped(errors: u8) {}\n",
)
.unwrap();
fs::create_dir_all(root.path().join("tests")).unwrap();
fs::write(
root.path().join("tests/outside.rs"),
"fn outside(errors: u8) {}\n",
)
.unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let query = |name: &str| dispatch(&sources, "ast_grep", &json!({"query": name}));
// Site queries honour paths and exclude.
let sites = query("requirements.errors/accumulators").unwrap();
assert_eq!(
found(&sites),
["src/lib.rs#fn[check]", "src/lib.rs#mod[inner]/fn[nested]"]
);
// Each site shows its matched lines, without terminology.
let lines = |delivery: &ToolDelivery, entry: usize| {
matched(delivery)[entry]["lines"]
.as_array()
.unwrap()
.iter()
.map(|line| line["matched"].as_bool().unwrap())
.collect::<Vec<_>>()
};
assert_eq!(lines(&sites, 0), [true; 6]);
assert!(sites.result.get("definitions").is_none());
// Violation matches belong to the innermost containing site; matches
// inside no site are discarded.
let violations = query("requirements.errors/exits").unwrap();
assert_eq!(found(&violations), ["src/lib.rs#fn[check]"]);
assert_eq!(
matched(&violations)[0]["lines"],
json!([{"text": " return;", "matched": true}])
);
for (name, message) in [
(
"requirements.errors/missing",
"declares no query named \"missing\"",
),
(
"requirements.broken/bad",
"exactly one fenced yaml code block",
),
] {
let error = query(name).err().unwrap();
assert!(error.to_string().contains(message), "{name}: {error}");
}
}
Input 28: outline src/index.rs mod[tests]/fn[invalid_evidence_detail_remains_readable]
- File:
src/index.rs - Selector:
mod[tests]/fn[invalid_evidence_detail_remains_readable] - Kind:
fn src/index.rs:1727–1813
// {test}`requirements.index.invalid_detail`
#[test]
fn invalid_evidence_detail_remains_readable() {
let definition = Definition {
path: Path::new("requirements.md").to_path_buf(),
text: "Ready MUST work.".to_owned(),
kind: DefinitionKind::Requirement,
};
let detail = Path::new("requirements-index/requirements.ready.md");
let index = Path::new("requirements-index.md");
let findings = ["evidence/requirements.ready.json: invalid JSON"];
let page = render_detail_page(
"requirements.ready",
detail,
Some(index),
&definition,
DetailEvidence {
state: EvidenceState::Invalid,
record: Some("{broken"),
errors: &findings.map(str::to_owned),
fixme_entries: &[],
},
&RenderSources {
root: Path::new("."),
definitions: &BTreeMap::new(),
references: &[],
source_links: None,
outlines: &crate::inputs::OutlineCache::default(),
},
);
assert!(page.contains("> Ready MUST work."));
assert!(page.contains("## Validation findings"));
assert!(page.contains("invalid JSON"));
assert!(page.contains("No rationale recorded."));
assert!(page.contains("No inputs recorded."));
assert!(page.contains("## Unreadable evidence record"));
assert!(page.contains("```json\n{broken\n```"));
let missing = render_detail_page(
"requirements.ready",
detail,
Some(index),
&definition,
DetailEvidence {
state: EvidenceState::Missing,
record: None,
errors: &[],
fixme_entries: &[],
},
&RenderSources {
root: Path::new("."),
definitions: &BTreeMap::new(),
references: &[],
source_links: None,
outlines: &crate::inputs::OutlineCache::default(),
},
);
assert!(missing.contains("> Ready MUST work."));
assert!(missing.contains("No rationale recorded."));
assert!(missing.contains("No inputs recorded."));
for record in ["{}", r#"{"rationale":" ","inputs":[]}"#] {
let page = render_detail_page(
"requirements.ready",
detail,
Some(index),
&definition,
DetailEvidence {
state: EvidenceState::Invalid,
record: Some(record),
errors: &findings.map(str::to_owned),
fixme_entries: &[],
},
&RenderSources {
root: Path::new("."),
definitions: &BTreeMap::new(),
references: &[],
source_links: None,
outlines: &crate::inputs::OutlineCache::default(),
},
);
assert!(page.contains("> Ready MUST work."), "{page}");
assert!(page.contains("## Validation findings"), "{page}");
assert!(page.contains("invalid JSON"), "{page}");
assert!(page.contains("No rationale recorded."), "{page}");
assert!(page.contains("No inputs recorded."), "{page}");
}
}
Input 30: outline src/evidence.rs fn[load_definitions]
- File:
src/evidence.rs - Selector:
fn[load_definitions] - Kind:
fn src/evidence.rs:156–173
// {impl}`requirements.authoring.mandatory_inputs`
// {impl}`requirements.ci.book_source`
// {impl}`requirements.ci.definition_errors`
pub(crate) fn load_definitions(root: &Path) -> io::Result<BTreeMap<String, Declaration>> {
let root = fs::canonicalize(root)?;
// Any failure aborts, so this is not a validation site.
let mut failures = Vec::new();
let md_root = book_source_dir(&root, &mut failures);
let definitions = collect_definitions(&root, &md_root, &mut failures);
if failures.is_empty() {
Ok(definitions)
} else {
Err(io::Error::new(
io::ErrorKind::InvalidData,
failures.join("\n"),
))
}
}
Input 31: outline src/evidence.rs fn[reference_set_digest_for]
- File:
src/evidence.rs - Selector:
fn[reference_set_digest_for] - Kind:
fn src/evidence.rs:1336–1372
/// The current reference-set digest of a requirement or named example, as
/// recorded in its evidence's `references` field.
// {impl}`requirements.ci.reference_set`
pub fn reference_set_digest_for(root: &Path, name: &str) -> io::Result<String> {
let root = fs::canonicalize(root)?;
// Errors in other declarations are validation errors; they do not change
// this definition's reference set.
let mut ignored = Vec::new();
let md_root = book_source_dir(&root, &mut ignored);
let definitions = collect_definitions(&root, &md_root, &mut ignored);
let definition = definitions
.get(name)
.filter(|definition| definition.kind != DefinitionKind::Term)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("{name}: no matching requirement or named example"),
)
})?;
// A discovery failure aborts, so this is not a validation site.
let mut failures = Vec::new();
let files = discovered_files(&root, &mut failures);
let references = collect_references_with_progress(&root, &files, &mut failures, &mut |_| {});
if !failures.is_empty() {
return Err(io::Error::other(failures.join("\n")));
}
let outlines = OutlineCache::default();
let sites = definition_sites(&root, name, definition, &files, &outlines)?;
Ok(reference_set_digest(
&root,
&outlines,
name,
definition,
&references,
&sites,
))
}
Input 32: outline src/refactor/tests.rs fn[site_reviews_follow_their_site_and_renamed_requirement]
- File:
src/refactor/tests.rs - Selector:
fn[site_reviews_follow_their_site_and_renamed_requirement] - Kind:
fn src/refactor/tests.rs:249–320
// {test}`requirements.refactor.record_files`
// {test}`requirements.refactor.record_fields`
// {test}`requirements.refactor.equivalence`
#[test]
fn site_reviews_follow_their_site_and_renamed_requirement() {
use crate::sites::tests::{RULE, SOURCE, inspect, project, write_review};
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_one]",
json!({"queries": ["checkers", "panics"]}),
);
write_review(root, "fn[check_two]", json!({}));
write_review(
root,
"mod[inner]/fn[check_three]",
json!({"queries": ["checkers", "panics"]}),
);
let site_errors = |root: &Path| {
let (errors, _) = inspect(root);
errors
.into_iter()
.filter(|error| error.starts_with("evidence/sites/"))
.collect::<Vec<_>>()
};
assert_eq!(site_errors(root), Vec::<String>::new());
// The requirement moves to the `rules` chapter and `check_two` to its
// own file, both unchanged.
let chapter = fs::read_to_string(root.join("md/requirements.md")).unwrap();
fs::remove_file(root.join("md/requirements.md")).unwrap();
fs::write(root.join("md/rules.md"), chapter).unwrap();
fs::write(
root.join("src/lib.rs"),
SOURCE.replace("fn check_two() {}\n", ""),
)
.unwrap();
fs::write(root.join("src/other.rs"), "fn check_two() {}\n").unwrap();
let report = refactor(
root,
&[
"requirements.rule=rules.rule".to_owned(),
"src/lib.rs#fn[check_two]=src/other.rs#fn[check_two]".to_owned(),
],
false,
)
.unwrap();
assert!(
report.contains(
"- evidence/sites/requirements.rule/src/lib.rs/fn[check_two].json -> evidence/sites/rules.rule/src/other.rs/fn[check_two].json"
),
"{report}"
);
let moved: Value = serde_json::from_str(
&fs::read_to_string(root.join("evidence/sites/rules.rule/src/other.rs/fn[check_two].json"))
.unwrap(),
)
.unwrap();
assert_eq!(moved["requirement"], "rules.rule");
assert_eq!(moved["file"], "src/other.rs");
assert_eq!(moved["item"], "fn[check_two]");
assert!(!root.join("evidence/sites/requirements.rule").exists());
assert_eq!(site_errors(root), Vec::<String>::new());
}