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.authoring.finish_search

Requirements index · View definition

evidence Valid

Requirement

The harness MUST expose:

finish_search({ search_id: UUID, used: Array<String> })
    -> { search_id: UUID, finished: true }

The arguments MUST contain exactly these fields.

Rationale

The tests adequately cover requirements.authoring.finish_search. That requirement has three obligations: the tool exists with the stated signature, its arguments are exactly search_id and used, and it returns {search_id, finished:true}.

  • Exposure and signature: src/authoring/tools.rs#mod[tests]/fn[finish_search_advertises_the_accounting_schema_and_selection_rule] asserts the full finish_search parameter schema. That schema has search_id as a UUID-format string and used as an array of strings. Both fields are required and additionalProperties is false. fn[dispatch_paged] routes finish_search to pages.finish_search, and I treated that routing as a pass-through. The behavioral tests call that same method.
  • Exactly these fields: src/authoring/searches.rs#mod[tests]/fn[invalid_completion_is_atomic_and_can_be_corrected] rejects null, [] and {}, a missing used, a missing search_id, and an extra field. Each rejection asserts the “exactly search_id and used” error. It also rejects wrong types for search_id and used. After each rejection it asserts that the search is still outstanding and that nothing was recorded. It then confirms a correct call succeeds.
  • Result shape: fn[delivered_searches_including_empty_results_need_explicit_completion] asserts that the result equals {"search_id": ..., "finished": true} for each finished search. fn[selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads] asserts the same result and that there is no text field.

Other behavior, such as dependency recording, deduplication, atomicity and the description text, belongs to the refining sub-requirements. Those carry their own {test} references and are not reassessed here. I found no gap.

Inputs

Implementation

