requirements.authoring.usage_storage
Requirements index · View definition
Requirement
Each assessment MUST have a separate JSON usage record under
<state-root>/authoring/usage/<run-id>.jsonusing. 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, orFIXME) when present, and whether evidence was written. It MUST record the selected output destination inevidence_outputasfileorstdout; a successful write to either destination MUST setevidence_writtento 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.
Rationale
I judge the marked tests adequate for requirements.authoring.usage_storage. I did not request any implementation source. Each obligation maps to tests and assertions as follows.
- Location and one record per run.
tests/authoring_cli.rs#fn[usage_record_identifies_its_run_and_unusable_state_is_reported]reads<state>/habeas/authoring/usage/. It asserts the file is named<run_id>.jsonand that a second--forcerun adds a second file. The first file stays byte-identical.src/authoring/mod.rs#mod[tests]/fn[citation_reviews_are_confirmed_with_fresh_targeted_conversations]andtests/authoring_batch.rs#fn[confirm_runs_a_second_assessment_with_its_own_usage_record]check that separate assessments get separate records with distinctrun_idvalues and subjects.- The batch tests check one record per assessment (6 for 6 subjects).
- Fields.
usage_record_identifies_its_run_and_unusable_state_is_reportedasserts these fields:version(1),run_id,project_root(the canonical path),subject,subject_kind,backendandmodel.evidence_output,start_time_msandend_time_ms, with start no later than end.authoring_uses_nearest_workspace_configuration_without_a_user_filechecksmodelfrom a workspace configuration.usage_subject_kind_is_known_before_sources_are_preparedandusage_record_of_an_early_failure_identifies_its_subject_kindchecksubject_kindfor all four kinds and for an early failure.
- Outcome and determination kind.
false_is_a_completed_assessmentassertsdeterminationis"false".stdout_emits_only_evidence_json_without_changing_project_filesassertstrue,falseandFIXMEacross its cases.ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_freeassertsFIXME.missing_duplicate_and_invalid_submissions_preserve_existing_evidenceasserts the determination is null when the submission was not accepted.
evidence_outputandevidence_written.stdout_emits_only_evidence_json_without_changing_project_filesassertsevidence_output == "stdout"andevidence_written == true.missing_duplicate_and_invalid_submissions_preserve_existing_evidencecovers both destinations withevidence_written == falseon failure.failed_evidence_write_keeps_the_accepted_judgment_in_usagechecks that a failed write leaves the determination kind butevidence_written == false.- The batch tests assert
evidence_written == truefor completed file-mode runs. live_bedrock_authoringalso asserts the stdout case.
- Outside the project in stdout mode.
usage_state_inside_the_project_is_refused_before_creating_itruns both default and--stdout. It points the state home inside the project and asserts a refusal, empty stdout, and that the directory is never created. - No FIXME entry text.
ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_freeasserts the serialized usage lacks#125, and the determination there isFIXME. - Failed, cancelled and unfinished are distinguishable.
cancelled_request_persists_elapsed_time_and_incomplete_totalschecks the initialunfinishedoutcome with a null end time, thencancelledwith an end time.failed_persistence_records_failure_or_cancellation_and_retains_the_causechecksfailedversuscancelled,evidence_written == false, and a null determination.a_denied_mandatory_input_aborts_only_its_assessmentandfailed_assessment_keeps_other_results_and_reports_failurecheckfailedrecords alongsidecompletedones.
- No source text, prompts, responses or rationale. These tests assert absence of private strings in the serialized record:
input_metadata_counts_components_and_reads_without_persisting_source(source, requirement, definition and builtin text, file names and item names).tool_outcomes_are_distinct_and_unknown_names_do_not_leak_model_text.ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free(requirement, definition, source and rationale text, and the credential).authoring_uses_nearest_workspace_configuration_without_a_user_file(the credential).
- Cited
requirements.configuration.state_location. The tests cover applying it to this feature. They check the XDG state home layout, persistence across invocations, and reporting a failure (non-zero exit, stderr message, no stdout) when the location cannot be created or determined. They also check that failed runs leave the existing evidence intact. The WindowsLOCALAPPDATAbranch is only exercised as a refused in-project path. That is part of the cited requirement, whose own tests are not reassessed here.
I found no obligation of the subject without a test that asserts its outcome.
Inputs
Tests
Input 3: outline src/authoring/mod.rs mod[tests]/fn[failed_persistence_records_failure_or_cancellation_and_retains_the_cause]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/fn[failed_persistence_records_failure_or_cancellation_and_retains_the_cause] - Kind:
fn src/authoring/mod.rs:1681–1743
// {test}`requirements.authoring.usage_storage`
#[test]
fn failed_persistence_records_failure_or_cancellation_and_retains_the_cause() {
let project = inputs::tests::project();
let state = tempfile::tempdir().unwrap();
for (kind, expected, block_usage) in [
(io::ErrorKind::PermissionDenied, "failed", false),
(io::ErrorKind::Interrupted, "cancelled", false),
(io::ErrorKind::PermissionDenied, "failed", true),
(io::ErrorKind::Interrupted, "cancelled", true),
] {
let subject = AuthoringSubject::Definition("requirements.ready".into());
let usage = UsageLog::start(state.path(), project.path(), &subject.label()).unwrap();
let path = usage.path.clone();
let pending = PendingAssessment {
subject,
record: json!({}),
outcome: AuthoringOutcome {
subject: "requirements.ready".into(),
backend: "fixture".into(),
model: "fixture".into(),
evidence_path: None,
usage_path: path.clone(),
determination: Judgment::True,
rationale: "Fixture assessment.".into(),
policy: AssessmentPolicy::Once,
},
usage,
};
if block_usage {
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
}
let error = pending.failed(io::Error::new(kind, "cannot persist fixture evidence"));
assert_eq!(error.kind(), kind, "retain the original failure kind");
let message = error.to_string();
assert!(
message.contains("cannot persist fixture evidence"),
"{message}"
);
assert!(message.contains(path.to_str().unwrap()), "{message}");
if block_usage {
assert!(message.contains("cannot record failed usage"), "{message}");
assert!(
path.is_dir(),
"failed usage writes do not replace the obstruction"
);
} else {
let record: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
assert_eq!(record["outcome"], expected);
assert_eq!(record["evidence_written"], false);
assert!(!record["end_time_ms"].is_null());
assert!(record["determination"].is_null());
assert!(!message.contains("cannot record failed usage"));
}
assert!(
!project
.path()
.join("evidence/requirements.ready.json")
.exists()
);
}
}
Input 4: outline src/authoring/mod.rs mod[tests]/fn[citation_reviews_are_confirmed_with_fresh_targeted_conversations]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/fn[citation_reviews_are_confirmed_with_fresh_targeted_conversations] - Kind:
fn src/authoring/mod.rs:3778–3823
// {test}`requirements.authoring.confirmation`
// {test}`requirements.authoring.usage_storage`
#[tokio::test]
async fn citation_reviews_are_confirmed_with_fresh_targeted_conversations() {
let project = inputs::tests::project();
fs::write(
project.path().join("src/lib.rs"),
"// {cite}`requirements.ready`\nfn helper() {}\n",
)
.unwrap();
let subject = AuthoringSubject::parse("citations:src/lib.rs#fn[helper]");
let sources = subject.sources(project.path()).unwrap();
let state = tempfile::tempdir().unwrap();
let mut usage = UsageLog::start(state.path(), project.path(), &subject.label()).unwrap();
let provider = RecordingProvider::new(vec![
judgment(json!(true), "First citation review."),
judgment(json!(true), "Second citation review."),
]);
let (_, record) = assess_subject(
&provider,
project.path(),
state.path(),
&subject,
sources,
&mut usage,
AssessmentPolicy::Confirm,
)
.await
.unwrap();
assert_eq!(record["item"], "fn[helper]");
assert_eq!(record["rationale"], "First citation review.");
let prompts = provider.prompts();
assert_eq!(prompts.len(), 2);
assert!(
prompts
.iter()
.all(|(text, _)| text.contains("Item under review: src/lib.rs fn[helper]"))
);
assert!(!prompts[1].0.contains("First citation review."));
let logs: Vec<Value> = fs::read_dir(state.path().join("authoring/usage"))
.unwrap()
.map(|p| serde_json::from_slice(&fs::read(p.unwrap().path()).unwrap()).unwrap())
.collect();
assert_eq!(logs.len(), 2);
assert_ne!(logs[0]["run_id"], logs[1]["run_id"]);
}
Input 5: outline src/authoring/mod.rs mod[tests]/fn[usage_subject_kind_is_known_before_sources_are_prepared]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/fn[usage_subject_kind_is_known_before_sources_are_prepared] - Kind:
fn src/authoring/mod.rs:4573–4606
// {test}`requirements.authoring.usage_storage`
#[test]
fn usage_subject_kind_is_known_before_sources_are_prepared() {
let project =
crate::sites::tests::project(crate::sites::tests::RULE, crate::sites::tests::SOURCE);
let root = project.path();
let requirements = root.join("md/requirements.md");
let mut book = fs::read_to_string(&requirements).unwrap();
let cite = "{cite}`requirements.rule`";
book.push_str(&format!("\n:::{{example}} case\nA case. {cite}\n:::\n"));
fs::write(&requirements, book).unwrap();
let source = root.join("src/lib.rs");
let mut text = fs::read_to_string(&source).unwrap();
text.push_str(&format!("\n// {cite}\nfn cites() {{}}\n"));
fs::write(&source, text).unwrap();
for (subject, kind) in [
("requirements.rule", "requirement"),
("requirements.case", "example"),
("citations:src/lib.rs#fn[cites]", "citation review"),
(
"sites:requirements.rule/src/lib.rs#fn[check_one]",
"site review",
),
] {
let subject = AuthoringSubject::parse(subject);
assert_eq!(subject.kind_noun(root), Some(kind), "{}", subject.label());
// The same kind the prepared sources record.
assert_eq!(subject.sources(root).unwrap().subject_kind.noun(), kind);
}
assert_eq!(
AuthoringSubject::parse("requirements.missing").kind_noun(root),
None
);
}
Input 6: outline src/authoring/usage.rs mod[tests]/fn[input_metadata_counts_components_and_reads_without_persisting_source]
- File:
src/authoring/usage.rs - Selector:
mod[tests]/fn[input_metadata_counts_components_and_reads_without_persisting_source] - Kind:
fn src/authoring/usage.rs:455–551
// {test}`requirements.authoring.usage_inputs`
// {test}`requirements.authoring.usage_storage`
#[test]
fn input_metadata_counts_components_and_reads_without_persisting_source() {
let state = tempfile::tempdir().unwrap();
let mut log =
UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
let file = json!({
"file": "private-source-file.rs", "item": "fn[private_item]", "hash": "0".repeat(64),
"kind": "fn", "line_start": 1, "line_end": 2,
"text": ["λ", "DO_NOT_LOG_SOURCE"]
});
let requirements = json!({
"requirements": "private.match.*",
"matches": ["private.match.a", "private.match.b"],
"text": ["PRIVATE_REQUIREMENT_TEXT"]
});
log.prepared("mandatory", &[file.clone(), requirements]);
log.prepared("habeas", &[file]);
let search = json!({"matches":[{"file":"private-source-file.rs","item":"fn[private_item]","lines":[{"text":"λ"},{"text":"DO_NOT_LOG_SOURCE"}]}]});
log.search_result(&search);
log.search_result(&search);
log.save().unwrap();
let prepared = persisted(&log);
assert_eq!(prepared["inputs"][0]["kind"], "outline");
assert_eq!(prepared["inputs"][0]["bytes"], "λ\nDO_NOT_LOG_SOURCE".len());
assert_eq!(prepared["inputs"][0]["lines"], 2);
assert_eq!(prepared["inputs"][1]["components"], 2);
assert_eq!(prepared["inputs"][1]["kind"], "requirements");
assert_eq!(
prepared["inputs"][1]["bytes"],
"PRIVATE_REQUIREMENT_TEXT".len()
);
assert_eq!(prepared["inputs"][1]["lines"], 1);
assert_eq!(prepared["inputs"][0]["unique"], true);
assert_eq!(prepared["inputs"][2]["unique"], false);
assert_eq!(prepared["inputs"][2]["origin"], "habeas");
assert!(prepared["inputs"][0]["submitted_in_request"].is_null());
assert!(prepared["inputs"][0]["sent_in_request"].is_null());
assert_eq!(prepared["inputs"][3]["kind"], "search");
assert_eq!(prepared["inputs"][3]["bytes"], "λ\nDO_NOT_LOG_SOURCE".len());
assert_eq!(prepared["inputs"][3]["lines"], 2);
assert_eq!(prepared["inputs"][3]["unique"], true);
assert_eq!(prepared["inputs"][4]["unique"], false);
assert!(prepared["inputs"][3]["sent_in_request"].is_null());
log.prepared(
"habeas",
&[
json!({"definition":"private.term","text":["PRIVATE_TERM_TEXT","λ"]}),
json!({"builtin":"habeas:util","text":["PRIVATE_BUILTIN_TEXT"]}),
],
);
log.save().unwrap();
let kinds = persisted(&log);
assert_eq!(kinds["inputs"][5]["kind"], "definition");
assert_eq!(kinds["inputs"][5]["bytes"], "PRIVATE_TERM_TEXT\nλ".len());
assert_eq!(kinds["inputs"][5]["lines"], 2);
assert_eq!(kinds["inputs"][6]["kind"], "builtin");
assert_eq!(kinds["inputs"][6]["bytes"], "PRIVATE_BUILTIN_TEXT".len());
assert_eq!(kinds["inputs"][6]["lines"], 1);
let index = log.begin_request().unwrap();
let submitted = persisted(&log);
assert_eq!(submitted["inputs"][0]["submitted_in_request"], index);
assert!(submitted["inputs"][0]["sent_in_request"].is_null());
log.end_request(index, 7, Some(&Usage::new()), None)
.unwrap();
log.record.determination = Some("FIXME".into());
log.record.evidence_written = true;
log.finish("completed").unwrap();
let sent = persisted(&log);
assert_eq!(sent["inputs"][0]["sent_in_request"], index);
assert_eq!(sent["inputs"][3]["sent_in_request"], index);
assert_eq!(sent["requests"][0]["outcome"], "completed");
assert_eq!(sent["outcome"], "completed");
assert_eq!(sent["determination"], "FIXME");
assert_eq!(sent["evidence_written"], true);
assert!(sent["tokens"]["input"].is_null());
assert!(sent["tokens"]["output"].is_null());
assert_eq!(sent["tokens"]["complete"], false);
let serialized = fs::read_to_string(&log.path).unwrap();
for private in [
"DO_NOT_LOG_SOURCE",
"PRIVATE_REQUIREMENT_TEXT",
"private-source-file.rs",
"private_item",
"private.match",
"private.term",
"PRIVATE_TERM_TEXT",
"PRIVATE_BUILTIN_TEXT",
] {
assert!(
!serialized.contains(private),
"stored source content: {private}"
);
}
}
Input 7: outline src/authoring/usage.rs mod[tests]/fn[cancelled_request_persists_elapsed_time_and_incomplete_totals]
- File:
src/authoring/usage.rs - Selector:
mod[tests]/fn[cancelled_request_persists_elapsed_time_and_incomplete_totals] - Kind:
fn src/authoring/usage.rs:653–688
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.usage_requests`
#[test]
fn cancelled_request_persists_elapsed_time_and_incomplete_totals() {
let state = tempfile::tempdir().unwrap();
let mut log =
UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
let initial = persisted(&log);
assert_eq!(initial["outcome"], "unfinished");
assert!(initial["end_time_ms"].is_null());
let first = log.begin_request().unwrap();
log.end_request(
first,
2,
Some(&Usage::new().input_tokens(2).output_tokens(3)),
None,
)
.unwrap();
let second = log.begin_request().unwrap();
log.active_request = Some((second, Instant::now() - Duration::from_millis(12)));
log.finish("cancelled").unwrap();
let cancelled = persisted(&log);
assert_eq!(cancelled["outcome"], "cancelled");
assert!(!cancelled["end_time_ms"].is_null());
assert_eq!(cancelled["requests"][second]["outcome"], "cancelled");
assert!(
cancelled["requests"][second]["elapsed_ms"]
.as_u64()
.unwrap()
>= 12
);
assert_eq!(cancelled["tokens"]["complete"], false);
assert_eq!(cancelled["tokens"]["input"], 2);
assert_eq!(cancelled["tokens"]["output"], 3);
assert_eq!(cancelled["requests"][first]["tokens"]["input"], 2);
}
Input 8: outline src/authoring/usage.rs mod[tests]/fn[tool_outcomes_are_distinct_and_unknown_names_do_not_leak_model_text]
- File:
src/authoring/usage.rs - Selector:
mod[tests]/fn[tool_outcomes_are_distinct_and_unknown_names_do_not_leak_model_text] - Kind:
fn src/authoring/usage.rs:725–758
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.usage_inputs`
// {test}`requirements.authoring.usage_storage`
#[test]
fn tool_outcomes_are_distinct_and_unknown_names_do_not_leak_model_text() {
let state = tempfile::tempdir().unwrap();
let mut log =
UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
log.tool("list_files", false);
log.tool("outline", false);
log.tool("habeas", true);
log.skipped_tool("ripgrep");
log.tool("ast_grep", false);
log.tool("github", false);
log.tool("MODEL_TEXT_SHOULD_NOT_APPEAR", true);
log.skipped_tool("OTHER_MODEL_TEXT");
log.finish("completed").unwrap();
let value = persisted(&log);
assert_eq!(value["tool_call_count"], 8);
assert_eq!(value["tool_calls"]["list_files"], 1);
assert_eq!(value["tool_calls"]["ast_grep"], 1);
assert_eq!(value["tool_calls"]["github"], 1);
assert_eq!(value["tool_calls"]["outline"], 1);
assert_eq!(value["tool_failures"]["habeas"], 1);
assert_eq!(value["tool_skipped"]["ripgrep"], 1);
assert_eq!(value["tool_calls"]["unknown"], 2);
assert_eq!(value["tool_failures"]["unknown"], 1);
assert_eq!(value["tool_skipped"]["unknown"], 1);
assert!(value["inputs"].as_array().unwrap().is_empty());
assert!(value["tokens"]["input"].is_null());
assert_eq!(value["tokens"]["complete"], false);
let serialized = fs::read_to_string(&log.path).unwrap();
assert!(!serialized.contains("MODEL_TEXT"));
}
Input 9: 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 10: 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 11: 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 12: 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 13: 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 14: outline tests/authoring_batch.rs fn[confirm_runs_a_second_assessment_with_its_own_usage_record]
- File:
tests/authoring_batch.rs - Selector:
fn[confirm_runs_a_second_assessment_with_its_own_usage_record] - Kind:
fn tests/authoring_batch.rs:1894–1934
// {test}`requirements.authoring.confirmation`
// {test}`requirements.authoring.usage_storage`
#[test]
// {test}`requirements.authoring.usage_storage`
fn confirm_runs_a_second_assessment_with_its_own_usage_record() {
let server = Server::start(false, None);
let fixture = Fixture::new(&server.endpoint, None);
let output = fixture.run(&["author", "requirements.alpha", "--policy", "confirm"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
server.subjects(),
[
"requirement requirements.alpha",
"requirement requirements.alpha"
]
);
let usage = fixture.usage();
let mut subjects = usage
.iter()
.map(|run| run["subject"].as_str().unwrap().to_owned())
.collect::<Vec<_>>();
subjects.sort();
assert_eq!(
subjects,
[
"requirements.alpha",
"requirements.alpha (second assessment)"
]
);
// Agreeing assessments record the first unchanged.
assert!(
!fixture.evidence("requirements.alpha")["rationale"]
.as_str()
.unwrap()
.contains("Confirmation")
);
}
Input 15: outline tests/authoring_cli.rs fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free]
- File:
tests/authoring_cli.rs - Selector:
fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free] - Kind:
fn tests/authoring_cli.rs:366–676
// {test}`requirements.authoring.complete_initial_bundle`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.additional_read`
// {test}`requirements.authoring.acknowledged_gap`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.initial_prompt`
// {test}`requirements.ci.review_criteria`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.usage_inputs`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.mandatory_inputs`
// {test}`requirements.authoring.github_reads`
// {test}`requirements.authoring.invocation`
// {test}`requirements.configuration.serialization`
// {test}`requirements.ci.fixme_implementation_gap`
// {test}`requirements.authoring.finish_search.empty`
// {test}`requirements.authoring.finish_search.completion`
#[test]
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.reporting`
fn ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free() {
let server = Server::start(vec![
reply(vec![
call("list", "list_files", json!({})),
call(
"search",
"ripgrep",
json!({"path":"extra.txt","pattern":"needle"}),
),
call(
"read",
"habeas",
json!({"file":"extra.txt","line_start":10}),
),
call(
"repeat",
"habeas",
json!({"file":"extra.txt","line_start":10}),
),
call(
"missing",
"habeas",
json!({"file":"absent.txt","line_start":1}),
),
]),
json!({"__finish_latest_search":true}),
reply(vec![call(
"submit",
"submit_judgment",
json!({
"determination":{"FIXME":["example/app#125"]},"rationale":"SECRET_RATIONALE: `src/lib.rs#fn[ready]` documents the gap."}),
)]),
]);
let fixture = Fixture::new(&server.endpoint);
let user_config = fixture.config.join("habeas/config.toml");
let configured = fs::read(&user_config).unwrap();
let output = fixture.run(&["author-evidence", SUBJECT]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
// The user configuration, with its environment-resolved key, is not
// rewritten.
assert_eq!(fs::read(&user_config).unwrap(), configured);
let requests = server.finish();
assert_eq!(requests.len(), 3);
for request in &requests {
assert!(request.headers.starts_with("POST /api/chat HTTP/1.1\r\n"));
assert!(request.headers.to_ascii_lowercase().contains(&format!(
"authorization: bearer {}",
AUTH.to_ascii_lowercase()
)));
assert_eq!(request.body["model"], MODEL);
assert_eq!(request.body["options"]["temperature"], 0.25);
assert_eq!(request.body["options"]["num_ctx"], 4096);
assert_eq!(request.body["think"], false);
assert_eq!(request.body["stream"], false);
}
let prompt = prompt_text(&requests[0].body);
for text in [
"Assess whether a project's tests adequately check one requirement.",
REQUIREMENT,
"SECRET_DEFINITION_TEXT",
"fn ready_test()",
"You MUST end by calling submit_judgment",
] {
assert!(prompt.contains(text), "prompt missing {text}");
}
assert!(!prompt.contains("pub fn ready()"), "{prompt}");
assert!(!prompt.contains("OLD_RATIONALE_MUST_NOT_REACH_MODEL"));
let mut tools = requests[0].body["tools"]
.as_array()
.unwrap()
.iter()
.map(|tool| tool["function"]["name"].as_str().unwrap())
.collect::<Vec<_>>();
tools.sort();
assert_eq!(
tools,
[
"ast_grep",
"finish_search",
"github",
"habeas",
"list_files",
"next_page",
"outline",
"references",
"ripgrep",
"submit_judgment"
]
);
let results = requests[1].body["messages"]
.as_array()
.unwrap()
.iter()
.filter(|message| message["role"] == "tool")
.collect::<Vec<_>>();
assert_eq!(results.len(), 5);
assert!(results.iter().any(|message| {
message["content"]
.as_str()
.unwrap()
.contains("SECRET_SOURCE_PAYLOAD")
}));
assert!(
results
.iter()
.any(|message| message["content"].as_str().unwrap().contains("absent.txt"))
);
let evidence: Value = serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(
evidence["determination"],
json!({"FIXME":["example/app#125"]})
);
assert_eq!(
evidence["rationale"],
"SECRET_RATIONALE: `src/lib.rs#fn[ready]` documents the gap."
);
assert_eq!(evidence["requirement"], REQUIREMENT);
let inputs = evidence["inputs"].as_array().unwrap();
assert!(
inputs
.iter()
.any(|input| input["file"] == "src/lib.rs" && input["item"] == "fn[ready_test]"),
"{inputs:#?}"
);
// The acknowledgment reaches the model as metadata, without the
// containing implementation. Its body is protected by the reference set.
assert!(prompt.contains(":github: example/app#125"));
assert!(prompt.contains("One acknowledged gap."));
// GitHub is unreachable, so the issue is supplied as open, but the state
// is not recorded.
assert!(
prompt.contains("\"reference\": \"example/app#125\"")
&& prompt.contains("\"state\": \"open\""),
"{prompt}"
);
assert!(!evidence.to_string().contains("github_issues"));
assert!(!fixture.usage().to_string().contains("github_issues"));
assert!(
!inputs
.iter()
.any(|input| input["file"] == "src/lib.rs" && input["item"] == "fn[ready]"),
"{inputs:#?}"
);
// CI accepts the FIXME judgment: its evidence has no validation error.
let report = habeas::validate_repository(&fixture.project).unwrap();
let label = format!("evidence/{SUBJECT}.json");
assert!(
!report.errors.iter().any(|error| error.contains(&label)),
"{:#?}",
report.errors
);
// The same record with a false determination is rejected.
let mut rejected = evidence.clone();
rejected["determination"] = json!(false);
let accepted = fs::read(&fixture.evidence).unwrap();
fs::write(&fixture.evidence, rejected.to_string()).unwrap();
let report = habeas::validate_repository(&fixture.project).unwrap();
assert!(
report.errors.iter().any(|error| error.contains(&label)),
"{:#?}",
report.errors
);
fs::write(&fixture.evidence, accepted).unwrap();
assert!(
inputs
.iter()
.any(|input| input["definition"] == "terms.readiness")
);
let extra = inputs
.iter()
.filter(|input| input["file"] == "extra.txt")
.collect::<Vec<_>>();
// The search only locates lines and records nothing; the reads cover
// lines 10-12, one plain-text line node each, and the repeated delivery
// is recorded once, by selector and hash only.
assert_eq!(
extra,
habeas::outline_inputs_for_lines(&fixture.project, "extra.txt", 10, 12)
.unwrap()
.iter()
.collect::<Vec<_>>(),
"repeated delivery is deduplicated in evidence"
);
assert!(
!evidence["inputs"]
.to_string()
.contains("SECRET_SOURCE_PAYLOAD")
);
assert!(
!inputs
.iter()
.any(|input| input["file"] == "absent.txt" || input["file"] == ".")
);
let usage = fixture.usage();
assert_eq!(usage["outcome"], "completed");
assert_eq!(usage["determination"], "FIXME");
assert_eq!(usage["evidence_written"], true);
assert_eq!(usage["request_count"], 3);
assert_eq!(usage["tool_call_count"], 7);
assert_eq!(usage["tool_calls"]["habeas"], 3);
assert_eq!(usage["tool_failures"]["habeas"], 1);
// The directory listing counts as a tool call but is not an input.
assert_eq!(usage["tool_calls"]["list_files"], 1);
assert_eq!(usage["tool_calls"]["ripgrep"], 1);
assert_eq!(usage["tool_calls"]["finish_search"], 1);
let usage_inputs = usage["inputs"].as_array().unwrap();
assert!(
!usage_inputs
.iter()
.any(|input| input["origin"] == "list_files"),
"{usage_inputs:?}"
);
// Search snippets count toward usage, without becoming evidence inputs.
assert!(
usage_inputs.iter().any(|input| input["origin"] == "ripgrep"
&& input["kind"] == "search"
&& input["bytes"].as_u64().unwrap() > 0
&& input["lines"].as_u64().unwrap() > 0),
"{usage_inputs:?}"
);
assert!(
usage_inputs
.iter()
.any(|input| input["origin"] == "habeas" && input["unique"] == true),
"{usage_inputs:?}"
);
assert_eq!(usage["tokens"]["input"], 33);
assert_eq!(usage["tokens"]["output"], 21);
assert_eq!(usage["tokens"]["complete"], true);
assert!(
usage["inputs"]
.as_array()
.unwrap()
.iter()
.any(|input| input["origin"] == "habeas"
&& input["unique"] == false
&& input["sent_in_request"] == 1)
);
assert!(
usage["inputs"]
.as_array()
.unwrap()
.iter()
.any(|input| input["origin"] == "mandatory"
&& input["kind"] == "definition"
&& input["bytes"].as_u64().unwrap() > 0)
);
let serialized = usage.to_string();
for secret in [
"SECRET_REQUIREMENT_TEXT",
"SECRET_DEFINITION_TEXT",
"SECRET_SOURCE_PAYLOAD",
"SECRET_RATIONALE",
AUTH,
"#125",
] {
assert!(
!serialized.contains(secret),
"usage contains source or credential content: {secret}"
);
}
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains(MODEL) && stdout.contains("Evidence:") && stdout.contains("Usage:"));
// By default the report names the subject and backend and identifies the
// evidence file it wrote.
assert!(
stdout.starts_with(&format!("{SUBJECT}: ollama / {MODEL}")),
"{stdout}"
);
let evidence = stdout
.lines()
.find_map(|line| line.strip_prefix("Evidence: "))
.unwrap();
assert!(
evidence.ends_with(&format!("evidence/{SUBJECT}.json")),
"{stdout}"
);
assert_eq!(
fs::canonicalize(evidence).unwrap(),
fs::canonicalize(fixture.project.join(format!("evidence/{SUBJECT}.json"))).unwrap()
);
}
Input 16: outline tests/authoring_cli.rs fn[authoring_uses_nearest_workspace_configuration_without_a_user_file]
- File:
tests/authoring_cli.rs - Selector:
fn[authoring_uses_nearest_workspace_configuration_without_a_user_file] - Kind:
fn tests/authoring_cli.rs:724–797
// {test}`requirements.configuration.workspace_location`
// {test}`requirements.authoring.configuration`
// {test}`requirements.configuration.workspace_structure`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.configuration.serialization`
#[test]
// {test}`requirements.configuration.documentation`
fn authoring_uses_nearest_workspace_configuration_without_a_user_file() {
let server = Server::start(vec![reply(vec![call(
"submit",
"submit_judgment",
json!({"determination":true,"rationale":"The supplied sources support the subject."}),
)])]);
let fixture = Fixture::new(&server.endpoint);
fs::remove_file(fixture.config.join("habeas/config.toml")).unwrap();
fs::write(
fixture.project.join("habeas.toml"),
"version = 1\n[authoring]\ndefault = 'missing-parent-choice'\n",
)
.unwrap();
let nested = fixture.project.join("src/nested");
fs::create_dir(&nested).unwrap();
let workspace = nested.join("habeas.toml");
fs::write(
&workspace,
format!(
"version = 1\n[authoring]\ndefault = 'workspace'\n[authoring.configs.workspace]\npolicy = 'once'\nbackend = 'ollama'\nmodel = 'workspace-model'\nendpoint = '{}'\napi_key = 'WORKSPACE_LITERAL_KEY'\n",
server.endpoint
),
)
.unwrap();
let configurations = [fixture.project.join("habeas.toml"), workspace.clone()];
let before = configurations
.iter()
.map(|path| fs::read(path).unwrap())
.collect::<Vec<_>>();
let output = fixture
.command()
.current_dir(&nested)
.args(["author", SUBJECT])
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
// Running the configured feature rewrites neither configuration file,
// and creates no user configuration.
for (path, before) in configurations.iter().zip(&before) {
assert_eq!(&fs::read(path).unwrap(), before, "{}", path.display());
}
assert!(!fixture.config.join("habeas/config.toml").exists());
let requests = server.finish();
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].body["model"], "workspace-model");
assert!(requests[0].headers.contains("WORKSPACE_LITERAL_KEY"));
assert!(
!requests[0]
.body
.to_string()
.contains("WORKSPACE_LITERAL_KEY")
);
let usage = fixture.usage();
assert_eq!(usage["model"], "workspace-model");
for text in [
usage.to_string(),
String::from_utf8_lossy(&output.stdout).into_owned(),
String::from_utf8_lossy(&output.stderr).into_owned(),
] {
assert!(!text.contains("WORKSPACE_LITERAL_KEY"), "{text}");
}
}
Input 17: outline tests/authoring_cli.rs fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues]
- File:
tests/authoring_cli.rs - Selector:
fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues] - Kind:
fn tests/authoring_cli.rs:853–922
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.structural_search`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.read_denial.untracked`
// {test}`requirements.authoring.read_denial`
#[test]
fn explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues() {
for (tool, arguments) in [
("habeas", json!({"file":"untracked.txt", "line_start":1})),
(
"ripgrep",
json!({"path":"untracked.txt", "pattern":"hidden"}),
),
(
"ast_grep",
json!({"path":"untracked.txt", "language":"rust", "rule":{"rule":{"pattern":"hidden"}}}),
),
("list_files", json!({"path":"untracked-directory"})),
] {
let server = Server::start(vec![
reply(vec![call("denied", tool, arguments)]),
reply(vec![call(
"submit",
"submit_judgment",
json!({"determination": true, "rationale": "The tracked sources support it."}),
)]),
]);
let fixture = Fixture::new(&server.endpoint);
for args in [["init", "--quiet"], ["add", "."]] {
let git = Command::new("git")
.current_dir(&fixture.project)
.args(args)
.output()
.unwrap();
assert!(git.status.success(), "{git:?}");
}
fs::write(fixture.project.join("untracked.txt"), "hidden source\n").unwrap();
fs::create_dir(fixture.project.join("untracked-directory")).unwrap();
fs::write(
fixture.project.join("untracked-directory/hidden.txt"),
"hidden source\n",
)
.unwrap();
let output = fixture.run(&["author", SUBJECT, "--stdout"]);
assert!(output.status.success(), "{tool}: {output:?}");
// The model was told the path is untracked and how to fix it, and
// the file was neither delivered nor recorded.
let requests = server.finish();
assert_eq!(requests.len(), 2, "{tool}");
let second = requests[1].body.to_string();
assert!(
second.contains("is untracked") || second.contains("untracked, so"),
"{tool}: {second}"
);
assert!(second.contains("git add"), "{tool}: {second}");
assert!(!second.contains("hidden source"), "{tool}: {second}");
let evidence = String::from_utf8_lossy(&output.stdout);
assert!(!evidence.contains("untracked"), "{tool}: {evidence}");
let usage = fixture.usage();
assert_eq!(usage["outcome"], "completed", "{tool}: {usage}");
assert_eq!(usage["request_count"], 2, "{tool}: {usage}");
assert_eq!(usage["tool_failures"][tool], 1, "{tool}: {usage}");
}
}
Input 18: outline tests/authoring_cli.rs fn[false_is_a_completed_assessment]
- File:
tests/authoring_cli.rs - Selector:
fn[false_is_a_completed_assessment] - Kind:
fn tests/authoring_cli.rs:924–995
// {test}`requirements.authoring.negative_assessment`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.persistence`
// {test}`requirements.ci.fixme_with_unacknowledged_gap`
// {test}`requirements.authoring.reporting`
#[test]
fn false_is_a_completed_assessment() {
let server = Server::start(vec![reply(vec![call(
"submit",
"submit_judgment",
json!({"determination":false,"rationale":"The test checks refusal for a full positive-capacity queue, without acknowledging missing checks for preservation and zero capacity."}),
)])]);
let fixture = Fixture::new(&server.endpoint);
fs::write(fixture.project.join("md/requirements.md"), ":::{req} ready\nInserting into a full queue MUST return false without overwriting its entries, including at zero capacity.\n:::\n").unwrap();
fs::write(fixture.project.join("src/lib.rs"), "// {impl}`requirements.ready`\n// FIXME(#125): zero-capacity insertion panics.\npub fn push(queue: &mut [u8], value: u8) -> bool {\n queue[0] = value;\n true\n}\n\n// {test}`requirements.ready`\n#[test]\nfn full_queue() { let mut queue = [1]; assert!(!push(&mut queue, 2)); }\n").unwrap();
let output = fixture.run(&["author-evidence", SUBJECT, "--config", "mock"]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
let prompt = prompt_text(&requests[0].body);
assert!(prompt.contains("and false otherwise."));
assert!(!prompt.contains("FIXME(#125): zero-capacity insertion panics"));
assert!(!prompt.contains("queue[0] = value"));
assert!(prompt.contains("fn full_queue()"));
let evidence: Value = serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(evidence["determination"], false);
assert!(!evidence["inputs"].as_array().unwrap().is_empty());
assert!(
evidence["rationale"]
.as_str()
.unwrap()
.contains("without acknowledging")
);
// Outline inputs record selectors and hashes, never the source text.
assert!(
evidence["inputs"]
.as_array()
.unwrap()
.iter()
.any(|input| input["item"].is_string() && input["hash"].is_string())
);
assert!(!evidence["inputs"].to_string().contains("FIXME(#125)"));
assert_eq!(fixture.usage()["outcome"], "completed");
assert_eq!(fixture.usage()["determination"], "false");
let diagnostics = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(&format!("{SUBJECT}: false")), "{stderr}");
assert!(
!String::from_utf8_lossy(&output.stdout).contains(&format!("{SUBJECT}: false")),
"{diagnostics}"
);
assert!(
!diagnostics.contains("without acknowledging"),
"{diagnostics}"
);
// CI rejects the false judgment even though a FIXME acknowledges one gap.
let report = habeas::validate_repository(&fixture.project).unwrap();
let evidence_file = format!("evidence/{SUBJECT}.json");
let rejection = report
.errors
.iter()
.find(|error| error.starts_with(&evidence_file) && error.contains("determination is false"))
.unwrap_or_else(|| panic!("{:?}", report.errors));
assert!(rejection.contains("without acknowledging"), "{rejection}");
}
Input 19: outline tests/authoring_cli.rs fn[usage_record_identifies_its_run_and_unusable_state_is_reported]
- File:
tests/authoring_cli.rs - Selector:
fn[usage_record_identifies_its_run_and_unusable_state_is_reported] - Kind:
fn tests/authoring_cli.rs:1259–1336
// {test}`requirements.authoring.usage_storage`
#[cfg(unix)]
#[test]
// {test}`requirements.configuration.state_location`
fn usage_record_identifies_its_run_and_unusable_state_is_reported() {
let server = Server::start(vec![
reply(vec![call(
"submit",
"submit_judgment",
json!({"determination":true,"rationale":"covered"}),
)]);
2
]);
let fixture = Fixture::new(&server.endpoint);
let output = fixture.run(&["author", SUBJECT]);
assert!(output.status.success(), "{output:?}");
let directory = fixture.state.join("habeas/authoring/usage");
let files = fs::read_dir(&directory)
.unwrap()
.map(|entry| entry.unwrap().path())
.collect::<Vec<_>>();
assert_eq!(files.len(), 1);
let usage: Value = serde_json::from_slice(&fs::read(&files[0]).unwrap()).unwrap();
let run_id = usage["run_id"].as_str().unwrap();
assert!(!run_id.is_empty());
assert_eq!(
files[0].file_name().unwrap().to_str().unwrap(),
format!("{run_id}.json"),
"the record is named after its run"
);
assert_eq!(usage["version"], 1);
assert_eq!(
usage["project_root"],
fixture.project.canonicalize().unwrap().to_str().unwrap()
);
assert_eq!(usage["subject"], SUBJECT);
assert_eq!(usage["subject_kind"], "requirement");
assert_eq!(usage["backend"], "ollama");
assert_eq!(usage["model"], MODEL);
assert_eq!(usage["evidence_output"], "file");
let start = usage["start_time_ms"].as_u64().unwrap();
let end = usage["end_time_ms"].as_u64().unwrap();
assert!(start > 0 && start <= end, "{usage}");
let first_bytes = fs::read(&files[0]).unwrap();
let second = fixture.run(&["author", SUBJECT, "--force"]);
assert!(second.status.success(), "{second:?}");
assert_eq!(fs::read(&files[0]).unwrap(), first_bytes);
assert_eq!(fs::read_dir(&directory).unwrap().count(), 2);
server.finish();
// A state location that cannot be determined or created is reported
// before any model request, and no evidence is written.
let blocker = fixture.temp.path().join("not-a-directory");
fs::write(&blocker, "").unwrap();
for (variable, value) in [
("XDG_STATE_HOME", Some(blocker.as_os_str())),
("XDG_STATE_HOME", None),
] {
let mut command = fixture.command();
match value {
Some(value) => command.env(variable, value),
None => command.env_remove(variable).env_remove("HOME"),
};
let output = command
.args(["author", SUBJECT, "--force"])
.output()
.unwrap();
assert!(!output.status.success(), "{value:?}: {output:?}");
assert!(!output.stderr.is_empty(), "{value:?}: {output:?}");
assert!(output.stdout.is_empty(), "{value:?}: {output:?}");
}
let evidence: Value = serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(
evidence["rationale"], "covered",
"failed runs preserved the evidence"
);
}
Input 20: outline tests/authoring_cli.rs fn[usage_record_of_an_early_failure_identifies_its_subject_kind]
- File:
tests/authoring_cli.rs - Selector:
fn[usage_record_of_an_early_failure_identifies_its_subject_kind] - Kind:
fn tests/authoring_cli.rs:1338–1362
// {test}`requirements.authoring.usage_storage`
#[test]
fn usage_record_of_an_early_failure_identifies_its_subject_kind() {
// The configuration selection fails before sources are prepared or a
// provider is connected.
let fixture = Fixture::new("http://127.0.0.1:1");
let output = fixture
.command()
.args(["author", SUBJECT, "--force", "--config", "missing"])
.output()
.unwrap();
assert!(!output.status.success(), "{output:?}");
let directory = fixture.state.join("habeas/authoring/usage");
let files = fs::read_dir(&directory)
.unwrap()
.map(|entry| entry.unwrap().path())
.collect::<Vec<_>>();
assert_eq!(files.len(), 1, "{output:?}");
let usage: Value = serde_json::from_slice(&fs::read(&files[0]).unwrap()).unwrap();
assert_eq!(usage["subject"], SUBJECT);
assert_eq!(usage["subject_kind"], "requirement", "{usage}");
assert_eq!(usage["outcome"], "failed", "{usage}");
assert_eq!(usage["evidence_written"], false, "{usage}");
assert!(usage["end_time_ms"].as_u64().is_some(), "{usage}");
}
Input 21: outline tests/authoring_cli.rs fn[usage_state_inside_the_project_is_refused_before_creating_it]
- File:
tests/authoring_cli.rs - Selector:
fn[usage_state_inside_the_project_is_refused_before_creating_it] - Kind:
fn tests/authoring_cli.rs:1364–1390
// {test}`requirements.authoring.usage_storage`
#[test]
fn usage_state_inside_the_project_is_refused_before_creating_it() {
let fixture = Fixture::new("http://127.0.0.1:1");
let inside = fixture.project.join("state");
for args in [vec!["author", SUBJECT], vec!["author", SUBJECT, "--stdout"]] {
let output = fixture
.command()
.env("XDG_STATE_HOME", &inside)
.env("LOCALAPPDATA", &inside)
.args(&args)
.output()
.unwrap();
assert!(!output.status.success(), "{output:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("authoring usage state must be outside the project repository"),
"{stderr}"
);
assert!(output.stdout.is_empty(), "{output:?}");
assert!(!inside.exists(), "state directory created inside project");
}
assert_eq!(
fs::read_to_string(&fixture.evidence).unwrap(),
fixture.original
);
}
Input 22: outline tests/authoring_cli.rs fn[stdout_emits_only_evidence_json_without_changing_project_files]
- File:
tests/authoring_cli.rs - Selector:
fn[stdout_emits_only_evidence_json_without_changing_project_files] - Kind:
fn tests/authoring_cli.rs:1447–1563
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.reporting`
// {test}`requirements.ci.schema`
#[test]
fn stdout_emits_only_evidence_json_without_changing_project_files() {
for (determination, kind, existing_evidence, verbose) in [
(json!(true), "true", true, false),
(json!(false), "false", true, false),
(json!({"FIXME":["#125"]}), "FIXME", true, false),
(json!(true), "true", false, false),
(json!(false), "false", true, true),
(json!(true), "true", true, true),
] {
let rationale = "The supplied sources explain this judgment.";
let server = Server::start(vec![reply(vec![call(
"submit",
"submit_judgment",
json!({"determination":determination,"rationale":rationale}),
)])]);
let fixture = Fixture::new(&server.endpoint);
if !existing_evidence {
fs::remove_dir_all(fixture.project.join("evidence")).unwrap();
}
let mut args = vec!["author-evidence", SUBJECT, "--stdout"];
if verbose {
args.push("--verbose");
}
let output = fixture.run(&args);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(server.finish().len(), 1);
let evidence: Value = serde_json::from_slice(&output.stdout).unwrap();
assert!(output.stdout.ends_with(b"\n"));
assert_eq!(evidence["requirement"], REQUIREMENT);
assert_eq!(evidence["determination"], determination);
assert_eq!(evidence["rationale"], rationale);
let inputs = evidence["inputs"].as_array().unwrap();
assert!(inputs.iter().any(|input| input["requirements"] == SUBJECT));
assert!(
inputs
.iter()
.any(|input| input["definition"] == "terms.readiness")
);
assert!(
inputs
.iter()
.any(|input| input["file"] == "src/lib.rs" && input["item"].is_string())
);
// The record has exactly the schema's fields, and outline inputs carry
// only their file, selector, and hash, never source text.
let keys = |value: &Value| {
let mut keys: Vec<_> = value.as_object().unwrap().keys().cloned().collect();
keys.sort();
keys
};
assert_eq!(
keys(&evidence),
[
"determination",
"inputs",
"rationale",
"references",
"requirement"
]
);
for input in inputs.iter().filter(|input| input.get("item").is_some()) {
assert_eq!(keys(input), ["file", "hash", "item"], "{input}");
}
if existing_evidence {
assert_eq!(
fs::read_to_string(&fixture.evidence).unwrap(),
fixture.original
);
} else {
assert!(!fixture.project.join("evidence").exists());
}
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains(&format!("{SUBJECT}: ollama / {MODEL}")),
"{stderr}"
);
assert!(!stderr.contains("— true"), "{stderr}");
assert!(!stderr.contains(&format!("{SUBJECT}: true")), "{stderr}");
assert_eq!(
stderr.contains(&format!("{SUBJECT}: false")),
kind == "false",
"{stderr}"
);
if kind == "FIXME" {
assert!(stderr.contains("— FIXME"), "{stderr}");
}
assert_eq!(
stderr.contains(rationale),
verbose && kind == "false",
"{stderr}"
);
assert!(!stderr.contains("SECRET_REQUIREMENT_TEXT"), "{stderr}");
assert!(!stderr.contains("SECRET_DEFINITION_TEXT"), "{stderr}");
assert!(stderr.contains("Evidence: stdout\n"));
let usage_path = stderr
.lines()
.find_map(|line| line.strip_prefix("Usage: "))
.expect("stderr reports usage location");
assert!(std::path::Path::new(usage_path).is_file());
let usage = fixture.usage();
assert_eq!(usage["outcome"], "completed");
assert_eq!(usage["determination"], kind);
assert_eq!(usage["evidence_output"], "stdout");
assert_eq!(usage["evidence_written"], true);
}
}
Input 23: outline tests/authoring_cli.rs fn[missing_duplicate_and_invalid_submissions_preserve_existing_evidence]
- File:
tests/authoring_cli.rs - Selector:
fn[missing_duplicate_and_invalid_submissions_preserve_existing_evidence] - Kind:
fn tests/authoring_cli.rs:1565–1620
// {test}`requirements.authoring.submission_count`
// {test}`requirements.authoring.submission`
// {test}`requirements.authoring.usage_storage`
#[test]
fn missing_duplicate_and_invalid_submissions_preserve_existing_evidence() {
let valid =
json!({"determination":true,"rationale":"The reviewed sources support the subject."});
for calls in [
vec![],
vec![
call("one", "submit_judgment", valid.clone()),
call("two", "submit_judgment", valid),
],
vec![call(
"bad",
"submit_judgment",
json!({"determination":true,"rationale":""}),
)],
vec![call(
"empty",
"submit_judgment",
json!({"determination":{"FIXME":[]},"rationale":"No gap identified."}),
)],
] {
for stdout in [false, true] {
let count = if calls.is_empty() { 2 } else { 1 };
let server = Server::start(vec![reply(calls.clone()); count]);
let fixture = Fixture::new(&server.endpoint);
let mut args = vec!["author-evidence", SUBJECT];
if stdout {
args.push("--stdout");
}
let output = fixture.run(&args);
assert!(!output.status.success());
assert!(output.stdout.is_empty());
assert_eq!(server.finish().len(), count);
if calls.is_empty() {
assert!(String::from_utf8_lossy(&output.stderr).contains("even after a reminder"));
}
assert_eq!(
fs::read_to_string(&fixture.evidence).unwrap(),
fixture.original
);
let usage = fixture.usage();
assert_eq!(usage["outcome"], "failed");
assert_eq!(
usage["evidence_output"],
if stdout { "stdout" } else { "file" }
);
assert_eq!(usage["evidence_written"], false);
// A response without a submission is reminded once.
assert_eq!(usage["request_count"], if calls.is_empty() { 2 } else { 1 });
assert!(usage["determination"].is_null());
}
}
}
Input 24: outline tests/authoring_cli.rs fn[bedrock_cli_uses_selected_profile_region_and_converse_tools]
- File:
tests/authoring_cli.rs - Selector:
fn[bedrock_cli_uses_selected_profile_region_and_converse_tools] - Kind:
fn tests/authoring_cli.rs:1727–1920
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.initial_prompt`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.submission`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.output_limit`
#[test]
fn bedrock_cli_uses_selected_profile_region_and_converse_tools() {
for typed in [false, true] {
let mut read_call = json!({"toolUseId":"bedrock-read","name":"habeas",
"input":{"file":"extra.txt","line_start":1,"line_end":2}});
let mut submit_call = json!({"toolUseId":"bedrock-submit","name":"submit_judgment",
"input":{"determination":true,"rationale":"The supplied sources support the subject."}});
if typed {
read_call["type"] = json!("tool_use");
submit_call["type"] = json!("tool_use");
}
let first_message = json!({"role":"assistant","content":[
{"text":"Reading source."},{"toolUse":read_call}
]});
let server = Server::start(vec![
json!({
"output":{"message":first_message.clone()},
"stopReason":"tool_use",
"usage":{"inputTokens":19,"outputTokens":5,"totalTokens":24},
"metrics":{"latencyMs":1}
}),
json!({
"output":{"message":{"role":"assistant","content":[{"toolUse":submit_call}]}},
"stopReason":"tool_use",
"usage":{"inputTokens":19,"outputTokens":5,"totalTokens":24},
"metrics":{"latencyMs":1}
}),
]);
let fixture = Fixture::new(&server.endpoint);
let credentials = fixture.temp.path().join("aws-credentials");
let aws_config = fixture.temp.path().join("aws-config");
fs::write(&credentials, "[default]\naws_access_key_id = WRONG_DEFAULT_ACCESS_KEY\naws_secret_access_key = wrong-default-secret\n[habeas-test]\naws_access_key_id = FAKE_PROFILE_ACCESS_KEY\naws_secret_access_key = fake-profile-secret-for-local-test-only\n").unwrap();
fs::write(&aws_config, "[profile habeas-test]\nregion = eu-west-1\n").unwrap();
fs::write(fixture.config.join("habeas/config.toml"), "version = 1\n[authoring]\ndefault = 'cloud'\n[authoring.configs.cloud]\npolicy = 'once'\nbackend = 'bedrock'\nmodel = 'fixture-bedrock-model'\naws_profile = 'habeas-test'\nregion = 'us-west-2'\n[authoring.configs.cloud.options]\ntemperature = 0.25\nmaxTokens = 321\ntopP = 0.75\nstopSequences = ['END']\ntop_k = 12\n").unwrap();
let mut command = fixture.command();
for key in [
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_SECURITY_TOKEN",
"AWS_PROFILE",
"AWS_DEFAULT_PROFILE",
"AWS_REGION",
"AWS_DEFAULT_REGION",
"AWS_ENDPOINT_URL",
"AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",
"AWS_BEARER_TOKEN_BEDROCK",
] {
command.env_remove(key);
}
let output = command
.env("AWS_CONFIG_FILE", aws_config)
.env("AWS_SHARED_CREDENTIALS_FILE", credentials)
.env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", &server.endpoint)
.env("AWS_EC2_METADATA_DISABLED", "true")
.args(["author-evidence", SUBJECT])
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(requests.len(), 2);
assert_eq!(requests[1].body["messages"][1], first_message);
let result = &requests[1].body["messages"][2]["content"][0]["toolResult"];
assert_eq!(result["toolUseId"], "bedrock-read");
let delivered = result["content"][0]["text"].as_str().unwrap();
assert!(delivered.contains("extra.txt") && delivered.contains("context line 1"));
assert!(
requests[0]
.headers
.starts_with("POST /model/fixture-bedrock-model/converse HTTP/1.1\r\n")
);
assert!(
requests[0]
.headers
.contains("Credential=FAKE_PROFILE_ACCESS_KEY/")
);
assert!(
requests[0]
.headers
.contains("/us-west-2/bedrock/aws4_request")
);
assert!(!requests[0].headers.contains("WRONG_DEFAULT_ACCESS_KEY"));
let body = &requests[0].body;
assert_eq!(
body["inferenceConfig"],
json!({"temperature":0.25,"maxTokens":321,"topP":0.75,"stopSequences":["END"]})
);
// A configured maxTokens is used as given on every request.
assert_eq!(requests[1].body["inferenceConfig"]["maxTokens"], 321);
assert_eq!(body["additionalModelRequestFields"], json!({"top_k":12}));
let prompt = prompt_text(body);
assert!(
prompt.contains("Assess whether a project's tests adequately check")
&& prompt.contains(REQUIREMENT)
);
let tool_specs = body["toolConfig"]["tools"].as_array().unwrap();
for tool in tool_specs {
let schema = &tool["toolSpec"]["inputSchema"]["json"];
assert_eq!(schema["type"], "object");
for unsupported in ["oneOf", "allOf", "anyOf"] {
assert!(
schema.get(unsupported).is_none(),
"Bedrock rejects {unsupported} at the root of {}'s input schema",
tool["toolSpec"]["name"]
);
}
}
let habeas_schema = &tool_specs
.iter()
.find(|tool| tool["toolSpec"]["name"] == "habeas")
.unwrap()["toolSpec"]["inputSchema"]["json"];
assert_eq!(habeas_schema["additionalProperties"], false);
for field in ["file", "item", "requirements", "definition"] {
assert_eq!(habeas_schema["properties"][field]["type"], "string");
}
for field in ["line_start", "line_end"] {
assert_eq!(habeas_schema["properties"][field]["type"], "integer");
assert_eq!(habeas_schema["properties"][field]["minimum"], 1);
}
let judgment_schema = &tool_specs
.iter()
.find(|tool| tool["toolSpec"]["name"] == "submit_judgment")
.unwrap()["toolSpec"]["inputSchema"]["json"]["properties"]["determination"];
let outcomes = judgment_schema["oneOf"].as_array().unwrap();
assert!(outcomes.iter().any(|outcome| outcome["type"] == "boolean"));
let fixme = &outcomes
.iter()
.find(|outcome| outcome["type"] == "object")
.unwrap()["properties"]["FIXME"];
assert_eq!(fixme["type"], "array");
assert_eq!(fixme["minItems"], 1);
assert_eq!(fixme["items"]["type"], "string");
assert_eq!(fixme["items"]["minLength"], 1);
let mut tools = tool_specs
.iter()
.map(|tool| tool["toolSpec"]["name"].as_str().unwrap())
.collect::<Vec<_>>();
tools.sort();
assert_eq!(
tools,
[
"ast_grep",
"finish_search",
"github",
"habeas",
"list_files",
"next_page",
"outline",
"references",
"ripgrep",
"submit_judgment"
]
);
let evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(evidence["determination"], true);
assert!(
evidence["inputs"]
.as_array()
.unwrap()
.iter()
.filter(|input| input["file"] == "extra.txt")
.collect::<Vec<_>>()
== habeas::outline_inputs_for_lines(&fixture.project, "extra.txt", 1, 2)
.unwrap()
.iter()
.collect::<Vec<_>>()
);
let usage = fixture.usage();
assert_eq!(usage["backend"], "bedrock");
assert_eq!(usage["model"], "fixture-bedrock-model");
assert_eq!(usage["tokens"]["input"], 38);
assert_eq!(usage["tokens"]["output"], 10);
assert_eq!(usage["request_count"], 2);
assert_eq!(usage["tool_calls"]["habeas"], 1);
assert_eq!(usage["tool_calls"]["submit_judgment"], 1);
assert_eq!(usage["outcome"], "completed");
}
}
Input 25: outline tests/authoring_cli.rs fn[failed_evidence_write_keeps_the_accepted_judgment_in_usage]
- File:
tests/authoring_cli.rs - Selector:
fn[failed_evidence_write_keeps_the_accepted_judgment_in_usage] - Kind:
fn tests/authoring_cli.rs:2332–2366
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.usage_storage`
#[test]
fn failed_evidence_write_keeps_the_accepted_judgment_in_usage() {
let fixture = Fixture::new("http://unconfigured");
let evidence_path = fixture.evidence.clone();
let server = Server::start_with(
vec![reply(vec![call(
"submit",
"submit_judgment",
json!({
"determination":{"FIXME":["#125"]},"rationale":"The source documents the remaining gap."
}),
)])],
move || {
fs::remove_file(&evidence_path).unwrap();
fs::create_dir(&evidence_path).unwrap();
},
);
let config_path = fixture.config.join("habeas/config.toml");
let config = fs::read_to_string(&config_path)
.unwrap()
.replace("http://unconfigured", &server.endpoint);
fs::write(config_path, config).unwrap();
let output = fixture.run(&["author-evidence", SUBJECT]);
assert!(!output.status.success());
assert_eq!(server.finish().len(), 1);
assert!(fixture.evidence.is_dir());
let usage = fixture.usage();
assert_eq!(usage["outcome"], "failed");
assert_eq!(usage["determination"], "FIXME");
assert_eq!(usage["evidence_written"], false);
assert_eq!(usage["request_count"], 1);
assert_eq!(usage["requests"][0]["outcome"], "completed");
}
Input 26: outline tests/authoring_cli.rs fn[openai_responses_replays_tool_calls_and_records_usage]
- File:
tests/authoring_cli.rs - Selector:
fn[openai_responses_replays_tool_calls_and_records_usage] - Kind:
fn tests/authoring_cli.rs:5173–5284
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.cache_checkpoints`
#[test]
// {test}`requirements.authoring.usage_storage`
fn openai_responses_replays_tool_calls_and_records_usage() {
fn assert_no_checkpoints(value: &Value) {
match value {
Value::Object(fields) => {
for (key, value) in fields {
assert!(
!matches!(key.as_str(), "cachePoint" | "cache_control"),
"explicit cache checkpoint: {key}"
);
if key == "type" {
assert!(
!matches!(value.as_str(), Some("cache_point" | "cache_checkpoint")),
"explicit cache checkpoint block: {value}"
);
}
assert_no_checkpoints(value);
}
}
Value::Array(values) => {
for value in values {
assert_no_checkpoints(value);
}
}
_ => {}
}
}
let response = |id: &str, name: &str, arguments: Value| {
json!({
"id": format!("resp_{id}"), "object":"response", "status":"completed",
"model":"fixture-openai", "output":[{
"type":"function_call", "id":format!("fc_{id}"), "call_id":id,
"name":name, "arguments":arguments.to_string(), "status":"completed"
}],
"usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
"input_tokens_details":{"cached_tokens":3},
"output_tokens_details":{"reasoning_tokens":2}}
})
};
let server = Server::start(vec![
response(
"read",
"habeas",
json!({"file":"extra.txt","line_start":10}),
),
response(
"submit",
"submit_judgment",
json!({"determination":false,"rationale":"Missing implementation."}),
),
]);
let fixture = Fixture::new(&server.endpoint);
fs::write(fixture.config.join("habeas/config.toml"), format!(
"version = 1\n[authoring]\ndefault = 'mock'\n[authoring.configs.mock]\nbackend = 'openai'\nmodel = 'fixture-openai'\npolicy = 'once'\nendpoint = '{}'\napi_key_env = 'HABEAS_TEST_MODEL_KEY'\n[authoring.configs.mock.options]\nmax_output_tokens = 1024\nreasoning = {{ effort = 'low' }}\n", server.endpoint)).unwrap();
let output = fixture.run(&["author-evidence", SUBJECT]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(requests.len(), 2);
for request in &requests {
assert!(request.headers.starts_with("POST /responses HTTP/1.1\r\n"));
assert!(request.headers.contains(&format!("Bearer {AUTH}")));
assert_eq!(request.body["model"], "fixture-openai");
assert_eq!(request.body["max_output_tokens"], 1024);
assert_eq!(request.body["reasoning"]["effort"], "low");
assert_eq!(request.body["tools"].as_array().unwrap().len(), 10);
assert_no_checkpoints(&request.body);
}
assert!(
!requests[0].body["instructions"]
.as_str()
.unwrap()
.is_empty()
);
assert_eq!(
requests[0].body["instructions"],
requests[1].body["instructions"]
);
assert_eq!(requests[0].body["tools"], requests[1].body["tools"]);
let initial_input = requests[0].body["input"].as_array().unwrap();
let history = requests[1].body["input"].as_array().unwrap();
assert_eq!(history.len(), initial_input.len() + 2);
assert_eq!(&history[..initial_input.len()], initial_input.as_slice());
assert_eq!(history[initial_input.len()]["type"], "function_call");
assert_eq!(history[initial_input.len()]["call_id"], "read");
assert_eq!(
history[initial_input.len() + 1]["type"],
"function_call_output"
);
assert_eq!(history[initial_input.len() + 1]["call_id"], "read");
let usage = fixture.usage();
assert_eq!(usage["backend"], "openai");
assert_eq!(usage["outcome"], "completed");
assert_eq!(usage["request_count"], 2);
assert_eq!(usage["tokens"]["input"], 22);
assert_eq!(usage["tokens"]["output"], 14);
assert_eq!(usage["tokens"]["cached_input"], 6);
assert_eq!(usage["tokens"]["reasoning"], 4);
assert!(!usage.to_string().contains(AUTH));
}
Input 27: outline tests/authoring_cli.rs fn[adaptive_routes_fresh_assessments_and_records_each_model]
- File:
tests/authoring_cli.rs - Selector:
fn[adaptive_routes_fresh_assessments_and_records_each_model] - Kind:
fn tests/authoring_cli.rs:5361–5517
// {test}`requirements.authoring.adaptive`
// {test}`requirements.authoring.openai_defaults`
// {test}`requirements.authoring.policy`
#[test]
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.confirmation`
fn adaptive_routes_fresh_assessments_and_records_each_model() {
let response = |arguments: Value| {
json!({
"id":"resp_submit", "object":"response", "status":"completed",
"model":"mock", "output":[{
"type":"function_call", "id":"fc_submit", "call_id":"submit",
"name":"submit_judgment", "arguments":arguments.to_string(), "status":"completed"
}], "usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}
})
};
for (existing_fixme, first, policy, expected_models, reason) in [
(
false,
json!({"determination":true,"rationale":"Good."}),
"",
vec!["gpt-5.4-mini"],
None,
),
(
false,
json!({"determination":false,"rationale":"MINI_ONLY_RATIONALE_SENTINEL"}),
"",
vec!["gpt-5.4-mini", "gpt-6.1-sol"],
Some("mini_false"),
),
(
false,
json!({"determination":{"FIXME":["Gap"]},"rationale":"MINI_ONLY_RATIONALE_SENTINEL"}),
"",
vec!["gpt-5.4-mini", "gpt-6.1-sol"],
Some("mini_fixme"),
),
(
false,
json!({"bad":"submission"}),
"",
vec!["gpt-5.4-mini", "gpt-6.1-sol"],
Some("mini_assessment_failed"),
),
(
true,
json!({"determination":true,"rationale":"Good."}),
"",
vec!["gpt-6.1-sol"],
Some("existing_fixme"),
),
(
false,
json!({"determination":true,"rationale":"FIRST_AGREEMENT_RATIONALE"}),
"policy = 'confirm'\n",
vec!["gpt-5.4-mini", "gpt-5.4-mini"],
None,
),
] {
let mut replies = vec![response(first)];
if expected_models.len() == 2 {
replies.push(response(json!({"determination":true,"rationale":"Good."})));
}
let server = Server::start(replies);
let fixture = Fixture::new(&server.endpoint);
if !existing_fixme {
fs::write(fixture.project.join("src/lib.rs"), "// {impl}`requirements.ready`\npub fn ready() {}\n// {test}`requirements.ready`\nfn ready_test() {}\n// A plain FIXME is not an acknowledgment.\n").unwrap();
}
fs::write(fixture.config.join("habeas/config.toml"), format!(
"version = 1\n[authoring]\ndefault = 'api'\n[authoring.configs.api]\nbackend = 'openai'\nmodel = 'adaptive'\n{policy}endpoint = '{}'\napi_key_env = 'HABEAS_TEST_MODEL_KEY'\n[authoring.configs.api.options]\nmax_output_tokens = 8192\nreasoning = {{ effort = 'medium' }}\n", server.endpoint)).unwrap();
let output = fixture.run(&["author", SUBJECT]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(
requests
.iter()
.map(|r| r.body["model"].as_str().unwrap())
.collect::<Vec<_>>(),
expected_models
);
for request in &requests {
assert!(
request
.headers
.to_lowercase()
.contains(&format!("authorization: bearer {}", AUTH.to_lowercase()))
);
assert!(
!request
.body
.to_string()
.contains("MINI_ONLY_RATIONALE_SENTINEL")
);
assert_eq!(
request.body["input"].as_array().unwrap().len(),
1,
"fresh conversation"
);
assert_eq!(request.body["reasoning"]["effort"], "medium");
assert_eq!(request.body["max_output_tokens"], 8192);
}
let evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(evidence["determination"], true);
if !policy.is_empty() {
assert_eq!(evidence["rationale"], "FIRST_AGREEMENT_RATIONALE");
}
let logs: Vec<Value> = fs::read_dir(fixture.state.join("habeas/authoring/usage"))
.unwrap()
.map(|entry| serde_json::from_slice(&fs::read(entry.unwrap().path()).unwrap()).unwrap())
.collect();
let expected_policy = if policy.is_empty() { "once" } else { "confirm" };
assert!(
logs.iter().all(|log| log["policy"] == expected_policy),
"{logs:?}"
);
let parent = logs
.iter()
.find(|log| log["subject"] == SUBJECT && log["model"] == "adaptive")
.unwrap();
assert_eq!(parent["routing_reason"].as_str(), reason);
assert!(!parent["attempts"].as_array().unwrap().is_empty());
let actual: Vec<_> = logs
.iter()
.filter(|log| log["model"] != "adaptive")
.collect();
assert_eq!(actual.len(), expected_models.len());
let ids: std::collections::BTreeSet<_> = actual
.iter()
.map(|log| log["run_id"].as_str().unwrap())
.collect();
assert_eq!(ids.len(), actual.len());
let links: Vec<_> = logs
.iter()
.flat_map(|log| log["attempts"].as_array().into_iter().flatten())
.filter_map(Value::as_str)
.collect();
for id in ids {
assert!(
links
.iter()
.any(|path| path.ends_with(&format!("{id}.json")))
);
}
for model in expected_models {
assert!(
logs.iter()
.any(|log| log["model"] == model && log["request_count"] == 1)
);
}
}
}
Input 28: outline tests/live_bedrock.rs fn[live_bedrock_authoring]
- File:
tests/live_bedrock.rs - Selector:
fn[live_bedrock_authoring] - Kind:
fn tests/live_bedrock.rs:188–301
// {test}`requirements.integration.live_bedrock_test`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.submission`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.usage_storage`
// {impl}`requirements.integration.live_bedrock_test`
#[test]
fn live_bedrock_authoring() {
if std::env::var_os("CI").is_some() {
report("warning: skipping live Bedrock test: CI is set");
return;
}
let LiveSelection {
config: selected,
workspace,
} = selected_config()
.expect("cannot select live Bedrock configuration")
.expect("no Bedrock authoring configuration; add one to your Habeas user config (see md/reference.md), or set CI=1 to disable live testing");
let BackendConfig::Bedrock(backend) = &selected.backend else {
unreachable!("selection only returns Bedrock configurations");
};
if !credentials_available(backend) {
return;
}
report(format!(
"live Bedrock test: configuration {:?}, model {:?}",
selected.name, backend.model
));
let temp = tempfile::tempdir().unwrap();
let project = temp.path().join("project");
for directory in [project.join("md"), project.join("src")] {
fs::create_dir_all(directory).unwrap();
}
fs::write(
project.join("Cargo.toml"),
"[package]\nname = 'live-fixture'\nversion = '0.1.0'\nedition = '2024'\n",
)
.unwrap();
fs::write(project.join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
if let Some(workspace) = &workspace {
fs::write(project.join("habeas.toml"), workspace).unwrap();
}
fs::write(
project.join("md/SUMMARY.md"),
"# Summary\n\n- [Requirements](requirements.md)\n",
)
.unwrap();
fs::write(
project.join("md/requirements.md"),
format!(":::{{req}} parity\n{REQUIREMENT}\n:::\n"),
)
.unwrap();
// No citation points to this file, so assessing its implementation requires
// an additional source read instead of only the mandatory initial inputs.
fs::write(project.join("src/parity.rs"), "pub fn is_even(value: u32) -> bool {\n value % 2 == 0\n}\n\n#[test]\nfn parity_cases() {\n assert!(is_even(0));\n assert!(!is_even(1));\n assert!(is_even(2));\n assert!(!is_even(u32::MAX));\n}\n").unwrap();
let checkout_evidence = Path::new(env!("CARGO_MANIFEST_DIR")).join("evidence");
let before = evidence_snapshot(&checkout_evidence);
let output = Command::new(env!("CARGO_BIN_EXE_habeas"))
.current_dir(&project)
.args([
"author-evidence",
SUBJECT,
"--config",
&selected.name,
"--stdout",
])
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
report(&stderr);
assert!(
output.status.success(),
"live Bedrock authoring failed: {stderr}"
);
let evidence: Value = serde_json::from_slice(&output.stdout).expect("stdout is evidence JSON");
assert_eq!(evidence["requirement"], REQUIREMENT);
habeas::judgment::Judgment::from_value(&evidence["determination"]).unwrap();
assert!(!evidence["rationale"].as_str().unwrap().trim().is_empty());
assert!(
evidence["inputs"].as_array().unwrap().iter().any(|input| {
input["file"] == "src/parity.rs"
&& input["item"].is_string()
&& input["hash"].is_string()
&& input.get("text").is_none()
}),
"model must inspect the fixture's source through a read tool"
);
assert!(!project.join("evidence").exists());
assert_eq!(
evidence_snapshot(&checkout_evidence),
before,
"checkout evidence changed"
);
let usage_path = stderr
.lines()
.find_map(|line| line.strip_prefix("Usage: "))
.expect("reported usage path");
let usage: Value = serde_json::from_slice(&fs::read(usage_path).unwrap()).unwrap();
assert_eq!(usage["backend"], "bedrock");
assert_eq!(usage["model"], backend.model);
assert_eq!(usage["outcome"], "completed");
assert_eq!(usage["evidence_output"], "stdout");
assert_eq!(usage["evidence_written"], true);
assert!(usage["request_count"].as_u64().unwrap() >= 2);
assert!(usage["tool_calls"]["submit_judgment"].as_u64().unwrap() >= 1);
assert!(
usage["tool_calls"]["habeas"].as_u64().unwrap_or(0)
+ usage["tool_calls"]["ripgrep"].as_u64().unwrap_or(0)
> 0
);
}
Referenced definitions
Input 2: requirements selection requirements.configuration.state_location
requirements.configuration.state_location:md/requirements/configuration.md:46–59
:::{req} state_location
Habeas MUST store persistent per-user activity state under
`$XDG_STATE_HOME/habeas` on Unix when XDG_STATE_HOME is an absolute, nonempty path,
otherwise under `$HOME/.local/state/habeas`. On Windows it MUST use
`%LOCALAPPDATA%/habeas/state`. `HOME` and `LOCALAPPDATA` MUST likewise be
absolute, nonempty paths to be used. Features MUST use a named subdirectory under that
state root and document their record formats and locations.
State MUST persist across invocations and MUST NOT be stored in the project
repository, the configuration file, or a disposable cache directory. Habeas MUST
create the required directories when recording state. If it cannot determine or
write the state location, the operation requiring that state MUST report the
failure and MUST NOT claim that its history was recorded.
:::
Other sources
Input 1: 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.
:::