Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.index.chapter

Requirements index · View definition

evidence Valid

Requirement

An mdBook chapter MAY contain one standalone {requirements-index} directive with an empty body, opened by at least three colons and closed by at least as many. A book MUST contain no more than one such directive. habeas mdbook MUST render a requirements index listing all requirements defined in rendered chapters, each linking to its evidence detail page under cite requirements.index.detail_pages. When a directive is present, it MUST replace the directive with the index table; otherwise, it MUST generate the chapter specified by cite requirements.index.chapter.default.

Rationale

The reviewed tests adequately cover requirements.index.chapter. I did not request implementation source; I judged the supplied test text against the requirement.

Marker syntax (standalone directive, empty body, opening and closing colons)

  • src/index.rs#mod[tests]/fn[marker_accepts_long_fences_and_ignores_examples] checks that a four-colon marker is accepted and that a closing fence longer than the opening one (:::: opened, ::::: closed) is accepted.
  • The same test rejects a marker with no closing fence, a marker with a non-empty body, and a closing fence shorter than the opening one.
  • It ignores a marker inside a code fence, a marker nested inside another directive such as {req}, a two-colon marker, and an inline “Inline :::{requirements-index}” marker.
  • It asserts the exact byte range replaced.

At most one directive per book (MUST)

  • src/index.rs#mod[tests]/fn[repeated_index_markers_fail_with_a_clear_error] covers two markers in separate chapters and two markers in one chapter. Both cases assert that preprocess_book returns an error containing “only one”.

Index lists all requirements, each linking to its detail page

  • src/index.rs#mod[tests]/fn[index_shows_evidence_states_and_links_generated_chapters] places an explicit marker in an index chapter and asserts the following:
    • The marker text is gone from the index content.
    • Each of five requirements has a table row linking to requirements-index/requirements.core.<name>.html.
    • The row’s state column is correct for each of the five states.
    • The table columns are aligned.
    • The index has six sub-items: five detail pages plus the coverage-gaps page.
  • The same test checks detail-page paths, titles, section numbers and the back link to the index.
  • src/lib.rs#mod[tests]/fn[index_owns_details_in_book_order_with_badge_icons] checks that an explicit index keeps its placement, with detail pages in book order across chapters, including an example (more.cli.mdbook). It also checks that definitions link to the detail pages with the correct relative paths.
  • src/lib.rs#mod[tests]/fn[definitions_without_a_marker_get_a_default_index_and_detail_pages] checks that definitions in nested sub-chapters are included, that both requirements and examples are indexed, and that pages appear in definition order.

Directive present replaces the directive; otherwise the default chapter is generated

  • Replacement is asserted in index_shows_evidence_states_and_links_generated_chapters.
  • The no-marker default is asserted in definitions_without_a_marker_get_a_default_index_and_detail_pages and default_index_exists_even_without_definitions_or_numbered_chapters.
  • Together they cover:
    • the title “Requirements index” and the path requirements-index.md;
    • appending as a top-level chapter, with no source file and no parent names;
    • section number 1 when no chapter is numbered, and 3 after a chapter numbered 2;
    • the chapter existing with no definitions;
    • a marker inside a code block in prose not counting as a marker.
  • The detailed behavior of requirements.index.chapter.default is a cited requirement. It is context only, and these tests also exercise it.

I found no unexercised obligation, and the assertions enforce the expected outcomes. No gaps and no acknowledgments.

Inputs

Tests

