requirements.index.detail_format
Requirements index · View definition
Requirement
Each evidence detail page MUST display its state as a Shields.io static badge image with meaningful alt text and the current requirement or example body as a Markdown block quote labeled by kind. It MUST render the recorded rationale as Markdown in a Rationale section and display the recorded FIXME strings when the determination is FIXME. Inputs MUST be grouped under headings in this order, each input appearing once, in the first group that applies to it: Implementation, for sources reached by an
{impl}edge from the definition, including anchored files; Tests, for sources reached by a{test}edge, including tests, examples, and anchored files; Referenced definitions, for declarations the definition cites and their terminology; and Other sources, for the remaining inputs the assessment consulted. Edges MUST be determined from the current references underand
. Each group and each input MUST be a collapsible disclosure element, with groups expanded and inputs collapsed by default, so readers can move between groups and open individual sources. Each input MUST have its own subsection identifying its selector. An outline input MUST show its file, selector, kind, and current inclusive line range. A requirements input MUST show its selection and each matched definition’s full name, file, and inclusive line range. Each outline input subsection MUST show the node’s current source text in a fenced code block and say when its hash no longer matches; a requirements or definition input subsection MUST show its recorded text. Code fences MUST request Rust highlighting for
.rsfiles and language-aware highlighting for Markdown, JSON, TOML, Java, JavaScript, TypeScript, and Python files; TOML MAY use INI highlighting when native TOML highlighting is unavailable.
Rationale
The reviewed tests cover each obligation in requirements.index.detail_format.
State badge and alt text
index_shows_evidence_states_and_links_generated_chaptersanddetail_page_renders_markdown_and_highlighted_input_sectionsassert the Shields.io evidence badge for the Valid state.detail_page_shows_recorded_text_locations_and_first_matching_groupasserts the alt textevidence Invalid.valid_fixme_remains_visible_in_status_info_and_bookintests/outcomes.rsasserts theevidence-FIXMEbadge.
Current body as a labelled block quote
- The page shows a
## Requirementheading followed by a multi-line>quote of the current text, and the stale recorded text is absent. index_lists_examples_and_links_their_detail_pagesasserts## Examplefollowed by the quoted body, so the kind label is checked for examples too.
Rationale and FIXME strings
- Rationale is rendered as Markdown under
## Rationale: the test asserts the bold text. - The FIXME section is checked in
valid_fixme_remains_visible_in_status_info_and_book. The record has determinationFIXMEwith two strings, and the page shows## FIXME referencesandrust-lang/rust#123. - That test does not assert the other entry (
example/io#125) on the detail page.render_detail_sectionsjoins allfixme_entriesin one block with no conditional, so I treat this as a minor weakness rather than a gap.
Group order, each input once, and edges
detail_inputs_are_grouped_by_current_edges_in_disclosuresrecords eight inputs in a scrambled order and asserts each lands in the correct group:- Implementation: an
{impl}source edge and an:impl:anchor. - Tests: a
{test}source edge, a:test:anchor, and an example’s{test}edge. - Referenced definitions: a cited definition.
- Other sources: the remaining inputs.
- Implementation: an
- It asserts the headings appear in the required order.
detail_page_shows_recorded_text_locations_and_first_matching_groupshows a source with both{impl}and{test}edges appears once, in Implementation, with no Tests group.- The same test places a
{term}-referenced definition under Referenced definitions.
Disclosures
- The grouping test counts four open group
<details>elements, eight collapsed input<details>elements, and twelve closing tags.
Input subsections
- An outline input shows its file, selector, kind and inclusive range, with the current source in a fence. The hash-mismatch message appears exactly once for one changed input among several.
- A whole-file input shows
Kind: file. - A requirements input shows its selection, each match’s name, file and inclusive range, then the recorded text.
- A definition input shows its name, location and recorded text.
- An unresolved selector is reported and its recorded text kept.
Highlighting
.rsfiles getrust,noplayground,.mdfiles getmarkdown(with a longer fence when the content has a fence), and.tomlfiles getini.common_input_extensions_select_highlighting_languagescheckscode_languagefor Markdown, JSON, TOML (ini), Java, JavaScript, TypeScript and Python.
Because detail_page_renders_markdown_and_highlighted_input_sections shows the page using this mapping, I accept the mapping test for the languages the page test does not render. No obligation is untested, and the assertions enforce the required outcomes.
Inputs
Implementation
Input 13: outline src/index.rs fn[render_detail_sections]
- File:
src/index.rs - Selector:
fn[render_detail_sections] - Kind:
fn src/index.rs:706–811
// {impl}`requirements.index.detail_format`
// {impl}`requirements.index.invalid_detail`
// {impl}`requirements.index.state`
// {impl}`requirements.examples.index`
// {impl}`requirements.authoring.redaction`
fn render_detail_sections(
mut content: String,
name: &str,
definition_text: &str,
kind: DefinitionKind,
detail_evidence: DetailEvidence<'_>,
sources: &RenderSources<'_>,
) -> String {
content.push_str(&shield_badge(
"evidence",
detail_evidence.state.label(),
detail_evidence.state.color(),
));
content.push_str(&format!(
"\n\n## {}\n\n",
if kind == DefinitionKind::Example {
"Example"
} else {
"Requirement"
}
));
for line in crate::redaction::redact_text(definition_text).lines() {
content.push_str("> ");
content.push_str(line);
content.push('\n');
}
if !detail_evidence.errors.is_empty() {
content.push_str("\n## Validation findings\n\n<pre><code>");
content.push_str(&escape_html(&crate::redaction::redact_text(
&detail_evidence.errors.join("\n\n"),
)));
content.push_str("</code></pre>\n");
}
let parsed = detail_evidence
.record
.and_then(|record| serde_json::from_str::<Value>(record).ok());
let evidence = parsed.as_ref().and_then(Value::as_object);
content.push_str("\n## Rationale\n\n");
match evidence
.and_then(|evidence| evidence.get("rationale"))
.and_then(Value::as_str)
{
Some(rationale) if !rationale.trim().is_empty() => content.push_str(rationale.trim()),
_ => content.push_str("No rationale recorded."),
}
if !detail_evidence.fixme_entries.is_empty() {
content.push_str("\n\n## FIXME references\n\n<pre><code>");
content.push_str(&escape_html(&detail_evidence.fixme_entries.join("\n")));
content.push_str("</code></pre>\n");
}
content.push_str("\n\n## Inputs\n\n");
match evidence
.and_then(|evidence| evidence.get("inputs"))
.and_then(Value::as_array)
{
Some(inputs) if !inputs.is_empty() => {
let edges = DefinitionEdges::current(name, sources);
let mut grouped: BTreeMap<InputGroup, Vec<(usize, &Value, InputLocation)>> =
BTreeMap::new();
for (index, input) in inputs.iter().enumerate() {
let location = InputLocation::resolve(input, sources);
let group = edges.group(
sources.root,
location.selector.as_ref(),
match &location.ranges {
Some(Ok(ranges)) => ranges,
_ => &[],
},
);
grouped
.entry(group)
.or_default()
.push((index + 1, input, location));
}
for group in InputGroup::ALL {
let Some(inputs) = grouped.get(&group) else {
continue;
};
content.push_str(&format!(
"<details class=\"habeas-input-group\" open>\n<summary><h3 id=\"{}\" style=\"display: inline\">{}</h3></summary>\n\n",
group.id(),
group.heading()
));
for (index, input, location) in inputs {
render_input(&mut content, *index, input, location, sources);
}
content.push_str("</details>\n\n");
}
}
_ => content.push_str("No inputs recorded.\n"),
}
if evidence.is_none()
&& let Some(record) = detail_evidence.record
{
content.push_str("\n## Unreadable evidence record\n\n");
push_code_block(&mut content, &crate::redaction::redact_text(record), "json");
}
content
}
Tests
Input 4: outline src/index.rs mod[tests]/fn[index_shows_evidence_states_and_links_generated_chapters]
- File:
src/index.rs - Selector:
mod[tests]/fn[index_shows_evidence_states_and_links_generated_chapters] - Kind:
fn src/index.rs:1101–1306
// {test}`requirements.index.chapter`
// {test}`requirements.index.state`
// {test}`requirements.index.navigation`
// {test}`requirements.index.source_links`
// {test}`requirements.cli.shared_status_rendering`
// {test}`requirements.index.detail_format`
// {test}`requirements.index.invalid_detail`
// {test}`requirements.test-coverage.index`
// {test}`requirements.index.detail_pages`
#[test]
fn index_shows_evidence_states_and_links_generated_chapters() {
let temp = TempDir::new().unwrap();
fs::create_dir_all(temp.path().join("md/requirements")).unwrap();
fs::create_dir_all(temp.path().join("evidence")).unwrap();
fs::create_dir_all(temp.path().join("src")).unwrap();
fs::write(temp.path().join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
let requirements = [
("ready", "Ready MUST work."),
("pending", "Pending MUST work."),
("changed", "Changed MUST work."),
("absent", "Absent MUST work."),
("uncovered", "Uncovered MUST work."),
];
let mut source = String::from("# Requirements\n\n");
for (name, body) in requirements {
source.push_str(&format!(":::{{req}} {name}\n{body}\n:::\n\n"));
}
fs::write(temp.path().join("md/requirements/core.md"), &source).unwrap();
fs::write(
temp.path().join("src/main.rs"),
"// {test}`requirements.core.uncovered`\n",
)
.unwrap();
for (name, body, determination) in [
("ready", "Ready MUST work.", true),
("pending", "Pending MUST work.", false),
("changed", "Old requirement.", true),
("uncovered", "Uncovered MUST work.", true),
] {
fs::write(
temp.path()
.join(format!("evidence/requirements.core.{name}.json")),
json!({
"requirement": body,
"determination": determination,
"rationale": "The fixture records the evidence state.",
"inputs": []
})
.to_string(),
)
.unwrap();
}
let mut book = Book::new();
let mut definition_chapter =
Chapter::new("Requirements", source, "requirements/core.md", Vec::new());
definition_chapter.number = Some(SectionNumber::new(vec![3]));
book.push_item(definition_chapter);
let mut index_chapter = Chapter::new(
"Requirements index",
"# Requirements index\n\n:::{requirements-index}\n:::\n".to_owned(),
"appendix/requirements-index.md",
Vec::new(),
);
index_chapter.number = Some(SectionNumber::new(vec![4]));
book.push_item(index_chapter);
crate::evidence::tests::stamp_reference_sets(temp.path());
preprocess_book(&mut book, temp.path()).unwrap();
let definition = book.chapters().next().unwrap();
assert!(definition.content.contains(
"id=\"habeas-req-requirements.core.ready\" href=\"#habeas-req-requirements.core.ready\""
));
let index = book
.chapters()
.find(|chapter| chapter.name == "Requirements index")
.unwrap();
assert!(!index.content.contains("{requirements-index}"));
for (name, state) in [
("ready", "Valid"),
("pending", "Determination false"),
("changed", "Invalid"),
("absent", "Missing"),
("uncovered", "Invalid"),
] {
let link = format!(
"| [`requirements.core.{name}`](requirements-index/requirements.core.{name}.html)"
);
let row = index
.content
.lines()
.find(|line| line.starts_with(&link))
.unwrap_or_else(|| panic!("missing {link} in:\n{}", index.content));
assert_eq!(row.split('|').nth(2).unwrap().trim(), state);
}
let table = index
.content
.lines()
.skip_while(|line| !line.starts_with("| "))
.take_while(|line| line.starts_with("| "))
.collect::<Vec<_>>();
let pipes = table[0]
.match_indices('|')
.map(|(position, _)| position)
.collect::<Vec<_>>();
assert_eq!(pipes.len(), 3);
assert!(table.iter().all(|line| {
line.match_indices('|')
.map(|(position, _)| position)
.collect::<Vec<_>>()
== pipes
}));
for column in 0..2 {
let widest = table
.iter()
.map(|line| line.split('|').nth(column + 1).unwrap().trim().len())
.max()
.unwrap();
assert_eq!(pipes[column + 1] - pipes[column] - 3, widest);
}
assert!(definition.sub_items.is_empty());
assert_eq!(index.sub_items.len(), 6);
let coverage = index
.sub_items
.iter()
.filter_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "Coverage gaps" => Some(chapter),
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(coverage.len(), 1);
assert_eq!(
coverage[0].path.as_deref(),
Some(Path::new("appendix/requirements-index/coverage.md"))
);
assert_eq!(coverage[0].parent_names, ["Requirements index"]);
assert!(
index
.content
.contains("[Coverage gaps](requirements-index/coverage.html)")
);
let ready = index
.sub_items
.iter()
.find_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "requirements.core.ready" => {
Some(chapter)
}
_ => None,
})
.unwrap();
assert_eq!(
ready.source_path.as_deref(),
Some(Path::new("../evidence/requirements.core.ready.json"))
);
assert_eq!(
ready.number.as_deref().map(Vec::as_slice),
Some(&[4, 2][..])
);
assert_eq!(
ready.path.as_deref(),
Some(Path::new(
"appendix/requirements-index/requirements.core.ready.md"
))
);
assert!(ready.content.contains(
"[View definition](../../requirements/core.html#habeas-req-requirements.core.ready)"
));
assert!(
ready
.content
.contains("[Requirements index](../requirements-index.html) · [View definition]")
);
assert!(
ready
.content
.contains("img.shields.io/badge/evidence-Valid-237346")
);
assert!(ready.content.contains("> Ready MUST work."));
assert!(!ready.content.contains("## Evidence record"));
let changed = index
.sub_items
.iter()
.find_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "requirements.core.changed" => {
Some(chapter)
}
_ => None,
})
.unwrap();
assert!(changed.content.contains("requirement text changed"));
let absent = index
.sub_items
.iter()
.find_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "requirements.core.absent" => {
Some(chapter)
}
_ => None,
})
.unwrap();
assert_eq!(
absent.source_path.as_deref(),
Some(Path::new("requirements/core.md"))
);
}
Input 5: outline src/index.rs mod[tests]/fn[detail_pages_and_info_display_redacted_source]
- File:
src/index.rs - Selector:
mod[tests]/fn[detail_pages_and_info_display_redacted_source] - Kind:
fn src/index.rs:1341–1461
// {test}`requirements.authoring.redaction`
// {test}`requirements.index.detail_format`
// {test}`requirements.cli.info`
#[test]
fn detail_pages_and_info_display_redacted_source() {
let token = crate::redaction::tests::github_token();
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
fs::create_dir_all(root.join("src")).unwrap();
fs::create_dir_all(root.join("md")).unwrap();
fs::create_dir_all(root.join("evidence")).unwrap();
fs::write(root.join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
fs::write(
root.join("md/requirements.md"),
format!(":::{{req}} ready\nTokens such as {token} MUST be hidden.\n:::\n"),
)
.unwrap();
fs::write(
root.join("src/main.rs"),
format!("fn main() {{\n println!(\"{token}\");\n}}\n"),
)
.unwrap();
fs::write(
root.join("habeas.toml"),
"version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 'plain ollama key'\n",
)
.unwrap();
let record = json!({
"requirement": format!("Tokens such as {token} MUST be hidden."),
"determination": true,
"rationale": "Checked.",
"inputs": [
crate::inputs::outline_input(root, "src/main.rs", "fn[main]").unwrap(),
crate::inputs::outline_input(root, "habeas.toml", "").unwrap(),
{"requirements": "requirements.ready", "matches": ["requirements.ready"], "text": [format!("Tokens such as {token} MUST be hidden.")]},
]
});
fs::write(
root.join("evidence/requirements.ready.json"),
record.to_string(),
)
.unwrap();
let definition = Definition {
path: Path::new("requirements.md").to_path_buf(),
text: format!("Tokens such as {token} MUST be hidden."),
kind: DefinitionKind::Requirement,
};
let record = record.to_string();
let page = render_detail_page(
"requirements.ready",
Path::new("appendix/requirements-index/requirements.ready.md"),
None,
&definition,
DetailEvidence {
state: EvidenceState::Valid,
record: Some(&record),
errors: &[],
fixme_entries: &[],
},
&RenderSources {
root,
definitions: &BTreeMap::new(),
references: &[],
source_links: None,
outlines: &crate::inputs::OutlineCache::default(),
},
);
let info = crate::commands::info_markdown(root, "requirements.ready").unwrap();
for page in [page, info] {
assert!(!page.contains(&token), "{page}");
assert!(!page.contains("plain ollama key"), "{page}");
assert!(
page.contains("Tokens such as [REDACTED:GitHub Token] MUST be hidden."),
"{page}"
);
assert!(
page.contains(" println!(\"[REDACTED:GitHub Token]\");"),
"{page}"
);
assert!(page.contains("api_key = '[REDACTED:api_key]'"), "{page}");
}
// Validation findings, an unresolved input shown as raw JSON, and an
// unreadable record are redacted too.
let unresolved = json!({
"requirement": "Ready.",
"determination": true,
"rationale": "Checked.",
"inputs": [{"file": "src/gone.rs", "item": "fn[gone]", "hash": token}],
})
.to_string();
let unreadable = format!("{{broken {token}");
let errors = [format!("evidence/requirements.ready.json: saw {token}")];
for (record, shown) in [
(&unresolved, "\"hash\": \"[REDACTED:GitHub Token]\""),
(&unreadable, "{broken [REDACTED:GitHub Token]"),
] {
let page = render_detail_page(
"requirements.ready",
Path::new("appendix/requirements-index/requirements.ready.md"),
None,
&definition,
DetailEvidence {
state: EvidenceState::Invalid,
record: Some(record),
errors: &errors,
fixme_entries: &[],
},
&RenderSources {
root,
definitions: &BTreeMap::new(),
references: &[],
source_links: None,
outlines: &crate::inputs::OutlineCache::default(),
},
);
assert!(!page.contains(&token), "{page}");
assert!(page.contains("saw [REDACTED:GitHub Token]"), "{page}");
assert!(page.contains(shown), "{page}");
}
}
Input 6: outline src/index.rs mod[tests]/fn[detail_page_renders_markdown_and_highlighted_input_sections]
- File:
src/index.rs - Selector:
mod[tests]/fn[detail_page_renders_markdown_and_highlighted_input_sections] - Kind:
fn src/index.rs:1463–1549
// {test}`requirements.index.detail_format`
#[test]
fn detail_page_renders_markdown_and_highlighted_input_sections() {
let definition = Definition {
path: Path::new("requirements/core.md").to_path_buf(),
text: "Ready MUST work.\n\n## Example\n\nUse the CLI.".to_owned(),
kind: DefinitionKind::Requirement,
};
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
fs::create_dir_all(root.join("src")).unwrap();
fs::create_dir_all(root.join("md")).unwrap();
fs::write(
root.join("src/main.rs"),
"// lead\nfn main() {\n println!(\"ready\");\n}\n",
)
.unwrap();
fs::write(root.join("md/notes.md"), "```rust\nfn x() {}\n```\n").unwrap();
fs::write(root.join("book.toml"), "[book]\n").unwrap();
let record = json!({
"requirement": "Stale text.",
"determination": true,
"rationale": "**Checked** against the source.\n\n- First check\n- Second check",
"inputs": [
crate::inputs::outline_input(root, "src/main.rs", "fn[main]").unwrap(),
crate::inputs::outline_input(root, "md/notes.md", "").unwrap(),
crate::inputs::outline_input(root, "book.toml", "").unwrap(),
]
})
.to_string();
// The page shows the current source, flagging a changed hash.
fs::write(
root.join("src/main.rs"),
"// lead\nfn main() {\n println!(\"changed\");\n}\n",
)
.unwrap();
let page = render_detail_page(
"requirements.core.ready",
Path::new("appendix/requirements-index/requirements.core.ready.md"),
Some(Path::new("appendix/requirements-index.md")),
&definition,
DetailEvidence {
state: EvidenceState::Valid,
record: Some(&record),
errors: &[],
fixme_entries: &[],
},
&RenderSources {
root,
definitions: &BTreeMap::new(),
references: &[],
source_links: None,
outlines: &crate::inputs::OutlineCache::default(),
},
);
assert!(page.contains("img.shields.io/badge/evidence-Valid-237346"));
assert!(page.contains("## Requirement\n\n> Ready MUST work.\n> \n> ## Example"));
assert!(page.contains("## Rationale\n\n**Checked** against the source."));
assert!(page.contains(
"<summary id=\"habeas-input-1\"><strong>Input 1</strong>: <code>outline src/main.rs fn[main]</code></summary>"
));
assert!(page.contains(
"- File: <code>src/main.rs</code>\n- Selector: <code>fn[main]</code>\n- Kind: <code>fn</code>\n- <code>src/main.rs:1–4</code>\n"
), "{page}");
assert!(
page.contains(
"```rust,noplayground\n// lead\nfn main() {\n println!(\"changed\");\n}\n```"
),
"{page}"
);
assert_eq!(
page.matches("The recorded hash no longer matches").count(),
1,
"{page}"
);
assert!(
page.contains("<code>outline md/notes.md (whole file)</code>"),
"{page}"
);
assert!(page.contains("- Kind: <code>file</code>"), "{page}");
assert!(
page.contains("````markdown\n```rust\nfn x() {}\n```\n````"),
"{page}"
);
assert!(page.contains("```ini\n[book]\n```"), "{page}");
assert!(!page.contains("Stale text."));
}
Input 7: outline src/index.rs mod[tests]/fn[common_input_extensions_select_highlighting_languages]
- File:
src/index.rs - Selector:
mod[tests]/fn[common_input_extensions_select_highlighting_languages] - Kind:
fn src/index.rs:1627–1642
// {test}`requirements.index.detail_format`
#[test]
fn common_input_extensions_select_highlighting_languages() {
for (file, expected) in [
("readme.md", "markdown"),
("record.json", "json"),
("book.toml", "ini"),
("Main.java", "java"),
("app.js", "javascript"),
("app.ts", "typescript"),
("script.py", "python"),
("notes.txt", "plaintext"),
] {
assert_eq!(code_language(Some(file)), expected, "{file}");
}
}
Input 8: outline src/index.rs mod[tests]/fn[index_lists_examples_and_links_their_detail_pages]
- File:
src/index.rs - Selector:
mod[tests]/fn[index_lists_examples_and_links_their_detail_pages] - Kind:
fn src/index.rs:2020–2112
// {test}`requirements.examples.index`
// {test}`requirements.index.detail_format`
// {test}`requirements.index.invalid_detail`
#[test]
fn index_lists_examples_and_links_their_detail_pages() {
let temp = TempDir::new().unwrap();
fs::create_dir_all(temp.path().join("md")).unwrap();
fs::create_dir_all(temp.path().join("evidence")).unwrap();
fs::write(temp.path().join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
let source = ":::{req} ready\nReady.\n:::\n\n:::{example} pending\nPending case. {cite}`rules.ready`\n:::\n\n:::{example} missing\nMissing case. {cite}`rules.ready`\n:::\n";
fs::write(temp.path().join("md/rules.md"), source).unwrap();
fs::write(
temp.path().join("evidence/rules.pending.json"),
json!({
"example": "Pending case. {cite}`rules.ready`",
"determination": false,
"rationale": "The case still needs a test.",
"inputs": []
})
.to_string(),
)
.unwrap();
let mut book = Book::new();
book.push_item(Chapter::new(
"Rules",
source.to_owned(),
"rules.md",
Vec::new(),
));
book.push_item(Chapter::new(
"Index",
":::{requirements-index}\n:::\n".to_owned(),
"requirements-index.md",
Vec::new(),
));
preprocess_book(&mut book, temp.path()).unwrap();
let rules = book.chapters().next().unwrap();
assert!(rules.content.contains(
"id=\"habeas-example-rules.pending\" href=\"#habeas-example-rules.pending\""
));
let index = book
.chapters()
.find(|chapter| chapter.name == "Index")
.unwrap();
assert!(
index
.content
.contains("| [`rules.pending`](requirements-index/rules.pending.html) (example)")
);
assert!(
index
.content
.contains("| [`rules.missing`](requirements-index/rules.missing.html) (example)")
);
// The requirement's row is identified as one too.
assert!(
index
.content
.contains("| [`rules.ready`](requirements-index/rules.ready.html) (requirement)"),
"{}",
index.content
);
let pending = index
.sub_items
.iter()
.find_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "rules.pending" => Some(chapter),
_ => None,
})
.unwrap();
assert!(pending.content.contains("## Example\n\n> Pending case."));
assert!(
pending
.content
.contains("[View definition](../rules.html#habeas-example-rules.pending)")
);
assert!(pending.content.contains("The case still needs a test."));
let missing = index
.sub_items
.iter()
.find_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "rules.missing" => Some(chapter),
_ => None,
})
.unwrap();
assert!(missing.content.contains("## Example\n\n> Missing case."));
assert!(missing.content.contains("## Validation findings"));
assert!(missing.content.contains("missing for example"));
assert!(missing.content.contains("No rationale recorded."));
}
Input 9: outline src/index.rs mod[tests]/fn[detail_inputs_are_grouped_by_current_edges_in_disclosures]
- File:
src/index.rs - Selector:
mod[tests]/fn[detail_inputs_are_grouped_by_current_edges_in_disclosures] - Kind:
fn src/index.rs:2114–2208
// {test}`requirements.index.detail_format`
// {test}`requirements.references.anchors`
#[test]
fn detail_inputs_are_grouped_by_current_edges_in_disclosures() {
let temp = TempDir::new().unwrap();
let root = temp.path();
for dir in ["md", "evidence", "src", "skills"] {
fs::create_dir_all(root.join(dir)).unwrap();
}
fs::write(root.join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
let source = ":::{req} ready\n:impl: skills/ready.md\n:test: skills/test.md\nReady relies on {cite}`rules.base`.\n:::\n\n:::{req} base\nBase.\n:::\n\n:::{example} case\nA case. {test}`rules.ready`\n:::\n".to_owned();
fs::write(root.join("md/rules.md"), &source).unwrap();
fs::write(root.join("skills/ready.md"), "# Skill\n").unwrap();
fs::write(root.join("skills/test.md"), "# Test\n").unwrap();
fs::write(root.join("notes.txt"), "Notes.\n").unwrap();
fs::write(
root.join("src/lib.rs"),
"// {impl}`rules.ready`\nfn run() {}\n\n// {test}`rules.ready`\nfn check() {}\n",
)
.unwrap();
let outline =
|file: &str, item: &str| crate::inputs::outline_input(root, file, item).unwrap();
let inputs = json!([
{"requirements": "rules.ready", "matches": ["rules.ready"], "text": ["ready"]},
outline("src/lib.rs", "fn[check]"),
outline("notes.txt", ""),
{"requirements": "rules.base", "matches": ["rules.base"], "text": ["base"]},
outline("skills/ready.md", "section[Skill]"),
{"requirements": "rules.case", "matches": ["rules.case"], "text": ["case"]},
outline("src/lib.rs", "fn[run]"),
outline("skills/test.md", ""),
]);
fs::write(
root.join("evidence/rules.ready.json"),
json!({
"requirement": "Ready relies on {cite}`rules.base`.",
"determination": true,
"rationale": "Checked.",
"inputs": inputs,
})
.to_string(),
)
.unwrap();
let mut book = Book::new();
book.push_item(Chapter::new("Rules", source, "rules.md", Vec::new()));
book.push_item(Chapter::new(
"Index",
":::{requirements-index}\n:::\n".into(),
"requirements-index.md",
Vec::new(),
));
preprocess_book(&mut book, root).unwrap();
let page = book
.chapters()
.find(|chapter| chapter.name == "rules.ready")
.unwrap();
let content = &page.content;
let position = |needle: &str| {
content
.find(needle)
.unwrap_or_else(|| panic!("missing {needle:?} in:\n{content}"))
};
let groups = [
("Implementation", [5, 7].as_slice()),
("Tests", &[2, 6, 8]),
("Referenced definitions", &[4]),
("Other sources", &[1, 3]),
];
let starts = groups
.iter()
.map(|(heading, _)| position(&format!("style=\"display: inline\">{heading}</h3>")))
.collect::<Vec<_>>();
assert!(starts.windows(2).all(|pair| pair[0] < pair[1]), "{content}");
for (group, (_, inputs)) in groups.iter().enumerate() {
let end = starts.get(group + 1).copied().unwrap_or(content.len());
for input in *inputs {
let at = position(&format!("<summary id=\"habeas-input-{input}\">"));
assert!(starts[group] < at && at < end, "input {input}:\n{content}");
}
}
assert_eq!(
content
.matches("<details class=\"habeas-input-group\" open>")
.count(),
4
);
assert_eq!(
content.matches("<details class=\"habeas-input\">").count(),
8
);
assert_eq!(content.matches("</details>").count(), 12);
assert!(content.contains("<code>requirements selection rules.base</code>"));
assert!(content.contains("[Requirements index](../requirements-index.html)"));
}
Input 10: outline src/index.rs mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group]
- File:
src/index.rs - Selector:
mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group] - Kind:
fn src/index.rs:2210–2314
// {test}`requirements.index.detail_format`
// {test}`requirements.definitions.inputs`
// {test}`requirements.ci.requirements_inputs`
// {test}`requirements.index.source_links`
#[test]
fn detail_page_shows_recorded_text_locations_and_first_matching_group() {
let temp = TempDir::new().unwrap();
let root = temp.path();
for dir in ["md", "evidence", "src"] {
fs::create_dir_all(root.join(dir)).unwrap();
}
fs::write(root.join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
let source = ":::{req} ready\nReady uses {term}`rules.term`.\n:::\n\n:::{req} base\nBase.\n:::\n\n:::{definition} term\n:phrase: term\n\nA term.\n:::\n".to_owned();
fs::write(root.join("md/rules.md"), &source).unwrap();
fs::write(
root.join("src/lib.rs"),
"// {impl}`rules.ready`\n// {test}`rules.ready`\nfn both() {}\n",
)
.unwrap();
let inputs = json!([
{"requirements": "rules.*", "matches": ["rules.base", "rules.ready"], "text": ["recorded base", "", "recorded ready"]},
{"definition": "rules.term", "text": ["recorded term"]},
{"requirements": "missing.*", "matches": ["missing.x"], "text": ["recorded missing"]},
crate::inputs::outline_input(root, "src/lib.rs", "fn[both]").unwrap(),
]);
fs::write(
root.join("evidence/rules.ready.json"),
json!({
"requirement": "Ready uses {term}`rules.term`.",
"determination": true,
"rationale": "Checked.",
"inputs": inputs,
})
.to_string(),
)
.unwrap();
let mut book = Book::new();
book.push_item(Chapter::new("Rules", source, "rules.md", Vec::new()));
book.push_item(Chapter::new(
"Index",
":::{requirements-index}\n:::\n".into(),
"requirements-index.md",
Vec::new(),
));
preprocess_book(&mut book, root).unwrap();
let page = book
.chapters()
.find(|chapter| chapter.name == "rules.ready")
.unwrap();
let content = &page.content;
let position = |needle: &str| {
content
.find(needle)
.unwrap_or_else(|| panic!("missing {needle:?} in:\n{content}"))
};
// The state badge has alt text naming the state.
let badge =
position("<img class=\"habeas-shield\" src=\"https://img.shields.io/badge/evidence-");
assert!(
content[badge..].contains("alt=\"evidence Invalid\""),
"{content}"
);
// A requirements input lists each match's name, file, and inclusive
// range, then its recorded text.
let selection = position("<code>requirements selection rules.*</code>");
let base = position("- <code>rules.base</code>: <code>md/rules.md:5–7</code>\n");
let ready = position("- <code>rules.ready</code>: <code>md/rules.md:1–3</code>\n");
let recorded = position("```markdown\nrecorded base\n\nrecorded ready\n```");
assert!(
selection < base && base < ready && ready < recorded,
"{content}"
);
// A definition input shows its name, location, and recorded text.
let definition = position("<code>definition rules.term</code>");
let location = position("- <code>rules.term</code>: <code>md/rules.md:9–13</code>\n");
let text = position("```markdown\nrecorded term\n```");
assert!(definition < location && location < text, "{content}");
let referenced = position("style=\"display: inline\">Referenced definitions</h3>");
let other = position("style=\"display: inline\">Other sources</h3>");
assert!(referenced < definition && definition < other, "{content}");
// An unresolved selector is reported and its recorded text kept.
let unresolved = position("Unresolved selector: ");
let missing = position("```markdown\nrecorded missing\n```");
assert!(unresolved < missing, "{content}");
// A source reached by both an implementation and a test edge appears
// once, in the first group that applies.
let implementation = position("style=\"display: inline\">Implementation</h3>");
let both = position("<code>outline src/lib.rs fn[both]</code>");
assert!(implementation < both, "{content}");
assert!(
!content.contains("style=\"display: inline\">Tests</h3>"),
"{content}"
);
assert_eq!(
content.matches("outline src/lib.rs fn[both]").count(),
1,
"{content}"
);
}
Input 11: outline tests/outcomes.rs fn[valid_fixme_remains_visible_in_status_info_and_book]
- File:
tests/outcomes.rs - Selector:
fn[valid_fixme_remains_visible_in_status_info_and_book] - Kind:
fn tests/outcomes.rs:471–527
// {test}`requirements.cli.status`
// {test}`requirements.cli.fixme_summary`
// {test}`requirements.cli.info`
// {test}`requirements.index.state`
// {test}`requirements.index.detail_format`
// {test}`requirements.index.detail_pages`
// {test}`requirements.examples.index`
#[test]
fn valid_fixme_remains_visible_in_status_info_and_book() {
let temp = fixture();
for all in [false, true] {
let status = habeas::status_markdown(temp.path(), all).unwrap();
assert_eq!(status.contains("requirements.timeout"), all, "{status}");
assert!(status.contains("FIXME"));
assert!(status.contains("example/io#125"));
assert!(status.contains("rust-lang/rust#123"));
assert!(status.contains("affects 1 judgment"), "{status}");
assert!(!status.contains("## Validation findings"));
}
let verbose = habeas::status_markdown_with_options(temp.path(), false, None, true).unwrap();
assert!(verbose.contains("requirements.timeout"), "{verbose}");
assert!(verbose.contains("example"), "{verbose}");
let info = habeas::info_markdown(temp.path(), "requirements.timeout").unwrap();
assert!(info.contains("## FIXME references"));
assert!(info.contains("rust-lang/rust#123"));
let mut book = Book::new();
book.push_item(Chapter::new(
"Requirements",
fs::read_to_string(temp.path().join("md/requirements.md")).unwrap(),
"requirements.md",
Vec::new(),
));
book.push_item(Chapter::new(
"Index",
":::{requirements-index}\n:::\n".to_owned(),
"requirements-index.md",
Vec::new(),
));
habeas::preprocess_book(&mut book, temp.path()).unwrap();
let index = book
.chapters()
.find(|chapter| chapter.name == "Index")
.unwrap();
assert!(index.content.contains("FIXME"));
let detail = index
.sub_items
.iter()
.find_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "requirements.timeout" => Some(chapter),
_ => None,
})
.unwrap();
assert!(detail.content.contains("evidence-FIXME"));
assert!(detail.content.contains("## FIXME references"));
assert!(detail.content.contains("rust-lang/rust#123"));
}
Referenced definitions
Input 2: 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 3: requirements selection requirements.references.anchors
requirements.references.anchors:md/requirements/references.md:176–197
:::{req} anchors
A `{req}` declaration MAY list `:impl:` and `:test:` options, and an `{example}`
declaration MAY list `:test:` options, immediately after its opening fence and
before its body, one per option line, naming a project file path or
`path#selector` for one outline node under
{cite}`requirements.references.outline_selectors`. Each anchor MUST be an `{impl}` or `{test}` edge, under
{cite}`requirements.references.roles`, from the definition to the anchored file or
node, for files that cannot or should not carry a reference themselves.
Paths MUST follow the path rules in {cite}`requirements.ci.schema`. Option lines
MUST NOT form part of the definition's text for evidence comparison or for
requirements inputs, and MUST NOT render as body text.
For each `:test:` anchor, the harness MUST include the selected file or node's
source text in the initial model request under
{cite}`requirements.authoring.mandatory_inputs` and MUST record that selection
as an evidence input under {cite}`requirements.references.evidence_coverage`,
so changing that source makes the evidence stale.
A `:impl:` anchor alone MUST NOT require an input selecting its source. A path or selector that
does not resolve to a readable, permitted file or node MUST be a validation error naming the
definition and the path; authoring MUST report it before inference. Any other option line in a `{req}` or
`{example}` declaration MUST be a validation error.
:::
Other sources
Input 1: requirements selection requirements.index.detail_format
requirements.index.detail_format:md/requirements/index/README.md:25–27
:::{req} detail_format
Each evidence detail page MUST display its state as a Shields.io static badge image with meaningful alt text and the current requirement or example body as a Markdown block quote labeled by kind. It MUST render the recorded rationale as Markdown in a Rationale section and display the recorded FIXME strings when the determination is FIXME. Inputs MUST be grouped under headings in this order, each input appearing once, in the first group that applies to it: Implementation, for sources reached by an `{impl}` edge from the definition, including anchored files; Tests, for sources reached by a `{test}` edge, including tests, examples, and anchored files; Referenced definitions, for declarations the definition cites and their terminology; and Other sources, for the remaining inputs the assessment consulted. Edges MUST be determined from the current references under {cite}`requirements.references.roles` and {cite}`requirements.references.anchors`. Each group and each input MUST be a collapsible disclosure element, with groups expanded and inputs collapsed by default, so readers can move between groups and open individual sources. Each input MUST have its own subsection identifying its selector. An outline input MUST show its file, selector, kind, and current inclusive line range. A requirements input MUST show its selection and each matched definition's full name, file, and inclusive line range. Each outline input subsection MUST show the node's current source text in a fenced code block and say when its hash no longer matches; a requirements or definition input subsection MUST show its recorded text. Code fences MUST request Rust highlighting for `.rs` files and language-aware highlighting for Markdown, JSON, TOML, Java, JavaScript, TypeScript, and Python files; TOML MAY use INI highlighting when native TOML highlighting is unavailable.
:::
Input 12: outline tests/outcomes.rs fn[fixture]
- File:
tests/outcomes.rs - Selector:
fn[fixture] - Kind:
fn tests/outcomes.rs:28–92
/// The example `requirements.timeout`, judged FIXME and acknowledged by a
/// `{fixme}` in `observed.rs` naming two issues.
// {test}`requirements.examples.evidence`
fn fixture() -> TempDir {
let temp = TempDir::new().unwrap();
fs::create_dir(temp.path().join("md")).unwrap();
fs::create_dir(temp.path().join("evidence")).unwrap();
fs::write(
temp.path().join("Cargo.toml"),
"[package]\nname = 'fixture'\n",
)
.unwrap();
fs::write(temp.path().join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
let example = "Timeout handling retries. {cite}`requirements.ready`".to_owned();
let example_lines = vec![
":::{example} timeout".to_owned(),
example.clone(),
":::".to_owned(),
];
fs::write(
temp.path().join("md/requirements.md"),
format!(
":::{{req}} ready\nThe behavior MUST work.\n:::\n\n{}\n",
example_lines.join("\n")
),
)
.unwrap();
let source = fixme(
"requirements.timeout",
&["example/io#125", "rust-lang/rust#123"],
"Retry-after-timeout and partial-write recovery are untested.",
);
fs::write(
temp.path().join("observed.rs"),
format!("{source}const RETRIES: u32 = 1;\n"),
)
.unwrap();
let source_input = habeas::outline_input(temp.path(), "observed.rs", "").unwrap();
write_record(
temp.path(),
"ready",
json!({
"requirement": "The behavior MUST work.",
"determination": true,
"rationale": "The requirement is supported by the fixture.",
"inputs": [{
"requirements": "requirements.timeout",
"matches": ["requirements.timeout"],
"text": example_lines
}]
}),
);
write_record(
temp.path(),
"timeout",
json!({
"example": example,
"determination": { "FIXME": ["example/io#125", "rust-lang/rust#123"] },
"rationale": "The recorded comments acknowledge the missing timeout tests.",
"inputs": [source_input]
}),
);
common::coverage_setup(temp.path());
temp
}