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

Requirements index · View definition

evidence Valid

Requirement

The harness MUST expose a ripgrep tool with this interface:

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.

Rationale

I found no adequacy gap in the tests for requirements.authoring.text_search. Each obligation below maps to a test with assertions that enforce it. All the tests are in src/authoring/tools.rs under mod[tests], except where noted.

Interface and description

  • fn[ripgrep_tool_is_advertised_with_its_interface_and_conventions] asserts the full parameter schema. That covers pattern, path, context (minimum 0, default 2) and referencing with its roles and scope enums and defaults.
  • The same test asserts the model-facing description. It must explain referencing and the context, window, no-line-number and no-definitions conventions. It must also carry the finish_search guidance.

Regex, case sensitivity and ignore rules

  • fn[search_merges_context_windows_and_respects_ignore_rules] shows that NEEDLE does not match needle. It also shows that gitignored and hidden files, even when force-added, are not searched.
  • fn[exact_match_ranges_preserve_regex_anchors_and_skip_unmatched_or_binary_sources] exercises regex anchors and (?i). It also shows a binary file is skipped.

Allowed paths and ordering

  • fn[search_records_nothing_clamps_at_eof_and_reports_failures], fn[allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not] and fn[cargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files] cover explicitly allowed and generated-output paths. They show an allowed hidden or ignored directory is searched, while a disallowed descendant and an unallowed hidden directory are not.
  • fn[parallel_search_orders_results_by_path_and_line] covers deterministic path ordering across 40 files and repeated runs.
  • fn[search_returns_innermost_nodes_and_comment_owners] and fn[search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes] cover ordering within a file.

Context, windows and entries

  • fn[context_windows_include_exactly_the_requested_lines_on_each_side] tests context None, 0, 1, 2 and 3.
  • fn[separate_windows_in_one_node_are_divided_by_an_elision_line] tests the unmarked elision line and merging of overlapping windows. It also checks that the default context equals 2.
  • fn[search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes] tests clipping at item boundaries, including attached comments and attributes. It also tests clipping within a line shared by two items.
  • fn[search_returns_innermost_nodes_and_comment_owners] tests that each entry is the innermost node and that a comment match belongs to its owner.
  • A negative context is rejected in fn[search_merges_context_windows_and_respects_ignore_rules], and a fractional context in fn[search_records_nothing_clamps_at_eof_and_reports_failures].

