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

Requirements index · View definition

evidence Valid

Requirement

No prompt, tool result, or tool error the harness gives the model MUST state a line number or line range of a project source, except within source text it quotes and where a tool error repeats a line number the model supplied. The harness MUST identify a source location by file and outline selector under cite requirements.references.outline_selectors instead.

Rationale

Obligations derived from requirements.authoring.no_line_numbers

  1. No tool result states a line number or range of a project source, except inside quoted source text.
  2. No tool error states one, except where it repeats a number the model supplied.
  3. No prompt states one.
  4. Locations are identified by file and outline selector.

Tool results

  • habeas reads: tools.rs#mod[tests]/fn[reading_records_only_delivered_sources_and_their_terms] asserts that item-form and line-range-form results have no start or end line fields, and that recorded inputs carry only the file, selector and hash.
  • habeas line-range reads: tools.rs#mod[tests]/fn[line_range_reads_record_the_innermost_covering_nodes] asserts no line fields on Rust nodes or plain-text line@ nodes, and that items are selectors such as mod[inner]/fn[second].
  • ripgrep: tools.rs#mod[tests]/fn[search_merges_context_windows_and_respects_ignore_rules] asserts no start-line field on entries and no line field on the lines. tools.rs#mod[tests]/fn[separate_windows_in_one_node_are_divided_by_an_elision_line] asserts the exact line objects, which are text and matched only, with an elision marker between windows.
  • ast_grep shares the SearchNodes::entries result shape with ripgrep, so those assertions cover it.
  • outline: tools.rs#mod[tests]/fn[outline_lists_nested_nodes_without_text_or_inputs] asserts the exact JSON of an outline result and that plain-text entries have no start-line field.
  • references: tools.rs#mod[tests]/fn[references_list_names_and_flattened_sites_without_recording_inputs] asserts the exact site objects, which are name, role, file and item only.

Prompts

  • Mandatory inputs: inputs.rs#mod[tests]/fn[anchored_files_contribute_root_node_inputs] asserts the exact JSON of the inputs, which are file, item, hash, kind and text with no line fields.
  • Site prompt: mod.rs#mod[tests]/fn[site_reviews_use_their_prompt_and_record_applies_and_the_site] compares the site subject message with the expected message built from the approved text. The query matches in it carry kind, query and item only. sites.rs#mod[tests]/fn[sites_are_the_innermost_nodes_of_site_matches_and_violations_within_them] asserts that the model-facing matches_value() of a violation has no lines.
  • Submission-tool descriptions: mod.rs#mod[submission_description_tests]/fn[submission_descriptions_explain_arguments_and_successful_completion] asserts they tell the model to give outline selectors and never line numbers.

Tool errors

  • line_numbers.rs#mod[tests]/fn[tool_errors_drop_the_source_line_of_a_parse_error] covers without_source_lines. It checks that:
    • parse positions are removed;
    • file:N: and secondary at <file>:N forms become file#;
    • the TOML and YAML at line N, column M forms are removed;
    • the model-supplied single-line and range forms of the out-of-range error are preserved unchanged.
  • mod.rs#mod[tests]/fn[tool_errors_give_the_model_no_line_numbers_it_did_not_supply] runs the whole flow:
    • A past-EOF read returns an error that repeats the supplied start number.
    • A parse error from a broken file contains a line position at the dispatch layer, but the request delivered to the model contains cannot parse and no such position.
  • I read the read_lines error message in inputs.rs. It states only the supplied range, so the starts_with assertion in that test is enough.

Judgment Every clause of the requirement has a test with a real assertion. That covers results, errors including the supplied-number exception, and prompts. The selector-instead clause is covered by the item and selector assertions above. I found no plausible violating behavior the tests would accept.

Inputs

Implementation

Input 15: outline src/authoring/line_numbers.rs (whole file)
//! Rejecting rationales that cite line numbers, with one chance to resubmit.

use std::sync::LazyLock;

use regex::Regex;
use serde_json::Value;

/// The forms of a line-number citation: a file path followed by `:` and a
/// digit, `line` or `lines` followed by a number, or a parenthesized number
/// range.
// {impl}`requirements.authoring.line_numbers.detection`
static LINE_NUMBERS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        // A file path's extension starts with a letter, so a version
        // such as `0.1:9` is not one.
        r"(?:[\w.-]+/)*[\w-]+\.[A-Za-z][A-Za-z0-9]*:\d",
        r"|(?i:\blines?)\s+\d",
        r"|\(\s*\d+\s*[-–]\s*\d+\s*\)",
    ))
    .expect("line-number pattern")
});

/// The first text in `rationale` that cites line numbers, if any.
// {impl}`requirements.authoring.line_numbers.detection`
pub(crate) fn cited(rationale: &str) -> Option<&str> {
    LINE_NUMBERS.find(rationale).map(|found| found.as_str())
}

/// The position a source parse error states: `line N: `, or `at line N`
/// with an optional column, as a TOML or YAML parser reports it.
static PARSE_POSITION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\bline \d+: |,? ?\bat line \d+(?:,? column \d+)?").expect("parse position pattern")
});

/// A source position elsewhere in the text, such as `first declared at
/// md/rules.md:3`: a file path with an extension, then `:` and a line.
static PATH_POSITION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"((?:[\w.-]+/)*[\w-]+\.[A-Za-z][A-Za-z0-9]*):\d+(?::\d+)?\b")
        .expect("path position pattern")
});

/// The position a diagnostic gives as `file:N: `, such as a malformed query.
static FILE_POSITION: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\S+?):\d+: ").expect("file position pattern"));

/// A file-level diagnostic uses the empty outline selector (the root node).
static FILE_DIAGNOSTIC: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"((?:[\w.-]+/)*[\w-]+\.[A-Za-z][A-Za-z0-9]*): ").expect("file diagnostic pattern")
});