Input 4: outline src/index.rs mod[tests]/fn[marker_accepts_long_fences_and_ignores_examples]
  • File: src/index.rs
  • Selector: mod[tests]/fn[marker_accepts_long_fences_and_ignores_examples]
  • Kind: fn
  • src/index.rs:1070–1099
    // {test}`requirements.index.chapter`
    #[test]
    fn marker_accepts_long_fences_and_ignores_examples() {
        let content = "```text\n:::{requirements-index}\n:::\n```\n\n::::{req} example\n:::{requirements-index}\n:::\n::::\n\n::::{requirements-index}\n::::\n";
        let ranges = marker_ranges(content).unwrap();
        assert_eq!(ranges.len(), 1);
        assert_eq!(
            &content[ranges[0].clone()],
            "::::{requirements-index}\n::::\n"
        );
        assert!(marker_ranges(":::{requirements-index}\n").is_err());
        assert!(marker_ranges(":::{requirements-index}\nUnexpected.\n:::").is_err());
        assert!(marker_ranges("::::{requirements-index}\n:::\n").is_err());
        assert!(
            marker_ranges("::{requirements-index}\n::\n")
                .unwrap()
                .is_empty()
        );
        assert!(
            marker_ranges("Inline :::{requirements-index}\n:::\n")
                .unwrap()
                .is_empty()
        );
        assert_eq!(
            marker_ranges("::::{requirements-index}\n:::::\n")
                .unwrap()
                .len(),
            1
        );
    }
Input 5: 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 6: outline src/index.rs mod[tests]/fn[repeated_index_markers_fail_with_a_clear_error]
  • File: src/index.rs
  • Selector: mod[tests]/fn[repeated_index_markers_fail_with_a_clear_error]
  • Kind: fn
  • src/index.rs:1644–1671
    // {test}`requirements.index.chapter`
    #[test]
    fn repeated_index_markers_fail_with_a_clear_error() {
        let mut book = Book::new();
        for path in ["one.md", "two.md"] {
            book.push_item(Chapter::new(
                "Index",
                ":::{requirements-index}\n:::\n".to_owned(),
                path,
                Vec::new(),
            ));
        }
        let error = preprocess_book(&mut book, Path::new(".")).unwrap_err();
        assert!(error.to_string().contains("only one"));
        let mut book = Book::new();
        book.push_item(Chapter::new(
            "Index",
            ":::{requirements-index}\n:::\n\n:::{requirements-index}\n:::\n".to_owned(),
            "one.md",
            Vec::new(),
        ));
        assert!(
            preprocess_book(&mut book, Path::new("."))
                .unwrap_err()
                .to_string()
                .contains("only one")
        );
    }
Input 7: outline src/lib.rs mod[tests]/fn[definitions_without_a_marker_get_a_default_index_and_detail_pages]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[definitions_without_a_marker_get_a_default_index_and_detail_pages]
  • Kind: fn
  • src/lib.rs:1050–1185
    // {test}`requirements.index.detail_pages`
    // {test}`requirements.index.chapter`
    // {test}`requirements.index.chapter.default`
    // {test}`requirements.index.navigation`
    // {test}`requirements.examples.index`
    // {test}`requirements.test-coverage.index`
    // {test}`requirements.references.anchors`
    #[test]
    fn definitions_without_a_marker_get_a_default_index_and_detail_pages() {
        let mut book = Book::new();
        let mut chapter = Chapter::new(
            "Rules",
            "# Rules\n\n:::{req} zeta\n:impl: notes.txt\nZeta.\n:::\n\n:::{example} alpha\nAlpha case. {cite}`rules.zeta`\n:::\n\n:::{req} cli.mdbook\nMdbook.\n:::\n".to_owned(),
            "rules.md",
            Vec::new(),
        );
        chapter.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![2]));
        chapter.sub_items.push(BookItem::Chapter(Chapter::new(
            "Child",
            ":::{req} nested\nNested.\n:::\n".to_owned(),
            "rules/child.md",
            vec!["Rules".to_owned()],
        )));
        book.push_item(chapter);
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();

        let rules = book.chapters().next().unwrap();
        let pages = rules
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(pages.len(), 1);
        assert_eq!(pages[0].name, "Child");
        assert_eq!(book.items.len(), 2);
        assert_eq!(book.chapters().count(), 8);
        assert!(rules.content.contains("habeas-detail-icon"));
        assert!(!rules.content.contains("See evidence"));
        assert!(!rules.content.contains("notes.txt"));
        for (kind, name) in [("req", "zeta"), ("example", "alpha"), ("req", "cli.mdbook")] {
            assert!(rules.content.contains(&format!(
                "id=\"habeas-{kind}-rules.{name}\" href=\"#habeas-{kind}-rules.{}\"",
                name.replace(".md", "%2Emd")
            )));
        }
        assert!(
            rules
                .content
                .contains("href=\"requirements-index/rules.cli%2Emdbook.html\"")
        );
        assert!(
            pages[0]
                .content
                .contains("href=\"../requirements-index/rules.child.nested.html\"")
        );
        let BookItem::Chapter(index) = book.items.last().unwrap() else {
            panic!("the default index must be a top-level chapter");
        };
        assert_eq!(index.name, "Requirements index");
        assert_eq!(
            index.path.as_deref(),
            Some(Path::new("requirements-index.md"))
        );
        assert!(index.source_path.is_none());
        assert!(index.parent_names.is_empty());
        assert_eq!(index.number.as_deref().map(Vec::as_slice), Some(&[3][..]));
        assert!(!index.content.contains("{requirements-index}"));
        assert!(index.content.contains("(requirement)"));
        assert!(index.content.contains("(example)"));
        assert!(index.content.contains("Missing"));
        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("requirements-index/coverage.md"))
        );
        assert_eq!(coverage[0].parent_names, ["Requirements index"]);
        assert!(
            index
                .content
                .contains("[Coverage gaps](requirements-index/coverage.html)")
        );
        let details = index
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) if chapter.name != "Coverage gaps" => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(
            details
                .iter()
                .map(|page| page.name.as_str())
                .collect::<Vec<_>>(),
            [
                "rules.zeta",
                "rules.alpha",
                "rules.cli.mdbook",
                "rules.child.nested"
            ]
        );
        for (offset, page) in details.iter().enumerate() {
            assert_eq!(page.parent_names, ["Requirements index"]);
            assert_eq!(
                page.number.as_deref().map(Vec::as_slice),
                Some(&[3, offset as u32 + 2][..])
            );
            assert!(
                page.content
                    .contains("[Requirements index](../requirements-index.html)")
            );
        }
        assert!(
            details[2]
                .content
                .contains("[View definition](../rules.html#habeas-req-rules.cli%2Emdbook)")
        );
        assert!(
            details[3]
                .content
                .contains("[View definition](../rules/child.html#habeas-req-rules.child.nested)")
        );
        assert!(!root.path().join("md/requirements-index.md").exists());
    }
