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.tool_descriptions.special_cases

Requirements index · View definition

evidence Valid

Requirement

Model tool descriptions SHOULD NOT explain cases the model meets only occasionally, such as access policy, excluded or build-output paths, redaction, paging, and failures, and the harness SHOULD explain each of these where it occurs: in the tool error, or in a note in the result it affects. The model reads every description on every assessment, so explaining rare cases there costs attention on every review for a case most never meet, and access-policy wording in particular can steer its reasoning away from the review. A tool whose purpose is one of these cases, such as next_page, explains it in its description.

Rationale

Obligations derived from requirements.authoring.tool_descriptions.special_cases

  • (a) Model tool descriptions SHOULD NOT explain rare cases: access policy, excluded or build-output paths, redaction, paging and failures.
  • (b) The harness SHOULD explain each of those cases where it occurs, either in the tool error or in a note in the affected result.
  • (c) A tool whose purpose is one of these cases, such as next_page, explains it in its description.

Coverage of (a) and (c)

  • tools.rs#mod[tests]/fn[descriptions_leave_paging_policy_redaction_and_failures_to_results] runs over every tool definition. It asserts that no lowercased description contains any of these markers:
    • paging and size: “kib”, “returned in pages”
    • redaction: “redact”, “credential”
    • policy: “denied”, “disallow”, “habeas.toml”, “aborts”, “untracked”, “policy”, “permitted”, “exclusion”, “ignore rules”
    • paths and failures: “build output”, “outside the project”, “tool error”
  • The same test pins the next_page parameter schema exactly.
  • tools.rs#mod[tests]/fn[descriptions_give_each_argument_and_the_result_form] checks that next_page still explains its own purpose (“following page”, “same shape”, “token is the page’s next value”, “opaque”). That covers obligation (c).
  • The check is a keyword blacklist, so a description worded around other terms (for example “excluded” or “tracked”) would slip past it. The list is broad and spans every case the requirement names, and I do not treat that as a gap.

Coverage of (b), by case

  • Access policy:
    • tools.rs#mod[tests]/fn[untracked_diagnostics_name_git_add_and_an_allow_rule] asserts the tool error names git add, a habeas.toml allow rule, and the path. It also asserts the harness stages nothing and writes no habeas.toml.
    • access.rs#mod[tests]/fn[evidence_rules_are_literal_paths_not_globs] asserts the “disallowed by habeas.toml rule” message.
    • tools.rs#mod[tests]/fn[unpermitted_requests_outside_the_project_are_recoverable_tool_errors] asserts the “outside the project” error for habeas, list_files, outline and ripgrep. It also asserts the error kind is not PermissionDenied for those requests, and is PermissionDenied for a matching disallow rule.
    • mod.rs#mod[tests]/fn[a_read_through_a_symlink_leaving_the_project_returns_an_error_to_the_model] checks that the denial reaches the model, naming the path and “outside the project”, without leaking the file content.
  • Excluded and generated paths: tools.rs#mod[tests]/fn[generated_evidence_is_excluded_from_reads_search_and_discovery] checks the “generated evidence” error across habeas, list_files, ripgrep and ast_grep, including through symlinks and ./ paths. It also checks that listings omit these paths.
  • Build-output paths: tools.rs#mod[tests]/fn[requests_for_book_or_target_output_are_ordinary_read_failures] asserts the “holds build output … the sources it is built from are elsewhere in the project” message for every tool. It covers the default build directory, a configured build-dir, and target, and checks that book is an ordinary directory when a build-dir is set.
  • Redaction: tools.rs#mod[tests]/fn[only_results_with_redacted_text_carry_the_redaction_note] asserts the note on redacted habeas and ripgrep results. It asserts no note on plain results or on source or requirement text that merely contains the marker.
  • Paging: pages.rs#mod[tests]/fn[large_listings_and_outlines_page_whole_entries_in_order] runs through the helper all_pages. That helper asserts page["note"] == PAGE_NOTE (“call next_page with this page’s next token”) on every page that has a successor.
  • Failures: mod.rs#mod[tests]/fn[malformed_and_failed_reads_return_to_the_model_and_the_assessment_continues] covers six malformed or failed reads. It asserts the error text appears in the second request to the model, is absent from the first, and that nothing is recorded as evidence.

