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

Requirements index · View definition

evidence Valid

Requirement

The harness MUST expose an ast_grep tool with this interface:

ast_grep({ language: String, rule: Object, path: String = ".",
           referencing: Optional<ReferenceScope> }) -> SearchResult
ast_grep({ query: String }) -> SearchResult

The second form MUST run the query a distributed requirement declares, named <full-name>/<query-name>, exactly as validation runs it, including paths, exclude, and within, and MUST return each match’s site. In the first form, referencing MUST restrict the search as for cite requirements.authoring.text_search, and language MUST follow the language key of a query body under cite requirements.references.distributed, and rule MUST be a JSON object holding that body’s rule, utils, and constraints keys. The tool MUST search the requested permitted file or directory in process, with the same file walking, ordering, and source-access policy as cite requirements.authoring.text_search, over files of that language. Each match MUST be returned as the entry of the innermost outline node containing it, in the SearchResult form and under the rules of cite requirements.authoring.text_search, with the matched lines as its lines; selected snippets MUST contribute inputs through cite requirements.authoring.finish_search.inputs. Its model-facing description MUST explain the rule syntax and the context and selector form for fragments that do not parse as standalone code. Explicitly requesting an excluded path MUST be handled as a denial under cite requirements.authoring.read_denial. No matches MUST return an empty array; an invalid language or rule, or a failed search, MUST return an explanatory tool error.

Rationale

The reviewed tests cover every obligation in requirements.authoring.structural_search. I found no gaps.

  • Interface and description. src/authoring/tools.rs#mod[tests]/fn[ast_grep_tool_is_advertised_with_both_forms_and_rule_syntax] asserts the full parameter schema (language enum, rule, path, referencing, query). It also checks the description phrases for rule syntax, utils/constraints, the context and selector form, the query form, the result shape, and finish_search guidance.
  • Query form. fn[ast_grep_queries_run_declared_queries_and_return_their_sites] runs a declared site query.
    • paths restricts the search: tests/outside.rs is not returned.
    • exclude is honoured: src/skip.rs is not returned.
    • Matches are returned as the innermost outline node, including a nested mod[inner]/fn[nested].
    • A violation query with within is attributed to its enclosing site, and a match outside any site (helper) is discarded.
    • Errors are asserted for a missing query name and for a malformed query body.
    • fn[ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures] adds errors for a malformed <full-name>/<query-name>, an unknown requirement, and mixing the two forms.
  • Language and rule. fn[ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures] and src/structural.rs#mod[tests]/fn[rules_compile_for_every_grammar_and_report_invalid_input] cover the language and rule obligations.
    • All eight grammars compile and match.
    • utils and constraints are accepted and have an effect.
    • Only files of the requested language are searched: the Python file is separate from the Rust files.
    • Errors are asserted for an unknown language, a non-object rule, a missing rule key, unexpected keys, and an invalid kind.
  • referencing. fn[ast_grep_referencing_restricts_the_search_as_ripgrep_does] covers the cite role, node scope, a glob selection, and the errors for a bad scope, role and selection.
  • Walking, ordering and source access.
    • fn[ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures] asserts ordering by path then line.
    • fn[allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not] covers ignored or hidden but allowed files, external paths, and disallowed descendants.
    • fn[cargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files] covers build output and disallow changes.
    • fn[generated_evidence_is_excluded_from_reads_search_and_discovery] covers generated evidence.
  • Excerpts and redaction. fn[search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes] covers matched lines and comment ownership for ast_grep, and asserts that tokens are redacted. src/structural.rs#mod[tests]/fn[matches_belong_to_the_innermost_node_or_comment_owner] covers the innermost-node and comment-owner mapping.
  • Denial. Explicitly requested excluded paths return a PermissionDenied error naming the path and reason. This is tested for generated evidence, disallowed paths, and untracked files in tests/authoring_cli.rs#fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues]. Operating-system permission failures are asserted to be ordinary read failures.
  • Empty and failed results. A search with no matches returns an empty matches array and records no inputs. A file with a syntax error produces an explanatory error.
  • Inputs from selected snippets. The tests assert that discovery alone records no inputs (structural.inputs.is_empty()). Recording selected snippets is carried out and tested by requirements.authoring.finish_search.inputs. src/authoring/mod.rs#mod[tests]/fn[every_submission_kind_waits_for_all_searches_and_can_recover] also exercises finish_search on ast_grep results. The ast_grep results go through the same search pipeline as ripgrep’s, so I treated that obligation as covered there.

Inputs

Implementation

Input 18: 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
}
Input 20: 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)
}

Tests

Input 6: outline src/authoring/tools.rs mod[tests]/fn[generated_evidence_is_excluded_from_reads_search_and_discovery]
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[test]
    fn generated_evidence_is_excluded_from_reads_search_and_discovery() {
        let root = project();
        fs::create_dir(root.path().join("evidence")).unwrap();
        fs::create_dir(root.path().join("src/evidence")).unwrap();
        fs::write(
            root.path().join("evidence/old.json"),
            "needle in a previous judgment\n",
        )
        .unwrap();
        fs::write(
            root.path().join("evidence/generated.rs"),
            "fn generated() {}\n",
        )
        .unwrap();
        fs::write(root.path().join("source.txt"), "needle in source\n").unwrap();
        fs::write(
            root.path().join("src/evidence/source.txt"),
            "needle in nested source\n",
        )
        .unwrap();
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(
                root.path().join("evidence"),
                root.path().join("old-output"),
            )
            .unwrap();
            std::os::unix::fs::symlink(
                root.path().join("evidence/old.json"),
                root.path().join("old.json"),
            )
            .unwrap();
        }
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle", "context":0}),
        )
        .unwrap();
        let files = matched(&search)
            .iter()
            .map(|input| input["file"].as_str().unwrap())
            .collect::<Vec<_>>();
        assert_eq!(files, vec!["source.txt", "src/evidence/source.txt"]);
        let structural = dispatch(
            &sources,
            "ast_grep",
            &json!({"language":"rust","rule":{"rule":{"kind":"function_item"}}}),
        )
        .unwrap();
        assert!(matched(&structural).is_empty(), "{:?}", structural.result);
        assert!(
            dispatch(
                &sources,
                "ast_grep",
                &json!({"language":"rust","rule":{"rule":{"kind":"function_item"}},"path":"evidence"}),
            )
            .err()
            .unwrap()
            .to_string()
            .contains("generated evidence")
        );
        let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
        assert!(listing.result.as_array().unwrap().iter().all(|entry| {
            !["evidence", "old-output", "old.json"].contains(&entry["path"].as_str().unwrap())
        }));
        for path in ["evidence/old.json", "./evidence/old.json"] {
            let error = dispatch(&sources, "habeas", &json!({"file":path, "line_start":1}))
                .err()
                .unwrap();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
            assert!(error.to_string().contains("evidence/old.json"), "{error}");
            assert!(error.to_string().contains("generated evidence"), "{error}");
            assert!(sources.recorded_inputs().is_empty());
        }
        for (name, arguments) in [
            (
                "habeas",
                json!({"file":"evidence/generated.rs", "item":"fn[generated]"}),
            ),
            ("list_files", json!({"path":"evidence"})),
            ("ripgrep", json!({"path":"evidence", "pattern":"needle"})),
            (
                "ast_grep",
                json!({"path":"evidence", "language":"rust","rule":{"rule":{"kind":"function_item"}}}),
            ),
        ] {
            let error = dispatch(&sources, name, &arguments).err().unwrap();
            let path = arguments["file"]
                .as_str()
                .or_else(|| arguments["path"].as_str())
                .unwrap();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
            assert!(error.to_string().contains(path), "{error}");
            assert!(error.to_string().contains("generated evidence"), "{error}");
            assert!(sources.recorded_inputs().is_empty());
        }
        #[cfg(unix)]
        {
            for path in ["old.json", "old-output/old.json"] {
                assert!(
                    dispatch(&sources, "habeas", &json!({"file":path, "line_start":1}))
                        .err()
                        .unwrap()
                        .to_string()
                        .contains("generated evidence")
                );
                assert!(
                    dispatch(
                        &sources,
                        "ripgrep",
                        &json!({"path":path, "pattern":"needle"})
                    )
                    .err()
                    .unwrap()
                    .to_string()
                    .contains("generated evidence")
                );
            }
            assert!(
                dispatch(&sources, "list_files", &json!({"path":"old-output"}))
                    .err()
                    .unwrap()
                    .to_string()
                    .contains("generated evidence")
            );
        }
    }