Result shape and redaction

  • The shape tests assert that entries have no line numbers and no hash. search_records_nothing_clamps_at_eof_and_reports_failures asserts that no definitions field is returned and that searching records no inputs. search_merges_context_windows_and_respects_ignore_rules asserts inputs is empty, so unselected snippets contribute nothing.
  • fn[model_inputs_reads_searches_and_citation_prompts_are_redacted] shows search results do not leak credentials, even when the pattern matches the credential itself.
  • fn[search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes] also asserts [REDACTED: and the absence of the token.

referencing

  • fn[ripgrep_referencing_searches_only_referencing_files_or_nodes] covers default roles, the fixme role, and glob selection. It covers file scope against node scope, including windows clipped at node boundaries. It covers the interaction with path, and a definition with no references returning an empty result.
  • The same test checks the explanatory errors for a selection matching nothing, an unknown role, an unknown scope, a non-array roles, an extra key, a missing selection, and a non-object referencing.
  • fn[text_search_selects_example_test_references_and_test_anchors] covers named examples, :test: anchors and role filtering.
  • fn[ripgrep_node_scope_searches_only_the_node_a_selector_anchor_names] covers :impl: selector anchors under node and file scope. It also shows an unresolvable selector selects nothing.

Denial, errors and empty results

  • fn[generated_evidence_is_excluded_from_reads_search_and_discovery], fn[outside_symlinks_are_excluded_from_reads_search_and_discovery], fn[git_tools_allow_staged_and_dirty_sources_but_hide_untracked_files], fn[git_symlink_reads_require_both_the_alias_and_target_to_be_tracked] and fn[unpermitted_requests_outside_the_project_are_recoverable_tool_errors] cover the exclusion and denial cases. They show excluded files are left out of walks and explicit requests for excluded paths return errors naming the path and reason.
  • tests/authoring_cli.rs#fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues] covers the untracked-path denial end to end for ripgrep.
  • fn[search_uses_the_validated_target_when_symlinks_precede_parent_components] checks that the validated path target is the one searched.
  • An empty match returns [] (NEEDLE absent). Invalid patterns, bad argument types, unknown arguments and an unparseable matched file all return explanatory errors in search_records_nothing_clamps_at_eof_and_reports_failures.

Delegated obligations

  • The instructions field on the first delivered search is governed by the cited requirements.authoring.search_accounting.instructions. It is tested against that requirement in src/authoring/pages.rs and src/authoring/searches.rs. It is covered in context and not reassessed here.
  • Recording evidence inputs for selected tags is governed by finish_search.inputs. The subject’s tests assert only that discovery alone records nothing.

Not covered by a dedicated test

  • “In process, without an external rg” and “policy applied while walking” are implementation-structure properties. The reviewed tests exercise the policy outcomes, and none depends on an rg binary.

Inputs

Tests

Input 13: outline src/authoring/tools.rs mod[tests]/fn[model_inputs_reads_searches_and_citation_prompts_are_redacted]
    // {test}`requirements.authoring.redaction`
    // {test}`requirements.authoring.credentials`
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring.citation_prompt`
    // {test}`requirements.authoring.fixme_inputs`
    #[test]
    fn model_inputs_reads_searches_and_citation_prompts_are_redacted() {
        let root = project();
        let token = crate::redaction::tests::github_token();
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 'plain ollama key'\n",
        )
        .unwrap();
        fs::write(
            root.path().join("src/lib.rs"),
            format!(
                "// {}\nfn client() -> &'static str {{\n    \"{token}\"\n}}\n\n// :::{} requirements.ready\n// Defaults to {token}.\n// :::\nfn helper() {{}}\n\n// :::{{fixme}} requirements.ready\n// Missing check for {token}.\n// :::\nfn gap() {{}}\n",
                role("test", "requirements.ready"),
                "{cite}"
            ),
        )
        .unwrap();
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        let leaks = |value: &Value| {
            let text = value.to_string();
            text.contains(&token) || text.contains("plain ollama key")
        };
        // Mandatory inputs, and so the initial and verification prompts.
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mandatory = Value::Array(sources.mandatory_inputs().to_vec());
        assert!(!leaks(&mandatory), "{mandatory:#}");
        assert!(mandatory.to_string().contains("[REDACTED:GitHub Token]"));
        let prompt = super::super::initial_prompt(&sources).unwrap().joined();
        assert!(!prompt.contains(&token), "{prompt}");
        assert!(
            prompt.contains("Missing check for [REDACTED:GitHub Token]."),
            "{prompt}"
        );
        assert!(!prompt.contains("fn gap()"), "{prompt}");
        // A habeas read of the configuration file and a line range.
        let read = dispatch(&sources, "habeas", &json!({"file":"habeas.toml","item":""})).unwrap();
        assert!(!leaks(&read.result), "{:#}", read.result);
        assert!(
            read.result["input"]["text"]
                .as_array()
                .unwrap()
                .contains(&json!("api_key = '[REDACTED:api_key]'"))
        );
        let lines = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":1}),
        )
        .unwrap();
        assert!(!leaks(&lines.result), "{:#}", lines.result);
        // Search results, even for a pattern matching the credential itself.
        for pattern in ["ollama", "gh[p]_", "Defaults"] {
            let search = dispatch(&sources, "ripgrep", &json!({"pattern": pattern})).unwrap();
            assert!(
                !search.result["matches"].as_array().unwrap().is_empty(),
                "{pattern}"
            );
            assert!(!leaks(&search.result), "{pattern}: {:#}", search.result);
        }
        // A citation review's inputs and its commentary in the prompt.
        let citation =
            AssessmentSources::prepare_citation(root.path(), "src/lib.rs", "fn[helper]").unwrap();
        assert!(!leaks(&Value::Array(citation.mandatory_inputs().to_vec())));
        let prompt = super::super::initial_prompt(&citation).unwrap().joined();
        assert!(!prompt.contains(&token), "{prompt}");
        assert!(
            prompt.contains("Defaults to [REDACTED:GitHub Token]."),
            "{prompt}"
        );
    }
Input 14: outline src/authoring/tools.rs mod[tests]/fn[search_merges_context_windows_and_respects_ignore_rules]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.additional_read`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn search_merges_context_windows_and_respects_ignore_rules() {
        let root = project();
        git(root.path(), &["init", "--quiet"]);
        fs::write(root.path().join(".gitignore"), "ignored.txt\n").unwrap();
        fs::write(root.path().join("ignored.txt"), "needle\n").unwrap();
        fs::write(root.path().join(".hidden.txt"), "needle\n").unwrap();
        let lines = (1..=20)
            .map(|number| {
                if number == 2 || number == 6 {
                    "needle".to_owned()
                } else {
                    format!("line {number}")
                }
            })
            .collect::<Vec<_>>();
        fs::write(root.path().join("sample.txt"), lines.join("\n")).unwrap();
        git(root.path(), &["add", "--force", "."]);
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = dispatch(&sources, "ripgrep", &json!({"pattern":"needle"})).unwrap();
        // Each plain-text line is an item. Even a large context window must
        // not include neighboring items.
        assert!(search.inputs.is_empty());
        let matches = search.result["matches"].as_array().unwrap();
        assert_eq!(matches.len(), 2, "{matches:#?}");
        let shown = matches
            .iter()
            .map(|entry| {
                assert_eq!(entry["file"], "sample.txt");
                assert_eq!(entry["kind"], "line");
                assert!(entry.get("line_start").is_none());
                entry["lines"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|line| {
                        assert!(line.get("line").is_none());
                        (
                            line["text"].as_str().unwrap(),
                            line["matched"].as_bool().unwrap(),
                        )
                    })
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();
        assert_eq!(shown, [vec![("needle", true)], vec![("needle", true)]]);
        let exact = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle","path":"sample.txt","context":0}),
        )
        .unwrap();
        assert_eq!(
            exact.result["matches"][0]["lines"],
            json!([{"text": "needle", "matched": true}])
        );
        assert_eq!(
            exact.result["matches"][1]["lines"],
            json!([{"text": "needle", "matched": true}])
        );
        let absent = dispatch(&sources, "ripgrep", &json!({"pattern":"NEEDLE"})).unwrap();
        assert_eq!(absent.result["matches"], json!([]));
        assert!(dispatch(&sources, "ripgrep", &json!({"pattern":"["})).is_err());
        assert!(
            dispatch(
                &sources,
                "ripgrep",
                &json!({"pattern":"needle","context":-1})
            )
            .is_err()
        );
        assert!(dispatch(&sources, "list_files", &json!({"path":"../"})).is_err());
    }
Input 15: 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 16: outline src/authoring/tools.rs mod[tests]/fn[outside_symlinks_are_excluded_from_reads_search_and_discovery]
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.text_search`
    #[cfg(unix)]
    #[test]
    fn outside_symlinks_are_excluded_from_reads_search_and_discovery() {
        let root = project();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("secret.rs"), "fn outside_needle() {}\n").unwrap();
        std::os::unix::fs::symlink(outside.path(), root.path().join("outside")).unwrap();
        std::os::unix::fs::symlink(
            outside.path().join("secret.rs"),
            root.path().join("outside.rs"),
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
        assert!(listing.result.as_array().unwrap().iter().all(|entry| {
            !["outside", "outside.rs"].contains(&entry["path"].as_str().unwrap())
        }));
        let search = dispatch(&sources, "ripgrep", &json!({"pattern":"outside_needle"})).unwrap();
        assert!(matched(&search).is_empty());
        for path in ["outside/secret.rs", "outside.rs"] {
            for arguments in [
                json!({"file":path, "line_start":1}),
                json!({"file":path, "line_start":1, "line_end":1}),
                json!({"file":path, "item":"fn[outside_needle]"}),
            ] {
                assert!(dispatch(&sources, "habeas", &arguments).is_err());
            }
            assert!(
                dispatch(
                    &sources,
                    "ripgrep",
                    &json!({"path":path, "pattern":"needle"})
                )
                .is_err()
            );
        }
        assert!(dispatch(&sources, "list_files", &json!({"path":"outside"})).is_err());
    }
Input 17: 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 18: outline src/authoring/tools.rs mod[tests]/fn[git_tools_allow_staged_and_dirty_sources_but_hide_untracked_files]
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.read_denial`
    #[test]
    fn git_tools_allow_staged_and_dirty_sources_but_hide_untracked_files() {
        let root = project();
        fs::create_dir(root.path().join("tracked-dir")).unwrap();
        fs::write(root.path().join("tracked-dir/file.txt"), "original\n").unwrap();
        fs::write(root.path().join("staged.txt"), "needle staged\n").unwrap();
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        fs::write(root.path().join("tracked-dir/file.txt"), "needle dirty\n").unwrap();
        fs::create_dir(root.path().join("untracked-dir")).unwrap();
        fs::write(
            root.path().join("untracked-dir/file.txt"),
            "needle hidden\n",
        )
        .unwrap();
        fs::write(root.path().join("untracked.rs"), "fn needle() {}\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
        assert_eq!(
            listing
                .result
                .get("entries")
                .unwrap_or(&listing.result)
                .as_array()
                .unwrap()
                .iter()
                .map(|entry| entry["path"].as_str().unwrap())
                .collect::<Vec<_>>(),
            vec!["Cargo.toml", "book.toml", "md", "staged.txt", "tracked-dir"]
        );
        for (path, text) in [
            ("staged.txt", "needle staged"),
            ("tracked-dir/file.txt", "needle dirty"),
        ] {
            let read = dispatch(&sources, "habeas", &json!({"file":path, "line_start":1})).unwrap();
            assert_eq!(read.result["inputs"][0]["text"], json!([text]));
        }
        let search = dispatch(&sources, "ripgrep", &json!({"pattern":"needle"})).unwrap();
        assert_eq!(
            matched(&search)
                .iter()
                .map(|input| input["file"].as_str().unwrap())
                .collect::<Vec<_>>(),
            vec!["staged.txt", "tracked-dir/file.txt"]
        );
        for arguments in [
            json!({"file":"untracked.rs", "line_start":1}),
            json!({"file":"untracked.rs", "line_start":1, "line_end":1}),
            json!({"file":"untracked.rs", "item":"fn[needle]"}),
        ] {
            let error = dispatch(&sources, "habeas", &arguments).err().unwrap();
            assert!(error.to_string().contains("git add"), "{error}");
        }
        let error = dispatch(&sources, "outline", &json!({"file":"untracked.rs"}))
            .err()
            .unwrap();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
        assert!(error.to_string().contains("git add"), "{error}");
        assert!(dispatch(&sources, "list_files", &json!({"path":"untracked-dir"})).is_err());
        assert!(
            dispatch(
                &sources,
                "ripgrep",
                &json!({"path":"untracked.rs", "pattern":"needle"})
            )
            .is_err()
        );
    }
Input 19: outline src/authoring/tools.rs mod[tests]/fn[git_symlink_reads_require_both_the_alias_and_target_to_be_tracked]
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.read_denial`
    #[cfg(unix)]
    #[test]
    fn git_symlink_reads_require_both_the_alias_and_target_to_be_tracked() {
        let root = project();
        fs::write(root.path().join("tracked.txt"), "needle allowed\n").unwrap();
        fs::write(root.path().join("untracked.txt"), "needle hidden\n").unwrap();
        for (alias, target) in [
            ("tracked-alias.txt", "tracked.txt"),
            ("untracked-target.txt", "untracked.txt"),
            ("untracked-alias.txt", "tracked.txt"),
        ] {
            std::os::unix::fs::symlink(target, root.path().join(alias)).unwrap();
        }
        git(root.path(), &["init", "--quiet"]);
        git(
            root.path(),
            &[
                "add",
                "Cargo.toml",
                "book.toml",
                "md",
                "tracked.txt",
                "tracked-alias.txt",
                "untracked-target.txt",
            ],
        );
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let allowed = dispatch(
            &sources,
            "habeas",
            &json!({"file":"tracked-alias.txt", "line_start":1}),
        )
        .unwrap();
        assert_eq!(
            allowed.result["inputs"][0]["text"],
            json!(["needle allowed"])
        );
        for alias in ["untracked-target.txt", "untracked-alias.txt"] {
            assert!(
                dispatch(&sources, "habeas", &json!({"file":alias, "line_start":1}))
                    .err()
                    .unwrap()
                    .to_string()
                    .contains("git add")
            );
            assert!(
                dispatch(
                    &sources,
                    "ripgrep",
                    &json!({"path":alias, "pattern":"needle"})
                )
                .is_err()
            );
        }
        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(&"tracked-alias.txt"));
        assert!(!paths.contains(&"untracked-target.txt"));
        assert!(!paths.contains(&"untracked-alias.txt"));
        assert!(!paths.contains(&"untracked.txt"));
    }
Input 20: 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 21: 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 22: outline src/authoring/tools.rs mod[tests]/fn[search_uses_the_validated_target_when_symlinks_precede_parent_components]
  • File: src/authoring/tools.rs
  • Selector: mod[tests]/fn[search_uses_the_validated_target_when_symlinks_precede_parent_components]
  • Kind: fn
  • src/authoring/tools.rs:2705–2730
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.configuration.evidence_paths`
    // {test}`requirements.ci.input_containment`
    #[cfg(unix)]
    #[test]
    fn search_uses_the_validated_target_when_symlinks_precede_parent_components() {
        let root = project();
        fs::create_dir_all(root.path().join("actual/nested")).unwrap();
        fs::write(root.path().join("actual/needle.txt"), "actual needle\n").unwrap();
        fs::write(root.path().join("needle.txt"), "wrong needle\n").unwrap();
        std::os::unix::fs::symlink(root.path().join("actual/nested"), root.path().join("alias"))
            .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let result = dispatch(
            &sources,
            "ripgrep",
            &json!({"path":"alias/../needle.txt", "pattern":"needle", "context":0}),
        )
        .unwrap();
        assert_eq!(matched(&result).len(), 1);
        assert_eq!(matched(&result)[0]["file"], "actual/needle.txt");
        assert_eq!(
            matched(&result)[0]["lines"],
            json!([{"text": "actual needle", "matched": true}])
        );
    }
Input 23: outline src/authoring/tools.rs mod[tests]/fn[parallel_search_orders_results_by_path_and_line]
    // {test}`requirements.authoring.text_search`
    #[test]
    fn parallel_search_orders_results_by_path_and_line() {
        let root = project();
        for index in (0..40).rev() {
            fs::write(
                root.path().join(format!("src/file{index:02}.rs")),
                "// needle\nfn a() {\n    // needle\n}\n",
            )
            .unwrap();
        }
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let first = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern": "needle", "path": "src", "context": 0}),
        )
        .unwrap();
        let files: Vec<_> = first.result["matches"]
            .as_array()
            .unwrap()
            .iter()
            .map(|input| {
                (
                    input["file"].as_str().unwrap().to_owned(),
                    input["item"].as_str().unwrap().to_owned(),
                )
            })
            .collect();
        let mut sorted = files.clone();
        sorted.sort();
        assert_eq!(files, sorted);
        // Both comment matches in each file belong to its one function.
        assert_eq!(files.len(), 40);
        assert!(
            first.result["matches"]
                .as_array()
                .unwrap()
                .iter()
                .all(|input| input["item"] == "fn[a]" && input.get("line_end").is_none())
        );
        for _ in 0..5 {
            let again = dispatch(
                &sources,
                "ripgrep",
                &json!({"pattern": "needle", "path": "src", "context": 0}),
            )
            .unwrap();
            assert_eq!(again.result["matches"], first.result["matches"]);
            assert_ne!(again.result["search_id"], first.result["search_id"]);
        }
        assert!(dispatch(&sources, "ripgrep", &json!({"pattern": "("})).is_err());
    }
Input 24: outline src/authoring/tools.rs mod[tests]/fn[unpermitted_requests_outside_the_project_are_recoverable_tool_errors]
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.outline_tool`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[test]
    fn unpermitted_requests_outside_the_project_are_recoverable_tool_errors() {
        let root = project();
        let external = tempfile::tempdir().unwrap();
        fs::write(external.path().join("lib.rs"), "fn external() {}\n").unwrap();
        let file = external.path().join("lib.rs");
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let requests = [
            ("habeas", json!({"file": file, "line_start": 1})),
            ("habeas", json!({"file": file, "item": "fn[external]"})),
            ("list_files", json!({"path": external.path()})),
            ("outline", json!({"file": file})),
            (
                "ripgrep",
                json!({"path": external.path(), "pattern": "external"}),
            ),
        ];
        for (name, arguments) in &requests {
            let error = dispatch(&sources, name, arguments).err().unwrap();
            assert_ne!(
                error.kind(),
                io::ErrorKind::PermissionDenied,
                "{name}: {error}"
            );
            assert!(error.to_string().contains("outside the project"), "{error}");
        }
        assert!(sources.recorded_inputs().is_empty());

        // A matching disallow still aborts, as do in-project denials.
        fs::write(
            root.path().join("habeas.toml"),
            format!(
                "version = 1\n[evidence]\ndisallow = [{:?}]\n",
                external.path().to_str().unwrap()
            ),
        )
        .unwrap();
        fs::create_dir_all(root.path().join("evidence")).unwrap();
        fs::write(root.path().join("evidence/old.json"), "{}\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for (name, arguments) in &requests[..1] {
            let error = dispatch(&sources, name, arguments).err().unwrap();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
        }
        let error = dispatch(
            &sources,
            "habeas",
            &json!({"file": "evidence/old.json", "item": ""}),
        )
        .err()
        .unwrap();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
    }
Input 25: outline src/authoring/tools.rs mod[tests]/fn[context_windows_include_exactly_the_requested_lines_on_each_side]
    // {test}`requirements.authoring.text_search`
    #[test]
    fn context_windows_include_exactly_the_requested_lines_on_each_side() {
        let root = project();
        let source = "fn long() {\n    before_far();\n    before_three();\n    before_two();\n    before_one();\n    needle();\n    after_one();\n    after_two();\n    after_three();\n    after_far();\n}\n";
        fs::write(root.path().join("src/lib.rs"), source).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for context in [None, Some(0), Some(1), Some(2), Some(3)] {
            let mut arguments = json!({"pattern":"needle","path":"src/lib.rs"});
            if let Some(context) = context {
                arguments["context"] = json!(context);
            }
            let delivery = dispatch(&sources, "ripgrep", &arguments).unwrap();
            let count = context.unwrap_or(2);
            let expected = source
                .lines()
                .enumerate()
                .skip(5 - count)
                .take(2 * count + 1)
                .map(|(index, text)| json!({"text":text, "matched":index == 5}))
                .collect::<Vec<_>>();
            assert_eq!(
                delivery.result["matches"][0]["lines"],
                json!(expected),
                "{context:?}"
            );
        }
    }
Input 26: outline src/authoring/tools.rs mod[tests]/fn[separate_windows_in_one_node_are_divided_by_an_elision_line]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn separate_windows_in_one_node_are_divided_by_an_elision_line() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn long() {\n    needle(1);\n    a();\n    b();\n    c();\n    needle(2);\n    d();\n}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle","path":"src/lib.rs","context":0}),
        )
        .unwrap();
        assert_eq!(
            matched(&search),
            &vec![
                json!({"file": "src/lib.rs", "item": "fn[long]", "kind": "fn", "tag":"1", "lines": [
                    {"text": "    needle(1);", "matched": true},
                    {"text": ELISION, "matched": false},
                    {"text": "    needle(2);", "matched": true},
                ]})
            ]
        );
        // Adjacent windows are one run, with no elision.
        let joined = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle","path":"src/lib.rs","context":2}),
        )
        .unwrap();
        let lines = matched(&joined)[0]["lines"].as_array().unwrap().clone();
        assert!(
            lines.iter().all(|line| line["text"] != ELISION),
            "{lines:?}"
        );
        assert_eq!(lines.len(), 8);
        let defaults = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle","path":"src/lib.rs"}),
        )
        .unwrap();
        assert_eq!(
            defaults.result["matches"][0]["lines"],
            joined.result["matches"][0]["lines"]
        );
    }
Input 27: 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 28: outline src/authoring/tools.rs mod[tests]/fn[exact_match_ranges_preserve_regex_anchors_and_skip_unmatched_or_binary_sources]
  • File: src/authoring/tools.rs
  • Selector: mod[tests]/fn[exact_match_ranges_preserve_regex_anchors_and_skip_unmatched_or_binary_sources]
  • Kind: fn
  • src/authoring/tools.rs:3670–3708
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.search_accounting.excerpts`
    #[test]
    fn exact_match_ranges_preserve_regex_anchors_and_skip_unmatched_or_binary_sources() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn exact() { needle(); }\nfn last() {}\n",
        )
        .unwrap();
        fs::write(root.path().join("src/broken.rs"), "fn incomplete( {\n").unwrap();
        fs::write(root.path().join("image.bin"), b"\0needle\xff").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for pattern in [
            r"^fn exact",
            r"needle\(\); \}$",
            r"(?i)EXACT",
            r"^fn exact.*$",
        ] {
            let result = dispatch(
                &sources,
                "ripgrep",
                &json!({"pattern":pattern,"context":10}),
            )
            .unwrap();
            assert_eq!(
                found(&result),
                ["src/lib.rs#fn[exact]"],
                "{pattern}: {}",
                result.result
            );
            assert_eq!(
                result.result["matches"][0]["lines"],
                json!([
                    {"text":"fn exact() { needle(); }","matched":true}
                ])
            );
        }
    }
