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.references.anchors

Requirements index · View definition

evidence Valid

Requirement

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.

Rationale

The reviewed tests cover each obligation in requirements.references.anchors. I found no gap.

Anchor syntax and edges

  • src/lib.rs#mod[tests]/fn[anchor_options_are_metadata_not_body_text] checks that option lines are parsed only when they sit immediately after the opening fence. Both req and example blocks are covered, including nested fences. A later :test: line and inline text such as Text :impl: stay body text.
  • src/evidence.rs#mod[tests]/fn[requirements_inputs_omit_option_lines] checks that the definition text and the requirements input exclude the option lines. It also checks that the parsed anchor is an Impl anchor with an empty selector.
  • src/authoring/tools.rs#mod[tests]/fn[references_report_anchors_as_file_or_node_sites] checks that :impl: and :test: anchors on requirements and examples become impl and test edges. File anchors report a null item and selector anchors report the node.
  • src/authoring/tools.rs#mod[tests]/fn[ripgrep_node_scope_searches_only_the_node_a_selector_anchor_names] checks that a selector anchor names exactly one node.

Not rendered, and not part of the evidence text

  • anchor_options_are_metadata_not_body_text asserts that the rendered output omits the option lines.
  • src/evidence.rs#mod[tests]/fn[anchored_files_must_be_completely_covered_and_resolvable] asserts that no “text changed” error appears when the evidence text omits the option lines.

:test: anchors become mandatory inputs and evidence inputs

  • src/authoring/inputs.rs#mod[tests]/fn[anchored_files_contribute_root_node_inputs] checks that the file’s root node is supplied with its text and hash. The :impl: text in the body stays part of the definition.
  • src/authoring/inputs.rs#mod[tests]/fn[test_anchors_supply_only_the_selected_node] checks that only the selected node is supplied, in both the inputs and the initial prompt. Sibling source is absent.
  • src/evidence.rs#mod[tests]/fn[anchored_files_must_be_completely_covered_and_resolvable] checks that a missing covering input is reported, that the whole file is required for a file anchor, and that example anchors are covered. It also checks that changing the anchored file makes the evidence stale.
  • src/evidence.rs#mod[tests]/fn[selector_anchors_are_covered_by_inputs_selecting_the_node_or_an_ancestor] checks that selector anchors are covered by an input selecting the node, an ancestor, or the root. A sibling node is not enough.

An :impl: anchor alone requires no input

  • selector_anchors_are_covered_by_inputs_selecting_the_node_or_an_ancestor writes an :impl: anchor with empty inputs and expects no anchor errors.
  • src/authoring/inputs.rs#mod[tests]/fn[references_contribute_their_owning_outline_nodes] shows that an :impl: anchor on src/lib.rs#mod[inner] adds no outline input.

Unresolvable, outside or denied paths

  • unreadable_or_denied_anchors_fail_before_inference checks a missing file, a missing node in an existing file, and a disallowed path. The errors name the definition (requirements.ready) and the anchor, and they come from AssessmentSources::prepare, so before inference.
  • anchored_files_must_be_completely_covered_and_resolvable checks the validation error for an unresolvable :test: anchor, missing.sh. The error names the requirement and the path.
  • selector_anchors_are_covered_by_inputs_selecting_the_node_or_an_ancestor checks the validation error for an unresolvable :impl: selector.
  • outside_test_anchors_follow_explicit_allow_and_disallow_rules checks absolute and parent-relative outside paths. They are denied by default, allowed by an explicit allow, and aborted by an explicit disallow.
  • mandatory_inputs_through_symlinks_leaving_the_project_abort_preparation checks a symlink that leaves the project.

Other option lines are errors

  • src/evidence.rs#mod[tests]/fn[unsupported_and_empty_options_are_validation_errors] checks three cases. An unsupported :phrase: on a requirement is an error. An empty :impl: option is an error. An :impl: option on an {example} is an error.

Residual note No authoring test builds an {example} subject with a :test: anchor and checks its mandatory inputs. The example path is covered on the evidence side. On the authoring side, AssessmentSources::prepare loops over subject.anchors without branching on subject kind. The text does not distinguish the two kinds there, so I treat this as not a gap.

Inputs

Implementation

