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.definition_globs

Requirements index · View definition

evidence Valid

Requirement

A definition glob MUST match a complete full name. * MUST match zero or more characters, including dots; all other valid name characters MUST match literally. An empty glob MUST be invalid. Every definition selection MUST use this matching rule, including requirements evidence inputs, CLI definition filters, and the authoring references tool, and MUST match against both requirements and named examples.

Rationale

The tests adequately cover requirements.references.definition_globs. They check the matching rule and each place the rule must apply.

Matching rule

  • src/definition_glob.rs#mod[tests]/fn[wildcard_crosses_dot_segments_and_matches_the_whole_name] checks that matching is anchored to the whole name. A prefix or suffix on foo.*.bar fails, and foo.bar.* does not match foo.bar.
  • The same test checks that * crosses dots: foo.*.bar matches both foo.x.bar and foo.x.y.bar.
  • It checks that other characters match literally. . is not a regex wildcard (foo.bar against fooxbar), and _ and - are literal.
  • It checks that an empty glob is invalid (validate("") errors) and that an unsupported character is invalid (foo[bar]).
  • Zero-character * matches are exercised in tests/commands.rs#fn[commands_report_invalid_arguments_and_unmatched_selectors]. There requirements.*ready matches both requirements.ready and requirements.xready.

Every selection path uses the rule

  • Evidence inputs: src/evidence.rs#mod[tests]/fn[requirements_inputs_track_matched_declarations_in_full_name_order] covers the dot-crossing glob foo.*.bar. It matches both a requirement and an example, and it also covers a glob that matches nothing. It rejects foo.[a].bar and "" as invalid.
  • Authoring habeas requirements reads: src/authoring/tools.rs#mod[tests]/fn[requirements_reads_select_requirements_and_examples_but_not_definitions] and tests/definitions.rs#fn[selections_match_requirements_and_examples_but_never_named_definitions] check that requirements.* or rules.* selects the requirement and the example. A term whose name also matches is not selected, and an exact definition name errors.
  • Authoring references tool: src/authoring/tools.rs#mod[tests]/fn[references_list_names_and_flattened_sites_without_recording_inputs] checks that requirements.* returns both requirements and the example, and that "" and bad name are rejected. The ripgrep and ast_grep referencing tests use globs and reject a missing selection.
  • CLI status and info: tests/commands.rs#fn[commands_report_invalid_arguments_and_unmatched_selectors] checks that [ is rejected as an invalid glob, that an unmatched glob fails, and that requirements.*ready matches. tests/definitions.rs#fn[selections_match_requirements_and_examples_but_never_named_definitions] checks rules.* for both commands and that info rules.used fails.

Empty glob on the CLI

  • No test passes an empty glob to the CLI directly. A search of the source shows info_markdown and status_markdown_with_coverage call the same definition_glob::validate. The empty-glob check is tested at the shared function, in evidence inputs and in the references tool. I do not count this as a gap.

Inputs

Implementation