Input 8: outline src/lib.rs mod[tests]/fn[default_index_exists_even_without_definitions_or_numbered_chapters]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[default_index_exists_even_without_definitions_or_numbered_chapters]
  • Kind: fn
  • src/lib.rs:1187–1235
    // {test}`requirements.index.chapter`
    // {test}`requirements.index.chapter.default`
    // {test}`requirements.index.detail_pages`
    #[test]
    fn default_index_exists_even_without_definitions_or_numbered_chapters() {
        for with_prose in [false, true] {
            let mut book = Book::new();
            let prose = "An index marker in a code block is literal.\n\n```text\n:::{requirements-index}\n:::\n```\n";
            if with_prose {
                book.push_item(Chapter::new(
                    "Introduction",
                    prose.into(),
                    "intro.md",
                    vec![],
                ));
            }
            let root = book_root();
            preprocess_book(&mut book, root.path()).unwrap();
            assert_eq!(book.items.len(), usize::from(with_prose) + 1);
            if with_prose {
                let BookItem::Chapter(intro) = &book.items[0] else {
                    panic!("the original introduction must remain a chapter");
                };
                assert_eq!(intro.content, prose);
                assert!(intro.number.is_none());
            }
            let BookItem::Chapter(index) = book.items.last().unwrap() else {
                panic!("the default index must be appended");
            };
            assert_eq!(index.name, "Requirements index");
            assert_eq!(
                index.path.as_deref(),
                Some(Path::new("requirements-index.md"))
            );
            assert_eq!(index.number.as_deref().map(Vec::as_slice), Some(&[1][..]));
            assert!(index.source_path.is_none());
            assert_eq!(index.sub_items.len(), 1);
            let BookItem::Chapter(coverage) = &index.sub_items[0] else {
                unreachable!()
            };
            assert_eq!(coverage.name, "Coverage gaps");
            assert!(coverage.source_path.is_none());
            assert!(index.parent_names.is_empty());
            assert!(index.content.starts_with("# Requirements index\n\n"));
            assert!(index.content.contains("| Definition | Evidence |"));
            assert!(!index.content.contains("{requirements-index}"));
            assert!(!root.path().join("md/requirements-index.md").exists());
        }
    }