Input 7: outline src/authoring/tools.rs mod[tests]/fn[operating_system_permission_failures_are_ordinary_read_failures]
    // {test}`requirements.authoring.read_denial`
    #[cfg(unix)]
    #[test]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.structural_search`
    fn operating_system_permission_failures_are_ordinary_read_failures() {
        use std::os::unix::fs::PermissionsExt;
        let root = project();
        fs::create_dir(root.path().join("locked")).unwrap();
        fs::write(root.path().join("locked.rs"), "fn locked() {}\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for path in ["locked", "locked.rs"] {
            fs::set_permissions(root.path().join(path), fs::Permissions::from_mode(0o000)).unwrap();
        }
        let unreadable = fs::read(root.path().join("locked.rs")).is_err();
        let results = [
            dispatch(
                &sources,
                "ripgrep",
                &json!({"path":"locked","pattern":"anything"}),
            ),
            dispatch(
                &sources,
                "ast_grep",
                &json!({"path":"locked","language":"rust","rule":{"rule":{"kind":"function_item"}}}),
            ),
            dispatch(&sources, "list_files", &json!({"path": "locked"})),
            dispatch(
                &sources,
                "habeas",
                &json!({"file": "locked.rs", "line_start": 1}),
            ),
        ];
        for path in ["locked", "locked.rs"] {
            fs::set_permissions(root.path().join(path), fs::Permissions::from_mode(0o755)).unwrap();
        }
        if !unreadable {
            // Permission bits do not restrict this user, e.g. root.
            return;
        }
        for result in results {
            let error = result.err().expect("the read fails");
            assert_ne!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
        }
    }