Input 12: outline src/authoring/inputs.rs fn[source_input]
// {impl}`requirements.authoring.mandatory_inputs`
// {impl}`requirements.configuration.evidence_paths`
// {impl}`requirements.references.definition_globs`
fn source_input(
    root: &Path,
    access: &SourceAccess,
    definitions: &BTreeMap<String, Declaration>,
    outlines: &OutlineCache,
    selector: &InputSelector,
) -> io::Result<Value> {
    match selector {
        InputSelector::Outline { file, .. } => {
            access.file(root, Path::new(file))?;
        }
        InputSelector::Definition { definition } => {
            if let Some(definition) = definitions.get(definition) {
                access.file(root, Path::new(&definition.file))?;
            }
        }
        InputSelector::Requirements { requirements } => {
            for (name, definition) in definitions {
                if definition.kind != DefinitionKind::Term
                    && crate::definition_glob::matches(requirements, name)
                {
                    access.file(root, Path::new(&definition.file))?;
                }
            }
        }
    }
    let resolved = selector
        .resolve(root, definitions, outlines)
        .map_err(io::Error::other)?;
    for range in &resolved.ranges {
        access.file(root, Path::new(&range.file))?;
    }
    Ok(selector.to_model_input(&resolved))
}
Input 13: outline src/authoring/tools.rs fn[references]
// {impl}`requirements.references.definition_globs`
// {impl}`requirements.references.anchors`
// {impl}`requirements.authoring.no_line_numbers`
// {impl}`requirements.references.authoring_inputs`
fn references(sources: &AssessmentSources, args: &Map<String, Value>) -> io::Result<Listing> {
    check_keys(args, &["selection", "roles"])?;
    let roles = match args.get("roles") {
        None => vec![
            crate::ReferenceKind::Impl,
            crate::ReferenceKind::Cite,
            crate::ReferenceKind::Test,
        ],
        Some(Value::Array(roles)) => roles
            .iter()
            .map(|role| match role.as_str() {
                Some("impl") => Ok(crate::ReferenceKind::Impl),
                Some("cite") => Ok(crate::ReferenceKind::Cite),
                Some("test") => Ok(crate::ReferenceKind::Test),
                _ => Err(io::Error::other(format!(
                    "invalid reference role {role}; expected impl, cite, or test"
                ))),
            })
            .collect::<io::Result<Vec<_>>>()?,
        Some(_) => {
            return Err(io::Error::other(
                "roles must be an array of impl, cite, or test",
            ));
        }
    };
    let selection = if args.contains_key("selection") {
        let selection = string(args, "selection")?;
        crate::definition_glob::validate(selection).map_err(io::Error::other)?;
        Some(selection)
    } else {
        None
    };
    let definitions = crate::evidence::load_definitions(&sources.root)?;
    let selected: Vec<_> = definitions
        .iter()
        .filter(|(name, definition)| {
            definition.kind != crate::DefinitionKind::Term
                && selection
                    .is_none_or(|selection| crate::definition_glob::matches(selection, name))
        })
        .map(|(name, definition)| json!({"name": name, "kind": definition.kind.noun()}))
        .collect();
    let Some(selection) = selection else {
        return Ok(Listing::object(
            REFERENCE_ARRAYS,
            vec![selected, Vec::new()],
        ));
    };
    if selected.is_empty() {
        return Err(io::Error::other(format!(
            "selection {selection:?} matches no requirement or named example"
        )));
    }
    let mut errors = Vec::new();
    let mut found = crate::evidence::collect_references(&sources.root, &mut errors);
    // A considered source that cannot be read would silently drop its sites.
    if !errors.is_empty() {
        return Err(io::Error::other(format!(
            "cannot list reference sites because reference discovery failed; fix or restore the named source before retrying:\n{}",
            errors.join("\n")
        )));
    }
    found.retain(|reference| {
        // Only `{impl}`, `{cite}`, and `{test}` references are sites; a
        // `{fixme}` acknowledges a gap rather than locating the definition.
        roles.contains(&reference.kind)
            // A fence that never closes is a validation error, not a site.
            && reference.closed
            && crate::definition_glob::matches(selection, &reference.name)
            && definitions
                .get(&reference.name)
                .is_some_and(|definition| definition.kind != crate::DefinitionKind::Term)
    });
    let mut sites = Vec::new();
    for reference in &found {
        let file = relative_path(&sources.root, &reference.file)?;
        let parsed = sources.outlines.parse(&sources.root, &file);
        let item = parsed.as_ref().as_ref().ok().map(|parsed| {
            let index = parsed.outline.owner_at_line(reference.line);
            parsed.outline.nodes[index].selector.clone()
        });
        sites.push((
            reference.name.clone(),
            file,
            Some(reference.line),
            json!({
                "name": reference.name,
                "role": reference.kind.label(),
                "file": relative_path(&sources.root, &reference.file)?,
                "item": item,
            }),
        ));
    }
    // {impl}`requirements.references.anchors`
    for (name, definition) in &definitions {
        if definition.kind == crate::DefinitionKind::Term
            || !crate::definition_glob::matches(selection, name)
        {
            continue;
        }
        for anchor in &definition.anchors {
            if !roles.contains(&anchor.kind) {
                continue;
            }
            // Discovery omits excluded sources rather than aborting.
            let Ok(path) = sources.access.file(&sources.root, Path::new(&anchor.file)) else {
                continue;
            };
            let file = relative_path(&sources.root, &path)?;
            sites.push((
                name.clone(),
                file.clone(),
                None,
                json!({
                    "name": name,
                    "role": anchor.kind.label(),
                    "file": file,
                    "item": (!anchor.item.is_empty()).then_some(&anchor.item),
                }),
            ));
        }
    }
    sites.sort_by(|a, b| (&a.0, &a.1, a.2).cmp(&(&b.0, &b.1, b.2)));
    Ok(Listing::object(
        REFERENCE_ARRAYS,
        vec![selected, sites.into_iter().map(|site| site.3).collect()],
    ))
}
Input 14: outline src/authoring/tools.rs fn[referencing]
/// The regions an optional `referencing` argument selects: the sources that
/// carry a reference in one of its roles to a requirement or example its
/// selection matches, including declaration anchors, as referencing nodes or
/// whole files by its scope.
// {impl}`requirements.references.definition_globs`
// {impl}`requirements.references.anchors`
fn referencing(
    sources: &AssessmentSources,
    args: &Map<String, Value>,
) -> io::Result<Option<ReferenceRegions>> {
    let Some(scope) = args.get("referencing") else {
        return Ok(None);
    };
    let scope = scope
        .as_object()
        .ok_or_else(|| io::Error::other("referencing must be an object"))?;
    for key in scope.keys() {
        if !["selection", "roles", "scope"].contains(&key.as_str()) {
            return Err(io::Error::other(format!(
                "unexpected referencing argument {key:?}"
            )));
        }
    }
    let selection = scope
        .get("selection")
        .and_then(Value::as_str)
        .ok_or_else(|| io::Error::other("referencing.selection must be a string"))?;
    crate::definition_glob::validate(selection).map_err(io::Error::other)?;
    let roles = match scope.get("roles") {
        None => vec![
            crate::ReferenceKind::Impl,
            crate::ReferenceKind::Test,
            crate::ReferenceKind::Cite,
        ],
        Some(Value::Array(roles)) => roles
            .iter()
            .map(|role| match role.as_str() {
                Some("impl") => Ok(crate::ReferenceKind::Impl),
                Some("test") => Ok(crate::ReferenceKind::Test),
                Some("cite") => Ok(crate::ReferenceKind::Cite),
                Some("fixme") => Ok(crate::ReferenceKind::Fixme),
                _ => Err(io::Error::other(format!(
                    "unknown referencing role {role}; expected impl, test, cite, or fixme"
                ))),
            })
            .collect::<io::Result<_>>()?,
        Some(_) => {
            return Err(io::Error::other(
                "referencing.roles must be an array of roles",
            ));
        }
    };
    let whole_files = match scope.get("scope") {
        None => true,
        Some(value) => match value.as_str() {
            Some("file") => true,
            Some("node") => false,
            _ => {
                return Err(io::Error::other(format!(
                    "unknown referencing scope {value}; expected \"node\" or \"file\""
                )));
            }
        },
    };
    let definitions = crate::evidence::load_definitions(&sources.root)?;
    let selected = |name: &str| {
        crate::definition_glob::matches(selection, name)
            && definitions
                .get(name)
                .is_some_and(|definition| definition.kind != crate::DefinitionKind::Term)
    };
    if !definitions.keys().any(|name| selected(name)) {
        return Err(io::Error::other(format!(
            "referencing selection {selection:?} matches no requirement or named example"
        )));
    }
    let mut errors = Vec::new();
    let found = crate::evidence::collect_references(&sources.root, &mut errors);
    // A considered source that cannot be read would silently drop its sources.
    if !errors.is_empty() {
        return Err(io::Error::other(format!(
            "cannot restrict the search to referencing sources because reference discovery failed; fix or restore the named source before retrying:\n{}",
            errors.join("\n")
        )));
    }
    let mut regions = ReferenceRegions(BTreeMap::new());
    for reference in found {
        if !reference.closed
            || !reference.is_fixme_edge()
            || !roles.contains(&reference.kind)
            || !selected(&reference.name)
        {
            continue;
        }
        let file = relative_path(&sources.root, &reference.file)?;
        let lines = if whole_files {
            None
        } else {
            let parsed = sources.outlines.parse(&sources.root, &file);
            match parsed.as_ref() {
                Ok(parsed) => {
                    let node = &parsed.outline.nodes[parsed.outline.owner_at_line(reference.line)];
                    Some((node.line_start, node.line_end))
                }
                Err(_) => None,
            }
        };
        regions.add(file, lines);
    }
    for (name, definition) in &definitions {
        if !selected(name) {
            continue;
        }
        for anchor in &definition.anchors {
            if !roles.contains(&anchor.kind) {
                continue;
            }
            // Discovery omits excluded sources rather than aborting.
            let Ok(path) = sources.access.file(&sources.root, Path::new(&anchor.file)) else {
                continue;
            };
            let file = relative_path(&sources.root, &path)?;
            let lines = if whole_files || anchor.item.is_empty() {
                None
            } else {
                let parsed = sources.outlines.parse(&sources.root, &file);
                match parsed.as_ref() {
                    Ok(parsed) => match parsed.outline.resolve(&anchor.item) {
                        Ok(index) => {
                            let node = &parsed.outline.nodes[index];
                            Some((node.line_start, node.line_end))
                        }
                        // An anchor that no longer resolves names no node.
                        Err(_) => continue,
                    },
                    Err(_) => None,
                }
            };
            regions.add(file, lines);
        }
    }
    Ok(Some(regions))
}
Input 16: outline src/commands.rs fn[info_markdown]
// {impl}`requirements.definitions.selection`
// {impl}`requirements.references.definition_globs`
pub fn info_markdown(root: &Path, selector: &str) -> io::Result<String> {
    let inspection = inspect_repository(root)?;
    definition_glob::validate(selector)
        .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
    let outlines = crate::inputs::OutlineCache::default();
    let mut pages = Vec::new();
    for (name, definition) in &inspection.definitions {
        if definition.kind == crate::DefinitionKind::Term {
            continue;
        }
        if !definition_glob::matches(selector, name) {
            continue;
        }
        let evidence = LoadedDetailEvidence::load(root, name, &inspection.report);
        let mut page = render_cli_detail_page(
            name,
            &definition.source,
            &definition.text,
            definition.kind,
            &evidence,
            &RenderSources {
                root,
                definitions: &inspection.definitions,
                references: &inspection.references,
                source_links: None,
                outlines: &outlines,
            },
        );
        if let Some(sites) = inspection.sites.get(name) {
            page.push_str(&site_section(root, sites, &inspection.report));
        }
        pages.push(page);
    }
    if pages.is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            format!("no definitions match {selector:?}"),
        ));
    }
    Ok(pages.join("\n\n---\n\n"))
}