No uncovered obligation, wrong expectation, or unmarked relevant test was found.

Inputs

Implementation

Input 13: outline src/authoring/pages.rs const[PAGE_NOTE]
/// Splits the entries into consecutive pages of whole entries whose JSON,
/// with their definitions and page fields, stays within [`PAGE_LIMIT`],
/// except that an entry exceeding it forms a page of its own. Sizes are
/// counted from above: every element's comma and every accompanying
/// What a page with more entries after it tells the model, since tool
/// descriptions do not explain paging.
// {impl}`requirements.authoring.result_pages`
// {impl}`requirements.authoring.tool_descriptions.special_cases`
const PAGE_NOTE: &str =
    "More entries remain: call next_page with this page's next token to get them.";

Tests

Input 2: outline src/authoring/access.rs mod[tests]/fn[evidence_rules_are_literal_paths_not_globs]
    // {test}`requirements.configuration.evidence_paths`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[test]
    fn evidence_rules_are_literal_paths_not_globs() {
        let root = tempfile::tempdir().unwrap();
        fs::create_dir_all(root.path().join("src")).unwrap();
        fs::write(root.path().join("src/lib.rs"), "pub fn lib() {}\n").unwrap();
        fs::write(root.path().join("notes.txt"), "notes\n").unwrap();
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "src/lib.rs"]);
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\nallow = ['*.txt', 'note?.txt']\ndisallow = ['src/*', 'src/[a-z]*.rs']\n",
        )
        .unwrap();
        let root = fs::canonicalize(root.path()).unwrap();
        let access = SourceAccess::load(&root).unwrap();
        // No pattern matches: the tracked file stays readable and the
        // untracked one stays refused by the default rules.
        assert!(access.file(&root, Path::new("src/lib.rs")).is_ok());
        assert!(access.file(&root, Path::new("notes.txt")).is_err());
        #[cfg(unix)]
        {
            // A rule names exactly the path written, metacharacters included.
            fs::write(root.join("*.txt"), "literal\n").unwrap();
            fs::write(root.join("src/*"), "literal\n").unwrap();
            let access = SourceAccess::load(&root).unwrap();
            assert!(access.file(&root, Path::new("*.txt")).is_ok());
            let error = access.file(&root, Path::new("src/*")).unwrap_err();
            assert!(
                error.to_string().contains("disallowed by habeas.toml rule"),
                "{error}"
            );
            assert!(access.file(&root, Path::new("src/lib.rs")).is_ok());
        }
    }