Input 7: outline src/authoring/tools.rs fn[definitions]
// {impl}`requirements.authoring.file_discovery`
// {impl}`requirements.authoring.structural_search`
// {impl}`requirements.configuration.evidence_paths`
// {impl}`requirements.authoring.generated_inputs`
// {impl}`requirements.authoring.outline_tool`
// {impl}`requirements.authoring.reference_index`
// {impl}`requirements.authoring.github_reads`
// {impl}`requirements.authoring.finish_search`
// {impl}`requirements.authoring.finish_search.description`
// {impl}`requirements.authoring.tool_descriptions.common_case`
// {impl}`requirements.authoring.tool_descriptions.special_cases`
pub(crate) fn definitions() -> Vec<Value> {
    // Providers such as Anthropic require a plain object at the schema root.
    // Describe the alternative forms here and enforce them in read().
    let definitions = vec![
        json!({
            "name": "habeas",
            "description": "Read project source as evidence. Supply exactly one request form: file + line_start (optional line_end), file + item, requirements, or definition. Do not combine forms. Paths are project-relative. A line range is one-based and inclusive (omitted line_end reads through EOF) and returns {inputs, definitions}: the innermost outline nodes covering those lines, each with its item selector, kind, and source text, e.g. {\"file\":\"src/lib.rs\",\"line_start\":10,\"line_end\":20}. Line numbers only locate sources: results never give line numbers, and evidence records each node's selector and structural hash. Cite code by file and selector. The item form reads one outline node and returns {input, definitions}, e.g. {\"file\":\"src/lib.rs\",\"item\":\"impl[Thing]/fn[run]\"}; use the outline tool to list a file's selectors. Selectors are /-separated paths from the file's root: kind[name] for named nodes (Rust trait impls use impl[Thing/Trait]), kind@hash for anonymous nodes such as use declarations and plain-text lines (line@hash), and #N (one-based) for otherwise identical siblings; the empty item selects the whole file. Characters %, [, ], /, #, @ and whitespace in names are percent-encoded UTF-8 bytes. The requirements form takes a definition selection: a full requirement or example name, or a glob matching complete names where * matches any characters including dots, e.g. {\"requirements\":\"requirements.cli.*\"}. Definition reads use the full terminology name, e.g. {\"definition\":\"glossary.command\"}. The requirements and definition forms return {input, definitions}: the selected input and the terminology it needs.",
            "parameters": {"type":"object", "properties": {
                "file":{"type":"string"},
                "line_start":{"type":"integer","minimum":1},
                "line_end":{"type":"integer","minimum":1},
                "item":{"type":"string"},
                "requirements":{"type":"string"},
                "definition":{"type":"string"}
            }, "additionalProperties":false}
        }),
        json!({
            "name": "list_files", "description": "List the immediate files and directories of a project-relative directory (default .). The result is an array of {path, kind}, where kind is file or directory; returned paths can be listed or read in another call. Use list_files for directory entries and outline for selectable nodes in one file. Directory listings are not evidence inputs.",
            "parameters":{"type":"object","properties":{"path":{"type":"string","default":"."}},"additionalProperties":false}
        }),
        json!({
            "name":"outline", "description":"List a file's outline; file is a project-relative path. The result contains its selectable nodes nested by ancestry, in source order, each with its item selector (for habeas {file, item} reads), kind, and name (null when anonymous), and no line numbers. Rust, Python, TypeScript, CSS, Markdown, TOML, and YAML files have language outlines; other text files list one line node per nonblank line. Results contain no source text and are not evidence inputs; read the nodes you rely on with habeas.",
            "parameters":{"type":"object","properties":{"file":{"type":"string"}},"required":["file"],"additionalProperties":false}
        }),
        json!({
            "name":"ripgrep", "description":"Search a project-relative file or directory (default .) using ripgrep regex syntax and case-sensitive matching. Use ripgrep for text patterns, ast_grep for syntax-tree rules, and references for requirement-reference sites. Account for snippets you rely on with finish_search. The result is {search_id, matches: [{tag, file, item, kind, lines: [{text, matched}]}]}: one entry for each innermost outline node containing a match (a match in a comment belongs to the node the comment belongs to), with the node's item selector and kind, and its matching lines (matched true) plus context lines before and after each match (default 2; zero means matches only), in source order and without line numbers. Windows stop at item boundaries, overlapping windows are merged within each item, and a line with text \"…\" and matched false separates windows within one node. Results carry no definitions. Before submitting, call finish_search with the result UUID and the tags whose snippets you used to justify your conclusion without an additional source read. Entries whose source you also read may be omitted; including them is harmless. Use an empty used list if no entries qualify. Selected items become evidence dependencies without another source read. No matches returns an empty matches array. With referencing {selection, roles, scope}, search only sources within path that carry a reference in one of roles (impl, test, cite, or fixme; default [impl, test, cite]) to a requirement or example the selection matches (a full name, or a glob where * matches any characters including dots), including :impl: and :test: declaration anchors: scope node searches only the outline nodes that contain or are named by those references, and scope file (the default) their whole files, e.g. {\"pattern\":\"errors\",\"referencing\":{\"selection\":\"requirements.ci.*\",\"roles\":[\"impl\"],\"scope\":\"node\"}}.",
            "parameters":{"type":"object","properties":{"pattern":{"type":"string"},"path":{"type":"string","default":"."},"context":{"type":"integer","minimum":0,"default":2},"referencing":reference_scope_schema()},"required":["pattern"],"additionalProperties":false}
        }),
        json!({
            "name":"ast_grep", "description":"Search syntax trees in process with an ast-grep rule. Use ripgrep for text patterns, ast_grep for syntax-tree rules, and references for requirement-reference sites. Supply exactly one form: {language, rule, path (default .), referencing (optional)} or {query}. language is one of rust, python, typescript, tsx, css, markdown, toml, or yaml, matched with Habeas's pinned grammars; only files of that language are searched. rule is an object holding the keys of an ast-grep rule file's rule core, written as JSON: rule (required), and optional utils (named rules) and constraints (metavariable name to rule). A rule object combines atomic rules: pattern (code with metavariables, where $A matches one node, $$$A any number of nodes, and $_ one node without capturing), kind (a grammar node kind such as function_item), regex (a Rust regex the node's whole text must match), and nthChild; relational rules: inside, has, precedes, and follows, each taking a rule plus optional stopBy (neighbor, the default, end, or a rule) and field; and composite rules: all, any, not, and matches (a utils name). Patterns parse as standalone code, so a fragment that does not parse on its own, such as a type or parameter, needs the context and selector form: pattern: {context: \"fn f(x: &mut Vec<String>) {}\", selector: reference_type} parses context and matches the node of kind selector within it. Example: {\"language\":\"rust\",\"rule\":{\"rule\":{\"pattern\":\"$X.unwrap()\",\"inside\":{\"kind\":\"function_item\",\"stopBy\":\"end\"}}}}. path selects a project-relative file or directory (default .); referencing works as for ripgrep, and results are ordered by path and then line. The query form, e.g. {\"query\":\"requirements.ci.errors/error_accumulators\"}, runs a query a distributed requirement declares, named <full-name>/<query-name>, exactly as validation runs it, including its paths, exclude, and within, and returns each match's site. The result has ripgrep's form, {search_id, matches: [{tag, file, item, kind, lines: [{text, matched}]}]}: one entry for each innermost outline node containing a match (a match in a comment belongs to the node the comment belongs to; a query match belongs to its site), with the node's item selector and kind, and the matched lines, without line numbers. Results carry no definitions. Before submitting, call finish_search with the result UUID and the tags whose snippets you used to justify your conclusion without an additional source read. Entries whose source you also read may be omitted; including them is harmless. Use an empty used list if no entries qualify. Selected items become evidence dependencies without another source read. No matches returns an empty matches array.",
            "parameters":{"type":"object","properties":{"language":{"type":"string","enum":crate::structural::QueryLanguage::names()},"rule":{"type":"object"},"path":{"type":"string","default":"."},"referencing":reference_scope_schema(),"query":{"type":"string"}},"additionalProperties":false}
        }),
        json!({
            "name":"references", "description":"Locate definitions and reference sites without reading their text. Without selection, return every requirement and named example name with its kind and empty sites. With selection (a full name or a glob where * matches any characters including dots), return the selected names/kinds plus reference sites: definition name, role, file, and item selector, without line numbers. roles filters sites and anchors by impl, cite, or test (default all three); {impl} marks implementations, {cite} related sources, and {test} tests. For example {\"selection\":\"requirements.cli.status\",\"roles\":[\"impl\"]} locates only implementations. Repeated roles have no effect; [] returns names/kinds only. An :impl: or :test: anchor is reported with item null for a whole file or its selector for a node. Results contain no requirement text, example text, commentary, or source text and are not evidence inputs. Request needed source with habeas to read and record it.",
            "parameters":{"type":"object","properties":{
                "selection":{"type":"string"},
                "roles":{"type":"array","items":{"type":"string","enum":["impl","cite","test"]},"default":["impl","cite","test"]}
            },"additionalProperties":false}
        }),
        crate::github::tool_definition(),
        json!({
            "name":"next_page", "description":"Return the following page of a paged result of habeas (line-range form), list_files, outline, ripgrep, ast_grep, or references, in the same shape as its first page. token is the page's next value, e.g. {\"token\":\"abc123\"}. Tokens are opaque.",
            "parameters":{"type":"object","properties":{"token":{"type":"string"}},"required":["token"],"additionalProperties":false}
        }),
        json!({
            "name":"finish_search",
            "description":"Close a delivered search and record dependencies for snippets you used to justify your conclusion without an additional source read. search_id is the result's UUID and used is an array of its short entry tags, e.g. {\"search_id\":\"11111111-1111-4111-8111-111111111111\",\"used\":[\"1\"]}. Entries whose source you also read may be omitted; including them is harmless. Use used:[] when no entries qualify, including an empty search. Every delivered search must be finished before submission. The result is {search_id, finished:true}; no additional source is delivered.",
            "parameters":{"type":"object","properties":{
                "search_id":{"type":"string","format":"uuid"},
                "used":{"type":"array","items":{"type":"string"}}
            },"required":["search_id","used"],"additionalProperties":false}
        }),
    ];
    definitions
}

