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

Requirements index · View definition

evidence Valid

Requirement

A site review under cite requirements.references.site_review MUST use the same tools and exactly-once submission rule as other assessments, except that submit_judgment MUST also require an applies: Boolean field, recorded as the review’s applies; a submission with applies false and a determination other than true MUST be invalid. It MUST use this prompt, replacing {{requirement_name}}, {{site_file}}, {{site_selector}}, {{matches}} (a JSON array giving, for each query match at the site, the query’s kind, sites or violations, its name, and the selector, under cite requirements.references.outline_selectors, of the innermost outline node containing the match, but no line numbers, and for a violation match its matched source text), {{habeas_background}} under cite requirements.authoring.habeas_background, {{distributed_background}} under cite requirements.authoring.habeas_background, {{judgment_rules}} under cite requirements.authoring.judgment_rules, and {{mandatory_inputs}}, the first block as its system prompt and the second as its subject message under cite requirements.authoring.prompt_parts:

# Task

Review one site of a distributed requirement. Your determination should be the
one any careful reviewer would reach from the same text and sources.

# Background: Habeas terms

{{habeas_background}}

{{distributed_background}}

# Your task

The mandatory inputs at the end contain the site, the requirement, and the
declarations it cites.

The requirement may also state obligations that particular code carries out;
those, and the requirement's tests, are assessed with the requirement, not here.
A site needs no {impl} or {test} reference and no tests of its own. Do not
assess the site against other requirements, and do not assess the queries, the
site's callers, or other sites.

1. Decide applies from the requirement's text describing its sites, not from
   which query matched; a violation match alone does not make the requirement
   apply. Read the site's callers only when its own code does not settle whether
   the text describes it. Set applies to true when the best-supported reading of
   that text, or one its wording supports equally well, governs the site.
   Otherwise set applies to false and determination to true, and explain in your
   rationale why the requirement does not apply.
2. If applies is true, judge the site: each obligation the requirement states
   for its sites that the site does not meet is a gap. Violation matches are
   leads, not verdicts: judge each one listed above, saying whether it breaks
   the requirement here and why, but a match may be harmless and the site may
   break the requirement without one.
3. Follow code the site calls only as far as needed to decide the site's
   behavior under the requirement, and do not judge that code on its own
   account.

# How to judge

{{judgment_rules}}

# Submitting

Choose true when your task finds no gap, {"FIXME": ["..."]} when every gap is
acknowledged, and false otherwise. You MUST end by calling submit_judgment
with applies, determination, and rationale until one submission is accepted.
A rejected submission does not complete the assessment. A judgment written in
your reply text is not accepted.
# Subject

Site under review: {{site_file}} {{site_selector}}
Requirement: {{requirement_name}}
Matches: {{matches}}
Judge against: the obligations the requirement states for each of its sites.

# Mandatory inputs

{{mandatory_inputs}}

Rationale

I judge the tests adequate for requirements.authoring.site_prompt. I found no unmet obligation.

submit_judgment and applies

  • Required field and type. src/authoring/mod.rs#mod[tests]/fn[site_submissions_require_applies_and_a_true_determination_when_it_is_false] calls site_submission directly. It accepts applies: false with determination true. It rejects a missing applies, a non-Boolean applies (“no”), and an extra field.
  • Invalid combination. The same test rejects applies: false with determination false and with {"FIXME": [...]}. That is the “applies false and a determination other than true MUST be invalid” clause.
  • Tool schema. fn[site_reviews_use_their_prompt_and_record_applies_and_the_site] asserts the submit_judgment tool’s required list is ["determination","rationale","applies"]. The fn[tool_definitions_with] snippet shows applies typed as boolean, and the sibling site-verification tests assert the same typing.
  • Recording. The same test asserts the record’s applies is true after an assessment run through assess. fn[site_assessments_differing_only_in_applies_are_verified] asserts record["applies"] for applies values including false. Together these cover recording a false value.

Tools and exactly-once submission

  • The site-review test compares the offered tool names to tool_definitions_with("submit_judgment", false) and checks submit_judgment is among them.
  • It also runs a scripted provider that submits twice and asserts the error contains “exactly once”.