Input 29: outline src/authoring/tools.rs mod[tests]/fn[search_returns_innermost_nodes_and_comment_owners]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.references.outline_comments`
    #[test]
    fn search_returns_innermost_nodes_and_comment_owners() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn outer() {\n    fn inner() {\n        needle();\n    }\n}\n\n// needle in a comment\nfn after() {}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle","path":"src/lib.rs","context":0}),
        )
        .unwrap();
        let items = matched(&search)
            .iter()
            .map(|input| input["item"].as_str().unwrap())
            .collect::<Vec<_>>();
        assert_eq!(items, ["fn[outer]/fn[inner]", "fn[after]"]);
        // A comment match belongs to its owner, and shows the matching line.
        assert_eq!(
            matched(&search)[1],
            json!({"file": "src/lib.rs", "item": "fn[after]", "kind": "fn", "tag":"2",
                "lines": [{"text": "// needle in a comment", "matched": true}]})
        );
        assert_eq!(
            matched(&search)[0]["lines"],
            json!([{"text": "        needle();", "matched": true}])
        );
        // Entries carry no hash: they are not evidence inputs.
        assert!(matched(&search)[0].get("hash").is_none());
    }
Input 30: outline src/authoring/tools.rs mod[tests]/fn[ripgrep_tool_is_advertised_with_its_interface_and_conventions]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.tool_descriptions.common_case`
    #[test]
    fn ripgrep_tool_is_advertised_with_its_interface_and_conventions() {
        let definitions = definitions();
        let ripgrep = definitions
            .iter()
            .find(|definition| definition["name"] == "ripgrep")
            .expect("ripgrep tool is advertised");
        assert_eq!(
            ripgrep["parameters"],
            json!({
                "type": "object",
                "properties": {
                    "pattern": {"type": "string"},
                    "path": {"type": "string", "default": "."},
                    "context": {"type": "integer", "minimum": 0, "default": 2},
                    "referencing": {
                        "type": "object",
                        "properties": {
                            "selection": {"type": "string"},
                            "roles": {
                                "type": "array",
                                "items": {"type": "string", "enum": ["impl", "test", "cite", "fixme"]},
                                "default": ["impl", "test", "cite"]
                            },
                            "scope": {"type": "string", "enum": ["node", "file"], "default": "file"}
                        },
                        "required": ["selection"],
                        "additionalProperties": false
                    }
                },
                "required": ["pattern"],
                "additionalProperties": false
            })
        );
        let description = ripgrep["description"].as_str().unwrap();
        for phrase in [
            "ripgrep regex syntax",
            "case-sensitive",
            "default 2",
            "zero means matches only",
            "overlapping windows are merged",
            "Windows stop at item boundaries",
            "Before submitting, call finish_search",
            "{search_id, matches: [{tag, file, item, kind, lines: [{text, matched}]}]}",
            "without line numbers",
            "separates windows within one node",
            "one entry for each innermost outline node containing a match",
            "a match in a comment belongs to the node the comment belongs to",
            "Results carry no definitions",
            "Selected items become evidence dependencies without another source read",
            "No matches returns an empty matches array",
            "With referencing {selection, roles, scope}",
            "Search a project-relative file or directory (default .)",
            "default [impl, test, cite]",
            "including :impl: and :test: declaration anchors",
            "scope node searches only the outline nodes that contain or are named by those references",
            "scope file (the default) their whole files",
            r#"{"pattern":"errors","referencing":{"selection":"requirements.ci.*","roles":["impl"],"scope":"node"}}"#,
        ] {
            assert!(description.contains(phrase), "{phrase:?} in {description}");
        }
    }