Tests

Input 2: outline src/authoring/searches.rs mod[tests]/fn[delivered_searches_including_empty_results_need_explicit_completion]
    // {test}`requirements.authoring.search_accounting.result_ids`
    // {test}`requirements.authoring.search_accounting.entry_tags`
    // {test}`requirements.authoring.search_accounting.outstanding`
    // {test}`requirements.authoring.search_accounting.instructions`
    // {test}`requirements.authoring.finish_search.empty`
    // {test}`requirements.authoring.finish_search.invalid`
    // {test}`requirements.authoring.finish_search`
    #[test]
    fn delivered_searches_including_empty_results_need_explicit_completion() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn first() {}\nfn second() {}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        assert!(dispatch_paged(&sources, &mut pages, "ripgrep", &json!({"pattern":"("})).is_err());
        assert!(pages.outstanding_searches().is_empty());
        let first = search(&sources, &mut pages, "fn");
        assert_eq!(
            first["instructions"],
            super::super::approved_text("search_accounting.instructions", 0)
        );
        let tags: Vec<_> = first["matches"]
            .as_array()
            .unwrap()
            .iter()
            .map(|entry| entry["tag"].as_str().unwrap())
            .collect();
        assert_eq!(tags, ["1", "2"]);
        for entry in first["matches"].as_array().unwrap() {
            assert!(entry.get("hash").is_none());
        }
        let empty = search(&sources, &mut pages, "absent");
        assert_eq!(empty["matches"], json!([]));
        assert!(empty.get("instructions").is_none());
        let repeated = search(&sources, &mut pages, "fn");
        assert!(repeated.get("instructions").is_none());
        let ids = [&first, &empty, &repeated]
            .map(|result| Uuid::parse_str(result["search_id"].as_str().unwrap()).unwrap());
        assert_eq!(
            ids.into_iter()
                .collect::<std::collections::BTreeSet<_>>()
                .len(),
            3
        );
        assert_eq!(pages.outstanding_searches().len(), 3);
        let mut other = ResultPages::default();
        let error = other
            .finish_search(&json!({"search_id":first["search_id"],"used":[]}))
            .err()
            .unwrap()
            .to_string();
        assert!(error.contains("delivered in this assessment"), "{error}");
        for result in [&first, &empty, &repeated] {
            let finished = pages
                .finish_search(&json!({"search_id":result["search_id"],"used":[]}))
                .unwrap();
            assert!(finished.inputs.is_empty());
            assert_eq!(
                finished.result,
                json!({"search_id":result["search_id"],"finished":true})
            );
        }
        assert!(pages.outstanding_searches().is_empty());
        assert!(sources.recorded_inputs().is_empty());
        for (tool, args) in [
            ("ripgrep", json!({"pattern":"absent","path":"src/lib.rs"})),
            (
                "ast_grep",
                json!({"language":"rust","rule":{"rule":{"pattern":"absent()"}}}),
            ),
        ] {
            let mut fresh = ResultPages::default();
            let result = dispatch_paged(&sources, &mut fresh, tool, &args)
                .unwrap()
                .result;
            assert_eq!(result["matches"], json!([]));
            assert_eq!(
                result["instructions"],
                super::super::approved_text("search_accounting.instructions", 0)
            );
            Uuid::parse_str(result["search_id"].as_str().unwrap()).unwrap();
            let again = dispatch_paged(&sources, &mut fresh, tool, &args)
                .unwrap()
                .result;
            assert_ne!(result["search_id"], again["search_id"]);
        }
    }