Input 24: outline src/authoring/inputs.rs impl[AssessmentSources]/fn[prepare]
    // {impl}`requirements.authoring.invocation`
    // {impl}`requirements.authoring.mandatory_inputs`
    // {impl}`requirements.authoring_input`
    // {impl}`requirements.examples.authoring_inputs`
    // {impl}`requirements.examples.definition`
    // {impl}`requirements.references.authoring_inputs`
    // {impl}`requirements.definitions.authoring_inputs`
    // {impl}`requirements.authoring.source_tools`
    // {impl}`requirements.references.anchors`
    // {impl}`requirements.ci.reference_set`
    // {impl}`requirements.references.builtin_definitions`
    // {impl}`requirements.references.site_review`
    pub(crate) fn prepare(root: &Path, subject_name: &str) -> io::Result<Self> {
        let root = fs::canonicalize(root)?;
        let access = SourceAccess::load(&root)?;
        let definitions = load_definitions(&root)?;
        let subject = definitions
            .get(subject_name)
            .filter(|definition| definition.kind != DefinitionKind::Term)
            .ok_or_else(|| {
                io::Error::other(format!(
                    "{subject_name}: no matching requirement or named example"
                ))
            })?;
        let mut selectors = vec![InputSelector::Requirements {
            requirements: subject_name.to_owned(),
        }];

        let mut builtins = Vec::new();
        for (kind, name) in crate::text_references(&subject.text, true) {
            // A `{fixme}` in a declaration is a validation error when named
            // and is not an edge when unnamed.
            if matches!(kind, ReferenceKind::Term | ReferenceKind::Fixme) {
                continue;
            }
            // A built-in has no declaration; its fixed text is supplied instead.
            if let Some(builtin) = crate::builtins::builtin(&name) {
                if kind == ReferenceKind::Cite && !builtins.contains(&builtin.name) {
                    builtins.push(builtin.name);
                }
                continue;
            }
            if !definitions
                .get(&name)
                .is_some_and(|definition| definition.kind != DefinitionKind::Term)
            {
                return Err(io::Error::other(format!(
                    "{subject_name}: referenced subject {name} does not exist"
                )));
            }
            // Only `{cite}` leaves the subject; its `{impl}` and `{test}`
            // references point into it from the definitions it implements or tests.
            if kind != ReferenceKind::Cite {
                continue;
            }
            insert_selector(
                &mut selectors,
                InputSelector::Requirements { requirements: name },
            );
        }

        let outlines = OutlineCache::default();
        let mut errors = Vec::new();
        let files = discovered_files(&root, &mut errors);
        let references = crate::evidence::collect_references_with_progress(
            &root,
            &files,
            &mut errors,
            &mut |_| {},
        );
        if !errors.is_empty() {
            return Err(io::Error::other(errors.join("\n")));
        }
        let sites =
            crate::evidence::definition_sites(&root, subject_name, subject, &files, &outlines)?;
        // The same edges determine the reference contributions below.
        let reference_set = crate::evidence::reference_set_digest(
            &root,
            &outlines,
            subject_name,
            subject,
            &references,
            &sites,
        );
        // Tests contribute source. Refining declarations contribute their text;
        // implementation references outside declarations only locate code.
        for reference in references.iter().filter(|reference| {
            reference.name == subject_name
                && matches!(reference.kind, ReferenceKind::Impl | ReferenceKind::Test)
        }) {
            // Generated evidence, including symlink aliases, is omitted by
            // default rather than denied.
            if access.omit_generated_evidence(&root, &reference.file) {
                continue;
            }
            let selector = reference_selector(&root, &definitions, &outlines, reference)?;
            if reference.kind == ReferenceKind::Test
                || matches!(selector, InputSelector::Requirements { .. })
            {
                access.file(&root, &reference.file)?;
                insert_selector(&mut selectors, selector);
            }
        }

        // {impl}`requirements.references.anchors`
        for anchor in &subject.anchors {
            if access.omit_generated_evidence(&root, Path::new(&anchor.file)) {
                continue;
            }
            let selector = access
                .file(&root, Path::new(&anchor.file))
                .and_then(|_| {
                    anchor
                        .resolve(&root, &outlines)
                        .map(|_| anchor.selector())
                        .map_err(io::Error::other)
                })
                .map_err(|error| {
                    io::Error::new(
                        error.kind(),
                        format!(
                            "{subject_name}: cannot read :{}: anchor {}: {error}",
                            anchor.kind.label(),
                            anchor.label()
                        ),
                    )
                })?;
            if anchor.kind == ReferenceKind::Test {
                insert_selector(&mut selectors, selector);
            }
        }

        // {impl}`requirements.authoring.fixme_inputs`
        let mut acknowledgments = crate::evidence::fixme_acknowledgments(
            &root,
            &outlines,
            references.iter().filter(|reference| {
                reference.name == subject_name
                    && !crate::sites::in_own_site(&root, &sites, reference)
                    && !access.omit_generated_evidence(&root, &reference.file)
            }),
        )
        .map_err(io::Error::other)?;
        for acknowledgment in &acknowledgments {
            access.file(&root, Path::new(acknowledgment["file"].as_str().unwrap()))?;
        }

        // Existing evidence only decides whether to reassess; its inputs are
        // not carried forward.
        let mut mandatory = Vec::new();
        for selector in selectors {
            if !generated_evidence_selector(&root, &access, &selector) {
                mandatory.push(source_input(
                    &root,
                    &access,
                    &definitions,
                    &outlines,
                    &selector,
                )?);
            }
        }
        // The dependency collector receives bodies separately so Markdown and
        // non-Markdown reference-literal rules keep their source semantics.
        let dependencies = crate::terms::dependencies(
            &root,
            &definitions,
            &outlines,
            json!({"inputs": mandatory, "acknowledgments": acknowledgments})
                .as_object()
                .unwrap(),
            Some(&subject.text),
        )
        .map_err(io::Error::other)?;
        for definition in dependencies {
            let input = source_input(
                &root,
                &access,
                &definitions,
                &outlines,
                &InputSelector::Definition { definition },
            )?;
            if !mandatory.contains(&input) {
                mandatory.push(input);
            }
        }
        mandatory.extend(builtins.into_iter().map(builtin_input));
        let github = GithubIssues::from_env(&root);
        let issue_states = crate::github::input_issue_states(
            &root,
            &github,
            &references,
            &definitions,
            &mandatory,
        );
        let issue_names = acknowledgments.iter().flat_map(|acknowledgment| {
            crate::fixme::FixmeBody::parse(acknowledgment["body"].as_str().unwrap()).issues
        });
        let issues = github.read_all(issue_names);
        for acknowledgment in &mut acknowledgments {
            let parsed = crate::fixme::FixmeBody::parse(acknowledgment["body"].as_str().unwrap());
            let mut seen = std::collections::BTreeSet::new();
            acknowledgment["issues"] = parsed
                .issues
                .into_iter()
                .filter(|issue| seen.insert(issue.clone()))
                .map(|reference| {
                    let state = issues
                        .get(&reference)
                        .map_or("open", crate::github::IssueRead::state);
                    json!({"reference": reference, "state": state})
                })
                .collect();
        }
        Ok(Self {
            root,
            access,
            subject_name: subject_name.to_owned(),
            has_applicable_fixme: !acknowledgments.is_empty(),
            subject_kind: AssessmentKind::Definition(
                subject.kind,
                crate::structural::has_query_directive(subject),
            ),
            subject_text: subject.text.clone(),
            outlines,
            reference_set,
            acknowledgments,
            mandatory,
            issue_states,
            github,
            recorded: Vec::new(),
        })
    }