Input 31: outline src/authoring/tools.rs mod[tests]/fn[search_records_nothing_clamps_at_eof_and_reports_failures]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.additional_read`
    #[test]
    fn search_records_nothing_clamps_at_eof_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();
        fs::write(
            root.path().join("src/lib.rs"),
            format!(
                "fn first() {{}}\n\n// {}\nfn needle() {{}}\n",
                role("term", "terms.value")
            ),
        )
        .unwrap();
        // An allowed hidden directory is searched; an unallowed one is not.
        fs::create_dir_all(root.path().join(".generated")).unwrap();
        fs::write(root.path().join(".generated/out.txt"), "needle allowed\n").unwrap();
        fs::create_dir_all(root.path().join(".other")).unwrap();
        fs::write(root.path().join(".other/out.txt"), "needle hidden\n").unwrap();
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\nallow = ['.generated']\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"fn needle","path":"src","context":5}),
        )
        .unwrap();
        // Context includes the attached comment and stops at the item boundary.
        assert_eq!(
            matched(&search),
            &vec![
                json!({"file": "src/lib.rs", "item": "fn[needle]", "kind": "fn", "tag":"1",
                "lines": [
                    {"text": "// {term}`terms.value`", "matched": false},
                    {"text": "fn needle() {}", "matched": true},
                ]})
            ]
        );
        // The terminology the node uses is neither supplied nor recorded.
        assert!(search.result.get("definitions").is_none());
        assert!(sources.recorded_inputs().is_empty());
        let hidden = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle (allowed|hidden)","context":0}),
        )
        .unwrap();
        let files = matched(&hidden)
            .iter()
            .map(|input| input["file"].as_str().unwrap())
            .collect::<Vec<_>>();
        assert_eq!(files, [".generated/out.txt"]);
        // Invalid arguments are explanatory tool errors.
        for (arguments, message) in [
            (json!({}), "pattern must be a string"),
            (json!({"pattern": 1}), "pattern must be a string"),
            (json!({"pattern":"x","path":1}), "path must be a string"),
            (
                json!({"pattern":"x","context":1.5}),
                "context must be a nonnegative integer",
            ),
            (
                json!({"pattern":"x","extra":true}),
                "unexpected tool argument \"extra\"",
            ),
            (json!({"pattern":"("}), "invalid ripgrep pattern"),
        ] {
            let error = dispatch(&sources, "ripgrep", &arguments).err().unwrap();
            assert!(error.to_string().contains(message), "{arguments}: {error}");
        }
        // A matched file that cannot be parsed fails the search with an
        // explanatory error rather than silently dropping the match.
        fs::write(root.path().join("src/broken.rs"), "fn needle( {\n").unwrap();
        let error = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"fn needle","path":"src"}),
        )
        .err()
        .unwrap();
        assert!(error.to_string().contains("syntax error"), "{error}");
    }
Input 32: outline src/authoring/tools.rs mod[tests]/fn[text_search_selects_example_test_references_and_test_anchors]
    // {test}`requirements.authoring.text_search`
    #[test]
    fn text_search_selects_example_test_references_and_test_anchors() {
        let root = referencing_project();
        let declarations = root.path().join("md/requirements.md");
        let mut text = fs::read_to_string(&declarations).unwrap();
        text.push_str("\n:::{example} case\n:test: src/other.rs\nA named case. {cite}`requirements.ready`\n:::\n");
        fs::write(declarations, text).unwrap();
        fs::write(
            root.path().join("src/example_test.rs"),
            format!(
                "// {}\nfn example_test() {{ needle(); }}\n",
                role("test", "requirements.case")
            ),
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let result = dispatch(&sources, "ripgrep", &json!({"pattern":"needle","context":0,"referencing":{"selection":"requirements.case","roles":["test"]}})).unwrap();
        assert_eq!(
            found(&result),
            [
                "src/example_test.rs#fn[example_test]",
                "src/other.rs#fn[elsewhere]"
            ]
        );
        let no_impl = dispatch(&sources, "ripgrep", &json!({"pattern":"needle","referencing":{"selection":"requirements.case","roles":["impl"]}})).unwrap();
        assert!(found(&no_impl).is_empty());
    }
Input 33: outline src/authoring/tools.rs mod[tests]/fn[ripgrep_referencing_searches_only_referencing_files_or_nodes]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.references.definition_globs`
    // {test}`requirements.references.anchors`
    #[test]
    fn ripgrep_referencing_searches_only_referencing_files_or_nodes() {
        let root = referencing_project();
        fs::write(
            root.path().join("src/gap.rs"),
            "// :::{fixme} requirements.ready\n// This boundary needs a test.\n// :::\nfn gap() { needle(); }\n",
        ).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = |referencing: Value, context: u64| {
            dispatch(
                &sources,
                "ripgrep",
                &json!({"pattern":"needle","context":context,"referencing":referencing}),
            )
        };
        // By default, every impl, test, or cite reference selects its whole file.
        assert_eq!(
            found(&search(json!({"selection":"requirements.ready"}), 0).unwrap()),
            [
                "src/cite.rs#fn[before]",
                "src/cite.rs#fn[cited]",
                "src/lib.rs#fn[ready]",
                "src/lib.rs#fn[unrelated]"
            ]
        );
        for scope in ["file", "node"] {
            assert_eq!(
                found(
                    &search(
                        json!({"selection":"requirements.ready","roles":["fixme"],"scope":scope}),
                        0
                    )
                    .unwrap()
                ),
                ["src/gap.rs#fn[gap]"]
            );
        }
        // Roles narrow the references; a glob selects several definitions,
        // including declaration anchors.
        assert_eq!(
            found(&search(json!({"selection":"requirements.*","roles":["impl"]}), 0).unwrap()),
            [
                "src/lib.rs#fn[ready]",
                "src/lib.rs#fn[unrelated]",
                "src/other.rs#fn[elsewhere]"
            ]
        );
        // Node scope searches only the nodes the references belong to, and
        // context windows stop at their boundaries.
        let node = search(json!({"selection":"requirements.ready","scope":"node"}), 5).unwrap();
        assert_eq!(
            found(&node),
            ["src/cite.rs#fn[cited]", "src/lib.rs#fn[ready]"]
        );
        // `path` still limits the search.
        let limited = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle","path":"src/lib.rs","referencing":{"selection":"requirements.*"}}),
        )
        .unwrap();
        assert_eq!(found(&limited).len(), 2);
        // A matching definition with no references in the roles finds nothing.
        let none = search(json!({"selection":"requirements.third"}), 0).unwrap();
        assert_eq!(none.result["matches"], json!([]));
        for (referencing, message) in [
            (
                json!({"selection":"requirements.none"}),
                "matches no requirement or named example",
            ),
            (
                json!({"selection":"requirements.ready","roles":["bogus"]}),
                "unknown referencing role",
            ),
            (
                json!({"selection":"requirements.ready","roles":"impl"}),
                "roles must be an array",
            ),
            (
                json!({"selection":"requirements.ready","scope":"dir"}),
                "unknown referencing scope",
            ),
            (
                json!({"selection":"requirements.ready","extra":1}),
                "unexpected referencing argument",
            ),
            (
                json!({"roles":["impl"]}),
                "referencing.selection must be a string",
            ),
            (json!("requirements.ready"), "referencing must be an object"),
        ] {
            let error = search(referencing.clone(), 0).err().unwrap();
            assert!(
                error.to_string().contains(message),
                "{referencing}: {error}"
            );
        }
    }