Prompt filling

  • The first block is the system prompt and the second is the subject message.
    • fn[subjects_of_one_kind_share_a_byte_identical_system_prompt] builds a regex from the site_prompt template blocks, allowing only declared placeholders to expand. It asserts both blocks match and contain no leftover {{.
    • It also asserts the opening chat history is system then user.
    • It checks the system prompt is identical across two sites and does not contain the subject name.
  • The site-review test asserts the subject message equals the site_prompt block 1 filled with requirement_name, site_file, site_selector, matches and mandatory_inputs. It also asserts the # Subject … Site under review: src/lib.rs fn[check_two] … Requirement: … Matches: … header.
  • It asserts the model-visible prompt contains the heading and the habeas_background, distributed_background and judgment_rules blocks. It asserts the reference-roles block is absent and no {{ remains. The mandatory inputs include the site node, the requirement, the cited requirement and the cited definition.
  • matches content. src/sites.rs#mod[tests]/fn[violation_text_reaches_the_model_redacted] asserts matches_value() gives {"kind","query","item"} exactly for a site match, so there is no line number. For a violation match it asserts kind violations and the matched text, which is redacted. A second test (fn[sites_are_the_innermost_nodes_of_site_matches_and_violations_within_them]) asserts the full violation match object, including item, query and text. initial_prompt serializes site.matches_value() into the prompt.

Not assessed here. The sub-requirements this one cites (habeas_background, judgment_rules, prompt_parts, outline_selectors, site_review) carry their own tests. No FIXME acknowledgments apply.

Inputs

Implementation

Input 11: outline src/authoring/mod.rs fn[site_submission]
/// A submitted site review: its judgment, rationale, and `applies`.
/// `applies` false requires a `true` determination.
// {impl}`requirements.authoring.site_prompt`
fn site_submission(arguments: &Value) -> io::Result<(Judgment, String, bool)> {
    let object = arguments
        .as_object()
        .ok_or_else(|| io::Error::other("submit_judgment expects an object"))?;
    if object.len() != 3 || !object.contains_key("applies") {
        return Err(io::Error::other(
            "submit_judgment requires exactly applies, determination, and rationale",
        ));
    }
    let applies = object["applies"]
        .as_bool()
        .ok_or_else(|| io::Error::other("submit_judgment applies must be a boolean"))?;
    let mut rest = object.clone();
    rest.remove("applies");
    let (judgment, rationale) = submission(&Value::Object(rest))?;
    if !applies && judgment != Judgment::True {
        return Err(io::Error::other(
            "submit_judgment determination must be true when applies is false",
        ));
    }
    Ok((judgment, rationale, applies))
}
Input 12: outline src/authoring/mod.rs fn[tool_definitions_with]
/// The source tools and one submission tool.
// {impl}`requirements.authoring.initial_prompt`
// {impl}`requirements.ci.outcomes`
// {impl}`requirements.authoring.site_prompt`
// {impl}`requirements.authoring.tool_descriptions.common_case`
fn tool_definitions_with(submit: &str, site: bool) -> io::Result<Vec<ToolDefinition>> {
    let mut definitions = tools::definitions();
    let mut submission = if submit == "submit_verification" {
        json!({"name": "submit_verification", "description": "Finish a gap verification by submitting its result until one submission is accepted, rather than using a source tool or a text message. real says whether the alleged gap is real; acknowledged says whether applicable FIXME comments acknowledge every real gap. acknowledgments lists their issue references, e.g. [\"owner/repo#123\"], or [] when none apply. rationale is a nonempty explanation grounded in the reviewed sources. Cite files and outline selectors, never line numbers, including in illustrative examples. Summarize diagnostic formats with placeholders rather than quoting numeric source locations. Close every delivered search with finish_search before submitting. A rejected submission leaves this verification open. A successful submission ends this verification and records these answers.",
            "parameters": {"type":"object", "additionalProperties": false, "required":["real","acknowledged","acknowledgments","rationale"], "properties": {
                "real":{"type":"boolean"},
                "acknowledged":{"type":"boolean"},
                "acknowledgments":{"type":"array","items":{"type":"string","minLength":1}},
                "rationale":{"type":"string","minLength":1}}}})
    } else {
        let determination = json!({"oneOf":[{"type":"boolean"},{"type":"object","additionalProperties":false,"required":["FIXME"],"properties":{"FIXME":{"type":"array","minItems":1,"items":{"type":"string","minLength":1}}}}]});
        json!({"name": "submit_judgment", "description": "Finish the assessment by submitting your final judgment until one submission is accepted, rather than using a source tool or a text message. determination is true when the subject meets its review criteria, false when it has an unacknowledged gap, or {\"FIXME\":[\"owner/repo#123\"]} naming the issues in applicable FIXME comments that acknowledge every gap. rationale is a nonempty explanation grounded in the reviewed sources. Cite files and outline selectors, never line numbers, including in illustrative examples. Summarize diagnostic formats with placeholders rather than quoting numeric source locations. Close every delivered search with finish_search before submitting. A rejected submission leaves this assessment open. A successful submission ends this assessment and records the judgment.",
            "parameters": {"type":"object", "additionalProperties": false, "required":["determination","rationale"], "properties": {
                "determination": determination,
                "rationale":{"type":"string","minLength":1}}}})
    };
    // A site review also records whether the requirement applies.
    if site {
        let description = submission["description"].as_str().unwrap().to_owned();
        submission["description"] = json!(format!(
            "{description} applies says whether this requirement applies to the reviewed site; when false, report no real gap{}.",
            if submit == "submit_verification" {
                " (real false)"
            } else {
                " (determination true)"
            }
        ));
        let parameters = &mut submission["parameters"];
        parameters["properties"]["applies"] = json!({"type": "boolean"});
        parameters["required"]
            .as_array_mut()
            .expect("required fields")
            .push(json!("applies"));
    }
    definitions.push(submission);
    definitions
        .into_iter()
        .map(|value| serde_json::from_value(value).map_err(io::Error::other))
        .collect()
}
Input 13: outline src/authoring/mod.rs fn[assess]
// {impl}`requirements.authoring.submission`
// {impl}`requirements.authoring.initial_prompt`
// {impl}`requirements.authoring.persistence`
// {impl}`requirements.authoring.mandatory_inputs`
// {impl}`requirements.ci.reference_set`
// {impl}`requirements.ci.schema`
// {impl}`requirements.authoring.citation_prompt`
// {impl}`requirements.authoring.site_prompt`
async fn assess(
    provider: &impl CompletionProvider,
    sources: &mut AssessmentSources,
    usage: &mut UsageLog,
) -> io::Result<(Judgment, Value)> {
    let prompt = initial_prompt(sources)?;
    let site = matches!(sources.subject_kind, AssessmentKind::Site(..));
    let (judgment, rationale, applies) = if site {
        let (judgment, rationale, applies) = converse(
            provider,
            sources,
            usage,
            prompt,
            ("submit_judgment", true),
            site_submission,
        )
        .await?;
        (judgment, rationale, Some(applies))
    } else {
        let (judgment, rationale) = converse(
            provider,
            sources,
            usage,
            prompt,
            ("submit_judgment", false),
            submission,
        )
        .await?;
        (judgment, rationale, None)
    };
    usage.record.determination = Some(judgment.kind().into());
    usage.save()?;
    let evidence = record(sources, &judgment, &rationale, applies);
    Ok((judgment, evidence))
}
Input 16: outline src/sites.rs impl[SiteItem]/fn[matches_value]
    /// The matches as the model receives them: each query's kind and name
    /// and the selector of the innermost node containing the match, without
    /// line numbers, and, for a violation match, its redacted text.
    // {impl}`requirements.authoring.site_prompt`
    // {impl}`requirements.authoring.no_line_numbers`
    pub(crate) fn matches_value(&self) -> Value {
        Value::Array(
            self.matches
                .iter()
                .map(|found| {
                    let mut value = json!({
                        "kind": found.kind.label(),
                        "query": found.query,
                        "item": found.item,
                    });
                    if found.kind == QueryKind::Violations {
                        value["text"] =
                            Value::String(crate::redaction::redact_text(&found.text).into_owned());
                    }
                    value
                })
                .collect(),
        )
    }

Tests

Input 7: outline src/authoring/mod.rs mod[tests]/fn[subjects_of_one_kind_share_a_byte_identical_system_prompt]
    /// Every system prompt is the same for two subjects of its kind, and
    /// every subject-dependent value is in the subject message.
    // {test}`requirements.authoring.prompt_parts`
    // {test}`requirements.authoring.initial_prompt`
    // {test}`requirements.authoring.citation_prompt`
    // {test}`requirements.authoring.site_prompt`
    // {test}`requirements.authoring.verifier_prompt`
    #[test]
    fn subjects_of_one_kind_share_a_byte_identical_system_prompt() {
        // Check every literal segment of the selected approved blocks, allowing
        // only declared placeholders to expand, then check the opening message roles.
        fn assert_opening(prompt: &Prompt, template: &str) {
            let placeholders = regex::Regex::new(r"\{\{[^}]+\}\}").unwrap();
            for (index, actual) in [&prompt.system, &prompt.subject].into_iter().enumerate() {
                let expected = approved_text(template, index);
                let mut pattern = String::from(r"\A");
                let mut end = 0;
                for placeholder in placeholders.find_iter(expected) {
                    pattern.push_str(&regex::escape(&expected[end..placeholder.start()]));
                    pattern.push_str("(?s:.*?)");
                    end = placeholder.end();
                }
                pattern.push_str(&regex::escape(&expected[end..]));
                pattern.push_str(r"\z");
                assert!(
                    regex::Regex::new(&pattern).unwrap().is_match(actual),
                    "{template} block {index}: {actual}"
                );
                assert!(!actual.contains("{{"), "{actual}");
            }
            let request = Prompt {
                system: prompt.system.clone(),
                subject: prompt.subject.clone(),
            }
            .request();
            assert_eq!(
                request.chat_history,
                vec![
                    Message::system(prompt.system.clone()),
                    Message::user(prompt.subject.clone())
                ]
            );
        }
        let project =
            crate::sites::tests::project(crate::sites::tests::RULE, crate::sites::tests::SOURCE);
        let requirements = project.path().join("md/requirements.md");
        let mut book = fs::read_to_string(&requirements).unwrap();
        let cite = "{cite}`requirements.rule`";
        book.push_str(&format!(
            "\n:::{{req}} other\nThe project MUST also work.\n:::\n\n:::{{req}} second\nThe project MUST keep working.\n:::\n\n:::{{example}} first_case\nA case. {cite}\n:::\n\n:::{{example}} second_case\nAnother case. {cite}\n:::\n"
        ));
        fs::write(&requirements, book).unwrap();
        let source = project.path().join("src/lib.rs");
        let mut text = fs::read_to_string(&source).unwrap();
        text.push_str(&format!(
            "\n// {cite}\nfn cites_one() {{}}\n\n// {cite}\n// :::{{cite}} habeas:util\n// Formats output.\n// :::\nfn cites_two() {{}}\n"
        ));
        fs::write(&source, text).unwrap();
        for (first, second, template) in [
            (
                "requirements.other",
                "requirements.second",
                "initial_prompt",
            ),
            (
                "requirements.first_case",
                "requirements.second_case",
                "initial_prompt",
            ),
            (
                "citations:src/lib.rs#fn[cites_one]",
                "citations:src/lib.rs#fn[cites_two]",
                "citation_prompt",
            ),
            (
                "sites:requirements.rule/src/lib.rs#fn[check_one]",
                "sites:requirements.rule/src/lib.rs#fn[check_two]",
                "site_prompt",
            ),
        ] {
            let sources = |subject: &str| {
                AuthoringSubject::parse(subject)
                    .sources(project.path())
                    .unwrap()
            };
            let (first, second) = (sources(first), sources(second));
            let (one, two) = (
                initial_prompt(&first).unwrap(),
                initial_prompt(&second).unwrap(),
            );
            assert_opening(&one, template);
            assert_opening(&two, template);
            assert_eq!(one.system, two.system, "{}", first.subject_name);
            assert_ne!(one.subject, two.subject);
            assert!(one.subject.starts_with("# Subject\n\n"), "{}", one.subject);
            assert!(!one.system.contains(&first.subject_name));
            let (one, two) = (
                verification_prompt(&first, &Judgment::False, "One gap.").unwrap(),
                verification_prompt(&second, &Judgment::Fixme(vec!["#2".into()]), "Two gaps.")
                    .unwrap(),
            );
            assert_opening(&one, "verifier_prompt");
            assert_opening(&two, "verifier_prompt");
            assert_eq!(one.system, two.system, "verifier of {}", first.subject_name);
            assert!(one.subject.contains("One gap."));
            assert!(!one.system.contains("One gap."));
        }
    }
Input 8: 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 9: outline src/authoring/mod.rs mod[tests]/fn[site_submissions_require_applies_and_a_true_determination_when_it_is_false]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[site_submissions_require_applies_and_a_true_determination_when_it_is_false]
  • Kind: fn
  • src/authoring/mod.rs:4981–5001
    // {test}`requirements.authoring.site_prompt`
    // {test}`requirements.authoring.verifier_outcome`
    #[test]
    fn site_submissions_require_applies_and_a_true_determination_when_it_is_false() {
        assert_eq!(
            site_submission(
                &json!({"applies": false, "determination": true, "rationale": "Not a checker."})
            )
            .unwrap(),
            (Judgment::True, "Not a checker.".to_owned(), false)
        );
        for arguments in [
            json!({"determination": true, "rationale": "x"}),
            json!({"applies": "no", "determination": true, "rationale": "x"}),
            json!({"applies": false, "determination": false, "rationale": "x"}),
            json!({"applies": false, "determination": {"FIXME": ["a"]}, "rationale": "x"}),
            json!({"applies": true, "determination": true, "rationale": "x", "extra": 1}),
        ] {
            assert!(site_submission(&arguments).is_err(), "accepted {arguments}");
        }
    }
Input 10: outline src/sites.rs mod[tests]/fn[violation_text_reaches_the_model_redacted]
  • File: src/sites.rs
  • Selector: mod[tests]/fn[violation_text_reaches_the_model_redacted]
  • Kind: fn
  • src/sites.rs:846–884
    // {test}`requirements.authoring.redaction`
    // {test}`requirements.authoring.site_prompt`
    #[test]
    fn violation_text_reaches_the_model_redacted() {
        let token = ["ghp_", "abcdefghijklmnopqrstuvwxyz0123456789"].concat();
        let found = |kind, text: &str| SiteMatch {
            kind,
            query: "q".to_owned(),
            line_start: 1,
            line_end: 1,
            item: "fn[check]".to_owned(),
            text: text.to_owned(),
        };
        let site = SiteItem {
            requirement: "requirements.rule".to_owned(),
            file: "src/lib.rs".to_owned(),
            item: "fn[check]".to_owned(),
            line_start: 1,
            line_end: 1,
            matches: vec![
                found(QueryKind::Sites, "fn check() {}"),
                found(QueryKind::Violations, &format!("connect(\"{token}\")")),
            ],
        };
        let value = site.matches_value();
        assert_eq!(
            value[0],
            json!({"kind": "sites", "query": "q", "item": "fn[check]"})
        );
        assert_eq!(value[1]["kind"], "violations");
        assert_eq!(site.selector_label(), "fn[check]");
        let root_site = SiteItem {
            item: String::new(),
            ..site.clone()
        };
        assert_eq!(root_site.selector_label(), "<root>");
        assert_eq!(value[1]["text"], "connect(\"[REDACTED:GitHub Token]\")");
        assert!(!value.to_string().contains(&token), "{value}");
    }

Referenced definitions

Input 2: requirements selection requirements.references.site_review
:::{req} site_review
Every site of a distributed requirement under
{cite}`requirements.references.distributed` MUST have a site review: an
assessment of whether that site upholds the requirement, recorded at
`evidence/sites/<full-name>/<file>/<selector>.json`, where `<file>` and
`<selector>` are encoded as under
{cite}`requirements.references.citation_review`. The review MUST use the prompt
defined by {cite}`requirements.authoring.site_prompt`. Mandatory inputs, under
{cite}`requirements.authoring.mandatory_inputs`, MUST be the site's outline
node, the requirement's complete declaration, and each declaration the
requirement cites. The record MUST contain the requirement's full name, the
site's file and selector, `queries`, the sorted names of the queries with a
match at the site, `applies`, `determination`, `rationale`, and `inputs`, with
determinations under {cite}`requirements.ci.outcomes`. `applies` MUST be a
Boolean recording whether the requirement applies to the site. A site to which
the requirement does not apply MUST be judged `true`, and the rationale MUST
explain why it does not apply. `habeas info` MUST report, for each selected
distributed requirement, how many of its sites the requirement does not apply
to.

Validation MUST require a current, accepted review for every site, MUST report a
false review with its rationale, and MUST report stale, missing, or orphaned
reviews; a review is orphaned when its file and selector no longer name a site
of the requirement. A `{fixme}` naming the requirement inside a site
acknowledges a gap at that site only: it MUST be an input to that site's review
and MUST NOT contribute to the requirement's own review, coverage, or reference
set. A review MUST become stale when the site's hash, the requirement's
declaration, a cited declaration, its `queries`, or the `{fixme}` references
naming the requirement inside the site, with the words of their bodies, change.
Each site review's determination MUST be checked on its own, independently of
the requirement's evidence. Authoring with `--all` MUST include site reviews,
`habeas author sites:<full-name>` MUST author the site reviews of the named
requirement, and `habeas author sites:<full-name>/<file>#<selector>` MUST author
the review of the one site it names, under
{cite}`requirements.authoring.refresh`, where omitting `#<selector>` names the
file's root node. `habeas status` MUST report missing, stale, invalid, and false
site reviews with their requirement, file, and selector, and `habeas info` MUST
list each selected requirement's sites with their determinations.
:::
Input 3: requirements selection requirements.references.outline_selectors
:::{req} outline_selectors
An outline selector MUST be a `/`-separated path of segments from the file's
root node to an outline node; the empty selector MUST select the root node. A
named node's segment MUST be `kind[name]`. An anonymous node's segment MUST be
`kind@hash`, where `hash` is the first twelve hexadecimal digits of its identity
hash under {cite}`requirements.references.structural_hash`. Siblings whose
segments would otherwise be identical MUST be disambiguated by `#N`, their
one-based position among those siblings in source order, except `line` nodes:
identical lines are interchangeable, so a `line` selector MUST resolve when any
line with that content exists in the file. In names, `%`, `[`, `]`, `/`, `#`,
`@`, and whitespace MUST be percent-encoded as UTF-8 bytes, so selectors are
reversible. Line numbers MUST NOT form part of a selector.
:::
Input 4: requirements selection requirements.authoring.habeas_background
:::{req} habeas_background
Every assessment prompt MUST replace `{{habeas_background}}` with the first text
below. The requirement, citation, and verifier prompts MUST replace
`{{reference_roles}}` with the second, except that a verifier checking a site
review MUST replace it with nothing. The site prompt, the distributed task, and a
verifier checking a site review MUST replace `{{distributed_background}}` with
the third. So all assessments share the same account of Habeas's terms:

```text
Habeas traces a project's requirements, written in its mdBook, to the source
code and tests that implement and verify them.

- A requirement is a {req} directive in the book that states obligations with
  MUST, MUST NOT, SHOULD, and MAY. A named example is an {example} directive
  describing a concrete case of one or more requirements. Both have
  dot-separated full names, such as requirements.cli.status. A vocabulary
  definition, a {definition} directive, defines a term that other text uses with
  {term}; it is never the target of a reference.
- Source code marks the requirements and examples it implements, tests, or
  relies on with {impl}, {test}, and {cite} references, such as
  {impl}`requirements.cli.status`, and acknowledges known gaps in them with
  {fixme} references.
- Sources are identified by outline nodes: a file's functions, types, sections,
  and similar items, named by selectors such as fn[run] or impl[Thing]/fn[run].
  <root> is the whole file.
```

```text
The reference roles:

- {impl}: the source implements part of the requirement or example. Source code
  implements part of one when it makes a decision, performs a check, produces an
  output, or handles a case it specifies, or when it constrains a type's fields,
  variants, serialized form, or validation. Calling code that implements it, or
  producing a value a caller uses to meet it, does not by itself count. A check
  counts only if the text states it, or the item could not meet one of the
  text's obligations without it; then returning its outcome counts even when a
  caller acts on it. Code that checks it is consistent with a requirement, such
  as recognizing a form the requirement defines in order to decide whether to
  run other behavior, relies on that requirement ({cite}) rather than
  implementing it. A requirement stating a convention for every output of a
  kind, such as every validation error, is implemented by the code that carries
  out the convention as a whole, not by each item that produces one such output.
  Only a root needs the reference: an item that no other item marked {impl}
  for the same requirement reaches. Code a reviewer reaches by following a
  marked item, through what it calls, the types it uses, or the implementations
  of trait methods it calls, needs none; nor does a test helper reached from a
  test marked {test}. A site of a
  distributed requirement needs no reference to it for being a site.
- {test}: the source is a test or test helper designed to verify behavior the
  requirement or example specifies.
- {cite}: the source relies on or refers to the requirement or example, and
  should be re-checked or kept in sync when it changes, without implementing or
  testing it. A {cite} needs no coverage; each item with citations has its own
  citation review.
- {fixme}: the source acknowledges a known gap in fulfilling the requirement or
  example. It is always fenced; its body describes the gap and may begin with
  lines such as :github: rust-lang/rust#123 naming issues that track it.

A declaration can also name a whole file or one outline node it is implemented
or tested by, with an :impl: or :test: option line directly after its opening
fence; that counts as an {impl} or {test} reference from that source. A
reference written as a fence, :::{role} name, then commentary, then :::,
attaches commentary.
```

```text
A distributed requirement states obligations that each of many sites upholds on
its own. It contains site queries, which select its sites, and violation
queries, which select constructs likely to break those obligations. Each site is
the innermost outline node containing a site-query match.
```
:::
Input 5: requirements selection requirements.authoring.judgment_rules
:::{req} judgment_rules
Every assessment prompt MUST replace `{{judgment_rules}}` with this text, so all
assessments judge by the same rules:

```text
- Derive obligations from the supplied subject and contextual text. Base
  conclusions about tests or other source behavior only on source code you have
  received: mandatory inputs, items read with the habeas tool, or snippets
  returned by ripgrep or ast_grep. Close every delivered search with
  finish_search, recording the tags whose snippets you relied on without an
  additional source read. Supplied acknowledgments establish what a {fixme}
  reference says and which issues it names; they do not establish that its
  claimed gap is real. outline, list_files, and references only locate items;
  read any item whose code your conclusion relies on unless a search snippet
  provides the information you need. Comments state intent; check behavior and
  assertions in the code itself.
- Judge only against the text your task names. Report a gap only where your task
  or these rules define one, naming the obligation and the relevant sources you
  have reviewed. For a missing test, identify the obligation or scenario after
  looking where your task directs; do not invent a source item for absent code.
  Do not report other bugs or issues you notice; edge cases the text does not name are
  not gaps.
- A SHOULD imposes an obligation unless the text or a source comment gives a
  reason it does not apply. In a test-adequacy assessment, apply the testing
  criteria to each applicable SHOULD, and explain any exception in your rationale.
  MAY imposes nothing to check. Examples and sample output inside the text
  illustrate the obligations its prose states; they bind their exact form only
  where the text says the output takes that form.
- If the text admits two readings that its wording supports equally, not merely
  one it fails to exclude, and they lead to different conclusions, such as
  whether code conforms or which role a citation calls for, that ambiguity is a
  gap. Name the readings in your rationale.
- These are not gaps: style, performance, logging, how helpers are factored,
  robustness the text does not require, and silently ignoring input the text
  does not mention.
- A gap is acknowledged only by a {fixme} reference, in the supplied
  acknowledgments, in the inputs, or in a source you read, to the requirement
  or example your task judges against, or,
  in a site review, to the distributed requirement within the site, whose body
  describes that same gap, and whose named issues are open; a {fixme} naming a
  closed issue no longer acknowledges its gap. A plain FIXME or TODO comment is
  not an acknowledgment. Judge an acknowledgment only within your task's scope.
  An acknowledgment of an implementation bug alone does not establish a
  test-adequacy gap or acknowledge a different missing-test or assertion gap.
  Do not inspect implementation correctness merely to validate an out-of-scope
  acknowledgment. In a FIXME determination or an acknowledgments list,
  give each distinct issue its :github: option names once, such as
  "rust-lang/rust#123", and, for a {fixme} naming no issue, its body's words
  joined by single spaces. A {fixme} describing a gap that your review establishes
  no longer exists within its task's scope is itself a gap.
- Explain your judgment in a Markdown rationale with source locations, including
  any acknowledged gaps.
- Give a source location as its file and outline selector, the address the
  habeas and outline tools use, in backticks: `src/config.rs#fn[load]`, or
  `src/config.rs` for a whole file. Name requirements, examples, and
  definitions by full name in backticks. Name functions, types, and tests in
  backticks exactly as they are written. Do not give line numbers: they change
  whenever nearby code changes, while a selector stays correct.
```
:::
Input 6: requirements selection requirements.authoring.prompt_parts
:::{req} prompt_parts
Each assessment conversation MUST send its prompt as a system prompt followed by
one user message, the subject message, filled from the first and second text
blocks of the prompt requirement for the assessment's kind. The kinds are
requirement, example, citation review, site review, and a verifier of each of
those. A system prompt MUST be the same for every assessment of its kind, so
every placeholder whose value depends on the subject MUST be in the subject
message.
:::

Other sources

Input 1: requirements selection requirements.authoring.site_prompt
:::{req} site_prompt
A site review under {cite}`requirements.references.site_review` MUST use the
same tools and exactly-once submission rule as other assessments, except that
`submit_judgment` MUST also require an `applies: Boolean` field, recorded as the
review's `applies`; a submission with `applies` false and a determination other
than `true` MUST be invalid. It MUST use this prompt, replacing
`{{requirement_name}}`, `{{site_file}}`, `{{site_selector}}`, `{{matches}}` (a
JSON array giving, for each query match at the site, the query's kind, `sites`
or `violations`, its name, and the selector, under
{cite}`requirements.references.outline_selectors`, of the innermost outline node
containing the match, but no line numbers, and for a violation match its
matched source text),
`{{habeas_background}}` under {cite}`requirements.authoring.habeas_background`,
`{{distributed_background}}` under
{cite}`requirements.authoring.habeas_background`, `{{judgment_rules}}` under
{cite}`requirements.authoring.judgment_rules`, and
`{{mandatory_inputs}}`, the first block as its system prompt and the second as
its subject message under {cite}`requirements.authoring.prompt_parts`:

```text
# Task

Review one site of a distributed requirement. Your determination should be the
one any careful reviewer would reach from the same text and sources.

# Background: Habeas terms

{{habeas_background}}

{{distributed_background}}

# Your task

The mandatory inputs at the end contain the site, the requirement, and the
declarations it cites.

The requirement may also state obligations that particular code carries out;
those, and the requirement's tests, are assessed with the requirement, not here.
A site needs no {impl} or {test} reference and no tests of its own. Do not
assess the site against other requirements, and do not assess the queries, the
site's callers, or other sites.

1. Decide applies from the requirement's text describing its sites, not from
   which query matched; a violation match alone does not make the requirement
   apply. Read the site's callers only when its own code does not settle whether
   the text describes it. Set applies to true when the best-supported reading of
   that text, or one its wording supports equally well, governs the site.
   Otherwise set applies to false and determination to true, and explain in your
   rationale why the requirement does not apply.
2. If applies is true, judge the site: each obligation the requirement states
   for its sites that the site does not meet is a gap. Violation matches are
   leads, not verdicts: judge each one listed above, saying whether it breaks
   the requirement here and why, but a match may be harmless and the site may
   break the requirement without one.
3. Follow code the site calls only as far as needed to decide the site's
   behavior under the requirement, and do not judge that code on its own
   account.

# How to judge

{{judgment_rules}}

# Submitting

Choose true when your task finds no gap, {"FIXME": ["..."]} when every gap is
acknowledged, and false otherwise. You MUST end by calling submit_judgment
with applies, determination, and rationale until one submission is accepted.
A rejected submission does not complete the assessment. A judgment written in
your reply text is not accepted.
```

```text
# Subject

Site under review: {{site_file}} {{site_selector}}
Requirement: {{requirement_name}}
Matches: {{matches}}
Judge against: the obligations the requirement states for each of its sites.

# Mandatory inputs

{{mandatory_inputs}}
```
:::
Input 14: outline src/authoring/mod.rs fn[record]
/// The record a judgment produces: definition evidence, or a citation
/// review with the item's file, selector, and citations.
// {impl}`requirements.authoring.persistence`
// {impl}`requirements.references.site_review`
fn record(
    sources: &AssessmentSources,
    judgment: &Judgment,
    rationale: &str,
    applies: Option<bool>,
) -> Value {
    match &sources.subject_kind {
        AssessmentKind::Site(site, fixmes) => json!({"requirement": site.requirement,
            "file": site.file, "item": site.item, "queries": site.queries(),
            "applies": applies.unwrap_or(true),
            "fixmes": fixmes.iter().map(crate::sites::SiteFixme::to_value).collect::<Vec<_>>(),
            "determination": judgment.to_value(), "rationale": rationale,
            "inputs": sources.recorded_inputs()}),
        AssessmentKind::Definition(kind, _) => json!({kind.noun(): sources.subject_text,
            "determination": judgment.to_value(), "rationale": rationale,
            "references": sources.reference_set, "inputs": sources.recorded_inputs()}),
        AssessmentKind::Citation(item) => json!({"file": item.file, "item": item.item,
            "citations": item.citations_value(), "determination": judgment.to_value(),
            "rationale": rationale, "inputs": sources.recorded_inputs()}),
    }
}
Input 15: outline src/authoring/mod.rs mod[tests]/fn[site_assessments_differing_only_in_applies_are_verified]
    // {test}`requirements.authoring.confirmation`
    // {test}`requirements.authoring.verifier_prompt`
    // {test}`requirements.authoring.verifier_outcome`
    // {test}`requirements.authoring.habeas_background`
    #[tokio::test]
    // {test}`requirements.authoring.judgment_rules`
    async fn site_assessments_differing_only_in_applies_are_verified() {
        let site = |applies: bool, determination: Value, rationale: &str| {
            (
                "submit_judgment",
                json!({"applies": applies, "determination": determination, "rationale": rationale}),
            )
        };
        let check = |applies: bool, real: bool, rationale: &str| {
            (
                "submit_verification",
                json!({"real": real, "acknowledged": false, "acknowledgments": [],
                    "rationale": rationale, "applies": applies}),
            )
        };
        // Agreement needs the same applies too.
        let (result, provider) = site_confirmed(vec![
            site(true, json!(true), "Reports problems."),
            site(true, json!(true), "Also fine."),
        ])
        .await;
        assert_eq!(result.unwrap().1["rationale"], "Reports problems.");
        assert_eq!(provider.requests.borrow().len(), 2);

        for (turns, recorded, applies, kept) in [
            // The verifier finds the requirement does not apply, unlike the
            // more favorable assessment it keeps: true on its rationale.
            (
                vec![
                    site(false, json!(true), "Not a checker."),
                    site(true, json!(true), "Reports problems."),
                    check(true, false, "It is a checker after all."),
                ],
                Judgment::True,
                true,
                "It is a checker after all.",
            ),
            // The verifier agrees with the more favorable assessment.
            (
                vec![
                    site(true, json!(true), "Reports problems."),
                    site(false, json!(true), "Not a checker."),
                    check(false, false, "Only a helper."),
                ],
                Judgment::True,
                false,
                "Not a checker.",
            ),
            // A real gap in the applying assessment records false.
            (
                vec![
                    site(false, json!(true), "Not a checker."),
                    site(true, json!(false), "It panics."),
                    check(true, true, "It panics in `src/lib.rs#fn[check_one]`."),
                ],
                Judgment::False,
                true,
                "It panics.",
            ),
            (
                vec![
                    site(false, json!(true), "Not a checker."),
                    site(true, json!(false), "It panics."),
                    (
                        "submit_verification",
                        json!({
                            "applies":true, "real":true, "acknowledged":true,
                            "acknowledgments":["o/r#1"], "rationale":"The site acknowledges its panic."
                        }),
                    ),
                ],
                Judgment::Fixme(vec!["o/r#1".into()]),
                true,
                "It panics.",
            ),
            (
                vec![
                    site(true, json!({"FIXME":["o/r#1"]}), "The known gap."),
                    site(true, json!(false), "Another gap."),
                    check(false, false, "Only a helper."),
                ],
                Judgment::True,
                false,
                "Only a helper.",
            ),
        ] {
            let (result, provider) = site_confirmed(turns.clone()).await;
            let (judgment, record) = result.unwrap();
            assert_eq!(judgment, recorded);
            assert_eq!(record["determination"], judgment.to_value());
            assert_eq!(record["applies"], applies, "{record}");
            let rationale = record["rationale"].as_str().unwrap();
            assert!(rationale.starts_with(kept), "{rationale}");
            assert!(
                rationale.contains("the assessments disagreed"),
                "{rationale}"
            );

            let prompts = provider.prompts();
            let (text, tools) = &prompts[2];
            let text = serde_json::from_str::<Value>(text).unwrap().to_string();
            let escaped = |value: &str| {
                serde_json::to_string(value)
                    .unwrap()
                    .trim_matches('"')
                    .to_owned()
            };
            assert!(
                text.contains(&escaped(
                    "The reviewer judged site review sites:requirements.rule/src/lib.rs#fn[check_one] as"
                )),
                "{text}"
            );
            assert!(
                text.contains(&escaped(approved_text("judgment_rules", 0))),
                "{text}"
            );
            assert!(text.contains(&escaped(SITE_STEP)), "{text}");
            assert!(
                text.contains(&escaped(approved_text("habeas_background", 0))),
                "{text}"
            );
            assert!(
                text.contains(&escaped(&format!(
                    "requirement states for each of its sites.\n\n{}\n\nThe mandatory inputs at the end contain the site",
                    distributed_background()
                ))),
                "{text}"
            );
            assert!(
                !text.contains(&escaped(approved_text("habeas_background", 1))),
                "{text}"
            );
            assert!(!text.contains("{{"), "{text}");
            assert!(tools.contains(&"submit_verification".to_owned()));
        }
    }
Input 17: 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
        );
    }