Tests

Input 7: outline src/authoring/inputs.rs mod[tests]/fn[mandatory_inputs_through_symlinks_leaving_the_project_abort_preparation]
    // {test}`requirements.authoring.read_denial`
    #[cfg(unix)]
    // {test}`requirements.references.anchors`
    #[test]
    fn mandatory_inputs_through_symlinks_leaving_the_project_abort_preparation() {
        let root = project();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("secret.rs"), "fn secret() {}\n").unwrap();
        std::os::unix::fs::symlink(
            outside.path().join("secret.rs"),
            root.path().join("src/escape.rs"),
        )
        .unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\n:impl: src/escape.rs\nThe project MUST be ready.\n:::\n",
        )
        .unwrap();
        let error = AssessmentSources::prepare(root.path(), "requirements.ready")
            .err()
            .unwrap();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
        assert!(error.to_string().contains("src/escape.rs"), "{error}");
        assert!(error.to_string().contains("outside the project"), "{error}");
    }
Input 8: outline src/authoring/inputs.rs mod[tests]/fn[anchored_files_contribute_root_node_inputs]
    // {test}`requirements.references.anchors`
    // {test}`requirements.references.authoring_inputs`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring_input`
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn anchored_files_contribute_root_node_inputs() {
        let root = project();
        fs::create_dir_all(root.path().join("skills")).unwrap();
        fs::write(root.path().join("skills/ready.md"), "# Skill\nBe ready.\n").unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\n:impl: skills/ready.md\n:test: skills/ready.md\nThe project MUST be ready.\n\nKeep the whole body.\n:impl: this is body text\n:::\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let inputs = sources.mandatory_inputs();
        let hash =
            crate::inputs::outline_input(root.path(), "skills/ready.md", "").unwrap()["hash"]
                .clone();
        assert_eq!(
            inputs,
            &[
                json!({
                    "requirements": "requirements.ready",
                    "matches": ["requirements.ready"],
                    "text": [":::{req} ready", "The project MUST be ready.", "", "Keep the whole body.", ":impl: this is body text", ":::"]
                }),
                json!({
                    "file": "skills/ready.md",
                    "item": "",
                    "hash": hash,
                    "kind": "file",
                    "text": ["# Skill", "Be ready."]
                }),
            ]
        );
        assert_eq!(
            sources.subject_text,
            "The project MUST be ready.\n\nKeep the whole body.\n:impl: this is body text"
        );
    }
Input 9: outline src/authoring/inputs.rs mod[tests]/fn[test_anchors_supply_only_the_selected_node]
    // {test}`requirements.references.authoring_inputs`
    // {test}`requirements.references.anchors`
    // {test}`requirements.authoring.mandatory_inputs`
    #[test]
    fn test_anchors_supply_only_the_selected_node() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn target() { assert_eq!(1, 1); }\nfn sibling() { panic!(\"UNRELATED_SOURCE\"); }\n",
        )
        .unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\n:test: src/lib.rs#fn[target]\nThe project MUST be ready.\n:::\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let inputs = sources.mandatory_inputs();
        assert_eq!(inputs.len(), 2, "{inputs:?}");
        let expected =
            crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[target]").unwrap();
        for key in ["file", "item", "hash"] {
            assert_eq!(inputs[1][key], expected[key]);
        }
        assert_eq!(inputs[1]["kind"], "fn");
        assert_eq!(
            inputs[1]["text"],
            json!(["fn target() { assert_eq!(1, 1); }"])
        );
        let prompt = super::super::initial_prompt(&sources).unwrap().joined();
        assert!(prompt.contains("assert_eq!(1, 1)"), "{prompt}");
        assert!(!prompt.contains("UNRELATED_SOURCE"), "{prompt}");
        assert!(!prompt.contains("fn sibling"), "{prompt}");
    }
Input 10: outline src/authoring/inputs.rs mod[tests]/fn[outside_test_anchors_follow_explicit_allow_and_disallow_rules]
    // {test}`requirements.references.anchors`
    // {test}`requirements.authoring.read_denial.mandatory`
    #[test]
    fn outside_test_anchors_follow_explicit_allow_and_disallow_rules() {
        let root = project();
        let outside = tempfile::tempdir().unwrap();
        let path = outside.path().join("check.txt");
        fs::write(&path, "CHECK_OUTSIDE_SOURCE\n").unwrap();
        let relative = format!(
            "../{}/check.txt",
            outside.path().file_name().unwrap().to_str().unwrap()
        );
        for anchor in [path.to_string_lossy().into_owned(), relative] {
            fs::write(
                root.path().join("md/requirements.md"),
                format!(":::{{req}} ready\n:test: {anchor}\nThe project MUST be ready.\n:::\n"),
            )
            .unwrap();
            let config = root.path().join("habeas.toml");
            fs::write(&config, "version = 1\n").unwrap();
            let error = AssessmentSources::prepare(root.path(), "requirements.ready")
                .err()
                .unwrap();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
            assert!(error.to_string().contains("outside the project"), "{error}");
            fs::write(
                &config,
                format!("version = 1\n[evidence]\nallow = ['{}']\n", path.display()),
            )
            .unwrap();
            let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
            assert!(
                super::super::initial_prompt(&sources)
                    .unwrap()
                    .joined()
                    .contains("CHECK_OUTSIDE_SOURCE")
            );
            fs::write(
                &config,
                format!(
                    "version = 1\n[evidence]\nallow = ['{}']\ndisallow = ['{}']\n",
                    path.display(),
                    path.display()
                ),
            )
            .unwrap();
            let error = AssessmentSources::prepare(root.path(), "requirements.ready")
                .err()
                .unwrap();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
            assert!(error.to_string().contains("disallowed"), "{error}");
        }
    }
