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

Requirements index · View definition

evidence Valid

Requirement

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.

Rationale

I judge the tests adequate for requirements.authoring.prompt_parts. I did not request any implementation source. I judged from the supplied test text only.

Obligations derived from the text

  1. Each conversation sends a system prompt followed by one user message.
  2. The system prompt is filled from the first block of the kind’s approved prompt text. The subject message is filled from the second block.
  3. The kinds are requirement, example, citation review, site review, and a verifier of each.
  4. A system prompt is identical for every assessment of its kind.
  5. Every placeholder whose value depends on the subject is in the subject message.

Coverage

  • src/authoring/mod.rs#mod[tests]/fn[subjects_of_one_kind_share_a_byte_identical_system_prompt] covers obligations 1–5 across all kinds.
    • It builds two distinct subjects for each of requirement (requirements.other and requirements.second), example (first_case and second_case), citation (cites_one and cites_two) and site (check_one and check_two).
    • For each pair it calls initial_prompt. Its assert_opening helper checks that block 0 of the approved template matches system and block 1 matches subject. Every literal segment must match exactly, and only {{…}} placeholders may expand. No unexpanded {{ may remain.
    • assert_opening also builds the request and asserts chat_history is exactly [Message::system(system), Message::user(subject)]. That covers the role order and the single user message.
    • It asserts one.system == two.system. It also asserts the subjects differ and that one.subject starts with # Subject. It asserts the system prompt does not contain the subject name.
    • For every pair it also calls verification_prompt with different judgments (Judgment::False and a Fixme judgment) and different rationales. It runs assert_opening against verifier_prompt and asserts the two verifier system prompts are equal. It asserts the verifier’s subject message carries the rationale text and the system prompt does not. This covers a verifier for each of the four kinds.
  • tests/authoring_cli.rs#fn[initial_prompt_substitutes_subject_and_mandatory_inputs_into_the_template] is an end-to-end check for requirement and example runs through a fake server.
    • It asserts the wire system prompt equals the first approved block with only the declared substitutions.
    • It asserts that system prompt does not contain the subject name.
    • It asserts the subject message equals the second block, with the subject name, kind, acknowledgments and mandatory inputs substituted.
  • tests/authoring_cli.rs#fn[claude_requests_carry_cache_checkpoints_and_record_cache_usage] and tests/authoring_cli.rs#fn[prompt_and_tools] are supporting tests. They check that the system prompt and messages reach the wire and are not altered by cache checkpoints. src/authoring/mod.rs#impl[Prompt]/fn[joined] is a test helper.

Assessment A hypothetical bug could put a subject-dependent value (the name, the subject text or the judgment) in the system prompt. The equality assertions across differing subjects would catch it, as would the exact-match assertion in the CLI test. A bug that swapped the blocks or the roles would fail the regex match and the chat_history equality. No gap is evident, and there are no acknowledgments to consider.

Inputs

Tests

Input 2: outline src/authoring/mod.rs impl[Prompt]/fn[joined]
    /// Both parts, for tests that look for text wherever it is sent.
    // {test}`requirements.authoring.prompt_parts`
    #[cfg(test)]
    fn joined(&self) -> String {
        format!("{}\n\n{}", self.system, self.subject)
    }
Input 3: 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 4: outline tests/authoring_cli.rs fn[initial_prompt_substitutes_subject_and_mandatory_inputs_into_the_template]
// {test}`requirements.authoring.initial_prompt`
// {test}`requirements.authoring.prompt_parts`
// {test}`requirements.authoring.fixme_inputs`
// {test}`requirements.authoring.invocation`
#[test]
fn initial_prompt_substitutes_subject_and_mandatory_inputs_into_the_template() {
    let template = approved_text("initial_prompt", 0);
    let subject_template = approved_text("initial_prompt", 1);
    for (subject, kind) in [
        (SUBJECT, "requirement"),
        ("requirements.ready_case", "example"),
    ] {
        let server = Server::start(vec![reply(vec![call(
            "submit",
            "submit_judgment",
            json!({"determination":true,"rationale":"covered"}),
        )])]);
        let fixture = Fixture::new(&server.endpoint);
        fs::write(
            fixture.project.join("md/requirements.md"),
            format!(
                ":::{{req}} ready\n{REQUIREMENT}\n:::\n\n:::{{example}} ready_case\nCalling ready succeeds. {{cite}}`requirements.ready`\n:::\n"
            ),
        )
        .unwrap();
        let output = fixture.run(&["author", subject]);
        assert!(output.status.success(), "{output:?}");
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.starts_with(&format!("{subject}: ollama / {MODEL}")),
            "{stdout}"
        );
        let evidence_path = stdout
            .lines()
            .find_map(|line| line.strip_prefix("Evidence: "))
            .unwrap();
        assert_eq!(
            std::path::Path::new(evidence_path),
            fixture.project.join(format!("evidence/{subject}.json"))
        );
        let record: Value = serde_json::from_slice(&fs::read(evidence_path).unwrap()).unwrap();
        let field = if kind == "requirement" {
            "requirement"
        } else {
            "example"
        };
        let other = if kind == "requirement" {
            "example"
        } else {
            "requirement"
        };
        assert!(record.get(other).is_none(), "{record}");
        assert_eq!(
            record[field],
            if kind == "requirement" {
                REQUIREMENT
            } else {
                "Calling ready succeeds. {cite}`requirements.ready`"
            }
        );
        let usage_path = stdout
            .lines()
            .find_map(|line| line.strip_prefix("Usage: "))
            .unwrap();
        assert!(std::path::Path::new(usage_path).is_file(), "{stdout}");
        let requests = server.finish();
        let (system, prompt) = opening(&requests[0].body);

        let task = if kind == "requirement" {
            format!(
                "{}\n{}",
                approved_text("requirement_task", 0),
                approved_text("testing_bar", 0)
            )
        } else {
            approved_text("example_task", 0).to_owned()
        };
        // Apart from the substitutions, the system prompt is the first block
        // as written, with nothing that names the subject.
        let expected = template
            .replace("{{subject_kind}}", kind)
            .replace(
                "{{habeas_background}}",
                approved_text("habeas_background", 0),
            )
            .replace("{{reference_roles}}", approved_text("habeas_background", 1))
            .replace("{{subject_task}}", &task)
            .replace("{{judgment_rules}}", approved_text("judgment_rules", 0));
        assert!(!expected.contains("{{"), "{expected}");
        assert_eq!(system, expected);
        assert!(!system.contains(subject), "{system}");
        let acknowledgments: Value = serde_json::from_str(
            prompt
                .split_once("# Acknowledgments\n\n")
                .unwrap()
                .1
                .split_once("\n\n# Mandatory inputs")
                .unwrap()
                .0,
        )
        .unwrap();
        if kind == "requirement" {
            assert_eq!(
                acknowledgments,
                json!([{
                    "body": ":github: example/app#125\n One acknowledged gap.",
                    "file": "src/lib.rs",
                    "issues": [{"reference": "example/app#125", "state": "open"}],
                    "item": "fn[ready]",
                }])
            );
        } else {
            assert_eq!(acknowledgments, json!([]));
        }
        let (before, after) = subject_template.split_once("{{mandatory_inputs}}").unwrap();
        // The subject is not distributed, so its distributed task is empty.
        let before = before
            .replace("{{subject_kind}}", kind)
            .replace("{{subject_name}}", subject)
            .replace("{{distributed_task}}", "")
            .replace(
                "{{acknowledgments}}",
                &serde_json::to_string_pretty(&acknowledgments).unwrap(),
            );
        assert!(
            before.contains(&format!("\nSubject: {kind} {subject}\n")),
            "{before}"
        );
        assert!(!before.contains("{{") && !after.contains("{{"));
        // Apart from the substitutions, the subject message is the second
        // block as written.
        assert!(prompt.starts_with(&before), "{prompt}");
        assert!(prompt.ends_with(after), "{prompt}");
        let rendered = &prompt[before.len()..prompt.len() - after.len()];

        // The mandatory inputs are a JSON array of evidence inputs.
        let inputs: Vec<Value> = serde_json::from_str(rendered).unwrap();
        assert!(!inputs.is_empty());
        for input in &inputs {
            let forms = [
                ("file", &["item", "hash", "text"][..]),
                ("requirements", &["matches", "text"][..]),
                ("definition", &["text"][..]),
            ];
            let matching = forms
                .iter()
                .filter(|(key, _)| input.get(key).is_some())
                .collect::<Vec<_>>();
            assert_eq!(matching.len(), 1, "one evidence-input form: {input}");
            for field in matching[0].1 {
                assert!(input.get(field).is_some(), "{input} lacks {field}");
            }
        }
        let defined = |name: &str| {
            inputs
                .iter()
                .any(|input| input["definition"] == name || input["requirements"] == name)
        };
        assert!(defined(subject), "{inputs:?}");
        if kind == "example" {
            assert!(defined(SUBJECT), "cited requirement supplied: {inputs:?}");
        } else {
            assert!(defined("terms.readiness"), "{inputs:?}");
        }
    }
}
Input 5: outline tests/authoring_cli.rs fn[claude_requests_carry_cache_checkpoints_and_record_cache_usage]
// {test}`requirements.authoring.cache_checkpoints`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.prompt_parts`
#[test]
fn claude_requests_carry_cache_checkpoints_and_record_cache_usage() {
    let checkpoint = json!({"cachePoint":{"type":"default"}});
    let (cached, usage) = bedrock_run("us.anthropic.claude-sonnet-4-5-20250929-v1:0");
    assert_eq!(cached.len(), 2);
    for body in &cached {
        // One checkpoint follows the system prompt...
        let system = body["system"].as_array().unwrap();
        assert_eq!(system.len(), 2, "{body}");
        assert!(system[0]["text"].as_str().unwrap().starts_with("# Task"));
        assert_eq!(system[1], checkpoint);
        // ...and one ends the last message, and there are no others.
        let messages = body["messages"].as_array().unwrap();
        let last = messages.last().unwrap()["content"].as_array().unwrap();
        assert_eq!(last.last().unwrap(), &checkpoint, "{body}");
        assert_eq!(body.to_string().matches("cachePoint").count(), 2, "{body}");
    }
    assert_eq!(cached[1]["messages"].as_array().unwrap().len(), 3);
    // The second request follows a reasoning turn and still ends in a
    // checkpoint.
    assert!(
        cached[1]["messages"][1]
            .to_string()
            .contains("reasoningContent")
    );
    // The checkpoints change nothing else: a model without caching gets the
    // same request without them.
    let (plain, _) = bedrock_run("fixture-uncached-model");
    assert!(!plain[0].to_string().contains("cachePoint"));
    for (cached, plain) in cached.iter().zip(&plain) {
        assert_eq!(&without_cache_points(cached), plain);
    }
    // Cache reads and writes are recorded per request and in total.
    let requests = usage["requests"].as_array().unwrap();
    assert_eq!(requests[0]["tokens"]["cached_input"], 0);
    assert_eq!(requests[0]["tokens"]["cache_creation_input"], 1000);
    assert_eq!(requests[1]["tokens"]["cached_input"], 1000);
    assert_eq!(requests[1]["tokens"]["cache_creation_input"], 200);
    assert_eq!(usage["tokens"]["cached_input"], 1000);
    assert_eq!(usage["tokens"]["cache_creation_input"], 1200);
}
Input 6: outline tests/authoring_cli.rs fn[prompt_and_tools]
/// Returns the first request's prompt and sorted tool definitions, removing
/// only the provider-specific envelopes around each definition.
// {test}`requirements.authoring.prompt_parts`
fn prompt_and_tools(body: &Value) -> (String, Vec<(String, String, Value)>) {
    let tools = body
        .get("toolConfig")
        .map_or(&body["tools"], |config| &config["tools"]);
    let mut tools = tools
        .as_array()
        .unwrap()
        .iter()
        .map(|tool| {
            let spec = tool
                .get("toolSpec")
                .or_else(|| tool.get("function"))
                .unwrap_or(tool);
            let parameters = spec
                .get("inputSchema")
                .map_or(&spec["parameters"], |schema| &schema["json"]);
            (
                spec["name"].as_str().unwrap().to_owned(),
                spec["description"].as_str().unwrap().to_owned(),
                parameters.clone(),
            )
        })
        .collect::<Vec<_>>();
    tools.sort_by(|left, right| left.0.cmp(&right.0));
    (prompt_text(body), tools)
}

Other sources

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