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

Requirements index · View definition

evidence Valid

Requirement

The harness MUST record the sources it supplies to the model, including mandatory inputs, additional reads, and selected search dependencies under cite requirements.authoring.finish_search.inputs, using the evidence input formats defined by cite requirements.ci.outline_inputs, cite requirements.ci.requirements_inputs, and cite requirements.definitions.inputs. The harness MUST create these records itself so ordinary evidence validation can check them later.

Rationale

I judge the tests adequate for requirements.authoring.delivered_inputs. Each obligation maps to at least one asserting test, and I found no requirement-violating behavior the reviewed tests would accept. I did not request implementation source.

Mandatory inputs are recorded.

  • tests/authoring_cli.rs#fn[stdout_emits_only_evidence_json_without_changing_project_files] asserts the evidence inputs contain a requirements input for the subject, a definition input (terms.readiness), and outline inputs for src/lib.rs.
  • tests/authoring_cli.rs#fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free] asserts the mandatory test item fn[ready_test] and the definition input are recorded. It also runs validate_repository and asserts no evidence error for the accepted record, so the recorded formats pass ordinary evidence validation. It also asserts that an altered record is rejected.
  • src/authoring/tools.rs#fn[declaration_text_reaches_the_model_redacted] shows mandatory inputs carrying the subject, a cited requirement, and terms.

Additional reads are recorded in the evidence input formats.

  • src/authoring/tools.rs#fn[reading_records_only_delivered_sources_and_their_terms] covers item reads and line-range reads. It asserts recorded outline inputs equal outline_input(...), which holds only file, selector and hash. It asserts recording is deduplicated and that nothing is recorded before record_inputs. It asserts failed reads and malformed request forms are errors. It asserts a read also records the terminology definitions.
  • src/authoring/tools.rs#fn[line_range_reads_record_the_innermost_covering_nodes] covers recording the innermost covering outline nodes, with no text or line numbers in the record. It covers plain-text line@ nodes as well.
  • src/authoring/tools.rs#fn[declaration_text_reaches_the_model_redacted] covers the requirements and definition read forms. It asserts that fresh.recorded_inputs() equals the read’s input plus its definitions, and that read.inputs equals the same list.
  • In the CLI test, failed reads (absent.txt) and directory listings are not recorded, and repeated reads are recorded once.

Selected search dependencies are recorded.

  • src/authoring/searches.rs#fn[selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads] covers selected tags producing an outline input with the delivered hash. It asserts a stale hash is detected by validate_input. It asserts accumulation across calls, harmless overlap with reads, and that an empty selection records nothing.
  • src/authoring/mod.rs#fn[a_helper_used_only_through_a_search_snippet_invalidates_saved_evidence_when_weakened] asserts that a helper selected only through a search snippet appears as a hash-only outline input. It also asserts that weakening the helper invalidates the evidence, and that unrelated items are not recorded.

Only supplied sources are recorded.

  • src/authoring/pages.rs#fn[paged_inputs_carry_their_definitions_and_deliver_only_their_own_inputs] asserts each page’s inputs equal that page’s own inputs plus definitions.
  • src/authoring/mod.rs#fn[only_inputs_on_delivered_pages_are_recorded] asserts that only inputs from pages actually delivered to the model end up in the evidence, and that undelivered entries do not.
  • tests/authoring_cli.rs#fn[implementation_discovery_has_no_text_or_evidence_until_the_model_requests_a_read] asserts that references discovery records nothing. It asserts the unread fn[ready] is recorded only after the read, and recorded once.

The harness creates the records itself. The tests build evidence only through harness paths such as record_inputs and the finish and read dispatch. They assert the result equals outline_input(...) and that the ordinary validators accept or reject it.

The text of the cited formats (requirements.ci.outline_inputs, requirements.ci.requirements_inputs, requirements.definitions.inputs) is context. Their own validation is not reassessed here.

Inputs

Tests

Input 6: outline src/authoring/mod.rs mod[tests]/fn[only_inputs_on_delivered_pages_are_recorded]
    // {test}`requirements.authoring.result_pages`
    // {test}`requirements.authoring.delivered_inputs`
    #[tokio::test]
    async fn only_inputs_on_delivered_pages_are_recorded() {
        let project = inputs::tests::project();
        let mut source = String::new();
        for index in 0..600 {
            source.push_str(&format!(
                "fn needle_{index}() {{\n    let text = \"padding padding padding\";\n}}\n\n"
            ));
        }
        fs::write(project.path().join("src/lib.rs"), source).unwrap();
        let mut sources = AssessmentSources::prepare(project.path(), "requirements.ready").unwrap();
        let state = tempfile::tempdir().unwrap();
        let mut usage =
            UsageLog::start(state.path(), project.path(), &sources.subject_name).unwrap();
        let provider = PagingProvider {
            requests: RefCell::default(),
        };
        let (_, evidence) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        let requests = provider.requests.borrow();
        assert_eq!(requests.len(), 3);
        let delivered = |request: &str| {
            (0..600)
                .filter(|index| request.contains(&format!("fn needle_{index}()")))
                .collect::<Vec<_>>()
        };
        let (first, second) = (delivered(&requests[1]), delivered(&requests[2]));
        assert!(!first.is_empty() && !second.is_empty());
        // The pages are consecutive and leave entries undelivered.
        assert_eq!(second[0], first.last().unwrap() + 1);
        let last = *second.last().unwrap();
        assert!(last < 599, "{last}");
        let recorded = evidence["inputs"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|input| input["item"].as_str())
            .filter_map(|item| item.strip_prefix("fn[needle_"))
            .map(|item| item.trim_end_matches(']').parse::<usize>().unwrap())
            .collect::<Vec<_>>();
        assert_eq!(recorded, (0..=last).collect::<Vec<_>>());
        let log: Value = serde_json::from_str(&fs::read_to_string(&usage.path).unwrap()).unwrap();
        assert_eq!(log["tool_calls"]["next_page"], 1);
    }