/// A tool error as the model receives it: without the source lines a parse
/// error or diagnostic names, which the model did not supply. Such locations
/// use the empty outline selector, `file#`, because malformed sources may not
/// have a parseable inner node.
// {impl}`requirements.authoring.no_line_numbers`
pub(crate) fn without_source_lines(error: &str) -> String {
    let error = PARSE_POSITION.replace_all(error, "");
    let error = FILE_DIAGNOSTIC.replace_all(&error, "$1#: ");
    let error = FILE_POSITION.replace_all(&error, "$1#: ");
    // A line or range the model supplied, `file:N` or `file:N-M`, is
    // repeated as it gave it.
    PATH_POSITION
        .replace_all(&error, |captures: &regex::Captures| {
            let whole = captures.get(0).expect("match");
            let rest = &error[whole.end()..];
            let rest = rest.strip_prefix('-').map_or(rest, |rest| {
                rest.trim_start_matches(|c: char| c.is_ascii_digit())
            });
            if rest.starts_with(" is not an inclusive range") {
                whole.as_str().to_owned()
            } else {
                format!("{}#", &captures[1])
            }
        })
        .into_owned()
}

/// The rationale of a submission's arguments.
// {cite}`habeas:util`
pub(crate) fn rationale(arguments: &Value) -> &str {
    arguments
        .get("rationale")
        .and_then(Value::as_str)
        .unwrap_or_default()
}

/// The state of an assessment's one allowed rejection.
#[derive(Default)]
pub(crate) struct Rejection {
    /// The UUID the rejection gave and the rejected submission's arguments.
    rejected: Option<(String, Value)>,
}

/// What to do with a submission that is otherwise valid.
pub(crate) enum Outcome {
    /// Accept the submission.
    Accept,
    /// Reject the submission with this tool result and continue.
    Reject(String),
    /// Fail the assessment with this error.
    Fail(String),
}

impl Rejection {
    /// The submission to accept in place of `arguments`: the rejected one
    /// when `arguments` gives exactly the UUID its rejection returned.
    // {impl}`requirements.authoring.line_numbers.resubmission`
    pub(crate) fn resubmitted(&self, arguments: &Value) -> Option<Value> {
        let (uuid, rejected) = self.rejected.as_ref()?;
        (rationale(arguments) == uuid).then(|| rejected.clone())
    }