Input 3: outline src/authoring/mod.rs mod[tests]/fn[malformed_and_failed_reads_return_to_the_model_and_the_assessment_continues]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[malformed_and_failed_reads_return_to_the_model_and_the_assessment_continues]
  • Kind: fn
  • src/authoring/mod.rs:2052–2103
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[tokio::test]
    async fn malformed_and_failed_reads_return_to_the_model_and_the_assessment_continues() {
        for read in [
            json!({"file": "src/lib.rs", "line_start": "one"}),
            json!({"file": "src/lib.rs"}),
            json!({"file": "src/lib.rs", "item": "fn[work]", "requirements": "*"}),
            json!({"file": "missing.rs", "line_start": 1}),
            json!({"file": "src/lib.rs", "item": "fn[absent]"}),
            json!({"file": "src/lib.rs", "line_start": 99}),
        ] {
            let project = inputs::tests::project();
            fs::write(project.path().join("src/lib.rs"), "fn work() {}\n").unwrap();
            let mut sources =
                AssessmentSources::prepare(project.path(), "requirements.ready").unwrap();
            let state = tempfile::tempdir().unwrap();
            let mut usage =
                UsageLog::start(state.path(), project.path(), &sources.subject_name).unwrap();
            let provider = ReadingProvider {
                read: read.clone(),
                requests: RefCell::default(),
            };
            let failure = tools::dispatch(&sources, "habeas", &read)
                .err()
                .unwrap_or_else(|| panic!("{read} fails"));
            assert_ne!(failure.kind(), io::ErrorKind::PermissionDenied, "{read}");
            let (_, evidence) = assess(&provider, &mut sources, &mut usage)
                .await
                .unwrap_or_else(|error| panic!("{read}: {error}"));
            // The failure went back to the model as a tool error, and the model
            // then submitted in a second request.
            let requests = provider.requests.borrow();
            assert_eq!(requests.len(), 2, "{read}");
            let message =
                serde_json::to_string(&line_numbers::without_source_lines(&failure.to_string()))
                    .unwrap();
            let message = message.trim_matches('"');
            assert!(!requests[0].to_string().contains(message), "{read}");
            assert!(requests[1].to_string().contains(message), "{read}");
            assert!(
                evidence["inputs"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .all(|input| input
                        .get("file")
                        .is_none_or(|file| file != "src/lib.rs" && file != "missing.rs")),
                "{read}: {evidence}"
            );
        }
    }
Input 4: outline src/authoring/mod.rs mod[tests]/fn[a_read_through_a_symlink_leaving_the_project_returns_an_error_to_the_model]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[a_read_through_a_symlink_leaving_the_project_returns_an_error_to_the_model]
  • Kind: fn
  • src/authoring/mod.rs:2105–2136
    // {test}`requirements.authoring.read_denial`
    #[cfg(unix)]
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[tokio::test]
    async fn a_read_through_a_symlink_leaving_the_project_returns_an_error_to_the_model() {
        let project = inputs::tests::project();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("secret.rs"), "fn secret() {}\n").unwrap();
        std::os::unix::fs::symlink(
            outside.path().join("secret.rs"),
            project.path().join("src/escape.rs"),
        )
        .unwrap();
        let mut sources = AssessmentSources::prepare(project.path(), "requirements.ready").unwrap();
        let state = tempfile::tempdir().unwrap();
        let mut usage =
            UsageLog::start(state.path(), project.path(), &sources.subject_name).unwrap();
        let provider = ReadingProvider {
            read: json!({"file": "src/escape.rs", "line_start": 1}),
            requests: RefCell::default(),
        };
        let (_, evidence) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        // The denial went back to the model, naming the path and the reason,
        // and the assessment continued without recording the file.
        let requests = provider.requests.borrow();
        assert_eq!(requests.len(), 2);
        let delivered = requests[1].to_string();
        assert!(delivered.contains("src/escape.rs"), "{delivered}");
        assert!(delivered.contains("outside the project"), "{delivered}");
        assert!(!delivered.contains("fn secret"), "{delivered}");
        assert!(!evidence.to_string().contains("escape.rs"), "{evidence}");
    }
Input 5: outline src/authoring/pages.rs mod[tests]/fn[large_listings_and_outlines_page_whole_entries_in_order]
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    // {test}`requirements.authoring.result_pages`
    #[test]
    // {test}`requirements.authoring.file_discovery`
    fn large_listings_and_outlines_page_whole_entries_in_order() {
        let root = project();
        let names = (0..800)
            .map(|index| format!("src/file_with_a_rather_long_name_{index:04}.rs"))
            .collect::<Vec<_>>();
        for name in &names {
            fs::write(root.path().join(name), "fn f() {}\n").unwrap();
        }
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        let first =
            dispatch_paged(&sources, &mut pages, "list_files", &json!({"path":"src"})).unwrap();
        let delivered = all_pages(&mut pages, first);
        let mut listed = Vec::new();
        for page in &delivered {
            assert!(page.result.to_string().len() <= PAGE_LIMIT);
            assert!(page.inputs.is_empty());
            assert_eq!(page.result.as_object().unwrap().len(), 2, "{}", page.result);
            let entries = page.result["entries"].as_array().unwrap();
            assert_eq!(
                page.result["page"]["returned_entries"],
                entries.len() as u64
            );
            listed.extend(
                entries
                    .iter()
                    .map(|entry| entry["path"].as_str().unwrap().to_owned()),
            );
        }
        // Whole entries, in the listing's order, each once.
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(listed, sorted);
        // A page is filled before the next starts.
        let first = delivered[0].result.to_string().len();
        assert!(first > PAGE_LIMIT - 200, "{first}");

        // An outline pages its top-level nodes, each with its children.
        let mut source = String::new();
        for index in 0..600 {
            source.push_str(&format!("mod module_{index} {{\n    fn inner() {{}}\n}}\n"));
        }
        fs::write(root.path().join("src/lib.rs"), source).unwrap();
        let first = dispatch_paged(
            &sources,
            &mut pages,
            "outline",
            &json!({"file":"src/lib.rs"}),
        )
        .unwrap();
        let delivered = all_pages(&mut pages, first);
        let nodes = delivered
            .iter()
            .flat_map(|page| page.result["entries"].as_array().unwrap().clone())
            .collect::<Vec<_>>();
        assert_eq!(nodes.len(), 600);
        for (index, node) in nodes.iter().enumerate() {
            assert_eq!(node["name"], format!("module_{index}"));
            assert_eq!(node["children"].as_array().unwrap().len(), 1);
        }
    }