Tests

Input 2: outline src/authoring/tools.rs mod[tests]/fn[requirements_reads_select_requirements_and_examples_but_not_definitions]
  • File: src/authoring/tools.rs
  • Selector: mod[tests]/fn[requirements_reads_select_requirements_and_examples_but_not_definitions]
  • Kind: fn
  • src/authoring/tools.rs:1651–1694
    // {test}`requirements.definitions.selection`
    // {test}`requirements.references.definition_globs`
    // {test}`requirements.authoring.source_tools`
    #[test]
    fn requirements_reads_select_requirements_and_examples_but_not_definitions() {
        let root = project();
        fs::write(
            root.path().join("md/requirements.md"),
            format!(
                ":::{{req}} ready\nThe project MUST be ready.\n:::\n\n\
                 :::{{example}} case\nA ready case. {}\n:::\n\n\
                 :::{{definition}} unused\n:phrase: unused\n\nNot referenced.\n:::\n",
                role("cite", "requirements.ready")
            ),
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let delivery = dispatch(
            &sources,
            "habeas",
            &json!({"requirements": "requirements.*"}),
        )
        .unwrap();
        assert_eq!(
            delivery.result["input"]["matches"],
            json!(["requirements.case", "requirements.ready"]),
            "{}",
            delivery.result
        );
        assert_eq!(delivery.result["definitions"], json!([]));
        let error = dispatch(
            &sources,
            "habeas",
            &json!({"requirements": "requirements.unused"}),
        )
        .err()
        .unwrap();
        assert!(
            error
                .to_string()
                .contains("matches no requirement or example"),
            "{error}"
        );
    }
Input 3: outline src/authoring/tools.rs mod[tests]/fn[references_list_names_and_flattened_sites_without_recording_inputs]
    // {test}`requirements.authoring.reference_index`
    // {test}`requirements.references.definition_globs`
    // {test}`requirements.authoring.no_line_numbers`
    // {test}`requirements.authoring.read_denial`
    #[test]
    // {test}`requirements.references.authoring_inputs`
    // {test}`requirements.authoring.read_denial`
    fn references_list_names_and_flattened_sites_without_recording_inputs() {
        let root = project();
        fs::write(
            root.path().join("md/requirements.md"),
            format!(
                ":::{{req}} ready\nThe project MUST be ready.\n:::\n\n:::{{req}} other\nOther MUST hold.\n:::\n\n:::{{example}} case\nA ready case. {}\n:::\n\n:::{{definition}} word\n:phrase: word\n:impl: src/lib.rs#fn[work]\nA vocabulary term.\n:::\n",
                role("cite", "requirements.ready")
            ),
        )
        .unwrap();
        fs::write(
            root.path().join("src/lib.rs"),
            format!(
                "// {}\nfn zeta() {{}}\n\n// {}\nfn work() {{\n    // {}\n    // {}\n}}\n",
                role("test", "requirements.ready"),
                role("impl", "requirements.ready"),
                role("cite", "requirements.other"),
                role("term", "requirements.word"),
            ),
        )
        .unwrap();
        fs::create_dir_all(root.path().join("private")).unwrap();
        fs::write(
            root.path().join("private/notes.md"),
            format!("{}\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 all = dispatch(&sources, "references", &json!({})).unwrap();
        assert_eq!(
            all.result,
            json!({"definitions": [
                {"name": "requirements.case", "kind": "example"},
                {"name": "requirements.other", "kind": "requirement"},
                {"name": "requirements.ready", "kind": "requirement"},
            ], "sites": []})
        );
        assert!(all.inputs.is_empty());

        let ready = dispatch(
            &sources,
            "references",
            &json!({"selection": "requirements.ready"}),
        )
        .unwrap();
        let mut result = ready.result.clone();
        let markdown = result["sites"][0]["item"].take();
        assert!(
            markdown.as_str().unwrap().starts_with("section@"),
            "{markdown}"
        );
        assert_eq!(
            result,
            json!({"definitions": [{"name": "requirements.ready", "kind": "requirement"}], "sites": [
                {"name": "requirements.ready", "role": "cite", "file": "md/requirements.md", "item": null},
                {"name": "requirements.ready", "role": "test", "file": "src/lib.rs", "item": "fn[zeta]"},
                {"name": "requirements.ready", "role": "impl", "file": "src/lib.rs", "item": "fn[work]"},
            ]})
        );
        assert!(ready.inputs.is_empty());
        let implementations = dispatch(
            &sources,
            "references",
            &json!({"selection":"requirements.ready", "roles":["impl", "impl"]}),
        )
        .unwrap();
        assert_eq!(
            implementations.result,
            json!({"definitions":[{"name":"requirements.ready","kind":"requirement"}],
                "sites":[{"name":"requirements.ready","role":"impl","file":"src/lib.rs","item":"fn[work]"}]})
        );
        assert!(implementations.inputs.is_empty());
        let names = dispatch(
            &sources,
            "references",
            &json!({"selection":"requirements.ready", "roles":[]}),
        )
        .unwrap();
        assert_eq!(names.result["definitions"], ready.result["definitions"]);
        assert_eq!(names.result["sites"], json!([]));
        assert!(names.inputs.is_empty());
        assert_eq!(
            dispatch(&sources, "references", &json!({"roles":["impl"]}))
                .unwrap()
                .result,
            all.result
        );
        for roles in [json!(null), json!("impl"), json!(["fixme"]), json!([1])] {
            let error = dispatch(&sources, "references", &json!({"roles":roles}))
                .err()
                .unwrap();
            assert!(error.to_string().contains("role"), "{roles}: {error}");
        }

        let flattened = dispatch(
            &sources,
            "references",
            &json!({"selection": "requirements.*"}),
        )
        .unwrap();
        let sites = flattened.result["sites"].as_array().unwrap();
        assert_eq!(flattened.result["definitions"], all.result["definitions"]);
        assert_eq!(sites.len(), 4);
        assert_eq!(sites[0]["name"], "requirements.other");
        assert_eq!(sites[0]["item"], "fn[work]");
        assert!(flattened.inputs.is_empty());

        // A fenced reference in a comment run is a site of the node the run
        // belongs to; a `{fixme}` is not a site, nor is a fence that never
        // closes.
        fs::write(
            root.path().join("src/fenced.rs"),
            format!(
                "// :::{} requirements.other\n// Commentary.\n// :::\nfn fenced() {{}}\n\n// :::{} requirements.other\n// Tracked by example/queue#1.\n// :::\nfn gap() {{}}\n\n// :::{} requirements.other\n// never closed\n\nfn open() {{}}\n",
                "{impl}", "{fixme}", "{cite}"
            ),
        )
        .unwrap();
        let other = dispatch(
            &sources,
            "references",
            &json!({"selection": "requirements.other"}),
        )
        .unwrap();
        assert_eq!(
            other.result["sites"],
            json!([
                {"name": "requirements.other", "role": "impl", "file": "src/fenced.rs", "item": "fn[fenced]"},
                {"name": "requirements.other", "role": "cite", "file": "src/lib.rs", "item": "fn[work]"},
            ])
        );
        fs::remove_file(root.path().join("src/fenced.rs")).unwrap();

        for selection in ["requirements.missing", "requirements.word", "bad name", ""] {
            assert!(
                dispatch(&sources, "references", &json!({"selection": selection})).is_err(),
                "accepted {selection:?}"
            );
        }
        let error = dispatch(&sources, "references", &json!({"selection": 1}))
            .err()
            .unwrap();
        assert!(
            error.to_string().contains("selection must be a string"),
            "{error}"
        );
        assert!(
            dispatch(
                &sources,
                "references",
                &json!({"name": "requirements.ready"})
            )
            .is_err()
        );
    }
Input 4: 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 5: 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 6: outline src/definition_glob.rs mod[tests]/fn[wildcard_crosses_dot_segments_and_matches_the_whole_name]
  • File: src/definition_glob.rs
  • Selector: mod[tests]/fn[wildcard_crosses_dot_segments_and_matches_the_whole_name]
  • Kind: fn
  • src/definition_glob.rs:40–57
    // {test}`requirements.references.definition_globs`
    // {test}`requirements.references.definition_glob_cases`
    #[test]
    fn wildcard_crosses_dot_segments_and_matches_the_whole_name() {
        assert!(validate("foo.*.bar").is_ok());
        assert!(matches("foo.*.bar", "foo.x.bar"));
        assert!(matches("foo.*.bar", "foo.x.y.bar"));
        assert!(!matches("foo.*.bar", "prefix.foo.x.bar"));
        assert!(!matches("foo.*.bar", "foo.x.bar.suffix"));
        assert!(!matches("foo.bar", "fooxbar"));
        assert!(matches("foo_bar-baz", "foo_bar-baz"));
        assert!(!matches("foo_bar-baz", "fooXbar-baz"));
        assert!(!matches("foo_bar-baz", "foo_barXbaz"));
        assert!(!matches("foo.bar.*", "foo.bar"));
        assert!(matches("foo.bar.*", "foo.bar.x.y"));
        assert!(validate("").is_err());
        assert!(validate("foo[bar]").is_err());
    }
Input 7: outline src/evidence.rs mod[tests]/fn[requirements_inputs_track_matched_declarations_in_full_name_order]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[requirements_inputs_track_matched_declarations_in_full_name_order]
  • Kind: fn
  • src/evidence.rs:2857–2975
    // {test}`requirements.ci.requirements_inputs`
    // {test}`requirements.references.definition_glob_cases`
    // {test}`requirements.references.definition_globs`
    #[test]
    fn requirements_inputs_track_matched_declarations_in_full_name_order() {
        let temp = fixture();
        let bar = ":::{req} a.bar\nBar.\n:::\n";
        let nested = ":::{example} a.b.bar\nNested. {cite}`foo.a.bar`\n:::\n";
        let other = ":::{req} other\nOther.\n:::\n";
        let write = |declarations: &[&str]| {
            fs::write(
                temp.path().join("md/foo.md"),
                format!("# Foo\n\n{}", declarations.join("\n")),
            )
            .unwrap();
        };
        let lines = |declaration: &str| declaration.lines().map(str::to_owned).collect::<Vec<_>>();
        let mut text = lines(nested);
        text.push(String::new());
        text.extend(lines(bar));
        let record = |glob: &str| {
            json!({
                "requirement": "Other.",
                "determination": true,
                "rationale": "Both matches were examined.",
                "inputs": [{
                    "requirements": glob,
                    "matches": ["foo.a.b.bar", "foo.a.bar"],
                    "text": text,
                }]
            })
            .to_string()
        };
        fs::write(
            temp.path().join("evidence/foo.other.json"),
            record("foo.*.bar"),
        )
        .unwrap();
        let errors = || {
            validate_repository(temp.path())
                .unwrap()
                .errors
                .into_iter()
                .filter(|error| error.starts_with("evidence/foo.other.json"))
                .collect::<Vec<_>>()
        };

        // `*` crosses dots, the example sorts before the requirement by full
        // name, and the stored text is both complete fenced declarations.
        write(&[bar, nested, other]);
        assert!(errors().is_empty(), "{:?}", errors());
        // Moving unchanged declarations does not invalidate the input.
        write(&[other, "Some prose.\n", nested, "More prose.\n", bar]);
        assert!(errors().is_empty(), "{:?}", errors());

        write(&[&bar.replace("Bar.", "Changed."), nested, other]);
        let changed = errors().join("\n");
        assert!(
            changed.contains(
                "inputs[0]: input text changed for Requirements { requirements: \"foo.*.bar\" }; changed definitions [\"foo.a.bar\"]\n- Bar.\n+ Changed."
            ),
            "{changed}"
        );

        let added = ":::{req} z.bar\nAdded.\n:::\n";
        write(&[bar, nested, other, added]);
        assert!(
            errors().join("\n").contains(
                "inputs[0]: requirements glob \"foo.*.bar\" matches changed; added [\"foo.z.bar\"], removed []"
            ),
            "{:?}",
            errors()
        );
        write(&[bar, other]);
        assert!(
            errors().join("\n").contains(
                "requirements glob \"foo.*.bar\" matches changed; added [], removed [\"foo.a.b.bar\"]"
            ),
            "{:?}",
            errors()
        );
        write(&[&bar.replace("a.bar", "c.bar"), nested, other]);
        assert!(
            errors().join("\n").contains(
                "requirements glob \"foo.*.bar\" matches changed; added [\"foo.c.bar\"], removed [\"foo.a.bar\"]"
            ),
            "{:?}",
            errors()
        );

        write(&[bar, nested, other]);
        fs::write(
            temp.path().join("evidence/foo.other.json"),
            record("foo.*.none"),
        )
        .unwrap();
        assert_eq!(
            errors(),
            [
                "evidence/foo.other.json: inputs[0]: requirements glob \"foo.*.none\" matches no requirement or example"
            ]
        );

        // A selection that is not a valid definition glob is rejected.
        for (glob, problem) in [
            ("foo.[a].bar", "unsupported character '['"),
            ("", "definition glob must not be empty"),
        ] {
            fs::write(temp.path().join("evidence/foo.other.json"), record(glob)).unwrap();
            let found = errors();
            assert!(
                found.len() == 1
                    && found[0].contains("inputs[0]")
                    && found[0].contains(&format!("requirements glob {glob:?}"))
                    && found[0].contains(problem),
                "{glob:?}: {found:?}"
            );
        }
    }
Input 8: outline tests/commands.rs fn[verbose_status_lists_fixme_judgments_and_globs_scope_issue_groups]
  • File: tests/commands.rs
  • Selector: fn[verbose_status_lists_fixme_judgments_and_globs_scope_issue_groups]
  • Kind: fn
  • tests/commands.rs:346–400
// {test}`requirements.cli.status`
// {test}`requirements.cli.fixme_summary`
// {test}`requirements.references.definition_globs`
#[test]
fn verbose_status_lists_fixme_judgments_and_globs_scope_issue_groups() {
    let temp = fixme_fixture();
    let output = habeas(temp.path(), &["status", "--verbose"]);
    assert!(output.status.success(), "{output:?}");
    let text = String::from_utf8(output.stdout).unwrap();
    for name in ["alpha", "beta", "case", "unlinked"] {
        assert!(text.contains(&format!("rules.{name}")), "{text}");
    }
    for detail in [
        "requirement",
        "example",
        "#123 is not a qualified issue",
        "https://github.com/rust-lang/rust/issues/456",
        "Unlinked extra detail",
        "An unrelated note",
        "&lt;script&gt;alert(1)&lt;/script&gt;",
    ] {
        assert!(text.contains(detail), "{text}");
    }
    assert!(!text.contains("<script>"), "{text}");

    let output = habeas(temp.path(), &["status", "rules.case", "--verbose"]);
    assert!(output.status.success(), "{output:?}");
    let filtered = String::from_utf8(output.stdout).unwrap();
    assert!(
        filtered.contains("example/app#45") && filtered.contains("affects 1 judgment"),
        "{filtered}"
    );
    assert!(filtered.contains("rules.case"), "{filtered}");
    for excluded in [
        "rules.alpha",
        "rules.beta",
        "rules.unlinked",
        "example/app#123",
        "rust-lang/rust",
    ] {
        assert!(!filtered.contains(excluded), "{filtered}");
    }

    let output = habeas(temp.path(), &["status", "--verbose", "rules.unlinked"]);
    assert!(output.status.success(), "{output:?}");
    let unlinked = String::from_utf8(output.stdout).unwrap();
    assert!(unlinked.contains("rules.unlinked"), "{unlinked}");
    assert!(
        unlinked
            .lines()
            .any(|line| line.contains("1 judgment") && line.contains("without an issue")),
        "{unlinked}"
    );
    assert!(!unlinked.contains("affects"), "{unlinked}");
}
Input 9: outline tests/commands.rs fn[status_preserves_repository_wide_rust_findings_in_every_form]
  • File: tests/commands.rs
  • Selector: fn[status_preserves_repository_wide_rust_findings_in_every_form]
  • Kind: fn
  • tests/commands.rs:460–513
// {test}`requirements.cli.status`
// {test}`requirements.references.rust_item_coverage`
// {test}`requirements.references.definition_globs`
// {test}`requirements.references.coverage.report`
#[test]
fn status_preserves_repository_wide_rust_findings_in_every_form() {
    let temp = fixture();
    let nested = temp.path().join("src/nested");
    // `main` is read by an evidence record; this item is read by none.
    fs::write(temp.path().join("src/extra.rs"), "fn unread() {}\n").unwrap();
    for flags in [
        [].as_slice(),
        ["--all"].as_slice(),
        ["--verbose"].as_slice(),
        ["--all", "--verbose"].as_slice(),
    ] {
        for selection in [None, Some("requirements.ready")] {
            for coverage in [false, true] {
                let mut args = vec!["status"];
                args.extend_from_slice(flags);
                args.extend(selection);
                if coverage {
                    args.push("--coverage");
                }
                let output = habeas(&nested, &args);
                assert!(output.status.success(), "{args:?}: {output:?}");
                let text = String::from_utf8(output.stdout).unwrap();
                if coverage {
                    assert!(text.contains("## Coverage warnings"), "{args:?}: {text}");
                    assert!(
                    text.contains(
                        "src/extra.rs:1: function unread has no recent coverage: it has no requirement or example reference, and no recent evidence record or review read it"
                    ),
                    "{args:?}: {text}"
                );
                } else {
                    assert!(
                        text.contains(
                            "1 nodes have coverage warnings. Use `status --coverage` to see them."
                        ),
                        "{args:?}: {text}"
                    );
                    assert!(!text.contains("has no recent coverage"), "{args:?}: {text}");
                    assert!(!text.contains("## Coverage warnings"), "{args:?}: {text}");
                }
                assert!(
                    !text.contains("function main has no recent coverage"),
                    "{args:?}: {text}"
                );
                assert!(!text.contains("attestation"), "{args:?}: {text}");
            }
        }
    }
}
Input 10: outline tests/commands.rs fn[commands_report_invalid_arguments_and_unmatched_selectors]
// {test}`requirements.cli.status`
// {test}`requirements.cli.info`
// {test}`requirements.references.definition_globs`
#[test]
fn commands_report_invalid_arguments_and_unmatched_selectors() {
    let temp = fixture();
    for args in [
        ["status", "--wrong"].as_slice(),
        ["status", "--all", "extra", "more"].as_slice(),
        ["info"].as_slice(),
        ["info", "ready", "extra"].as_slice(),
    ] {
        let output = habeas(temp.path(), args);
        assert!(!output.status.success(), "{args:?}: {output:?}");
        assert!(
            String::from_utf8_lossy(&output.stderr).contains("Usage: habeas"),
            "{args:?}: {output:?}"
        );
    }
    for command in ["info", "status"] {
        let invalid = habeas(temp.path(), &[command, "["]);
        assert!(!invalid.status.success());
        assert!(
            String::from_utf8_lossy(&invalid.stderr).contains("invalid definition glob"),
            "{command}: {invalid:?}"
        );
    }
    let unmatched = habeas(temp.path(), &["info", "nothing.*"]);
    assert!(!unmatched.status.success());
    assert!(
        String::from_utf8_lossy(&unmatched.stderr).contains("no definitions match"),
        "{unmatched:?}"
    );
    let status = habeas(temp.path(), &["status", "requirements.*ready", "--all"]);
    assert!(status.status.success(), "{status:?}");
    let status = String::from_utf8(status.stdout).unwrap();
    assert!(
        status.contains("`requirements.ready` (requirement)"),
        "{status}"
    );
    assert!(
        status.contains("`requirements.xready` (requirement)"),
        "{status}"
    );
    assert!(!status.contains("| `requirements.pending`"), "{status}");
    let no_status = habeas(temp.path(), &["status", "nothing.*"]);
    assert!(!no_status.status.success());
    assert!(String::from_utf8_lossy(&no_status.stderr).contains("no definitions match"));

    let outside_project = TempDir::new().unwrap();
    let status = habeas(outside_project.path(), &["status"]);
    assert!(!status.status.success(), "{status:?}");
    assert!(
        String::from_utf8_lossy(&status.stderr)
            .contains("cannot find a project with Cargo.toml and book.toml"),
        "{status:?}"
    );
}
Input 11: outline tests/definitions.rs fn[selections_match_requirements_and_examples_but_never_named_definitions]
  • File: tests/definitions.rs
  • Selector: fn[selections_match_requirements_and_examples_but_never_named_definitions]
  • Kind: fn
  • tests/definitions.rs:349–417
// {test}`requirements.definitions.selection`
// {test}`requirements.references.definition_globs`
#[test]
fn selections_match_requirements_and_examples_but_never_named_definitions() {
    let temp = fixture();
    let root = temp.path();
    fs::write(
        root.join("md/rules.md"),
        ":::{req} ready\nUse {term}`glossary.a`.\n:::\n\n\
         :::{example} case\nA ready case. {cite}`rules.ready`\n:::\n\n\
         :::{definition} used\n:phrase: used\n\nNot referenced by the selection.\n:::\n",
    )
    .unwrap();
    // The glob selects the requirement and the example, not the definition
    // whose name it also matches, and that definition is not a dependency.
    let selected = vec![
        requirements(root, "rules.*", &["rules.case", "rules.ready"]),
        definition(root, "glossary.a"),
        definition(root, "glossary.b"),
    ];
    let path = record(root, "rules.ready", selected.clone());
    approve(&path);
    let errors = validate_repository(root).unwrap().errors;
    assert!(
        errors
            .iter()
            .all(|error| !error.starts_with("evidence/rules.ready.json")),
        "{errors:?}"
    );

    // A named definition's exact name selects nothing.
    let exact = requirements(root, "rules.used", &["rules.used"]);
    record(
        root,
        "rules.ready",
        vec![
            exact,
            definition(root, "glossary.a"),
            definition(root, "glossary.b"),
        ],
    );
    let errors = validate_repository(root).unwrap().errors;
    assert!(
        errors
            .iter()
            .any(|error| error.contains("matches no requirement or example")),
        "{errors:?}"
    );
    record(root, "rules.ready", selected);

    // The CLI selection paths apply the same rule.
    for args in [["status", "rules.*"], ["info", "rules.*"]] {
        let output = std::process::Command::new(env!("CARGO_BIN_EXE_habeas"))
            .current_dir(root)
            .args(args)
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("rules.ready"), "{args:?}: {stdout}");
        assert!(stdout.contains("rules.case"), "{args:?}: {stdout}");
        assert!(!stdout.contains("rules.used"), "{args:?}: {stdout}");
    }
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_habeas"))
        .current_dir(root)
        .args(["info", "rules.used"])
        .output()
        .unwrap();
    assert!(!output.status.success(), "{output:?}");
}

Other sources

Input 1: requirements selection requirements.references.definition_globs
:::{req} definition_globs
A definition glob MUST match a complete full name. `*` MUST match zero or more characters, including dots; all other valid name characters MUST match literally. An empty glob MUST be invalid. Every definition selection MUST use this matching rule, including requirements evidence inputs, CLI definition filters, and the authoring `references` tool, and MUST match against both requirements and named examples.
:::
Input 15: outline src/commands.rs fn[status_markdown_with_coverage]
/// Renders status with coverage-warning details when `coverage` is enabled.
// {impl}`requirements.cli.status`
// {impl}`requirements.references.coverage.report`
pub fn status_markdown_with_coverage(
    root: &Path,
    all: bool,
    glob: Option<&str>,
    verbose: bool,
    coverage: bool,
    github: &GithubIssues,
) -> io::Result<String> {
    let mut inspection = inspect_repository(root)?;
    crate::github::add_issue_findings(&mut inspection, github);
    if let Some(glob) = glob {
        definition_glob::validate(glob)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
        if !inspection.definitions.iter().any(|(name, d)| {
            d.kind != crate::DefinitionKind::Term && definition_glob::matches(glob, name)
        }) {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("no definitions match {glob:?}"),
            ));
        }
    }
    let mut output = String::from("# Definitions status\n\n");
    let mut rows = Vec::new();
    let mut findings = String::new();
    let mut fixmes = FixmeSummary::default();
    let mut associated_errors = BTreeSet::new();

    for (name, definition) in &inspection.definitions {
        if definition.kind == crate::DefinitionKind::Term {
            continue;
        }
        if glob.is_some_and(|glob| !definition_glob::matches(glob, name)) {
            continue;
        }
        let evidence = LoadedDetailEvidence::load(root, name, &inspection.report);
        for error in evidence.errors() {
            associated_errors.insert(error.clone());
        }
        fixmes.add(name, definition.kind.noun(), evidence.fixme_entries());
        if !all && evidence.state() == EvidenceState::Valid {
            continue;
        }
        if !all && !verbose && evidence.state() == EvidenceState::Fixme {
            continue;
        }

        rows.push((
            format!("`{name}` ({})", definition.kind.noun()),
            evidence.state().label(),
        ));
        if !evidence.errors().is_empty() {
            findings.push_str(&format!("\n### `{name}`\n\n<pre><code>"));
            findings.push_str(&escape_html(&evidence.errors().join("\n\n")));
            findings.push_str("</code></pre>\n");
        }
    }

    let fixmes = fixmes.render(verbose);
    if rows.is_empty() {
        output.push_str(if all {
            "No definitions found.\n"
        } else if !fixmes.is_empty() {
            "No other definitions need attention.\n"
        } else {
            "All matching definitions have valid evidence.\n"
        });
    } else {
        output.push_str(&render_evidence_table(&rows));
    }

    output.push_str(&fixmes);
    // Site reviews are checked on their own; list those needing attention,
    // or every one with `--all`, by requirement, file, and selector.
    // {impl}`requirements.references.site_review`
    let mut site_rows = Vec::new();
    for site in inspection
        .sites
        .iter()
        .filter(|(name, _)| glob.is_none_or(|glob| definition_glob::matches(glob, name)))
        .flat_map(|(_, sites)| sites)
    {
        let evidence =
            LoadedDetailEvidence::load_path(root, &site.review_path(), &inspection.report);
        for error in evidence.errors() {
            associated_errors.insert(error.clone());
        }
        if !evidence.errors().is_empty() {
            findings.push_str(&format!(
                "\n### `{}`\n\n<pre><code>",
                crate::sites::subject_label(&site.requirement, &site.file, &site.item)
            ));
            findings.push_str(&escape_html(&evidence.errors().join("\n\n")));
            findings.push_str("</code></pre>\n");
        }
        if all || evidence.state() != EvidenceState::Valid {
            site_rows.push(format!(
                "| `{}` | `{}` | `{}` | {} |\n",
                site.requirement,
                site.file,
                site.selector_label(),
                evidence.state().label()
            ));
        }
    }
    if !site_rows.is_empty() {
        output.push_str(
            "\n## Site reviews\n\n| Requirement | File | Selector | Evidence |\n| --- | --- | --- | --- |\n",
        );
        output.push_str(&site_rows.concat());
    }
    output.push_str(&disagreements(root, &inspection, glob));
    let other_findings = inspection
        .report
        .errors
        .iter()
        .filter(|error| !associated_errors.contains(error.as_str()))
        .collect::<Vec<_>>();
    match crate::evidence::untracked_reference_files(&inspection.root) {
        Ok(untracked) if untracked.is_empty() => {}
        Ok(untracked) => {
            output.push_str(
                "\n## Untracked files with references\n\n\
                 Reference discovery considers only files in the Git index, so these \
                 references are not validated. Stage the files with `git add` to include them.\n\n",
            );
            for file in untracked {
                let file = file.strip_prefix(&inspection.root).unwrap_or(&file);
                output.push_str(&format!("- `{}`\n", file.display()));
            }
        }
        Err(error) => output.push_str(&format!(
            "\n## Untracked files with references\n\nCannot check untracked files for references: {}\n",
            escape_html(&error.to_string())
        )),
    }
    if !findings.is_empty() {
        output.push_str("\n## Validation findings\n");
        output.push_str(&findings);
    }
    if !other_findings.is_empty() {
        output.push_str("\n## Other validation findings\n\n<pre><code>");
        output.push_str(&escape_html(
            &other_findings
                .into_iter()
                .map(String::as_str)
                .collect::<Vec<_>>()
                .join("\n\n"),
        ));
        output.push_str("</code></pre>\n");
    }
    // An invalid workspace file, including an invalid `[coverage]` table, is
    // already a validation finding; status still reports everything else and
    // says why the warnings could not be computed.
    match inspected_coverage_warnings(&inspection) {
        Ok(warnings) => output.push_str(&coverage_section(&warnings, coverage)),
        Err(error) => output.push_str(&format!(
            "\n## Coverage warnings\n\nCoverage warnings could not be computed: {}\n",
            escape_html(&error.to_string())
        )),
    }
    Ok(output)
}
Input 17: outline src/inputs.rs impl[InputSelector]/fn[resolve]
    pub(crate) fn resolve(
        &self,
        root: &Path,
        definitions: &BTreeMap<String, Declaration>,
        outlines: &OutlineCache,
    ) -> Result<ResolvedInput, String> {
        match self {
            Self::Outline { file, item } => {
                let parsed = outlines.parse(root, file);
                let parsed = parsed.as_ref().as_ref().map_err(Clone::clone)?;
                let index = parsed.resolve(file, item)?;
                let (range, text) = parsed.node_range(file, index);
                let node = &parsed.outline.nodes[index];
                Ok(ResolvedInput {
                    ranges: vec![range],
                    text,
                    matches: Vec::new(),
                    node: Some(ResolvedNode {
                        path: parsed.path.clone(),
                        index,
                        kind: if index == 0 { "file" } else { node.kind },
                        hash: node.structural_hash.clone(),
                    }),
                })
            }
            Self::Definition { definition } => {
                let target = definitions
                    .get(definition)
                    .filter(|d| d.kind == crate::DefinitionKind::Term)
                    .ok_or_else(|| format!("{definition}: no matching named definition"))?;
                check_project_file(root, &target.file)?;
                Ok(ResolvedInput {
                    ranges: vec![SourceRange {
                        file: target.file.clone(),
                        line_start: target.line_start,
                        line_end: target.line_end,
                        name: Some(definition.clone()),
                    }],
                    text: crate::redaction::redact_lines(&target.raw_lines),
                    matches: Vec::new(),
                    node: None,
                })
            }
            Self::Requirements { requirements } => {
                definition_glob::validate(requirements)
                    .map_err(|error| format!("requirements glob {requirements:?}: {error}"))?;
                let mut ranges = Vec::new();
                let mut text = Vec::new();
                let mut matches = Vec::new();
                for (name, definition) in definitions {
                    if definition.kind == crate::DefinitionKind::Term
                        || !definition_glob::matches(requirements, name)
                    {
                        continue;
                    }
                    check_project_file(root, &definition.file)?;
                    if !text.is_empty() {
                        text.push(String::new());
                    }
                    text.extend(crate::redaction::redact_lines(&definition.raw_lines));
                    ranges.push(SourceRange {
                        file: definition.file.clone(),
                        line_start: definition.line_start,
                        line_end: definition.line_end,
                        name: Some(name.clone()),
                    });
                    matches.push(name.clone());
                }
                if matches.is_empty() {
                    return Err(format!(
                        "requirements glob {requirements:?} matches no requirement or example"
                    ));
                }
                Ok(ResolvedInput {
                    ranges,
                    text,
                    matches,
                    node: None,
                })
            }
        }
    }