Input 8: outline src/authoring/tools.rs mod[tests]/fn[allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not]
  • File: src/authoring/tools.rs
  • Selector: mod[tests]/fn[allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not]
  • Kind: fn
  • src/authoring/tools.rs:2432–2566
    // {test}`requirements.configuration.evidence_paths`
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.structural_search`
    #[test]
    fn allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not() {
        let root = project();
        let external = tempfile::tempdir().unwrap();
        fs::create_dir_all(root.path().join("generated/private")).unwrap();
        fs::write(
            root.path().join("generated/visible.txt"),
            "needle allowed\n",
        )
        .unwrap();
        fs::write(
            root.path().join("generated/private/hidden.txt"),
            "needle denied\n",
        )
        .unwrap();
        fs::write(external.path().join("outside.txt"), "needle external\n").unwrap();
        fs::write(external.path().join("outside.rs"), "fn external() {}\n").unwrap();
        fs::write(
            root.path().join("generated/visible.rs"),
            "fn visible() {}\n",
        )
        .unwrap();
        fs::write(
            root.path().join("generated/private/denied.rs"),
            "fn denied() {}\n",
        )
        .unwrap();
        fs::write(root.path().join(".hidden.rs"), "fn hidden() {}\n").unwrap();
        fs::write(root.path().join(".gitignore"), "generated/\n").unwrap();
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        let external_toml = toml::Value::String(external.path().display().to_string());
        fs::write(root.path().join("habeas.toml"), format!(
            "version = 1\n[evidence]\nallow = ['generated', '.hidden.rs', {external_toml}]\ndisallow = ['generated/private']\n"
        )).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
        let paths = listing
            .result
            .get("entries")
            .unwrap_or(&listing.result)
            .as_array()
            .unwrap()
            .iter()
            .map(|entry| entry["path"].as_str().unwrap())
            .collect::<Vec<_>>();
        assert!(paths.contains(&"generated"));
        assert!(paths.contains(&external.path().to_str().unwrap()));
        let generated = dispatch(&sources, "list_files", &json!({"path":"generated"})).unwrap();
        assert_eq!(
            generated.result,
            json!([
                {"path":"generated/visible.rs", "kind":"file"},
                {"path":"generated/visible.txt", "kind":"file"}
            ])
        );
        assert!(generated.inputs.is_empty());
        let external_listing =
            dispatch(&sources, "list_files", &json!({"path":external.path()})).unwrap();
        assert_eq!(
            external_listing.result,
            json!([
                {"path":external.path().join("outside.rs"),"kind":"file"},
                {"path":external.path().join("outside.txt"),"kind":"file"}
            ])
        );
        assert!(external_listing.inputs.is_empty());

        let structural = dispatch(
            &sources,
            "ast_grep",
            &json!({"language":"rust","rule":{"rule":{"kind":"function_item"}}}),
        )
        .unwrap();
        let structural_files = matched(&structural)
            .iter()
            .map(|entry| entry["file"].as_str().unwrap())
            .collect::<Vec<_>>();
        for expected in [
            ".hidden.rs",
            "generated/visible.rs",
            external.path().join("outside.rs").to_str().unwrap(),
        ] {
            assert!(structural_files.contains(&expected), "{structural_files:?}");
        }
        assert!(!structural_files.contains(&"generated/private/denied.rs"));
        assert!(structural.inputs.is_empty());

        let search = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle", "context":0}),
        )
        .unwrap();
        assert_eq!(matched(&search).len(), 2);
        assert!(
            matched(&search)
                .iter()
                .any(|input| input["file"] == "generated/visible.txt")
        );
        assert!(matched(&search).iter().any(|input| input["file"] == external.path().join("outside.txt").to_str().unwrap()));
        let read = dispatch(
            &sources,
            "habeas",
            &json!({"file":external.path().join("outside.txt"), "line_start":1}),
        )
        .unwrap();
        assert_eq!(read.result["inputs"][0]["text"], json!(["needle external"]));
        for (name, args) in [
            (
                "habeas",
                json!({"file":"generated/private/hidden.txt", "line_start":1}),
            ),
            ("list_files", json!({"path":"generated/private"})),
            (
                "ripgrep",
                json!({"path":"generated/private", "pattern":"needle"}),
            ),
            (
                "ast_grep",
                json!({"path":"generated/private","language":"rust","rule":{"rule":{"kind":"function_item"}}}),
            ),
        ] {
            assert_eq!(
                dispatch(&sources, name, &args).err().unwrap().kind(),
                io::ErrorKind::PermissionDenied
            );
        }
    }
Input 9: outline src/authoring/tools.rs mod[tests]/fn[cargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files]
  • File: src/authoring/tools.rs
  • Selector: mod[tests]/fn[cargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files]
  • Kind: fn
  • src/authoring/tools.rs:2568–2703
    // {test}`requirements.authoring.generated_inputs`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.configuration.evidence_paths`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.read_denial.build_output`
    // {test}`requirements.authoring.structural_search`
    #[test]
    fn cargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files() {
        let root = project();
        fs::write(root.path().join("src/lib.rs"), "pub fn ready() {}\n").unwrap();
        fs::write(
            root.path().join("Cargo.lock"),
            "version = 4\n\n[[package]]\nname = 'fixture'\nversion = '0.1.0'\n",
        )
        .unwrap();
        fs::write(root.path().join(".gitignore"), "target/\n").unwrap();
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        let unbuilt = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        assert!(
            dispatch(
                &unbuilt,
                "habeas",
                &json!({"file":"src/lib.rs", "line_start":1})
            )
            .is_ok()
        );
        assert!(!root.path().join("target").exists());
        let out = root.path().join("target/debug/build/fixture-hash/out");
        fs::create_dir_all(&out).unwrap();
        fs::write(out.join("generated.rs"), "pub fn generated_needle() {}\n").unwrap();
        fs::write(
            out.parent().unwrap().join("root-output"),
            out.to_str().unwrap(),
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
        assert!(
            listing
                .result
                .get("entries")
                .unwrap_or(&listing.result)
                .as_array()
                .unwrap()
                .iter()
                .any(|entry| entry["path"] == "target/debug/build/fixture-hash/out")
        );
        let search = dispatch(&sources, "ripgrep", &json!({"pattern":"generated_needle"})).unwrap();
        let generated = dispatch(
            &sources,
            "list_files",
            &json!({"path":"target/debug/build/fixture-hash/out"}),
        )
        .unwrap();
        assert_eq!(
            generated.result,
            json!([{"path":"target/debug/build/fixture-hash/out/generated.rs","kind":"file"}])
        );
        assert!(generated.inputs.is_empty());
        assert_eq!(matched(&search).len(), 1);
        let structural_arguments =
            json!({"language":"rust","rule":{"rule":{"pattern":"pub fn generated_needle() {}"}}});
        let structural = dispatch(&sources, "ast_grep", &structural_arguments).unwrap();
        assert_eq!(
            found(&structural),
            ["target/debug/build/fixture-hash/out/generated.rs#fn[generated_needle]"]
        );
        assert!(structural.inputs.is_empty());
        let read = dispatch(&sources, "habeas", &json!({"file":"target/debug/build/fixture-hash/out/generated.rs", "item":"fn[generated_needle]"})).unwrap();
        assert_eq!(
            read.result["input"]["text"],
            json!(["pub fn generated_needle() {}"])
        );
        // Other build output under target is an ordinary read failure.
        let error = dispatch(
            &sources,
            "habeas",
            &json!({"file":"target/debug/build/fixture-hash/root-output", "line_start":1}),
        )
        .err()
        .unwrap();
        assert_ne!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
        assert!(error.to_string().contains("holds build output"), "{error}");
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\ndisallow = ['target/debug/build/fixture-hash/out']\n",
        )
        .unwrap();
        let denied = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let listing = dispatch(&denied, "list_files", &json!({})).unwrap();
        assert!(
            !listing
                .result
                .get("entries")
                .unwrap_or(&listing.result)
                .as_array()
                .unwrap()
                .iter()
                .any(|entry| entry["path"] == "target/debug/build/fixture-hash/out")
        );
        assert!(
            matched(&dispatch(&denied, "ripgrep", &json!({"pattern":"generated_needle"})).unwrap())
                .is_empty()
        );
        assert!(matched(&dispatch(&denied, "ast_grep", &structural_arguments).unwrap()).is_empty());
        for (name, arguments) in [
            (
                "habeas",
                json!({"file":"target/debug/build/fixture-hash/out/generated.rs", "line_start":1}),
            ),
            (
                "list_files",
                json!({"path":"target/debug/build/fixture-hash/out"}),
            ),
            (
                "ripgrep",
                json!({"path":"target/debug/build/fixture-hash/out", "pattern":"generated_needle"}),
            ),
            (
                "ast_grep",
                json!({"path":"target/debug/build/fixture-hash/out","language":"rust","rule":{"rule":{"kind":"function_item"}}}),
            ),
        ] {
            let error = dispatch(&denied, name, &arguments).err().unwrap();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
            assert!(error.to_string().contains("disallowed"), "{error}");
            let path = arguments["file"]
                .as_str()
                .or_else(|| arguments["path"].as_str())
                .unwrap();
            assert!(error.to_string().contains(path), "{error}");
        }
    }
Input 10: outline src/authoring/tools.rs mod[tests]/fn[search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes]
  • File: src/authoring/tools.rs
  • Selector: mod[tests]/fn[search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes]
  • Kind: fn
  • src/authoring/tools.rs:3587–3668
    // {test}`requirements.authoring.search_accounting.excerpts`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.authoring.redaction`
    #[test]
    fn search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes() {
        let root = project();
        let token = format!("ghp_{}", "S".repeat(36));
        fs::write(root.path().join("src/lib.rs"), format!(
            "fn before() {{ unwanted_before(); }}\n\
             /// needle docs\n\
             #[inline]\n\
             fn target() {{\n    let café = \"{token}\";\n    needle();\n}}\n\
             fn after() {{ unwanted_after(); }}\n\
             fn left() {{ unwanted_left(); }} /* needle attached */ #[inline] fn right() {{ needle(); }} fn last() {{ unwanted_last(); }}\n"
        )).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for (tool, args) in [
            (
                "ripgrep",
                json!({"pattern":"needle","path":"src/lib.rs","context":99}),
            ),
            (
                "ast_grep",
                json!({"language":"rust","path":"src/lib.rs",
                "rule":{"rule":{"any":[{"pattern":"needle()"},{"kind":"block_comment","regex":"needle"}]}}}),
            ),
        ] {
            let result = dispatch(&sources, tool, &args).unwrap().result;
            let matches = result["matches"].as_array().unwrap();
            assert_eq!(matches.len(), 3, "{tool}: {matches:?}");
            assert_eq!(matches[0]["item"], "fn[target]");
            assert_eq!(matches[1]["item"], "fn[left]");
            assert_eq!(matches[2]["item"], "fn[right]");
            assert!(!matches[1]["lines"].to_string().contains("fn right"));
            assert!(!matches[2]["lines"].to_string().contains("fn left"));
            assert!(!matches[2]["lines"].to_string().contains("needle attached"));
            let text = result.to_string();
            for unwanted in [
                "unwanted_before",
                "unwanted_after",
                "unwanted_last",
                "fn last",
            ] {
                assert!(!text.contains(unwanted), "{tool}: {text}");
            }
            assert!(!text.contains(&token), "{text}");
            if tool == "ripgrep" {
                let lines = &matches[0]["lines"];
                assert!(lines.to_string().contains("needle docs"));
                assert!(lines.to_string().contains("#[inline]"));
                assert!(lines.to_string().contains("café"));
                assert!(lines.to_string().contains("[REDACTED:"));
            }
            assert!(matches[1]["lines"].to_string().contains("needle attached"));
            assert!(
                matches[2]["lines"]
                    .to_string()
                    .contains("#[inline] fn right")
            );
        }
        let only = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"café","path":"src/lib.rs","context":0}),
        )
        .unwrap();
        assert_eq!(only.result["matches"].as_array().unwrap().len(), 1);
        assert_eq!(only.result["matches"][0]["item"], "fn[target]");
        let attributes = dispatch(
            &sources,
            "ripgrep",
            &json!({
                "pattern":"inline","path":"src/lib.rs","context":0
            }),
        )
        .unwrap();
        assert_eq!(
            found(&attributes),
            ["src/lib.rs#fn[target]", "src/lib.rs#fn[right]"]
        );
    }