Input 34: outline src/authoring/tools.rs mod[tests]/fn[ripgrep_node_scope_searches_only_the_node_a_selector_anchor_names]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.references.anchors`
    #[test]
    fn ripgrep_node_scope_searches_only_the_node_a_selector_anchor_names() {
        let root = referencing_project();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\nThe project MUST be ready.\n:::\n\n:::{req} anchored\n:impl: src/plain.rs#fn[second]\nAnchored.\n:::\n\n:::{req} stale\n:impl: src/plain.rs#fn[gone]\nStale.\n:::\n",
        )
        .unwrap();
        fs::write(
            root.path().join("src/plain.rs"),
            "fn plain() {\n    needle();\n}\n\nfn second() {\n    needle();\n}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = |selection: &str, scope: &str| {
            dispatch(
                &sources,
                "ripgrep",
                &json!({"pattern":"needle","context":5,"referencing":{"selection":selection,"scope":scope}}),
            )
            .unwrap()
        };
        // Node scope searches only the node the anchor names, and the context
        // window stops at its boundary rather than reaching `plain`.
        let node = search("requirements.anchored", "node");
        assert_eq!(found(&node), ["src/plain.rs#fn[second]"]);
        // File scope searches the anchored file.
        assert_eq!(
            found(&search("requirements.anchored", "file")),
            ["src/plain.rs#fn[plain]", "src/plain.rs#fn[second]"]
        );
        // A selector that no longer resolves names no node to search.
        assert_eq!(
            found(&search("requirements.stale", "node")),
            Vec::<String>::new()
        );
    }
Input 35: 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.search_accounting.excerpts
:::{req} search_accounting.excerpts
Every `ripgrep` or `ast_grep` excerpt, including matching and context text,
MUST be clipped to
the source span of the outline item identified by their `file` and `item`,
including that item's attached source under
{cite}`requirements.references.outline_comments`.
Clipping MUST apply within a line shared by different items.
:::
Input 3: requirements selection requirements.references.outline_comments
:::{req} outline_comments
Each documented profile defines which grammar nodes are comments; the Markdown
profile's comments are HTML comment blocks, so an inline HTML comment within a
paragraph is text of its section. In every supported language, comments on consecutive lines with no other source
between them MUST form one comment run. A comment that follows other source on
the same line, including another comment, MUST form a run by itself and MUST belong to the innermost outline node
containing that line. Any other run MUST belong to the next outline node that
starts after it within the smallest node containing it; when that container has
no such node, the run MUST belong to the container, which is the root node at top
level. A profile MAY bind a comment kind to its container
instead: such a run MUST belong to the smallest node containing it. The Rust
profile MUST bind inner doc comments (`//!`, `/*!`) to their container, so a
file-level inner doc comment belongs to the root node. A reference in a comment MUST count for the node its run belongs to under
{cite}`requirements.references.rust_item_coverage` and
{cite}`requirements.references.authoring_inputs`.
:::
Input 4: requirements selection requirements.references.outline_selectors
:::{req} outline_selectors
An outline selector MUST be a `/`-separated path of segments from the file's
root node to an outline node; the empty selector MUST select the root node. A
named node's segment MUST be `kind[name]`. An anonymous node's segment MUST be
`kind@hash`, where `hash` is the first twelve hexadecimal digits of its identity
hash under {cite}`requirements.references.structural_hash`. Siblings whose
segments would otherwise be identical MUST be disambiguated by `#N`, their
one-based position among those siblings in source order, except `line` nodes:
identical lines are interchangeable, so a `line` selector MUST resolve when any
line with that content exists in the file. In names, `%`, `[`, `]`, `/`, `#`,
`@`, and whitespace MUST be percent-encoded as UTF-8 bytes, so selectors are
reversible. Line numbers MUST NOT form part of a selector.
:::
Input 5: requirements selection requirements.authoring.redaction
:::{req} redaction
Every source text the harness supplies to a model, including mandatory inputs,
`habeas` reads, and `ripgrep` results, and every source text Habeas displays in
the book or `habeas info`, MUST be redacted:

1. In a workspace `habeas.toml` or user configuration file, the value of every
   explicit credential field defined by {cite}`requirements.authoring.credentials`
   MUST be replaced. Such a file that is not valid TOML MUST be replaced whole,
   with `configuration` as the kind, because its fields cannot be located.
2. In every source, each match of a built-in rule of the `secretshape` crate MUST
   be replaced. The replaced region MUST be extended through each adjacent region
   that the crate's entropy heuristic flags and that only whitespace separates
   from the region, repeating until no flagged region is adjacent. The heuristic
   MUST NOT cause redaction on its own.

A replacement MUST read `[REDACTED:<kind>]`, where `<kind>` is the credential
field or the rule's name, and MUST keep every line break within the replaced
text, so line numbers are unchanged. Outlines MUST be built from the original
source, and the structural hash MUST hash each text piece that overlaps a
redacted region in its redacted form, so evidence never depends on a credential's
value and redaction never changes or breaks a file's outline. The `secretshape` version MUST be pinned exactly; upgrading
it MAY change redaction and hashes and MUST be treated as a deliberate change.
:::
Input 6: 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 7: requirements selection requirements.authoring.search_accounting.instructions
:::{req} search_accounting.instructions
The first delivered search result in each assessment MUST include an
`instructions` field containing this text:

```text
Before submitting your assessment, close every delivered search with finish_search({search_id, used:[tags]}). Submission fails while any search remains open. Include a tag only when you used information in its snippet to justify your conclusion without an additional source read. Entries whose source you subsequently read with habeas may be omitted; including them is harmless. Use used:[] when no entries qualify, including for an empty search. finish_search records dependencies and does not request more source.
```
:::
Input 8: requirements selection requirements.authoring.finish_search.description
:::{req} finish_search.description
The model-facing search and `finish_search` tool descriptions MUST give the
same selection guidance as
{cite}`requirements.authoring.search_accounting.instructions`.
:::
Input 9: requirements selection requirements.references.definition_globs
:::{req} definition_globs
A definition glob MUST match a complete full name. `*` MUST match zero or more characters, including dots; all other valid name characters MUST match literally. An empty glob MUST be invalid. Every definition selection MUST use this matching rule, including requirements evidence inputs, CLI definition filters, and the authoring `references` tool, and MUST match against both requirements and named examples.
:::
Input 10: requirements selection requirements.references.anchors
:::{req} anchors
A `{req}` declaration MAY list `:impl:` and `:test:` options, and an `{example}`
declaration MAY list `:test:` options, immediately after its opening fence and
before its body, one per option line, naming a project file path or
`path#selector` for one outline node under
{cite}`requirements.references.outline_selectors`. Each anchor MUST be an `{impl}` or `{test}` edge, under
{cite}`requirements.references.roles`, from the definition to the anchored file or
node, for files that cannot or should not carry a reference themselves.
Paths MUST follow the path rules in {cite}`requirements.ci.schema`. Option lines
MUST NOT form part of the definition's text for evidence comparison or for
requirements inputs, and MUST NOT render as body text.

For each `:test:` anchor, the harness MUST include the selected file or node's
source text in the initial model request under
{cite}`requirements.authoring.mandatory_inputs` and MUST record that selection
as an evidence input under {cite}`requirements.references.evidence_coverage`,
so changing that source makes the evidence stale.
A `:impl:` anchor alone MUST NOT require an input selecting its source. A path or selector that
does not resolve to a readable, permitted file or node MUST be a validation error naming the
definition and the path; authoring MUST report it before inference. Any other option line in a `{req}` or
`{example}` declaration MUST be a validation error.
:::
Input 11: requirements selection requirements.authoring.source_tools
:::{req} source_tools
The harness MUST expose a `habeas` tool accepting exactly one of these request
forms. Each form MUST correspond to one existing evidence-input kind:

| Request fields | Evidence input returned | Definition |
| --- | --- | --- |
| `file: String`, `line_start: Integer`, optional `line_end: Integer` | Outline inputs for the innermost outline nodes covering the range | {cite}`requirements.ci.outline_inputs` |
| `file: String`, `item: String` | Outline input | {cite}`requirements.ci.outline_inputs` |
| `requirements: String` | Requirements input, including its matching names | {cite}`requirements.ci.requirements_inputs` |
| `definition: String` | Definition input | {cite}`requirements.definitions.inputs` |

