requirements.authoring.batch
Requirements index · View definition
Requirement
habeas author --all [--config <name>] [--missing | --force] [-v|--verbose]MUST author the evidence of every current requirement and named example, together with the reviewsand
include, under
.
--allMUST be mutually exclusive with a subject name and--stdout. It MUST also delete each orphaned citation review underand each orphaned site review under
, and report each deletion; the deletion MUST NOT require model configuration or credentials. Failure to discover declarations or to read, scan, or parse project sources MUST report an error, not a successful empty batch.
Each subject MUST receive an independent assessment with its own prompt, inputs, judgment, and usage record. The command MUST report aggregate completion and each authoring error under
, and retain successful writes when another assessment fails. It MUST return a nonzero exit status if any assessment fails. False judgments MUST still be written as completed assessments; they remain failures under ordinary evidence validation. A denied mandatory input MUST abort only the affected assessment under
. Interruption MUST instead stop the whole batch: queued assessments MUST NOT start, running assessments MUST be cancelled, and an assessment whose evidence has not been written when the interruption is observed MUST NOT begin committing it. After preparing a temporary evidence file, the harness MUST check interruption again before its atomic replacement; a replacement already in progress MAY finish. Evidence already written MUST be retained, and the command MUST report the number of assessments not started as a batch failure.
The bundled Habeas skills MUST direct the supervising agent to run this command to create or refresh evidence. They MUST leave judgments, rationales, and input snapshots to the authoring harness; the supervising agent addresses findings by changing requirements, source citations, implementation, or tests.
![]()
![]()
Rationale
I found no adequacy gap in the tests for requirements.authoring.batch. Each obligation maps to a marked test that asserts its outcome.
Scope and selection
--allauthors every requirement, named example, citation review and site review. Thetests/authoring_batch.rstestsbatch_fills_evidence_preserves_current_records_and_reauthors_only_changed_inputsandbatch_authors_citation_reviews_and_preserves_current_onescover this. The first checks 6 model requests, the usage records and that validation is clean. The second checks the citation review record and 7 requests.site_reviews_are_authored_by_requirement_and_orphans_deleted_by_allcovers site reviews.- The unit tests
selection_counts_definitions_and_citation_reviews_in_one_phaseandselection_includes_site_reviews_and_sites_of_selects_only_themcover selection of citation and site-review subjects. - Refresh behavior is tested for current records, stale records and false judgments,
--force, and reporting skips as current. - The no-op runs are tested with a missing or invalid configuration.
- The relevant tests are
batch_preserves_current_false_judgments_and_reauthors_stale_ones,batch_reauthors_a_false_judgment_when_its_reference_set_changesandmissing_keeps_current_records_and_force_reassesses_every_selected_subject.
Mutual exclusion
batch_stdout_is_rejected_before_authoringchecks that--all --stdoutfails, mentions--stdout, and sends no requests.author_rejects_unknown_subjects_and_conflicting_targetschecks that--allwith a subject, and--all --stdout, are rejected with exit code 2 and “cannot be used with”.
Orphan deletion
- The unit test
orphaned_citation_and_site_reviews_are_deletedchecks that orphaned citation and site reviews are deleted, returned, and that a current review is kept. - The CLI test
site_reviews_are_authored_by_requirement_and_orphans_deleted_by_allremoves the configuration, runs--all, and checks that the orphan file is gone. It also checks that the “Deleted orphaned review …” message is reported.
Discovery and read failures
discovery_errors_fail_before_configuration_or_inferencecovers a Rust parse error and an unclosed declaration. Both fail with a nonzero exit and make no state or evidence.unreadable_reference_sources_fail_the_batch_before_inferencecovers an unreadable reference source.a_query_that_cannot_run_is_a_discovery_errorchecks that an unrunnable site query is a discovery error.- None of these is a successful empty batch.
Independent assessments and failure handling
failed_assessment_keeps_other_results_and_reports_failurechecks one rejected assessment, which gives a nonzero exit. The other 5 write evidence, 6 separate usage records are kept, and the error is reported.terminal_progress_distinguishes_judgments_from_authoring_errorsandbatch_reports_false_rationales_only_when_verbosecheck that a false judgment is written as a completed assessment. They also check aggregate counts and that the batch reports errors.
Denied mandatory input
a_denied_mandatory_input_aborts_only_its_assessmentchecks that the denied assessment sends no request, writes no evidence, and has a failed usage record withevidence_writtenfalse. Later queued assessments, run at concurrency 1, still write their evidence, and the exit status is nonzero.
Interruption
interrupted_terminal_progress_keeps_unstarted_work_incompleteruns the helperassert_interruption_stops_the_batchat concurrency 2 and 1.- That helper checks the “N assessments not started” report and a nonzero exit.
- It checks that running assessments are cancelled with
evidence_writtenfalse, and that only the one finished assessment wrote evidence. cancellation_after_staging_prevents_replacement_but_preserves_committed_evidencecovers the pre-replacement interruption check. A staged file is not swapped in when interrupted, and an already-committed record stays.
Bundled skills
bundled_skills_direct_the_agent_to_the_authoring_harnessasserts the skill text. It directs the agent tohabeas author --alland forbids writing evidence, determinations, rationales or inputs by hand.
Obligations that sit in cited requirements, such as progress, concurrency, usage storage, persistence and reporting, are context here. They have their own tests and need none for this subject.
Inputs
Tests
Input 10: outline src/authoring/batch.rs mod[tests]/fn[cancellation_after_staging_prevents_replacement_but_preserves_committed_evidence]
- File:
src/authoring/batch.rs - Selector:
mod[tests]/fn[cancellation_after_staging_prevents_replacement_but_preserves_committed_evidence] - Kind:
fn src/authoring/batch.rs:619–645
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.persistence`
#[test]
fn cancellation_after_staging_prevents_replacement_but_preserves_committed_evidence() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("record.json");
fs::write(&path, "old").unwrap();
let staged = || {
let mut file = tempfile::NamedTempFile::new_in(root.path()).unwrap();
write!(file, "new").unwrap();
file
};
let (cancel, receiver) = watch::channel(None);
let file = staged();
cancel.send(Some("cancelled")).unwrap();
assert_eq!(
persist_record(file, path.clone(), &receiver)
.unwrap_err()
.kind(),
io::ErrorKind::Interrupted
);
assert_eq!(fs::read_to_string(&path).unwrap(), "old");
cancel.send(None).unwrap();
persist_record(staged(), path.clone(), &receiver).unwrap();
cancel.send(Some("cancelled")).unwrap();
assert_eq!(fs::read_to_string(path).unwrap(), "new");
}
Input 11: outline src/authoring/batch.rs mod[tests]/fn[selection_counts_definitions_and_citation_reviews_in_one_phase]
- File:
src/authoring/batch.rs - Selector:
mod[tests]/fn[selection_counts_definitions_and_citation_reviews_in_one_phase] - Kind:
fn src/authoring/batch.rs:694–750
// {test}`requirements.authoring.progress`
// {test}`requirements.authoring.batch`
#[test]
fn selection_counts_definitions_and_citation_reviews_in_one_phase() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
fs::create_dir_all(root.join("md")).unwrap();
fs::create_dir_all(root.join("src")).unwrap();
fs::write(root.join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
fs::write(
root.join("md/requirements.md"),
":::{req} ready\nReady.\n:::\n",
)
.unwrap();
let cite = "{cite}`requirements.ready`".to_owned();
fs::write(
root.join("src/main.rs"),
format!("// {cite}\nfn one() {{}}\n// {cite}\nfn two() {{}}\n"),
)
.unwrap();
let inspection = crate::evidence::inspect_repository(root).unwrap();
let mut updates = Vec::new();
let (subjects, unchanged) =
select_subjects(root, &inspection, None, false, &mut |update| {
updates.push(update)
});
assert_eq!(unchanged, 0);
assert_eq!(
subjects
.iter()
.map(AuthoringSubject::label)
.collect::<Vec<_>>(),
[
"requirements.ready",
"citations:src/main.rs#fn[one]",
"citations:src/main.rs#fn[two]"
]
);
assert!(
updates
.iter()
.all(|update| update.stage == "selecting assessments")
);
assert_eq!(
updates
.iter()
.map(|update| (update.completed, update.total))
.collect::<Vec<_>>(),
[
(0, None),
(0, Some(3)),
(1, Some(3)),
(2, Some(3)),
(3, Some(3))
]
);
}
Input 12: outline src/authoring/batch.rs mod[tests]/fn[selection_includes_site_reviews_and_sites_of_selects_only_them]
- File:
src/authoring/batch.rs - Selector:
mod[tests]/fn[selection_includes_site_reviews_and_sites_of_selects_only_them] - Kind:
fn src/authoring/batch.rs:752–792
// {test}`requirements.authoring.batch`
// {test}`requirements.references.site_review`
#[test]
fn selection_includes_site_reviews_and_sites_of_selects_only_them() {
let temp =
crate::sites::tests::project(crate::sites::tests::RULE, crate::sites::tests::SOURCE);
let root = temp.path();
crate::sites::tests::write_review(root, "fn[check_two]", serde_json::json!({}));
let inspection = crate::evidence::inspect_repository(root).unwrap();
let labels = |subjects: Vec<AuthoringSubject>| {
subjects
.iter()
.map(AuthoringSubject::label)
.collect::<Vec<_>>()
};
let (subjects, unchanged) = select_subjects(root, &inspection, None, false, &mut |_| {});
assert_eq!(
labels(subjects),
[
"requirements.rule",
"sites:requirements.rule/src/lib.rs#fn[check_one]",
"sites:requirements.rule/src/lib.rs#mod[inner]/fn[check_three]",
]
);
assert_eq!(unchanged, 1);
let (subjects, unchanged) = select_subjects(
root,
&inspection,
Some("requirements.rule"),
false,
&mut |_| {},
);
assert_eq!(
labels(subjects),
[
"sites:requirements.rule/src/lib.rs#fn[check_one]",
"sites:requirements.rule/src/lib.rs#mod[inner]/fn[check_three]",
]
);
assert_eq!(unchanged, 1);
}
Input 13: outline src/authoring/batch.rs mod[tests]/fn[orphaned_citation_and_site_reviews_are_deleted]
- File:
src/authoring/batch.rs - Selector:
mod[tests]/fn[orphaned_citation_and_site_reviews_are_deleted] - Kind:
fn src/authoring/batch.rs:794–827
// {test}`requirements.authoring.batch`
// {test}`requirements.references.site_review`
// {test}`requirements.references.citation_review`
#[test]
fn orphaned_citation_and_site_reviews_are_deleted() {
let temp =
crate::sites::tests::project(crate::sites::tests::RULE, crate::sites::tests::SOURCE);
let root = temp.path();
crate::sites::tests::write_review(root, "fn[check_two]", serde_json::json!({}));
crate::sites::tests::write_review(root, "fn[other]", serde_json::json!({}));
fs::create_dir_all(root.join("evidence/citations/src/lib.rs")).unwrap();
fs::write(
root.join("evidence/citations/src/lib.rs/fn[gone].json"),
"{}",
)
.unwrap();
let inspection = crate::evidence::inspect_repository(root).unwrap();
assert_eq!(
delete_orphaned_reviews(root, &inspection).unwrap(),
[
"evidence/citations/src/lib.rs/fn[gone].json",
"evidence/sites/requirements.rule/src/lib.rs/fn[other].json",
]
);
assert!(
root.join("evidence/sites/requirements.rule/src/lib.rs/fn[check_two].json")
.exists()
);
assert!(
!root
.join("evidence/sites/requirements.rule/src/lib.rs/fn[other].json")
.exists()
);
}
Input 14: outline src/sites.rs mod[tests]/fn[a_query_that_cannot_run_is_a_discovery_error]
- File:
src/sites.rs - Selector:
mod[tests]/fn[a_query_that_cannot_run_is_a_discovery_error] - Kind:
fn src/sites.rs:886–912
// {test}`requirements.authoring.batch`
#[cfg(unix)]
#[test]
fn a_query_that_cannot_run_is_a_discovery_error() {
use std::os::unix::fs::PermissionsExt;
let temp = project(RULE, SOURCE);
let root = temp.path();
let unreadable = root.join("src/other.rs");
fs::write(&unreadable, "fn check_four() {}\n").unwrap();
fs::set_permissions(&unreadable, fs::Permissions::from_mode(0o000)).unwrap();
if fs::read(&unreadable).is_ok() {
// Running as root: permissions do not stop reads.
return;
}
let inspection = crate::evidence::inspect_repository(root).unwrap();
fs::set_permissions(&unreadable, fs::Permissions::from_mode(0o644)).unwrap();
// The incomplete scan aborts authoring, so no site review is taken
// for an orphan and deleted.
assert!(
inspection
.discovery_errors
.iter()
.any(|error| error.contains("cannot run") && error.contains("other.rs")),
"{:#?}",
inspection.discovery_errors
);
}
Input 15: outline tests/authoring_batch.rs fn[batch_fills_evidence_preserves_current_records_and_reauthors_only_changed_inputs]
- File:
tests/authoring_batch.rs - Selector:
fn[batch_fills_evidence_preserves_current_records_and_reauthors_only_changed_inputs] - Kind:
fn tests/authoring_batch.rs:531–686
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.concurrency`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.ci.determination`
// {test}`requirements.authoring.progress`
// {test}`requirements.configuration.loading`
// {test}`requirements.authoring.configuration`
// {test}`requirements.authoring.refresh`
// {test}`requirements.authoring.persistence`
#[test]
fn batch_fills_evidence_preserves_current_records_and_reauthors_only_changed_inputs() {
let server = Server::start(true, None);
let fixture = Fixture::new(&server.endpoint, Some(2));
let source = fixture.project.join("src/lib.rs");
fs::write(
&source,
format!(
"{}\n// {{test}}`requirements.alpha`\n#[test]\nfn alpha_requirement() {{ assert_eq!(alpha(), 1); }}\n",
fs::read_to_string(&source).unwrap().replace(
"pub fn beta()",
"// :::{fixme} requirements.beta\n// :github: example/app#123\n// Beta has no test yet.\n// :::\npub fn beta()",
)
),
)
.unwrap();
let output = fixture.run(&["author", "--all", "--config", "mock"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(server.subjects().len(), 6);
let report = habeas::validate_repository(&fixture.project).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert!(!fixture.project.join("evidence/rust").exists());
let mut beta = fixture.evidence("requirements.beta");
beta["determination"] = json!({"FIXME":["example/app#123"]});
beta["rationale"] = "The source explicitly acknowledges the missing beta test.".into();
fs::write(
fixture.project.join("evidence/requirements.beta.json"),
serde_json::to_vec_pretty(&beta).unwrap(),
)
.unwrap();
let example = fixture.evidence("requirements.alpha_case");
let gamma = fixture.evidence("requirements.gamma");
let gamma_case = fixture.evidence("requirements.gamma_case");
for (record, name) in [(&example, "alpha_case"), (&gamma_case, "gamma_case")] {
assert!(record.get("requirement").is_none(), "{record}");
assert!(
record["example"]
.as_str()
.unwrap()
.contains(name.split('_').next().unwrap()),
"{record}"
);
}
let usage = fixture.usage();
assert_eq!(usage.len(), 6);
assert!(
usage
.iter()
.all(|run| run["outcome"] == "completed" && run["evidence_written"] == true)
);
{
let requests = server.requests.0.lock().unwrap();
assert_eq!(
requests.peak, 2,
"the configured concurrency bounds in-flight requests"
);
assert!(
requests.first_pair_overlapped,
"a second assessment must start before the first model response"
);
}
fs::write(&fixture.config, "invalid TOML [").unwrap();
let no_op = fixture.run(&["author", "--all"]);
assert!(
no_op.status.success(),
"{}",
String::from_utf8_lossy(&no_op.stderr)
);
fs::remove_file(&fixture.config).unwrap();
let no_config = fixture.run(&["author", "--all"]);
assert!(
no_config.status.success(),
"{}",
String::from_utf8_lossy(&no_config.stderr)
);
#[cfg(unix)]
{
let no_op_terminal = fixture.run_in_pty(false, "xterm-256color");
assert!(
no_op_terminal.status.success(),
"{}",
String::from_utf8_lossy(&no_op_terminal.stderr)
);
assert_eq!(
String::from_utf8_lossy(&no_op_terminal.stdout).trim(),
"0 authored; 6 skipped as current; 0 failed"
);
assert!(!String::from_utf8_lossy(&no_op_terminal.stderr).contains("0/0 finished"));
}
assert_eq!(server.subjects().len(), 6);
assert_eq!(fixture.usage().len(), 6);
fs::write(&fixture.config, &fixture.config_text).unwrap();
let changed = fs::read_to_string(&source)
.unwrap()
.replace("-> u8 { 1 }", "-> u8 { 1_u8 }");
fs::write(&source, changed).unwrap();
let unread_change = fixture.run(&["author", "--all"]);
assert!(unread_change.status.success(), "{unread_change:?}");
assert_eq!(server.subjects().len(), 6);
fs::write(
&source,
fs::read_to_string(&source).unwrap().replace(
"fn alpha_requirement() { assert_eq!(alpha(), 1); }",
"fn alpha_requirement() { assert_eq!(alpha(), 1_u8); }",
),
)
.unwrap();
#[cfg(unix)]
let updated = fixture.run_in_pty(false, "xterm-256color");
#[cfg(not(unix))]
let updated = fixture.run(&["author", "--all"]);
#[cfg(unix)]
{
let escape = regex::Regex::new(r"\x1b\[[0-?]*[ -/]*[@-~]").unwrap();
let raw = String::from_utf8_lossy(&updated.stderr);
let plain = escape.replace_all(&raw, "");
assert!(plain.contains("1/1 finished"), "{plain}");
assert!(!plain.contains("6/6 finished"), "{plain}");
}
assert!(
updated.status.success(),
"{}",
String::from_utf8_lossy(&updated.stderr)
);
assert_eq!(server.subjects().len(), 7);
assert_eq!(
server.subjects().last().unwrap(),
"requirement requirements.alpha"
);
assert_eq!(fixture.usage().len(), 7);
assert_eq!(
String::from_utf8_lossy(&updated.stdout).trim(),
"1 authored; 5 skipped as current; 0 failed; policy once"
);
assert_eq!(fixture.evidence("requirements.beta"), beta);
assert_eq!(fixture.evidence("requirements.alpha_case"), example);
assert_eq!(fixture.evidence("requirements.gamma"), gamma);
assert_eq!(fixture.evidence("requirements.gamma_case"), gamma_case);
let report = habeas::validate_repository(&fixture.project).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
}
Input 16: outline tests/authoring_batch.rs fn[ollama_batches_are_serial_by_default]
- File:
tests/authoring_batch.rs - Selector:
fn[ollama_batches_are_serial_by_default] - Kind:
fn tests/authoring_batch.rs:688–702
// {test}`requirements.authoring.concurrency`
// {test}`requirements.authoring.batch`
#[test]
fn ollama_batches_are_serial_by_default() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, None);
let output = fixture.run(&["author", "--all"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(server.subjects().len(), 6);
assert_eq!(server.requests.0.lock().unwrap().peak, 1);
}
Input 17: outline tests/authoring_batch.rs fn[failed_assessment_keeps_other_results_and_reports_failure]
- File:
tests/authoring_batch.rs - Selector:
fn[failed_assessment_keeps_other_results_and_reports_failure] - Kind:
fn tests/authoring_batch.rs:804–859
// {test}`requirements.authoring.concurrency`
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.reporting`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.progress`
#[test]
fn failed_assessment_keeps_other_results_and_reports_failure() {
let server = Server::start(true, Some("requirement requirements.alpha"));
let fixture = Fixture::new(&server.endpoint, Some(2));
let output = fixture.run(&["author", "--all"]);
assert!(!output.stderr.contains(&b'\x1b'));
assert!(!output.stderr.contains(&b'\r'));
assert!(!output.status.success());
assert_eq!(server.subjects().len(), 6);
assert!(
!fixture
.project
.join("evidence/requirements.alpha.json")
.exists()
);
assert_eq!(fixture.evidence("requirements.beta")["determination"], true);
assert_eq!(
fixture.evidence("requirements.alpha_case")["determination"],
true
);
assert_eq!(
fixture.evidence("requirements.gamma")["determination"],
true
);
let usage = fixture.usage();
assert_eq!(usage.len(), 6);
assert_eq!(
usage
.iter()
.filter(|run| run["outcome"] == "failed")
.count(),
1
);
assert_eq!(
usage
.iter()
.filter(|run| run["outcome"] == "completed")
.count(),
5
);
let diagnostics = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(diagnostics.contains("requirements.alpha"), "{diagnostics}");
assert!(
diagnostics.contains("fixture model rejected"),
"{diagnostics}"
);
}
Input 18: outline tests/authoring_batch.rs fn[terminal_progress_distinguishes_judgments_from_authoring_errors]
- File:
tests/authoring_batch.rs - Selector:
fn[terminal_progress_distinguishes_judgments_from_authoring_errors] - Kind:
fn tests/authoring_batch.rs:861–953
// {test}`requirements.authoring.progress`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.reporting`
#[cfg(unix)]
#[test]
fn terminal_progress_distinguishes_judgments_from_authoring_errors() {
let server = Server::start_with(true, Behavior::MixedJudgments);
let fixture = Fixture::new(&server.endpoint, Some(2));
let output = fixture.run_in_pty(false, "xterm-256color");
assert!(!output.status.success(), "{output:?}");
assert_eq!(server.subjects().len(), 6);
let terminal = String::from_utf8_lossy(&output.stderr);
assert!(terminal.contains('\x1b'), "no terminal redraw: {terminal}");
assert!(
!regex::Regex::new(r"\x1b\[[0-9;]*m")
.unwrap()
.is_match(&terminal),
"NO_COLOR must override forced color: {terminal}"
);
let escape = regex::Regex::new(r"\x1b\[[0-?]*[ -/]*[@-~]").unwrap();
let plain = escape.replace_all(&terminal, "");
let counted_progress = regex::Regex::new(r"\b[0-9]+/[1-9][0-9]*\b").unwrap();
assert!(
plain.split(['\r', '\n']).any(|line| {
line.contains("Inspecting evidence")
&& line.contains('%')
&& counted_progress.is_match(line)
}),
"inspection must show counted progress before authoring: {plain}"
);
assert!(plain.contains("100%"), "{plain}");
assert!(plain.contains("6/6 finished"), "{plain}");
assert!(
regex::Regex::new(r"\b[1-9][0-9]* active\b")
.unwrap()
.is_match(&plain),
"{plain}"
);
assert!(
regex::Regex::new(r"\b[1-9][0-9]* queued\b")
.unwrap()
.is_match(&plain),
"{plain}"
);
let elapsed = regex::Regex::new(r"\[\d{2}:\d{2}:\d{2}\]").unwrap();
assert!(
plain
.split(['\r', '\n'])
.any(|line| line.contains("Authoring") && elapsed.is_match(line)),
"{plain}"
);
assert!(plain.contains("Finished"), "{plain}");
let final_counts = plain
.split(['\r', '\n'])
.rfind(|line| line.contains("true ") && line.contains("errors "))
.expect("final outcome counts in the terminal progress display");
assert!(
!final_counts.contains("Error:"),
"the final progress line must end before command diagnostics: {final_counts}"
);
for count in [
"true 3", "false 1", "FIXME 1", "errors 1", "0 active", "0 queued",
] {
assert!(
final_counts.contains(count),
"missing {count}: {final_counts}"
);
}
assert!(plain.contains("fixture model rejected"), "{plain}");
assert!(!plain.contains(": true (usage:"), "{plain}");
assert!(
plain.contains("requirements.alpha: false (usage:"),
"{plain}"
);
assert!(!plain.contains("Fixture judgment for"), "{plain}");
assert!(!plain.contains("Fixture false rationale"), "{plain}");
assert!(plain.contains("requirements.beta: FIXME"), "{plain}");
let stdout = String::from_utf8_lossy(&output.stdout);
assert_eq!(
stdout.trim(),
"5 authored; 0 skipped as current; 1 failed; policy once"
);
assert_eq!(
fixture.evidence("requirements.alpha")["determination"],
false
);
assert_eq!(
fixture.evidence("requirements.beta")["determination"],
json!({"FIXME": ["#123"]})
);
}
Input 19: outline tests/authoring_batch.rs fn[batch_reports_false_rationales_only_when_verbose]
- File:
tests/authoring_batch.rs - Selector:
fn[batch_reports_false_rationales_only_when_verbose] - Kind:
fn tests/authoring_batch.rs:955–1002
// {test}`requirements.authoring.reporting`
// {test}`requirements.authoring.progress`
// {test}`requirements.authoring.batch`
#[test]
fn batch_reports_false_rationales_only_when_verbose() {
for verbose in [false, true] {
let server = Server::start_with(true, Behavior::MixedJudgments);
let fixture = Fixture::new(&server.endpoint, Some(2));
let args = if verbose {
vec!["author", "--all", "--verbose"]
} else {
vec!["author", "--all"]
};
let output = fixture.run(&args);
assert!(!output.status.success(), "{output:?}");
assert_eq!(server.subjects().len(), 6);
let diagnostics = String::from_utf8_lossy(&output.stderr);
assert!(!diagnostics.contains('\x1b'), "{diagnostics}");
assert!(!diagnostics.contains(": true (usage:"), "{diagnostics}");
assert!(
diagnostics.contains("requirements.alpha: false (usage:"),
"{diagnostics}"
);
let rationale = fixture.evidence("requirements.alpha")["rationale"]
.as_str()
.unwrap()
.to_owned();
assert_eq!(diagnostics.contains(&rationale), verbose, "{diagnostics}");
assert!(
diagnostics.contains("requirements.beta: FIXME"),
"{diagnostics}"
);
assert!(
diagnostics.contains("fixture model rejected"),
"{diagnostics}"
);
assert!(!diagnostics.contains("pub fn alpha()"), "{diagnostics}");
let true_rationale = fixture.evidence("requirements.gamma")["rationale"]
.as_str()
.unwrap()
.to_owned();
assert!(!diagnostics.contains(&true_rationale), "{diagnostics}");
assert_eq!(
String::from_utf8_lossy(&output.stdout).trim(),
"5 authored; 0 skipped as current; 1 failed; policy once"
);
}
}
Input 20: 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 21: outline tests/authoring_batch.rs fn[interrupted_terminal_progress_keeps_unstarted_work_incomplete]
- File:
tests/authoring_batch.rs - Selector:
fn[interrupted_terminal_progress_keeps_unstarted_work_incomplete] - Kind:
fn tests/authoring_batch.rs:1066–1078
// {test}`requirements.authoring.progress`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.concurrency`
// {test}`requirements.references.coverage.report`
#[cfg(unix)]
#[test]
fn interrupted_terminal_progress_keeps_unstarted_work_incomplete() {
// Concurrency one is the Ollama default: only one assessment is running.
for (overlap, concurrency) in [(true, 2), (false, 1)] {
assert_interruption_stops_the_batch(overlap, concurrency);
}
}
Input 22: outline tests/authoring_batch.rs fn[a_denied_read_returns_an_error_and_its_assessment_continues]
- File:
tests/authoring_batch.rs - Selector:
fn[a_denied_read_returns_an_error_and_its_assessment_continues] - Kind:
fn tests/authoring_batch.rs:1151–1208
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.usage_storage`
#[test]
fn a_denied_read_returns_an_error_and_its_assessment_continues() {
let server = Server::start_with(
false,
Behavior::DeniedRead {
subject: "example requirements.alpha_case",
hold_other_requests: false,
},
);
let fixture = Fixture::new(&server.endpoint, Some(1));
fs::create_dir(fixture.project.join("evidence")).unwrap();
fs::write(
fixture.project.join("evidence/private.txt"),
"generated output\n",
)
.unwrap();
let output = fixture.run(&["author", "--all"]);
assert!(output.status.success(), "{output:?}");
let subjects = server.subjects();
// The denied assessment made a second request after the tool error.
assert_eq!(
subjects
.iter()
.filter(|subject| *subject == "example requirements.alpha_case")
.count(),
2,
"{subjects:?}"
);
for name in [
"requirements.alpha",
"requirements.alpha_case",
"requirements.beta",
"requirements.gamma",
] {
assert_eq!(fixture.evidence(name)["determination"], true, "{name}");
}
let usage = fixture.usage();
assert!(
usage.iter().all(|run| run["outcome"] == "completed"),
"{usage:?}"
);
let denied = usage
.iter()
.find(|run| run["subject"] == "requirements.alpha_case")
.unwrap();
assert_eq!(denied["request_count"], 2);
assert_eq!(denied["tool_failures"]["habeas"], 1);
// The denied file is not recorded.
assert!(
!fixture
.evidence("requirements.alpha_case")
.to_string()
.contains("private.txt")
);
}
Input 23: outline tests/authoring_batch.rs fn[a_denied_mandatory_input_aborts_only_its_assessment]
- File:
tests/authoring_batch.rs - Selector:
fn[a_denied_mandatory_input_aborts_only_its_assessment] - Kind:
fn tests/authoring_batch.rs:1210–1283
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.concurrency`
// {test}`requirements.authoring.read_denial.mandatory`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.usage_storage`
#[test]
fn a_denied_mandatory_input_aborts_only_its_assessment() {
let server = Server::start_with(
false,
Behavior::Judgments {
failing_subject: None,
},
);
// One at a time, so the assessments after the aborted one were queued.
let fixture = Fixture::new(&server.endpoint, Some(1));
fs::write(fixture.project.join("private.txt"), "private\n").unwrap();
fs::write(
fixture.project.join("habeas.toml"),
"version = 1\n\n[evidence]\ndisallow = [\"private.txt\"]\n",
)
.unwrap();
// The workspace disallows this anchor, a mandatory input of
// `requirements.alpha`.
let chapter = fixture.project.join("md/requirements.md");
let text = fs::read_to_string(&chapter).unwrap();
fs::write(
&chapter,
text.replacen(
":::{req} alpha\n",
":::{req} alpha\n:impl: private.txt\n",
1,
),
)
.unwrap();
let output = fixture.run(&["author", "--all"]);
assert!(!output.status.success(), "{output:?}");
let diagnostic = String::from_utf8_lossy(&output.stderr);
assert!(diagnostic.contains("private.txt"), "{diagnostic}");
assert!(diagnostic.contains("disallowed"), "{diagnostic}");
assert!(diagnostic.contains("habeas.toml rule"), "{diagnostic}");
// It made no request; the others ran and kept their evidence.
let subjects = server.subjects();
assert!(
!subjects
.iter()
.any(|subject| subject == "requirement requirements.alpha"),
"{subjects:?}"
);
assert!(
!fixture
.project
.join("evidence/requirements.alpha.json")
.exists()
);
for name in [
"requirements.alpha_case",
"requirements.beta",
"requirements.gamma",
] {
assert_eq!(fixture.evidence(name)["determination"], true, "{name}");
}
let usage = fixture.usage();
let aborted = usage
.iter()
.find(|run| run["subject"] == "requirements.alpha")
.expect("the aborted assessment has a usage record");
assert_eq!(aborted["outcome"], "failed");
assert_eq!(aborted["request_count"], 0);
assert_eq!(aborted["evidence_written"], false);
// With --stdout it emits no evidence JSON.
let single = fixture.run(&["author", "requirements.alpha", "--stdout"]);
assert!(!single.status.success(), "{single:?}");
assert!(single.stdout.is_empty(), "{single:?}");
}
Input 24: outline tests/authoring_batch.rs fn[batch_preserves_current_false_judgments_and_reauthors_stale_ones]
- File:
tests/authoring_batch.rs - Selector:
fn[batch_preserves_current_false_judgments_and_reauthors_stale_ones] - Kind:
fn tests/authoring_batch.rs:1321–1411
// {test}`requirements.authoring.batch`
// {test}`requirements.ci.determination`
// {test}`requirements.authoring.refresh`
#[test]
fn batch_preserves_current_false_judgments_and_reauthors_stale_ones() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, Some(2));
let source = fixture.project.join("src/lib.rs");
let original = fs::read_to_string(&source).unwrap();
fs::write(
&source,
format!(
"{original}\n// {{test}}`requirements.gamma`\n#[test]\nfn gamma_requirement() {{ assert_eq!(gamma(), 3); }}\n"
),
)
.unwrap();
let output = fixture.run(&["author", "--all"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(server.subjects().len(), 6);
let mark_false = |name: &str| {
let path = fixture.project.join(format!("evidence/{name}.json"));
let mut record = fixture.evidence(name);
record["determination"] = json!(false);
record["rationale"] = json!("The tests omit a boundary case.");
fs::write(&path, serde_json::to_vec_pretty(&record).unwrap()).unwrap();
fs::read(path).unwrap()
};
let alpha = mark_false("requirements.alpha");
mark_false("requirements.gamma");
let current = fixture.run(&["author", "--all"]);
assert!(
current.status.success(),
"{}",
String::from_utf8_lossy(¤t.stderr)
);
assert_eq!(server.subjects().len(), 6, "{:?}", server.subjects());
assert_eq!(
String::from_utf8_lossy(¤t.stdout).trim(),
"0 authored; 6 skipped as current; 0 failed"
);
assert_eq!(
fs::read(fixture.project.join("evidence/requirements.alpha.json")).unwrap(),
alpha
);
assert_eq!(
fixture.evidence("requirements.gamma")["determination"],
false
);
fs::write(
&source,
fs::read_to_string(&source).unwrap().replace(
"fn gamma_requirement() { assert_eq!(gamma(), 3); }",
"fn gamma_requirement() { assert_eq!(gamma(), 3_u8); }",
),
)
.unwrap();
let stale = fixture.run(&["author", "--all"]);
assert!(
stale.status.success(),
"{}",
String::from_utf8_lossy(&stale.stderr)
);
let subjects = server.subjects();
assert_eq!(subjects.len(), 7, "{subjects:?}");
assert_eq!(subjects[6], "requirement requirements.gamma");
assert_eq!(
String::from_utf8_lossy(&stale.stdout).trim(),
"1 authored; 5 skipped as current; 0 failed; policy once"
);
assert_eq!(
fixture.evidence("requirements.gamma")["determination"],
true
);
assert_eq!(
fs::read(fixture.project.join("evidence/requirements.alpha.json")).unwrap(),
alpha
);
let forced = fixture.run(&["author", "requirements.alpha", "--force"]);
assert!(forced.status.success(), "{forced:?}");
assert_eq!(server.subjects().len(), 8);
assert_eq!(
fixture.evidence("requirements.alpha")["determination"],
true
);
}
Input 25: outline tests/authoring_batch.rs fn[batch_reauthors_a_false_judgment_when_its_reference_set_changes]
- File:
tests/authoring_batch.rs - Selector:
fn[batch_reauthors_a_false_judgment_when_its_reference_set_changes] - Kind:
fn tests/authoring_batch.rs:1413–1480
/// A new test reference changes the reference set and requires its source
/// to be supplied on reassessment, even when the old assessment read no code.
// {test}`requirements.authoring.batch`
// {test}`requirements.ci.reference_set`
// {test}`requirements.authoring.refresh`
#[test]
fn batch_reauthors_a_false_judgment_when_its_reference_set_changes() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, Some(2));
let output = fixture.run(&["author", "--all"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(server.subjects().len(), 6);
for name in ["requirements.alpha", "requirements.delta"] {
assert_eq!(
fixture.evidence(name)["references"],
habeas::reference_set_digest_for(&fixture.project, name).unwrap()
);
}
let path = fixture.project.join("evidence/requirements.delta.json");
let mut record = fixture.evidence("requirements.delta");
record["determination"] = json!(false);
record["rationale"] = json!("The behavior has no {test} reference.");
fs::write(&path, serde_json::to_vec_pretty(&record).unwrap()).unwrap();
let source = fixture.project.join("src/lib.rs");
fs::write(
&source,
fs::read_to_string(&source).unwrap().replace(
"pub fn delta() -> u8 { 4 }",
"pub fn delta() -> u8 {\n // {test}`requirements.delta`\n 4\n}",
),
)
.unwrap();
let errors = habeas::validate_repository(&fixture.project)
.unwrap()
.errors;
assert_eq!(errors.len(), 3, "{errors:?}");
assert!(
errors[0].starts_with("evidence/requirements.delta.json: determination is false")
&& errors[1].starts_with("evidence/requirements.delta.json: reference set changed"),
"{errors:?}"
);
assert!(errors[2].contains("no input covers {test}"), "{errors:?}");
let stale = fixture.run(&["author", "--all"]);
assert!(
stale.status.success(),
"{}",
String::from_utf8_lossy(&stale.stderr)
);
let subjects = server.subjects();
assert_eq!(subjects.len(), 7, "{subjects:?}");
assert_eq!(subjects[6], "requirement requirements.delta");
assert_eq!(
String::from_utf8_lossy(&stale.stdout).trim(),
"1 authored; 5 skipped as current; 0 failed; policy once"
);
assert_eq!(
fixture.evidence("requirements.delta")["references"],
habeas::reference_set_digest_for(&fixture.project, "requirements.delta").unwrap()
);
let report = habeas::validate_repository(&fixture.project).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
}
Input 26: outline tests/authoring_batch.rs fn[site_reviews_are_authored_by_requirement_and_orphans_deleted_by_all]
- File:
tests/authoring_batch.rs - Selector:
fn[site_reviews_are_authored_by_requirement_and_orphans_deleted_by_all] - Kind:
fn tests/authoring_batch.rs:1482–1593
// {test}`requirements.references.site_review`
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.refresh`
#[test]
fn site_reviews_are_authored_by_requirement_and_orphans_deleted_by_all() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, None);
let chapter = fs::read_to_string(fixture.project.join("md/requirements.md")).unwrap();
fs::write(
fixture.project.join("md/requirements.md"),
format!(
"{chapter}\n:::::{{req}} spread\nEach public function MUST return a constant.\n\n::::{{sites}} public\n```yaml\nlanguage: rust\nrule: {{ kind: function_item, regex: \"^pub fn (alpha|beta)\" }}\nmatch: [\"pub fn alpha() {{}}\"]\nno_match: [\"fn alpha() {{}}\"]\n```\n::::\n:::::\n"
),
)
.unwrap();
let output = fixture.run(&["author", "sites:requirements.spread"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let mut subjects = server.subjects();
subjects.sort();
assert_eq!(subjects, ["src/lib.rs fn[alpha]", "src/lib.rs fn[beta]"]);
let review = fixture
.project
.join("evidence/sites/requirements.spread/src/lib.rs/fn[alpha].json");
let record: Value = serde_json::from_str(&fs::read_to_string(&review).unwrap()).unwrap();
assert_eq!(record["applies"], true);
assert_eq!(record["queries"], json!(["public"]));
// Current reviews are kept; an unknown requirement is an error.
let output = fixture.run(&["author", "sites:requirements.spread"]);
assert!(output.status.success());
assert_eq!(server.subjects().len(), 2);
// A single named site review that is current is kept under `--missing`,
// the default, without a model or configuration.
fs::write(&fixture.config, "not toml [").unwrap();
let site = "sites:requirements.spread/src/lib.rs#fn[alpha]";
for args in [&["author", site][..], &["author", site, "--missing"]] {
let output = fixture.run(args);
assert!(
output.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
String::from_utf8_lossy(&output.stdout).trim(),
format!("{site}: evidence is current; 1 skipped as current (use --force to reassess)")
);
}
assert_eq!(server.subjects().len(), 2, "no model was invoked");
fs::write(&fixture.config, &fixture.config_text).unwrap();
let mut before: Value = serde_json::from_slice(&fs::read(&review).unwrap()).unwrap();
before["rationale"] = json!("CURRENT_RECORD_BEFORE_FORCE");
fs::write(&review, before.to_string()).unwrap();
let output = fixture.run(&["author", site, "--force"]);
assert!(output.status.success(), "{output:?}");
assert_eq!(server.subjects().len(), 3);
assert!(review.exists());
assert_eq!(
serde_json::from_slice::<Value>(&fs::read(&review).unwrap()).unwrap()["item"],
"fn[alpha]"
);
assert!(
!fs::read_to_string(&review)
.unwrap()
.contains("CURRENT_RECORD_BEFORE_FORCE")
);
let output = fixture.run(&["author", "--all", "--force"]);
assert!(output.status.success(), "{output:?}");
assert_eq!(server.subjects().len(), 12);
assert_eq!(
server
.subjects()
.iter()
.filter(|s| *s == "src/lib.rs fn[alpha]")
.count(),
3
);
assert_eq!(
server
.subjects()
.iter()
.filter(|s| *s == "src/lib.rs fn[beta]")
.count(),
2
);
let output = fixture.run(&["author", "sites:requirements.alpha"]);
assert!(!output.status.success());
assert!(
String::from_utf8_lossy(&output.stderr).contains("no distributed requirement"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
// `--all` deletes a review whose site is gone, without configuration.
let orphan = fixture
.project
.join("evidence/sites/requirements.spread/src/lib.rs/fn[gone].json");
fs::write(&orphan, "{}").unwrap();
fs::remove_file(&fixture.config).unwrap();
let output = fixture.run(&["author", "--all"]);
assert!(!orphan.exists());
assert!(
String::from_utf8_lossy(&output.stderr).contains(
"Deleted orphaned review evidence/sites/requirements.spread/src/lib.rs/fn[gone].json"
),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(review.exists());
}
Input 27: outline tests/authoring_batch.rs fn[batch_stdout_is_rejected_before_authoring]
- File:
tests/authoring_batch.rs - Selector:
fn[batch_stdout_is_rejected_before_authoring] - Kind:
fn tests/authoring_batch.rs:1595–1605
// {test}`requirements.authoring.batch`
#[test]
fn batch_stdout_is_rejected_before_authoring() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, None);
let output = fixture.run(&["author", "--all", "--stdout"]);
assert!(!output.status.success());
assert!(String::from_utf8_lossy(&output.stderr).contains("--stdout"));
assert!(server.subjects().is_empty());
assert!(!fixture.project.join("evidence").exists());
}
Input 28: outline tests/authoring_batch.rs fn[discovery_errors_fail_before_configuration_or_inference]
- File:
tests/authoring_batch.rs - Selector:
fn[discovery_errors_fail_before_configuration_or_inference] - Kind:
fn tests/authoring_batch.rs:1607–1634
// {test}`requirements.authoring.batch`
// {test}`requirements.ci.definition_errors`
// {test}`requirements.references.rust_item_coverage`
#[test]
fn discovery_errors_fail_before_configuration_or_inference() {
for (declarations, source, location, diagnostic) in [
("", "fn broken(", "src/lib.rs", "cannot parse Rust source"),
(
":::{req} unclosed\nThis MUST be valid.\n",
"",
"md/requirements.md",
"missing a closing colon fence",
),
] {
let fixture = Fixture::new("http://127.0.0.1:9", None);
fs::write(fixture.project.join("md/requirements.md"), declarations).unwrap();
fs::write(fixture.project.join("src/lib.rs"), source).unwrap();
fs::remove_file(&fixture.config).unwrap();
let output = fixture.run(&["author", "--all"]);
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(location), "{stderr}");
assert!(stderr.contains(diagnostic), "{stderr}");
assert!(!stderr.contains("no authoring configuration"), "{stderr}");
assert!(!fixture.state.exists());
assert!(!fixture.project.join("evidence").exists());
}
}
Input 29: outline tests/authoring_batch.rs fn[unreadable_reference_sources_fail_the_batch_before_inference]
- File:
tests/authoring_batch.rs - Selector:
fn[unreadable_reference_sources_fail_the_batch_before_inference] - Kind:
fn tests/authoring_batch.rs:1636–1661
// {test}`requirements.authoring.batch`
#[cfg(unix)]
#[test]
fn unreadable_reference_sources_fail_the_batch_before_inference() {
use std::os::unix::fs::PermissionsExt;
let fixture = Fixture::new("http://127.0.0.1:9", None);
let unreadable = fixture.project.join("notes.txt");
fs::write(&unreadable, "a reference source\n").unwrap();
fs::set_permissions(&unreadable, fs::Permissions::from_mode(0o000)).unwrap();
if fs::read(&unreadable).is_ok() {
// Permission bits do not restrict this user (for example, root).
return;
}
fs::remove_file(&fixture.config).unwrap();
let output = fixture.run(&["author", "--all"]);
fs::set_permissions(&unreadable, fs::Permissions::from_mode(0o644)).unwrap();
assert!(!output.status.success(), "{output:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("notes.txt: cannot read reference source"),
"{stderr}"
);
assert!(!stderr.contains("no authoring configuration"), "{stderr}");
assert!(!fixture.state.exists());
assert!(!fixture.project.join("evidence").exists());
}
Input 30: outline tests/authoring_batch.rs fn[batch_authors_citation_reviews_and_preserves_current_ones]
- File:
tests/authoring_batch.rs - Selector:
fn[batch_authors_citation_reviews_and_preserves_current_ones] - Kind:
fn tests/authoring_batch.rs:1769–1892
// {test}`requirements.references.citation_review`
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.refresh`
// {test}`requirements.references.coverage.report`
#[test]
fn batch_authors_citation_reviews_and_preserves_current_ones() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, None);
let source = fixture.project.join("src/lib.rs");
let cite = "// {cite}`requirements.alpha`\n".to_owned();
fs::write(
&source,
format!(
"{}{cite}pub fn helper() {{}}\n",
fs::read_to_string(&source).unwrap()
),
)
.unwrap();
let output = fixture.run(&["author", "--all"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let subjects = server.subjects();
assert_eq!(subjects.len(), 7, "{subjects:?}");
assert!(
subjects.contains(&"src/lib.rs fn[helper]".to_owned()),
"{subjects:?}"
);
let review: Value = serde_json::from_slice(
&fs::read(
fixture
.project
.join("evidence/citations/src/lib.rs/fn[helper].json"),
)
.unwrap(),
)
.unwrap();
assert_eq!(
review["citations"],
json!([{"role": "cite", "name": "requirements.alpha", "commentary": ""}])
);
let report = habeas::validate_repository(&fixture.project).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
let again = fixture.run(&["author", "--all"]);
assert_eq!(
String::from_utf8_lossy(&again.stdout).trim(),
"0 authored; 7 skipped as current; 0 failed"
);
// A single named citation review that is current is kept under
// `--missing`, the default, without a model or configuration.
fs::write(&fixture.config, "not toml [").unwrap();
let citation = "citations:src/lib.rs#fn[helper]";
for args in [
&["author", citation][..],
&["author", citation, "--missing"],
] {
let output = fixture.run(args);
assert!(
output.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
String::from_utf8_lossy(&output.stdout).trim(),
format!(
"{citation}: evidence is current; 1 skipped as current (use --force to reassess)"
)
);
}
assert_eq!(server.subjects().len(), 7, "no model was invoked");
fs::write(&fixture.config, &fixture.config_text).unwrap();
let path = fixture
.project
.join("evidence/citations/src/lib.rs/fn[helper].json");
let mut before: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
before["rationale"] = json!("CURRENT_RECORD_BEFORE_FORCE");
fs::write(&path, before.to_string()).unwrap();
let output = fixture.run(&["author", citation, "--force"]);
assert!(output.status.success(), "{output:?}");
assert_eq!(server.subjects().len(), 8);
assert_eq!(
serde_json::from_slice::<Value>(&fs::read(&path).unwrap()).unwrap()["item"],
"fn[helper]"
);
assert!(
!fs::read_to_string(&path)
.unwrap()
.contains("CURRENT_RECORD_BEFORE_FORCE")
);
let output = fixture.run(&["author", "--all", "--force"]);
assert!(output.status.success(), "{output:?}");
assert_eq!(server.subjects().len(), 15);
assert_eq!(
server
.subjects()
.iter()
.filter(|s| *s == "src/lib.rs fn[helper]")
.count(),
3
);
// A citation review can also be named on its own.
let single = fixture.run(&["author", "citations:src/lib.rs#fn[helper]", "--stdout"]);
assert!(
single.status.success(),
"{}",
String::from_utf8_lossy(&single.stderr)
);
let printed: Value = serde_json::from_slice(&single.stdout).unwrap();
assert_eq!(printed["item"], "fn[helper]");
// The coverage summary stays on stderr; stdout holds only the record.
let stderr = String::from_utf8_lossy(&single.stderr);
assert!(
stderr.contains("nodes have coverage warnings. Use `status --coverage` to see them."),
"{stderr}"
);
assert!(
!stderr.contains("coverage history is incomplete"),
"{stderr}"
);
assert_eq!(server.subjects().len(), 16);
}
Input 31: outline tests/authoring_batch.rs fn[confirm_with_all_runs_a_second_assessment_for_each_batch_subject]
- File:
tests/authoring_batch.rs - Selector:
fn[confirm_with_all_runs_a_second_assessment_for_each_batch_subject] - Kind:
fn tests/authoring_batch.rs:1936–1968
// {test}`requirements.authoring.confirmation`
// {test}`requirements.authoring.batch`
#[test]
// {test}`requirements.authoring.policy`
fn confirm_with_all_runs_a_second_assessment_for_each_batch_subject() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, None);
let output = fixture.run(&["author", "--all", "--policy", "confirm"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let mut subjects = server.subjects();
subjects.sort();
assert!(!subjects.is_empty());
for pair in subjects.chunks(2) {
assert_eq!(pair.len(), 2, "{subjects:?}");
assert_eq!(pair[0], pair[1], "{subjects:?}");
}
let usage = fixture.usage();
let seconds = usage
.iter()
.filter(|run| {
run["subject"]
.as_str()
.unwrap()
.ends_with(" (second assessment)")
})
.count();
assert_eq!(seconds * 2, subjects.len(), "{usage:?}");
assert_eq!(usage.len(), subjects.len(), "{usage:?}");
}
Input 32: outline tests/authoring_batch.rs fn[missing_keeps_current_records_and_force_reassesses_every_selected_subject]
- File:
tests/authoring_batch.rs - Selector:
fn[missing_keeps_current_records_and_force_reassesses_every_selected_subject] - Kind:
fn tests/authoring_batch.rs:2019–2152
/// Under `--missing`, the default, a named subject or `--all` keeps current
/// records without a model or configuration; `--force` reassesses them, and
/// `--stdout` implies it.
// {test}`requirements.authoring.refresh`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.batch`
// {test}`requirements.references.coverage.report`
#[test]
fn missing_keeps_current_records_and_force_reassesses_every_selected_subject() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, None);
let first = fixture.run(&["author", "--all"]);
assert!(
first.status.success(),
"{}",
String::from_utf8_lossy(&first.stderr)
);
assert_eq!(server.subjects().len(), 6);
let alpha = fixture.evidence("requirements.alpha");
// Without a usable configuration, current records are still kept: no
// configuration is resolved when nothing needs assessment.
fs::write(&fixture.config, "not toml [").unwrap();
// An item nothing reads is warned about even when nothing is assessed.
fs::write(fixture.project.join("src/extra.rs"), "pub fn orphan() {}\n").unwrap();
for args in [
&["author", "requirements.alpha"][..],
&["author", "requirements.alpha", "--missing"],
&["author-evidence", "requirements.alpha_case"],
] {
let output = fixture.run(args);
assert!(
output.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
String::from_utf8_lossy(&output.stdout).trim(),
format!(
"{}: evidence is current; 1 skipped as current (use --force to reassess)",
args[1]
)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("nodes have coverage warnings. Use `status --coverage` to see them."),
"{args:?}: {stderr}"
);
assert!(
!stderr.contains("function orphan has no recent coverage"),
"{stderr}"
);
}
for args in [&["author", "--all"][..], &["author", "--all", "--missing"]] {
let output = fixture.run(args);
assert!(
output.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
String::from_utf8_lossy(&output.stdout).trim(),
"0 authored; 6 skipped as current; 0 failed"
);
}
assert_eq!(server.subjects().len(), 6, "no model was invoked");
assert_eq!(fixture.usage().len(), 6);
assert_eq!(fixture.evidence("requirements.alpha"), alpha);
// `--missing` and `--force` are mutually exclusive, and `--stdout`
// already implies `--force`.
for args in [
&["author", "requirements.alpha", "--missing", "--force"][..],
&["author", "--all", "--missing", "--force"],
&["author", "requirements.alpha", "--stdout", "--missing"],
] {
let output = fixture.run(args);
assert!(!output.status.success(), "{args:?}");
assert!(
String::from_utf8_lossy(&output.stderr).contains("cannot be used with"),
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
}
assert_eq!(server.subjects().len(), 6);
fs::write(&fixture.config, &fixture.config_text).unwrap();
let forced = fixture.run(&["author", "requirements.alpha", "--force"]);
assert!(
forced.status.success(),
"{}",
String::from_utf8_lossy(&forced.stderr)
);
assert_eq!(
server.subjects().last().unwrap(),
"requirement requirements.alpha"
);
assert_eq!(server.subjects().len(), 7);
let stdout = fixture.run(&["author", "requirements.alpha", "--stdout"]);
assert!(
stdout.status.success(),
"{}",
String::from_utf8_lossy(&stdout.stderr)
);
let printed: Value = serde_json::from_slice(&stdout.stdout).unwrap();
assert_eq!(printed["requirement"], alpha["requirement"]);
assert_eq!(server.subjects().len(), 8, "--stdout implies --force");
let all = fixture.run(&["author", "--all", "--force"]);
assert!(
all.status.success(),
"{}",
String::from_utf8_lossy(&all.stderr)
);
assert_eq!(
String::from_utf8_lossy(&all.stdout).trim(),
"6 authored; 0 skipped as current; 0 failed; policy once"
);
assert_eq!(server.subjects().len(), 14);
fs::write(
fixture.project.join("evidence/requirements.alpha.json"),
"{invalid",
)
.unwrap();
let repaired = fixture.run(&["author", "--all", "--missing"]);
assert!(repaired.status.success(), "{repaired:?}");
assert_eq!(server.subjects().len(), 15);
assert_eq!(
fixture.evidence("requirements.alpha")["determination"],
true
);
let report = habeas::validate_repository(&fixture.project).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
}
Input 33: outline tests/authoring_batch.rs fn[closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed]
- File:
tests/authoring_batch.rs - Selector:
fn[closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed] - Kind:
fn tests/authoring_batch.rs:2384–2483
// {test}`requirements.ci.fixme_closed_issue`
// {test}`requirements.cli.fixme_issues`
// {test}`requirements.authoring.github_reads`
// {test}`requirements.authoring.batch`
// {test}`requirements.ci.outcomes`
// {test}`requirements.configuration.state_location`
#[test]
fn closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed() {
let server = Server::start_with(false, Behavior::ClosedIssueIsFalse);
let github = FakeGithub::start();
let fixture = Fixture::new(&server.endpoint, None);
let source = fixture.project.join("src/lib.rs");
fs::write(
&source,
fs::read_to_string(&source).unwrap().replace(
"pub fn beta()",
"// :::{fixme} requirements.beta\n// :github: example/queue#125\n// Zero capacity is untested.\n// :::\npub fn beta()",
),
)
.unwrap();
let run = |args: &[&str]| {
let output = fixture
.command()
.env("HABEAS_GITHUB_API_URL", &github.endpoint)
.env("GITHUB_TOKEN", "TEST_GITHUB_TOKEN")
.args(args)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout).unwrap()
};
run(&["author", "--all"]);
assert!(github.headers.lock().unwrap().iter().any(|headers| {
headers
.to_ascii_lowercase()
.contains("authorization: bearer test_github_token\r\n")
}));
assert_eq!(server.subjects().len(), 6);
// The issue was open, so record the acknowledged gap as current FIXME
// evidence.
let mut beta = fixture.evidence("requirements.beta");
beta["determination"] = json!({"FIXME": ["example/queue#125"]});
fs::write(
fixture.project.join("evidence/requirements.beta.json"),
serde_json::to_vec_pretty(&beta).unwrap(),
)
.unwrap();
let cache = fixture.state.join(if cfg!(windows) {
"habeas/state/github/example+queue+125.json"
} else {
"habeas/github/example+queue+125.json"
});
assert!(
cache.exists(),
"GitHub reads are cached under the state root"
);
let status = run(&["status"]);
assert!(!status.contains("stale"), "{status}");
let reads = github.requests();
*github.state.lock().unwrap() = "closed";
// The cached open state is reused for an hour.
assert!(!run(&["status"]).contains("stale"));
assert_eq!(github.requests(), reads);
fs::remove_file(&cache).unwrap();
let status = run(&["status"]);
assert_eq!(github.requests(), reads + 1);
let row = status
.lines()
.find(|line| line.starts_with("| `requirements.beta`"))
.unwrap_or_else(|| panic!("{status}"));
assert!(row.contains("Invalid"), "{status}");
for expected in [
"evidence/requirements.beta.json: stale: issue example/queue#125, named by the acknowledging {fixme} to requirements.beta at src/lib.rs:5, is closed",
"src/lib.rs:5: {fixme} names example/queue#125, which is closed",
"src/lib.rs:9: fn beta fails: its {fixme} at line 5 names example/queue#125, which is closed",
] {
assert!(status.contains(expected), "{expected}\n{status}");
}
// Repository validation, which does not contact GitHub, still accepts it.
let report = habeas::validate_repository(&fixture.project).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert_eq!(github.requests(), reads + 1);
run(&["author", "--all"]);
let subjects = server.subjects();
assert_eq!(subjects.len(), 7, "{subjects:?}");
assert_eq!(subjects[6], "requirement requirements.beta");
let beta = fixture.evidence("requirements.beta");
assert_eq!(beta["determination"], json!(false), "{beta}");
// Issue states are supplied with inputs but never recorded.
assert!(!beta.to_string().contains("github_issues"), "{beta}");
for run in fixture.usage() {
assert!(!run.to_string().contains("github_issues"), "{run}");
}
}
Input 34: outline tests/authoring_cli.rs fn[author_rejects_unknown_subjects_and_conflicting_targets]
- File:
tests/authoring_cli.rs - Selector:
fn[author_rejects_unknown_subjects_and_conflicting_targets] - Kind:
fn tests/authoring_cli.rs:1234–1257
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.batch`
#[test]
fn author_rejects_unknown_subjects_and_conflicting_targets() {
let fixture = Fixture::new("http://127.0.0.1:1");
let output = fixture.run(&["author", "requirements.absent"]);
assert!(!output.status.success(), "{output:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("requirements.absent"), "{stderr}");
for args in [
["author", SUBJECT, "--all"],
["author", "--all", "--stdout"],
["author-evidence", SUBJECT, "--all"],
] {
let output = fixture.run(&args);
assert_eq!(output.status.code(), Some(2), "{args:?}: {output:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("cannot be used with"), "{stderr}");
}
assert_eq!(
fs::read_to_string(&fixture.evidence).unwrap(),
fixture.original
);
}
Input 35: outline tests/authoring_cli.rs fn[bundled_skills_direct_the_agent_to_the_authoring_harness]
- File:
tests/authoring_cli.rs - Selector:
fn[bundled_skills_direct_the_agent_to_the_authoring_harness] - Kind:
fn tests/authoring_cli.rs:4491–4520
// {test}`requirements.authoring.batch`
#[test]
fn bundled_skills_direct_the_agent_to_the_authoring_harness() {
// habeas-evidence is the home of the authoring workflow.
assert_phrases(
"habeas-evidence",
&[
"`habeas author --all` assesses every definition whose evidence is missing, stale, or invalid and skips current ones",
"Never write or edit evidence JSON, determinations, rationales, or inputs yourself, and never hand that to another agent",
"Fix the source, tests, references, or requirement text instead",
],
);
// The other skills run the command or defer to habeas-evidence.
assert_phrases(
"habeas-requirements",
&["Next, follow the habeas-evidence skill to author evidence and fix what it reports"],
);
assert_phrases(
"habeas-bootstrap-requirements",
&[
"Citation reviews are authored only by `habeas author --all`",
"Follow the habeas-evidence workflow for this area's definitions",
"Never write evidence yourself or ask another agent to",
],
);
assert_phrases(
"habeas",
&["Never write or edit evidence yourself, or ask another agent to"],
);
}
Referenced definitions
Input 2: requirements selection requirements.references.citation_review
requirements.references.citation_review:md/requirements/references.md:146–174
:::{req} citation_review
Every source item outside the book that carries at least one `{cite}` reference
other than a citation of `habeas:util` under {cite}`requirements.references.util`
MUST have a citation review: an assessment of that item's citations, recorded at
`evidence/citations/<file>/<selector>.json`, where `<file>` is the item's
project-relative path, `<selector>` is its outline selector with every `/` and
`%` percent-encoded, and the root node uses `_root`. The review MUST use the
prompt defined by {cite}`requirements.authoring.citation_prompt`. For citations
of project requirements and examples, the reviewer MUST assess whether the item
should be re-checked or kept in sync when the cited definition changes, and
whether the reference procedure of
{cite}`requirements.references.procedure` calls for `{impl}` or `{test}` instead.
For citations of built-ins, the reviewer MUST check the permitted reference
roles and forms and any citation-review criteria stated in the built-in's fixed
text, using the item's source and commentary. A permitted citation role alone
MUST NOT suffice when the fixed text states additional criteria. Mandatory inputs,
under {cite}`requirements.authoring.mandatory_inputs`, MUST be the item's outline
node, each cited declaration or built-in text, and the citations' commentary. The record MUST contain the item's file and selector,
its citations by role, name, and commentary, `determination`, `rationale`, and
`inputs`, with determinations under {cite}`requirements.ci.outcomes`. Validation
MUST require a current, accepted review for every such item and report stale,
missing, or orphaned reviews; a review MUST become stale when the item's hash,
a cited declaration, or its citations or their commentary change. Authoring with
`--all` MUST include citation reviews, and `habeas author citations:<file>#<selector>`
MUST author the review of the one item it names, under
{cite}`requirements.authoring.refresh`, where omitting `#<selector>`
names the file's root node. A citation in a requirement or example
declaration is reviewed as part of that definition's own assessment instead.
:::
Input 3: requirements selection requirements.references.site_review
requirements.references.site_review:md/requirements/references.md:521–559
:::{req} site_review
Every site of a distributed requirement under
{cite}`requirements.references.distributed` MUST have a site review: an
assessment of whether that site upholds the requirement, recorded at
`evidence/sites/<full-name>/<file>/<selector>.json`, where `<file>` and
`<selector>` are encoded as under
{cite}`requirements.references.citation_review`. The review MUST use the prompt
defined by {cite}`requirements.authoring.site_prompt`. Mandatory inputs, under
{cite}`requirements.authoring.mandatory_inputs`, MUST be the site's outline
node, the requirement's complete declaration, and each declaration the
requirement cites. The record MUST contain the requirement's full name, the
site's file and selector, `queries`, the sorted names of the queries with a
match at the site, `applies`, `determination`, `rationale`, and `inputs`, with
determinations under {cite}`requirements.ci.outcomes`. `applies` MUST be a
Boolean recording whether the requirement applies to the site. A site to which
the requirement does not apply MUST be judged `true`, and the rationale MUST
explain why it does not apply. `habeas info` MUST report, for each selected
distributed requirement, how many of its sites the requirement does not apply
to.
Validation MUST require a current, accepted review for every site, MUST report a
false review with its rationale, and MUST report stale, missing, or orphaned
reviews; a review is orphaned when its file and selector no longer name a site
of the requirement. A `{fixme}` naming the requirement inside a site
acknowledges a gap at that site only: it MUST be an input to that site's review
and MUST NOT contribute to the requirement's own review, coverage, or reference
set. A review MUST become stale when the site's hash, the requirement's
declaration, a cited declaration, its `queries`, or the `{fixme}` references
naming the requirement inside the site, with the words of their bodies, change.
Each site review's determination MUST be checked on its own, independently of
the requirement's evidence. Authoring with `--all` MUST include site reviews,
`habeas author sites:<full-name>` MUST author the site reviews of the named
requirement, and `habeas author sites:<full-name>/<file>#<selector>` MUST author
the review of the one site it names, under
{cite}`requirements.authoring.refresh`, where omitting `#<selector>` names the
file's root node. `habeas status` MUST report missing, stale, invalid, and false
site reviews with their requirement, file, and selector, and `habeas info` MUST
list each selected requirement's sites with their determinations.
:::
Input 4: requirements selection requirements.authoring.refresh
requirements.authoring.refresh:md/requirements/authoring.md:62–73
:::{req} refresh
Every `habeas author` form MUST accept `--missing` and `--force`, which are
mutually exclusive; `--missing` MUST be the default. Under `--missing`, the
command MUST assess only the selected subjects whose evidence is missing, stale,
or invalid, and MUST preserve every current record without invoking a model,
including accepted FIXME judgments and current false judgments; a current false
judgment is reassessed only when its subject or inputs change or `--force` is
given. Under `--force`, the command MUST assess every selected subject. `--stdout`
MUST imply `--force`, because it writes no evidence. The command MUST report the
number of selected subjects it skipped as current. When no assessment is needed,
the command MUST succeed without resolving model configuration or credentials.
:::
Input 5: requirements selection requirements.authoring.reporting
requirements.authoring.reporting:md/requirements/authoring.md:520–537
:::{req} reporting
By default, authoring MUST suppress per-subject `true` judgment lines and show
each `false` judgment's subject and outcome on stderr, on both terminals and
redirected output. Existing progress counters and completion summaries MUST remain
available; FIXME notices and authoring errors MUST remain visible. Single-subject
authoring MUST retain its subject, backend, model, evidence destination, and
usage-record metadata.
`-v` and `--verbose` MUST additionally show each false judgment's recorded Markdown
rationale on stderr; rationales MUST be omitted by default. This applies to
single-subject and batch authoring. It MUST
NOT print true rationales or append recorded
input snapshots. Reporting MUST use the completed assessment's existing result,
without additional inference. In `--stdout` mode, stdout MUST remain only the
evidence JSON; verbose rationale and other diagnostics MUST go to stderr.
Verbosity MUST NOT change persistence, validation, or exit-status rules.
{cite}`requirements.authoring.invocation` {cite}`requirements.authoring.batch`
:::
Input 6: requirements selection requirements.authoring.read_denial.mandatory
requirements.authoring.read_denial.mandatory:md/requirements/authoring.md:725–734
:::{req} read_denial.mandatory
When source-access policy denies a mandatory input, the assessment MUST abort
before any model request and report the denied path and reason to its caller;
for an untracked file, the report MUST say what {cite}`requirements.authoring.read_denial.untracked`
says. The aborted assessment MUST NOT write evidence or emit evidence JSON, and
its usage record MUST identify the failure. In a batch, other assessments MUST
continue, including queued assessments, and their successful writes MUST be
retained; the command MUST return a nonzero exit status after the batch
finishes.
:::
Input 7: requirements selection requirements.authoring.concurrency
requirements.authoring.concurrency:md/requirements/authoring.md:1744–1759
:::{req} concurrency
Each named authoring configuration MUST accept an optional positive integer
`concurrency` in its configuration table. When omitted, the maximum number of
simultaneous assessments MUST default to the number of available logical CPUs
for Bedrock and OpenAI, falling back to one when that count is unavailable, and to one for
Ollama. A configured value MUST override the default for each backend; zero
MUST be rejected as invalid configuration.
Batch authoring MUST use asynchronous tasks on a runtime with a fixed worker
thread pool. The number of assessments running at once MUST NOT exceed the
selected concurrency. Each assessment MUST retain its own model conversation and
usage record. Transient provider failures, including throttling, MUST be
retried within the affected assessment under
{cite}`requirements.authoring.provider_backoff`; every other provider error MUST
be reported through the ordinary assessment-failure path.
:::
Input 8: requirements selection requirements.authoring.usage_storage
requirements.authoring.usage_storage:md/requirements/authoring.md:2165–2179
:::{req} usage_storage
Each assessment MUST have a separate JSON usage record under
`<state-root>/authoring/usage/<run-id>.json` using
{cite}`requirements.configuration.state_location`.
It MUST identify its format version, run, project root, subject kind and full
name, start time, backend and model when known, end time when finished, outcome,
accepted determination kind (`true`, `false`, or `FIXME`) when present, and
whether evidence was written. It MUST record the selected output destination in
`evidence_output` as `file` or `stdout`; a successful write to either destination
MUST set `evidence_written` to true. Usage recording MUST remain outside the
project in stdout mode. FIXME entry text MUST NOT be stored in usage records.
Failed, cancelled, or unfinished
runs MUST remain distinguishable from completed judgments. Records MUST persist
for later review without storing source text, prompts, responses, or rationale.
:::
Input 9: requirements selection requirements.authoring.persistence
requirements.authoring.persistence:md/requirements/authoring.md:2152–2161
:::{req} persistence
After one valid judgment, the harness MUST write the subject text, submitted
determination and rationale, and recorded inputs using the existing evidence
schema. {cite}`requirements.ci.schema`
By default, it MUST write the subject's evidence file. With `--stdout`, it MUST
emit a single evidence JSON object followed by a newline to stdout and MUST NOT
create or change evidence files or directories. All three outcomes MUST be
written to the selected destination as completed assessments; their validation
status MUST follow {cite}`requirements.ci.determination`.
:::
Other sources
Input 1: requirements selection requirements.authoring.batch
requirements.authoring.batch:md/requirements/authoring.md:19–60
:::{req} batch
`habeas author --all [--config <name>] [--missing | --force] [-v|--verbose]` MUST author
the evidence of every current requirement and named example, together with the
reviews {cite}`requirements.references.citation_review` and
{cite}`requirements.references.site_review` include, under
{cite}`requirements.authoring.refresh`.
`--all` MUST be mutually exclusive with a subject name and `--stdout`. It MUST
also delete each orphaned citation review under
{cite}`requirements.references.citation_review` and each orphaned site review
under {cite}`requirements.references.site_review`, and report each deletion; the
deletion MUST NOT require model configuration or credentials.
Failure to discover declarations or to read, scan, or parse project sources MUST report an error,
not a successful empty batch.
Each subject MUST receive an independent assessment with its own prompt, inputs,
judgment, and usage record. The command MUST report aggregate completion and each
authoring error under {cite}`requirements.authoring.reporting`, and retain
successful writes when another assessment fails. It MUST return a nonzero
exit status if any assessment fails. False judgments MUST still be written as
completed assessments; they remain failures under ordinary evidence validation.
A denied mandatory input MUST abort only the affected assessment under
{cite}`requirements.authoring.read_denial.mandatory`. Interruption MUST instead stop the
whole batch: queued assessments MUST NOT start, running assessments MUST be
cancelled, and an assessment whose evidence has not been written when the
interruption is observed MUST NOT begin committing it. After preparing a
temporary evidence file, the harness MUST check interruption again before its
atomic replacement; a replacement already in progress MAY finish. Evidence already written MUST be
retained, and the command MUST report the number of assessments not started as
a batch failure.
The bundled Habeas skills MUST direct the supervising agent to run this command
to create or refresh evidence. They MUST leave judgments, rationales, and input
snapshots to the authoring harness; the supervising agent addresses findings by
changing requirements, source citations, implementation, or tests.
{cite}`requirements.authoring.concurrency`
{cite}`requirements.authoring.usage_storage`
{cite}`requirements.authoring.persistence`
:::
Input 36: outline tests/authoring_batch.rs fn[assert_interruption_stops_the_batch]
- File:
tests/authoring_batch.rs - Selector:
fn[assert_interruption_stops_the_batch] - Kind:
fn tests/authoring_batch.rs:1080–1149
// {cite}`habeas:util`
#[cfg(unix)]
fn assert_interruption_stops_the_batch(overlap: bool, concurrency: usize) {
let server = Server::start_with(overlap, Behavior::WaitAfterFirst);
let fixture = Fixture::new(&server.endpoint, Some(concurrency));
let output = fixture.run_in_pty(true, "xterm-256color");
assert!(!output.status.success(), "{output:?}");
let terminal = String::from_utf8_lossy(&output.stderr);
let escape = regex::Regex::new(r"\x1b\[[0-?]*[ -/]*[@-~]").unwrap();
let plain = escape.replace_all(&terminal, "");
assert!(plain.contains("Stopped"), "{plain}");
assert!(plain.contains("assessments not started"), "{plain}");
let started = concurrency + 1;
let remaining = 6 - started;
assert!(
plain.contains(&format!("{remaining} assessments not started")),
"{plain}"
);
// A cancelled batch does not compute coverage warnings.
assert!(!plain.contains("coverage history"), "{plain}");
let stopped = &plain[plain.rfind("Stopped").unwrap()..];
assert!(!stopped.contains("100%"), "{stopped}");
assert!(!stopped.contains("6/6 finished"), "{stopped}");
assert!(String::from_utf8_lossy(&output.stdout).contains("1 authored;"));
// A launched assessment may be cancelled before its HTTP request arrives.
let received = server.subjects().len();
assert!(
(concurrency..=started).contains(&received),
"{received} requests for {started} launched assessments"
);
let usage = fixture.usage();
assert_eq!(usage.len(), started);
assert_eq!(
usage
.iter()
.filter(|run| run["evidence_written"] == true)
.count(),
1
);
// The assessment running at the interruption is cancelled without writing.
assert!(
usage
.iter()
.any(|run| run["outcome"] == "cancelled" && run["evidence_written"] == false),
"{usage:?}"
);
assert_eq!(
usage
.iter()
.filter(|run| run["outcome"] == "cancelled" && run["evidence_written"] == false)
.count(),
concurrency,
"{usage:?}"
);
let screen = final_screen(&output.stderr);
for expected in [
"Stopped".to_owned(),
format!("{started}/6 finished"),
format!("errors {concurrency}"),
"0 active".to_owned(),
format!("{remaining} queued"),
] {
assert!(screen.contains(&expected), "missing {expected}: {screen}");
}
assert!(!screen.contains("100%"), "{screen}");
let written = fs::read_dir(fixture.project.join("evidence"))
.unwrap()
.count();
assert_eq!(written, 1, "only the finished assessment wrote evidence");
}