Input 11: outline src/authoring/inputs.rs mod[tests]/fn[unreadable_or_denied_anchors_fail_before_inference]
    // {test}`requirements.references.anchors`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.read_denial.mandatory`
    #[test]
    // {test}`requirements.authoring.mandatory_inputs`
    fn unreadable_or_denied_anchors_fail_before_inference() {
        let root = project();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\n:impl: skills/missing.md\nThe project MUST be ready.\n:::\n",
        )
        .unwrap();
        let error = AssessmentSources::prepare(root.path(), "requirements.ready")
            .err()
            .unwrap();
        assert!(
            error
                .to_string()
                .contains("requirements.ready: cannot read :impl: anchor skills/missing.md"),
            "{error}"
        );

        // An anchor naming a node its existing file lacks fails the same way.
        fs::write(root.path().join("src/lib.rs"), "fn present() {}\n").unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\n:impl: src/lib.rs#fn[missing]\nThe project MUST be ready.\n:::\n",
        )
        .unwrap();
        let error = AssessmentSources::prepare(root.path(), "requirements.ready")
            .err()
            .unwrap();
        assert!(
            error
                .to_string()
                .contains("cannot read :impl: anchor src/lib.rs#fn[missing]"),
            "{error}"
        );

        fs::create_dir_all(root.path().join("private")).unwrap();
        fs::write(root.path().join("private/skill.md"), "secret\n").unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\n:impl: private/skill.md\nThe project MUST be ready.\n:::\n",
        )
        .unwrap();
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\ndisallow = ['private']\n",
        )
        .unwrap();
        let error = AssessmentSources::prepare(root.path(), "requirements.ready")
            .err()
            .unwrap();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
        assert!(error.to_string().contains("private/skill.md"), "{error}");
    }
Input 12: outline src/authoring/inputs.rs mod[tests]/fn[references_contribute_their_owning_outline_nodes]
    // {test}`requirements.references.authoring_inputs`
    // {test}`requirements.references.outline_comments`
    // {test}`requirements.references.anchors`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring.fixme_inputs`
    // {test}`requirements.references.roles`
    #[test]
    fn references_contribute_their_owning_outline_nodes() {
        let root = project();
        fs::create_dir_all(root.path().join("docs")).unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\n:impl: src/lib.rs#mod[inner]\nThe project MUST be ready.\n:::\n",
        )
        .unwrap();
        // A `{fixme}` contributes metadata for the node its comment belongs to;
        // an unnamed one is not an acknowledgment edge.
        fs::write(
            root.path().join("src/lib.rs"),
            "mod inner {\n    fn unrelated() {}\n}\n\n// :::{fixme} requirements.ready\n// The gap.\n// :::\nfn gap() {}\n\n// :::{fixme}\n// :github: example/app#1\n// :::\nfn tracked() {}\n",
        )
        .unwrap();
        fs::write(
            root.path().join("docs/guide.md"),
            format!(
                "# Intro\n\nText.\n\n# Usage\n\nSee {}.\n",
                role("test", "requirements.ready")
            ),
        )
        .unwrap();
        fs::write(
            root.path().join("notes.txt"),
            format!("first\n{}\n", role("test", "requirements.ready")),
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let items = sources
            .mandatory_inputs()
            .iter()
            .filter(|input| input.get("item").is_some())
            .map(|input| {
                (
                    input["file"].as_str().unwrap(),
                    input["item"].as_str().unwrap(),
                )
            })
            .collect::<Vec<_>>();
        assert_eq!(
            items,
            [
                ("docs/guide.md", "section[Usage]"),
                // A plain-text file contributes the complete file.
                ("notes.txt", ""),
            ]
        );
        let acknowledgments = sources.model_acknowledgments();
        assert_eq!(acknowledgments.len(), 1, "{acknowledgments:#?}");
        assert_eq!(acknowledgments[0]["file"], "src/lib.rs");
        assert_eq!(acknowledgments[0]["item"], "fn[gap]");
        assert_eq!(acknowledgments[0]["body"], "The gap.");
    }