Input 6: outline src/authoring/tools.rs mod[tests]/fn[generated_evidence_is_excluded_from_reads_search_and_discovery]
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[test]
    fn generated_evidence_is_excluded_from_reads_search_and_discovery() {
        let root = project();
        fs::create_dir(root.path().join("evidence")).unwrap();
        fs::create_dir(root.path().join("src/evidence")).unwrap();
        fs::write(
            root.path().join("evidence/old.json"),
            "needle in a previous judgment\n",
        )
        .unwrap();
        fs::write(
            root.path().join("evidence/generated.rs"),
            "fn generated() {}\n",
        )
        .unwrap();
        fs::write(root.path().join("source.txt"), "needle in source\n").unwrap();
        fs::write(
            root.path().join("src/evidence/source.txt"),
            "needle in nested source\n",
        )
        .unwrap();
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(
                root.path().join("evidence"),
                root.path().join("old-output"),
            )
            .unwrap();
            std::os::unix::fs::symlink(
                root.path().join("evidence/old.json"),
                root.path().join("old.json"),
            )
            .unwrap();
        }
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle", "context":0}),
        )
        .unwrap();
        let files = matched(&search)
            .iter()
            .map(|input| input["file"].as_str().unwrap())
            .collect::<Vec<_>>();
        assert_eq!(files, vec!["source.txt", "src/evidence/source.txt"]);
        let structural = dispatch(
            &sources,
            "ast_grep",
            &json!({"language":"rust","rule":{"rule":{"kind":"function_item"}}}),
        )
        .unwrap();
        assert!(matched(&structural).is_empty(), "{:?}", structural.result);
        assert!(
            dispatch(
                &sources,
                "ast_grep",
                &json!({"language":"rust","rule":{"rule":{"kind":"function_item"}},"path":"evidence"}),
            )
            .err()
            .unwrap()
            .to_string()
            .contains("generated evidence")
        );
        let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
        assert!(listing.result.as_array().unwrap().iter().all(|entry| {
            !["evidence", "old-output", "old.json"].contains(&entry["path"].as_str().unwrap())
        }));
        for path in ["evidence/old.json", "./evidence/old.json"] {
            let error = dispatch(&sources, "habeas", &json!({"file":path, "line_start":1}))
                .err()
                .unwrap();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
            assert!(error.to_string().contains("evidence/old.json"), "{error}");
            assert!(error.to_string().contains("generated evidence"), "{error}");
            assert!(sources.recorded_inputs().is_empty());
        }
        for (name, arguments) in [
            (
                "habeas",
                json!({"file":"evidence/generated.rs", "item":"fn[generated]"}),
            ),
            ("list_files", json!({"path":"evidence"})),
            ("ripgrep", json!({"path":"evidence", "pattern":"needle"})),
            (
                "ast_grep",
                json!({"path":"evidence", "language":"rust","rule":{"rule":{"kind":"function_item"}}}),
            ),
        ] {
            let error = dispatch(&sources, name, &arguments).err().unwrap();
            let path = arguments["file"]
                .as_str()
                .or_else(|| arguments["path"].as_str())
                .unwrap();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
            assert!(error.to_string().contains(path), "{error}");
            assert!(error.to_string().contains("generated evidence"), "{error}");
            assert!(sources.recorded_inputs().is_empty());
        }
        #[cfg(unix)]
        {
            for path in ["old.json", "old-output/old.json"] {
                assert!(
                    dispatch(&sources, "habeas", &json!({"file":path, "line_start":1}))
                        .err()
                        .unwrap()
                        .to_string()
                        .contains("generated evidence")
                );
                assert!(
                    dispatch(
                        &sources,
                        "ripgrep",
                        &json!({"path":path, "pattern":"needle"})
                    )
                    .err()
                    .unwrap()
                    .to_string()
                    .contains("generated evidence")
                );
            }
            assert!(
                dispatch(&sources, "list_files", &json!({"path":"old-output"}))
                    .err()
                    .unwrap()
                    .to_string()
                    .contains("generated evidence")
            );
        }
    }