    /// Decides an otherwise valid submission: accepted unless its rationale
    /// cites line numbers, rejected once with a fresh UUID, and failed after
    /// that.
    // {impl}`requirements.authoring.line_numbers.rejection`
    // {impl}`requirements.authoring.line_numbers.resubmission`
    pub(crate) fn decide(&mut self, submit: &str, arguments: &Value, guidance: &str) -> Outcome {
        let Some(found) = cited(rationale(arguments)).map(str::to_owned) else {
            return Outcome::Accept;
        };
        if self.rejected.is_some() {
            return Outcome::Fail(format!(
                "{submit} rationale cites line numbers ({found:?}) after a rejection for citing them"
            ));
        }
        let uuid = uuid::Uuid::new_v4().to_string();
        self.rejected = Some((uuid.clone(), arguments.clone()));
        Outcome::Reject(format!(
            "Not accepted: the rationale cites line numbers ({found:?}). Line numbers \
             change whenever nearby code changes, so cite locations as the judgment rules \
             say:\n\n{guidance}\n\nThe detector also matches numeric locations in quoted \
             diagnostics and illustrative examples, even when they are not source \
             citations. Remove those numbers or replace them with placeholders throughout \
             the rationale, including quoted text. Do not repeat the matched text while \
             explaining this rejection. Call {submit} once more, either with a rationale that \
             gives no line numbers, or with rationale set to exactly {uuid} to keep the \
             submission you just made as it was. Another rationale that cites line numbers \
             fails the assessment."
        ))
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    // {test}`requirements.authoring.line_numbers.detection`
    #[test]
    fn line_numbers_are_detected_in_each_form() {
        for text in [
            "see src/lib.rs:12",
            "`tests/cli.rs:3-9` covers it",
            "Cargo.toml:4",
            "on line 7",
            "Lines 10 to 12",
            "`check` (12–30) handles it",
            "`check` (12-30)",
            "( 3 - 4 )",
        ] {
            assert!(cited(text).is_some(), "{text}");
        }
        for text in [
            "`src/lib.rs#fn[check]` covers it",
            "`src/lib.rs` and `requirements.ci.errors`",
            "the deadline 7 days",
            "inline 3 items",
            "two lines of output",
            "(see the example)",
            "a ratio of 3:4",
            "version 0.1:9",
            "at 12.30:15",
            "(1)",
        ] {
            assert_eq!(cited(text), None, "{text}");
        }
        assert_eq!(cited("at src/a.rs:5 and line 3"), Some("src/a.rs:5"));
    }

    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn tool_errors_drop_the_source_line_of_a_parse_error() {
        assert_eq!(
            without_source_lines("src/a.rs: cannot parse Rust source: line 3: unexpected token"),
            "src/a.rs#: cannot parse Rust source: unexpected token"
        );
        // Both forms `read_lines` reports keep the numbers the model gave.
        for requested in ["9", "3-9"] {
            let error = format!(
                "src/lib.rs:{requested} is not an inclusive range within the file; read it by selector instead"
            );
            assert_eq!(without_source_lines(&error), error);
        }
        assert_eq!(
            without_source_lines("md/rules.md:12: query checkers is not closed"),
            "md/rules.md#: query checkers is not closed"
        );
        assert_eq!(
            without_source_lines("md/b.md:4: duplicate requirement r; first declared at md/a.md:3"),
            "md/b.md#: duplicate requirement r; first declared at md/a.md#"
        );
        assert_eq!(
            without_source_lines(
                "md/rules.md: query q: the yaml block must be a mapping: invalid type at line 2, column 5"
            ),
            "md/rules.md#: query q: the yaml block must be a mapping: invalid type"
        );
        assert_eq!(
            without_source_lines("habeas.toml: invalid TOML syntax at line 3, column 1"),
            "habeas.toml#: invalid TOML syntax"
        );
    }

    // {test}`requirements.authoring.line_numbers.rejection`
    // {test}`requirements.authoring.line_numbers.resubmission`
    #[test]
    fn a_rejection_gives_a_uuid_that_keeps_the_rejected_submission() {
        let mut rejection = Rejection::default();
        let clean = json!({"determination": true, "rationale": "`src/lib.rs#fn[a]` is fine."});
        assert!(matches!(
            rejection.decide("submit_judgment", &clean, "- guidance"),
            Outcome::Accept
        ));
        let cited = json!({"determination": false, "rationale": "src/lib.rs:3 panics."});
        assert!(rejection.resubmitted(&cited).is_none());
        let Outcome::Reject(message) = rejection.decide("submit_judgment", &cited, "- guidance")
        else {
            panic!("expected a rejection");
        };
        assert!(message.contains("\"src/lib.rs:3\""), "{message}");
        assert!(message.contains("- guidance"), "{message}");
        let uuid = message
            .split_whitespace()
            .find_map(|word| uuid::Uuid::parse_str(word).ok())
            .expect("a UUID")
            .to_string();
        assert!(message.contains(&format!("Call submit_judgment once more, either with a rationale that gives no line numbers, or with rationale set to exactly {uuid} to keep the submission you just made as it was.")), "{message}");
        // Exactly the UUID keeps the rejected submission unchanged.
        let keep = json!({"determination": true, "rationale": uuid});
        assert_eq!(rejection.resubmitted(&keep), Some(cited.clone()));
        let other = json!({"determination": true, "rationale": format!("{uuid} ")});
        assert_eq!(rejection.resubmitted(&other), None);
        // A clean resubmission is accepted; another citing one fails.
        assert!(matches!(
            rejection.decide("submit_judgment", &clean, "- guidance"),
            Outcome::Accept
        ));
        assert!(matches!(
            rejection.decide("submit_judgment", &cited, "- guidance"),
            Outcome::Fail(message) if message.contains("after a rejection")
        ));
        // Each rejection gives a fresh UUID.
        let mut again = Rejection::default();
        let Outcome::Reject(second) = again.decide(
            "submit_judgment",
            &json!({"rationale": "line 4"}),
            "- guidance",
        ) else {
            panic!("expected a rejection");
        };
        assert!(!second.contains(&uuid));
    }
}
Input 17: outline src/inputs.rs impl[InputSelector]/fn[to_model_input]
    /// The input as shown to the model: the recorded input plus, for an
    /// outline input, the node's kind and source text, without line numbers.
    // {impl}`requirements.authoring.mandatory_inputs`
    // {impl}`requirements.authoring.no_line_numbers`
    pub(crate) fn to_model_input(&self, resolved: &ResolvedInput) -> Value {
        let mut input = self.to_input(resolved);
        if let (Self::Outline { .. }, Some(node), Some(object)) =
            (self, &resolved.node, input.as_object_mut())
        {
            object.insert("kind".to_owned(), json!(node.kind));
            object.insert("text".to_owned(), json!(resolved.text));
        }
        input
    }
Input 18: outline src/authoring/inputs.rs impl[AssessmentSources]/fn[read_lines]
    /// Reads the innermost outline nodes covering an inclusive line range,
    /// as model-facing outline inputs. With `comments`, comment lines select
    /// their comments' owners.
    // {impl}`requirements.ci.outline_inputs`
    pub(crate) fn read_lines(
        &self,
        file: &str,
        line_start: usize,
        line_end: Option<usize>,
        comments: bool,
    ) -> io::Result<Vec<Value>> {
        let parsed = self.parse_file(file)?;
        let parsed = parsed
            .as_ref()
            .as_ref()
            .map_err(|error| io::Error::other(error.clone()))?;
        let count = parsed.source.lines().count();
        // The error repeats only the numbers the model supplied.
        // {impl}`requirements.authoring.no_line_numbers`
        let requested = match line_end {
            Some(line_end) => format!("{line_start}-{line_end}"),
            None => line_start.to_string(),
        };
        let line_end = line_end.unwrap_or(count);
        if line_start == 0 || line_end < line_start || line_end > count || line_start > count {
            return Err(io::Error::other(format!(
                "{file}:{requested} is not an inclusive range within the file; read it by selector instead"
            )));
        }
        parsed
            .nodes_for_range(line_start, line_end, comments)
            .into_iter()
            .map(|index| {
                self.read_selector(&InputSelector::Outline {
                    file: file.to_owned(),
                    item: parsed.outline.nodes[index].selector.clone(),
                })
            })
            .collect()
    }

Tests

Input 3: outline src/authoring/inputs.rs mod[tests]/fn[anchored_files_contribute_root_node_inputs]
    // {test}`requirements.references.anchors`
    // {test}`requirements.references.authoring_inputs`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring_input`
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn anchored_files_contribute_root_node_inputs() {
        let root = project();
        fs::create_dir_all(root.path().join("skills")).unwrap();
        fs::write(root.path().join("skills/ready.md"), "# Skill\nBe ready.\n").unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\n:impl: skills/ready.md\n:test: skills/ready.md\nThe project MUST be ready.\n\nKeep the whole body.\n:impl: this is body text\n:::\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let inputs = sources.mandatory_inputs();
        let hash =
            crate::inputs::outline_input(root.path(), "skills/ready.md", "").unwrap()["hash"]
                .clone();
        assert_eq!(
            inputs,
            &[
                json!({
                    "requirements": "requirements.ready",
                    "matches": ["requirements.ready"],
                    "text": [":::{req} ready", "The project MUST be ready.", "", "Keep the whole body.", ":impl: this is body text", ":::"]
                }),
                json!({
                    "file": "skills/ready.md",
                    "item": "",
                    "hash": hash,
                    "kind": "file",
                    "text": ["# Skill", "Be ready."]
                }),
            ]
        );
        assert_eq!(
            sources.subject_text,
            "The project MUST be ready.\n\nKeep the whole body.\n:impl: this is body text"
        );
    }
Input 4: outline src/authoring/line_numbers.rs mod[tests]/fn[tool_errors_drop_the_source_line_of_a_parse_error]
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn tool_errors_drop_the_source_line_of_a_parse_error() {
        assert_eq!(
            without_source_lines("src/a.rs: cannot parse Rust source: line 3: unexpected token"),
            "src/a.rs#: cannot parse Rust source: unexpected token"
        );
        // Both forms `read_lines` reports keep the numbers the model gave.
        for requested in ["9", "3-9"] {
            let error = format!(
                "src/lib.rs:{requested} is not an inclusive range within the file; read it by selector instead"
            );
            assert_eq!(without_source_lines(&error), error);
        }
        assert_eq!(
            without_source_lines("md/rules.md:12: query checkers is not closed"),
            "md/rules.md#: query checkers is not closed"
        );
        assert_eq!(
            without_source_lines("md/b.md:4: duplicate requirement r; first declared at md/a.md:3"),
            "md/b.md#: duplicate requirement r; first declared at md/a.md#"
        );
        assert_eq!(
            without_source_lines(
                "md/rules.md: query q: the yaml block must be a mapping: invalid type at line 2, column 5"
            ),
            "md/rules.md#: query q: the yaml block must be a mapping: invalid type"
        );
        assert_eq!(
            without_source_lines("habeas.toml: invalid TOML syntax at line 3, column 1"),
            "habeas.toml#: invalid TOML syntax"
        );
    }
Input 5: outline src/authoring/mod.rs mod[submission_description_tests]/fn[submission_descriptions_explain_arguments_and_successful_completion]
  • File: src/authoring/mod.rs
  • Selector: mod[submission_description_tests]/fn[submission_descriptions_explain_arguments_and_successful_completion]
  • Kind: fn
  • src/authoring/mod.rs:1178–1225
    // {test}`requirements.authoring.tool_descriptions.common_case`
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn submission_descriptions_explain_arguments_and_successful_completion() {
        for tool in ["submit_judgment", "submit_verification"] {
            for site in [false, true] {
                let definitions = super::tool_definitions_with(tool, site).unwrap();
                let value = serde_json::to_value(definitions.last().unwrap()).unwrap();
                let description = value["description"].as_str().unwrap();
                for argument in value["parameters"]["properties"]
                    .as_object()
                    .unwrap()
                    .keys()
                {
                    assert!(
                        description.contains(argument),
                        "{tool} omits {argument}: {description}"
                    );
                }
                for phrase in [
                    "until one submission is accepted",
                    "source tool",
                    "nonempty explanation",
                    "outline selectors",
                    "never line numbers",
                    "A successful submission ends",
                    "owner/repo#123",
                ] {
                    assert!(
                        description.contains(phrase),
                        "{tool} omits {phrase}: {description}"
                    );
                }
                if tool == "submit_judgment" {
                    assert!(
                        description.contains("true when the subject meets its review criteria")
                    );
                    assert!(description.contains("false when it has an unacknowledged gap"));
                    assert!(description.contains(r#"{"FIXME":["owner/repo#123"]}"#));
                } else {
                    assert!(description.contains("real says whether the alleged gap is real"));
                    assert!(description.contains("acknowledged says whether"));
                    assert!(description.contains("or [] when none apply"));
                }
                assert_eq!(description.contains("applies says whether"), site);
            }
        }
    }
Input 6: outline src/authoring/mod.rs mod[tests]/fn[tool_errors_give_the_model_no_line_numbers_it_did_not_supply]
    // {test}`requirements.authoring.no_line_numbers`
    #[tokio::test]
    async fn tool_errors_give_the_model_no_line_numbers_it_did_not_supply() {
        let project = inputs::tests::project();
        fs::write(project.path().join("src/lib.rs"), "fn work() {}\n").unwrap();
        fs::write(
            project.path().join("src/broken.rs"),
            "fn ok() {}\nfn broken( {\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(project.path(), "requirements.ready").unwrap();
        // A range past the end repeats only the supplied start line.
        let past = tools::dispatch(
            &sources,
            "habeas",
            &json!({"file": "src/lib.rs", "line_start": 99}),
        )
        .err()
        .unwrap()
        .to_string();
        assert!(
            past.starts_with("src/lib.rs:99 is not an inclusive range"),
            "{past}"
        );
        // A parse error names its line, but the model receives it without.
        let read = json!({"file": "src/broken.rs", "item": ""});
        let parse = tools::dispatch(&sources, "habeas", &read)
            .err()
            .unwrap()
            .to_string();
        assert!(
            regex::Regex::new(r"line \d+: ").unwrap().is_match(&parse),
            "{parse}"
        );
        let mut sources = sources;
        let state = tempfile::tempdir().unwrap();
        let mut usage =
            UsageLog::start(state.path(), project.path(), &sources.subject_name).unwrap();
        let provider = ReadingProvider {
            read,
            requests: RefCell::default(),
        };
        assess(&provider, &mut sources, &mut usage).await.unwrap();
        let delivered = provider.requests.borrow()[1].to_string();
        assert!(delivered.contains("cannot parse"), "{delivered}");
        assert!(
            !regex::Regex::new(r"line \d+: ")
                .unwrap()
                .is_match(&delivered),
            "{delivered}"
        );
    }
Input 7: outline src/authoring/mod.rs mod[tests]/fn[site_reviews_use_their_prompt_and_record_applies_and_the_site]
    // {test}`requirements.authoring.site_prompt`
    // {test}`requirements.authoring.habeas_background`
    // {test}`requirements.references.site_review`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring.judgment_rules`
    // {test}`requirements.authoring.no_line_numbers`
    #[tokio::test]
    async fn site_reviews_use_their_prompt_and_record_applies_and_the_site() {
        let project = crate::sites::tests::project(
            crate::sites::tests::RULE,
            &crate::sites::tests::SOURCE.replace(
                "fn check_two() {}",
                "fn check_two() {\n    // :::{fixme} requirements.rule\n    // Panics.\n    // :::\n}",
            ),
        );
        let root = project.path();
        let declaration = crate::sites::tests::RULE.replace("Each checker MUST report problems instead of panicking.", "Each checker MUST report problems instead of panicking. {cite}`requirements.other` {term}`terms.value`");
        fs::write(
            root.join("md/requirements.md"),
            format!("{declaration}\n:::{{req}} other\nOther MUST hold.\n:::\n"),
        )
        .unwrap();
        fs::write(
            root.join("md/terms.md"),
            ":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
        )
        .unwrap();
        let subject = AuthoringSubject::parse("sites:requirements.rule/src/lib.rs#fn[check_two]");
        assert_eq!(
            subject.evidence_path(root),
            root.join("evidence/sites/requirements.rule/src/lib.rs/fn[check_two].json")
        );
        let mut sources = subject.sources(root).unwrap();
        let mandatory = sources.mandatory_inputs().to_vec();
        assert_eq!(mandatory[0]["file"], "src/lib.rs");
        assert_eq!(mandatory[0]["item"], "fn[check_two]");
        assert_eq!(mandatory[1]["requirements"], "requirements.rule");
        assert_eq!(mandatory.len(), 4, "{mandatory:#?}");
        assert!(
            mandatory
                .iter()
                .any(|input| input["requirements"] == "requirements.other")
        );
        assert!(
            mandatory
                .iter()
                .any(|input| input["definition"] == "terms.value")
        );

        // The subject message names the requirement, the site's file and
        // selector, and each query match with its kind, name and lines.
        let matches =
            json!([{"kind": "sites", "query": "checkers", "item": "fn[check_two]"}]).to_string();
        let mandatory_inputs =
            serde_json::to_string_pretty(&sources.model_mandatory_inputs()).unwrap();
        let expected_subject = fill(
            approved_text("site_prompt", 1),
            &[
                ("requirement_name", "requirements.rule"),
                ("site_file", "src/lib.rs"),
                ("site_selector", "fn[check_two]"),
                ("matches", &matches),
                ("mandatory_inputs", &mandatory_inputs),
            ],
        );
        let initial = initial_prompt(&sources).unwrap();
        assert_eq!(initial.subject, expected_subject);
        assert!(
            initial
                .subject
                .starts_with(&format!(
                    "# Subject\n\nSite under review: src/lib.rs fn[check_two]\nRequirement: requirements.rule\nMatches: {matches}\n"
                )),
            "{}",
            initial.subject
        );

        let state = tempfile::tempdir().unwrap();
        let mut usage = UsageLog::start(state.path(), root, &subject.label()).unwrap();
        let provider = RecordingProvider::new(vec![(
            "submit_judgment",
            json!({"applies": true, "determination": {"FIXME": ["Panics."]}, "rationale": "Acknowledged."}),
        )]);
        let (_, record) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        let prompts = provider.prompts();
        let (prompt, tools) = &prompts[0];
        let prompt = serde_json::from_str::<Value>(prompt).unwrap();
        let text = prompt.to_string();
        assert!(
            text.contains(
                serde_json::to_string(&initial.subject)
                    .unwrap()
                    .trim_matches('"')
            ),
            "the subject message reaches the model"
        );
        let heading = approved_text("site_prompt", 0)
            .split("\n\n# Background")
            .next()
            .unwrap();
        assert!(
            text.contains(serde_json::to_string(heading).unwrap().trim_matches('"')),
            "{heading}\n{text}"
        );
        for block in [
            approved_text("habeas_background", 0),
            distributed_background(),
            approved_text("judgment_rules", 0),
        ] {
            assert!(
                text.contains(serde_json::to_string(block).unwrap().trim_matches('"')),
                "{block}"
            );
        }
        assert!(
            !text.contains(
                serde_json::to_string(approved_text("habeas_background", 1))
                    .unwrap()
                    .trim_matches('"')
            ),
            "the site prompt has no reference roles"
        );
        assert!(!text.contains("{{"), "{text}");
        assert!(tools.contains(&"submit_judgment".to_owned()));
        let expected: Vec<_> = tool_definitions_with("submit_judgment", false)
            .unwrap()
            .into_iter()
            .map(|tool| tool.name)
            .collect();
        assert_eq!(*tools, expected);
        let duplicate = json!({"applies":true,"determination":true,"rationale":"Covered."});
        let duplicate_provider = ScriptedProvider {
            turns: vec![vec![
                ("submit_judgment", duplicate.clone()),
                ("submit_judgment", duplicate),
            ]],
            requests: RefCell::default(),
        };
        let mut duplicate_sources = subject.sources(root).unwrap();
        assert!(
            assess(&duplicate_provider, &mut duplicate_sources, &mut usage)
                .await
                .unwrap_err()
                .to_string()
                .contains("exactly once")
        );
        let submit = provider.requests.borrow()[0]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .find(|tool| tool["name"] == "submit_judgment")
            .unwrap()
            .clone();
        assert_eq!(
            submit["parameters"]["required"],
            json!(["determination", "rationale", "applies"])
        );

        assert_eq!(record["requirement"], "requirements.rule");
        assert_eq!(record["file"], "src/lib.rs");
        assert_eq!(record["item"], "fn[check_two]");
        assert_eq!(record["queries"], json!(["checkers"]));
        assert_eq!(record["applies"], true);
        assert_eq!(
            record["fixmes"],
            json!([{"item": "fn[check_two]", "commentary": "Panics."}])
        );
        // The recorded review satisfies validation for its site.
        let path = subject.evidence_path(root);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, record.to_string()).unwrap();
        let errors = crate::validate_repository(root).unwrap().errors;
        let prefix = crate::sites::review_path("requirements.rule", "src/lib.rs", "fn[check_two]");
        assert!(
            !errors.iter().any(|error| error.starts_with(&prefix)),
            "{errors:#?}"
        );
    }
Input 8: outline src/authoring/tools.rs mod[tests]/fn[reading_records_only_delivered_sources_and_their_terms]
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.delivered_inputs`
    // {test}`requirements.definitions.authoring_inputs`
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn reading_records_only_delivered_sources_and_their_terms() {
        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!("// {}\nfn work() {{}}\n", role("term", "terms.value")),
        )
        .unwrap();
        let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let listing = dispatch(&sources, "list_files", &json!({"path":"src"})).unwrap();
        assert_eq!(listing.result, json!([{"path":"src/lib.rs","kind":"file"}]));
        assert!(listing.inputs.is_empty());
        let read = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","item":"fn[work]"}),
        )
        .unwrap();
        assert_eq!(read.inputs.len(), 2);
        assert_eq!(read.result["input"]["item"], "fn[work]");
        assert_eq!(read.result["input"]["kind"], "fn");
        // Results give the selector, never line numbers.
        assert!(read.result["input"].get("line_start").is_none());
        assert!(read.result["input"].get("line_end").is_none());
        assert_eq!(read.result["input"]["text"][1], "fn work() {}");
        assert_eq!(read.result["definitions"][0]["definition"], "terms.value");
        assert!(sources.recorded_inputs().is_empty());
        sources.record_inputs(&read.inputs);
        sources.record_inputs(&read.inputs);
        assert_eq!(sources.recorded_inputs().len(), 2);
        // Recorded outline inputs carry only the file, selector, and hash.
        assert_eq!(
            sources.recorded_inputs()[0],
            crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[work]").unwrap()
        );
        let eof = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":2}),
        )
        .unwrap();
        assert_eq!(eof.result["inputs"].as_array().unwrap().len(), 1);
        assert_eq!(eof.result["inputs"][0]["item"], "fn[work]");
        assert!(eof.result["inputs"][0].get("line_end").is_none());
        // A line-range read supplies the terminology of what it delivers.
        let fresh = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let lines = dispatch(
            &fresh,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":1}),
        )
        .unwrap();
        assert_eq!(lines.result["definitions"][0]["definition"], "terms.value");
        assert_eq!(lines.result["definitions"][0]["text"][1], ":phrase: value");
        assert_eq!(lines.inputs.len(), 2);
        assert!(
            dispatch(
                &sources,
                "habeas",
                &json!({"file":"src/lib.rs","line_start":3})
            )
            .is_err()
        );
        assert!(
            dispatch(
                &sources,
                "habeas",
                &json!({"file":"src/lib.rs","item":"fn[missing]"})
            )
            .is_err()
        );
        assert!(
            dispatch(
                &sources,
                "habeas",
                &json!({"file":"src/lib.rs","line_start":0})
            )
            .is_err()
        );
        // The provider-facing schema leaves selector fields optional; the
        // harness still rejects incomplete, mixed, and unknown request forms.
        for arguments in [
            json!({}),
            json!({"file":"src/lib.rs"}),
            json!({"line_start":1}),
            json!({"rust_file":"src/lib.rs","rust_item":"fn[work]"}),
            json!({"item":"fn[work]"}),
            json!({"file":"src/lib.rs","line_start":1,"definition":"terms.value"}),
            json!({"file":"src/lib.rs","item":"fn[work]","line_start":1}),
            json!({"file":"src/lib.rs","item":"fn[work]","requirements":"requirements.*"}),
            json!({"requirements":"requirements.*","definition":"terms.value"}),
            json!({"definition":"terms.value","extra":true}),
        ] {
            assert!(
                dispatch(&sources, "habeas", &arguments).is_err(),
                "unexpectedly accepted {arguments}"
            );
        }
        assert!(
            dispatch(
                &sources,
                "habeas",
                &json!({"requirements":"requirements.*"})
            )
            .is_ok()
        );
        assert!(dispatch(&sources, "habeas", &json!({"definition":"terms.value"})).is_ok());
    }
Input 9: 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 10: outline src/authoring/tools.rs mod[tests]/fn[references_list_names_and_flattened_sites_without_recording_inputs]
    // {test}`requirements.authoring.reference_index`
    // {test}`requirements.references.definition_globs`
    // {test}`requirements.authoring.no_line_numbers`
    // {test}`requirements.authoring.read_denial`
    #[test]
    // {test}`requirements.references.authoring_inputs`
    // {test}`requirements.authoring.read_denial`
    fn references_list_names_and_flattened_sites_without_recording_inputs() {
        let root = project();
        fs::write(
            root.path().join("md/requirements.md"),
            format!(
                ":::{{req}} ready\nThe project MUST be ready.\n:::\n\n:::{{req}} other\nOther MUST hold.\n:::\n\n:::{{example}} case\nA ready case. {}\n:::\n\n:::{{definition}} word\n:phrase: word\n:impl: src/lib.rs#fn[work]\nA vocabulary term.\n:::\n",
                role("cite", "requirements.ready")
            ),
        )
        .unwrap();
        fs::write(
            root.path().join("src/lib.rs"),
            format!(
                "// {}\nfn zeta() {{}}\n\n// {}\nfn work() {{\n    // {}\n    // {}\n}}\n",
                role("test", "requirements.ready"),
                role("impl", "requirements.ready"),
                role("cite", "requirements.other"),
                role("term", "requirements.word"),
            ),
        )
        .unwrap();
        fs::create_dir_all(root.path().join("private")).unwrap();
        fs::write(
            root.path().join("private/notes.md"),
            format!("{}\n", role("cite", "requirements.ready")),
        )
        .unwrap();
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n\n[evidence]\ndisallow = [\"private\"]\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();

        let all = dispatch(&sources, "references", &json!({})).unwrap();
        assert_eq!(
            all.result,
            json!({"definitions": [
                {"name": "requirements.case", "kind": "example"},
                {"name": "requirements.other", "kind": "requirement"},
                {"name": "requirements.ready", "kind": "requirement"},
            ], "sites": []})
        );
        assert!(all.inputs.is_empty());

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

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

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

        for selection in ["requirements.missing", "requirements.word", "bad name", ""] {
            assert!(
                dispatch(&sources, "references", &json!({"selection": selection})).is_err(),
                "accepted {selection:?}"
            );
        }
        let error = dispatch(&sources, "references", &json!({"selection": 1}))
            .err()
            .unwrap();
        assert!(
            error.to_string().contains("selection must be a string"),
            "{error}"
        );
        assert!(
            dispatch(
                &sources,
                "references",
                &json!({"name": "requirements.ready"})
            )
            .is_err()
        );
    }
Input 11: outline src/authoring/tools.rs mod[tests]/fn[outline_lists_nested_nodes_without_text_or_inputs]
    // {test}`requirements.authoring.outline_tool`
    // {test}`requirements.references.outlines`
    // {test}`requirements.authoring.no_line_numbers`
    // {test}`requirements.authoring.read_denial`
    #[test]
    fn outline_lists_nested_nodes_without_text_or_inputs() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "/// Docs.\nstruct Thing;\n\nimpl Thing {\n    fn run(&self) {}\n}\n",
        )
        .unwrap();
        fs::write(root.path().join("notes.txt"), "alpha\n\nbeta\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let outline = dispatch(&sources, "outline", &json!({"file":"src/lib.rs"})).unwrap();
        assert!(outline.inputs.is_empty());
        assert_eq!(
            outline.result,
            json!([
                {"item": "struct[Thing]", "kind": "struct", "name": "Thing", "children": []},
                {"item": "impl[Thing]", "kind": "impl", "name": "Thing", "children": [
                    {"item": "impl[Thing]/fn[run]", "kind": "fn", "name": "run", "children": []},
                ]},
            ])
        );
        assert!(!outline.result.to_string().contains("Docs"));
        let plain = dispatch(&sources, "outline", &json!({"file":"notes.txt"})).unwrap();
        let entries = plain.result.as_array().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.iter().all(|entry| entry["kind"] == "line"
            && entry["name"].is_null()
            && entry["item"].as_str().unwrap().starts_with("line@")));
        assert!(entries[1].get("line_start").is_none());
        for (arguments, message) in [
            (json!({"file":"missing.rs"}), "missing.rs"),
            (json!({}), "file"),
            (json!({"file":1}), "file"),
            (json!({"file":"src/lib.rs", "extra":true}), "extra"),
        ] {
            let error = dispatch(&sources, "outline", &arguments).err().unwrap();
            assert!(error.to_string().contains(message), "{arguments}: {error}");
        }
        let error = dispatch(&sources, "outline", &json!({})).err().unwrap();
        assert!(
            error.to_string().contains("file must be a string"),
            "{error}"
        );

        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\ndisallow = ['notes.txt']\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let error = dispatch(&sources, "outline", &json!({"file":"notes.txt"}))
            .err()
            .unwrap();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
        assert!(error.to_string().contains("notes.txt"), "{error}");
        assert!(error.to_string().contains("disallowed"), "{error}");
    }
Input 12: outline src/authoring/tools.rs mod[tests]/fn[line_range_reads_record_the_innermost_covering_nodes]
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.delivered_inputs`
    // {test}`requirements.ci.outline_inputs`
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn line_range_reads_record_the_innermost_covering_nodes() {
        let root = project();
        let source = "use std::fmt;\n\nfn first() {}\n\nmod inner {\n    fn second() {\n        let x = 1;\n    }\n}\n";
        fs::write(root.path().join("src/lib.rs"), source).unwrap();
        let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        // Blank lines between nodes do not select their common ancestor.
        let read = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":3,"line_end":7}),
        )
        .unwrap();
        let items = read.result["inputs"]
            .as_array()
            .unwrap()
            .iter()
            .map(|input| {
                assert!(input.get("line_start").is_none());
                input["item"].as_str().unwrap()
            })
            .collect::<Vec<_>>();
        assert_eq!(
            items,
            ["fn[first]", "mod[inner]"],
            "line 5 is mod inner's own line, so the module is selected"
        );
        let nested = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":7,"line_end":7}),
        )
        .unwrap();
        assert_eq!(nested.result["inputs"][0]["item"], "mod[inner]/fn[second]");
        assert_eq!(
            nested.result["inputs"][0]["text"],
            json!(["    fn second() {", "        let x = 1;", "    }"])
        );
        sources.record_inputs(&nested.inputs);
        assert_eq!(
            sources.recorded_inputs(),
            [
                crate::inputs::outline_input(root.path(), "src/lib.rs", "mod[inner]/fn[second]")
                    .unwrap()
            ]
        );
        assert!(sources.recorded_inputs()[0].get("line_start").is_none());
        assert!(sources.recorded_inputs()[0].get("text").is_none());
        let whole = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":1}),
        )
        .unwrap();
        assert!(
            whole.result["inputs"][0]["item"]
                .as_str()
                .unwrap()
                .starts_with("use@")
        );
        assert_eq!(whole.result["inputs"].as_array().unwrap().len(), 3);
        fs::write(root.path().join("notes.txt"), "alpha\nbeta\ngamma\ndelta\n").unwrap();
        let plain = dispatch(
            &sources,
            "habeas",
            &json!({"file":"notes.txt","line_start":2,"line_end":3}),
        )
        .unwrap();
        let inputs = plain.result["inputs"].as_array().unwrap();
        assert_eq!(inputs.len(), 2);
        assert_eq!(inputs[0]["text"], json!(["beta"]));
        assert_eq!(inputs[1]["text"], json!(["gamma"]));
        assert_ne!(inputs[0]["item"], inputs[1]["item"]);
        for input in inputs {
            assert!(input["item"].as_str().unwrap().starts_with("line@"));
            assert!(input.get("line_start").is_none());
            assert!(input.get("line_end").is_none());
        }
    }