Input 11: outline src/authoring/tools.rs mod[tests]/fn[ast_grep_tool_is_advertised_with_both_forms_and_rule_syntax]
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.authoring.result_pages`
    // {test}`requirements.authoring.tool_descriptions.common_case`
    #[test]
    fn ast_grep_tool_is_advertised_with_both_forms_and_rule_syntax() {
        let definitions = definitions();
        let names = definitions
            .iter()
            .map(|definition| definition["name"].as_str().unwrap())
            .collect::<Vec<_>>();
        assert_eq!(
            names,
            [
                "habeas",
                "list_files",
                "outline",
                "ripgrep",
                "ast_grep",
                "references",
                "github",
                "next_page",
                "finish_search"
            ]
        );
        let ast_grep = &definitions[4];
        let ripgrep = &definitions[3];
        assert_eq!(
            ast_grep["parameters"],
            json!({
                "type": "object",
                "properties": {
                    "language": {
                        "type": "string",
                        "enum": ["rust", "python", "typescript", "tsx", "css", "markdown", "toml", "yaml"]
                    },
                    "rule": {"type": "object"},
                    "path": {"type": "string", "default": "."},
                    "referencing": ripgrep["parameters"]["properties"]["referencing"],
                    "query": {"type": "string"}
                },
                "additionalProperties": false
            })
        );
        let description = ast_grep["description"].as_str().unwrap();
        for phrase in [
            "{language, rule, path (default .), referencing (optional)} or {query}",
            "matched with Habeas's pinned grammars",
            "Search syntax trees in process with an ast-grep rule",
            "path selects a project-relative file or directory (default .)",
            "language is one of rust, python, typescript, tsx, css, markdown, toml, or yaml",
            "rule (required), and optional utils (named rules) and constraints",
            "pattern (code with metavariables",
            "kind (a grammar node kind",
            "inside, has, precedes, and follows",
            "all, any, not, and matches",
            "the context and selector form",
            "path selects a project-relative file or directory (default .); referencing works as for ripgrep, and results are ordered by path and then line",
            "named <full-name>/<query-name>, exactly as validation runs it, including its paths, exclude, and within, and returns each match's site",
            "Before submitting, call finish_search",
            "{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",
            "the matched lines, without line numbers",
            "Results carry no definitions",
            "Selected items become evidence dependencies without another source read",
            "No matches returns an empty matches array",
            r#"{"language":"rust","rule":{"rule":{"pattern":"$X.unwrap()","inside":{"kind":"function_item","stopBy":"end"}}}}"#,
            r#"{"query":"requirements.ci.errors/error_accumulators"}"#,
        ] {
            assert!(description.contains(phrase), "{phrase:?} in {description}");
        }
    }
Input 12: outline src/authoring/tools.rs mod[tests]/fn[ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures]
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.references.outline_comments`
    // {test}`requirements.authoring.redaction`
    // {test}`requirements.authoring.read_denial`
    #[test]
    fn ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures() {
        let root = project();
        fs::write(
            root.path().join("md/terms.md"),
            ":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
        )
        .unwrap();
        let token = ["gh", "p_", "abcdefghijklmnopqrstuvwxyz0123456789"].concat();
        fs::write(
            root.path().join("src/lib.rs"),
            format!(
                "// {}\nfn first() {{\n    let x = value.unwrap();\n}}\n\n/// Calls unwrap in docs.\nfn second() {{\n    other(\"{token}\").unwrap();\n}}\n\nmod inner {{\n    fn third() {{\n        a.unwrap();\n        b.unwrap();\n    }}\n}}\n",
                role("term", "terms.value")
            ),
        )
        .unwrap();
        fs::write(
            root.path().join("src/a.rs"),
            "fn a() {\n    z.unwrap();\n}\n",
        )
        .unwrap();
        fs::write(root.path().join("src/tool.py"), "value.unwrap()\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let rust = |rule: Value, path: &str| {
            dispatch(
                &sources,
                "ast_grep",
                &json!({"language":"rust","rule":rule,"path":path}),
            )
        };
        let search = rust(json!({"rule":{"pattern":"$X.unwrap()"}}), ".").unwrap();
        // Only Rust files are searched, ordered by path and then line, and
        // each node once.
        assert_eq!(
            found(&search),
            [
                "src/a.rs#fn[a]",
                "src/lib.rs#fn[first]",
                "src/lib.rs#fn[second]",
                "src/lib.rs#mod[inner]/fn[third]"
            ]
        );
        // Each entry shows the matched lines, redacted; no terminology is
        // supplied.
        let second = &matched(&search)[2]["lines"];
        assert_eq!(second[0]["matched"], true);
        assert!(second.to_string().contains("[REDACTED:"), "{second}");
        assert!(!second.to_string().contains(&token), "{second}");
        assert_eq!(
            matched(&search)[3]["lines"],
            json!([
                {"text": "        a.unwrap();", "matched": true},
                {"text": "        b.unwrap();", "matched": true},
            ])
        );
        assert!(search.result.get("definitions").is_none());
        // A match in a comment belongs to the comment's owner; utils and
        // constraints are accepted.
        let comment = rust(
            json!({
                "rule": {"matches": "doc"},
                "utils": {"doc": {"kind": "line_comment", "regex": "unwrap"}}
            }),
            "src/lib.rs",
        )
        .unwrap();
        assert_eq!(found(&comment), ["src/lib.rs#fn[second]"]);
        let constrained = rust(
            json!({
                "rule": {"pattern": "$X.unwrap()"},
                "constraints": {"X": {"regex": "^[ab]$"}}
            }),
            "src",
        )
        .unwrap();
        assert_eq!(found(&constrained), ["src/lib.rs#mod[inner]/fn[third]"]);
        let python = dispatch(
            &sources,
            "ast_grep",
            &json!({"language":"python","rule":{"rule":{"pattern":"$X.unwrap()"}}}),
        )
        .unwrap();
        assert_eq!(found(&python), ["src/tool.py#"]);
        let none = rust(json!({"rule":{"pattern":"missing()"}}), ".").unwrap();
        assert_eq!(none.result["matches"], json!([]));
        assert!(none.inputs.is_empty());
        for (arguments, message) in [
            (
                json!({"language":"cobol","rule":{"rule":{"kind":"x"}}}),
                "unknown structural search language",
            ),
            (
                json!({"rule":{"rule":{"kind":"x"}}}),
                "language must be a string",
            ),
            (
                json!({"language":"rust","rule":"x"}),
                "rule must be an object",
            ),
            (
                json!({"language":"rust","rule":{"rule":{"kind":"no_such_kind"}}}),
                "invalid ast-grep rule",
            ),
            (
                json!({"language":"rust","rule":{"pattern":"x"}}),
                "unexpected key \"pattern\"",
            ),
            (
                json!({"language":"rust","rule":{"rule":{"kind":"x"}},"extra":1}),
                "unexpected tool argument \"extra\"",
            ),
            (
                json!({"query":"x","language":"rust"}),
                "unexpected tool argument \"language\"",
            ),
            (
                json!({"query":"x"}),
                "must have the form <full-name>/<query-name>",
            ),
            (
                json!({"query":"requirements.none/sites"}),
                "names no declared requirement",
            ),
            (
                json!({"query":"requirements.ready/sites"}),
                "declares no query named \"sites\"",
            ),
        ] {
            let error = dispatch(&sources, "ast_grep", &arguments).err().unwrap();
            assert!(error.to_string().contains(message), "{arguments}: {error}");
        }
        // A matched file that cannot be parsed fails the search.
        fs::write(
            root.path().join("src/broken.rs"),
            "fn broken() {\n    q.unwrap();\n}\n}\n",
        )
        .unwrap();
        let error = rust(json!({"rule":{"pattern":"$X.unwrap()"}}), "src")
            .err()
            .unwrap();
        assert!(error.to_string().contains("syntax error"), "{error}");
        assert!(sources.recorded_inputs().is_empty());
    }