Input 9: outline src/lib.rs mod[tests]/fn[index_owns_details_in_book_order_with_badge_icons]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[index_owns_details_in_book_order_with_badge_icons]
  • Kind: fn
  • src/lib.rs:1268–1350
    // {test}`requirements.index.chapter`
    // {test}`requirements.index.detail_pages`
    // {test}`requirements.index.navigation`
    #[test]
    fn index_owns_details_in_book_order_with_badge_icons() {
        let mut book = Book::new();
        book.push_item(Chapter::new(
            "Rules",
            ":::{req} zeta\nZeta.\n:::\n".into(),
            "rules.md",
            vec![],
        ));
        book.push_item(Chapter::new(
            "More",
            ":::{example} cli.mdbook\nExample.\n:::\n".into(),
            "more.md",
            vec![],
        ));
        let mut index = Chapter::new(
            "Index",
            ":::{requirements-index}\n:::\n".into(),
            "appendix/index.md",
            vec![],
        );
        index.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![3]));
        let mut child = Chapter::new(
            "Existing",
            "Existing.".into(),
            "appendix/existing.md",
            vec!["Index".into()],
        );
        child.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![3, 1]));
        index.sub_items.push(BookItem::Chapter(child));
        book.push_item(index);
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();
        assert_eq!(
            book.items.len(),
            3,
            "the explicit index keeps its placement"
        );
        let chapters = book.chapters().collect::<Vec<_>>();
        for chapter in &chapters[..2] {
            assert!(chapter.sub_items.is_empty());
            assert!(
                chapter
                    .content
                    .contains("title=\"View evidence\" aria-label=\"View evidence for ")
            );
            assert!(chapter.content.contains("stroke=\"#fff\""));
            assert!(!chapter.content.contains("See evidence"));
        }
        assert!(
            chapters[1]
                .content
                .contains("href=\"appendix/index/more.cli%2Emdbook.html\"")
        );
        let pages = chapters[2]
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(
            pages
                .iter()
                .map(|page| page.name.as_str())
                .collect::<Vec<_>>(),
            ["Coverage gaps", "Existing", "rules.zeta", "more.cli.mdbook"]
        );
        assert_eq!(pages[3].parent_names, ["Index"]);
        assert_eq!(
            pages[3].number.as_deref().map(Vec::as_slice),
            Some(&[3, 4][..])
        );
        assert!(
            pages[3]
                .content
                .contains("[View definition](../../more.html#habeas-example-more.cli%2Emdbook)")
        );
    }

Referenced definitions

Input 2: requirements selection requirements.index.detail_pages
:::{req} detail_pages
`habeas mdbook` MUST generate one evidence detail
page for every requirement and named example defined in a rendered chapter.
Each page MUST be a subchapter of the index chapter, in definition order,
titled by the definition's full name, at a path derived from the index chapter's
path.
Books configured by {cite}`requirements.cli.setup` fold these subchapters in the
sidebar until a reader expands the index chapter.
:::
Input 3: requirements selection requirements.index.chapter.default
:::{req} chapter.default
When a book contains no standalone `{requirements-index}` directive, `habeas mdbook` MUST append a new top-level chapter titled "Requirements index" at `requirements-index.md`, containing the index table, even when the book defines no requirements or examples. The generated chapter MUST have no source file or edit target. Its section number MUST be one greater than the largest numbered top-level chapter, or 1 when no top-level chapter is numbered.
:::

Other sources

Input 1: requirements selection requirements.index.chapter
:::{req} chapter
An mdBook chapter MAY contain one standalone `{requirements-index}` directive with an empty body, opened by at least three colons and closed by at least as many. A book MUST contain no more than one such directive. `habeas mdbook` MUST render a requirements index listing all requirements defined in rendered chapters, each linking to its evidence detail page under {cite}`requirements.index.detail_pages`. When a directive is present, it MUST replace the directive with the index table; otherwise, it MUST generate the chapter specified by {cite}`requirements.index.chapter.default`.
:::