requirements.authoring.github_reads
Requirements index · View definition
Requirement
The harness MUST expose a
githubtool with this interface:github({ issue: String }) -> Issue Issue { reference: String, state: "open" | "closed", title: String, body: String }
issueMUST have the form<owner>/<repo>#<number>. The tool MUST read the issue or pull request through the GitHub API, authenticating with theGITHUB_TOKENenvironment variable when that is set, and MUST return its body redacted under. GitHub reads cannot be reproduced later, so their results MUST NOT be recorded as evidence inputs and MUST NOT make evidence stale. Every GitHub read by Habeas, including this tool’s, the lookups below, and those of
, MUST go through one cache under the state root of
, keyed by issue, and MUST reuse a cached result less than one hour old instead of contacting GitHub. A malformed reference, a missing issue, or a failed request MUST return an explanatory tool error.
When the mandatory inputs contain a
{fixme}reference under, or the initial request includes one under
, the harness MUST look up the state of each issue its
:github:lines name in the same way and MUST supply each state with the corresponding source input or acknowledgment asopenorclosed; when GitHub cannot be reached, the issue MUST be assumed open. These states MUST NOT be recorded either. Instead,habeas statusandhabeas authorMUST treat a recorded FIXME determination as stale, exactly as if one of its inputs had changed, when an issue that one of its acknowledging{fixme}references names, or for a site review the{fixme}references inside the site, is closed or does not exist; repository validation, which never contacts GitHub, MUST NOT.The harness MAY take the GitHub API base URL from
HABEAS_GITHUB_API_URL, accepting onlyhttp://127.0.0.1:<port>, so that tests can use a local server.
Rationale
The reviewed tests adequately cover requirements.authoring.github_reads. I judged adequacy from the requirement text and the supplied tests and did not request implementation source. Obligations map to tests as follows.
- Tool interface and result shape
src/github.rs#mod[tests]/fn[the_tool_reads_issues_with_the_token_and_redacts_bodies]assertsreference,state,titleandbodyfrom a local fake GitHub server.src/authoring/tools.rs#mod[tests]/fn[a_successful_github_read_records_no_evidence_inputs]does the same throughdispatch.src/authoring/tools.rs#mod[tests]/fn[additional_read_flow_searches_outlines_and_reads_a_rust_file]checks that arguments other than exactly anissuestring are rejected.
- Reference form and tool errors
- The same
the_tool_reads_issues...test covers the malformed referencesexample/queueand#7. It also covers a missing issue (404, “does not exist”), a failed request (HTTP 500) and an unreachable endpoint (“cannot read GitHub issue”). Each case asserts an explanatory error. additional_read_flow_searches_outlines_and_reads_a_rust_filerepeats the malformed-reference and failed-read cases through the dispatcher.
- The same
GITHUB_TOKENauthenticationthe_tool_reads_issues...asserts that the request head containsBearer TEST_TOKEN.tests/authoring_batch.rs#fn[closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed]setsGITHUB_TOKENin the environment and asserts that theauthorization: bearerheader reaches the server.
- Body redaction:
the_tool_reads_issues...plants aghp_token in the issue body and asserts the returned body is redacted. It also asserts the cached file does not contain the token. - Not evidence inputs and no staleness:
a_successful_github_read_records_no_evidence_inputsassertsdelivery.inputsis empty and the recorded inputs are unchanged.closing_an_acknowledged_issue...andollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_freeassert thatgithub_issuesstates appear in neither evidence nor usage records. - One cache under the state root, keyed by issue, one-hour reuse
src/github.rs#mod[tests]/fn[results_are_cached_by_issue_for_an_hour_and_failures_are_not]checks that definitive results are reused (request counts stay flat) and that failures are retried and not cached.- The same test checks that an entry an hour old is re-read, that a fresh entry is reused, and that an entry from another endpoint is re-read.
closing_an_acknowledged_issue...checks that the cache file.../github/example+queue+125.jsonexists under the state root. It also checks that status lookups reuse the cached open state after the fake server flips to closed. After the cache file is deleted, the next lookup performs one new read.src/github.rs#mod[tests]/fn[cache_write_failures_are_reported_instead_of_returning_uncached_success]covers a cache write failure.
- FIXME issue states supplied with inputs and acknowledgments
inputs_containing_fixmes_carry_their_issue_stateschecks the per-input states, including that an input with no FIXME gets none. It also checks that offline reads are assumed open.tests/authoring_batch.rs#fn[initial_acknowledgments_supply_closed_and_missing_issue_states_without_source]checks that closed and missing issues are supplied asclosedin the initial prompt without the containing source.ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_freechecks that an unreachable GitHub yieldsopen.
- Stale determination when an issue is closed or missing; validation does not contact GitHub
closed_and_missing_issues_fail_their_fixmes_items_and_acknowledged_recordscovers closed and missing issues. It asserts that the stale error appears on the record and that inspection reads no issues (github.count() == 0).- The same test covers offline and unreachable issues, which add nothing.
closing_an_acknowledged_issue...checkshabeas status, thenhabeas authorreassessing tofalse. It also asserts thatvalidate_repositoryaccepts the record without making a new request.a_closed_issue_of_a_fixme_inside_a_site_makes_only_its_site_review_stalecovers the site-review variant. It asserts that only the site review goes stale and the requirement’s record does not.
HABEAS_GITHUB_API_URLrestriction:only_loopback_api_urls_with_a_port_are_acceptedtests accepted and rejected forms, although the clause is a MAY.
The cited requirements (redaction, state_location, fixme_issues, roles, fixme_inputs) are context, and their own tests were not reassessed here. The test helpers FakeGithub, start, count and issue are reached from marked tests.
I found no unaddressed gap. The one thin spot is that no test asserts the absence of an Authorization header when no token is set, but the text only requires authentication “when set”.
Inputs
Tests
Input 7: outline src/authoring/tools.rs mod[tests]/fn[a_successful_github_read_records_no_evidence_inputs]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[a_successful_github_read_records_no_evidence_inputs] - Kind:
fn src/authoring/tools.rs:1315–1349
// {test}`requirements.authoring.github_reads`
#[test]
fn a_successful_github_read_records_no_evidence_inputs() {
use std::io::{BufRead, BufReader, Write};
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let endpoint = format!("http://{}", listener.local_addr().unwrap());
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(&mut stream);
let mut line = String::new();
while reader.read_line(&mut line).unwrap() > 0 && line != "\r\n" {
line.clear();
}
let body =
json!({"state":"open","title":"Queue capacity","body":"Details."}).to_string();
write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
.unwrap();
});
let root = project();
let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
sources.github = crate::github::GithubIssues::with_api(endpoint, None, None);
let before = sources.recorded_inputs().to_vec();
let delivery = dispatch(&sources, "github", &json!({"issue": "example/queue#7"})).unwrap();
server.join().unwrap();
assert_eq!(delivery.result["reference"], "example/queue#7");
assert_eq!(delivery.result["state"], "open");
assert_eq!(delivery.result["body"], "Details.");
assert!(delivery.inputs.is_empty());
sources.record_inputs(&delivery.inputs);
assert_eq!(sources.recorded_inputs(), before.as_slice());
}
Input 8: outline src/authoring/tools.rs mod[tests]/fn[additional_read_flow_searches_outlines_and_reads_a_rust_file]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[additional_read_flow_searches_outlines_and_reads_a_rust_file] - Kind:
fn src/authoring/tools.rs:1351–1495
// {test}`requirements.authoring.additional_read`
// {test}`requirements.authoring.github_reads`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.read_denial`
#[test]
fn additional_read_flow_searches_outlines_and_reads_a_rust_file() {
let root = project();
fs::write(
root.path().join("md/terms.md"),
":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
)
.unwrap();
fs::write(
root.path().join("src/lib.rs"),
format!(
"// {}\nfn work() {{}}\n\nfn other() {{}}\n",
role("term", "terms.value")
),
)
.unwrap();
let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
for arguments in [json!({}), json!({"issue": 7})] {
let error = dispatch(&sources, "github", &arguments).err().unwrap();
assert!(
error
.to_string()
.contains("github expects exactly an issue field"),
"{error}"
);
}
// GitHub reads return tool errors here, since unit tests never contact
// GitHub, and are never evidence inputs.
for (issue, message) in [
("example/app#1", "cannot read GitHub issue example/app#1"),
("example/app", "is not an issue reference"),
] {
let error = dispatch(&sources, "github", &json!({ "issue": issue }))
.err()
.unwrap();
assert!(error.to_string().contains(message), "{error}");
}
let directories = dispatch(&sources, "list_files", &json!({})).unwrap();
let directory = directories
.result
.as_array()
.unwrap()
.iter()
.find(|entry| entry["path"] == "src")
.unwrap();
assert_eq!(directory["kind"], "directory");
assert!(directories.inputs.is_empty());
// The listing finds the directory's file and records nothing.
let listing = dispatch(&sources, "list_files", &json!({"path":directory["path"]})).unwrap();
assert_eq!(listing.result, json!([{"path":"src/lib.rs","kind":"file"}]));
assert!(listing.inputs.is_empty());
// Searching the Rust file returns the innermost item containing the match.
let search = dispatch(
&sources,
"ripgrep",
&json!({"path":"src/lib.rs","pattern":"work","context":0}),
)
.unwrap();
// It only locates the item: nothing is recorded and no definitions
// accompany it.
assert!(search.inputs.is_empty());
assert_eq!(
search.result["matches"],
json!([{
"file": "src/lib.rs", "item": "fn[work]", "kind": "fn", "tag":"1",
"lines": [{"text": "fn work() {}", "matched": true}],
}])
);
// Outlining it lists its items without content and records nothing.
let outline = dispatch(&sources, "outline", &json!({"file":"src/lib.rs"})).unwrap();
assert!(outline.inputs.is_empty());
let items = outline
.result
.get("entries")
.unwrap_or(&outline.result)
.as_array()
.unwrap()
.iter()
.map(|entry| entry["item"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(items, ["fn[work]", "fn[other]"]);
assert!(!outline.result.to_string().contains("fn other()"));
// Reading one item by selector returns it with its terminology.
let item = dispatch(
&sources,
"habeas",
&json!({"file":"src/lib.rs","item":"fn[work]"}),
)
.unwrap();
assert_eq!(item.result["input"]["item"], "fn[work]");
assert!(
item.result["input"]["text"]
.as_array()
.unwrap()
.iter()
.any(|line| line == "fn work() {}")
);
assert_eq!(item.result["definitions"].as_array().unwrap().len(), 1);
assert_eq!(item.result["definitions"][0]["definition"], "terms.value");
assert!(
item.inputs
.iter()
.any(|input| input["definition"] == "terms.value")
);
assert_eq!(item.inputs.len(), 2);
sources.record_inputs(&item.inputs);
assert!(sources.recorded_inputs().contains(
&crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[work]").unwrap()
));
assert_eq!(sources.recorded_inputs().len(), 2);
// A line range without line_end reads through EOF.
let eof = dispatch(
&sources,
"habeas",
&json!({"file":"src/lib.rs","line_start":2}),
)
.unwrap();
let covered = eof.result["inputs"]
.as_array()
.unwrap()
.iter()
.map(|input| input["item"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(covered, ["fn[work]", "fn[other]"]);
sources.record_inputs(&eof.inputs);
let recorded = sources.recorded_inputs();
for item in ["fn[work]", "fn[other]"] {
assert!(
recorded.contains(
&crate::inputs::outline_input(root.path(), "src/lib.rs", item).unwrap()
),
"{item} recorded: {recorded:?}"
);
}
assert!(
recorded
.iter()
.any(|input| input["definition"] == "terms.value"),
"terminology recorded: {recorded:?}"
);
}
Input 9: outline src/github.rs mod[tests]/struct[FakeGithub]
- File:
src/github.rs - Selector:
mod[tests]/struct[FakeGithub] - Kind:
struct src/github.rs:736–742
/// A local stand-in for the GitHub API: each request's path selects a
/// status and JSON body, and the request heads are kept.
// {test}`requirements.authoring.github_reads`
struct FakeGithub {
endpoint: String,
requests: Arc<Mutex<Vec<String>>>,
}
Input 10: outline src/github.rs mod[tests]/impl[FakeGithub]/fn[start]
- File:
src/github.rs - Selector:
mod[tests]/impl[FakeGithub]/fn[start] - Kind:
fn src/github.rs:745–781
// {test}`requirements.authoring.github_reads`
fn start(answers: &[(&str, u16, Value)]) -> Self {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let endpoint = format!("http://{}", listener.local_addr().unwrap());
let answers = answers
.iter()
.map(|(path, status, body)| ((*path).to_owned(), (*status, body.to_string())))
.collect::<BTreeMap<_, _>>();
let requests = Arc::new(Mutex::new(Vec::new()));
let seen = Arc::clone(&requests);
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { return };
let mut head = String::new();
let mut reader = BufReader::new(&mut stream);
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
break;
}
head.push_str(&line);
}
let path = head.split_whitespace().nth(1).unwrap_or("").to_owned();
seen.lock().unwrap().push(head);
let (status, body) = answers
.get(&path)
.cloned()
.unwrap_or((404, "{}".to_owned()));
let _ = write!(
stream,
"HTTP/1.1 {status} Fixture\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
}
});
Self { endpoint, requests }
}
Input 11: outline src/github.rs mod[tests]/impl[FakeGithub]/fn[count]
- File:
src/github.rs - Selector:
mod[tests]/impl[FakeGithub]/fn[count] - Kind:
fn src/github.rs:783–786
// {test}`requirements.authoring.github_reads`
fn count(&self) -> usize {
self.requests.lock().unwrap().len()
}
Input 12: outline src/github.rs mod[tests]/fn[issue]
- File:
src/github.rs - Selector:
mod[tests]/fn[issue] - Kind:
fn src/github.rs:789–792
// {test}`requirements.authoring.github_reads`
fn issue(state: &str, body: &str) -> Value {
json!({"state": state, "title": "Queue capacity", "body": body})
}
Input 13: outline src/github.rs mod[tests]/fn[only_loopback_api_urls_with_a_port_are_accepted]
- File:
src/github.rs - Selector:
mod[tests]/fn[only_loopback_api_urls_with_a_port_are_accepted] - Kind:
fn src/github.rs:794–821
// {test}`requirements.authoring.github_reads`
#[test]
fn only_loopback_api_urls_with_a_port_are_accepted() {
for url in [
"http://127.0.0.1:8080",
"http://127.0.0.1:1/",
"http://127.0.0.1:65535",
] {
assert!(is_loopback_api_url(url), "{url} should be accepted");
}
for url in [
"https://api.github.com",
"http://example.com:8080",
"https://127.0.0.1:8080",
"http://localhost:8080",
"http://127.0.0.1",
"http://127.0.0.1:",
"http://127.0.0.1:0",
"http://127.0.0.1:abc",
"http://127.0.0.1:65536",
"http://127.0.0.1:+80",
"http://127.0.0.1:80/api",
"http://127.0.0.1:80@evil.example/",
"http://127.0.0.10:80",
] {
assert!(!is_loopback_api_url(url), "{url} should be ignored");
}
}
Input 14: outline src/github.rs mod[tests]/fn[the_tool_reads_issues_with_the_token_and_redacts_bodies]
- File:
src/github.rs - Selector:
mod[tests]/fn[the_tool_reads_issues_with_the_token_and_redacts_bodies] - Kind:
fn src/github.rs:823–880
// {test}`requirements.authoring.github_reads`
// {test}`requirements.authoring.redaction`
#[test]
fn the_tool_reads_issues_with_the_token_and_redacts_bodies() {
let token = ["ghp_", "abcdefghijklmnopqrstuvwxyz0123456789"].concat();
let github = FakeGithub::start(&[
(
"/repos/example/queue/issues/125",
200,
issue("closed", &format!("Leaked {token} here.")),
),
("/repos/example/queue/issues/7", 200, issue("open", "")),
("/repos/example/queue/issues/500", 500, json!({})),
]);
let cache = tempfile::tempdir().unwrap();
let issues = GithubIssues::with_api(
github.endpoint.clone(),
Some(cache.path().to_owned()),
Some("TEST_TOKEN".to_owned()),
);
let read = tool(&issues, &json!({"issue": "example/queue#125"})).unwrap();
assert_eq!(read["reference"], "example/queue#125");
assert_eq!(read["state"], "closed");
assert_eq!(read["title"], "Queue capacity");
let body = read["body"].as_str().unwrap();
assert!(
!body.contains(&token) && body.contains("[REDACTED"),
"{body}"
);
let head = github.requests.lock().unwrap()[0].clone();
assert!(
head.starts_with("GET /repos/example/queue/issues/125 "),
"{head}"
);
assert!(head.contains("Bearer TEST_TOKEN"), "{head}");
// The cache keeps only redacted text.
let cached = fs::read_to_string(cache.path().join("example+queue+125.json")).unwrap();
assert!(!cached.contains(&token), "{cached}");
assert_eq!(
tool(&issues, &json!({"issue": "example/queue#7"})).unwrap()["state"],
"open"
);
for (arguments, message) in [
(json!({"issue": "example/queue"}), "not an issue reference"),
(json!({"issue": "#7"}), "not an issue reference"),
(json!({"issue": "o/r#1", "extra": 1}), "exactly an issue"),
(json!({"issue": "example/queue#404"}), "does not exist"),
(json!({"issue": "example/queue#500"}), "HTTP 500"),
] {
let error = tool(&issues, &arguments).unwrap_err();
assert!(error.contains(message), "{arguments}: {error}");
}
let unreachable = GithubIssues::with_api("http://127.0.0.1:9".to_owned(), None, None);
let error = tool(&unreachable, &json!({"issue": "example/queue#1"})).unwrap_err();
assert!(error.contains("cannot read GitHub issue"), "{error}");
assert_eq!(unreachable.read("example/queue#1").state(), "open");
}
Input 15: outline src/github.rs mod[tests]/fn[results_are_cached_by_issue_for_an_hour_and_failures_are_not]
- File:
src/github.rs - Selector:
mod[tests]/fn[results_are_cached_by_issue_for_an_hour_and_failures_are_not] - Kind:
fn src/github.rs:882–919
// {test}`requirements.authoring.github_reads`
// {test}`requirements.configuration.state_location`
#[test]
fn results_are_cached_by_issue_for_an_hour_and_failures_are_not() {
let github = FakeGithub::start(&[
("/repos/o/r/issues/1", 200, issue("open", "")),
("/repos/o/r/issues/3", 503, json!({})),
]);
let cache = tempfile::tempdir().unwrap();
let issues =
GithubIssues::with_api(github.endpoint.clone(), Some(cache.path().to_owned()), None);
let reads = issues.read_all(["o/r#1".to_owned(), "o/r#2".to_owned(), "o/r#3".to_owned()]);
assert_eq!(reads["o/r#1"].state(), "open");
assert_eq!(reads["o/r#2"], IssueRead::Missing);
assert!(matches!(reads["o/r#3"], IssueRead::Failed(_)));
assert_eq!(github.count(), 3);
// Definitive results are reused; the failure is retried.
let again = issues.read_all(["o/r#1".to_owned(), "o/r#2".to_owned(), "o/r#3".to_owned()]);
assert_eq!(again["o/r#1"], reads["o/r#1"]);
assert_eq!(again["o/r#2"], IssueRead::Missing);
assert_eq!(github.count(), 4);
assert!(!cache.path().join("o+r+3.json").exists());
// An entry an hour old, or from another endpoint, is read again.
let path = cache.path().join("o+r+1.json");
let mut entry: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
entry["fetched"] = json!(entry["fetched"].as_u64().unwrap() - 3600);
fs::write(&path, entry.to_string()).unwrap();
issues.read("o/r#1");
assert_eq!(github.count(), 5);
issues.read("o/r#1");
assert_eq!(github.count(), 5);
let other = FakeGithub::start(&[]);
let moved =
GithubIssues::with_api(other.endpoint.clone(), Some(cache.path().to_owned()), None);
assert_eq!(moved.read("o/r#1"), IssueRead::Missing);
assert_eq!(other.count(), 1);
}
Input 16: outline src/github.rs mod[tests]/fn[a_closed_issue_of_a_fixme_inside_a_site_makes_only_its_site_review_stale]
- File:
src/github.rs - Selector:
mod[tests]/fn[a_closed_issue_of_a_fixme_inside_a_site_makes_only_its_site_review_stale] - Kind:
fn src/github.rs:921–962
// {test}`requirements.authoring.github_reads`
// {test}`requirements.references.site_review`
#[test]
fn a_closed_issue_of_a_fixme_inside_a_site_makes_only_its_site_review_stale() {
let github = FakeGithub::start(&[("/repos/o/r/issues/1", 200, issue("closed", ""))]);
let source = crate::sites::tests::SOURCE.replace(
"fn check_two() {}",
"fn check_two() {\n // :::{fixme} requirements.rule\n // :github: o/r#1\n // Panics.\n // :::\n}",
);
let temp = crate::sites::tests::project(crate::sites::tests::RULE, &source);
let root = temp.path();
crate::sites::tests::write_review(
root,
"fn[check_two]",
json!({"determination": {"FIXME": ["o/r#1"]}}),
);
fs::write(
root.join("evidence/requirements.rule.json"),
json!({"determination": {"FIXME": ["o/r#1"]}}).to_string(),
)
.unwrap();
let mut inspection = crate::evidence::inspect_repository(root).unwrap();
let before = inspection.report.errors.len();
add_issue_findings(
&mut inspection,
&GithubIssues::with_api(github.endpoint.clone(), None, None),
);
let added = inspection.report.errors[before..].to_vec();
let review = crate::sites::review_path("requirements.rule", "src/lib.rs", "fn[check_two]");
assert!(
added.contains(&format!(
"{review}: stale: issue o/r#1, named by the {{fixme}} to requirements.rule inside the site at src/lib.rs:3, is closed; reassess the review"
)),
"{added:#?}"
);
assert!(
!added
.iter()
.any(|error| error.starts_with("evidence/requirements.rule.json")),
"{added:#?}"
);
}
Input 17: outline src/github.rs mod[tests]/fn[closed_and_missing_issues_fail_their_fixmes_items_and_acknowledged_records]
- File:
src/github.rs - Selector:
mod[tests]/fn[closed_and_missing_issues_fail_their_fixmes_items_and_acknowledged_records] - Kind:
fn src/github.rs:1000–1065
// {test}`requirements.cli.fixme_issues`
// {test}`requirements.authoring.github_reads`
#[test]
fn closed_and_missing_issues_fail_their_fixmes_items_and_acknowledged_records() {
let github = FakeGithub::start(&[
("/repos/o/r/issues/1", 200, issue("closed", "")),
("/repos/o/r/issues/2", 200, issue("open", "")),
]);
let temp = project();
let chapter = temp.path().join("md/rules.md");
let mut text = fs::read_to_string(&chapter).unwrap();
text.push_str(
"\n::::{example} unfinished\nGiven ready, it succeeds. {cite}`rules.ready`\n\n:::{fixme}\n:github: o/r#3\nThe example is untested.\n:::\n::::\n",
);
fs::write(&chapter, text).unwrap();
let mut inspection = crate::evidence::inspect_repository(temp.path()).unwrap();
let before = inspection.report.errors.clone();
assert_eq!(github.count(), 0, "inspection reads no issues");
let issues = GithubIssues::with_api(github.endpoint.clone(), None, None);
add_issue_findings(&mut inspection, &issues);
let added = inspection.report.errors[before.len()..].to_vec();
for expected in [
"src/lib.rs:1: {fixme} names o/r#1, which is closed",
"src/lib.rs:6: fn ready fails: its {fixme} at line 1 names o/r#1, which is closed",
"md/rules.md:6: {fixme} names o/r#3, which does not exist",
"md/rules.md:3: requirement rules.ready fails: its {fixme} at line 6 names o/r#3, which does not exist",
"evidence/rules.ready.json: stale: issue o/r#1, named by the acknowledging {fixme} to rules.ready at src/lib.rs:1, is closed; reassess the record",
] {
assert!(
added.iter().any(|error| error == expected),
"{expected}\n{added:#?}"
);
}
assert!(
added.iter().any(
|error| error.contains("example rules.unfinished fails: its {fixme}")
&& error.contains("o/r#3, which does not exist")
),
"{added:#?}"
);
assert_eq!(added.len(), 7, "{added:#?}");
assert!(!added.iter().any(|error| error.contains("o/r#2")));
let missing = FakeGithub::start(&[]);
let mut missing_inspection = crate::evidence::inspect_repository(temp.path()).unwrap();
add_issue_findings(
&mut missing_inspection,
&GithubIssues::with_api(missing.endpoint.clone(), None, None),
);
assert!(
missing_inspection.report.errors.iter().any(|error| error
.contains("evidence/rules.ready.json: stale: issue o/r#1")
&& error.contains("does not exist")),
"{:?}",
missing_inspection.report.errors
);
// Unreachable issues count as open, and nothing is added.
let mut inspection = crate::evidence::inspect_repository(temp.path()).unwrap();
add_issue_findings(&mut inspection, &GithubIssues::offline());
assert_eq!(inspection.report.errors, before);
let mut inspection = crate::evidence::inspect_repository(temp.path()).unwrap();
let unreachable = GithubIssues::with_api("http://127.0.0.1:9".to_owned(), None, None);
add_issue_findings(&mut inspection, &unreachable);
assert_eq!(inspection.report.errors, before);
}
Input 18: outline src/github.rs mod[tests]/fn[cache_write_failures_are_reported_instead_of_returning_uncached_success]
- File:
src/github.rs - Selector:
mod[tests]/fn[cache_write_failures_are_reported_instead_of_returning_uncached_success] - Kind:
fn src/github.rs:1067–1083
// {test}`requirements.authoring.github_reads`
// {test}`requirements.configuration.state_location`
#[test]
fn cache_write_failures_are_reported_instead_of_returning_uncached_success() {
let github = FakeGithub::start(&[("/repos/o/r/issues/1", 200, issue("open", ""))]);
let state = tempfile::tempdir().unwrap();
let blocked = state.path().join("github");
fs::write(&blocked, "not a directory").unwrap();
let issues = GithubIssues::with_api(github.endpoint.clone(), Some(blocked.clone()), None);
let result = issues.read("o/r#1");
assert!(
matches!(result, IssueRead::Failed(ref message) if message.contains("cannot record GitHub cache")),
"{result:?}"
);
assert_eq!(github.count(), 1);
assert_eq!(fs::read_to_string(blocked).unwrap(), "not a directory");
}
Input 19: outline src/github.rs mod[tests]/fn[inputs_containing_fixmes_carry_their_issue_states]
- File:
src/github.rs - Selector:
mod[tests]/fn[inputs_containing_fixmes_carry_their_issue_states] - Kind:
fn src/github.rs:1085–1129
// {test}`requirements.authoring.github_reads`
#[test]
fn inputs_containing_fixmes_carry_their_issue_states() {
let github = FakeGithub::start(&[
("/repos/o/r/issues/1", 200, issue("closed", "")),
("/repos/o/r/issues/2", 200, issue("open", "")),
]);
let temp = project();
let root = fs::canonicalize(temp.path()).unwrap();
let mut errors = Vec::new();
let references = crate::evidence::collect_references(&root, &mut errors);
let definitions = crate::evidence::load_definitions(&root).unwrap();
let inputs = [
json!({"file": "src/lib.rs", "item": "fn[ready]"}),
json!({"file": "src/lib.rs", "item": "fn[other]"}),
json!({"requirements": "rules.ready", "matches": ["rules.ready"]}),
json!({"requirements": "rules.other", "matches": ["rules.other"]}),
];
let issues = GithubIssues::with_api(github.endpoint.clone(), None, None);
let states = input_issue_states(&root, &issues, &references, &definitions, &inputs);
let owned = |pairs: &[(&str, &'static str)]| {
pairs
.iter()
.map(|(issue, state)| ((*issue).to_owned(), *state))
.collect::<Vec<_>>()
};
assert_eq!(
states,
[
owned(&[("o/r#1", "closed"), ("o/r#2", "open")]),
owned(&[("o/r#2", "open")]),
owned(&[("o/r#3", "closed")]),
Vec::new(),
]
);
// Offline, every named issue is assumed open.
let offline = input_issue_states(
&root,
&GithubIssues::offline(),
&references,
&definitions,
&inputs,
);
assert_eq!(offline[0], owned(&[("o/r#1", "open"), ("o/r#2", "open")]));
}
Input 20: outline tests/authoring_batch.rs struct[FakeGithub]
- File:
tests/authoring_batch.rs - Selector:
struct[FakeGithub] - Kind:
struct tests/authoring_batch.rs:2277–2286
/// A local stand-in for the GitHub API serving one issue,
/// `example/queue#125`, whose state a test can change; other issues do not
/// exist.
// {test}`requirements.authoring.github_reads`
struct FakeGithub {
endpoint: String,
state: Arc<Mutex<&'static str>>,
requests: Arc<Mutex<usize>>,
headers: Arc<Mutex<Vec<String>>>,
}
Input 21: outline tests/authoring_batch.rs impl[FakeGithub]/fn[start]
- File:
tests/authoring_batch.rs - Selector:
impl[FakeGithub]/fn[start] - Kind:
fn tests/authoring_batch.rs:2289–2338
// {test}`requirements.authoring.github_reads`
fn start() -> Self {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let endpoint = format!("http://{}", listener.local_addr().unwrap());
let state = Arc::new(Mutex::new("open"));
let requests = Arc::new(Mutex::new(0));
let headers = Arc::new(Mutex::new(Vec::new()));
let served_headers = headers.clone();
let (served_state, served) = (state.clone(), requests.clone());
thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { return };
let mut reader = BufReader::new(&mut stream);
let mut request = String::new();
reader.read_line(&mut request).unwrap();
let mut request_headers = String::new();
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
break;
}
request_headers.push_str(&line);
}
served_headers.lock().unwrap().push(request_headers);
*served.lock().unwrap() += 1;
let (status, body) = if request.starts_with("GET /repos/example/queue/issues/125 ")
{
let state = *served_state.lock().unwrap();
(
"200 OK",
json!({"state": state, "title": "Zero capacity", "body": ""}),
)
} else {
("404 Not Found", json!({"message": "Not Found"}))
};
let body = body.to_string();
let _ = write!(
stream,
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
}
});
Self {
endpoint,
state,
requests,
headers,
}
}
Input 22: outline tests/authoring_batch.rs fn[initial_acknowledgments_supply_closed_and_missing_issue_states_without_source]
- File:
tests/authoring_batch.rs - Selector:
fn[initial_acknowledgments_supply_closed_and_missing_issue_states_without_source] - Kind:
fn tests/authoring_batch.rs:2346–2382
// {test}`requirements.authoring.fixme_inputs`
// {test}`requirements.authoring.github_reads`
#[test]
fn initial_acknowledgments_supply_closed_and_missing_issue_states_without_source() {
let server = Server::start(false, None);
let github = FakeGithub::start();
*github.state.lock().unwrap() = "closed";
let fixture = Fixture::new(&server.endpoint, None);
let source = fixture.project.join("src/lib.rs");
fs::write(&source, fs::read_to_string(&source).unwrap().replace(
"pub fn beta()",
"// :::{fixme} requirements.beta\n// :github: example/queue#125\n// :github: example/queue#404\n// Boundary cases are untested.\n// :::\npub fn beta()",
)).unwrap();
let output = fixture
.command()
.env("HABEAS_GITHUB_API_URL", &github.endpoint)
.args(["author", "requirements.beta"])
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
let state = server.requests.0.lock().unwrap();
let request = &state.conversations[0].1;
let user = request["messages"]
.as_array()
.unwrap()
.iter()
.find(|m| m["role"] == "user")
.unwrap()["content"]
.as_str()
.unwrap();
for issue in ["example/queue#125", "example/queue#404"] {
let expected = format!("\"reference\": \"{issue}\",\n \"state\": \"closed\"");
assert!(user.contains(&expected), "{user}");
}
assert!(user.contains("Boundary cases are untested."), "{user}");
assert!(!user.contains("pub fn beta()"), "{user}");
}
Input 23: outline tests/authoring_batch.rs fn[closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed]
- File:
tests/authoring_batch.rs - Selector:
fn[closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed] - Kind:
fn tests/authoring_batch.rs:2384–2483
// {test}`requirements.ci.fixme_closed_issue`
// {test}`requirements.cli.fixme_issues`
// {test}`requirements.authoring.github_reads`
// {test}`requirements.authoring.batch`
// {test}`requirements.ci.outcomes`
// {test}`requirements.configuration.state_location`
#[test]
fn closing_an_acknowledged_issue_makes_the_fixme_record_stale_and_reassessed() {
let server = Server::start_with(false, Behavior::ClosedIssueIsFalse);
let github = FakeGithub::start();
let fixture = Fixture::new(&server.endpoint, None);
let source = fixture.project.join("src/lib.rs");
fs::write(
&source,
fs::read_to_string(&source).unwrap().replace(
"pub fn beta()",
"// :::{fixme} requirements.beta\n// :github: example/queue#125\n// Zero capacity is untested.\n// :::\npub fn beta()",
),
)
.unwrap();
let run = |args: &[&str]| {
let output = fixture
.command()
.env("HABEAS_GITHUB_API_URL", &github.endpoint)
.env("GITHUB_TOKEN", "TEST_GITHUB_TOKEN")
.args(args)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout).unwrap()
};
run(&["author", "--all"]);
assert!(github.headers.lock().unwrap().iter().any(|headers| {
headers
.to_ascii_lowercase()
.contains("authorization: bearer test_github_token\r\n")
}));
assert_eq!(server.subjects().len(), 6);
// The issue was open, so record the acknowledged gap as current FIXME
// evidence.
let mut beta = fixture.evidence("requirements.beta");
beta["determination"] = json!({"FIXME": ["example/queue#125"]});
fs::write(
fixture.project.join("evidence/requirements.beta.json"),
serde_json::to_vec_pretty(&beta).unwrap(),
)
.unwrap();
let cache = fixture.state.join(if cfg!(windows) {
"habeas/state/github/example+queue+125.json"
} else {
"habeas/github/example+queue+125.json"
});
assert!(
cache.exists(),
"GitHub reads are cached under the state root"
);
let status = run(&["status"]);
assert!(!status.contains("stale"), "{status}");
let reads = github.requests();
*github.state.lock().unwrap() = "closed";
// The cached open state is reused for an hour.
assert!(!run(&["status"]).contains("stale"));
assert_eq!(github.requests(), reads);
fs::remove_file(&cache).unwrap();
let status = run(&["status"]);
assert_eq!(github.requests(), reads + 1);
let row = status
.lines()
.find(|line| line.starts_with("| `requirements.beta`"))
.unwrap_or_else(|| panic!("{status}"));
assert!(row.contains("Invalid"), "{status}");
for expected in [
"evidence/requirements.beta.json: stale: issue example/queue#125, named by the acknowledging {fixme} to requirements.beta at src/lib.rs:5, is closed",
"src/lib.rs:5: {fixme} names example/queue#125, which is closed",
"src/lib.rs:9: fn beta fails: its {fixme} at line 5 names example/queue#125, which is closed",
] {
assert!(status.contains(expected), "{expected}\n{status}");
}
// Repository validation, which does not contact GitHub, still accepts it.
let report = habeas::validate_repository(&fixture.project).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert_eq!(github.requests(), reads + 1);
run(&["author", "--all"]);
let subjects = server.subjects();
assert_eq!(subjects.len(), 7, "{subjects:?}");
assert_eq!(subjects[6], "requirement requirements.beta");
let beta = fixture.evidence("requirements.beta");
assert_eq!(beta["determination"], json!(false), "{beta}");
// Issue states are supplied with inputs but never recorded.
assert!(!beta.to_string().contains("github_issues"), "{beta}");
for run in fixture.usage() {
assert!(!run.to_string().contains("github_issues"), "{run}");
}
}
Input 24: 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()
);
}
Referenced definitions
Input 2: requirements selection requirements.authoring.redaction
requirements.authoring.redaction:md/requirements/authoring.md:1795–1817
:::{req} redaction
Every source text the harness supplies to a model, including mandatory inputs,
`habeas` reads, and `ripgrep` results, and every source text Habeas displays in
the book or `habeas info`, MUST be redacted:
1. In a workspace `habeas.toml` or user configuration file, the value of every
explicit credential field defined by {cite}`requirements.authoring.credentials`
MUST be replaced. Such a file that is not valid TOML MUST be replaced whole,
with `configuration` as the kind, because its fields cannot be located.
2. In every source, each match of a built-in rule of the `secretshape` crate MUST
be replaced. The replaced region MUST be extended through each adjacent region
that the crate's entropy heuristic flags and that only whitespace separates
from the region, repeating until no flagged region is adjacent. The heuristic
MUST NOT cause redaction on its own.
A replacement MUST read `[REDACTED:<kind>]`, where `<kind>` is the credential
field or the rule's name, and MUST keep every line break within the replaced
text, so line numbers are unchanged. Outlines MUST be built from the original
source, and the structural hash MUST hash each text piece that overlaps a
redacted region in its redacted form, so evidence never depends on a credential's
value and redaction never changes or breaks a file's outline. The `secretshape` version MUST be pinned exactly; upgrading
it MAY change redaction and hashes and MUST be treated as a deliberate change.
:::
Input 3: requirements selection requirements.cli.fixme_issues
requirements.cli.fixme_issues:md/requirements/cli.md:40–50
:::{req} fixme_issues
`habeas status` MUST look up, under {cite}`requirements.authoring.github_reads`,
every issue that a `:github:` option line of a named or unnamed `{fixme}` under
{cite}`requirements.references.roles` names, and MUST report each `{fixme}`
naming an issue that is closed or does not exist as an error, with its file and
line and the issue. It MUST also report the item that contains that `{fixme}` as
failing: the outline node containing it, or the requirement or example
declaration whose body contains it, in the same way it reports an uncovered
Rust item. When GitHub cannot be reached, the issue MUST be assumed open.
Repository validation MUST NOT contact GitHub.
:::
Input 4: 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.
:::
Input 5: requirements selection requirements.references.roles
requirements.references.roles:md/requirements/references.md:3–49
:::{req} roles
Project text files MAY use the `{impl}`, `{cite}`, and `{test}` roles with a backtick-delimited full requirement or example name, or with a built-in name under {cite}`requirements.references.builtin_definitions`, and MAY use the `{fixme}` role in fenced form. A reference MAY instead be written in fenced form, `:::{role} name` on one line, a body, and a closing fence, following the fence rules of {cite}`requirements.ci.span` and {cite}`requirements.ci.fence_lengths`; the fenced form is the same edge with attached commentary, and the inline form carries none. In a source comment, fence lines MUST be recognized after removing each line's comment delimiters within one comment run under {cite}`requirements.references.outline_comments`, and a fence that does not close within its comment run MUST be a validation error. Each reference is a directed edge between its source and the named definition. A source is a project source item or a requirement or example declaration. The roles MUST mean:
- `{cite}`: the source relies on, supports, or refers to the definition. It is an
edge from the source to the definition.
- `{impl}`: the source implements part of the definition: it makes a decision,
performs a check, produces an output, or handles a case that the definition
specifies. A requirement MAY implement part of another requirement by refining
one of its obligations. Calling code that implements a definition, or
producing a result a caller uses to meet it, MUST NOT by itself count as
implementing it. A check MUST count only if the definition states it, or the
source could not meet one of the definition's obligations without it; source
that checks it is consistent with a definition, such as recognizing a form the
definition specifies in order to decide whether to run other behavior, relies
on that definition and calls for `{cite}`. A requirement stating a convention
for every output of a kind, such as every validation error, is implemented by
the source that carries out the convention as a whole, such as the step that
collects and reports those outputs.
- `{test}`: the source is designed to verify behavior the definition specifies:
a test through its scenario and the assertions about that scenario's outcome,
or a named example through the concrete case it describes.
- `{fixme}`: the source acknowledges a known gap in fulfilling the definition. It
MUST use the fenced form, and its body MUST describe the gap. The body MAY
begin with option lines naming issues that track the gap, one per line, in the
form `:github: <owner>/<repo>#<number>`, such as
`:github: rust-lang/rust#123`. `github` MUST be the only recognized option.
A named `{fixme}` MAY appear only in sources outside the book. Validation MUST report
any other option line, a `:github:` value not in that form, an inline
`{fixme}`, a `{fixme}` in a requirement or example declaration, and a
`{fixme}` whose body, without option lines and comment delimiters, is empty.
An unnamed `{fixme}`, a fence of `:::{fixme}` with no name, MAY appear in any
project text, including a requirement or example body, to tie that place to
the issues it names. It MUST have at least one `:github:` option line and MAY
have a description; it is not a reference edge, acknowledges no gap, needs no
coverage, and does not count as a reference for Rust item coverage. Its
issues are checked under {cite}`requirements.cli.fixme_issues`.
`{impl}`, `{test}`, and `{fixme}` are edges from the definition to the source.
Only requirements and examples are assessed; code is reviewed as part of the
definitions it implements or tests.
```text
{impl}`requirements.references.roles`
{cite}`requirements.references.roles`
{test}`requirements.references.roles`
```
:::
Input 6: requirements selection requirements.authoring.fixme_inputs
requirements.authoring.fixme_inputs:md/requirements/authoring.md:1305–1345
:::{req} fixme_inputs
For a requirement or example assessment, the initial request MUST include every
valid named `{fixme}` reference to the subject found under
{cite}`requirements.references.discovery`, except a reference inside one of
the subject's sites under {cite}`requirements.references.site_review`, in this
form:
```text
Acknowledgment {
file: String,
item: String,
body: String,
issues: Array<{ reference: String, state: "open" | "closed" }>,
}
```
`file` and `item` MUST locate the containing source by project-relative path and
outline selector, using `<root>` for a whole file. `body` MUST contain the
reference's complete fenced commentary without its fences or source-comment
delimiters, including its option lines, redacted under
{cite}`requirements.authoring.redaction`. `issues` MUST give every distinct issue
its `:github:` lines name, in their order, with state supplied under
{cite}`requirements.authoring.github_reads`. Acknowledgments MUST be ordered by
file and position in the file and MUST carry no line numbers or containing
implementation source.
The locations and bodies MUST be protected against staleness by the reference-set
digest under {cite}`requirements.ci.reference_set`; the acknowledgment MUST NOT
create an outline input merely to cover its containing source. Actual reads of
that source MUST still be recorded under
{cite}`requirements.authoring.delivered_inputs`. Sources MUST satisfy
{cite}`requirements.authoring.source_tools`; an inaccessible acknowledgment
MUST be reported before inference.
Terminology definitions referenced by an acknowledgment's body MUST contribute
their complete, transitive declarations to the mandatory input set under
{cite}`requirements.definitions.authoring_inputs` and MUST be recorded as
definition inputs. Only the acknowledgment's body MUST contribute these
dependencies; its containing implementation source MUST NOT be supplied merely
to discover them.
:::
Other sources
Input 1: requirements selection requirements.authoring.github_reads
requirements.authoring.github_reads:md/requirements/authoring.md:1091–1122
:::{req} github_reads
The harness MUST expose a `github` tool with this interface:
```text
github({ issue: String }) -> Issue
Issue { reference: String, state: "open" | "closed", title: String, body: String }
```
`issue` MUST have the form `<owner>/<repo>#<number>`. The tool MUST read the issue
or pull request through the GitHub API, authenticating with the `GITHUB_TOKEN`
environment variable when that is set, and MUST return its body redacted under
{cite}`requirements.authoring.redaction`. GitHub reads cannot be reproduced
later, so their results MUST NOT be recorded as evidence inputs and MUST NOT
make evidence stale. Every GitHub read by Habeas, including this tool's, the
lookups below, and those of {cite}`requirements.cli.fixme_issues`, MUST go
through one cache under the state root of
{cite}`requirements.configuration.state_location`, keyed by issue, and MUST
reuse a cached result less than one hour old instead of contacting GitHub. A malformed reference, a missing issue, or a failed request
MUST return an explanatory tool error.
When the mandatory inputs contain a `{fixme}` reference under
{cite}`requirements.references.roles`, or the initial request includes one under
{cite}`requirements.authoring.fixme_inputs`, the harness MUST look up the state of
each issue its `:github:` lines name in the same way and MUST supply each state
with the corresponding source input or acknowledgment as `open` or `closed`;
when GitHub cannot be reached, the issue MUST be assumed open. These states MUST
NOT be recorded either. Instead, `habeas status` and `habeas author` MUST treat a recorded FIXME determination as stale, exactly as if one of its inputs had changed, when an issue that one of its acknowledging `{fixme}` references names, or for a site review the `{fixme}` references inside the site, is closed or does not exist; repository validation, which never contacts GitHub, MUST NOT.
The harness MAY take the GitHub API base URL from `HABEAS_GITHUB_API_URL`,
accepting only `http://127.0.0.1:<port>`, so that tests can use a local server.
:::