Input 13: 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 14: outline src/sites.rs mod[tests]/fn[sites_are_the_innermost_nodes_of_site_matches_and_violations_within_them]
  • File: src/sites.rs
  • Selector: mod[tests]/fn[sites_are_the_innermost_nodes_of_site_matches_and_violations_within_them]
  • Kind: fn
  • src/sites.rs:914–979
    // {test}`requirements.references.distributed`
    #[test]
    // {test}`requirements.authoring.no_line_numbers`
    fn sites_are_the_innermost_nodes_of_site_matches_and_violations_within_them() {
        let temp = project(RULE, SOURCE);
        let (errors, sites) = inspect(temp.path());
        let sites = &sites["requirements.rule"];
        let found = sites
            .iter()
            .map(|site| (site.item.as_str(), site.queries()))
            .collect::<Vec<_>>();
        assert_eq!(
            found,
            [
                (
                    "fn[check_one]",
                    vec!["checkers".to_owned(), "panics".to_owned()]
                ),
                ("fn[check_two]", vec!["checkers".to_owned()]),
                (
                    "mod[inner]/fn[check_three]",
                    vec!["checkers".to_owned(), "panics".to_owned()]
                ),
            ]
        );
        let nested = &sites[2];
        assert_eq!((nested.line_start, nested.line_end), (5, 7));
        let violation = nested
            .matches
            .iter()
            .find(|found| found.kind == QueryKind::Violations)
            .unwrap();
        assert_eq!(violation.text, "panic!(\"z\")");
        assert_eq!(violation.line_start, 6);
        assert_eq!(
            nested.matches_value()[1],
            json!({"kind": "violations", "query": "panics", "item": "mod[inner]/fn[check_three]/fn[nested]", "text": "panic!(\"z\")"})
        );
        // No query problems; each site lacks a review, and being a site is
        // not a reference for Rust item coverage.
        assert!(
            !errors.iter().any(|error| error.contains("query")),
            "{errors:?}"
        );
        for item in [
            "fn[check_one]",
            "fn[check_two]",
            "mod[inner]/fn[check_three]",
        ] {
            let path = review_path("requirements.rule", "src/lib.rs", item);
            assert!(
                errors
                    .iter()
                    .any(|error| error.starts_with(&format!("{path}: missing site review"))),
                "{item}: {errors:?}"
            );
        }
        let inspection = crate::evidence::inspect_repository(temp.path()).unwrap();
        assert!(
            inspection.uncovered.iter().any(|item| item
                .error
                .contains("function check_two has no recent coverage")),
            "{:?}",
            inspection.uncovered
        );
    }