Input 13: 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 14: outline src/authoring/tools.rs mod[tests]/fn[ast_grep_queries_run_declared_queries_and_return_their_sites]
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.references.distributed`
    #[test]
    fn ast_grep_queries_run_declared_queries_and_return_their_sites() {
        let root = project();
        fs::write(
            root.path().join("md/requirements.md"),
            concat!(
                ":::{req} ready\nThe project MUST be ready.\n:::\n\n",
                "::::{req} errors\nAccumulating functions MUST keep going.\n\n",
                ":::{sites} accumulators\n```yaml\nlanguage: rust\npaths: [src]\nexclude: [src/skip.rs]\n",
                "rule:\n  kind: function_item\n  has:\n    stopBy: end\n    kind: identifier\n    regex: \"^errors$\"\n",
                "match: [\"fn f(errors: u8) {}\"]\nno_match: [\"fn f() {}\"]\n```\n:::\n\n",
                ":::{violations} exits\n```yaml\nlanguage: rust\nwithin: accumulators\n",
                "rule:\n  kind: return_expression\n",
                "match: [\"fn f(errors: u8) { return; }\"]\nno_match: [\"fn f() { return; }\"]\n```\n:::\n",
                "::::\n\n",
                "::::{req} broken\nBroken.\n\n:::{sites} bad\nNo code block.\n:::\n::::\n",
            ),
        )
        .unwrap();
        fs::write(
            root.path().join("md/terms.md"),
            ":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
        )
        .unwrap();
        fs::write(
            root.path().join("src/lib.rs"),
            format!(
                "fn check(errors: &mut Vec<String>) {{\n    // {}\n    if errors.is_empty() {{\n        return;\n    }}\n}}\n\nfn helper() {{\n    return;\n}}\n\nmod inner {{\n    fn nested(errors: u8) {{}}\n}}\n",
                role("term", "terms.value")
            ),
        )
        .unwrap();
        fs::write(
            root.path().join("src/skip.rs"),
            "fn skipped(errors: u8) {}\n",
        )
        .unwrap();
        fs::create_dir_all(root.path().join("tests")).unwrap();
        fs::write(
            root.path().join("tests/outside.rs"),
            "fn outside(errors: u8) {}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let query = |name: &str| dispatch(&sources, "ast_grep", &json!({"query": name}));
        // Site queries honour paths and exclude.
        let sites = query("requirements.errors/accumulators").unwrap();
        assert_eq!(
            found(&sites),
            ["src/lib.rs#fn[check]", "src/lib.rs#mod[inner]/fn[nested]"]
        );
        // Each site shows its matched lines, without terminology.
        let lines = |delivery: &ToolDelivery, entry: usize| {
            matched(delivery)[entry]["lines"]
                .as_array()
                .unwrap()
                .iter()
                .map(|line| line["matched"].as_bool().unwrap())
                .collect::<Vec<_>>()
        };
        assert_eq!(lines(&sites, 0), [true; 6]);
        assert!(sites.result.get("definitions").is_none());
        // Violation matches belong to the innermost containing site; matches
        // inside no site are discarded.
        let violations = query("requirements.errors/exits").unwrap();
        assert_eq!(found(&violations), ["src/lib.rs#fn[check]"]);
        assert_eq!(
            matched(&violations)[0]["lines"],
            json!([{"text": "        return;", "matched": true}])
        );
        for (name, message) in [
            (
                "requirements.errors/missing",
                "declares no query named \"missing\"",
            ),
            (
                "requirements.broken/bad",
                "exactly one fenced yaml code block",
            ),
        ] {
            let error = query(name).err().unwrap();
            assert!(error.to_string().contains(message), "{name}: {error}");
        }
    }
