requirements.test-coverage.index.file_map.notes
Requirements index · View definition
Requirement
Each listed first-party Rust file in the combined file coverage map MUST provide access to a file-notes view identifying its workspace-relative path.
Rationale
The requirement has two obligations. (1) Each listed first-party Rust file in the combined map must give access to a file-notes view. (2) That view must identify the file’s workspace-relative path.
Link from the map (obligation 1).
src/execution_coverage/book.rs#mod[tests]/fn[gaps_union_process_locations_and_omit_per_test_reports]populates a combined map with three listed files. It computes the notes path withnotes::pathand the expected href withchapter_href. It asserts that thecode.rscard contains that exacthref.- The same test finds the generated chapter at that path. It asserts the chapter exists and contains
File: <code>code.rs</code>. - It also asserts that every generated chapter after the index is named
File notes: …. - The link is built by
GapDirectory::renderandgaps_mapthrough one uniform expression with no per-file conditional. Testing it forcode.rstherefore covers the other listed files. I did not request the check.rs tests that assert thecoverage-reports/files/link in the accepted-exceptions section, because they are not marked for this requirement and the marked tests already suffice.
Notes view and path (obligation 2).
src/execution_coverage/book.rs#mod[tests]/fn[gap_notes_use_current_source_without_collecting]checks three files:code.rs,src/a.rsandsrc/nested/a.rs. The last two share the file namea.rsand sit in different directories.- It asserts that each file’s
notes::pathis distinct. It asserts that each file has exactly one chapter at that path. It asserts that each chapter containsFile: <code>{file}</code>with the workspace-relative path. Together these rule out collisions and a basename-only identifier. src/execution_coverage/notes.rs#mod[tests]/fn[notes_show_root_function_and_method_proposals_with_owned_commentary_and_docs]renders a page directly and assertsFile: <code>code.rs</code>andSource: <code>code.rs:….
Not assessed here.
- The notes content, currency, render-only behaviour and justifications belong to the refining sub-requirements (
notes.current,notes.render_only,notes.justifications). - The unavailable-coverage cases show no file rows, so no file is “listed” there and no link is required.
I found no plausible violation that these tests would accept. The remaining untested variants (a link for a nested file’s row, or for the not-measured file) share the same unconditional code paths.
Inputs
Implementation
Input 6: outline src/execution_coverage/notes.rs fn[pages]
- File:
src/execution_coverage/notes.rs - Selector:
fn[pages] - Kind:
fn src/execution_coverage/notes.rs:24–77
// {impl}`requirements.test-coverage.index.file_map.notes`
// {impl}`requirements.test-coverage.index.file_map.notes.justifications`
// {impl}`requirements.test-coverage.index.file_map.notes.current`
// {impl}`requirements.test-coverage.index.file_map.notes.availability`
// {impl}`requirements.test-coverage.index.file_map.notes.reviews`
// {impl}`requirements.test-coverage.index.file_map.notes.render_only`
pub(super) fn pages(root: &Path, files: &BTreeSet<String>, index: &Path) -> Vec<Chapter> {
let outlines = OutlineCache::default();
let mut diagnostics = Vec::new();
let references = crate::evidence::collect_references(root, &mut diagnostics);
let definitions = crate::evidence::load_definitions(root).unwrap_or_else(|error| {
diagnostics.push(error.to_string());
BTreeMap::new()
});
let items = citation_items(root, &definitions, &references, &outlines);
files
.iter()
.map(|file| {
let path = path(index, file);
let mut content = format!(
"# Coverage explanations\n\n[Back to coverage index]({})\n\nFile: <code>{}</code>.\n\n**Current workspace source notes**, read at book-render time. These explanations and review states describe the current source.\n\n",
crate::chapter_href(&path, index, None), escaped(file),
);
match outlines.parse(root, file).as_ref() {
Err(error) => diagnostic(&mut content, error),
Ok(parsed) => {
for error in &diagnostics {
diagnostic(&mut content, error);
}
let mut count = 0;
for item in items.values().filter(|item| item.file == *file) {
let Ok(node) = parsed.resolve(file, &item.item) else {
diagnostic(&mut content, "Cannot resolve the cited source item.");
continue;
};
if !(item.item.is_empty() || parsed.outline.nodes[node].kind == "fn")
|| !item.citations.iter().any(|cite| cite.name == "habeas:coverage")
{
continue;
}
count += 1;
entry(&mut content, root, parsed, node, item, &definitions, &outlines);
}
if count == 0 && diagnostics.is_empty() {
content.push_str("No coverage explanations are present on this file's root or explicitly declared functions and methods.\n");
}
},
}
let mut chapter = Chapter::new(&format!("File notes: {file}"), content, path, vec![]);
chapter.source_path = None;
chapter
})
.collect()
}
Input 8: outline src/execution_coverage/book.rs fn[gaps_map]
- File:
src/execution_coverage/book.rs - Selector:
fn[gaps_map] - Kind:
fn src/execution_coverage/book.rs:213–302
// {impl}`requirements.test-coverage.index.file_map.combined`
// {impl}`requirements.test-coverage.index.file_map.combined.measurement`
// {impl}`requirements.test-coverage.index.file_map.table`
// {impl}`requirements.test-coverage.index.file_map.directories`
// {impl}`requirements.test-coverage.index.file_map.directories.initial`
// {impl}`requirements.test-coverage.index.file_map.directories.data`
// {impl}`requirements.test-coverage.index.file_map.minimum`
// {impl}`requirements.test-coverage.index.file_map.minimum.statuses`
// {impl}`requirements.test-coverage.index.gaps`
// {impl}`requirements.test-coverage.index.gaps.summary`
// {impl}`requirements.test-coverage.index.gaps.details`
// {impl}`requirements.test-coverage.index.gaps.details.initial`
// {impl}`requirements.test-coverage.index.gaps.accepted`
// {impl}`requirements.test-coverage.index.file_map.notes`
fn gaps_map(policy: &super::check::PolicyReport, index: &Path, attempts: usize) -> String {
let mut html = format!(
"<style>{}</style>\n<section class=\"habeas-coverage-map habeas-coverage-gaps\" aria-label=\"Coverage gaps\">\n<p class=\"gap-meta\">Combined coverage · {attempts} selected test attempts</p><p class=\"gap-policy gap-meta\">File target: 80% of instrumented lines. Every function needs execution or an accepted explanation.</p>\n",
include_str!("../../assets/coverage-gaps.css")
);
let unresolved: Vec<_> = policy
.files
.iter()
.flat_map(|file| &file.obligations)
.filter(|gap| !gap.accepted())
.collect();
let files = unresolved
.iter()
.filter(|gap| gap.selector.is_empty())
.count();
let functions = unresolved.len() - files;
html.push_str(&format!(
"<div class=\"gap-verdict\" role=\"status\"><strong>CI would {}</strong>",
if policy.report.passed { "pass" } else { "fail" }
));
if policy.counts_complete {
html.push_str(&format!("<span>{} unresolved gaps</span><span class=\"gap-meta\">{files} file obligations · {functions} function obligations</span>", unresolved.len()));
} else if policy.measured {
html.push_str(&format!(
"<span>Gap counts incomplete: {} established unresolved gaps</span>",
unresolved.len()
));
} else {
html.push_str("<span>Coverage unavailable · gap counts unavailable</span>");
}
html.push_str("</div><p class=\"gap-section-label\">Unresolved coverage gaps</p>\n");
let mut directory = GapDirectory::default();
for file in &policy.files {
if !file.obligations.iter().any(|gap| !gap.accepted()) {
continue;
}
let mut dir = &mut directory;
if let Some((folder, _)) = file.file.rsplit_once('/') {
for part in folder.split('/') {
dir = dir.directories.entry(part.into()).or_default();
}
}
dir.files.push(file);
}
directory.render(&mut html, "", policy, index, &mut 0);
if unresolved.is_empty() && policy.counts_complete {
html.push_str("<p>No unsatisfied file or function obligations.</p>\n");
}
let accepted = policy
.files
.iter()
.flat_map(|file| {
file.obligations
.iter()
.filter(|gap| gap.accepted())
.map(move |gap| (file, gap))
})
.collect::<Vec<_>>();
html.push_str(&format!("<details class=\"gap-accepted-group\"><summary>Documented gaps — {} accepted exceptions</summary><p class=\"gap-meta\">Current workspace source notes. Accepted exceptions do not increase measured percentages.</p>\n", accepted.len()));
for (file, gap) in accepted {
let notes = crate::chapter_href(index, &super::notes::path(index, &file.file), None);
html.push_str(&format!("<div class=\"gap-accepted-item\"><p><a href=\"{}\"><code>{}:{} #{}</code></a> · {} · <span class=\"gap-accepted-state\">current and accepted</span></p>{}</div>\n", escaped(¬es), escaped(&file.file), gap.line, escaped(if gap.selector.is_empty() { "File root" } else { &gap.selector }), escaped(&gap.measurement), explanation_html(gap)));
}
html.push_str("</details>\n");
if !policy.findings.is_empty() {
html.push_str(
"<details class=\"gap-footer\"><summary>Coverage-check findings</summary><ul>",
);
for finding in &policy.findings {
html.push_str(&format!("<li>{}</li>", escaped(finding)));
}
html.push_str("</ul></details>\n");
}
html.push_str("<p class=\"gap-footer gap-meta\">Coverage uses the latest compatible attempt for each test, including filtered runs. This does not establish that all current tests were measured. Saved measurements and current exception reviews determine the CI verdict.</p>\n</section>\n\n");
html
}
Tests
Input 2: outline src/execution_coverage/book.rs mod[tests]/fn[gaps_union_process_locations_and_omit_per_test_reports]
- File:
src/execution_coverage/book.rs - Selector:
mod[tests]/fn[gaps_union_process_locations_and_omit_per_test_reports] - Kind:
fn src/execution_coverage/book.rs:1116–1205
// {test}`requirements.test-coverage.index.file_map`
// {test}`requirements.test-coverage.index.file_map.table`
// {test}`requirements.test-coverage.index.file_map.combined`
// {test}`requirements.test-coverage.index.file_map.test`
// {test}`requirements.test-coverage.index.summary`
// {test}`requirements.test-coverage.index.file_map.combined.details`
// {test}`requirements.test-coverage.index.file_map.notes`
// {test}`requirements.test-coverage.index.details`
#[test]
fn gaps_union_process_locations_and_omit_per_test_reports() {
let (temp, mut book) = fixture();
let root = temp.path();
fs::write(
root.join("code.rs"),
"fn one() {}\nfn two() {}\nfn three() {}\n// not instrumented\n",
)
.unwrap();
fs::write(root.join("zero.rs"), "fn zero() {}\n").unwrap();
fs::write(root.join("unmeasured.rs"), "// no instrumentation\n").unwrap();
fs::write(root.join("executable.rs"), "fn unmeasured() {}\n").unwrap();
let path = record(root, "one", 1, "a", &[(1, 2), (2, 0)]);
let run_path = path.parent().unwrap().parent().unwrap().join("run.json");
let mut run: Run = load(&run_path).unwrap();
for file in ["zero.rs", "unmeasured.rs", "executable.rs"] {
run.sources
.insert(file.into(), fs::read_to_string(root.join(file)).unwrap());
}
save(&run_path, &run).unwrap();
let mut attempt: Attempt = load(&path.join("attempt.json")).unwrap();
attempt.processes[0]
.lines
.insert("zero.rs".into(), BTreeMap::from([(1, 0)]));
fs::write(path.join("2-child.profraw"), "child profile fixture").unwrap();
attempt.processes.push(Process {
functions: Some(vec![]),
pid: 2,
profiles: vec!["2-child.profraw".into()],
diagnostic: None,
lines: BTreeMap::from([("code.rs".into(), BTreeMap::from([(1, 0), (3, u64::MAX)]))]),
});
save(&path.join("attempt.json"), &attempt).unwrap();
populate(&mut book, root).unwrap();
let index = &book.chapters().next().unwrap().content;
assert!(index.contains("Line coverage: **2/4 (50.0%)**"));
let map = map_html(index);
assert!(file_card(map, "code.rs").contains("2/3 instrumented lines covered"));
assert!(file_card(map, "code.rs").contains("66.7%"));
assert!(file_card(map, "code.rs").contains("--gap-covered: 66.666667%"));
let notes_path = super::super::notes::path(Path::new("reports/coverage.md"), "code.rs");
let href = crate::chapter_href(Path::new("reports/coverage.md"), ¬es_path, None);
assert!(file_card(map, "code.rs").contains(&format!("href=\"{href}\"")));
let notes = book
.chapters()
.find(|chapter| chapter.path.as_ref() == Some(¬es_path))
.unwrap();
assert!(notes.content.contains("File: <code>code.rs</code>"));
assert!(file_card(map, "zero.rs").contains("0.0%"));
assert!(file_card(map, "zero.rs").contains("--gap-covered: 0.000000%"));
assert!(
!map.contains("data-file=\"unmeasured.rs\""),
"a non-executable file has no gap"
);
let unmeasured = file_card(map, "executable.rs")
.split("</tr>")
.next()
.unwrap();
assert!(unmeasured.contains("not measured"));
assert!(!unmeasured.contains('%'));
assert!(!unmeasured.contains("gap-coverage-bar"));
assert!(map.contains("<th>File</th><th>Coverage</th>"));
assert_eq!(
map.matches("class=\"gap-file-row habeas-coverage-file\"")
.count(),
3
);
let mut html = String::new();
pulldown_cmark::html::push_html(
&mut html,
pulldown_cmark::Parser::new_ext(index, pulldown_cmark::Options::all()),
);
assert!(html.contains("Unresolved coverage gaps"));
assert!(!html.contains("habeas-coverage-test"));
assert!(!html.contains("Test runs and provenance"));
assert!(!html.contains("binary / one"));
assert!(
book.chapters()
.skip(1)
.all(|chapter| chapter.name.starts_with("File notes:"))
);
}
Input 3: outline src/execution_coverage/book.rs mod[tests]/fn[gap_notes_use_current_source_without_collecting]
- File:
src/execution_coverage/book.rs - Selector:
mod[tests]/fn[gap_notes_use_current_source_without_collecting] - Kind:
fn src/execution_coverage/book.rs:1644–1718
// {test}`requirements.test-coverage.index.file_map.notes`
// {test}`requirements.test-coverage.index.file_map.notes.current`
// {test}`requirements.test-coverage.index.file_map.notes.render_only`
#[test]
fn gap_notes_use_current_source_without_collecting() {
let (temp, mut book) = fixture();
let root = temp.path();
fs::create_dir(root.join("md")).unwrap();
fs::write(root.join("book.toml"), "[book]\nsrc='md'\n").unwrap();
fs::write(root.join("md/SUMMARY.md"), "# Summary\n").unwrap();
fs::create_dir_all(root.join("src/nested")).unwrap();
for file in ["src/a.rs", "src/nested/a.rs"] {
fs::write(root.join(file), "fn another() {}\n").unwrap();
}
let attempt = record(root, "one", 1, "a", &[(1, 1)]);
let run_path = attempt.parent().unwrap().parent().unwrap().join("run.json");
let mut run: Run = load(&run_path).unwrap();
let mut process: Attempt = load(&attempt.join("attempt.json")).unwrap();
for file in ["src/a.rs", "src/nested/a.rs"] {
run.sources
.insert(file.into(), fs::read_to_string(root.join(file)).unwrap());
process.processes[0]
.lines
.insert(file.into(), BTreeMap::from([(1, 1)]));
}
save(&run_path, &run).unwrap();
save(&attempt.join("attempt.json"), &process).unwrap();
let captured = fs::read(attempt.join("attempt.json")).unwrap();
fs::write(root.join("code.rs"),
"// :::{cite} habeas:coverage\n// Current explanation, added after capture.\n// :::\nfn current() {}\n").unwrap();
populate(&mut book, root).unwrap();
let index = book.chapters().next().unwrap();
let notes_path = super::super::notes::path(index.path.as_ref().unwrap(), "code.rs");
let notes = book
.chapters()
.find(|chapter| chapter.path.as_ref() == Some(¬es_path))
.unwrap();
assert!(
notes
.content
.contains("Current explanation, added after capture.")
);
assert!(notes.content.contains("Current workspace source notes"));
assert!(notes.content.contains("code.rs"));
assert_eq!(
book.chapters()
.filter(|chapter| chapter.path.as_ref() == Some(¬es_path))
.count(),
1
);
let mut distinct = BTreeSet::new();
for file in ["code.rs", "src/a.rs", "src/nested/a.rs"] {
let path = super::super::notes::path(index.path.as_ref().unwrap(), file);
assert!(
distinct.insert(path.clone()),
"files must have distinct views"
);
let notes = book
.chapters()
.find(|chapter| chapter.path.as_ref() == Some(&path))
.unwrap();
assert!(
notes
.content
.contains(&format!("File: <code>{file}</code>"))
);
assert!(index.content.contains("Coverage unavailable"));
}
assert_eq!(fs::read(attempt.join("attempt.json")).unwrap(), captured);
assert_eq!(
fs::read_to_string(attempt.join("1-1.profraw")).unwrap(),
"retained profile fixture"
);
assert!(!root.join("evidence").exists());
}
Input 4: outline src/execution_coverage/notes.rs mod[tests]/fn[notes_show_root_function_and_method_proposals_with_owned_commentary_and_docs]
- File:
src/execution_coverage/notes.rs - Selector:
mod[tests]/fn[notes_show_root_function_and_method_proposals_with_owned_commentary_and_docs] - Kind:
fn src/execution_coverage/notes.rs:250–351
// {test}`requirements.test-coverage.index.file_map.notes`
// {test}`requirements.test-coverage.index.file_map.notes.justifications`
#[test]
fn notes_show_root_function_and_method_proposals_with_owned_commentary_and_docs() {
let temp = fixture(
"//! Root documentation.\n\
//! :::{cite} habeas:coverage\n\
//! File threshold justification.\n\
//! :::\n\n\
/// Function documentation.\n\
// :::{cite} habeas:coverage\n\
// Function explanation with <unsafe> text.\n\
// :::\n\
fn ordinary() {}\n\n\
struct Worker;\n\
impl Worker {\n\
/** Method documentation. */\n\
// :::{cite} habeas:coverage\n\
// Method explanation.\n\
// :::\n\
fn work(&self) {}\n\
}\n\n\
// {cite}`habeas:coverage`\n\
fn unexplained() {}\n\n\
// :::{cite} habeas:coverage\n\
// Nested module must not become a file exception.\n\
// :::\n\
mod nested {\n\
/// Child documentation must stay with the child.\n\
fn child() {}\n\
}\n",
);
let content = render(temp.path());
for text in [
"File: <code>code.rs</code>",
"File root",
"File-threshold exception proposal",
"fn[ordinary]",
"impl[Worker]/fn[work]",
"Function exception proposal",
"Root documentation.",
"File threshold justification.",
"Function documentation.",
"Function explanation with <unsafe> text.",
"Method documentation.",
"Method explanation.",
"fn[unexplained]",
"No tracked justification is present.",
"Source: <code>code.rs:",
"First source citation at line",
] {
assert!(content.contains(text), "missing {text}: {content}");
}
assert_eq!(
content.matches("File-threshold exception proposal").count(),
1
);
assert_eq!(content.matches("Function exception proposal").count(), 3);
assert!(!content.contains("Nested module must"));
assert!(!content.contains("Child documentation"));
assert!(!content.contains("<unsafe>"));
assert_eq!(content.matches("Review: **missing**").count(), 4);
assert_eq!(
content
.matches("No tracked justification is present.")
.count(),
1
);
assert!(content.contains("cannot read citation review"));
let unexplained = content
.split("## <code>fn[unexplained]")
.nth(1)
.unwrap()
.split("## <code>")
.next()
.unwrap();
assert!(!unexplained.contains("Rust doc comments"));
assert!(unexplained.contains("No tracked justification is present."));
for (label, first, last, citation) in [
("File root", 1, 30, 2),
("fn[ordinary]", 6, 10, 7),
("impl[Worker]/fn[work]", 14, 18, 15),
("fn[unexplained]", 21, 22, 21),
] {
let heading = format!("## <code>{label}</code>");
let entry = content
.split(&heading)
.nth(1)
.unwrap()
.split("## <code>")
.next()
.unwrap();
assert!(
entry.contains(&format!("Source: <code>code.rs:{first}–{last}</code>")),
"{label}: {entry}"
);
assert!(
entry.contains(&format!("First source citation at line {citation}.")),
"{label}: {entry}"
);
}
}
Other sources
Input 1: requirements selection requirements.test-coverage.index.file_map.notes
requirements.test-coverage.index.file_map.notes:md/requirements/test-coverage.md:312–316
:::{req} index.file_map.notes
Each listed first-party Rust file in the combined file coverage
map MUST provide access to a file-notes view identifying its
workspace-relative path.
:::
Input 5: outline src/execution_coverage/book.rs impl[GapDirectory<'_>]/fn[render]
- File:
src/execution_coverage/book.rs - Selector:
impl[GapDirectory<'_>]/fn[render] - Kind:
fn src/execution_coverage/book.rs:87–182
fn render(
&self,
html: &mut String,
folder: &str,
policy: &super::check::PolicyReport,
index: &Path,
next: &mut usize,
) {
if !self.files.is_empty() {
html.push_str("<table class=\"gap-file-table\"><colgroup><col><col><col><col></colgroup><thead><tr><th>File</th><th>Coverage</th><th>Uncovered obligations</th><th>Explanation</th></tr></thead><tbody>\n");
for file in &self.files {
let id = format!("habeas-gap-file-{}", *next);
*next += 1;
let gaps: Vec<_> = file
.obligations
.iter()
.filter(|gap| !gap.accepted())
.collect();
let threshold = gaps.iter().any(|gap| gap.selector.is_empty());
let functions = gaps.len() - usize::from(threshold);
let undocumented = gaps.iter().filter(|gap| gap.exception.is_none()).count();
let description = match (threshold, functions) {
(true, 0) => "file below target".to_owned(),
(true, n) => format!("file + {n} functions"),
(false, 1) => "1 function".to_owned(),
(false, n) => format!("{n} functions"),
};
let explanation = if undocumented == gaps.len() {
"Missing"
} else {
"Review needed"
};
let percentage = if file.total == 0 {
"not measured".to_owned()
} else {
percentage_label(file.covered, file.total)
};
let indicator = if file.total == 0 {
String::new()
} else {
format!(
"<span class=\"gap-coverage-bar\" aria-hidden=\"true\" style=\"--gap-covered: {:.6}%\"></span>",
100.0 * file.covered as f64 / file.total as f64
)
};
html.push_str(&format!("<tr class=\"gap-file-row habeas-coverage-file\" data-file=\"{}\" data-status=\"{}\"><td><button class=\"gap-file-button\" aria-expanded=\"false\" aria-controls=\"{id}\" onclick=\"const row=document.getElementById(this.getAttribute('aria-controls'));row.hidden=!row.hidden;this.setAttribute('aria-expanded',String(!row.hidden));this.querySelector('.gap-chevron').textContent=row.hidden?'▸':'▾'\"><span class=\"gap-chevron\" aria-hidden=\"true\">▸</span><code>{}</code></button></td><td class=\"gap-percentage\">{percentage}{indicator}</td><td>{description}</td><td class=\"gap-unresolved\">{explanation}</td></tr>\n", escaped(&file.file), if file.total == 0 { "not measured" } else { "measured" }, escaped(&file.file)));
let notes =
crate::chapter_href(index, &super::notes::path(index, &file.file), None);
html.push_str(&format!("<tr class=\"gap-detail-row\" id=\"{id}\" hidden><td colspan=\"4\"><p class=\"gap-detail-title\"><code>{}</code> · {}/{} instrumented lines covered · <a href=\"{}\">Current source notes</a></p><table class=\"gap-obligation-table\"><thead><tr><th>Source item</th><th>Measurement</th><th>Explanation</th></tr></thead><tbody>", escaped(&file.file), file.covered, file.total, escaped(¬es)));
for gap in gaps {
html.push_str(&format!("<tr><td><code>{}</code><br><span class=\"gap-meta\">{}:{}</span></td><td>{}</td><td>{}</td></tr>\n", escaped(if gap.selector.is_empty() { "File root" } else { &gap.selector }), escaped(&file.file), gap.line, escaped(&gap.measurement), explanation_html(gap)));
}
html.push_str("</tbody></table></td></tr>\n");
}
html.push_str("</tbody></table>\n");
}
for (name, directory) in &self.directories {
let path = if folder.is_empty() {
name.clone()
} else {
format!("{folder}/{name}")
};
let prefix = format!("{path}/");
let minimum = policy
.files
.iter()
.filter(|file| file.file.starts_with(&prefix) && file.total > 0)
.min_by(|a, b| {
((a.covered as u128) * (b.total as u128))
.cmp(&((b.covered as u128) * (a.total as u128)))
});
let min = minimum.map_or_else(|| "No measured files".to_owned(), |file| format!("Minimum measured file coverage: <strong data-min-covered=\"{}\" data-min-instrumented=\"{}\">{}</strong>", file.covered, file.total, percentage_label(file.covered, file.total)));
let not_measured = policy
.files
.iter()
.filter(|file| {
file.file.starts_with(&prefix)
&& file.total == 0
&& file.obligations.iter().any(|gap| !gap.accepted())
})
.count();
let counts = if policy.counts_complete {
format!("{} uncovered obligations", directory.count())
} else if policy.measured {
format!(
"Gap counts incomplete: {} established uncovered obligations",
directory.count()
)
} else {
"Gap counts unavailable".to_owned()
};
html.push_str(&format!("<details class=\"gap-directory\" data-directory=\"{}\" open><summary><code>{}/</code><span class=\"gap-meta\">{min} · {counts}{} </span></summary>\n", escaped(&path), escaped(&path), if not_measured > 0 { format!(" · {not_measured} not measured") } else { String::new() }));
directory.render(html, &path, policy, index, next);
html.push_str("</details>\n");
}
}
Input 7: outline src/execution_coverage/book.rs fn[populate_in]
- File:
src/execution_coverage/book.rs - Selector:
fn[populate_in] - Kind:
fn src/execution_coverage/book.rs:526–691
// {impl}`requirements.test-coverage.index.navigation`
// {impl}`requirements.test-coverage.index.source`
// {impl}`requirements.test-coverage.index.guidance`
// {impl}`requirements.test-coverage.index.summary`
// {impl}`requirements.test-coverage.index.details`
// {impl}`requirements.test-coverage.index.file_map.test`
// {impl}`requirements.test-coverage.index.file_map.combined.details`
pub(super) fn populate_in(
book: &mut Book,
project: &Path,
target: Option<PathBuf>,
parent: &Path,
) -> io::Result<()> {
let index_path = parent.with_extension("").join("coverage.md");
let saved = load_saved(project, target);
let root = workspace_root(project).unwrap_or_else(|_| project.to_path_buf());
let policy = super::check::check_saved(&root, &saved)?;
let SavedCoverage {
records,
selected,
diagnostics,
uncertain_history,
current_files,
discovery_failed: _,
} = saved;
let note_files = if policy.measured {
policy
.files
.iter()
.filter(|file| !file.obligations.is_empty())
.map(|file| file.file.clone())
.collect()
} else {
current_files
};
let mut summary = String::from("# Coverage gaps\n\n");
summary.push_str(&gaps_map(&policy, &index_path, selected.len()));
if policy.measured {
let totals = union(selected.iter().map(|&index| &records[index]));
let covered = totals.values().filter(|&&count| count > 0).count();
summary.push_str(&format!("Line coverage: **{covered}/{} ({:.1}%)** from the union of instrumented file-and-line locations.\n\n", totals.len(), 100.0 * covered as f64 / totals.len() as f64));
}
if uncertain_history {
summary.push_str("Coverage history is incomplete: cannot establish latest-per-test selection. Combined totals are unavailable until the affected build artifacts are repaired or removed.\n\n");
}
if records.is_empty() {
summary.push_str("No test coverage is available. Run `habeas coverage` (or `cargo habeas coverage` in this repository), then rebuild the book.\n\n");
}
let stale = selected
.iter()
.filter(|&&index| !records[index].fresh)
.count();
let incomplete = selected
.iter()
.filter(|&&index| records[index].fresh && !readable(&records[index]))
.count();
let historical = records.last().map_or(0, |latest| {
records
.iter()
.filter(|record| record.run.configuration != latest.run.configuration)
.count()
});
if stale > 0 || incomplete > 0 || historical > 0 {
summary.push_str(&format!(
"**Excluded coverage:** {stale} stale test attempts; {incomplete} unavailable test attempts; {historical} attempts from a historical build configuration.\n\n"
));
}
for diagnostic in diagnostics {
summary.push_str(&format!(
"**Coverage diagnostic:** {}\n\n",
escaped(&diagnostic)
));
}
let existing: BTreeSet<_> = book
.chapters()
.filter_map(|chapter| chapter.path.clone())
.collect();
let mut generated = BTreeSet::from([index_path.clone()]);
if existing.contains(&index_path) {
return Err(io::Error::other(format!(
"coverage index path conflicts with an existing chapter: {}",
index_path.display()
)));
}
let mut details = Vec::new();
let notes_root = workspace_root(project).unwrap_or_else(|_| project.to_path_buf());
for chapter in super::notes::pages(¬es_root, ¬e_files, &index_path) {
let path = chapter
.path
.as_ref()
.expect("file notes have a render path");
if existing.contains(path) || !generated.insert(path.clone()) {
return Err(io::Error::other(format!(
"coverage report path conflicts with an existing chapter: {}",
path.display()
)));
}
details.push(BookItem::Chapter(chapter));
}
summary.push_str("## Collect coverage and check CI policy\n\n");
summary.push_str(super::GUIDANCE);
summary.push('\n');
let mut coverage = Some(Chapter::new("Coverage gaps", summary, &index_path, vec![]));
let mut found = false;
book.for_each_chapter_mut(|chapter| {
if chapter.path.as_deref() == Some(parent) {
found = true;
chapter.content.push_str(&format!(
"\n\n[Coverage gaps]({}) — uncovered obligations and their explanations.\n",
crate::chapter_href(parent, &index_path, None)
));
let mut page = coverage.take().expect("requirements index occurs once");
page.source_path = None;
page.parent_names = chapter.parent_names.clone();
page.parent_names.push(chapter.name.clone());
page.number = chapter.number.as_ref().map(|number| {
let mut parts = number.to_vec();
parts.push(1);
SectionNumber::new(parts)
});
for (offset, item) in details.iter_mut().enumerate() {
let BookItem::Chapter(child) = item else {
unreachable!()
};
child.parent_names = page.parent_names.clone();
child.parent_names.push(page.name.clone());
child.number = page.number.as_ref().map(|number| {
let mut parts = number.to_vec();
parts.push(offset as u32 + 1);
SectionNumber::new(parts)
});
}
page.sub_items.append(&mut details);
fn renumber(chapter: &mut Chapter, number: Vec<u32>) {
chapter.number = Some(SectionNumber::new(number.clone()));
let mut next = 1;
for item in &mut chapter.sub_items {
if let BookItem::Chapter(child) = item {
let mut parts = number.clone();
parts.push(next);
renumber(child, parts);
next += 1;
}
}
}
if let Some(number) = &chapter.number {
let mut next = 2;
for item in &mut chapter.sub_items {
if let BookItem::Chapter(child) = item {
let mut parts = number.to_vec();
parts.push(next);
renumber(child, parts);
next += 1;
}
}
}
chapter.sub_items.insert(0, BookItem::Chapter(page));
}
});
if !found {
return Err(io::Error::other(
"requirements index chapter disappeared before coverage generation",
));
}
Ok(())
}