Input 7: outline src/authoring/mod.rs mod[tests]/fn[a_helper_used_only_through_a_search_snippet_invalidates_saved_evidence_when_weakened]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[a_helper_used_only_through_a_search_snippet_invalidates_saved_evidence_when_weakened]
  • Kind: fn
  • src/authoring/mod.rs:3153–3235
    // {test}`requirements.authoring.search_accounting.helper_freshness`
    // {test}`requirements.authoring.finish_search.snapshot`
    // {test}`requirements.authoring.finish_search.inputs`
    // {test}`requirements.authoring.delivered_inputs`
    #[tokio::test]
    async fn a_helper_used_only_through_a_search_snippet_invalidates_saved_evidence_when_weakened()
    {
        use SearchAction::{Call, Finish};
        let root = inputs::tests::project();
        let helper_source = "fn assert_refusal(bytes: &mut Vec<u8>) {\n    let before = bytes.clone();\n    assert!(!try_insert(bytes));\n    assert_eq!(*bytes, before);\n}";
        let source = format!(
            "{helper_source}\nfn try_insert(_bytes: &mut Vec<u8>) -> bool {{ false }}\n\
            // {{test}}`requirements.ready`\n#[test]\nfn refuses_without_change() {{\n\
                let mut bytes = vec![1, 2];\n    assert_refusal(&mut bytes);\n}}\nfn unrelated() {{}}\n"
        );
        fs::write(root.path().join("src/lib.rs"), &source).unwrap();
        let marked_test =
            crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[refuses_without_change]")
                .unwrap();
        let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let state = tempfile::tempdir().unwrap();
        let mut usage = UsageLog::start(state.path(), root.path(), &sources.subject_name).unwrap();
        let provider = SearchProvider {
            submit: "submit_judgment",
            turns: vec![
                vec![Call(
                    "ripgrep",
                    json!({"pattern":"assert_refusal","path":"src/lib.rs","context":5}),
                )],
                vec![Finish(0, vec!["1"])],
                vec![Call(
                    "submit_judgment",
                    json!({"determination":true,
                    "rationale":"The assert_refusal snippet asserts refusal and byte preservation."}),
                )],
            ],
            requests: RefCell::default(),
        };
        let (_, evidence) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        let inputs = evidence["inputs"].as_array().unwrap();
        let helper = inputs
            .iter()
            .find(|input| input["item"] == "fn[assert_refusal]")
            .unwrap();
        assert!(inputs.contains(&marked_test));
        assert!(!inputs.iter().any(|input| input["item"] == "fn[unrelated]"));
        assert!(helper.get("text").is_none());
        let mut errors = Vec::new();
        crate::evidence::validate_input(
            root.path(),
            &std::collections::BTreeMap::new(),
            &crate::inputs::OutlineCache::default(),
            helper,
            "helper",
            &mut errors,
        );
        assert!(errors.is_empty(), "{errors:?}");
        fs::write(
            root.path().join("src/lib.rs"),
            source.replace(helper_source, "fn assert_refusal(_bytes: &mut Vec<u8>) {}"),
        )
        .unwrap();
        assert_eq!(
            crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[refuses_without_change]")
                .unwrap(),
            marked_test
        );
        crate::evidence::validate_input(
            root.path(),
            &std::collections::BTreeMap::new(),
            &crate::inputs::OutlineCache::default(),
            helper,
            "helper",
            &mut errors,
        );
        assert!(
            errors.iter().any(|error| error.contains("hash")),
            "{errors:?}"
        );
        let log: Value = serde_json::from_str(&fs::read_to_string(&usage.path).unwrap()).unwrap();
        assert!(log["tool_calls"].get("habeas").is_none());
        assert_eq!(log["tool_calls"]["finish_search"], 1);
    }
Input 8: outline src/authoring/pages.rs mod[tests]/fn[paged_inputs_carry_their_definitions_and_deliver_only_their_own_inputs]
  • File: src/authoring/pages.rs
  • Selector: mod[tests]/fn[paged_inputs_carry_their_definitions_and_deliver_only_their_own_inputs]
  • Kind: fn
  • src/authoring/pages.rs:806–896
    // {test}`requirements.authoring.result_pages`
    // {test}`requirements.authoring.delivered_inputs`
    // {test}`requirements.definitions.authoring_inputs`
    // {test}`requirements.authoring.read_denial`
    #[test]
    // {test}`requirements.authoring.source_tools`
    fn paged_inputs_carry_their_definitions_and_deliver_only_their_own_inputs() {
        let root = project();
        fs::write(
            root.path().join("md/terms.md"),
            ":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
        )
        .unwrap();
        let term = role("term", "terms.value");
        let mut source = String::new();
        for index in 0..400 {
            // Only the last function uses the term, so only its page needs it.
            let comment = if index == 399 { term.as_str() } else { "plain" };
            source.push_str(&format!(
                "// {comment}\nfn needle_{index}() {{\n    let text = \"padding padding padding\";\n}}\n\n"
            ));
        }
        fs::write(root.path().join("src/lib.rs"), source).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        let error = dispatch_paged(&sources, &mut pages, "next_page", &json!({}))
            .err()
            .unwrap();
        assert!(
            error.to_string().contains("token must be a string"),
            "{error}"
        );
        let first = dispatch_paged(
            &sources,
            &mut pages,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":1}),
        )
        .unwrap();
        let delivered = all_pages(&mut pages, first);
        let mut items = Vec::new();
        for (number, page) in delivered.iter().enumerate() {
            assert!(page.result.to_string().len() <= PAGE_LIMIT);
            let inputs = page.result["inputs"].as_array().unwrap();
            let definitions = page.result["definitions"].as_array().unwrap();
            // A page's delivery is exactly its own inputs and definitions.
            let mut expected = inputs.clone();
            expected.extend(definitions.iter().cloned());
            assert_eq!(page.inputs, expected);
            let last = number == delivered.len() - 1;
            assert_eq!(
                definitions
                    .iter()
                    .any(|definition| definition["definition"] == "terms.value"),
                last,
                "page {number}: {definitions:?}"
            );
            items.extend(
                inputs
                    .iter()
                    .map(|input| input["item"].as_str().unwrap().to_owned()),
            );
        }
        let expected = (0..400)
            .map(|index| format!("fn[needle_{index}]"))
            .collect::<Vec<_>>();
        assert_eq!(items, expected);

        // A token is unknown to another assessment, and an unknown token is
        // an explanatory tool error.
        let token = delivered[0].result["page"]["next"].as_str().unwrap();
        let mut other = ResultPages::default();
        let error = other.next_page(token).err().unwrap();
        assert!(error.to_string().contains("unknown page token"), "{error}");
        let error = dispatch_paged(
            &sources,
            &mut pages,
            "next_page",
            &json!({"token":"not-a-token"}),
        )
        .err()
        .unwrap();
        assert!(
            error.to_string().contains("valid only in the assessment"),
            "{error}"
        );
        // A token's page comes back in the same shape when asked again.
        let again =
            dispatch_paged(&sources, &mut pages, "next_page", &json!({"token": token})).unwrap();
        assert_eq!(again.result, delivered[1].result);
    }
Input 9: outline src/authoring/searches.rs mod[tests]/fn[selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads]
  • File: src/authoring/searches.rs
  • Selector: mod[tests]/fn[selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads]
  • Kind: fn
  • src/authoring/searches.rs:269–353
    // {test}`requirements.authoring.finish_search.completion`
    // {test}`requirements.authoring.finish_search.no_additional_source`
    // {test}`requirements.authoring.finish_search.inputs`
    // {test}`requirements.authoring.finish_search.snapshot`
    // {test}`requirements.authoring.finish_search.unselected`
    // {test}`requirements.authoring.finish_search.deduplication`
    // {test}`requirements.authoring.finish_search.repetition`
    // {test}`requirements.authoring.delivered_inputs`
    // {test}`requirements.authoring.finish_search`
    #[test]
    fn selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn first() { assert!(true); }\nfn second() {}\n",
        )
        .unwrap();
        let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        let result = search(&sources, &mut pages, "fn");
        let original =
            crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[first]").unwrap();
        // Mutation after delivery must not silently substitute a new hash.
        fs::write(
            root.path().join("src/lib.rs"),
            "fn first() {}\nfn second() {}\n",
        )
        .unwrap();
        let finish = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":["1","1"]}))
            .unwrap();
        assert_eq!(finish.inputs, [original]);
        assert_eq!(
            finish.result,
            json!({"search_id":result["search_id"],"finished":true})
        );
        assert!(finish.result.get("text").is_none());
        assert!(pages.outstanding_searches().is_empty());
        sources.record_inputs(&finish.inputs);
        assert_eq!(sources.recorded_inputs().len(), 1);
        assert_eq!(sources.recorded_inputs()[0]["item"], "fn[first]");
        let mut errors = Vec::new();
        crate::evidence::validate_input(
            root.path(),
            &BTreeMap::new(),
            &crate::inputs::OutlineCache::default(),
            &finish.inputs[0],
            "selected",
            &mut errors,
        );
        assert!(
            errors.iter().any(|error| error.contains("hash")),
            "{errors:?}"
        );

        let second = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":["2"]}))
            .unwrap();
        assert_eq!(
            second.inputs,
            [crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[second]").unwrap()]
        );
        sources.record_inputs(&second.inputs);
        assert_eq!(sources.recorded_inputs().len(), 2);
        // A separately read item can be included harmlessly, or omitted.
        let read = dispatch_paged(
            &sources,
            &mut pages,
            "habeas",
            &json!({"file":"src/lib.rs","item":"fn[second]"}),
        )
        .unwrap();
        sources.record_inputs(&read.inputs);
        let repeated = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":["2"]}))
            .unwrap();
        sources.record_inputs(&repeated.inputs);
        let empty = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":[]}))
            .unwrap();
        sources.record_inputs(&empty.inputs);
        assert_eq!(sources.recorded_inputs().len(), 2);
        assert_eq!(sources.recorded_inputs()[0]["item"], "fn[first]");
        assert_eq!(sources.recorded_inputs()[1]["item"], "fn[second]");
    }