Input 7: outline src/authoring/tools.rs mod[tests]/fn[untracked_diagnostics_name_git_add_and_an_allow_rule]
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.read_denial.untracked`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[test]
    fn untracked_diagnostics_name_git_add_and_an_allow_rule() {
        let root = project();
        fs::write(root.path().join("tracked.txt"), "tracked\n").unwrap();
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        fs::create_dir(root.path().join("untracked-dir")).unwrap();
        fs::write(root.path().join("untracked-dir/file.rs"), "fn f() {}\n").unwrap();
        fs::write(root.path().join("untracked.rs"), "fn g() {}\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for (name, arguments) in [
            ("habeas", json!({"file": "untracked.rs", "line_start": 1})),
            ("list_files", json!({"path": "untracked-dir"})),
        ] {
            let error = dispatch(&sources, name, &arguments).err().unwrap();
            assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
            let message = error.to_string();
            assert!(message.contains("git add"), "{message}");
            assert!(message.contains("habeas.toml allow rule"), "{message}");
            let path = arguments["file"]
                .as_str()
                .or_else(|| arguments["path"].as_str())
                .unwrap();
            assert!(message.contains(path), "{message}");
        }
        // The harness neither stages nor permits the files itself.
        let status = std::process::Command::new("git")
            .args(["status", "--porcelain"])
            .current_dir(root.path())
            .output()
            .unwrap();
        let status = String::from_utf8(status.stdout).unwrap();
        assert!(status.contains("?? untracked-dir/"), "{status}");
        assert!(status.contains("?? untracked.rs"), "{status}");
        assert!(!root.path().join("habeas.toml").exists());
    }
Input 8: 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 9: outline src/authoring/tools.rs mod[tests]/fn[requests_for_book_or_target_output_are_ordinary_read_failures]
    // {test}`requirements.authoring.read_denial`
    // {test}`requirements.authoring.read_denial.build_output`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[test]
    fn requests_for_book_or_target_output_are_ordinary_read_failures() {
        let root = project();
        for (book, built) in [("", "book"), ("[build]\nbuild-dir = 'site'\n", "site")] {
            fs::write(
                root.path().join("book.toml"),
                format!("[book]\nsrc = 'md'\n{book}"),
            )
            .unwrap();
            for directory in [built, "target"] {
                fs::create_dir_all(root.path().join(directory).join("nested")).unwrap();
                fs::write(
                    root.path().join(directory).join("nested/page.html"),
                    "fn built_needle() {}\n",
                )
                .unwrap();
            }
            let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
            for directory in [built, "target"] {
                let file = format!("{directory}/nested/page.html");
                for (name, arguments) in [
                    ("habeas", json!({"file": file, "line_start": 1})),
                    ("habeas", json!({"file": file, "item": ""})),
                    ("outline", json!({"file": file})),
                    ("list_files", json!({"path": directory})),
                    ("ripgrep", json!({"pattern": "needle", "path": directory})),
                ] {
                    let error = dispatch(&sources, name, &arguments).err().unwrap();
                    assert_ne!(
                        error.kind(),
                        io::ErrorKind::PermissionDenied,
                        "{name} {arguments}: {error}"
                    );
                    assert!(
                        error.to_string().contains("holds build output")
                            && error.to_string().contains(
                                "the sources it is built from are elsewhere in the project"
                            ),
                        "{name} {arguments}: {error}"
                    );
                }
            }
        }
        // With a build-dir set, `book` is an ordinary project directory.
        fs::write(root.path().join("book/source.txt"), "plain\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        assert!(
            dispatch(
                &sources,
                "habeas",
                &json!({"file":"book/source.txt","line_start":1})
            )
            .is_ok()
        );
    }
Input 10: outline src/authoring/tools.rs mod[tests]/fn[descriptions_give_each_argument_and_the_result_form]
    // {test}`requirements.authoring.tool_descriptions.common_case`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[test]
    fn descriptions_give_each_argument_and_the_result_form() {
        for definition in definitions() {
            let name = definition["name"].as_str().unwrap();
            let description = definition["description"].as_str().unwrap();
            // At least a few sentences.
            assert!(
                description.matches(". ").count() >= 2,
                "{name}: {description}"
            );
            for argument in definition["parameters"]["properties"]
                .as_object()
                .unwrap()
                .keys()
            {
                assert!(
                    description.contains(argument.as_str()),
                    "{name} omits {argument}"
                );
            }
            let result = match name {
                "habeas" => "{input, definitions}",
                "list_files" => "{path, kind}",
                "outline" => "item selector",
                "ripgrep" | "ast_grep" => {
                    "{search_id, matches: [{tag, file, item, kind, lines: [{text, matched}]}]}"
                }
                "references" => "definition name, role, file, and item",
                "next_page" => "same shape",
                "github" => "state (open or closed), title, and body",
                "finish_search" => "{search_id, finished:true}",
                _ => continue,
            };
            assert!(
                description.contains(result),
                "{name} omits its result: {description}"
            );
            let phrases: &[&str] = match name {
                "list_files" => &[
                    "immediate files and directories",
                    "Use list_files for directory entries and outline for selectable nodes in one file",
                    "project-relative",
                    "default .",
                    "listed or read",
                    "not evidence inputs",
                ],
                "next_page" => &[
                    "following page",
                    "habeas (line-range form), list_files, outline, ripgrep, ast_grep, or references",
                    "same shape",
                    "token is the page's next value",
                    "opaque",
                    r#"{"token":"abc123"}"#,
                ],
                "github" => &[
                    "<owner>/<repo>#<number>",
                    "issue or pull request",
                    "one a {fixme} option line names",
                ],
                _ => &[],
            };
            for phrase in phrases {
                assert!(
                    description.contains(phrase),
                    "{name}: missing {phrase}: {description}"
                );
            }
        }
    }
Input 11: outline src/authoring/tools.rs mod[tests]/fn[only_results_with_redacted_text_carry_the_redaction_note]
    // {test}`requirements.authoring.redaction_notice`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[test]
    fn only_results_with_redacted_text_carry_the_redaction_note() {
        let root = project();
        let token = crate::redaction::tests::github_token();
        fs::write(
            root.path().join("src/lib.rs"),
            format!("fn client() -> &'static str {{\n    \"{token}\"\n}}\n\nfn plain() {{}}\n"),
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        let mut read = |arguments: Value| {
            dispatch_paged(&sources, &mut pages, "habeas", &arguments)
                .unwrap()
                .result
        };
        let redacted = read(json!({"file": "src/lib.rs", "item": "fn[client]"}));
        assert!(redacted.to_string().contains("[REDACTED:"), "{redacted}");
        assert_eq!(redacted["note"], REDACTION_NOTE);
        let plain = read(json!({"file": "src/lib.rs", "item": "fn[plain]"}));
        assert!(plain.get("note").is_none(), "{plain}");
        let search = dispatch_paged(
            &sources,
            &mut pages,
            "ripgrep",
            &json!({"pattern": "client", "path": "src/lib.rs"}),
        )
        .unwrap()
        .result;
        assert_eq!(search["note"], REDACTION_NOTE, "{search}");
        // Source that itself contains the marker text was not redacted.
        fs::write(
            root.path().join("src/notes.rs"),
            "// Secrets show as [REDACTED:kind] in tool output.\nfn notes() {}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let literal = dispatch_paged(
            &sources,
            &mut ResultPages::default(),
            "habeas",
            &json!({"file": "src/notes.rs", "item": "fn[notes]"}),
        )
        .unwrap()
        .result;
        assert!(literal.to_string().contains("[REDACTED:kind]"), "{literal}");
        assert!(literal.get("note").is_none(), "{literal}");
        // So is requirement text that contains it, which names no file.
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\nSecrets MUST read [REDACTED:kind].\n:::\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let requirement = dispatch_paged(
            &sources,
            &mut ResultPages::default(),
            "habeas",
            &json!({"requirements": "requirements.ready"}),
        )
        .unwrap()
        .result;
        assert!(
            requirement.to_string().contains("[REDACTED:kind]"),
            "{requirement}"
        );
        assert!(requirement.get("note").is_none(), "{requirement}");
        fs::write(
            root.path().join("md/requirements.md"),
            format!(":::{{req}} ready\nThe credential {token} MUST be private.\n:::\n"),
        )
        .unwrap();
        fs::write(
            root.path().join("md/terms.md"),
            format!(":::{{definition}} secret\n:phrase: secret\nA credential {token}.\n:::\n"),
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for args in [
            json!({"requirements":"requirements.ready"}),
            json!({"definition":"terms.secret"}),
        ] {
            let result = dispatch(&sources, "habeas", &args).unwrap().result;
            assert!(!result.to_string().contains(&token));
            assert!(result.to_string().contains("[REDACTED:"));
            assert_eq!(result["note"], REDACTION_NOTE);
        }
    }
Input 12: outline src/authoring/tools.rs mod[tests]/fn[descriptions_leave_paging_policy_redaction_and_failures_to_results]
    // {test}`requirements.authoring.result_pages`
    // {test}`requirements.authoring.tool_descriptions.special_cases`
    #[test]
    fn descriptions_leave_paging_policy_redaction_and_failures_to_results() {
        let definitions = definitions();
        let next = definitions
            .iter()
            .find(|definition| definition["name"] == "next_page")
            .unwrap();
        assert_eq!(
            next["parameters"],
            json!({"type":"object","properties":{"token":{"type":"string"}},"required":["token"],"additionalProperties":false})
        );
        for definition in &definitions {
            let name = definition["name"].as_str().unwrap();
            let description = definition["description"].as_str().unwrap().to_lowercase();
            for special in [
                "kib",
                "returned in pages",
                "redact",
                "credential",
                "denied",
                "disallow",
                "habeas.toml",
                "aborts",
                "untracked",
                "build output",
                "outside the project",
                "tool error",
                "policy",
                "ignore rules",
                "exclusion",
                "permitted",
            ] {
                assert!(
                    !description.contains(special),
                    "{name} explains {special:?}: {description}"
                );
            }
        }
    }

Other sources

Input 1: requirements selection requirements.authoring.tool_descriptions.special_cases
:::{req} tool_descriptions.special_cases
Model tool descriptions SHOULD NOT explain cases the model meets only
occasionally, such as access policy, excluded or build-output paths, redaction,
paging, and failures, and the harness SHOULD explain each of these where it
occurs: in the tool error, or in a note in the result it affects. The model reads
every description on every assessment, so explaining rare cases there costs
attention on every review for a case most never meet, and access-policy wording
in particular can steer its reasoning away from the review. A tool whose purpose
is one of these cases, such as `next_page`, explains it in its description.
:::
Input 14: outline src/authoring/pages.rs mod[tests]/fn[all_pages]
    /// Follows a paged result to its end, checking each page's size and
    /// counts, and returns every page's delivery.
    fn all_pages(pages: &mut ResultPages, first: ToolDelivery) -> Vec<ToolDelivery> {
        let page = &first.result["page"];
        let total = page["total_entries"].as_u64().unwrap();
        let mut delivered = vec![first];
        loop {
            let page = delivered.last().unwrap().result["page"].clone();
            assert_eq!(page["total_entries"], total);
            assert!(page["returned_entries"].as_u64().unwrap() > 0);
            let Some(token) = page["next"].as_str() else {
                assert!(page["next"].is_null());
                // The last page needs no note.
                assert!(page.get("note").is_none(), "{page}");
                break;
            };
            // A page with more after it says how to continue.
            assert_eq!(page["note"], PAGE_NOTE);
            delivered.push(pages.next_page(token).unwrap());
        }
        let returned: u64 = delivered
            .iter()
            .map(|page| page.result["page"]["returned_entries"].as_u64().unwrap())
            .sum();
        assert_eq!(returned, total);
        assert!(delivered.len() > 1);
        delivered
    }
Input 15: outline src/authoring/pages.rs mod[tests]/fn[redacted_results_reserve_space_for_the_note_on_every_delivered_page]
  • File: src/authoring/pages.rs
  • Selector: mod[tests]/fn[redacted_results_reserve_space_for_the_note_on_every_delivered_page]
  • Kind: fn
  • src/authoring/pages.rs:438–511
    // {test}`requirements.authoring.result_pages`
    #[test]
    fn redacted_results_reserve_space_for_the_note_on_every_delivered_page() {
        let root = project();
        let token = crate::redaction::tests::github_token();
        let read = |count: usize, padding: usize| {
            let source = (0..count)
                .map(|index| {
                    format!(
                        "fn item_{index}() {{ let key = \"{token}\"; let padding = \"{}\"; }}\n",
                        "x".repeat(padding)
                    )
                })
                .collect::<String>();
            fs::write(root.path().join("src/secret.rs"), source).unwrap();
            let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
            let mut pages = ResultPages::default();
            let first = dispatch_paged(
                &sources,
                &mut pages,
                "habeas",
                &json!({"file":"src/secret.rs","line_start":1}),
            )
            .unwrap();
            let mut delivered = vec![first];
            while let Some(next) = delivered.last().unwrap().result["page"]["next"].as_str() {
                let next = next.to_owned();
                delivered.push(
                    dispatch_paged(&sources, &mut pages, "next_page", &json!({"token":next}))
                        .unwrap(),
                );
            }
            for page in &delivered {
                let encoded = page.result.to_string();
                assert!(encoded.len() <= PAGE_LIMIT, "{}", encoded.len());
                assert_eq!(page.result["note"], super::super::tools::REDACTION_NOTE);
                // Continuation guidance is inside `page`; the redaction
                // explanation is a separate note on the enclosing result.
                if page.result["page"]["next"].is_string() {
                    assert_eq!(page.result["page"]["note"], PAGE_NOTE);
                } else {
                    assert!(page.result["page"].get("note").is_none());
                }
                assert!(!encoded.contains(&token));
                assert!(encoded.contains("[REDACTED:"));
            }
            delivered
        };
        let baseline = read(4, 1);
        assert_eq!(baseline.len(), 1);
        assert!(baseline[0].result.get("page").is_none());
        let mut without_note = baseline[0].result.clone();
        without_note.as_object_mut().unwrap().remove("note");
        let size = without_note.to_string().len();
        let padding = 1 + (PAGE_LIMIT - 5 - size) / 4;
        // The raw result fits; its redaction note pushes it over the limit.
        assert!(size + 4 * (padding - 1) <= PAGE_LIMIT);
        assert!(size + 4 * (padding - 1) + super::super::tools::REDACTION_NOTE.len() > PAGE_LIMIT);
        for (count, padding) in [(4, padding), (256, 256)] {
            let pages = read(count, padding);
            assert!(pages.len() > 1);
            let items = pages
                .iter()
                .flat_map(|page| page.result["inputs"].as_array().unwrap())
                .map(|input| input["item"].as_str().unwrap().to_owned())
                .collect::<Vec<_>>();
            assert_eq!(
                items,
                (0..count)
                    .map(|index| format!("fn[item_{index}]"))
                    .collect::<Vec<_>>()
            );
        }
    }