requirements.authoring.persistence
Requirements index · View definition
Requirement
After one valid judgment, the harness MUST write the subject text, submitted determination and rationale, and recorded inputs using the existing evidence 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.
Rationale
The reviewed tests cover each obligation in requirements.authoring.persistence.
Written record content. After a valid judgment, the record must hold the subject text, determination, rationale and recorded inputs in the existing schema.
stdout_emits_only_evidence_json_without_changing_project_filesasserts therequirementtext equalsREQUIREMENTand checksdeterminationandrationale.- The same test checks that the inputs contain a requirements input, a definition input and an outline input.
- It checks that the top-level keys are exactly
determination,inputs,rationale,referencesandrequirement, and that outline inputs carry onlyfile,hashanditem. ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_freechecks the written file’s determination, rationale, subject text and inputs.false_is_a_completed_assessmentandverbose_single_author_reports_only_false_rationale_without_source_inputsalso check the written file’s determination and rationale.batch_fills_evidence_preserves_current_records_and_reauthors_only_changed_inputscovers example subjects. It checks that example records carryexampleand notrequirement, and thathabeas::validate_repositoryreports no errors.
Default destination. The default run writes evidence/<subject>.json in these tests:
ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free(FIXME outcome) checks that the file it wrote is the subject’s evidence path.false_is_a_completed_assessment(false outcome) reads the written evidence file.verbose_single_author_reports_only_false_rationale_without_source_inputs(true and false outcomes) reads the written evidence file.- The batch tests check the per-subject files under the batch.
--stdout behavior.
stdout_emits_only_evidence_json_without_changing_project_filesparses all of stdout as one JSON object and asserts it ends with a newline.- It asserts that existing evidence is byte-identical to the original.
- When no evidence directory existed, it asserts none was created.
- It runs all three outcomes, with and without verbose.
explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continuesandlive_bedrock_authoringalso run--stdout. The live test asserts that noevidencedirectory appears in the project and that the checkout’s evidence is unchanged.a_denied_mandatory_input_aborts_only_its_assessmentasserts that a failed--stdoutrun emits nothing.
All three outcomes as completed assessments, with validation following the determination.
- The stdout test asserts the usage
outcomeiscompletedfor true, false and FIXME. ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_freeasserts that the FIXME record has no validation error and that the same record withfalseis rejected.false_is_a_completed_assessmentasserts that the false record is rejected with “determination is false”.verbose_single_author_reports_only_false_rationale_without_source_inputsasserts that true validates cleanly and false is rejected.
Failure and atomicity.
failed_evidence_write_keeps_the_accepted_judgment_in_usagechecks that a failed write is not reported as written.adaptive_sol_failure_is_final_and_confirm_uses_sol_verificationchecks that an invalid judgment leaves the existing evidence unchanged.cancellation_after_staging_prevents_replacement_but_preserves_committed_evidencechecks that a cancelled replacement leaves the old record and a committed one stays committed.
I found no plausible requirement-violating behavior that these tests would accept.
Inputs
Tests
Input 4: 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 5: 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 6: 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 7: 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 8: outline tests/authoring_cli.rs impl[Server]/fn[start_with]
- File:
tests/authoring_cli.rs - Selector:
impl[Server]/fn[start_with] - Kind:
fn tests/authoring_cli.rs:72–155
// {test}`requirements.authoring.persistence`
fn start_with(responses: Vec<Value>, mut before_reply: impl FnMut() + Send + 'static) -> Self {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
listener.set_nonblocking(true).unwrap();
let endpoint = format!("http://{}", listener.local_addr().unwrap());
let thread = thread::spawn(move || {
let mut requests = Vec::new();
for response in responses {
let deadline = Instant::now() + Duration::from_secs(15);
let mut stream = loop {
match listener.accept() {
Ok((stream, _)) => break stream,
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
assert!(
Instant::now() < deadline,
"model did not send the expected request"
);
thread::sleep(Duration::from_millis(5));
}
Err(error) => panic!("cannot accept mock request: {error}"),
}
};
// Accepted sockets can inherit the listener's nonblocking mode
// (macOS). Wait for request bytes using the read timeout below.
stream.set_nonblocking(false).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
let mut reader = BufReader::new(&mut stream);
let mut headers = String::new();
loop {
let mut line = String::new();
assert!(reader.read_line(&mut line).unwrap() > 0);
if line == "\r\n" {
break;
}
headers.push_str(&line);
}
let length: usize = headers
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse().unwrap())
})
.expect("request has content length");
let mut bytes = vec![0; length];
reader.read_exact(&mut bytes).unwrap();
requests.push(Request {
headers,
body: serde_json::from_slice(&bytes).unwrap(),
});
before_reply();
let mut response = response;
if response == json!({"__finish_latest_search":true}) {
let messages = requests.last().unwrap().body["messages"]
.as_array()
.unwrap();
let search = messages
.iter()
.rev()
.filter_map(|message| {
serde_json::from_str::<Value>(message["content"].as_str()?).ok()
})
.find(|result| result.get("matches").is_some())
.unwrap();
response = reply(vec![call(
"finish",
"finish_search",
json!({"search_id":search["search_id"],"used":[]}),
)]);
}
let status = response
.as_object_mut()
.and_then(|object| object.remove("__http_status"))
.and_then(|value| value.as_u64())
.unwrap_or(200);
let body = response.to_string();
write!(stream, "HTTP/1.1 {status} Mock Response\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
}
requests
});
Self { endpoint, thread }
}
Input 9: outline tests/authoring_cli.rs impl[Fixture]/fn[new]
- File:
tests/authoring_cli.rs - Selector:
impl[Fixture]/fn[new] - Kind:
fn tests/authoring_cli.rs:174–239
// {test}`requirements.authoring.persistence`
fn new(endpoint: &str) -> Self {
let temp = tempfile::tempdir().unwrap();
let project = temp.path().join("project");
let config = temp.path().join("config");
let state = temp.path().join("state");
for path in [
project.join("md"),
project.join("src"),
project.join("evidence"),
config.join("habeas"),
] {
fs::create_dir_all(path).unwrap();
}
fs::write(
project.join("Cargo.toml"),
"[package]\nname = 'fixture'\nversion = '0.1.0'\n",
)
.unwrap();
fs::write(project.join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
fs::write(
project.join("md/SUMMARY.md"),
"# Summary\n\n- [Requirements](requirements.md)\n- [Terms](terms.md)\n",
)
.unwrap();
fs::write(
project.join("md/requirements.md"),
format!(":::{{req}} ready\n{REQUIREMENT}\n:::\n"),
)
.unwrap();
fs::write(
project.join("md/terms.md"),
":::{definition} readiness\n:phrase: readiness\n\nSECRET_DEFINITION_TEXT.\n:::\n",
)
.unwrap();
fs::write(project.join("src/lib.rs"), "// {impl}`requirements.ready`\n// :::{fixme} requirements.ready\n// :github: example/app#125\n// One acknowledged gap.\n// :::\npub fn ready() {}\n// {test}`requirements.ready`\nfn ready_test() {}\n").unwrap();
fs::write(
project.join("extra.txt"),
(1..=12)
.map(|line| {
if line == 6 {
"SECRET_SOURCE_PAYLOAD needle".to_owned()
} else {
format!("context line {line}")
}
})
.collect::<Vec<_>>()
.join("\n"),
)
.unwrap();
let original = json!({"requirement":REQUIREMENT,"determination":false,
"rationale":"OLD_RATIONALE_MUST_NOT_REACH_MODEL", "inputs":[]})
.to_string();
let evidence = project.join(format!("evidence/{SUBJECT}.json"));
fs::write(&evidence, &original).unwrap();
fs::write(config.join("habeas/config.toml"), format!(
"version = 1\n[authoring]\ndefault = 'mock'\n[authoring.configs.mock]\npolicy = 'once'\nbackend = 'ollama'\nmodel = '{MODEL}'\nendpoint = '{endpoint}'\napi_key_env = 'HABEAS_TEST_MODEL_KEY'\n[authoring.configs.mock.options]\ntemperature = 0.25\nnum_ctx = 4096\nthink = false\n")).unwrap();
Self {
temp,
project,
config,
state,
evidence,
original,
}
}
Input 10: 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 11: 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 12: 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 13: outline tests/authoring_cli.rs fn[verbose_single_author_reports_only_false_rationale_without_source_inputs]
- File:
tests/authoring_cli.rs - Selector:
fn[verbose_single_author_reports_only_false_rationale_without_source_inputs] - Kind:
fn tests/authoring_cli.rs:1392–1445
// {test}`requirements.authoring.reporting`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.persistence`
#[test]
fn verbose_single_author_reports_only_false_rationale_without_source_inputs() {
for (determination, flag) in [(false, "-v"), (false, "--verbose"), (true, "-v")] {
let rationale = "REVIEW_RATIONALE_ONLY:\n\n- The captured test misses an interesting boundary.\n- Add an assertion for that boundary.";
let server = Server::start(vec![reply(vec![call(
"submit",
"submit_judgment",
json!({"determination": determination, "rationale": rationale}),
)])]);
let fixture = Fixture::new(&server.endpoint);
common::coverage_setup(&fixture.project);
let output = fixture.run(&["author", SUBJECT, flag]);
assert!(output.status.success(), "{output:?}");
assert_eq!(server.finish().len(), 1);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
stderr.contains(&format!("{SUBJECT}: false")),
!determination,
"{stderr}"
);
assert_eq!(stderr.contains(rationale), !determination, "{stderr}");
assert!(!stdout.contains(rationale), "{stdout}");
for text in [&stdout, &stderr] {
assert!(!text.contains("SECRET_REQUIREMENT_TEXT"), "{text}");
assert!(!text.contains("SECRET_DEFINITION_TEXT"), "{text}");
assert!(!text.contains("pub fn ready()"), "{text}");
assert!(!text.contains("— true"), "{text}");
assert!(!text.contains(&format!("{SUBJECT}: true")), "{text}");
}
assert!(stdout.contains("Evidence:"), "{stdout}");
assert!(stdout.contains("Usage:"), "{stdout}");
let evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(evidence["determination"], determination);
assert_eq!(evidence["rationale"], rationale);
let errors = habeas::validate_repository(&fixture.project)
.unwrap()
.errors;
assert_eq!(
errors
.iter()
.any(|error| error.contains("determination is false")),
!determination,
"{errors:?}"
);
if determination {
assert!(errors.is_empty(), "{errors:?}");
}
}
}
Input 14: 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 15: 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 16: outline tests/authoring_cli.rs fn[adaptive_sol_failure_is_final_and_confirm_uses_sol_verification]
- File:
tests/authoring_cli.rs - Selector:
fn[adaptive_sol_failure_is_final_and_confirm_uses_sol_verification] - Kind:
fn tests/authoring_cli.rs:5519–5639
// {test}`requirements.authoring.adaptive`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.policy`
#[test]
// {test}`requirements.authoring.confirmation`
fn adaptive_sol_failure_is_final_and_confirm_uses_sol_verification() {
let response = |name: &str, arguments: Value| {
json!({
"id":"resp", "object":"response", "status":"completed", "model":"mock",
"output":[{"type":"function_call", "id":"fc", "call_id":"call", "name":name,
"arguments":arguments.to_string(), "status":"completed"}],
"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}
})
};
let assert_policy = |fixture: &Fixture, expected: &str| {
for path in fs::read_dir(fixture.state.join("habeas/authoring/usage")).unwrap() {
let log: Value =
serde_json::from_slice(&fs::read(path.unwrap().path()).unwrap()).unwrap();
assert_eq!(log["policy"], expected);
}
};
let good = response(
"submit_judgment",
json!({"determination":true,"rationale":"Good."}),
);
let bad = response(
"submit_judgment",
json!({"determination":false,"rationale":"Gap."}),
);
for confirm in [false, true] {
let replies = if confirm {
vec![
good.clone(),
bad.clone(),
bad.clone(),
response(
"submit_verification",
json!({
"real":false,"acknowledged":false,"acknowledgments":[],"rationale":"No real gap."}),
),
]
} else {
vec![
bad.clone(),
response("submit_judgment", json!({"invalid":true})),
]
};
let server = Server::start(replies);
let fixture = Fixture::new(&server.endpoint);
fs::write(fixture.project.join("src/lib.rs"), "// {impl}`requirements.ready`\npub fn ready() {}\n// {test}`requirements.ready`\nfn ready_test() {}\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'\nendpoint = '{}'\napi_key_env = 'HABEAS_TEST_MODEL_KEY'\n", server.endpoint)).unwrap();
let output = if confirm {
fixture.run(&["author", SUBJECT, "--policy", "confirm"])
} else {
fixture.run(&["author", SUBJECT])
};
let requests = server.finish();
assert_policy(&fixture, if confirm { "confirm" } else { "once" });
let models: Vec<_> = requests
.iter()
.map(|r| r.body["model"].as_str().unwrap())
.collect();
if confirm {
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
models,
["gpt-5.4-mini", "gpt-5.4-mini", "gpt-6.1-sol", "gpt-6.1-sol"]
);
let evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(evidence["determination"], true);
assert!(
evidence["rationale"]
.as_str()
.unwrap()
.contains("assessments disagreed")
);
} else {
assert!(!output.status.success());
assert_eq!(models, ["gpt-5.4-mini", "gpt-6.1-sol"]);
assert_eq!(
fs::read_to_string(&fixture.evidence).unwrap(),
fixture.original
);
}
}
for policy in ["once", "confirm"] {
let server = Server::start(vec![
response(
"submit_judgment",
json!({"determination":false,"rationale":"Mini found a gap."}),
),
response(
"submit_judgment",
json!({"determination":false,"rationale":"Sol confirms the gap."}),
),
]);
let fixture = Fixture::new(&server.endpoint);
configure_adaptive_fixture(&fixture, &server.endpoint);
let output = fixture.run(&["author", SUBJECT, "--policy", policy]);
assert!(output.status.success(), "{output:?}");
assert_policy(&fixture, policy);
let requests = server.finish();
assert_eq!(
requests
.iter()
.map(|request| request.body["model"].as_str().unwrap())
.collect::<Vec<_>>(),
["gpt-5.4-mini", "gpt-6.1-sol"]
);
let evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(evidence["determination"], false);
assert_eq!(evidence["rationale"], "Sol confirms the gap.");
}
}
Input 17: 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.ci.schema
requirements.ci.schema:md/requirements/ci.md:11–13
:::{req} schema
A requirement or example evidence file at `evidence/<full-name>.json` MUST be a JSON object with exactly `requirement` or `example`, `determination`, `rationale`, `references`, and `inputs`. `references` MUST be the reference-set digest defined by {cite}`requirements.ci.reference_set`. The definition text and rationale MUST be nonempty strings, `determination` MUST use one of the outcomes defined by {cite}`requirements.ci.outcomes`, and `inputs` MUST be an array. Every evidence input MUST have exactly one of three forms: an outline input with `file`, `item`, and `hash`; a requirements input with `requirements`, `matches`, and `text`; or a definition input with `definition` and `text`. File paths MUST resolve to permitted inputs under {cite}`requirements.ci.input_containment`. Project-local paths SHOULD be recorded relative to the project for portability; absolute and parent-relative paths MAY be used when their resolved targets are permitted. `matches` MUST be an array of distinct full definition names, `hash` MUST be a lowercase hexadecimal SHA-256 digest, and `text` MUST be a nonempty array of strings. Evidence MUST NOT store source text for outline inputs.
:::
Input 3: requirements selection requirements.ci.determination
requirements.ci.determination:md/requirements/ci.md:19–21
:::{req} determination
For requirement and example evidence, both `true` and `FIXME` MUST satisfy the determination check in `habeas::validate()`. A false determination MUST fail validation and be reported with its rationale. Each definition's determination MUST be checked on its own; a false determination MUST NOT fail the definitions it implements, tests, or cites. All other evidence checks MUST still pass: FIXME MUST NOT excuse malformed, missing, or stale evidence or uncovered references. Validation MUST check the recorded outcome, schema, input freshness, and reference coverage without inference or reassessing whether a source comment adequately acknowledges a gap.
:::
Other sources
Input 1: 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`.
:::