Input 10: outline src/authoring/tools.rs mod[tests]/fn[reading_records_only_delivered_sources_and_their_terms]
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.file_discovery`
    // {test}`requirements.authoring.delivered_inputs`
    // {test}`requirements.definitions.authoring_inputs`
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn reading_records_only_delivered_sources_and_their_terms() {
        let root = project();
        fs::write(
            root.path().join("md/terms.md"),
            ":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
        )
        .unwrap();
        fs::write(
            root.path().join("src/lib.rs"),
            format!("// {}\nfn work() {{}}\n", role("term", "terms.value")),
        )
        .unwrap();
        let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let listing = dispatch(&sources, "list_files", &json!({"path":"src"})).unwrap();
        assert_eq!(listing.result, json!([{"path":"src/lib.rs","kind":"file"}]));
        assert!(listing.inputs.is_empty());
        let read = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","item":"fn[work]"}),
        )
        .unwrap();
        assert_eq!(read.inputs.len(), 2);
        assert_eq!(read.result["input"]["item"], "fn[work]");
        assert_eq!(read.result["input"]["kind"], "fn");
        // Results give the selector, never line numbers.
        assert!(read.result["input"].get("line_start").is_none());
        assert!(read.result["input"].get("line_end").is_none());
        assert_eq!(read.result["input"]["text"][1], "fn work() {}");
        assert_eq!(read.result["definitions"][0]["definition"], "terms.value");
        assert!(sources.recorded_inputs().is_empty());
        sources.record_inputs(&read.inputs);
        sources.record_inputs(&read.inputs);
        assert_eq!(sources.recorded_inputs().len(), 2);
        // Recorded outline inputs carry only the file, selector, and hash.
        assert_eq!(
            sources.recorded_inputs()[0],
            crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[work]").unwrap()
        );
        let eof = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":2}),
        )
        .unwrap();
        assert_eq!(eof.result["inputs"].as_array().unwrap().len(), 1);
        assert_eq!(eof.result["inputs"][0]["item"], "fn[work]");
        assert!(eof.result["inputs"][0].get("line_end").is_none());
        // A line-range read supplies the terminology of what it delivers.
        let fresh = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let lines = dispatch(
            &fresh,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":1}),
        )
        .unwrap();
        assert_eq!(lines.result["definitions"][0]["definition"], "terms.value");
        assert_eq!(lines.result["definitions"][0]["text"][1], ":phrase: value");
        assert_eq!(lines.inputs.len(), 2);
        assert!(
            dispatch(
                &sources,
                "habeas",
                &json!({"file":"src/lib.rs","line_start":3})
            )
            .is_err()
        );
        assert!(
            dispatch(
                &sources,
                "habeas",
                &json!({"file":"src/lib.rs","item":"fn[missing]"})
            )
            .is_err()
        );
        assert!(
            dispatch(
                &sources,
                "habeas",
                &json!({"file":"src/lib.rs","line_start":0})
            )
            .is_err()
        );
        // The provider-facing schema leaves selector fields optional; the
        // harness still rejects incomplete, mixed, and unknown request forms.
        for arguments in [
            json!({}),
            json!({"file":"src/lib.rs"}),
            json!({"line_start":1}),
            json!({"rust_file":"src/lib.rs","rust_item":"fn[work]"}),
            json!({"item":"fn[work]"}),
            json!({"file":"src/lib.rs","line_start":1,"definition":"terms.value"}),
            json!({"file":"src/lib.rs","item":"fn[work]","line_start":1}),
            json!({"file":"src/lib.rs","item":"fn[work]","requirements":"requirements.*"}),
            json!({"requirements":"requirements.*","definition":"terms.value"}),
            json!({"definition":"terms.value","extra":true}),
        ] {
            assert!(
                dispatch(&sources, "habeas", &arguments).is_err(),
                "unexpectedly accepted {arguments}"
            );
        }
        assert!(
            dispatch(
                &sources,
                "habeas",
                &json!({"requirements":"requirements.*"})
            )
            .is_ok()
        );
        assert!(dispatch(&sources, "habeas", &json!({"definition":"terms.value"})).is_ok());
    }
Input 11: outline src/authoring/tools.rs mod[tests]/fn[declaration_text_reaches_the_model_redacted]
    // {test}`requirements.authoring.redaction`
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.delivered_inputs`
    // {test}`requirements.definitions.authoring_inputs`
    #[test]
    fn declaration_text_reaches_the_model_redacted() {
        let root = project();
        let token = crate::redaction::tests::github_token();
        fs::write(
            root.path().join("md/terms.md"),
            format!(":::{{definition}} value\n:phrase: value\nA value such as {token}, with a {}.\n:::\n\n:::{{definition}} base\n:phrase: base\nA foundation.\n:::\n", role("term", "terms.base")),
        )
        .unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            format!(
                ":::{{req}} ready\nThe project MUST accept {token} as a {}.\n{}\n:::\n\n:::{{req}} other\nOther MUST reject\n{token}\non its own line.\n:::\n",
                role("term", "terms.value"),
                role("cite", "requirements.other"),
            ),
        )
        .unwrap();
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        // The subject, a cited requirement, and a term in the mandatory
        // inputs and so the prompt, with their line structure kept.
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mandatory = Value::Array(sources.mandatory_inputs().to_vec());
        let text = mandatory.to_string();
        assert!(!text.contains(&token), "{mandatory:#}");
        for expected in [
            "The project MUST accept [REDACTED:GitHub Token] as a",
            "A value such as [REDACTED:GitHub Token], with a",
            "\"Other MUST reject\",\"[REDACTED:GitHub Token]\",\"on its own line.\"",
        ] {
            assert!(
                text.contains(expected),
                "missing {expected:?}: {mandatory:#}"
            );
        }
        let prompt = super::super::initial_prompt(&sources).unwrap().joined();
        assert!(!prompt.contains(&token), "{prompt}");
        // Requirements and definition reads.
        for arguments in [
            json!({"requirements":"requirements.*"}),
            json!({"definition":"terms.value"}),
        ] {
            let read = dispatch(&sources, "habeas", &arguments).unwrap();
            let text = read.result.to_string();
            assert!(!text.contains(&token), "{arguments}: {:#}", read.result);
            assert!(
                text.contains("[REDACTED:GitHub Token]"),
                "{arguments}: {:#}",
                read.result
            );
            let definition = arguments.get("definition").is_some();
            assert_eq!(read.result["input"].get("definition").is_some(), definition);
            assert_eq!(
                read.result["input"].get("requirements").is_some(),
                !definition
            );
            assert!(read.result.get("inputs").is_none());
            let expected_terms = if definition {
                vec!["terms.base"]
            } else {
                vec!["terms.base", "terms.value"]
            };
            let terms: Vec<_> = read.result["definitions"]
                .as_array()
                .unwrap()
                .iter()
                .map(|input| input["definition"].as_str().unwrap())
                .collect();
            assert_eq!(terms, expected_terms);
            if definition {
                assert_eq!(read.result["input"]["definition"], "terms.value");
                assert_eq!(
                    read.result["input"]["text"],
                    json!([
                        ":::{definition} value",
                        ":phrase: value",
                        "A value such as [REDACTED:GitHub Token], with a {term}`terms.base`.",
                        ":::"
                    ])
                );
            } else {
                assert_eq!(read.result["input"]["requirements"], "requirements.*");
                assert_eq!(
                    read.result["input"]["matches"],
                    json!(["requirements.other", "requirements.ready"])
                );
                assert_eq!(
                    read.result["input"]["text"],
                    json!([
                        ":::{req} other",
                        "Other MUST reject",
                        "[REDACTED:GitHub Token]",
                        "on its own line.",
                        ":::",
                        "",
                        ":::{req} ready",
                        "The project MUST accept [REDACTED:GitHub Token] as a {term}`terms.value`.",
                        "{cite}`requirements.other`",
                        ":::"
                    ])
                );
            }
            let mut fresh = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
            assert!(fresh.recorded_inputs().is_empty());
            fresh.record_inputs(&read.inputs);
            fresh.record_inputs(&read.inputs);
            let mut expected = vec![read.result["input"].clone()];
            expected.extend(
                read.result["definitions"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .cloned(),
            );
            assert_eq!(fresh.recorded_inputs(), expected);
            assert_eq!(read.inputs, expected);
        }
    }
