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

Requirements index · View definition

evidence Valid

Requirement

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:

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

Rationale

The tests adequately check requirements.authoring.habeas_background. They cover every assessment kind and every placeholder the requirement names, and they assert on actual prompt text.

Obligations and mapping

  1. Every assessment prompt replaces {{habeas_background}} with the first text.

    • Requirement initial prompt: mod[tests]/fn[initial_prompt_carries_the_review_criteria] asserts the prompt contains approved_text("habeas_background", 0). It also asserts no {{ remains, for both the requirement and the example subject.
    • Citation initial prompt: mod[tests]/fn[citation_reviews_use_their_prompt_and_record_the_item_and_citations] asserts the JSON-escaped first text is present.
    • Site initial prompt: mod[tests]/fn[site_reviews_use_their_prompt_and_record_applies_and_the_site] asserts the same.
    • Requirement verifier: mod[tests]/fn[disagreeing_assessments_verify_the_less_favorable_one] asserts the first text is present.
    • Example and citation verifiers: mod[tests]/fn[verifier_prompts_name_examples_and_citation_reviews] asserts the first text is present.
    • Site verifier: mod[tests]/fn[site_assessments_differing_only_in_applies_are_verified] asserts the first text is present.
    • The example initial prompt does not assert the background text directly. The code, initial_prompt in src/authoring/mod.rs, builds shared_blocks() once for every subject kind. The example case in the initial-prompt test also asserts that no {{ remains. Example verifier prompts do assert the text, so this is not a gap.
  2. The requirement, citation and verifier prompts replace {{reference_roles}} with the second text, except that a site-review verifier replaces it with nothing.

    • Requirement initial prompt: the initial-prompt test asserts the second text is present.
    • Distributed requirement system prompt: mod[tests]/fn[a_distributed_requirement_task_continues_with_the_filled_distributed_task] asserts the second text is present.
    • Citation initial prompt: the citation test asserts the second text is present.
    • Requirement, example and citation verifiers: the disagreeing-assessments test and the verifier-prompts test assert the second text is present.
    • Site-review verifier: site_assessments_differing_only_in_applies_are_verified asserts the second text is absent and that no {{ remains.
    • Site initial prompt: the site test asserts the second text is absent.
  3. The site prompt, the distributed task and a site-review verifier replace {{distributed_background}} with the third text.

    • Site initial prompt: site_reviews_use_their_prompt_and_record_applies_and_the_site asserts distributed_background() is present. It also compares the whole subject message against the filled site_prompt template.
    • Distributed task: a_distributed_requirement_task_continues_with_the_filled_distributed_task asserts the filled task starts with distributed_background(). It asserts that task appears in the subject message and in the verifier’s criteria.
    • Site-review verifier: site_assessments_differing_only_in_applies_are_verified asserts the text sits between “requirement states for each of its sites.” and “The mandatory inputs at the end contain the site”.
  4. Non-distributed prompts do not carry the third text. The initial-prompt test asserts a plain requirement prompt does not contain it.

Findings

I found no scenario where a plausible violation would pass. Examples are a missing background, a wrongly included or excluded reference-roles text, or an unreplaced placeholder. Substring assertions on the full approved text and the {{ absence checks would catch each of these.

Inputs

Implementation

Input 9: outline src/authoring/mod.rs fn[initial_prompt]
// {impl}`requirements.authoring.initial_prompt`
// {impl}`requirements.ci.review_criteria`
// {impl}`requirements.ci.outcomes`
// {impl}`requirements.examples.evidence`
// {impl}`requirements.examples.definition`
// {impl}`requirements.authoring.mandatory_inputs`
// {impl}`requirements.authoring.citation_prompt`
// {impl}`requirements.authoring.redaction`
// {impl}`requirements.authoring.github_reads`
// {impl}`requirements.authoring.site_prompt`
// {impl}`requirements.authoring.habeas_background`
// {impl}`requirements.authoring.judgment_rules`
// {impl}`requirements.authoring.credentials`
fn initial_prompt(sources: &AssessmentSources) -> io::Result<Prompt> {
    let mandatory = serde_json::to_string_pretty(&sources.model_mandatory_inputs())?;
    let mut values = shared_blocks().to_vec();
    values.push(("mandatory_inputs", &mandatory));
    Ok(match &sources.subject_kind {
        AssessmentKind::Definition(kind, distributed) => {
            let acknowledgments = serde_json::to_string_pretty(&sources.model_acknowledgments())?;
            let task = subject_task(kind);
            let distributed = distributed_task(kind, *distributed);
            values.extend([
                ("subject_kind", sources.subject_kind.noun()),
                ("subject_name", &sources.subject_name),
                ("subject_task", &task),
                ("distributed_task", &distributed),
                ("acknowledgments", &acknowledgments),
            ]);
            Prompt::filled("initial_prompt", &values)
        }
        AssessmentKind::Citation(item) => {
            let citations = serde_json::to_string(&item.model_citations_value())?;
            values.extend([
                ("item_file", item.file.as_str()),
                ("item_selector", item.selector_label()),
                ("citations", &citations),
            ]);
            Prompt::filled("citation_prompt", &values)
        }
        AssessmentKind::Site(site, _) => {
            let matches = serde_json::to_string(&site.matches_value())?;
            values.extend([
                ("requirement_name", site.requirement.as_str()),
                ("site_file", site.file.as_str()),
                ("site_selector", site.selector_label()),
                ("matches", &matches),
                ("distributed_background", distributed_background()),
            ]);
            Prompt::filled("site_prompt", &values)
        }
    })
}
Input 10: outline src/authoring/mod.rs fn[verification_prompt]
/// The verifier's prompt for a determination and its rationale.
// {impl}`requirements.authoring.judgment_rules`
// {impl}`requirements.authoring.github_reads`
// {impl}`requirements.authoring.habeas_background`
// {impl}`requirements.authoring.prompt_parts`
fn verification_prompt(
    sources: &AssessmentSources,
    determination: &Judgment,
    rationale: &str,
) -> io::Result<Prompt> {
    let site = matches!(sources.subject_kind, AssessmentKind::Site(..));
    let instructions = review_instructions(&initial_prompt(sources)?, site);
    let mandatory = serde_json::to_string_pretty(&sources.model_mandatory_inputs())?;
    let determination = determination.to_value().to_string();
    let mut values = shared_blocks().to_vec();
    if site {
        // A site review's verifier gets no reference roles.
        values.retain(|(name, _)| *name != "reference_roles");
        values.push(("reference_roles", ""));
    }
    values.extend([
        ("subject_kind", sources.subject_kind.noun()),
        ("subject_name", sources.subject_name.as_str()),
        ("determination", &determination),
        ("rationale", rationale.trim()),
        ("review_instructions", &instructions),
        ("site_step", if site { SITE_STEP } else { "" }),
        ("mandatory_inputs", &mandatory),
    ]);
    Ok(Prompt::filled("verifier_prompt", &values))
}

Tests

Input 2: outline src/authoring/mod.rs mod[tests]/fn[initial_prompt_carries_the_review_criteria]
    // {test}`requirements.ci.review_criteria`
    // {test}`requirements.authoring.requirement_task`
    // {test}`requirements.authoring.testing_bar`
    // {test}`requirements.authoring.example_task`
    // {test}`requirements.authoring.judgment_rules`
    // {test}`requirements.authoring.habeas_background`
    // {test}`requirements.examples.evidence`
    // {test}`requirements.examples.definition`
    #[test]
    fn initial_prompt_carries_the_review_criteria() {
        let project = inputs::tests::project();
        let sources = AssessmentSources::prepare(project.path(), "requirements.ready").unwrap();
        let prompt = initial_prompt(&sources).unwrap().joined();
        for criterion in [
            "Subject: requirement requirements.ready\nJudge against: the subject's text.",
            approved_text("habeas_background", 0),
            approved_text("habeas_background", 1),
            approved_text("judgment_rules", 0),
            approved_text("requirement_task", 0),
            approved_text("testing_bar", 0),
            "Derive testable obligations and expected outcomes from each MUST, MUST NOT,",
            "Testing criteria:",
            "The project MUST be ready.",
        ] {
            assert!(
                prompt.contains(criterion),
                "missing {criterion:?} in:\n{prompt}"
            );
        }
        // The testing criteria follow the requirement task.
        assert!(prompt.contains(&format!(
            "{}\n{}",
            approved_text("requirement_task", 0),
            approved_text("testing_bar", 0)
        )));
        assert!(!prompt.contains(approved_text("example_task", 0)));
        assert!(!prompt.contains("This subject is a distributed requirement."));
        assert!(!prompt.contains(distributed_background()));
        assert!(!prompt.contains("{{"), "{prompt}");

        // An example's task replaces the requirement task.
        let requirements = project.path().join("md/requirements.md");
        let mut book = fs::read_to_string(&requirements).unwrap();
        let cite = "{cite}`requirements.ready`";
        book.push_str(&format!(
            "\n:::{{example}} case\nA ready case. {cite}\n:::\n"
        ));
        fs::write(&requirements, book).unwrap();
        let sources = AssessmentSources::prepare(project.path(), "requirements.case").unwrap();
        let prompt = initial_prompt(&sources).unwrap().joined();
        assert!(
            prompt.contains("Subject: example requirements.case"),
            "{prompt}"
        );
        assert!(
            prompt.contains(approved_text("example_task", 0)),
            "{prompt}"
        );
        assert!(
            prompt.contains("First check that it describes a concrete case\nwith expected behavior; a missing concrete case or expected behavior is a gap."),
            "{prompt}"
        );
        assert!(
            !prompt.contains(approved_text("requirement_task", 0)),
            "{prompt}"
        );
        assert!(
            !prompt.contains(approved_text("testing_bar", 0)),
            "{prompt}"
        );
        assert!(!prompt.contains("Testing criteria:"), "{prompt}");
        assert!(!prompt.contains("{{"), "{prompt}");
    }
Input 3: outline src/authoring/mod.rs mod[tests]/fn[disagreeing_assessments_verify_the_less_favorable_one]
    // {test}`requirements.authoring.confirmation`
    // {test}`requirements.authoring.verifier_prompt`
    // {test}`requirements.authoring.verifier_outcome`
    // {test}`requirements.authoring.habeas_background`
    // {test}`requirements.authoring.judgment_rules`
    #[tokio::test]
    async fn disagreeing_assessments_verify_the_less_favorable_one() {
        for (turns, recorded, kept, conclusion, less) in [
            // A real, unacknowledged gap records false with the less favorable
            // (second) assessment's rationale.
            (
                vec![
                    judgment(json!(true), "Looks complete."),
                    judgment(json!(false), "The empty case is unhandled."),
                    verdict(true, &[], "The empty case panics."),
                ],
                Judgment::False,
                1,
                "found an unacknowledged real gap",
                1,
            ),
            // A false assessment ranks below an acknowledged gap.
            (
                vec![
                    judgment(json!({"FIXME": ["#7"]}), "Only the known gap."),
                    judgment(json!(false), "An additional unacknowledged gap."),
                    verdict(true, &[], "The additional gap is real."),
                ],
                Judgment::False,
                1,
                "found an unacknowledged real gap",
                1,
            ),
            // A FIXME whose gap is real but unacknowledged also becomes false.
            (
                vec![
                    judgment(json!({"FIXME": ["#7"]}), "Issue 7 is open."),
                    judgment(json!(true), "Complete."),
                    verdict(true, &[], "Issue 7 is closed."),
                ],
                Judgment::False,
                0,
                "found an unacknowledged real gap",
                0,
            ),
            // Real and acknowledged gaps record FIXME with the verifier's
            // acknowledgments.
            (
                vec![
                    judgment(json!(true), "Looks complete."),
                    judgment(json!(false), "The empty case is unhandled."),
                    verdict(true, &["example/queue#9"], "A fixme tracks it."),
                ],
                Judgment::Fixme(vec!["example/queue#9".into()]),
                1,
                "found its real gaps all acknowledged",
                1,
            ),
            // No real gap records the more favorable (second) assessment.
            (
                vec![
                    judgment(json!({"FIXME": ["#7"]}), "Issue 7 is open."),
                    judgment(json!(true), "Complete."),
                    verdict(false, &[], "Issue 7 does not affect this."),
                ],
                Judgment::True,
                1,
                "found none of its claimed gaps real",
                0,
            ),
            (
                vec![
                    judgment(json!({"FIXME": ["#7"]}), "Only the known gap."),
                    judgment(json!(false), "An additional unacknowledged gap."),
                    verdict(false, &[], "The additional gap is not real."),
                ],
                Judgment::Fixme(vec!["#7".into()]),
                0,
                "found none of its claimed gaps real",
                1,
            ),
            (
                vec![
                    judgment(json!(true), "Complete."),
                    judgment(json!({"FIXME":["#7"]}), "Issue 7 is open."),
                    verdict(true, &["#7"], "The known gap is real and acknowledged."),
                ],
                Judgment::Fixme(vec!["#7".into()]),
                1,
                "found its real gaps all acknowledged",
                1,
            ),
            (
                vec![
                    judgment(json!(true), "Complete."),
                    judgment(json!({"FIXME":["#7"]}), "Issue 7 is open."),
                    verdict(false, &[], "The known gap does not apply."),
                ],
                Judgment::True,
                0,
                "found none of its claimed gaps real",
                1,
            ),
        ] {
            let (result, provider, logs) = confirmed(turns.clone(), true).await;
            let (judgment, record) = result.unwrap();
            assert_eq!(judgment, recorded);
            assert_eq!(record["determination"], judgment.to_value());
            let rationale = record["rationale"].as_str().unwrap();
            assert!(
                rationale.starts_with(turns[kept].1["rationale"].as_str().unwrap()),
                "{rationale}"
            );
            assert!(
                rationale.contains("the assessments disagreed"),
                "{rationale}"
            );
            assert!(rationale.contains(conclusion), "{rationale}");
            assert!(
                rationale.contains(turns[2].1["rationale"].as_str().unwrap()),
                "{rationale}"
            );

            // Prompts are recorded as serialized requests, so expected text is
            // compared in its JSON-escaped form.
            // The verifier receives the less favorable determination, its
            // rationale, and the criteria it applied, with the source tools
            // and submit_verification only.
            let prompts = provider.prompts();
            assert_eq!(prompts.len(), 3);
            let determination = turns[less].1["determination"].to_string();
            let less_rationale = turns[less].1["rationale"].as_str().unwrap();
            let escaped = serde_json::to_string(&format!(
                "The reviewer judged requirement requirements.ready as {determination}."
            ))
            .unwrap();
            let (text, tools) = &prompts[2];
            assert!(text.contains(escaped.trim_matches('"')), "{text}");
            assert!(text.contains(less_rationale), "{text}");
            assert!(
                text.contains("Judge against: the subject's text."),
                "{text}"
            );
            assert!(text.contains("Derive testable obligations"), "{text}");
            assert!(text.contains("# Mandatory inputs"), "{text}");
            // The verifier of a requirement carries both background texts,
            // the judgment rules, and the subject's mandatory input.
            let text = serde_json::from_str::<Value>(text).unwrap().to_string();
            for background in [
                approved_text("habeas_background", 0),
                approved_text("habeas_background", 1),
                approved_text("judgment_rules", 0),
                "\"requirements\": \"requirements.ready\"",
                "The project MUST be ready.",
            ] {
                let background = serde_json::to_string(background).unwrap();
                assert!(text.contains(background.trim_matches('"')), "{text}");
            }
            assert!(!text.contains("{{"), "{text}");
            assert!(tools.contains(&"submit_verification".to_owned()));
            assert!(tools.contains(&"habeas".to_owned()));
            assert!(!tools.contains(&"submit_judgment".to_owned()));
            // The verifier has the assessments' source tools.
            let source_tools = |tools: &[String]| {
                tools
                    .iter()
                    .filter(|tool| !tool.starts_with("submit_"))
                    .cloned()
                    .collect::<Vec<_>>()
            };
            assert_eq!(source_tools(tools), source_tools(&prompts[0].1));

            assert_eq!(logs.len(), 3);
            assert_eq!(logs[2]["subject"], "requirements.ready (verification)");
            assert_eq!(logs[2]["outcome"], "completed");
        }
    }
Input 4: outline src/authoring/mod.rs mod[tests]/fn[verifier_prompts_name_examples_and_citation_reviews]
    // {test}`requirements.authoring.verifier_prompt`
    // {test}`requirements.authoring.habeas_background`
    // {test}`requirements.authoring.judgment_rules`
    #[test]
    fn verifier_prompts_name_examples_and_citation_reviews() {
        let project = inputs::tests::project();
        let cite = "{cite}`requirements.ready`";
        let requirements = project.path().join("md/requirements.md");
        let mut book = fs::read_to_string(&requirements).unwrap();
        book.push_str(&format!(
            "\n:::{{example}} case\nA ready case. {cite}\n:::\n"
        ));
        fs::write(&requirements, book).unwrap();
        fs::write(
            project.path().join("src/lib.rs"),
            format!("// {cite}\n// :::{{cite}} habeas:util\n// Formats output.\n// :::\nfn helper() {{}}\n"),
        )
        .unwrap();
        for (subject, header, named) in [
            (
                "requirements.case",
                "The reviewer judged example requirements.case as false.",
                "Subject: example requirements.case",
            ),
            (
                "citations:src/lib.rs#fn[helper]",
                "The reviewer judged citation review citations:src/lib.rs#fn[helper] as false.",
                "Item under review: src/lib.rs fn[helper]\nCitations to check:",
            ),
        ] {
            let sources = AuthoringSubject::parse(subject)
                .sources(project.path())
                .unwrap();
            let parts = verification_prompt(&sources, &Judgment::False, "A claimed gap.").unwrap();
            let prompt = parts.joined();
            let initial = initial_prompt(&sources).unwrap();
            // The reviewer's criteria are its subject message between the
            // "# Subject" and "# Mandatory inputs" headings, then its task.
            let subject_section = prompt_section(&initial.subject, "Subject").trim();
            let first = prompt_section(&initial.system, "Task");
            assert!(
                parts.subject.contains(&format!(
                    "The criteria the reviewer applied:\n\n{subject_section}\n\n{}",
                    prompt_section(&initial.system, "Your task")
                )),
                "{prompt}"
            );
            for expected in [
                header,
                named,
                "A claimed gap.",
                approved_text("habeas_background", 0),
                approved_text("habeas_background", 1),
                approved_text("judgment_rules", 0),
            ] {
                assert!(
                    prompt.contains(expected),
                    "missing {expected:?} in:\n{prompt}"
                );
            }
            // The rationale and subject stay out of the system prompt.
            assert!(!parts.system.contains("A claimed gap."), "{prompt}");
            assert!(!parts.system.contains(&sources.subject_name), "{prompt}");
            assert!(!prompt.contains(first), "{prompt}");
            assert!(!prompt.contains(SITE_STEP), "{prompt}");
            // Every mandatory input is delivered.
            let mandatory =
                serde_json::to_string_pretty(&sources.model_mandatory_inputs()).unwrap();
            assert!(prompt.contains(&mandatory), "{prompt}");
            assert!(!prompt.contains("{{"), "{prompt}");
        }
    }
Input 5: outline src/authoring/mod.rs mod[tests]/fn[citation_reviews_use_their_prompt_and_record_the_item_and_citations]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[citation_reviews_use_their_prompt_and_record_the_item_and_citations]
  • Kind: fn
  • src/authoring/mod.rs:4261–4416
    // {test}`requirements.authoring.citation_prompt`
    // {test}`requirements.references.citation_review`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring.habeas_background`
    // {test}`requirements.authoring.judgment_rules`
    // {test}`requirements.authoring.adaptive`
    #[tokio::test]
    async fn citation_reviews_use_their_prompt_and_record_the_item_and_citations() {
        let project = inputs::tests::project();
        let cite = "{cite}`requirements.ready`";
        fs::write(
            project.path().join("src/lib.rs"),
            format!(
                "// {cite}\n// :::{{cite}} habeas:util\n// Formats output for the caller.\n// :::\nfn helper() {{}}\n"
            ),
        )
        .unwrap();
        let subject = AuthoringSubject::parse("citations:src/lib.rs#fn[helper]");
        assert_eq!(
            subject.evidence_path(project.path()),
            project
                .path()
                .join("evidence/citations/src/lib.rs/fn[helper].json")
        );
        let mut sources = subject.sources(project.path()).unwrap();
        assert!(!sources.has_applicable_fixme);
        let mandatory = sources.mandatory_inputs().to_vec();
        assert_eq!(mandatory[0]["file"], "src/lib.rs");
        assert_eq!(mandatory[0]["item"], "fn[helper]");
        assert_eq!(mandatory[1]["requirements"], "requirements.ready");
        assert_eq!(mandatory[2]["builtin"], "habeas:util");
        assert!(
            mandatory[2]["text"][0]
                .as_str()
                .unwrap()
                .starts_with("Cite this on an item that serves")
        );

        let state = tempfile::tempdir().unwrap();
        let mut usage = UsageLog::start(state.path(), project.path(), &subject.label()).unwrap();
        let provider = RecordingProvider::new(vec![judgment(json!(true), "Both are sensible.")]);
        let (_, record) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        let prompts = provider.prompts();
        let expected: Vec<_> = tool_definitions_with("submit_judgment", false)
            .unwrap()
            .into_iter()
            .map(|tool| tool.name)
            .collect();
        assert_eq!(prompts[0].1, expected);
        let duplicate = json!({"determination":true,"rationale":"Both are sensible."});
        let duplicate_provider = ScriptedProvider {
            turns: vec![vec![
                ("submit_judgment", duplicate.clone()),
                ("submit_judgment", duplicate),
            ]],
            requests: RefCell::default(),
        };
        let mut duplicate_sources = subject.sources(project.path()).unwrap();
        assert!(
            assess(&duplicate_provider, &mut duplicate_sources, &mut usage)
                .await
                .unwrap_err()
                .to_string()
                .contains("exactly once")
        );
        let prompt = &prompts[0].0;
        assert!(
            prompt.contains("Review one source item's citations."),
            "{prompt}"
        );
        assert!(
            prompt.contains("Item under review: src/lib.rs fn[helper]"),
            "{prompt}"
        );
        assert!(
            prompt.contains("Formats output for the caller."),
            "{prompt}"
        );
        // The initial request carries the complete mandatory set.
        assert!(
            prompt.contains(mandatory[0]["hash"].as_str().unwrap()),
            "{prompt}"
        );
        assert!(prompt.contains("The project MUST be ready."), "{prompt}");
        assert!(
            prompt.contains("Cite this on an item that serves"),
            "{prompt}"
        );
        // Prompts are recorded as serialized requests.
        for background in [
            approved_text("habeas_background", 0),
            approved_text("habeas_background", 1),
            approved_text("judgment_rules", 0),
        ] {
            let background = serde_json::to_string(background).unwrap();
            assert!(prompt.contains(background.trim_matches('"')), "{prompt}");
        }
        assert!(!prompt.contains("{{"), "{prompt}");

        let citations = json!([
            {"role": "cite", "name": "requirements.ready", "commentary": ""},
            {"role": "cite", "name": "habeas:util", "commentary": "Formats output for the caller."}
        ]);
        let request: Value = serde_json::from_str(prompt).unwrap();
        // Compare the actual placeholder payload, rather than text which
        // could also appear independently in the mandatory source inputs.
        let user = request["chat_history"]
            .as_array()
            .unwrap()
            .iter()
            .find(|message| message["role"] == "user")
            .unwrap();
        let subject_text = user["content"][0]["text"].as_str().unwrap();
        let payload = subject_text
            .lines()
            .find_map(|line| line.strip_prefix("Citations to check: "))
            .unwrap();
        assert_eq!(serde_json::from_str::<Value>(payload).unwrap(), citations);
        assert_eq!(record["file"], "src/lib.rs");
        assert_eq!(record["item"], "fn[helper]");
        assert_eq!(record["citations"], citations);
        assert_eq!(record["determination"], true);
        let inputs = record["inputs"].as_array().unwrap();
        assert!(inputs.iter().all(|input| input.get("builtin").is_none()));
        assert_eq!(inputs.len(), 2, "{inputs:#?}");

        // The recorded review satisfies validation for its item.
        let path = subject.evidence_path(project.path());
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, record.to_string()).unwrap();
        let errors = crate::validate_repository(project.path()).unwrap().errors;
        assert!(
            !errors
                .iter()
                .any(|error| error.starts_with("evidence/citations/")),
            "{errors:#?}"
        );

        // A name without a selector reviews the file's root node.
        assert!(matches!(
            AuthoringSubject::parse("citations:notes.txt"),
            AuthoringSubject::Citation { file, item } if file == "notes.txt" && item.is_empty()
        ));

        // The root node's selector is shown as `<root>` in the prompt.
        fs::write(project.path().join("notes.txt"), format!("Notes. {cite}\n")).unwrap();
        let sources = AuthoringSubject::parse("citations:notes.txt")
            .sources(project.path())
            .unwrap();
        let prompt = initial_prompt(&sources).unwrap().joined();
        assert!(
            prompt.contains("Item under review: notes.txt <root>"),
            "{prompt}"
        );
        assert!(!prompt.contains("{{"), "{prompt}");
    }
Input 6: outline src/authoring/mod.rs mod[tests]/fn[a_distributed_requirement_task_continues_with_the_filled_distributed_task]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[a_distributed_requirement_task_continues_with_the_filled_distributed_task]
  • Kind: fn
  • src/authoring/mod.rs:4418–4462
    // {test}`requirements.authoring.distributed_task`
    // {test}`requirements.authoring.habeas_background`
    // {test}`requirements.authoring.initial_prompt`
    // {test}`requirements.ci.review_criteria`
    #[test]
    fn a_distributed_requirement_task_continues_with_the_filled_distributed_task() {
        let project =
            crate::sites::tests::project(crate::sites::tests::RULE, crate::sites::tests::SOURCE);
        let sources = AssessmentSources::prepare(project.path(), "requirements.rule").unwrap();
        let prompt = initial_prompt(&sources).unwrap();
        let task = fill(
            approved_text("distributed_task", 0),
            &[("distributed_background", distributed_background())],
        );
        assert!(task.starts_with(distributed_background()), "{task}");
        // The requirement task stays in the system prompt; the distributed
        // task follows the subject line in the subject message.
        assert!(
            prompt.system.contains(&format!(
                "{}\n{}\n\n# How to judge",
                approved_text("requirement_task", 0),
                approved_text("testing_bar", 0)
            )),
            "{}",
            prompt.system
        );
        assert!(!prompt.system.contains(&task), "{}", prompt.system);
        assert!(
            prompt.subject.contains(&format!(
                "Judge against: the subject's text.\n\n{task}\n\n# Acknowledgments\n\n[]\n\n# Mandatory inputs"
            )),
            "{}",
            prompt.subject
        );
        assert!(
            prompt
                .system
                .contains(approved_text("habeas_background", 1))
        );
        assert!(!prompt.joined().contains("{{"), "{}", prompt.joined());
        // The verifier's criteria carry the distributed task too.
        let verifier = verification_prompt(&sources, &Judgment::False, "A gap.").unwrap();
        assert!(verifier.subject.contains(&task), "{}", verifier.subject);
        assert!(!verifier.system.contains(&task), "{}", verifier.system);
    }
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/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()));
        }
    }

Other sources

Input 1: 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.
```
:::