Referenced definitions

Input 2: 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.
:::

Other sources

Input 1: requirements selection requirements.authoring.no_line_numbers
:::{req} no_line_numbers
No prompt, tool result, or tool error the harness gives the model MUST state a
line number or line range of a project source, except within source text it
quotes and where a tool error repeats a line number the model supplied. The
harness MUST identify a source location by file and outline selector under
{cite}`requirements.references.outline_selectors` instead.
:::
Input 16: outline src/authoring/tools.rs fn[dispatch_paged]
// {impl}`requirements.authoring.file_discovery`
// {impl}`requirements.authoring.structural_search`
// {impl}`requirements.authoring.outline_tool`
// {impl}`requirements.authoring.reference_index`
// {impl}`requirements.authoring.github_reads`
pub(crate) fn dispatch_paged(
    sources: &AssessmentSources,
    pages: &mut ResultPages,
    name: &str,
    arguments: &Value,
) -> io::Result<ToolDelivery> {
    let arguments = arguments
        .as_object()
        .ok_or_else(|| io::Error::other("tool arguments must be an object"))?;
    let mut deliver = |listing: io::Result<Listing>| pages.deliver(sources, listing?);
    match name {
        "habeas" => read(sources, arguments).and_then(|read| match read {
            Ok(delivery) => Ok(delivery),
            Err(listing) => deliver(Ok(listing)),
        }),
        "list_files" => {
            deliver(list_files(sources, arguments).and_then(|listing| {
                with_not_listed(sources, arguments, NotListed::Children, listing)
            }))
        }
        "outline" => deliver(outline(sources, arguments)),
        "ripgrep" => deliver(search(sources, arguments).and_then(|listing| {
            let pattern = regex::Regex::new(string(arguments, "pattern")?).ok();
            with_not_listed(sources, arguments, NotListed::Text(pattern), listing)
        })),
        "ast_grep" => deliver(structural(sources, arguments).and_then(|listing| {
            let rule = arguments
                .get("language")
                .and_then(Value::as_str)
                .zip(arguments.get("rule").and_then(Value::as_object))
                .and_then(|(language, rule)| StructuralRule::compile(language, rule).ok());
            with_not_listed(sources, arguments, NotListed::Rule(rule), listing)
        })),
        "references" => deliver(references(sources, arguments)),
        "next_page" => check_keys(arguments, &["token"])
            .and_then(|()| pages.next_page(string(arguments, "token")?)),
        "finish_search" => pages.finish_search(&Value::Object(arguments.clone())),
        // GitHub reads are not evidence inputs.
        "github" => crate::github::tool(&sources.github, &Value::Object(arguments.clone()))
            .map(|result| ToolDelivery {
                result,
                inputs: Vec::new(),
            })
            .map_err(io::Error::other),
        _ => Err(io::Error::other(format!("unknown read tool {name:?}"))),
    }
    .map(|delivery| with_redaction_note(sources, delivery))
    .map_err(super::access::recoverable_os_denial)
    .map_err(super::access::recoverable_outside_request)
}