Input 12: outline src/authoring/tools.rs mod[tests]/fn[line_range_reads_record_the_innermost_covering_nodes]
    // {test}`requirements.authoring.source_tools`
    // {test}`requirements.authoring.delivered_inputs`
    // {test}`requirements.ci.outline_inputs`
    // {test}`requirements.authoring.no_line_numbers`
    #[test]
    fn line_range_reads_record_the_innermost_covering_nodes() {
        let root = project();
        let source = "use std::fmt;\n\nfn first() {}\n\nmod inner {\n    fn second() {\n        let x = 1;\n    }\n}\n";
        fs::write(root.path().join("src/lib.rs"), source).unwrap();
        let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        // Blank lines between nodes do not select their common ancestor.
        let read = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":3,"line_end":7}),
        )
        .unwrap();
        let items = read.result["inputs"]
            .as_array()
            .unwrap()
            .iter()
            .map(|input| {
                assert!(input.get("line_start").is_none());
                input["item"].as_str().unwrap()
            })
            .collect::<Vec<_>>();
        assert_eq!(
            items,
            ["fn[first]", "mod[inner]"],
            "line 5 is mod inner's own line, so the module is selected"
        );
        let nested = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":7,"line_end":7}),
        )
        .unwrap();
        assert_eq!(nested.result["inputs"][0]["item"], "mod[inner]/fn[second]");
        assert_eq!(
            nested.result["inputs"][0]["text"],
            json!(["    fn second() {", "        let x = 1;", "    }"])
        );
        sources.record_inputs(&nested.inputs);
        assert_eq!(
            sources.recorded_inputs(),
            [
                crate::inputs::outline_input(root.path(), "src/lib.rs", "mod[inner]/fn[second]")
                    .unwrap()
            ]
        );
        assert!(sources.recorded_inputs()[0].get("line_start").is_none());
        assert!(sources.recorded_inputs()[0].get("text").is_none());
        let whole = dispatch(
            &sources,
            "habeas",
            &json!({"file":"src/lib.rs","line_start":1}),
        )
        .unwrap();
        assert!(
            whole.result["inputs"][0]["item"]
                .as_str()
                .unwrap()
                .starts_with("use@")
        );
        assert_eq!(whole.result["inputs"].as_array().unwrap().len(), 3);
        fs::write(root.path().join("notes.txt"), "alpha\nbeta\ngamma\ndelta\n").unwrap();
        let plain = dispatch(
            &sources,
            "habeas",
            &json!({"file":"notes.txt","line_start":2,"line_end":3}),
        )
        .unwrap();
        let inputs = plain.result["inputs"].as_array().unwrap();
        assert_eq!(inputs.len(), 2);
        assert_eq!(inputs[0]["text"], json!(["beta"]));
        assert_eq!(inputs[1]["text"], json!(["gamma"]));
        assert_ne!(inputs[0]["item"], inputs[1]["item"]);
        for input in inputs {
            assert!(input["item"].as_str().unwrap().starts_with("line@"));
            assert!(input.get("line_start").is_none());
            assert!(input.get("line_end").is_none());
        }
    }
Input 13: outline tests/authoring_cli.rs fn[implementation_discovery_has_no_text_or_evidence_until_the_model_requests_a_read]
  • File: tests/authoring_cli.rs
  • Selector: fn[implementation_discovery_has_no_text_or_evidence_until_the_model_requests_a_read]
  • Kind: fn
  • tests/authoring_cli.rs:292–364
