requirements.references.coverage.history
Requirements index · View definition
Requirement
An item has recent coverage when it has a reference that covers it under
, or when its outline node, or an outline node containing it, is named by file and selector in the inputs of any version of an existing evidence record, citation review, or site review in its coverage window. A file’s coverage window MUST be its current contents on disk, committed or not, together with its contents in each of the last N commits in its Git history that changed it, read through a Git library rather than by running
git. A recorded hash MUST NOT matter here: an earlier version names the node, whatever its code was then. N MUST be the workspace[coverage]settingreauthorings, a positive integer, and 3 when it is not set. When the history is unavailable, such as outside Git or in a shallow clone missing those commits, the window MUST be the commits that are available, andhabeas status --coverageMUST say that coverage history is incomplete.
Rationale
The reviewed tests cover each obligation of requirements.references.coverage.history, and I found no adequacy gap.
Coverage by evidence name, whatever the hash, including enclosing nodes and all three record kinds
tests/references.rs#fn[items_named_by_recent_evidence_have_recent_coverage_whatever_their_hash]uses an ordinary record, a citation review and a site review.- The citation review names
impl[Thing], which covers the method inside it. - The site review records a stale hash, and the item is still covered.
- After the source is edited, coverage remains, so the recorded hash does not matter.
- An unread item is the only one reported.
- The citation review names
src/coverage_history.rs#mod[tests]/fn[coverage_follows_the_outline_parent_chain_not_selector_text]checks the parent-chain matching.- It matches the containing
impl[Thing]and the root"". - It rejects an unrelated selector and a different file.
- It rejects a
/inside brackets that only looks like a prefix.
- It matches the containing
Window of the current contents on disk plus the last N commits that changed the file
tests/coverage.rs#fn[coverage_lasts_for_three_reauthorings_of_the_record_that_read_an_item]covers the default N of 3 and thecoverage.reauthoredexample.- After two re-authorings the item is still covered.
- After a third,
parseis warned about. - The warning is not a validation error.
tests/coverage.rs#fn[uncommitted_records_count_as_they_are_on_disk]coverscoverage.uncommitted.- An uncommitted record that drops the item leaves it covered by the committed version.
- An uncommitted new record covers the item before any commit.
tests/coverage.rs#fn[deleting_the_only_record_that_read_an_item_warns_at_once]coverscoverage.deleted_requirement: a deleted record has no window, so its item is warned about at once.tests/coverage.rs#fn[a_merge_counts_only_when_it_differs_from_every_parent]rules out counting every commit rather than only commits that changed the file. With N=2, a merge that takes the side branch’s file unchanged is not counted, and the older version that readparsestays in the window.
N from [coverage] reauthorings, which must be a positive integer, and 3 by default
tests/coverage.rs#fn[the_window_follows_the_workspace_setting]sets N to 1 and shows the older version drops out. It also shows thatreauthorings = 0is rejected, and the error namescoverage.reauthorings.tests/coverage.rs#fn[an_invalid_coverage_table_is_a_validation_finding_but_authoring_proceeds]rejects0, a string value and an unknown key.
Read through a Git library, not by running git
tests/coverage.rs#fn[coverage_history_uses_the_git_library_without_launching_git]puts a tripwiregitonPATHthat fails every history-reading command.status --coveragestill gives the correct answer, and the tripwire is never triggered.tests/coverage.rs#fn[validation_does_not_read_git_history]checks that validation does not read history.
Unavailable history uses the available commits and is reported as incomplete
- Shallow clones:
a_shallow_clone_uses_the_history_it_has_and_says_so,status_shows_coverage_warnings_and_says_when_history_is_incomplete,incomplete_history_is_noted_even_with_nothing_to_warn_about,a_shallow_clone_holding_every_window_is_complete,a_linked_worktree_of_a_shallow_clone_knows_where_history_endsandan_uncommitted_record_does_not_make_a_full_shallow_history_incomplete.- These show the window shrinks to the available commits and the incomplete flag is set.
- They show
status --coverageprints “Coverage history is incomplete”. - They also show plain status does not print the incomplete notice, and the incomplete flag is not set when the clone holds the whole window.
- This covers
coverage.shallow_clone.
- Outside Git:
outside_git_only_the_files_on_disk_count_and_history_is_incompletecovers the no-repository case. - Unreadable history:
an_unreadable_historical_version_makes_history_incompletecovers a missing blob, andan_unlistable_evidence_directory_makes_history_incompletecovers an unlistable evidence directory.
The historical-version tests all use ordinary records. Historical versions of citation reviews and site reviews are not tested separately. They are handled by the same window loader over the evidence files, and their naming and selector semantics are covered by the tests/references.rs test, so I treat this as a minor risk and not a gap.
Inputs
Tests
Input 3: requirements selection requirements.references.coverage.reauthored
requirements.references.coverage.reauthored:md/requirements/references.md:281–290
:::{example} coverage.reauthored
Function `parse` has no reference, and the evidence of `requirements.cli.check`
read it. The requirement is re-authored and committed twice, and neither new
record reads `parse`. With the default window of 3, the record's third most
recent version still names `parse`, so `habeas status --coverage` does not warn.
After a third such commit, no version in the window names it, and
`habeas status --coverage` warns about `parse`.
{test}`requirements.references.coverage.history`
{test}`requirements.references.coverage.report`
:::
Input 4: requirements selection requirements.references.coverage.deleted_requirement
requirements.references.coverage.deleted_requirement:md/requirements/references.md:292–298
:::{example} coverage.deleted_requirement
Function `render` is read only by the evidence of `requirements.cli.render`.
The requirement and its evidence file are deleted.
Deleted files have no coverage window, so `habeas status --coverage` warns about
`render` at once, before any further commit.
{test}`requirements.references.coverage.history`
:::
Input 5: requirements selection requirements.references.coverage.uncommitted
requirements.references.coverage.uncommitted:md/requirements/references.md:307–314
:::{example} coverage.uncommitted
The evidence of `requirements.cli.check` read `parse`. The requirement is
re-authored but not yet committed, and the new record does not read `parse`.
The committed versions in the window still name it, so
`habeas status --coverage` does not warn. If the new record had read `parse`,
its contents on disk would cover it even before the commit.
{test}`requirements.references.coverage.history`
:::
Input 6: requirements selection requirements.references.coverage.shallow_clone
requirements.references.coverage.shallow_clone:md/requirements/references.md:316–321
:::{example} coverage.shallow_clone
In a shallow clone with no history beyond the last commit, each window holds
only the files' contents on disk and in that commit. `habeas status --coverage`
says that coverage history is incomplete and warns about items those contents
do not cover. {test}`requirements.references.coverage.history`
:::
Input 7: outline src/coverage_history.rs mod[tests]/fn[coverage_follows_the_outline_parent_chain_not_selector_text]
- File:
src/coverage_history.rs - Selector:
mod[tests]/fn[coverage_follows_the_outline_parent_chain_not_selector_text] - Kind:
fn src/coverage_history.rs:333–366
// {test}`requirements.references.coverage.history`
#[test]
fn coverage_follows_the_outline_parent_chain_not_selector_text() {
let source = "struct Thing;\n\nimpl Thing {\n fn x() {}\n}\n\nfn y() {}\n";
let outline =
crate::outline::parse_with(&crate::outline::RUST_PROFILE, source).expect("parses");
let index = |selector: &str| {
outline
.nodes
.iter()
.position(|node| node.selector == selector)
.expect(selector)
};
let method = enclosing_selectors(&outline, index("impl[Thing]/fn[x]"));
assert_eq!(method, ["impl[Thing]/fn[x]", "impl[Thing]", ""]);
let record = |items: &[&str]| {
let mut recent = RecentCoverage::default();
let inputs: Vec<_> = items
.iter()
.map(|item| serde_json::json!({"file": "src/lib.rs", "item": item}))
.collect();
recent.add(&serde_json::json!({ "inputs": inputs }).to_string());
recent
};
assert!(record(&["impl[Thing]"]).covers("src/lib.rs", &method));
assert!(record(&[""]).covers("src/lib.rs", &method));
assert!(!record(&["fn[y]"]).covers("src/lib.rs", &method));
assert!(!record(&["impl[Thing]"]).covers("src/other.rs", &method));
// A `/` inside brackets does not make a prefix of the selector an
// enclosing node.
let chain = ["impl[A/B]/fn[x]".to_owned(), "impl[A/B]".to_owned()];
assert!(!record(&["impl[A"]).covers("src/lib.rs", &chain));
assert!(record(&["impl[A/B]"]).covers("src/lib.rs", &chain));
}
Input 8: outline tests/authoring_batch.rs fn[dumb_terminal_keeps_plain_batch_diagnostics]
- File:
tests/authoring_batch.rs - Selector:
fn[dumb_terminal_keeps_plain_batch_diagnostics] - Kind:
fn tests/authoring_batch.rs:1032–1064
// {test}`requirements.authoring.progress`
// {test}`requirements.authoring.batch`
// {test}`requirements.references.coverage.report`
// {test}`requirements.references.coverage.history`
#[cfg(unix)]
#[test]
fn dumb_terminal_keeps_plain_batch_diagnostics() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, Some(2));
let output = fixture.run_in_pty(false, "dumb");
assert!(output.status.success(), "{output:?}");
assert_eq!(server.subjects().len(), 6);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!stderr.contains('\x1b'), "{stderr}");
assert!(
stderr.contains("Authoring 6 assessments under the once policy with concurrency 2"),
"{stderr}"
);
assert!(!stderr.contains("6/6 finished"), "{stderr}");
assert_eq!(
String::from_utf8_lossy(&output.stdout).trim(),
"6 authored; 0 skipped as current; 0 failed; policy once"
);
// A finished batch reports only the count; history details are opt-in.
assert!(
stderr.contains("nodes have coverage warnings. Use `status --coverage` to see them."),
"{stderr}"
);
assert!(
!stderr.contains("coverage history is incomplete"),
"{stderr}"
);
}
Input 9: outline tests/coverage.rs fn[coverage_lasts_for_three_reauthorings_of_the_record_that_read_an_item]
- File:
tests/coverage.rs - Selector:
fn[coverage_lasts_for_three_reauthorings_of_the_record_that_read_an_item] - Kind:
fn tests/coverage.rs:98–137
// {test}`requirements.references.coverage.reauthored`
// {test}`requirements.references.coverage.new_function`
// {test}`requirements.references.coverage.test_module`
// {test}`requirements.references.coverage.history`
// {test}`requirements.references.coverage.report`
#[test]
fn coverage_lasts_for_three_reauthorings_of_the_record_that_read_an_item() {
let temp = project();
let root = temp.path();
record(root, "rules.check", &["fn[parse]"]);
record(root, "rules.render", &["fn[render]"]);
commit(root, "first");
// `helper` was never read, and `fixture` is in `mod tests`.
assert_eq!(warned(root), ["helper"]);
for round in 1..=2 {
// Each re-authoring changes the file, so each commit counts.
fs::write(
root.join("evidence/rules.check.json"),
json!({"requirement": "x", "determination": true, "rationale": format!("round {round}"), "inputs": []})
.to_string(),
)
.unwrap();
commit(root, &format!("round {round}"));
assert_eq!(warned(root), ["helper"], "round {round}");
}
fs::write(
root.join("evidence/rules.check.json"),
json!({"requirement": "x", "determination": true, "rationale": "round 3", "inputs": []})
.to_string(),
)
.unwrap();
commit(root, "round 3");
assert_eq!(warned(root), ["parse", "helper"]);
// A warning does not fail validation.
let errors = habeas::validate_repository(root).unwrap().errors;
assert!(
!errors.iter().any(|error| error.contains("parse")),
"{errors:#?}"
);
}
Input 10: outline tests/coverage.rs fn[deleting_the_only_record_that_read_an_item_warns_at_once]
- File:
tests/coverage.rs - Selector:
fn[deleting_the_only_record_that_read_an_item_warns_at_once] - Kind:
fn tests/coverage.rs:139–156
// {test}`requirements.references.coverage.deleted_requirement`
// {test}`requirements.references.coverage.history`
#[test]
fn deleting_the_only_record_that_read_an_item_warns_at_once() {
let temp = project();
let root = temp.path();
record(root, "rules.check", &["fn[parse]", "fn[helper]"]);
record(root, "rules.render", &["fn[render]"]);
commit(root, "first");
assert!(warned(root).is_empty());
fs::write(
root.join("md/rules.md"),
":::{req} check\nChecking MUST work.\n:::\n",
)
.unwrap();
fs::remove_file(root.join("evidence/rules.render.json")).unwrap();
assert_eq!(warned(root), ["render"]);
}
Input 11: outline tests/coverage.rs fn[uncommitted_records_count_as_they_are_on_disk]
- File:
tests/coverage.rs - Selector:
fn[uncommitted_records_count_as_they_are_on_disk] - Kind:
fn tests/coverage.rs:158–173
// {test}`requirements.references.coverage.uncommitted`
// {test}`requirements.references.coverage.history`
#[test]
fn uncommitted_records_count_as_they_are_on_disk() {
let temp = project();
let root = temp.path();
record(root, "rules.check", &["fn[parse]"]);
commit(root, "first");
assert_eq!(warned(root), ["render", "helper"]);
// Re-authored but not committed: the committed version still covers it.
record(root, "rules.check", &[]);
assert_eq!(warned(root), ["render", "helper"]);
// A new record on disk covers what it reads before any commit.
record(root, "rules.render", &["fn[render]"]);
assert_eq!(warned(root), ["helper"]);
}
Input 12: outline tests/coverage.rs fn[a_shallow_clone_uses_the_history_it_has_and_says_so]
- File:
tests/coverage.rs - Selector:
fn[a_shallow_clone_uses_the_history_it_has_and_says_so] - Kind:
fn tests/coverage.rs:175–199
// {test}`requirements.references.coverage.shallow_clone`
// {test}`requirements.references.coverage.history`
#[test]
fn a_shallow_clone_uses_the_history_it_has_and_says_so() {
let temp = project();
let root = temp.path();
record(root, "rules.check", &["fn[parse]"]);
commit(root, "first");
record(root, "rules.check", &[]);
commit(root, "second");
let clone = tempfile::tempdir().unwrap();
let url = format!("file://{}", root.display());
let target = clone.path().join("shallow");
let output = Command::new("git")
.args(["clone", "--quiet", "--depth", "1", &url])
.arg(&target)
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
// Only the last commit is available, and it no longer reads `parse`.
assert!(habeas::coverage_warnings(&target).unwrap().incomplete);
assert_eq!(warned(&target), ["parse", "render", "helper"]);
// The full history still covers it.
assert_eq!(warned(root), ["render", "helper"]);
}
Input 13: outline tests/coverage.rs fn[the_window_follows_the_workspace_setting]
- File:
tests/coverage.rs - Selector:
fn[the_window_follows_the_workspace_setting] - Kind:
fn tests/coverage.rs:201–229
// {test}`requirements.references.coverage.history`
// {test}`requirements.configuration.loading`
#[test]
fn the_window_follows_the_workspace_setting() {
let temp = project();
let root = temp.path();
fs::write(
root.join("habeas.toml"),
"version = 1\n\n[coverage]\nreauthorings = 1\n",
)
.unwrap();
record(
root,
"rules.check",
&["fn[parse]", "fn[render]", "fn[helper]"],
);
commit(root, "first");
assert!(warned(root).is_empty());
record(root, "rules.check", &["fn[render]", "fn[helper]"]);
commit(root, "second");
assert_eq!(warned(root), ["parse"]);
fs::write(
root.join("habeas.toml"),
"version = 1\n\n[coverage]\nreauthorings = 0\n",
)
.unwrap();
let error = habeas::coverage_warnings(root).unwrap_err().to_string();
assert!(error.contains("coverage.reauthorings"), "{error}");
}
Input 14: outline tests/coverage.rs fn[status_shows_coverage_warnings_and_says_when_history_is_incomplete]
- File:
tests/coverage.rs - Selector:
fn[status_shows_coverage_warnings_and_says_when_history_is_incomplete] - Kind:
fn tests/coverage.rs:231–283
// {test}`requirements.references.coverage.shallow_clone`
// {test}`requirements.references.coverage.history`
// {test}`requirements.references.coverage.report`
#[test]
fn status_shows_coverage_warnings_and_says_when_history_is_incomplete() {
let temp = project();
let root = temp.path();
record(root, "rules.check", &["fn[parse]"]);
commit(root, "first");
let status = habeas::status_markdown(root, false).unwrap();
assert!(
status.contains("2 nodes have coverage warnings. Use `status --coverage` to see them."),
"{status}"
);
assert!(!status.contains("has no recent coverage"), "{status}");
assert!(!status.contains("## Coverage warnings"), "{status}");
let status = coverage_status(root);
assert!(status.contains("## Coverage warnings"), "{status}");
assert!(
status.contains("src/lib.rs:3: function render has no recent coverage"),
"{status}"
);
assert!(
!status.contains("function parse has no recent coverage"),
"{status}"
);
assert!(!status.contains("history is incomplete"), "{status}");
record(root, "rules.check", &[]);
commit(root, "second");
let clone = tempfile::tempdir().unwrap();
let target = clone.path().join("shallow");
let output = Command::new("git")
.args([
"clone",
"--quiet",
"--depth",
"1",
&format!("file://{}", root.display()),
])
.arg(&target)
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
let status = coverage_status(&target);
assert!(
status.contains("Coverage history is incomplete"),
"{status}"
);
assert!(
status.contains("function parse has no recent coverage"),
"{status}"
);
}
Input 15: outline tests/coverage.rs fn[outside_git_only_the_files_on_disk_count_and_history_is_incomplete]
- File:
tests/coverage.rs - Selector:
fn[outside_git_only_the_files_on_disk_count_and_history_is_incomplete] - Kind:
fn tests/coverage.rs:285–294
// {test}`requirements.references.coverage.history`
#[test]
fn outside_git_only_the_files_on_disk_count_and_history_is_incomplete() {
let temp = project();
let root = temp.path();
fs::remove_dir_all(root.join(".git")).unwrap();
record(root, "rules.check", &["fn[parse]"]);
assert!(habeas::coverage_warnings(root).unwrap().incomplete);
assert_eq!(warned(root), ["render", "helper"]);
}
Input 16: outline tests/coverage.rs fn[incomplete_history_is_noted_even_with_nothing_to_warn_about]
- File:
tests/coverage.rs - Selector:
fn[incomplete_history_is_noted_even_with_nothing_to_warn_about] - Kind:
fn tests/coverage.rs:347–394
// {test}`requirements.references.coverage.history`
// {test}`requirements.references.coverage.shallow_clone`
// {test}`requirements.references.coverage.report`
#[test]
fn incomplete_history_is_noted_even_with_nothing_to_warn_about() {
let temp = project();
let root = temp.path();
record(
root,
"rules.check",
&["fn[parse]", "fn[render]", "fn[helper]"],
);
commit(root, "first");
commit(root, "second");
let clone = tempfile::tempdir().unwrap();
let target = clone.path().join("shallow");
let output = Command::new("git")
.args(["clone", "--quiet", "--depth", "1"])
.arg(format!("file://{}", root.display()))
.arg(&target)
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
assert!(warned(&target).is_empty());
assert_eq!(
habeas::coverage_warnings(&target).unwrap(),
habeas::CoverageWarnings {
items: Vec::new(),
incomplete: true
}
);
let status = habeas::status_markdown(&target, false).unwrap();
assert!(
status.contains("0 nodes have coverage warnings. Use `status --coverage` to see them."),
"{status}"
);
assert!(!status.contains("history is incomplete"), "{status}");
let status = coverage_status(&target);
assert!(
status.contains("Coverage history is incomplete"),
"{status}"
);
assert!(warned(root).is_empty());
assert_eq!(
habeas::coverage_warnings(root).unwrap(),
habeas::CoverageWarnings::default()
);
}
Input 17: outline tests/coverage.rs fn[coverage_history_uses_the_git_library_without_launching_git]
- File:
tests/coverage.rs - Selector:
fn[coverage_history_uses_the_git_library_without_launching_git] - Kind:
fn tests/coverage.rs:396–454
// {test}`requirements.references.coverage.history`
#[cfg(unix)]
#[test]
fn coverage_history_uses_the_git_library_without_launching_git() {
use std::os::unix::fs::PermissionsExt;
let temp = project();
let root = temp.path();
record(root, "rules.check", &["fn[parse]"]);
commit(root, "read parse");
record(root, "rules.check", &[]);
commit(root, "stop reading parse");
assert_eq!(warned(root), ["render", "helper"]);
let tools = tempfile::tempdir().unwrap();
let tripwire = tools.path().join("git-launched");
let executable = tools.path().join("git");
// Status also asks Git to discover indexed sources. Supply those metadata
// answers, while making every command capable of reading history fail.
let index = Command::new("git")
.args(["ls-files", "--cached", "-z", "--", "."])
.current_dir(root)
.output()
.unwrap();
assert!(index.status.success());
let index_path = tools.path().join("index");
fs::write(&index_path, index.stdout).unwrap();
fs::write(
&executable,
"#!/bin/sh\ncase \"$*\" in\n 'rev-parse --is-inside-work-tree') printf 'true\\n'; exit 0;;\n 'ls-files --cached -z -- .') cat \"$HABEAS_TEST_INDEX\"; exit 0;;\n 'ls-files --others --exclude-standard -z -- .') exit 0;;\nesac\nprintf '%s\\n' \"$*\" >> \"$HABEAS_GIT_TRIPWIRE\"\nexit 97\n",
)
.unwrap();
fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)).unwrap();
let mut paths = vec![tools.path().to_path_buf()];
paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
let output = Command::new(env!("CARGO_BIN_EXE_habeas"))
.args(["status", "--coverage"])
.current_dir(root)
.env("PATH", std::env::join_paths(paths).unwrap())
.env("HABEAS_GIT_TRIPWIRE", &tripwire)
.env("HABEAS_TEST_INDEX", &index_path)
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
let status = String::from_utf8(output.stdout).unwrap();
for name in ["render", "helper"] {
assert!(
status.contains(&format!("function {name} has no recent coverage")),
"{status}"
);
}
assert!(
!status.contains("function parse has no recent coverage"),
"{status}"
);
assert!(
!tripwire.exists(),
"coverage history invoked a Git history command"
);
}
Input 18: outline tests/coverage.rs fn[validation_does_not_read_git_history]
- File:
tests/coverage.rs - Selector:
fn[validation_does_not_read_git_history] - Kind:
fn tests/coverage.rs:456–474
// {test}`requirements.references.coverage.report`
// {test}`requirements.references.coverage.history`
#[test]
fn validation_does_not_read_git_history() {
let temp = project();
let root = temp.path();
record(root, "rules.check", &["fn[parse]"]);
commit(root, "first");
let before = habeas::validate_repository(root).unwrap().errors;
// Without the object database, no committed version can be read.
for entry in fs::read_dir(root.join(".git/objects")).unwrap() {
let path = entry.unwrap().path();
if path.file_name().unwrap().len() == 2 {
fs::remove_dir_all(path).unwrap();
}
}
assert_eq!(habeas::validate_repository(root).unwrap().errors, before);
assert!(habeas::coverage_warnings(root).unwrap().incomplete);
}
Input 19: outline tests/coverage.rs fn[a_merge_counts_only_when_it_differs_from_every_parent]
- File:
tests/coverage.rs - Selector:
fn[a_merge_counts_only_when_it_differs_from_every_parent] - Kind:
fn tests/coverage.rs:503–531
// {test}`requirements.references.coverage.history`
#[test]
fn a_merge_counts_only_when_it_differs_from_every_parent() {
let temp = project();
let root = temp.path();
fs::write(
root.join("habeas.toml"),
"version = 1\n\n[coverage]\nreauthorings = 2\n",
)
.unwrap();
record(
root,
"rules.check",
&["fn[parse]", "fn[render]", "fn[helper]"],
);
commit(root, "first");
git(root, &["switch", "--quiet", "-c", "side"]);
record(root, "rules.check", &["fn[render]", "fn[helper]"]);
commit(root, "side");
git(root, &["switch", "--quiet", "-"]);
git(
root,
&["merge", "--quiet", "--no-ff", "-m", "merge", "side"],
);
// The merge takes the side branch's version unchanged, so the window of
// two holds that version and the first, which still reads `parse`.
assert!(warned(root).is_empty(), "{:?}", warned(root));
assert!(!habeas::coverage_warnings(root).unwrap().incomplete);
}
Input 20: outline tests/coverage.rs fn[an_unreadable_historical_version_makes_history_incomplete]
- File:
tests/coverage.rs - Selector:
fn[an_unreadable_historical_version_makes_history_incomplete] - Kind:
fn tests/coverage.rs:533–550
// {test}`requirements.references.coverage.history`
#[test]
fn an_unreadable_historical_version_makes_history_incomplete() {
let temp = project();
let root = temp.path();
record(root, "rules.check", &["fn[parse]"]);
commit(root, "first");
record(root, "rules.check", &[]);
commit(root, "second");
assert_eq!(warned(root), ["render", "helper"]);
assert!(!habeas::coverage_warnings(root).unwrap().incomplete);
let blob = git_output(root, &["rev-parse", "HEAD~1:evidence/rules.check.json"]);
fs::remove_file(root.join(format!(".git/objects/{}/{}", &blob[..2], &blob[2..]))).unwrap();
// The version that read `parse` cannot be read, and that is reported.
let warnings = habeas::coverage_warnings(root).unwrap();
assert!(warnings.incomplete, "{warnings:?}");
assert_eq!(warned(root), ["parse", "render", "helper"]);
}
Input 21: outline tests/coverage.rs fn[a_shallow_clone_holding_every_window_is_complete]
- File:
tests/coverage.rs - Selector:
fn[a_shallow_clone_holding_every_window_is_complete] - Kind:
fn tests/coverage.rs:552–578
// {test}`requirements.references.coverage.history`
// {test}`requirements.references.coverage.shallow_clone`
#[test]
fn a_shallow_clone_holding_every_window_is_complete() {
let temp = project();
let root = temp.path();
commit(root, "first");
record(
root,
"rules.check",
&["fn[parse]", "fn[render]", "fn[helper]"],
);
commit(root, "add the record");
commit(root, "unrelated");
// The clone reaches the commit before the record was added, so the
// record's whole history is there.
let (_clone, target) = shallow_clone(root, 3);
assert_eq!(
habeas::coverage_warnings(&target).unwrap(),
habeas::CoverageWarnings::default()
);
let status = habeas::status_markdown(&target, false).unwrap();
assert!(!status.contains("history is incomplete"), "{status}");
// A clone that stops at the commit adding it cannot tell.
let (_clone, target) = shallow_clone(root, 2);
assert!(habeas::coverage_warnings(&target).unwrap().incomplete);
}
Input 22: outline tests/coverage.rs fn[an_invalid_coverage_table_is_a_validation_finding_but_authoring_proceeds]
- File:
tests/coverage.rs - Selector:
fn[an_invalid_coverage_table_is_a_validation_finding_but_authoring_proceeds] - Kind:
fn tests/coverage.rs:598–633
// {test}`requirements.configuration.workspace_structure`
// {test}`requirements.configuration.loading`
// {test}`requirements.references.coverage.history`
#[test]
fn an_invalid_coverage_table_is_a_validation_finding_but_authoring_proceeds() {
let temp = project();
let root = temp.path();
fs::write(root.join("md/rules.md"), "# Rules\n").unwrap();
commit(root, "first");
for (table, setting) in [
("[coverage]\nreauthorings = 0\n", "coverage.reauthorings"),
("[coverage]\nreauthorings = 'x'\n", "coverage.reauthorings"),
("[coverage]\nwindow = 2\n", "coverage.window"),
] {
fs::write(root.join("habeas.toml"), format!("version = 1\n\n{table}")).unwrap();
let errors = habeas::validate_repository(root).unwrap().errors;
assert!(
errors
.iter()
.any(|error| error.contains("habeas.toml") && error.contains(setting)),
"{table}: {errors:#?}"
);
// Authoring does not use `[coverage]`.
let output = Command::new(env!("CARGO_BIN_EXE_habeas"))
.args(["author", "--all"])
.current_dir(root)
.output()
.unwrap();
assert!(output.status.success(), "{table}: {output:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("cannot compute coverage warnings"),
"{stderr}"
);
}
}
Input 23: outline tests/coverage.rs fn[a_linked_worktree_of_a_shallow_clone_knows_where_history_ends]
- File:
tests/coverage.rs - Selector:
fn[a_linked_worktree_of_a_shallow_clone_knows_where_history_ends] - Kind:
fn tests/coverage.rs:665–699
// {test}`requirements.references.coverage.history`
// {test}`requirements.references.coverage.shallow_clone`
#[test]
fn a_linked_worktree_of_a_shallow_clone_knows_where_history_ends() {
let temp = project();
let root = temp.path();
fs::write(
root.join("habeas.toml"),
"version = 1\n\n[coverage]\nreauthorings = 1\n",
)
.unwrap();
record(root, "rules.check", &["fn[parse]"]);
commit(root, "first");
record(root, "rules.check", &["fn[render]"]);
commit(root, "second");
// The one-commit clone holds the record's whole window of one version;
// so does a linked worktree of it, whose `shallow` file is in the common
// directory rather than its own.
let (clone, target) = shallow_clone(root, 1);
assert!(!habeas::coverage_warnings(&target).unwrap().incomplete);
let worktree = clone.path().join("linked");
git(
&target,
&[
"worktree",
"add",
"--quiet",
"--detach",
worktree.to_str().unwrap(),
],
);
let warnings = habeas::coverage_warnings(&worktree).unwrap();
assert!(!warnings.incomplete, "{warnings:?}");
assert_eq!(warned(&worktree), ["parse", "helper"]);
}
Input 24: outline tests/coverage.rs fn[an_uncommitted_record_does_not_make_a_full_shallow_history_incomplete]
- File:
tests/coverage.rs - Selector:
fn[an_uncommitted_record_does_not_make_a_full_shallow_history_incomplete] - Kind:
fn tests/coverage.rs:701–724
// {test}`requirements.references.coverage.history`
// {test}`requirements.references.coverage.uncommitted`
#[test]
fn an_uncommitted_record_does_not_make_a_full_shallow_history_incomplete() {
let temp = project();
let root = temp.path();
fs::write(
root.join("habeas.toml"),
"version = 1\n\n[coverage]\nreauthorings = 1\n",
)
.unwrap();
record(root, "rules.check", &["fn[parse]"]);
commit(root, "first");
record(root, "rules.check", &["fn[render]"]);
commit(root, "second");
// The one-commit clone holds the committed record's whole window.
let (_clone, target) = shallow_clone(root, 1);
assert!(!habeas::coverage_warnings(&target).unwrap().incomplete);
// A new record that was never committed has no history to miss.
record(&target, "rules.render", &["fn[helper]"]);
let warnings = habeas::coverage_warnings(&target).unwrap();
assert!(!warnings.incomplete, "{warnings:?}");
assert_eq!(warned(&target), ["parse"]);
}
Input 25: outline tests/coverage.rs fn[an_unlistable_evidence_directory_makes_history_incomplete]
- File:
tests/coverage.rs - Selector:
fn[an_unlistable_evidence_directory_makes_history_incomplete] - Kind:
fn tests/coverage.rs:726–751
// {test}`requirements.references.coverage.history`
#[cfg(unix)]
#[test]
fn an_unlistable_evidence_directory_makes_history_incomplete() {
use std::os::unix::fs::PermissionsExt;
let temp = project();
let root = temp.path();
record(
root,
"rules.check",
&["fn[parse]", "fn[render]", "fn[helper]"],
);
commit(root, "first");
assert!(!habeas::coverage_warnings(root).unwrap().incomplete);
let hidden = root.join("evidence/hidden");
fs::create_dir_all(&hidden).unwrap();
fs::set_permissions(&hidden, fs::Permissions::from_mode(0o000)).unwrap();
// Permissions do not stop a privileged user, so there is nothing to test.
let listable = fs::read_dir(&hidden).is_ok();
let warnings = (!listable).then(|| habeas::coverage_warnings(root));
fs::set_permissions(&hidden, fs::Permissions::from_mode(0o755)).unwrap();
if let Some(warnings) = warnings {
let warnings = warnings.unwrap();
assert!(warnings.incomplete, "{warnings:?}");
}
}
Input 26: outline tests/references.rs fn[items_named_by_recent_evidence_have_recent_coverage_whatever_their_hash]
- File:
tests/references.rs - Selector:
fn[items_named_by_recent_evidence_have_recent_coverage_whatever_their_hash] - Kind:
fn tests/references.rs:801–862
// {test}`requirements.references.rust_item_coverage`
// {test}`requirements.references.coverage.history`
// {test}`requirements.references.procedure`
#[test]
fn items_named_by_recent_evidence_have_recent_coverage_whatever_their_hash() {
let temp = project();
let root = temp.path();
let source = "fn read_directly() {}\n\nstruct Thing;\n\nimpl Thing {\n fn method(&self) {}\n}\n\nfn changed() {}\n\nfn unread() {}\n";
fs::write(root.join("src/lib.rs"), source).unwrap();
let input = |item: &str| habeas::outline_input(root, "src/lib.rs", item).unwrap();
let mut stale = input("fn[changed]");
stale["hash"] = json!("0".repeat(64));
// An ordinary record reads one item; a citation review reads the impl
// block containing a method; a site review records a stale hash.
fs::write(
root.join("evidence/rules.ready.json"),
json!({"inputs": [input("fn[read_directly]")]}).to_string(),
)
.unwrap();
fs::create_dir_all(root.join("evidence/citations/src/lib.rs")).unwrap();
fs::write(
root.join("evidence/citations/src/lib.rs/struct[Thing].json"),
json!({"inputs": [input("impl[Thing]"), input("struct[Thing]")]}).to_string(),
)
.unwrap();
fs::create_dir_all(root.join("evidence/sites/rules.ready/src/lib.rs")).unwrap();
fs::write(
root.join("evidence/sites/rules.ready/src/lib.rs/fn[changed].json"),
json!({"inputs": [stale]}).to_string(),
)
.unwrap();
let uncovered = |errors: &[String]| {
errors
.iter()
.filter(|error| error.contains(" has no recent coverage: "))
.map(|error| error.split(':').take(3).collect::<Vec<_>>().join(":"))
.collect::<Vec<_>>()
};
// Recent coverage names a node by file and selector, whatever hash a
// record gave it: a stale hash still covers it.
let found = errors(root);
assert_eq!(
uncovered(&found),
["src/lib.rs:11: function unread has no recent coverage"],
"{found:#?}"
);
// Editing a read item, or a method inside a read impl block, keeps it
// covered while some recent version of an evidence file names it.
fs::write(
root.join("src/lib.rs"),
source
.replace("fn read_directly() {}", "fn read_directly() { 1; }")
.replace("fn method(&self) {}", "fn method(&self) { 2; }"),
)
.unwrap();
let found = errors(root);
assert_eq!(
uncovered(&found),
["src/lib.rs:11: function unread has no recent coverage"],
"{found:#?}"
);
}
Referenced definitions
Input 2: requirements selection requirements.references.rust_item_coverage
requirements.references.rust_item_coverage:md/requirements/references.md:224–226
:::{req} rust_item_coverage
During repository validation, Habeas MUST parse every first-party Rust source file: every `.rs` file among the sources reference discovery considers under {cite}`requirements.references.discovery`, except those under the project-root `vendor` directory. Each explicitly declared function or method, including trait methods and test helpers, and each struct, enum, and union is an item that can be covered. An item is covered when it has a valid `{impl}`, `{cite}`, or `{test}` reference to a defined requirement or named example, or a valid citation of the built-in `habeas:util` under {cite}`requirements.references.util`, in a Rust comment attached to it or within its body; or when its outline node, or an outline node containing it, is recorded with its current hash as an outline input of an evidence record, a citation review, or a site review. Outline inputs recorded from selected search snippets under {cite}`requirements.authoring.finish_search.inputs` MUST count alongside mandatory inputs and additional reads. Comments belong to items under {cite}`requirements.references.outline_comments`; a comment before a field, variant, or attribute inside an item belongs to that item. A named example MUST reference a requirement under {cite}`requirements.examples.definition`. A reference in a string literal, on an enclosing module or impl block, or only in an evidence input MUST NOT count for the items it encloses. Habeas MUST report a Rust parse failure instead of silently skipping the file. Only {cite}`requirements.references.coverage.tests` and {cite}`requirements.references.coverage.examples` make an uncovered item a validation error; other items without recent coverage are warned about under {cite}`requirements.references.coverage.report`.
:::
Other sources
Input 1: requirements selection requirements.references.coverage.history
requirements.references.coverage.history:md/requirements/references.md:245–260
:::{req} coverage.history
{impl}`requirements.configuration.feature_sections`
An item has recent coverage when it has a reference that covers it under
{cite}`requirements.references.rust_item_coverage`, or when its outline node, or
an outline node containing it, is named by file and selector in the inputs of
any version of an existing evidence record, citation review, or site review in
its coverage window. A file's coverage window MUST be its current contents on
disk, committed or not, together with its contents in each of the last N
commits in its Git history that changed it, read through a Git library rather
than by running `git`. A recorded hash MUST NOT matter here: an earlier version
names the node, whatever its code was then. N MUST be the workspace
`[coverage]` setting `reauthorings`, a positive integer, and 3 when it is not
set. When the history is unavailable, such as outside Git or in a shallow clone
missing those commits, the window MUST be the commits that are available, and
`habeas status --coverage` MUST say that coverage history is incomplete.
:::
Input 27: outline tests/coverage.rs fn[commit]
- File:
tests/coverage.rs - Selector:
fn[commit] - Kind:
fn tests/coverage.rs:78–82
// {cite}`habeas:util`
fn commit(root: &Path, message: &str) {
git(root, &["add", "-A"]);
git(root, &["commit", "--quiet", "--allow-empty", "-m", message]);
}
Input 28: outline src/coverage_history.rs impl[RecentCoverage]/fn[add_history]
- File:
src/coverage_history.rs - Selector:
impl[RecentCoverage]/fn[add_history] - Kind:
fn src/coverage_history.rs:38–188
/// Adds the committed versions; false when some window may be short:
/// the history is unavailable or unreadable, or a shallow clone ends
/// before a file's window is full and before the commit that added it.
fn add_history(&mut self, root: &Path, evidence_files: &[PathBuf], depth: usize) -> bool {
let Ok(repository) = git2::Repository::discover(root) else {
return false;
};
let Some(workdir) = repository
.workdir()
.and_then(|dir| fs::canonicalize(dir).ok())
else {
return false;
};
// Each file's path in the tree and the versions found so far.
let mut pending: Vec<(PathBuf, usize)> = evidence_files
.iter()
.filter_map(|file| {
let file = fs::canonicalize(file).ok()?;
Some((file.strip_prefix(&workdir).ok()?.to_owned(), 0))
})
.collect();
if pending.is_empty() || depth == 0 {
return true;
}
let head = match repository.head() {
Ok(head) => head,
// No commits yet: every window is the file on disk alone.
Err(error) if error.code() == git2::ErrorCode::UnbornBranch => return true,
Err(_) => return false,
};
let (Some(head_id), Ok(head_tree)) = (head.target(), head.peel_to_tree()) else {
return false;
};
let mut complete = true;
// A file absent from HEAD has never been committed on this branch: no
// earlier commit holds it either, so its window is its contents on
// disk alone and the walk need not look for it.
pending.retain(|(path, _)| blob_id(&head_tree, path, &mut complete).is_some());
if pending.is_empty() {
return complete;
}
// Every evidence file lies under this directory, so a commit whose
// directory matches each parent's changes none of them.
let evidence = fs::canonicalize(root.join("evidence"))
.ok()
.and_then(|dir| Some(dir.strip_prefix(&workdir).ok()?.to_owned()))
.filter(|dir| pending.iter().all(|(path, _)| path.starts_with(dir)));
// A linked worktree shares the main repository's objects and shallow
// boundary, but libgit2 walks its history as if it were complete, so
// walk this worktree's HEAD in the main repository instead.
drop((head_tree, head));
let repository = if repository.is_worktree() {
match git2::Repository::open(repository.commondir()) {
Ok(main) => main,
Err(_) => return false,
}
} else {
repository
};
let Ok(mut walk) = repository.revwalk() else {
return false;
};
if walk.push(head_id).is_err()
|| walk
.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)
.is_err()
{
return false;
}
// The commits a shallow clone cut off from their parents.
let boundary = shallow_boundary(&repository);
for oid in walk {
let Some((commit, tree)) = oid.ok().and_then(|oid| {
let commit = repository.find_commit(oid).ok()?;
let tree = commit.tree().ok()?;
Some((commit, tree))
}) else {
complete = false;
continue;
};
// `None` when the parents are unknown: cut off or unreadable.
let parents = if boundary.contains(&commit.id()) {
None
} else {
let parents: Result<Vec<_>, _> = (0..commit.parent_count())
.map(|index| commit.parent(index).and_then(|parent| parent.tree()))
.collect();
if parents.is_err() {
complete = false;
}
parents.ok()
};
if let (Some(evidence), Some(parents)) = (&evidence, &parents)
&& !parents.is_empty()
&& let Ok(here) = tree.get_path(evidence).map(|entry| entry.id())
&& parents.iter().all(|parent| {
parent
.get_path(evidence)
.is_ok_and(|entry| entry.id() == here)
})
{
continue;
}
let mut done = Vec::new();
for (position, (path, count)) in pending.iter_mut().enumerate() {
let Some(id) = blob_id(&tree, path, &mut complete) else {
continue;
};
// A commit changes the file when it differs from every
// parent; a root commit changes every file it holds.
let (changed, added) = match &parents {
Some(parents) => {
let before: Vec<_> = parents
.iter()
.map(|parent| blob_id(parent, path, &mut complete))
.collect();
(
before.iter().all(|before| *before != Some(id)),
before.iter().all(Option::is_none),
)
}
// Its contents here are available, whether or not this
// commit changed it.
None => (true, false),
};
if changed {
match repository.find_blob(id) {
Ok(blob) => {
if let Ok(text) = std::str::from_utf8(blob.content()) {
*count += 1;
self.add(text);
}
}
Err(_) => complete = false,
}
}
// No earlier commit holds the file once the one that added it
// is seen.
if added || *count >= depth {
done.push(position);
}
}
for position in done.into_iter().rev() {
pending.remove(position);
}
if pending.is_empty() {
break;
}
}
complete && (pending.is_empty() || !repository.is_shallow())
}