requirements.authoring.deterministic_validation
Requirements index · View definition
Requirement
Ordinary evidence validation, status inspection, and book rendering MUST continue to check evidence using the existing rules without invoking models, contacting providers, or requiring authoring configuration or credentials. Missing or stale evidence MUST remain a validation failure rather than trigger authoring.
Rationale
I found no gaps. I did not exhaustively trace habeas::preprocess_book or status_markdown_with_github; I relied on the tests that exercise them end to end and on a search of src for calls into the authoring module.
Obligations
- Ordinary validation, status and book rendering keep checking evidence with the existing rules.
- They do not invoke models.
- They do not contact providers.
- They do not require authoring configuration or credentials.
- Missing or stale evidence stays a validation failure rather than triggering authoring.
Implementation
src/evidence.rs#fn[inspect_repository_with_progress]is the shared inspection path. It collects missing evidence asevidence/{name}.json: missing for ...errors and its comment says it never starts authoring. It calls no model, provider or authoring-configuration code.- Its only authoring-module use is
DiscoverySources(viadiscovered_files,validate_committed_credentialsanduntracked_reference_files). That type is marked{impl}on this requirement and loads only the Git index and the workspace[evidence]rules. An invalid workspace file falls back toPathPolicy::default(), so it needs no authoring configuration. Seesrc/authoring/access.rs#struct[DiscoverySources]andimpl[DiscoverySources]/fn[load]. src/config.rs#fn[load_workspace_evidence]decodes only the[evidence]table. It reads[authoring]only to record whether credentials appear in it, and it does not validate that section.src/main.rs#fn[main]does the same for every command exceptauthor: it loads only the evidence settings, so status and book rendering never need authoring configuration or credentials.statusandinfoskip that early load and report an invalid workspace file as a finding instead.- The only authoring-module calls I found in
src/main.rsare for the authoring commands.
Tests
tests/authoring_cli.rs#fn[missing_or_stale_evidence_fails_validation_without_contacting_the_provider]covers obligation 5 and the no-provider obligations.validate_repositorymust report “missing for requirement” or “changed” for the subject, and this is run with the full authoring configuration and with a bareversion = 1configuration.status --allandmdbookrendering succeed with the model key removed from the environment.- A listening socket sees no connection, no usage state is written, and the evidence file is unchanged.
tests/authoring_cli.rs#fn[ordinary_status_ignores_invalid_user_authoring_configuration]shows status works with an unparsable user authoring configuration, writes no state and does not modify evidence.tests/evidence_boundaries.rs#fn[validation_checks_workspace_common_config_without_loading_unused_authoring_settings]shows validation ignores unused or invalid workspace[authoring]settings while still checking the common workspace configuration.tests/commands.rs#fn[status_loads_nearest_workspace_file_without_validating_authoring]andfn[status_applies_workspace_disallow_to_existing_evidence]cover the existing evidence rules still applying under status.tests/authoring_cli.rs#impl[Fixture]/fn[run]carries a{test}reference as a helper.
Inputs
Implementation
Input 2: outline src/authoring/access.rs struct[DiscoverySources]
- File:
src/authoring/access.rs - Selector:
struct[DiscoverySources] - Kind:
struct src/authoring/access.rs:227–235
/// The project files reference discovery and Rust item coverage consider: the
/// sources [`SourceAccess`] would let authoring read by default, found without
/// authoring configuration or Cargo metadata.
// {impl}`requirements.authoring.deterministic_validation`
pub(crate) struct DiscoverySources {
root: PathBuf,
tracked: Option<BTreeSet<PathBuf>>,
policy: PathPolicy,
}
Input 3: outline src/authoring/access.rs impl[DiscoverySources]/fn[load]
- File:
src/authoring/access.rs - Selector:
impl[DiscoverySources]/fn[load] - Kind:
fn src/authoring/access.rs:238–248
/// Loads the Git index and the workspace `[evidence]` rules. An invalid
/// workspace configuration is reported by inspection itself, so discovery
/// then applies no workspace rules rather than failing a second time.
// {impl}`requirements.authoring.deterministic_validation`
pub(crate) fn load(root: &Path) -> io::Result<Self> {
Ok(Self {
root: root.to_owned(),
tracked: tracked_sources(root)?,
policy: PathPolicy::load(root).unwrap_or_default(),
})
}
Input 4: outline src/config.rs fn[load_workspace_evidence]
- File:
src/config.rs - Selector:
fn[load_workspace_evidence] - Kind:
fn src/config.rs:917–951
// {impl}`requirements.configuration.workspace_location`
// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.evidence_paths`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.authoring.deterministic_validation`
// {impl}`requirements.configuration.feature_sections`
pub fn load_workspace_evidence(root: &Path) -> io::Result<Option<WorkspaceEvidenceConfig>> {
let Some((path, table)) = workspace_document(root)? else {
return Ok(None);
};
let evidence: EvidenceConfig = table
.get("evidence")
.map(|value| decode(value.clone(), &path, "evidence"))
.transpose()?
.unwrap_or_default();
evidence.validate(&path)?;
let contains_credentials = table
.get("authoring")
.and_then(|value| value.get("configs"))
.and_then(toml::Value::as_table)
.is_some_and(|configs| {
configs.values().any(|config| {
config.get("credentials").is_some() || config.get("api_key").is_some()
})
});
Ok(Some(WorkspaceEvidenceConfig {
root: path
.parent()
.expect("configuration has a parent")
.to_owned(),
path,
evidence,
contains_credentials,
}))
}
Input 5: 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 6: outline src/main.rs fn[main]/use@118842506675
- File:
src/main.rs - Selector:
fn[main]/use@118842506675 - Kind:
use src/main.rs:133–235
// {impl}`requirements.cli.clap`
let cli = Cli::parse();
// {impl}`requirements.configuration.workspace_location`
// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.loading`
// Commands other than `author` load only the evidence settings, so status
// and book rendering never need authoring configuration or credentials.
// {impl}`requirements.authoring.deterministic_validation`
// Only commands that resolve evidence inputs use the workspace evidence
// path policy; setup, the session-start hook, and support queries do not.
// `status` and `info` render the validation report, which records an
// invalid workspace file as one finding and still runs the other checks,
// so they must not stop here.
// {impl}`requirements.ci.errors`
if !matches!(
cli.command,
Command::Mdbook {
command: Some(MdbookCommand::Supports { .. })
} | Command::Setup { .. }
| Command::Coverage { .. }
| Command::CoverageCheck
| Command::Test
| Command::CoverageProcess { .. }
| Command::Hook { .. }
| Command::Status { .. }
| Command::Info { .. }
) {
habeas::config::load_workspace_evidence(&std::env::current_dir()?)?;
}
match cli.command {
Command::Coverage { args } => {
std::process::exit(habeas::execution_coverage::run(
&setup::project_root()?,
&args,
)?);
}
// {impl}`requirements.test-coverage.check`
Command::CoverageCheck => {
let report = habeas::execution_coverage::check(&setup::project_root()?)?;
print!("{}", report.text);
std::process::exit(i32::from(!report.passed));
}
// {impl}`requirements.test-coverage.test`
Command::Test => {
std::process::exit(habeas::execution_coverage::test(&setup::project_root()?)?);
}
Command::CoverageProcess { args } => {
std::process::exit(habeas::execution_coverage::collect_process(&args)?);
}
// {impl}`requirements.cli.mdbook`
Command::Mdbook { command: None } => {
let (context, mut book) = mdbook_preprocessor::parse_input(io::stdin())?;
habeas::preprocess_book(&mut book, &context.root)?;
serde_json::to_writer(io::stdout().lock(), &book)?;
Ok(())
}
// {impl}`requirements.cli.invocation`
Command::Mdbook {
command: Some(MdbookCommand::Supports { renderer }),
} => {
if renderer == "html" {
Ok(())
} else {
std::process::exit(1)
}
}
// {impl}`requirements.cli.setup`
// {impl}`requirements.cli.setup_local_path`
Command::Setup { path } => setup::run(path.as_deref()),
// {impl}`requirements.cli.status`
// {impl}`requirements.cli.fixme_summary`
// {impl}`requirements.cli.fixme_issues`
Command::Status {
all,
selection,
verbose,
coverage,
} => {
let root = setup::project_root()?;
io::stdout().lock().write_all(
habeas::status_markdown_with_coverage(
&root,
all,
selection.as_deref(),
verbose,
coverage,
&habeas::GithubIssues::from_env(&root),
)?
.as_bytes(),
)?;
Ok(())
}
// {impl}`requirements.refactor.command`
// {impl}`requirements.refactor.invalid_mappings`
Command::Refactor { mappings, dry_run } => {
let root = setup::project_root()?;
match habeas::refactor(&root, &mappings, dry_run) {
Ok(report) => {
io::stdout().lock().write_all(report.as_bytes())?;
Ok(())
}
Err(habeas::RefactorError::Usage(message)) => {
use clap::CommandFactory;
Tests
Input 7: outline tests/authoring_cli.rs impl[Fixture]/fn[run]
- File:
tests/authoring_cli.rs - Selector:
impl[Fixture]/fn[run] - Kind:
fn tests/authoring_cli.rs:241–245
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.deterministic_validation`
fn run(&self, args: &[&str]) -> Output {
self.command().args(args).output().unwrap()
}
Input 8: outline tests/authoring_cli.rs fn[ordinary_status_ignores_invalid_user_authoring_configuration]
- File:
tests/authoring_cli.rs - Selector:
fn[ordinary_status_ignores_invalid_user_authoring_configuration] - Kind:
fn tests/authoring_cli.rs:1622–1644
// {test}`requirements.authoring.deterministic_validation`
// {test}`requirements.configuration.loading`
#[test]
fn ordinary_status_ignores_invalid_user_authoring_configuration() {
let fixture = Fixture::new("http://127.0.0.1:1");
fs::write(
fixture.config.join("habeas/config.toml"),
"this is not TOML [",
)
.unwrap();
let output = fixture.run(&["status", SUBJECT, "--all"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(String::from_utf8_lossy(&output.stdout).contains(SUBJECT));
assert!(!fixture.state.exists());
assert_eq!(
fs::read_to_string(&fixture.evidence).unwrap(),
fixture.original
);
}
Input 9: outline tests/authoring_cli.rs fn[missing_or_stale_evidence_fails_validation_without_contacting_the_provider]
- File:
tests/authoring_cli.rs - Selector:
fn[missing_or_stale_evidence_fails_validation_without_contacting_the_provider] - Kind:
fn tests/authoring_cli.rs:1646–1725
// {test}`requirements.authoring.deterministic_validation`
// {test}`requirements.authoring.configuration`
#[test]
fn missing_or_stale_evidence_fails_validation_without_contacting_the_provider() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
listener.set_nonblocking(true).unwrap();
let fixture = Fixture::new(&format!("http://{}", listener.local_addr().unwrap()));
let changed = format!(":::{{req}} ready\n{REQUIREMENT} Changed.\n:::\n");
let config_path = fixture.config.join("habeas/config.toml");
let configured = fs::read_to_string(&config_path).unwrap();
for config in [&configured[..], "version = 1\n"] {
fs::write(&config_path, config).unwrap();
for (case, expected) in [("missing", "missing for requirement"), ("stale", "changed")] {
if case == "missing" {
fs::remove_file(&fixture.evidence).unwrap();
} else {
fs::write(&fixture.evidence, &fixture.original).unwrap();
fs::write(fixture.project.join("md/requirements.md"), &changed).unwrap();
}
let report = habeas::validate_repository(&fixture.project).unwrap();
assert!(
report
.errors
.iter()
.any(|error| error.contains(SUBJECT) && error.contains(expected)),
"{case}: {:?}",
report.errors
);
// Status and book rendering need no authoring credentials.
let status = fixture
.command()
.env_remove("HABEAS_TEST_MODEL_KEY")
.args(["status", "--all"])
.output()
.unwrap();
assert!(status.status.success(), "{case}: {status:?}");
assert!(
String::from_utf8_lossy(&status.stdout).contains(SUBJECT),
"{case}: {status:?}"
);
let mut book = mdbook_preprocessor::book::Book::new();
book.push_item(mdbook_preprocessor::book::Chapter::new(
"Requirements",
fs::read_to_string(fixture.project.join("md/requirements.md")).unwrap(),
"requirements.md",
Vec::new(),
));
let context = mdbook_preprocessor::PreprocessorContext::new(
fixture.project.clone(),
mdbook_preprocessor::config::Config::default(),
"html".to_owned(),
);
let mut render = fixture
.command()
.env_remove("HABEAS_TEST_MODEL_KEY")
.arg("mdbook")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
serde_json::to_writer(render.stdin.take().unwrap(), &(&context, &book)).unwrap();
let rendered = render.wait_with_output().unwrap();
assert!(rendered.status.success(), "{case}: {rendered:?}");
let rendered: Value = serde_json::from_slice(&rendered.stdout).unwrap();
assert!(rendered.to_string().contains(SUBJECT), "{case}");
}
}
assert!(
matches!(listener.accept(), Err(error) if error.kind() == std::io::ErrorKind::WouldBlock),
"validation, status, or rendering contacted the provider"
);
assert!(!fixture.state.exists(), "no authoring usage was recorded");
assert_eq!(
fs::read_to_string(&fixture.evidence).unwrap(),
fixture.original,
"validation did not author evidence"
);
}
Input 10: 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 11: outline tests/commands.rs fn[status_applies_workspace_disallow_to_existing_evidence]
- File:
tests/commands.rs - Selector:
fn[status_applies_workspace_disallow_to_existing_evidence] - Kind:
fn tests/commands.rs:271–291
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.ci.input_containment`
// {test}`requirements.cli.status`
// {test}`requirements.authoring.deterministic_validation`
#[test]
fn status_applies_workspace_disallow_to_existing_evidence() {
let temp = fixture();
fs::write(
temp.path().join("habeas.toml"),
"version = 1\n[evidence]\nallow = ['src']\ndisallow = ['src/main.rs']\n",
)
.unwrap();
let output = habeas(temp.path(), &["status", "requirements.ready"]);
assert!(output.status.success(), "{output:?}");
let text = String::from_utf8(output.stdout).unwrap();
assert!(
text.contains("Invalid") && text.contains("disallowed"),
"{text}"
);
assert!(text.contains("src/main.rs"), "{text}");
}
Input 12: outline tests/evidence_boundaries.rs fn[validation_checks_workspace_common_config_without_loading_unused_authoring_settings]
- File:
tests/evidence_boundaries.rs - Selector:
fn[validation_checks_workspace_common_config_without_loading_unused_authoring_settings] - Kind:
fn tests/evidence_boundaries.rs:508–533
// {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]
fn validation_checks_workspace_common_config_without_loading_unused_authoring_settings() {
let temp = fixture();
let root = temp.path().join("project");
for text in [
"version = 2\n",
"version = 1\nunknown = true\n",
"version = [\n",
] {
fs::write(root.join("habeas.toml"), text).unwrap();
let errors = validate_repository(&root).unwrap().errors.join("\n");
assert!(errors.contains("habeas.toml"), "{text:?}: {errors}");
}
fs::write(
root.join("habeas.toml"),
"version = 1\n[authoring]\nconfigs = 'invalid unused authoring settings'\n",
)
.unwrap();
let report = validate_repository(&root).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
}
Other sources
Input 1: requirements selection requirements.authoring.deterministic_validation
requirements.authoring.deterministic_validation:md/requirements/authoring.md:2209–2214
:::{req} deterministic_validation
Ordinary evidence validation, status inspection, and book rendering MUST continue
to check evidence using the existing rules without invoking models, contacting
providers, or requiring authoring configuration or credentials. Missing or stale
evidence MUST remain a validation failure rather than trigger authoring.
:::