Input 13: outline src/authoring/tools.rs mod[tests]/fn[references_report_anchors_as_file_or_node_sites]
    // {test}`requirements.authoring.reference_index`
    // {test}`requirements.references.anchors`
    #[test]
    fn references_report_anchors_as_file_or_node_sites() {
        let root = project();
        fs::create_dir_all(root.path().join("skills")).unwrap();
        fs::write(root.path().join("skills/ready.md"), "# Skill\n").unwrap();
        fs::create_dir_all(root.path().join("private")).unwrap();
        fs::write(root.path().join("private/notes.md"), "hidden\n").unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            format!(
                ":::{{req}} ready\n:impl: skills/ready.md#section[Skill]\nThe project MUST be ready.\n:::\n\n:::{{example}} case\n:test: skills/ready.md\n:test: private/notes.md\nA ready case. {}\n:::\n",
                role("cite", "requirements.ready")
            ),
        )
        .unwrap();
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n\n[evidence]\ndisallow = [\"private\"]\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let result = dispatch(
            &sources,
            "references",
            &json!({"selection": "requirements.*"}),
        )
        .unwrap();
        let mut sites = result.result["sites"].clone();
        assert!(
            sites[1]["item"]
                .take()
                .as_str()
                .unwrap()
                .starts_with("section@")
        );
        assert_eq!(
            sites,
            json!([
                {"name": "requirements.case", "role": "test", "file": "skills/ready.md", "item": null},
                {"name": "requirements.ready", "role": "cite", "file": "md/requirements.md", "item": null},
                {"name": "requirements.ready", "role": "impl", "file": "skills/ready.md", "item": "section[Skill]"},
            ])
        );
        assert!(result.inputs.is_empty());
        let filtered = dispatch(
            &sources,
            "references",
            &json!({"selection":"requirements.*", "roles":["impl"]}),
        )
        .unwrap();
        assert_eq!(
            filtered.result["sites"],
            json!([{"name":"requirements.ready","role":"impl","file":"skills/ready.md","item":"section[Skill]"}])
        );
        assert!(filtered.inputs.is_empty());
    }
Input 14: outline src/authoring/tools.rs mod[tests]/fn[ripgrep_referencing_searches_only_referencing_files_or_nodes]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.references.definition_globs`
    // {test}`requirements.references.anchors`
    #[test]
    fn ripgrep_referencing_searches_only_referencing_files_or_nodes() {
        let root = referencing_project();
        fs::write(
            root.path().join("src/gap.rs"),
            "// :::{fixme} requirements.ready\n// This boundary needs a test.\n// :::\nfn gap() { needle(); }\n",
        ).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = |referencing: Value, context: u64| {
            dispatch(
                &sources,
                "ripgrep",
                &json!({"pattern":"needle","context":context,"referencing":referencing}),
            )
        };
        // By default, every impl, test, or cite reference selects its whole file.
        assert_eq!(
            found(&search(json!({"selection":"requirements.ready"}), 0).unwrap()),
            [
                "src/cite.rs#fn[before]",
                "src/cite.rs#fn[cited]",
                "src/lib.rs#fn[ready]",
                "src/lib.rs#fn[unrelated]"
            ]
        );
        for scope in ["file", "node"] {
            assert_eq!(
                found(
                    &search(
                        json!({"selection":"requirements.ready","roles":["fixme"],"scope":scope}),
                        0
                    )
                    .unwrap()
                ),
                ["src/gap.rs#fn[gap]"]
            );
        }
        // Roles narrow the references; a glob selects several definitions,
        // including declaration anchors.
        assert_eq!(
            found(&search(json!({"selection":"requirements.*","roles":["impl"]}), 0).unwrap()),
            [
                "src/lib.rs#fn[ready]",
                "src/lib.rs#fn[unrelated]",
                "src/other.rs#fn[elsewhere]"
            ]
        );
        // Node scope searches only the nodes the references belong to, and
        // context windows stop at their boundaries.
        let node = search(json!({"selection":"requirements.ready","scope":"node"}), 5).unwrap();
        assert_eq!(
            found(&node),
            ["src/cite.rs#fn[cited]", "src/lib.rs#fn[ready]"]
        );
        // `path` still limits the search.
        let limited = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle","path":"src/lib.rs","referencing":{"selection":"requirements.*"}}),
        )
        .unwrap();
        assert_eq!(found(&limited).len(), 2);
        // A matching definition with no references in the roles finds nothing.
        let none = search(json!({"selection":"requirements.third"}), 0).unwrap();
        assert_eq!(none.result["matches"], json!([]));
        for (referencing, message) in [
            (
                json!({"selection":"requirements.none"}),
                "matches no requirement or named example",
            ),
            (
                json!({"selection":"requirements.ready","roles":["bogus"]}),
                "unknown referencing role",
            ),
            (
                json!({"selection":"requirements.ready","roles":"impl"}),
                "roles must be an array",
            ),
            (
                json!({"selection":"requirements.ready","scope":"dir"}),
                "unknown referencing scope",
            ),
            (
                json!({"selection":"requirements.ready","extra":1}),
                "unexpected referencing argument",
            ),
            (
                json!({"roles":["impl"]}),
                "referencing.selection must be a string",
            ),
            (json!("requirements.ready"), "referencing must be an object"),
        ] {
            let error = search(referencing.clone(), 0).err().unwrap();
            assert!(
                error.to_string().contains(message),
                "{referencing}: {error}"
            );
        }
    }
Input 15: outline src/authoring/tools.rs mod[tests]/fn[ripgrep_node_scope_searches_only_the_node_a_selector_anchor_names]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.references.anchors`
    #[test]
    fn ripgrep_node_scope_searches_only_the_node_a_selector_anchor_names() {
        let root = referencing_project();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\nThe project MUST be ready.\n:::\n\n:::{req} anchored\n:impl: src/plain.rs#fn[second]\nAnchored.\n:::\n\n:::{req} stale\n:impl: src/plain.rs#fn[gone]\nStale.\n:::\n",
        )
        .unwrap();
        fs::write(
            root.path().join("src/plain.rs"),
            "fn plain() {\n    needle();\n}\n\nfn second() {\n    needle();\n}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = |selection: &str, scope: &str| {
            dispatch(
                &sources,
                "ripgrep",
                &json!({"pattern":"needle","context":5,"referencing":{"selection":selection,"scope":scope}}),
            )
            .unwrap()
        };
        // Node scope searches only the node the anchor names, and the context
        // window stops at its boundary rather than reaching `plain`.
        let node = search("requirements.anchored", "node");
        assert_eq!(found(&node), ["src/plain.rs#fn[second]"]);
        // File scope searches the anchored file.
        assert_eq!(
            found(&search("requirements.anchored", "file")),
            ["src/plain.rs#fn[plain]", "src/plain.rs#fn[second]"]
        );
        // A selector that no longer resolves names no node to search.
        assert_eq!(
            found(&search("requirements.stale", "node")),
            Vec::<String>::new()
        );
    }