Input 3: outline src/authoring/searches.rs mod[tests]/fn[selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads]
  • File: src/authoring/searches.rs
  • Selector: mod[tests]/fn[selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads]
  • Kind: fn
  • src/authoring/searches.rs:269–353
    // {test}`requirements.authoring.finish_search.completion`
    // {test}`requirements.authoring.finish_search.no_additional_source`
    // {test}`requirements.authoring.finish_search.inputs`
    // {test}`requirements.authoring.finish_search.snapshot`
    // {test}`requirements.authoring.finish_search.unselected`
    // {test}`requirements.authoring.finish_search.deduplication`
    // {test}`requirements.authoring.finish_search.repetition`
    // {test}`requirements.authoring.delivered_inputs`
    // {test}`requirements.authoring.finish_search`
    #[test]
    fn selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn first() { assert!(true); }\nfn second() {}\n",
        )
        .unwrap();
        let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        let result = search(&sources, &mut pages, "fn");
        let original =
            crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[first]").unwrap();
        // Mutation after delivery must not silently substitute a new hash.
        fs::write(
            root.path().join("src/lib.rs"),
            "fn first() {}\nfn second() {}\n",
        )
        .unwrap();
        let finish = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":["1","1"]}))
            .unwrap();
        assert_eq!(finish.inputs, [original]);
        assert_eq!(
            finish.result,
            json!({"search_id":result["search_id"],"finished":true})
        );
        assert!(finish.result.get("text").is_none());
        assert!(pages.outstanding_searches().is_empty());
        sources.record_inputs(&finish.inputs);
        assert_eq!(sources.recorded_inputs().len(), 1);
        assert_eq!(sources.recorded_inputs()[0]["item"], "fn[first]");
        let mut errors = Vec::new();
        crate::evidence::validate_input(
            root.path(),
            &BTreeMap::new(),
            &crate::inputs::OutlineCache::default(),
            &finish.inputs[0],
            "selected",
            &mut errors,
        );
        assert!(
            errors.iter().any(|error| error.contains("hash")),
            "{errors:?}"
        );

        let second = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":["2"]}))
            .unwrap();
        assert_eq!(
            second.inputs,
            [crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[second]").unwrap()]
        );
        sources.record_inputs(&second.inputs);
        assert_eq!(sources.recorded_inputs().len(), 2);
        // A separately read item can be included harmlessly, or omitted.
        let read = dispatch_paged(
            &sources,
            &mut pages,
            "habeas",
            &json!({"file":"src/lib.rs","item":"fn[second]"}),
        )
        .unwrap();
        sources.record_inputs(&read.inputs);
        let repeated = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":["2"]}))
            .unwrap();
        sources.record_inputs(&repeated.inputs);
        let empty = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":[]}))
            .unwrap();
        sources.record_inputs(&empty.inputs);
        assert_eq!(sources.recorded_inputs().len(), 2);
        assert_eq!(sources.recorded_inputs()[0]["item"], "fn[first]");
        assert_eq!(sources.recorded_inputs()[1]["item"], "fn[second]");
    }