Selector arguments MUST use the syntax defined by
{cite}`requirements.references.outline_selectors`. Reads MUST use the current
project working tree, including unstaged changes to tracked files and staged new
files. By default, source inputs MUST stay within the project root after
resolving symlinks; in a Git worktree, both the requested file and its resolved
target MUST be present in the Git index. Projects outside Git MUST use the same
containment rules without requiring an index. Failure to read an existing
repository's index MUST be reported as an error.
The project-root `evidence/` directory MUST be excluded from model reads by
default, including symlink aliases. Every source the harness supplies to the
model MUST be redacted under {cite}`requirements.authoring.redaction`. Generated build outputs MUST follow
{cite}`requirements.authoring.generated_inputs`. Workspace path overrides MUST
follow {cite}`requirements.configuration.evidence_paths`, including explicit
permission for otherwise excluded inputs. A denied mandatory input MUST abort
under {cite}`requirements.authoring.read_denial.mandatory`, and a denied model
read MUST return a tool error under {cite}`requirements.authoring.read_denial`.

Line numbers are only a way to request sources; recorded evidence MUST identify
sources by outline selector and structural hash, never by line number. Request
line numbers MUST be one-based and inclusive, and omitting `line_end` MUST read
through EOF. A line-range request MUST be resolved to the innermost outline
nodes covering the requested lines, which are `line` nodes in a file using the
plain-text profile; the result MUST show the model each node's selector and
source text, without line numbers, and the harness MUST record those nodes as
outline inputs. The model-facing tool description MUST include the argument conventions
from the cited requirements, including outline selector syntax, definition
selections, and full definition names, with a short request example for each form.

A successful call MUST return the requested evidence input, populated by the
harness with the selected source text, using the existing evidence schema.
{cite}`requirements.ci.schema`
Required terminology dependencies MUST be returned alongside it as additional
definition inputs under {cite}`requirements.definitions.authoring_inputs`.
For item, requirement, and definition selections, the result MUST have this shape:

```text
HabeasResult {
    input: EvidenceInput,
    definitions: Array<DefinitionInput>,
}
```

Line-range selections can contain multiple outline nodes. Their result MUST use
`inputs: Array<EvidenceInput>` instead of the singular `input` field, including
when only one node is selected.

`definitions` MUST be empty when no additional terminology is required. The
harness MUST record inputs supplied to the model in the assessment's evidence.
A failed read MUST add no evidence input. Access-policy denials MUST be handled
under {cite}`requirements.authoring.read_denial`; other failed reads MUST return
an explanatory tool error.
:::
Input 12: 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.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 36: outline src/authoring/pages.rs mod[tests]/fn[search_pages_are_accounted_only_when_delivered_and_replay_stays_closed]
  • File: src/authoring/pages.rs
  • Selector: mod[tests]/fn[search_pages_are_accounted_only_when_delivered_and_replay_stays_closed]
  • Kind: fn
  • src/authoring/pages.rs:662–738
    // {test}`requirements.authoring.search_accounting.pagination`
    // {test}`requirements.authoring.search_accounting.page_replay`
    // {test}`requirements.authoring.search_accounting.outstanding`
    // {test}`requirements.authoring.search_accounting.entry_tags`
    // {test}`requirements.authoring.search_accounting.result_ids`
    // {test}`requirements.authoring.search_accounting.instructions`
    // {test}`requirements.authoring.finish_search.completion`
    // {test}`requirements.authoring.finish_search.invalid`
    // {test}`requirements.authoring.result_pages`
    #[test]
    fn search_pages_are_accounted_only_when_delivered_and_replay_stays_closed() {
        let root = project();
        let source: String = (0..600)
            .map(|i| format!("fn needle_{i:04}() {{ let marker = 1; }}\n"))
            .collect();
        fs::write(root.path().join("src/lib.rs"), source).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for (tool, arguments) in [
            ("ripgrep", json!({"pattern":"marker","path":"src/lib.rs"})),
            (
                "ast_grep",
                json!({"language":"rust","rule":{"rule":{"pattern":"let marker = 1;"}}}),
            ),
        ] {
            let mut pages = ResultPages::default();
            let first = dispatch_paged(&sources, &mut pages, tool, &arguments)
                .unwrap()
                .result;
            let token = first["page"]["next"].as_str().unwrap().to_owned();
            assert_eq!(
                first["instructions"],
                super::super::approved_text("search_accounting.instructions", 0)
            );
            uuid::Uuid::parse_str(first["search_id"].as_str().unwrap()).unwrap();
            assert_eq!(
                pages.outstanding_searches(),
                [first["search_id"].as_str().unwrap()]
            );
            let undelivered = pages.pages[&token].0.clone();
            assert!(
                pages
                    .finish_search(&json!({"search_id":undelivered["search_id"],"used":[]}))
                    .is_err()
            );
            assert!(
                pages
                    .finish_search(&json!({"search_id":first["search_id"],
                "used":[undelivered["matches"][0]["tag"]]}))
                    .is_err()
            );
            let second = pages.next_page(&token).unwrap().result;
            uuid::Uuid::parse_str(second["search_id"].as_str().unwrap()).unwrap();
            assert_eq!(second, undelivered);
            assert_ne!(first["search_id"], second["search_id"]);
            assert!(second.get("instructions").is_none());
            assert_eq!(pages.outstanding_searches().len(), 2);
            let finished = pages
                .finish_search(&json!({"search_id":second["search_id"],
                "used":[second["matches"][0]["tag"]]}))
                .unwrap();
            assert_eq!(finished.inputs.len(), 1);
            assert_eq!(finished.inputs[0]["item"], second["matches"][0]["item"]);
            let replay = pages.next_page(&token).unwrap().result;
            assert_eq!(replay, second);
            assert_eq!(
                pages.outstanding_searches(),
                [first["search_id"].as_str().unwrap()]
            );
            pages
                .finish_search(&json!({"search_id":first["search_id"],"used":[]}))
                .unwrap();
            assert!(pages.outstanding_searches().is_empty());
            assert!(sources.recorded_inputs().is_empty());
            assert!(first.to_string().len() <= PAGE_LIMIT);
            assert!(second.to_string().len() <= PAGE_LIMIT);
        }
    }
Input 37: 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"]);
        }
    }