Input 16: outline src/authoring/tools.rs mod[tests]/fn[ast_grep_referencing_restricts_the_search_as_ripgrep_does]
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.references.definition_globs`
    // {test}`requirements.references.anchors`
    #[test]
    fn ast_grep_referencing_restricts_the_search_as_ripgrep_does() {
        let root = referencing_project();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = |referencing: Value| {
            dispatch(
                &sources,
                "ast_grep",
                &json!({"language":"rust","rule":{"rule":{"pattern":"needle()"}},"referencing":referencing}),
            )
        };
        assert_eq!(
            found(&search(json!({"selection":"requirements.ready","roles":["cite"]})).unwrap()),
            ["src/cite.rs#fn[before]", "src/cite.rs#fn[cited]"]
        );
        assert_eq!(
            found(&search(json!({"selection":"requirements.*","scope":"node"})).unwrap()),
            [
                "src/cite.rs#fn[cited]",
                "src/lib.rs#fn[ready]",
                "src/other.rs#fn[elsewhere]"
            ]
        );
        let error = search(json!({"selection":"requirements.ready","scope":"dir"}))
            .err()
            .unwrap();
        assert!(
            error.to_string().contains("unknown referencing scope"),
            "{error}"
        );
        for (referencing, message) in [
            (json!({"scope":"node"}), "selection must be a string"),
            (
                json!({"selection":"requirements.ready","roles":["bogus"]}),
                "unknown referencing role",
            ),
        ] {
            let error = search(referencing).err().unwrap();
            assert!(error.to_string().contains(message), "{error}");
        }
    }
Input 17: outline src/evidence.rs mod[tests]/fn[anchored_files_must_be_completely_covered_and_resolvable]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[anchored_files_must_be_completely_covered_and_resolvable]
  • Kind: fn
  • src/evidence.rs:3760–3851
    // {test}`requirements.references.anchors`
    // {test}`requirements.ci.requirement_text`
    // {test}`requirements.references.evidence_coverage`
    // {test}`requirements.ci.span`
    // {test}`requirements.examples.definition`
    #[test]
    fn anchored_files_must_be_completely_covered_and_resolvable() {
        let temp = fixture();
        let root = temp.path();
        fs::create_dir_all(root.join("skills")).unwrap();
        fs::write(root.join("skills/ready.md"), "# Skill\nUse ready.\n").unwrap();
        fs::write(
            root.join("md/requirements.md"),
            ":::{req} ready\n:test: skills/ready.md\n:test: missing.sh\nReady MUST hold.\n:::\n\n:::{example} case\n:test: skills/ready.md\nA ready case. {cite}`requirements.ready`\n:::\n",
        )
        .unwrap();
        // The root node is the whole file; its heading's section is not.
        let skill = |item: &str| outline(root, "skills/ready.md", item);
        let write = |name: &str, field: &str, text: &str, inputs: Value| {
            fs::write(
                root.join(format!("evidence/{name}.json")),
                json!({
                    field: text,
                    "determination": true,
                    "rationale": "Checked.",
                    "inputs": inputs,
                })
                .to_string(),
            )
            .unwrap();
        };
        // The option lines are not part of the definition text.
        write(
            "requirements.ready",
            "requirement",
            "Ready MUST hold.",
            json!([skill("section[Skill]")]),
        );
        write(
            "requirements.case",
            "example",
            "A ready case. {cite}`requirements.ready`",
            json!([skill("")]),
        );
        let errors = validate_repository(root).unwrap().errors.join("\n");
        assert!(!errors.contains("text changed"), "{errors}");
        assert!(
            errors.contains("evidence/requirements.ready.json: no input selects skills/ready.md (lines 1-2) anchored by :test: on requirement requirements.ready"),
            "{errors}"
        );
        assert!(
            errors.contains("evidence/requirements.ready.json: :test: anchor missing.sh on requirement requirements.ready at md/requirements.md:1 does not resolve"),
            "{errors}"
        );
        assert!(!errors.contains("requirements.case.json"), "{errors}");

        fs::write(
            root.join("md/requirements.md"),
            ":::{req} ready\n:test: skills/ready.md\nReady MUST hold.\n:::\n\n:::{example} case\n:test: skills/ready.md\nA ready case. {cite}`requirements.ready`\n:::\n",
        )
        .unwrap();
        write(
            "requirements.ready",
            "requirement",
            "Ready MUST hold.",
            json!([skill("")]),
        );
        let report = validate_repository(root).unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);

        // Changing the anchored file makes the evidence stale.
        fs::write(root.join("skills/ready.md"), "# Skill\nUse ready now.\n").unwrap();
        let errors = validate_repository(root).unwrap().errors.join("\n");
        assert!(
            errors.contains("evidence/requirements.ready.json: inputs[0]: outline input changed: skills/ready.md <root> (now lines 1-2) no longer has the recorded hash"),
            "{errors}"
        );
        fs::write(
            root.join("habeas.toml"),
            "version = 1\n[evidence]\ndisallow = ['skills/ready.md']\n",
        )
        .unwrap();
        let errors = validate_repository(root).unwrap().errors;
        assert!(
            errors
                .iter()
                .any(|error| error.contains("anchor skills/ready.md")
                    && error.contains("requirements.ready")
                    && error.contains("disallow")),
            "{errors:?}"
        );
    }
Input 18: outline src/evidence.rs mod[tests]/fn[selector_anchors_are_covered_by_inputs_selecting_the_node_or_an_ancestor]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[selector_anchors_are_covered_by_inputs_selecting_the_node_or_an_ancestor]
  • Kind: fn
  • src/evidence.rs:3853–3920
    // {test}`requirements.references.anchors`
    // {test}`requirements.ci.outline_inputs`
    // {test}`requirements.references.evidence_coverage`
    #[test]
    fn selector_anchors_are_covered_by_inputs_selecting_the_node_or_an_ancestor() {
        let temp = fixture();
        let root = temp.path();
        fs::write(
            root.join("src/lib.rs"),
            "mod inner {\n    fn run() {}\n    fn other() {}\n}\n",
        )
        .unwrap();
        fs::write(
            root.join("md/requirements.md"),
            ":::{req} ready\n:test: src/lib.rs#mod[inner]/fn[run]\nReady MUST hold.\n:::\n",
        )
        .unwrap();
        let write = |inputs: Value| {
            fs::write(
                root.join("evidence/requirements.ready.json"),
                json!({
                    "requirement": "Ready MUST hold.",
                    "determination": true,
                    "rationale": "Checked.",
                    "inputs": inputs,
                })
                .to_string(),
            )
            .unwrap();
        };
        let anchor_errors = || {
            validate_repository(root)
                .unwrap()
                .errors
                .into_iter()
                .filter(|error| error.contains("anchor"))
                .collect::<Vec<_>>()
        };
        write(json!([outline(root, "src/lib.rs", "mod[inner]/fn[other]")]));
        let errors = anchor_errors();
        assert_eq!(
            errors,
            [
                "evidence/requirements.ready.json: no input selects src/lib.rs#mod[inner]/fn[run] (lines 2-2) anchored by :test: on requirement requirements.ready"
            ],
        );
        for item in ["mod[inner]/fn[run]", "mod[inner]", ""] {
            write(json!([outline(root, "src/lib.rs", item)]));
            assert!(anchor_errors().is_empty(), "{item}: {:?}", anchor_errors());
        }
        fs::write(
            root.join("md/requirements.md"),
            ":::{req} ready\n:impl: src/lib.rs#mod[inner]/fn[run]\nReady MUST hold.\n:::\n",
        )
        .unwrap();
        write(json!([]));
        assert!(anchor_errors().is_empty(), "{:?}", anchor_errors());
        fs::write(
            root.join("md/requirements.md"),
            ":::{req} ready\n:impl: src/lib.rs#fn[missing]\nReady MUST hold.\n:::\n",
        )
        .unwrap();
        let errors = anchor_errors().join("\n");
        assert!(
            errors.contains(":impl: anchor src/lib.rs#fn[missing] on requirement requirements.ready at md/requirements.md:1 does not resolve to a readable, permitted file or node: src/lib.rs: no outline node matches \"fn[missing]\""),
            "{errors}"
        );
    }
Input 19: outline src/evidence.rs mod[tests]/fn[unsupported_and_empty_options_are_validation_errors]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[unsupported_and_empty_options_are_validation_errors]
  • Kind: fn
  • src/evidence.rs:3922–3940
    // {test}`requirements.references.anchors`
    #[test]
    fn unsupported_and_empty_options_are_validation_errors() {
        let temp = fixture();
        fs::write(
            temp.path().join("md/requirements.md"),
            ":::{req} ready\n:phrase: ready\n:impl:\nReady MUST hold.\n:::\n\n:::{example} case\n:impl: src/main.rs\nA case. {cite}`requirements.ready`\n:::\n",
        )
        .unwrap();
        let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
        for expected in [
            "md/requirements.md:2: requirement requirements.ready has unsupported option :phrase:",
            "md/requirements.md:3: requirement requirements.ready has an :impl: option without a file path",
            "md/requirements.md:8: example requirements.case has unsupported option :impl:",
        ] {
            assert!(errors.contains(expected), "missing {expected:?}: {errors}");
        }
        assert!(super::load_definitions(temp.path()).is_err());
    }
Input 20: outline src/evidence.rs mod[tests]/fn[requirements_inputs_omit_option_lines]
    // {test}`requirements.references.anchors`
    // {test}`requirements.ci.requirements_inputs`
    #[test]
    fn requirements_inputs_omit_option_lines() {
        let temp = fixture();
        fs::write(
            temp.path().join("md/requirements.md"),
            "# Rules\n\n:::{req} ready\n:impl: src/main.rs\nReady MUST hold.\n:::\n",
        )
        .unwrap();
        let definitions = super::load_definitions(temp.path()).unwrap();
        let ready = &definitions["requirements.ready"];
        assert_eq!(ready.text, "Ready MUST hold.");
        assert_eq!((ready.line_start, ready.line_end), (3, 6));
        assert_eq!(
            ready.raw_lines,
            [":::{req} ready", "Ready MUST hold.", ":::"]
        );
        assert_eq!(
            ready.anchors,
            [super::Anchor {
                kind: crate::ReferenceKind::Impl,
                file: "src/main.rs".to_owned(),
                item: String::new(),
            }]
        );
        let resolved = crate::inputs::InputSelector::Requirements {
            requirements: "requirements.ready".to_owned(),
        }
        .resolve(
            &fs::canonicalize(temp.path()).unwrap(),
            &definitions,
            &crate::inputs::OutlineCache::default(),
        )
        .unwrap();
        assert_eq!(resolved.text, ready.raw_lines);
    }
Input 21: 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 22: outline src/lib.rs mod[tests]/fn[anchor_options_are_metadata_not_body_text]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[anchor_options_are_metadata_not_body_text]
  • Kind: fn
  • src/lib.rs:1006–1048
    // {test}`requirements.references.anchors`
    #[test]
    // {test}`requirements.ci.span`
    // {test}`requirements.examples.definition`
    fn anchor_options_are_metadata_not_body_text() {
        let source = "::::{req} ready\n:impl: skills/ready.md\n:test: tests/ready.sh\nReady.\n\n:::{example} case\n:test: tests/case.sh\nA case.\n:::\n::::\n\n:::{req} plain\nText :impl: inline.\n\n:test: later.md\n:::\n";
        let blocks = definition_blocks(source);
        assert_eq!(blocks.len(), 3);
        let options = |index: usize| {
            blocks[index]
                .options
                .iter()
                .map(|option| (option.name.as_str(), option.value.as_str(), option.line))
                .collect::<Vec<_>>()
        };
        assert_eq!(
            options(0),
            [
                ("impl", "skills/ready.md", 2),
                ("test", "tests/ready.sh", 3)
            ]
        );
        assert_eq!(options(1), [("test", "tests/case.sh", 7)]);
        // Only lines immediately after the opening fence are options.
        assert!(options(2).is_empty());
        assert_eq!(
            super::without_options(source, blocks[0].body_start..blocks[0].body_end, &blocks)
                .trim(),
            "Ready.\n\n:::{example} case\nA case.\n:::"
        );
        assert_eq!(
            super::without_options(source, blocks[1].body_start..blocks[1].body_end, &blocks)
                .trim(),
            "A case."
        );

        let rendered = replace_definitions(source, "requirements", None, None);
        assert!(!rendered.contains(":impl: skills"), "{rendered}");
        assert!(!rendered.contains("skills/ready.md"), "{rendered}");
        assert!(!rendered.contains("tests/case.sh"), "{rendered}");
        assert!(rendered.contains("Text :impl: inline."), "{rendered}");
        assert!(rendered.contains(":test: later.md"), "{rendered}");
    }
Input 23: 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());
    }

Referenced definitions

Input 2: requirements selection requirements.references.outline_selectors
:::{req} outline_selectors
An outline selector MUST be a `/`-separated path of segments from the file's
root node to an outline node; the empty selector MUST select the root node. A
named node's segment MUST be `kind[name]`. An anonymous node's segment MUST be
`kind@hash`, where `hash` is the first twelve hexadecimal digits of its identity
hash under {cite}`requirements.references.structural_hash`. Siblings whose
segments would otherwise be identical MUST be disambiguated by `#N`, their
one-based position among those siblings in source order, except `line` nodes:
identical lines are interchangeable, so a `line` selector MUST resolve when any
line with that content exists in the file. In names, `%`, `[`, `]`, `/`, `#`,
`@`, and whitespace MUST be percent-encoded as UTF-8 bytes, so selectors are
reversible. Line numbers MUST NOT form part of a selector.
:::
Input 3: requirements selection requirements.references.roles
:::{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 4: requirements selection requirements.ci.schema
:::{req} schema
A requirement or example evidence file at `evidence/<full-name>.json` MUST be a JSON object with exactly `requirement` or `example`, `determination`, `rationale`, `references`, and `inputs`. `references` MUST be the reference-set digest defined by {cite}`requirements.ci.reference_set`. The definition text and rationale MUST be nonempty strings, `determination` MUST use one of the outcomes defined by {cite}`requirements.ci.outcomes`, and `inputs` MUST be an array. Every evidence input MUST have exactly one of three forms: an outline input with `file`, `item`, and `hash`; a requirements input with `requirements`, `matches`, and `text`; or a definition input with `definition` and `text`. File paths MUST resolve to permitted inputs under {cite}`requirements.ci.input_containment`. Project-local paths SHOULD be recorded relative to the project for portability; absolute and parent-relative paths MAY be used when their resolved targets are permitted. `matches` MUST be an array of distinct full definition names, `hash` MUST be a lowercase hexadecimal SHA-256 digest, and `text` MUST be a nonempty array of strings. Evidence MUST NOT store source text for outline inputs.
:::
Input 5: requirements selection requirements.authoring.mandatory_inputs
:::{req} mandatory_inputs
The harness MUST construct each assessment's mandatory input set by combining
the contributions specified by the requirements applicable to that subject and
its inputs. A requirement that contributes inputs MUST cite this requirement and
define which sources it contributes and when. The harness MUST include every
applicable contribution, deduplicate identical selections, and report
unresolvable mandatory inputs before inference. The complete set MUST be supplied
in the initial model request.
Generated output under project-root `evidence/`, including symlink aliases, MUST
be omitted from mandatory inputs when the default exclusion applies. An explicit
workspace allow MUST permit those selections; an explicit disallow MUST abort
under {cite}`requirements.authoring.read_denial.mandatory`.
:::
Input 6: requirements selection requirements.references.evidence_coverage
:::{req} evidence_coverage
For every `{test}` reference in a project source file, including one in a
requirement or example declaration, the evidence file for the referenced
requirement or example MUST contain an input whose resolved source ranges cover
the reference's file and line. An `{impl}`, `{cite}`, or `{fixme}` reference alone
MUST NOT require an input selecting its source. `{impl}` and `{cite}` sources
remain discoverable through {cite}`requirements.authoring.reference_index`;
`{fixme}` acknowledgments are supplied under
{cite}`requirements.authoring.fixme_inputs` and tracked by
{cite}`requirements.ci.reference_set`. Habeas MUST report every uncovered
reference requiring coverage with its role, full name, source file, and line
number.
:::

Other sources

Input 1: requirements selection requirements.references.anchors
:::{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.
:::