Input 4: outline src/authoring/searches.rs mod[tests]/fn[invalid_completion_is_atomic_and_can_be_corrected]
    // {test}`requirements.authoring.finish_search.invalid`
    // {test}`requirements.authoring.finish_search.atomicity`
    // {test}`requirements.authoring.finish_search`
    #[test]
    fn invalid_completion_is_atomic_and_can_be_corrected() {
        let root = project();
        fs::write(root.path().join("src/lib.rs"), "fn first() {}\n").unwrap();
        let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        let result = search(&sources, &mut pages, "first");
        let id = result["search_id"].clone();
        for (args, expected) in [
            (json!(null), "exactly search_id and used"),
            (json!([]), "exactly search_id and used"),
            (json!({}), "exactly search_id and used"),
            (json!({"search_id":id}), "exactly search_id and used"),
            (json!({"used":[]}), "exactly search_id and used"),
            (
                json!({"search_id":id,"used":[],"extra":0}),
                "exactly search_id and used",
            ),
            (
                json!({"search_id":0,"used":[]}),
                "search_id must be a UUID string",
            ),
            (
                json!({"search_id":"bad","used":[]}),
                "search_id must be a UUID string",
            ),
            (
                json!({"search_id":Uuid::new_v4().to_string(),"used":[]}),
                "only search results delivered in this assessment",
            ),
            (
                json!({"search_id":id,"used":null}),
                "used must be an array of tag strings",
            ),
            (
                json!({"search_id":id,"used":"1"}),
                "used must be an array of tag strings",
            ),
            (
                json!({"search_id":id,"used":["1",1]}),
                "used must contain only tag strings",
            ),
            (
                json!({"search_id":id,"used":["1","missing"]}),
                "unknown tag \"missing\"",
            ),
        ] {
            let error = pages.finish_search(&args).err().unwrap().to_string();
            assert!(error.contains(expected), "{args}: {error}");
            assert_eq!(pages.outstanding_searches(), [id.as_str().unwrap()]);
            assert!(sources.recorded_inputs().is_empty());
        }
        let good = pages
            .finish_search(&json!({"search_id":id,"used":["1"]}))
            .unwrap();
        sources.record_inputs(&good.inputs);
        assert_eq!(sources.recorded_inputs().len(), 1);
        assert!(pages.outstanding_searches().is_empty());
        assert!(
            pages
                .finish_search(&json!({"search_id":id,"used":["1","missing"]}))
                .is_err()
        );
        assert!(pages.outstanding_searches().is_empty());
        assert_eq!(sources.recorded_inputs().len(), 1);
    }