// {test}`requirements.authoring.mandatory_inputs`
// {test}`requirements.authoring.reference_index`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.fixme_inputs`
// {test}`requirements.authoring.complete_initial_bundle`
#[test]
fn implementation_discovery_has_no_text_or_evidence_until_the_model_requests_a_read() {
    let server = Server::start(vec![
        reply(vec![call(
            "locate",
            "references",
            json!({"selection": SUBJECT, "roles": ["impl"]}),
        )]),
        reply(vec![call(
            "read",
            "habeas",
            json!({"file": "src/lib.rs", "item": "fn[ready]"}),
        )]),
        reply(vec![call(
            "submit",
            "submit_judgment",
            json!({"determination": true, "rationale": "The tests check the requirement."}),
        )]),
    ]);
    let fixture = Fixture::new(&server.endpoint);
    let output = fixture.run(&["author", SUBJECT]);
    assert!(output.status.success(), "{output:?}");
    let requests = server.finish();
    assert_eq!(requests.len(), 3);
    let prompt = prompt_text(&requests[0].body);
    assert!(prompt.contains("fn ready_test()"));
    assert!(prompt.contains("One acknowledged gap."));
    assert!(!prompt.contains("pub fn ready()"));
    let tool_result = |request: &Request| -> Value {
        let message = request.body["messages"]
            .as_array()
            .unwrap()
            .iter()
            .rev()
            .find(|message| message["role"] == "tool")
            .unwrap();
        serde_json::from_str(message["content"].as_str().unwrap()).unwrap()
    };
    let locations = tool_result(&requests[1]);
    assert!(locations.to_string().contains("fn[ready]"), "{locations:#}");
    for text in [
        REQUIREMENT,
        "One acknowledged gap.",
        "pub fn ready()",
        "\"input\"",
        "\"inputs\"",
    ] {
        assert!(!locations.to_string().contains(text), "{locations:#}");
    }
    let read = tool_result(&requests[2]);
    assert!(read["input"]["text"].to_string().contains("pub fn ready()"));
    assert_eq!(read["input"]["file"], "src/lib.rs");
    assert_eq!(read["input"]["item"], "fn[ready]");
    assert_eq!(
        read["input"]["hash"],
        habeas::outline_input(&fixture.project, "src/lib.rs", "fn[ready]").unwrap()["hash"]
    );
    let record: Value = serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
    let inputs = record["inputs"].as_array().unwrap();
    assert_eq!(
        inputs
            .iter()
            .filter(|input| input["file"] == "src/lib.rs" && input["item"] == "fn[ready]")
            .count(),
        1
    );
    assert!(!fixture.usage()["inputs"].to_string().contains("references"));
}
Input 14: outline tests/authoring_cli.rs fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free]
// {test}`requirements.authoring.complete_initial_bundle`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.additional_read`
// {test}`requirements.authoring.acknowledged_gap`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.initial_prompt`
// {test}`requirements.ci.review_criteria`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.usage_inputs`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.mandatory_inputs`
// {test}`requirements.authoring.github_reads`
// {test}`requirements.authoring.invocation`
// {test}`requirements.configuration.serialization`
// {test}`requirements.ci.fixme_implementation_gap`
// {test}`requirements.authoring.finish_search.empty`
// {test}`requirements.authoring.finish_search.completion`
#[test]
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.reporting`
fn ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free() {
    let server = Server::start(vec![
        reply(vec![
            call("list", "list_files", json!({})),
            call(
                "search",
                "ripgrep",
                json!({"path":"extra.txt","pattern":"needle"}),
            ),
            call(
                "read",
                "habeas",
                json!({"file":"extra.txt","line_start":10}),
            ),
            call(
                "repeat",
                "habeas",
                json!({"file":"extra.txt","line_start":10}),
            ),
            call(
                "missing",
                "habeas",
                json!({"file":"absent.txt","line_start":1}),
            ),
        ]),
        json!({"__finish_latest_search":true}),
        reply(vec![call(
            "submit",
            "submit_judgment",
            json!({
            "determination":{"FIXME":["example/app#125"]},"rationale":"SECRET_RATIONALE: `src/lib.rs#fn[ready]` documents the gap."}),
        )]),
    ]);
    let fixture = Fixture::new(&server.endpoint);
    let user_config = fixture.config.join("habeas/config.toml");
    let configured = fs::read(&user_config).unwrap();
    let output = fixture.run(&["author-evidence", SUBJECT]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    // The user configuration, with its environment-resolved key, is not
    // rewritten.
    assert_eq!(fs::read(&user_config).unwrap(), configured);
    let requests = server.finish();
    assert_eq!(requests.len(), 3);
    for request in &requests {
        assert!(request.headers.starts_with("POST /api/chat HTTP/1.1\r\n"));
        assert!(request.headers.to_ascii_lowercase().contains(&format!(
            "authorization: bearer {}",
            AUTH.to_ascii_lowercase()
        )));
        assert_eq!(request.body["model"], MODEL);
        assert_eq!(request.body["options"]["temperature"], 0.25);
        assert_eq!(request.body["options"]["num_ctx"], 4096);
        assert_eq!(request.body["think"], false);
        assert_eq!(request.body["stream"], false);
    }
    let prompt = prompt_text(&requests[0].body);
    for text in [
        "Assess whether a project's tests adequately check one requirement.",
        REQUIREMENT,
        "SECRET_DEFINITION_TEXT",
        "fn ready_test()",
        "You MUST end by calling submit_judgment",
    ] {
        assert!(prompt.contains(text), "prompt missing {text}");
    }
    assert!(!prompt.contains("pub fn ready()"), "{prompt}");
    assert!(!prompt.contains("OLD_RATIONALE_MUST_NOT_REACH_MODEL"));
    let mut tools = requests[0].body["tools"]
        .as_array()
        .unwrap()
        .iter()
        .map(|tool| tool["function"]["name"].as_str().unwrap())
        .collect::<Vec<_>>();
    tools.sort();
    assert_eq!(
        tools,
        [
            "ast_grep",
            "finish_search",
            "github",
            "habeas",
            "list_files",
            "next_page",
            "outline",
            "references",
            "ripgrep",
            "submit_judgment"
        ]
    );
    let results = requests[1].body["messages"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|message| message["role"] == "tool")
        .collect::<Vec<_>>();
    assert_eq!(results.len(), 5);
    assert!(results.iter().any(|message| {
        message["content"]
            .as_str()
            .unwrap()
            .contains("SECRET_SOURCE_PAYLOAD")
    }));
    assert!(
        results
            .iter()
            .any(|message| message["content"].as_str().unwrap().contains("absent.txt"))
    );

    let evidence: Value = serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
    assert_eq!(
        evidence["determination"],
        json!({"FIXME":["example/app#125"]})
    );
    assert_eq!(
        evidence["rationale"],
        "SECRET_RATIONALE: `src/lib.rs#fn[ready]` documents the gap."
    );
    assert_eq!(evidence["requirement"], REQUIREMENT);
    let inputs = evidence["inputs"].as_array().unwrap();
    assert!(
        inputs
            .iter()
            .any(|input| input["file"] == "src/lib.rs" && input["item"] == "fn[ready_test]"),
        "{inputs:#?}"
    );
    // The acknowledgment reaches the model as metadata, without the
    // containing implementation. Its body is protected by the reference set.
    assert!(prompt.contains(":github: example/app#125"));
    assert!(prompt.contains("One acknowledged gap."));
    // GitHub is unreachable, so the issue is supplied as open, but the state
    // is not recorded.
    assert!(
        prompt.contains("\"reference\": \"example/app#125\"")
            && prompt.contains("\"state\": \"open\""),
        "{prompt}"
    );
    assert!(!evidence.to_string().contains("github_issues"));
    assert!(!fixture.usage().to_string().contains("github_issues"));
    assert!(
        !inputs
            .iter()
            .any(|input| input["file"] == "src/lib.rs" && input["item"] == "fn[ready]"),
        "{inputs:#?}"
    );
    // CI accepts the FIXME judgment: its evidence has no validation error.
    let report = habeas::validate_repository(&fixture.project).unwrap();
    let label = format!("evidence/{SUBJECT}.json");
    assert!(
        !report.errors.iter().any(|error| error.contains(&label)),
        "{:#?}",
        report.errors
    );
    // The same record with a false determination is rejected.
    let mut rejected = evidence.clone();
    rejected["determination"] = json!(false);
    let accepted = fs::read(&fixture.evidence).unwrap();
    fs::write(&fixture.evidence, rejected.to_string()).unwrap();
    let report = habeas::validate_repository(&fixture.project).unwrap();
    assert!(
        report.errors.iter().any(|error| error.contains(&label)),
        "{:#?}",
        report.errors
    );
    fs::write(&fixture.evidence, accepted).unwrap();
    assert!(
        inputs
            .iter()
            .any(|input| input["definition"] == "terms.readiness")
    );
    let extra = inputs
        .iter()
        .filter(|input| input["file"] == "extra.txt")
        .collect::<Vec<_>>();
    // The search only locates lines and records nothing; the reads cover
    // lines 10-12, one plain-text line node each, and the repeated delivery
    // is recorded once, by selector and hash only.
    assert_eq!(
        extra,
        habeas::outline_inputs_for_lines(&fixture.project, "extra.txt", 10, 12)
            .unwrap()
            .iter()
            .collect::<Vec<_>>(),
        "repeated delivery is deduplicated in evidence"
    );
    assert!(
        !evidence["inputs"]
            .to_string()
            .contains("SECRET_SOURCE_PAYLOAD")
    );
    assert!(
        !inputs
            .iter()
            .any(|input| input["file"] == "absent.txt" || input["file"] == ".")
    );

    let usage = fixture.usage();
    assert_eq!(usage["outcome"], "completed");
    assert_eq!(usage["determination"], "FIXME");
    assert_eq!(usage["evidence_written"], true);
    assert_eq!(usage["request_count"], 3);
    assert_eq!(usage["tool_call_count"], 7);
    assert_eq!(usage["tool_calls"]["habeas"], 3);
    assert_eq!(usage["tool_failures"]["habeas"], 1);
    // The directory listing counts as a tool call but is not an input.
    assert_eq!(usage["tool_calls"]["list_files"], 1);
    assert_eq!(usage["tool_calls"]["ripgrep"], 1);
    assert_eq!(usage["tool_calls"]["finish_search"], 1);
    let usage_inputs = usage["inputs"].as_array().unwrap();
    assert!(
        !usage_inputs
            .iter()
            .any(|input| input["origin"] == "list_files"),
        "{usage_inputs:?}"
    );
    // Search snippets count toward usage, without becoming evidence inputs.
    assert!(
        usage_inputs.iter().any(|input| input["origin"] == "ripgrep"
            && input["kind"] == "search"
            && input["bytes"].as_u64().unwrap() > 0
            && input["lines"].as_u64().unwrap() > 0),
        "{usage_inputs:?}"
    );
    assert!(
        usage_inputs
            .iter()
            .any(|input| input["origin"] == "habeas" && input["unique"] == true),
        "{usage_inputs:?}"
    );
    assert_eq!(usage["tokens"]["input"], 33);
    assert_eq!(usage["tokens"]["output"], 21);
    assert_eq!(usage["tokens"]["complete"], true);
    assert!(
        usage["inputs"]
            .as_array()
            .unwrap()
            .iter()
            .any(|input| input["origin"] == "habeas"
                && input["unique"] == false
                && input["sent_in_request"] == 1)
    );
    assert!(
        usage["inputs"]
            .as_array()
            .unwrap()
            .iter()
            .any(|input| input["origin"] == "mandatory"
                && input["kind"] == "definition"
                && input["bytes"].as_u64().unwrap() > 0)
    );
    let serialized = usage.to_string();
    for secret in [
        "SECRET_REQUIREMENT_TEXT",
        "SECRET_DEFINITION_TEXT",
        "SECRET_SOURCE_PAYLOAD",
        "SECRET_RATIONALE",
        AUTH,
        "#125",
    ] {
        assert!(
            !serialized.contains(secret),
            "usage contains source or credential content: {secret}"
        );
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains(MODEL) && stdout.contains("Evidence:") && stdout.contains("Usage:"));
    // By default the report names the subject and backend and identifies the
    // evidence file it wrote.
    assert!(
        stdout.starts_with(&format!("{SUBJECT}: ollama / {MODEL}")),
        "{stdout}"
    );
    let evidence = stdout
        .lines()
        .find_map(|line| line.strip_prefix("Evidence: "))
        .unwrap();
    assert!(
        evidence.ends_with(&format!("evidence/{SUBJECT}.json")),
        "{stdout}"
    );
    assert_eq!(
        fs::canonicalize(evidence).unwrap(),
        fs::canonicalize(fixture.project.join(format!("evidence/{SUBJECT}.json"))).unwrap()
    );
}
Input 15: outline tests/authoring_cli.rs fn[stdout_emits_only_evidence_json_without_changing_project_files]
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.reporting`
// {test}`requirements.ci.schema`
#[test]
fn stdout_emits_only_evidence_json_without_changing_project_files() {
    for (determination, kind, existing_evidence, verbose) in [
        (json!(true), "true", true, false),
        (json!(false), "false", true, false),
        (json!({"FIXME":["#125"]}), "FIXME", true, false),
        (json!(true), "true", false, false),
        (json!(false), "false", true, true),
        (json!(true), "true", true, true),
    ] {
        let rationale = "The supplied sources explain this judgment.";
        let server = Server::start(vec![reply(vec![call(
            "submit",
            "submit_judgment",
            json!({"determination":determination,"rationale":rationale}),
        )])]);
        let fixture = Fixture::new(&server.endpoint);
        if !existing_evidence {
            fs::remove_dir_all(fixture.project.join("evidence")).unwrap();
        }
        let mut args = vec!["author-evidence", SUBJECT, "--stdout"];
        if verbose {
            args.push("--verbose");
        }
        let output = fixture.run(&args);
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(server.finish().len(), 1);
        let evidence: Value = serde_json::from_slice(&output.stdout).unwrap();
        assert!(output.stdout.ends_with(b"\n"));
        assert_eq!(evidence["requirement"], REQUIREMENT);
        assert_eq!(evidence["determination"], determination);
        assert_eq!(evidence["rationale"], rationale);
        let inputs = evidence["inputs"].as_array().unwrap();
        assert!(inputs.iter().any(|input| input["requirements"] == SUBJECT));
        assert!(
            inputs
                .iter()
                .any(|input| input["definition"] == "terms.readiness")
        );
        assert!(
            inputs
                .iter()
                .any(|input| input["file"] == "src/lib.rs" && input["item"].is_string())
        );
        // The record has exactly the schema's fields, and outline inputs carry
        // only their file, selector, and hash, never source text.
        let keys = |value: &Value| {
            let mut keys: Vec<_> = value.as_object().unwrap().keys().cloned().collect();
            keys.sort();
            keys
        };
        assert_eq!(
            keys(&evidence),
            [
                "determination",
                "inputs",
                "rationale",
                "references",
                "requirement"
            ]
        );
        for input in inputs.iter().filter(|input| input.get("item").is_some()) {
            assert_eq!(keys(input), ["file", "hash", "item"], "{input}");
        }
        if existing_evidence {
            assert_eq!(
                fs::read_to_string(&fixture.evidence).unwrap(),
                fixture.original
            );
        } else {
            assert!(!fixture.project.join("evidence").exists());
        }
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains(&format!("{SUBJECT}: ollama / {MODEL}")),
            "{stderr}"
        );
        assert!(!stderr.contains("— true"), "{stderr}");
        assert!(!stderr.contains(&format!("{SUBJECT}: true")), "{stderr}");
        assert_eq!(
            stderr.contains(&format!("{SUBJECT}: false")),
            kind == "false",
            "{stderr}"
        );
        if kind == "FIXME" {
            assert!(stderr.contains("— FIXME"), "{stderr}");
        }
        assert_eq!(
            stderr.contains(rationale),
            verbose && kind == "false",
            "{stderr}"
        );
        assert!(!stderr.contains("SECRET_REQUIREMENT_TEXT"), "{stderr}");
        assert!(!stderr.contains("SECRET_DEFINITION_TEXT"), "{stderr}");
        assert!(stderr.contains("Evidence: stdout\n"));
        let usage_path = stderr
            .lines()
            .find_map(|line| line.strip_prefix("Usage: "))
            .expect("stderr reports usage location");
        assert!(std::path::Path::new(usage_path).is_file());
        let usage = fixture.usage();
        assert_eq!(usage["outcome"], "completed");
        assert_eq!(usage["determination"], kind);
        assert_eq!(usage["evidence_output"], "stdout");
        assert_eq!(usage["evidence_written"], true);
    }
}
Input 16: outline tests/authoring_cli.rs fn[bedrock_cli_uses_selected_profile_region_and_converse_tools]
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.initial_prompt`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.submission`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.output_limit`
#[test]
fn bedrock_cli_uses_selected_profile_region_and_converse_tools() {
    for typed in [false, true] {
        let mut read_call = json!({"toolUseId":"bedrock-read","name":"habeas",
        "input":{"file":"extra.txt","line_start":1,"line_end":2}});
        let mut submit_call = json!({"toolUseId":"bedrock-submit","name":"submit_judgment",
        "input":{"determination":true,"rationale":"The supplied sources support the subject."}});
        if typed {
            read_call["type"] = json!("tool_use");
            submit_call["type"] = json!("tool_use");
        }
        let first_message = json!({"role":"assistant","content":[
            {"text":"Reading source."},{"toolUse":read_call}
        ]});
        let server = Server::start(vec![
            json!({
                "output":{"message":first_message.clone()},
                "stopReason":"tool_use",
                "usage":{"inputTokens":19,"outputTokens":5,"totalTokens":24},
                "metrics":{"latencyMs":1}
            }),
            json!({
                "output":{"message":{"role":"assistant","content":[{"toolUse":submit_call}]}},
                "stopReason":"tool_use",
                "usage":{"inputTokens":19,"outputTokens":5,"totalTokens":24},
                "metrics":{"latencyMs":1}
            }),
        ]);
        let fixture = Fixture::new(&server.endpoint);
        let credentials = fixture.temp.path().join("aws-credentials");
        let aws_config = fixture.temp.path().join("aws-config");
        fs::write(&credentials, "[default]\naws_access_key_id = WRONG_DEFAULT_ACCESS_KEY\naws_secret_access_key = wrong-default-secret\n[habeas-test]\naws_access_key_id = FAKE_PROFILE_ACCESS_KEY\naws_secret_access_key = fake-profile-secret-for-local-test-only\n").unwrap();
        fs::write(&aws_config, "[profile habeas-test]\nregion = eu-west-1\n").unwrap();
        fs::write(fixture.config.join("habeas/config.toml"), "version = 1\n[authoring]\ndefault = 'cloud'\n[authoring.configs.cloud]\npolicy = 'once'\nbackend = 'bedrock'\nmodel = 'fixture-bedrock-model'\naws_profile = 'habeas-test'\nregion = 'us-west-2'\n[authoring.configs.cloud.options]\ntemperature = 0.25\nmaxTokens = 321\ntopP = 0.75\nstopSequences = ['END']\ntop_k = 12\n").unwrap();
        let mut command = fixture.command();
        for key in [
            "AWS_ACCESS_KEY_ID",
            "AWS_SECRET_ACCESS_KEY",
            "AWS_SESSION_TOKEN",
            "AWS_SECURITY_TOKEN",
            "AWS_PROFILE",
            "AWS_DEFAULT_PROFILE",
            "AWS_REGION",
            "AWS_DEFAULT_REGION",
            "AWS_ENDPOINT_URL",
            "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",
            "AWS_BEARER_TOKEN_BEDROCK",
        ] {
            command.env_remove(key);
        }
        let output = command
            .env("AWS_CONFIG_FILE", aws_config)
            .env("AWS_SHARED_CREDENTIALS_FILE", credentials)
            .env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", &server.endpoint)
            .env("AWS_EC2_METADATA_DISABLED", "true")
            .args(["author-evidence", SUBJECT])
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let requests = server.finish();
        assert_eq!(requests.len(), 2);
        assert_eq!(requests[1].body["messages"][1], first_message);
        let result = &requests[1].body["messages"][2]["content"][0]["toolResult"];
        assert_eq!(result["toolUseId"], "bedrock-read");
        let delivered = result["content"][0]["text"].as_str().unwrap();
        assert!(delivered.contains("extra.txt") && delivered.contains("context line 1"));
        assert!(
            requests[0]
                .headers
                .starts_with("POST /model/fixture-bedrock-model/converse HTTP/1.1\r\n")
        );
        assert!(
            requests[0]
                .headers
                .contains("Credential=FAKE_PROFILE_ACCESS_KEY/")
        );
        assert!(
            requests[0]
                .headers
                .contains("/us-west-2/bedrock/aws4_request")
        );
        assert!(!requests[0].headers.contains("WRONG_DEFAULT_ACCESS_KEY"));
        let body = &requests[0].body;
        assert_eq!(
            body["inferenceConfig"],
            json!({"temperature":0.25,"maxTokens":321,"topP":0.75,"stopSequences":["END"]})
        );
        // A configured maxTokens is used as given on every request.
        assert_eq!(requests[1].body["inferenceConfig"]["maxTokens"], 321);
        assert_eq!(body["additionalModelRequestFields"], json!({"top_k":12}));
        let prompt = prompt_text(body);
        assert!(
            prompt.contains("Assess whether a project's tests adequately check")
                && prompt.contains(REQUIREMENT)
        );
        let tool_specs = body["toolConfig"]["tools"].as_array().unwrap();
        for tool in tool_specs {
            let schema = &tool["toolSpec"]["inputSchema"]["json"];
            assert_eq!(schema["type"], "object");
            for unsupported in ["oneOf", "allOf", "anyOf"] {
                assert!(
                    schema.get(unsupported).is_none(),
                    "Bedrock rejects {unsupported} at the root of {}'s input schema",
                    tool["toolSpec"]["name"]
                );
            }
        }
        let habeas_schema = &tool_specs
            .iter()
            .find(|tool| tool["toolSpec"]["name"] == "habeas")
            .unwrap()["toolSpec"]["inputSchema"]["json"];
        assert_eq!(habeas_schema["additionalProperties"], false);
        for field in ["file", "item", "requirements", "definition"] {
            assert_eq!(habeas_schema["properties"][field]["type"], "string");
        }
        for field in ["line_start", "line_end"] {
            assert_eq!(habeas_schema["properties"][field]["type"], "integer");
            assert_eq!(habeas_schema["properties"][field]["minimum"], 1);
        }
        let judgment_schema = &tool_specs
            .iter()
            .find(|tool| tool["toolSpec"]["name"] == "submit_judgment")
            .unwrap()["toolSpec"]["inputSchema"]["json"]["properties"]["determination"];
        let outcomes = judgment_schema["oneOf"].as_array().unwrap();
        assert!(outcomes.iter().any(|outcome| outcome["type"] == "boolean"));
        let fixme = &outcomes
            .iter()
            .find(|outcome| outcome["type"] == "object")
            .unwrap()["properties"]["FIXME"];
        assert_eq!(fixme["type"], "array");
        assert_eq!(fixme["minItems"], 1);
        assert_eq!(fixme["items"]["type"], "string");
        assert_eq!(fixme["items"]["minLength"], 1);
        let mut tools = tool_specs
            .iter()
            .map(|tool| tool["toolSpec"]["name"].as_str().unwrap())
            .collect::<Vec<_>>();
        tools.sort();
        assert_eq!(
            tools,
            [
                "ast_grep",
                "finish_search",
                "github",
                "habeas",
                "list_files",
                "next_page",
                "outline",
                "references",
                "ripgrep",
                "submit_judgment"
            ]
        );
        let evidence: Value =
            serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
        assert_eq!(evidence["determination"], true);
        assert!(
            evidence["inputs"]
                .as_array()
                .unwrap()
                .iter()
                .filter(|input| input["file"] == "extra.txt")
                .collect::<Vec<_>>()
                == habeas::outline_inputs_for_lines(&fixture.project, "extra.txt", 1, 2)
                    .unwrap()
                    .iter()
                    .collect::<Vec<_>>()
        );
        let usage = fixture.usage();
        assert_eq!(usage["backend"], "bedrock");
        assert_eq!(usage["model"], "fixture-bedrock-model");
        assert_eq!(usage["tokens"]["input"], 38);
        assert_eq!(usage["tokens"]["output"], 10);
        assert_eq!(usage["request_count"], 2);
        assert_eq!(usage["tool_calls"]["habeas"], 1);
        assert_eq!(usage["tool_calls"]["submit_judgment"], 1);
        assert_eq!(usage["outcome"], "completed");
    }
}
Input 17: outline tests/live_bedrock.rs fn[live_bedrock_authoring]
// {test}`requirements.integration.live_bedrock_test`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.submission`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.usage_storage`
// {impl}`requirements.integration.live_bedrock_test`
#[test]
fn live_bedrock_authoring() {
    if std::env::var_os("CI").is_some() {
        report("warning: skipping live Bedrock test: CI is set");
        return;
    }
    let LiveSelection {
        config: selected,
        workspace,
    } = selected_config()
        .expect("cannot select live Bedrock configuration")
        .expect("no Bedrock authoring configuration; add one to your Habeas user config (see md/reference.md), or set CI=1 to disable live testing");
    let BackendConfig::Bedrock(backend) = &selected.backend else {
        unreachable!("selection only returns Bedrock configurations");
    };
    if !credentials_available(backend) {
        return;
    }
    report(format!(
        "live Bedrock test: configuration {:?}, model {:?}",
        selected.name, backend.model
    ));

    let temp = tempfile::tempdir().unwrap();
    let project = temp.path().join("project");
    for directory in [project.join("md"), project.join("src")] {
        fs::create_dir_all(directory).unwrap();
    }
    fs::write(
        project.join("Cargo.toml"),
        "[package]\nname = 'live-fixture'\nversion = '0.1.0'\nedition = '2024'\n",
    )
    .unwrap();
    fs::write(project.join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
    if let Some(workspace) = &workspace {
        fs::write(project.join("habeas.toml"), workspace).unwrap();
    }
    fs::write(
        project.join("md/SUMMARY.md"),
        "# Summary\n\n- [Requirements](requirements.md)\n",
    )
    .unwrap();
    fs::write(
        project.join("md/requirements.md"),
        format!(":::{{req}} parity\n{REQUIREMENT}\n:::\n"),
    )
    .unwrap();
    // No citation points to this file, so assessing its implementation requires
    // an additional source read instead of only the mandatory initial inputs.
    fs::write(project.join("src/parity.rs"), "pub fn is_even(value: u32) -> bool {\n    value % 2 == 0\n}\n\n#[test]\nfn parity_cases() {\n    assert!(is_even(0));\n    assert!(!is_even(1));\n    assert!(is_even(2));\n    assert!(!is_even(u32::MAX));\n}\n").unwrap();
    let checkout_evidence = Path::new(env!("CARGO_MANIFEST_DIR")).join("evidence");
    let before = evidence_snapshot(&checkout_evidence);
    let output = Command::new(env!("CARGO_BIN_EXE_habeas"))
        .current_dir(&project)
        .args([
            "author-evidence",
            SUBJECT,
            "--config",
            &selected.name,
            "--stdout",
        ])
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    report(&stderr);
    assert!(
        output.status.success(),
        "live Bedrock authoring failed: {stderr}"
    );
    let evidence: Value = serde_json::from_slice(&output.stdout).expect("stdout is evidence JSON");
    assert_eq!(evidence["requirement"], REQUIREMENT);
    habeas::judgment::Judgment::from_value(&evidence["determination"]).unwrap();
    assert!(!evidence["rationale"].as_str().unwrap().trim().is_empty());
    assert!(
        evidence["inputs"].as_array().unwrap().iter().any(|input| {
            input["file"] == "src/parity.rs"
                && input["item"].is_string()
                && input["hash"].is_string()
                && input.get("text").is_none()
        }),
        "model must inspect the fixture's source through a read tool"
    );
    assert!(!project.join("evidence").exists());
    assert_eq!(
        evidence_snapshot(&checkout_evidence),
        before,
        "checkout evidence changed"
    );
    let usage_path = stderr
        .lines()
        .find_map(|line| line.strip_prefix("Usage: "))
        .expect("reported usage path");
    let usage: Value = serde_json::from_slice(&fs::read(usage_path).unwrap()).unwrap();
    assert_eq!(usage["backend"], "bedrock");
    assert_eq!(usage["model"], backend.model);
    assert_eq!(usage["outcome"], "completed");
    assert_eq!(usage["evidence_output"], "stdout");
    assert_eq!(usage["evidence_written"], true);
    assert!(usage["request_count"].as_u64().unwrap() >= 2);
    assert!(usage["tool_calls"]["submit_judgment"].as_u64().unwrap() >= 1);
    assert!(
        usage["tool_calls"]["habeas"].as_u64().unwrap_or(0)
            + usage["tool_calls"]["ripgrep"].as_u64().unwrap_or(0)
            > 0
    );
}

Referenced definitions

Input 2: requirements selection requirements.authoring.finish_search.inputs
:::{req} finish_search.inputs
For each tag selected by a valid `finish_search` call, the harness MUST record
its `file`, `item`, and structural hash as an outline input under
{cite}`requirements.ci.outline_inputs` before acknowledging that call.
:::
Input 3: requirements selection requirements.ci.outline_inputs
:::{req} outline_inputs
For an outline input, Habeas MUST parse `file` with its language's grammar under
{cite}`requirements.references.outlines` and resolve `item` to exactly one
outline node under {cite}`requirements.references.outline_selectors`. It MUST
compare `hash` with the node's current structural hash under
{cite}`requirements.references.structural_hash`. It MUST derive the node's
inclusive line range, including attached comments and attributes, during
validation for display and reference coverage. Moving the node, editing other
nodes, or editing comments its profile does not hash MUST NOT invalidate the
input. Habeas MUST report a missing file, unsupported language, parse failure,
invalid or ambiguous selector, or changed hash.
:::
Input 4: requirements selection requirements.ci.requirements_inputs
:::{req} requirements_inputs
For a requirements input, `requirements` MUST be a {term}`requirements.references.definition_selection`, and Habeas MUST match it against all defined requirements and named examples. It MUST recompute the matches during validation, sort their full names, and compare them with `matches`. It MUST take each match's complete raw fenced declaration, including its opening and closing lines, concatenate those declarations in full-name order with one blank line between them, and compare the resulting raw lines with `text`. It MUST retain every match's current source file and inclusive line range for display and reference coverage. A selection matching no definitions MUST be invalid. Adding, removing, renaming, or changing a matched definition MUST invalidate the stored input; moving an unchanged declaration within the book MUST NOT. Errors MUST identify the selection and affected definitions when available.
:::
Input 5: requirements selection requirements.definitions.inputs
:::{req} inputs
Evidence inputs MAY have a definition form containing exactly `definition` and `text`. `definition` MUST identify one named definition; `text` MUST contain its complete raw fenced declaration as source lines, including its phrase option and explanatory body.

Validation MUST reject missing definitions and changed snapshot text, identifying the definition and showing a compact diff when available. Moving an unchanged definition within its chapter MUST NOT invalidate its snapshot. Evidence displays MUST show the definition name, current source location, and recorded text.
:::
Input 18: definition requirements.references.definition_selection
:::{definition} definition_selection
:phrase: definition selection

A full requirement or example name, or a definition glob, identifying the
requirements and named examples it matches under
{cite}`requirements.references.definition_globs`. A name without `*` selects
exactly that definition.
:::

Other sources

Input 1: requirements selection requirements.authoring.delivered_inputs
:::{req} delivered_inputs
The harness MUST record the sources it supplies to the model, including
mandatory inputs, additional reads, and selected search dependencies under
{cite}`requirements.authoring.finish_search.inputs`, using the evidence input formats
defined by {cite}`requirements.ci.outline_inputs`,
{cite}`requirements.ci.requirements_inputs`, and
{cite}`requirements.definitions.inputs`. The harness MUST create these records
itself so ordinary evidence validation can check them later.
:::