Input 15: outline src/structural.rs mod[tests]/fn[rules_compile_for_every_grammar_and_report_invalid_input]
  • File: src/structural.rs
  • Selector: mod[tests]/fn[rules_compile_for_every_grammar_and_report_invalid_input]
  • Kind: fn
  • src/structural.rs:657–754
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.references.distributed`
    #[test]
    fn rules_compile_for_every_grammar_and_report_invalid_input() {
        for (language, rule, source, expected) in [
            (
                "rust",
                json!({"pattern": "foo($A)"}),
                "fn f() { foo(1); }\n",
                "foo(1)",
            ),
            (
                "python",
                json!({"pattern": "foo($A)"}),
                "foo(1)\n",
                "foo(1)",
            ),
            (
                "typescript",
                json!({"pattern": "foo($A)"}),
                "foo(1);\n",
                "foo(1)",
            ),
            (
                "tsx",
                json!({"pattern": "<a>{$X}</a>"}),
                "const x = <a>{y}</a>;\n",
                "<a>{y}</a>",
            ),
            (
                "css",
                json!({"kind": "class_selector"}),
                ".a { color: red; }\n",
                ".a",
            ),
            (
                "markdown",
                json!({"kind": "atx_heading"}),
                "# Title\n\nText.\n",
                "# Title\n",
            ),
            (
                "toml",
                json!({"pattern": "name = $V"}),
                "name = 'x'\n",
                "name = 'x'",
            ),
            (
                "yaml",
                json!({"kind": "block_mapping_pair"}),
                "key: value\n",
                "key: value",
            ),
        ] {
            let rule =
                StructuralRule::compile(language, json!({"rule": rule}).as_object().unwrap())
                    .unwrap_or_else(|error| panic!("{language}: {error}"));
            let found = rule
                .matches(source)
                .into_iter()
                .map(|range| &source[range])
                .collect::<Vec<_>>();
            assert_eq!(found, [expected], "{language}");
        }
        for (language, rule, message) in [
            (
                "cobol",
                json!({"rule": {"kind": "x"}}),
                "unknown structural search language",
            ),
            (
                "plain-text",
                json!({"rule": {"kind": "x"}}),
                "unknown structural search language",
            ),
            ("rust", json!({}), "missing key \"rule\""),
            (
                "rust",
                json!({"rule": {"kind": "x"}, "fix": "y"}),
                "unexpected key \"fix\"",
            ),
            (
                "rust",
                json!({"rule": {"kind": "no_such_kind"}}),
                "invalid ast-grep rule",
            ),
            (
                "rust",
                json!({"rule": {"bogus": 1}}),
                "invalid ast-grep rule",
            ),
        ] {
            let error = StructuralRule::compile(language, rule.as_object().unwrap())
                .err()
                .unwrap();
            assert!(error.contains(message), "{rule}: {error}");
        }
    }
Input 16: outline src/structural.rs mod[tests]/fn[matches_belong_to_the_innermost_node_or_comment_owner]
  • File: src/structural.rs
  • Selector: mod[tests]/fn[matches_belong_to_the_innermost_node_or_comment_owner]
  • Kind: fn
  • src/structural.rs:756–773
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.references.distributed`
    // {test}`requirements.references.outline_comments`
    #[test]
    fn matches_belong_to_the_innermost_node_or_comment_owner() {
        let source = "mod outer {\n    /// Uses foo.\n    #[inline]\n    fn inner() {\n        foo(1);\n    }\n}\n";
        let outline = crate::outline::parse(Path::new("lib.rs"), source).unwrap();
        let item = |text: &str| {
            let start = source.find(text).unwrap();
            let index = innermost_node(&outline, source, &(start..start + text.len()));
            outline.nodes[index].selector.clone()
        };
        assert_eq!(item("foo(1)"), "mod[outer]/fn[inner]");
        assert_eq!(item("/// Uses foo.\n"), "mod[outer]/fn[inner]");
        assert_eq!(item("#[inline]"), "mod[outer]/fn[inner]");
        assert_eq!(item("mod outer"), "mod[outer]");
        assert_eq!(item(source), "");
    }
Input 17: outline tests/authoring_cli.rs fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues]
  • File: tests/authoring_cli.rs
  • Selector: fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues]
  • Kind: fn
  • tests/authoring_cli.rs:853–922
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.structural_search`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.read_denial.untracked`
// {test}`requirements.authoring.read_denial`
#[test]
fn explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues() {
    for (tool, arguments) in [
        ("habeas", json!({"file":"untracked.txt", "line_start":1})),
        (
            "ripgrep",
            json!({"path":"untracked.txt", "pattern":"hidden"}),
        ),
        (
            "ast_grep",
            json!({"path":"untracked.txt", "language":"rust", "rule":{"rule":{"pattern":"hidden"}}}),
        ),
        ("list_files", json!({"path":"untracked-directory"})),
    ] {
        let server = Server::start(vec![
            reply(vec![call("denied", tool, arguments)]),
            reply(vec![call(
                "submit",
                "submit_judgment",
                json!({"determination": true, "rationale": "The tracked sources support it."}),
            )]),
        ]);
        let fixture = Fixture::new(&server.endpoint);
        for args in [["init", "--quiet"], ["add", "."]] {
            let git = Command::new("git")
                .current_dir(&fixture.project)
                .args(args)
                .output()
                .unwrap();
            assert!(git.status.success(), "{git:?}");
        }
        fs::write(fixture.project.join("untracked.txt"), "hidden source\n").unwrap();
        fs::create_dir(fixture.project.join("untracked-directory")).unwrap();
        fs::write(
            fixture.project.join("untracked-directory/hidden.txt"),
            "hidden source\n",
        )
        .unwrap();

        let output = fixture.run(&["author", SUBJECT, "--stdout"]);
        assert!(output.status.success(), "{tool}: {output:?}");
        // The model was told the path is untracked and how to fix it, and
        // the file was neither delivered nor recorded.
        let requests = server.finish();
        assert_eq!(requests.len(), 2, "{tool}");
        let second = requests[1].body.to_string();
        assert!(
            second.contains("is untracked") || second.contains("untracked, so"),
            "{tool}: {second}"
        );
        assert!(second.contains("git add"), "{tool}: {second}");
        assert!(!second.contains("hidden source"), "{tool}: {second}");
        let evidence = String::from_utf8_lossy(&output.stdout);
        assert!(!evidence.contains("untracked"), "{tool}: {evidence}");
        let usage = fixture.usage();
        assert_eq!(usage["outcome"], "completed", "{tool}: {usage}");
        assert_eq!(usage["request_count"], 2, "{tool}: {usage}");
        assert_eq!(usage["tool_failures"][tool], 1, "{tool}: {usage}");
    }
}