Input 5: outline src/authoring/tools.rs mod[tests]/fn[finish_search_advertises_the_accounting_schema_and_selection_rule]
    // {test}`requirements.authoring.finish_search`
    // {test}`requirements.authoring.finish_search.description`
    // {test}`requirements.authoring.tool_descriptions.common_case`
    #[test]
    fn finish_search_advertises_the_accounting_schema_and_selection_rule() {
        let tools = definitions();
        let finish = tools
            .iter()
            .find(|tool| tool["name"] == "finish_search")
            .unwrap();
        assert_eq!(
            finish["parameters"],
            json!({"type":"object","properties":{
            "search_id":{"type":"string","format":"uuid"},
            "used":{"type":"array","items":{"type":"string"}}
        },"required":["search_id","used"],"additionalProperties":false})
        );
        let description = finish["description"].as_str().unwrap();
        for phrase in [
            "snippets you used to justify your conclusion without an additional source read",
            "Entries whose source you also read may be omitted; including them is harmless",
            "Use used:[] when no entries qualify, including an empty search",
            "Every delivered search must be finished before submission",
            "{search_id, finished:true}",
            "no additional source is delivered",
            "search_id is the result's UUID and used is an array of its short entry tags",
            r#"{"search_id":"11111111-1111-4111-8111-111111111111","used":["1"]}"#,
        ] {
            assert!(description.contains(phrase), "{phrase}: {description}");
        }
        for name in ["ripgrep", "ast_grep"] {
            let description =
                tools.iter().find(|tool| tool["name"] == name).unwrap()["description"]
                    .as_str()
                    .unwrap();
            for phrase in [
                "tags whose snippets you used to justify your conclusion without an additional source read",
                "Entries whose source you also read may be omitted; including them is harmless",
                "Use an empty used list if no entries qualify",
                "Before submitting, call finish_search",
                "Use ripgrep for text patterns, ast_grep for syntax-tree rules, and references for requirement-reference sites",
            ] {
                assert!(
                    description.contains(phrase),
                    "{name}: {phrase}: {description}"
                );
            }
        }
    }

Other sources

Input 1: requirements selection requirements.authoring.finish_search
:::{req} finish_search
The harness MUST expose:

```text
finish_search({ search_id: UUID, used: Array<String> })
    -> { search_id: UUID, finished: true }
```

The arguments MUST contain exactly these fields.
:::
Input 6: outline src/authoring/tools.rs fn[dispatch_paged]
// {impl}`requirements.authoring.file_discovery`
// {impl}`requirements.authoring.structural_search`
// {impl}`requirements.authoring.outline_tool`
// {impl}`requirements.authoring.reference_index`
// {impl}`requirements.authoring.github_reads`
pub(crate) fn dispatch_paged(
    sources: &AssessmentSources,
    pages: &mut ResultPages,
    name: &str,
    arguments: &Value,
) -> io::Result<ToolDelivery> {
    let arguments = arguments
        .as_object()
        .ok_or_else(|| io::Error::other("tool arguments must be an object"))?;
    let mut deliver = |listing: io::Result<Listing>| pages.deliver(sources, listing?);
    match name {
        "habeas" => read(sources, arguments).and_then(|read| match read {
            Ok(delivery) => Ok(delivery),
            Err(listing) => deliver(Ok(listing)),
        }),
        "list_files" => {
            deliver(list_files(sources, arguments).and_then(|listing| {
                with_not_listed(sources, arguments, NotListed::Children, listing)
            }))
        }
        "outline" => deliver(outline(sources, arguments)),
        "ripgrep" => deliver(search(sources, arguments).and_then(|listing| {
            let pattern = regex::Regex::new(string(arguments, "pattern")?).ok();
            with_not_listed(sources, arguments, NotListed::Text(pattern), listing)
        })),
        "ast_grep" => deliver(structural(sources, arguments).and_then(|listing| {
            let rule = arguments
                .get("language")
                .and_then(Value::as_str)
                .zip(arguments.get("rule").and_then(Value::as_object))
                .and_then(|(language, rule)| StructuralRule::compile(language, rule).ok());
            with_not_listed(sources, arguments, NotListed::Rule(rule), listing)
        })),
        "references" => deliver(references(sources, arguments)),
        "next_page" => check_keys(arguments, &["token"])
            .and_then(|()| pages.next_page(string(arguments, "token")?)),
        "finish_search" => pages.finish_search(&Value::Object(arguments.clone())),
        // GitHub reads are not evidence inputs.
        "github" => crate::github::tool(&sources.github, &Value::Object(arguments.clone()))
            .map(|result| ToolDelivery {
                result,
                inputs: Vec::new(),
            })
            .map_err(io::Error::other),
        _ => Err(io::Error::other(format!("unknown read tool {name:?}"))),
    }
    .map(|delivery| with_redaction_note(sources, delivery))
    .map_err(super::access::recoverable_os_denial)
    .map_err(super::access::recoverable_outside_request)
}