Referenced definitions

Input 2: requirements selection requirements.authoring.text_search
:::{req} text_search
The harness MUST expose a `ripgrep` tool with this interface:

```text
ripgrep({ pattern: String, path: String = ".", context: Integer = 2,
          referencing: Optional<ReferenceScope> }) -> SearchResult

ReferenceScope {
    selection: String,                     // full name or definition glob
    roles: Array<Role> = ["impl", "test", "cite"],
    scope: "node" | "file" = "file",
}

SearchResult {
    search_id: UUID,
    instructions: Optional<String>,
    matches: Array<SearchMatch>,
}

SearchMatch {
    tag: String,         // short tag for finish_search
    file: String,
    item: String,        // selector of the innermost outline node
    kind: String,
    lines: Array<{ text: String, matched: Boolean }>,
}
```

The tool MUST search the requested permitted file or directory using
ripgrep's regular-expression syntax and default case-sensitive search and ignore
rules. It MUST search in process using ripgrep's library crates, without
requiring an external `rg` executable, and MUST apply source-access policy while
walking files rather than filtering results afterwards. It MAY search files in
parallel; results MUST be ordered by path and then line regardless of
parallelism, so the same sources always produce the same inputs. Explicitly allowed paths and discovered generated-output directories MUST
be searched even when ignored or hidden; workspace disallow rules still apply.
`context`
MUST be nonnegative and specify how many lines before and after each matching
line to include, defaulting to two on each side. Windows MUST stop at item
boundaries under {cite}`requirements.authoring.search_accounting.excerpts`,
and overlapping windows within the same item MUST be merged. The result
MUST give one entry for each innermost outline node containing a match, where a
match in a comment belongs to the node the comment belongs to under
{cite}`requirements.references.outline_comments`: the node's file, selector
under {cite}`requirements.references.outline_selectors`, kind, and its matching
and context lines in source order, each marked as matching or not and redacted
under {cite}`requirements.authoring.redaction`. Results MUST NOT give line
numbers; the model locates and cites code by selector. Separate windows within
one node MUST be distinguishable, such as by an elision line that is not
marked as matching. Search results MUST NOT include definitions. Selected snippets MUST contribute
evidence inputs through {cite}`requirements.authoring.finish_search.inputs`;
unselected snippets MUST NOT contribute inputs merely through discovery.
Results and descriptions MUST follow
{cite}`requirements.authoring.search_accounting.instructions` and
{cite}`requirements.authoring.finish_search.description`. Setting `context` to zero MUST return only matching lines.
With `referencing`, the tool MUST search only sources, within `path`, that carry
a reference in one of `roles` to a requirement or example the `selection`
matches under {cite}`requirements.references.definition_globs`, including
anchors under {cite}`requirements.references.anchors`: with `scope` `node`, only
the outline nodes that contain or are named by those references, and with
`file`, their whole files. A selection matching no requirement or example, or an
unknown role or scope, MUST return an explanatory tool error. Its model-facing
description MUST explain `referencing`.
Search results MUST exclude files disallowed by
{cite}`requirements.authoring.source_tools`; explicitly requesting an excluded
path MUST be handled as a denial under {cite}`requirements.authoring.read_denial`.
No matches MUST return an empty array; invalid arguments or a failed search MUST
return an explanatory tool error.
:::
Input 3: requirements selection requirements.references.distributed
:::{req} distributed
A requirement MAY be distributed: it states obligations that each of many sites
in the sources must uphold on its own, such as a convention every validation
function follows, and MAY also state obligations that particular code carries
out, which that code implements with `{impl}`. A `{req}` body declares a distributed requirement
by containing one or more nested query directives: `:::{sites} <name>` for a
site query, which finds the places the obligation applies, or
`:::{violations} <name>` for a violation query, which finds constructs likely to
break it. A requirement with a violation query MUST also have a site query.
Query names MUST be single identifier segments under
{cite}`requirements.ci.identifiers`, unique within the requirement. A query
directive outside a `{req}` body MUST be a validation error. Each query body
MUST be one fenced `yaml` code block containing a mapping with only these keys:

- `language`, required: the name of an outline profile with a grammar under
  {cite}`requirements.references.outlines`: `rust`, `python`, `typescript`,
  `tsx`, `css`, `markdown`, `toml`, or `yaml`.
- `paths`, optional: project-relative files or directories. Only sources at or
  under one of them are searched; without it, every source of the language is.
- `exclude`, optional: project-relative files or directories whose sources are
  not searched, even under `paths`.
- `rule`, required, with optional `utils` and `constraints`: an ast-grep rule
  core in the syntax of Habeas's pinned `ast-grep-config` version, matched
  against the language's pinned grammar.
- `within`, required for violation queries and not allowed for site queries:
  the name of a site query in the same requirement.
- `match` and `no_match`, required: nonempty lists of source snippets in the
  query's language. Each `match` snippet MUST contain at least one match of the
  query, and each `no_match` snippet none, where a violation query counts only matches inside a site of its `within` query in the same snippet.

Validation MUST report a query whose body is not such a mapping, whose rule does
not compile, whose `within` names no site query of the requirement, a violation query without `within`, or one of whose snippets fails to parse or has the wrong match result, and a site query
that matches nothing in the project. Queries MUST search exactly the sources
reference discovery considers under {cite}`requirements.references.discovery`, in
their original text.

A match's site MUST be the innermost outline node, under
{cite}`requirements.references.outlines`, whose range contains the match; for a violation query, it MUST instead be the innermost site of its `within` query that contains the match, and a match inside none of that query's
sites MUST be discarded. A requirement's sites MUST be the distinct sites of all
its queries' matches. Each site MUST have a site review under
{cite}`requirements.references.site_review`, and needs no reference to the
requirement; being a site MUST NOT count as a reference for
{cite}`requirements.references.rust_item_coverage`, because a distributed
requirement concerns a cross-cutting obligation, not why the item exists.
Upgrading `ast-grep-config` MAY change matches and MUST be treated as a
deliberate change. The book MUST render each query directive as a badge
naming its kind and name, followed by its code block.
:::
Input 4: requirements selection requirements.authoring.finish_search.inputs
:::{req} finish_search.inputs
For each tag selected by a valid `finish_search` call, the harness MUST record
its `file`, `item`, and structural hash as an outline input under
{cite}`requirements.ci.outline_inputs` before acknowledging that call.
:::
Input 5: requirements selection requirements.authoring.read_denial
:::{req} read_denial
When source-access policy denies a path that a model tool call names
explicitly, the harness MUST return a tool error naming the path and the reason
it cannot be read, add no evidence input, and continue the assessment.
Discovery and search MUST leave denied candidates out of their entries,
reporting untracked ones under {cite}`requirements.authoring.not_listed`. Malformed tool
arguments and ordinary read failures MUST also return explanatory tool errors.
:::

Other sources

Input 1: requirements selection requirements.authoring.structural_search
:::{req} structural_search
The harness MUST expose an `ast_grep` tool with this interface:

```text
ast_grep({ language: String, rule: Object, path: String = ".",
           referencing: Optional<ReferenceScope> }) -> SearchResult
ast_grep({ query: String }) -> SearchResult
```

The second form MUST run the query a distributed requirement declares, named
`<full-name>/<query-name>`, exactly as validation runs it, including `paths`,
`exclude`, and `within`, and MUST return each match's site. In the first form,
`referencing` MUST restrict the search as for
{cite}`requirements.authoring.text_search`, and `language` MUST follow the `language` key of a query body under
{cite}`requirements.references.distributed`, and `rule` MUST be a JSON object
holding that body's `rule`, `utils`, and `constraints` keys. The tool MUST search
the requested permitted file or directory in process, with the same file walking,
ordering, and source-access policy as {cite}`requirements.authoring.text_search`,
over files of that language. Each match MUST be returned as the entry of the
innermost outline node containing it, in the `SearchResult` form and under the
rules of {cite}`requirements.authoring.text_search`, with the matched lines as
its lines; selected snippets MUST contribute inputs through
{cite}`requirements.authoring.finish_search.inputs`. Its model-facing description MUST
explain the rule syntax and the `context` and `selector` form for fragments that
do not parse as standalone code. Explicitly requesting an excluded path MUST be
handled as a denial under {cite}`requirements.authoring.read_denial`. No matches
MUST return an empty array; an invalid language or rule, or a failed search,
MUST return an explanatory tool error.
:::
Input 19: outline src/authoring/mod.rs mod[tests]/fn[every_submission_kind_waits_for_all_searches_and_can_recover]
    // {test}`requirements.authoring.submission.searches`
    // {test}`requirements.authoring.submission.searches.diagnostic`
    // {test}`requirements.authoring.submission.searches.recovery`
    // {test}`requirements.authoring.submission.searches.accompanying_calls`
    // {test}`requirements.authoring.finish_search.inputs`
    // {test}`requirements.authoring.search_accounting.recovery`
    #[tokio::test]
    async fn every_submission_kind_waits_for_all_searches_and_can_recover() {
        use SearchAction::{Call, Finish};
        for submit in ["submit_judgment", "submit_verification"] {
            let root = inputs::tests::project();
            fs::write(
                root.path().join("src/lib.rs"),
                "fn helper() { assert!(true); }\nfn untouched() {}\n",
            )
            .unwrap();
            let mut sources =
                AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
            let state = tempfile::tempdir().unwrap();
            let mut usage =
                UsageLog::start(state.path(), root.path(), &sources.subject_name).unwrap();
            let arguments = if submit == "submit_judgment" {
                json!({"determination":true,"rationale":"Helper checks its assertion."})
            } else {
                json!({"real":false,"acknowledged":false,"acknowledgments":[],
                    "rationale":"Helper checks its assertion."})
            };
            let provider = SearchProvider {
                submit,
                turns: vec![
                    vec![
                        Call("ripgrep", json!({"pattern":"assert","path":"src/lib.rs"})),
                        Call(
                            "ast_grep",
                            json!({"language":"rust","rule":{"rule":{"pattern":"absent()"}}}),
                        ),
                    ],
                    // Accompanying completion is skipped, so both IDs remain open.
                    vec![
                        Finish(0, vec!["1"]),
                        Call(
                            "habeas",
                            json!({"file":"src/lib.rs","item":"fn[untouched]"}),
                        ),
                        Call("ripgrep", json!({"pattern":"absent","path":"src/lib.rs"})),
                        Call(submit, arguments.clone()),
                    ],
                    vec![Finish(0, vec!["1"])],
                    vec![Call(submit, arguments.clone())],
                    vec![Finish(1, vec![])],
                    vec![Call(submit, arguments)],
                ],
                requests: RefCell::default(),
            };
            if submit == "submit_judgment" {
                let (_, evidence) = assess(&provider, &mut sources, &mut usage).await.unwrap();
                assert!(
                    evidence["inputs"]
                        .as_array()
                        .unwrap()
                        .iter()
                        .any(|input| input["item"] == "fn[helper]" && input.get("hash").is_some())
                );
            } else {
                let result = verify(
                    &provider,
                    &mut sources,
                    &mut usage,
                    &Judgment::False,
                    "Alleged gap",
                )
                .await
                .unwrap();
                assert!(!result.real);
            }
            let requests = provider.requests.borrow();
            assert_eq!(requests.len(), 6);
            let mut searches = Vec::new();
            delivered_searches(&requests[1], &mut searches);
            assert_eq!(searches.len(), 2);
            let blocked = requests[2].as_array().unwrap().last().unwrap().to_string();
            assert!(blocked.contains("not run: the response also made a submission"));
            assert!(blocked.contains(searches[0]["search_id"].as_str().unwrap()));
            assert!(blocked.contains(searches[1]["search_id"].as_str().unwrap()));
            assert!(blocked.contains("Call finish_search for every listed search_id"));
            assert!(blocked.contains("then resubmit"));
            let latest = requests[4].as_array().unwrap().last().unwrap().to_string();
            assert!(latest.contains("outstanding searches"));
            assert!(!latest.contains(searches[0]["search_id"].as_str().unwrap()));
            assert!(latest.contains(searches[1]["search_id"].as_str().unwrap()));
            assert_eq!(
                sources
                    .recorded_inputs()
                    .iter()
                    .filter(|input| input["item"] == "fn[helper]")
                    .count(),
                1
            );
            let log: Value =
                serde_json::from_str(&fs::read_to_string(&usage.path).unwrap()).unwrap();
            assert_eq!(log["tool_calls"]["finish_search"], 3);
            assert_eq!(log["tool_skipped"]["finish_search"], 1);
            assert_eq!(log["tool_skipped"]["habeas"], 1);
            assert_eq!(log["tool_skipped"]["ripgrep"], 1);
            assert!(
                !sources
                    .recorded_inputs()
                    .iter()
                    .any(|input| input["item"] == "fn[untouched]")
            );
            assert_eq!(
                log["tool_failures"]
                    .as_object()
                    .unwrap()
                    .values()
                    .filter_map(Value::as_u64)
                    .sum::<u64>(),
                2
            );
        }
    }