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

Requirements index · View definition

evidence Valid

Requirement

Usage MUST record each provider request’s outcome and available input/output token counts, including retries, with cached or reasoning-token counts when provided, and for a failed request the failure under cite requirements.authoring.usage_requests.failures. Missing measurements MUST be recorded as unavailable, not zero. Run totals MUST include request and tool-call counts by tool, elapsed time, and available token usage, identifying incomplete totals without double counting provider counters that overlap.

Rationale

The reviewed tests cover each obligation of requirements.authoring.usage_requests. They also apply the cited requirements.authoring.usage_requests.failures to this requirement’s cases.

Per-request outcome and tokens, including retries

  • src/authoring/mod.rs#mod[tests]/fn[throttled_requests_retry_unchanged_and_record_every_attempt] has five throttled attempts and one success. It asserts request_count is 6, the first five outcomes are failed, and the last is completed. The failed attempts have tokens.complete == false.
  • src/authoring/mod.rs#mod[tests]/fn[unanswered_requests_are_abandoned_and_retried] records an abandoned request as failed and its retry as completed.
  • src/authoring/mod.rs#mod[tests]/fn[success_resets_backoff_and_retries_keep_history_without_repeating_tools] checks request_count is 4 across retries.
  • Provider-level token mapping is asserted in tests/authoring_cli.rs#fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free], which asserts input 33 and output 21.
  • It is also asserted in tests/authoring_cli.rs#fn[bedrock_cli_uses_selected_profile_region_and_converse_tools], which asserts 38 input and 10 output.
  • tests/authoring_cli.rs#fn[openai_responses_replays_tool_calls_and_records_usage] asserts input 22 and output 14.

Cached and reasoning counts when provided

  • tests/authoring_cli.rs#fn[claude_requests_carry_cache_checkpoints_and_record_cache_usage] asserts per-request and total cached_input and cache_creation_input.
  • The OpenAI test asserts cached 6 and reasoning 4 in the totals.
  • src/authoring/usage.rs#mod[tests]/fn[token_totals_keep_subsets_separate_and_missing_counters_unknown] covers all five counters.

Missing measurements recorded as unavailable, not zero

  • The same usage.rs test and fn[partial_failure_retains_available_totals_and_optional_measurements] assert is_null() for a failed request’s tokens and for unreported cached or reasoning totals.
  • The partial-failure test also asserts that an explicitly reported cached_input_tokens(0) stays 0 while an unreported reasoning stays null. That separates unavailable from zero.

Failures (the cited requirements.authoring.usage_requests.failures)

  • The throttled-requests test asserts the exact failure object {http_status:429, error_code:"ThrottlingException", retried:true} for the five retried failures, and that the successful attempt has no failure.
  • fn[failed_submission_can_be_confirmed_on_a_later_attempt] asserts the failure is retried:false first and true after retried(). Its exact-equality assertion also rules out any message field.

Run totals

  • Request counts are asserted in many tests.
  • Tool-call counts by tool, with distinct failure and skipped counters, are asserted in fn[tool_outcomes_are_distinct_and_unknown_names_do_not_leak_model_text]. In the CLI tests, the Ollama test asserts the per-tool counts.
  • Elapsed time is asserted per request and for the run in fn[completed_requests_and_the_run_record_elapsed_time]. fn[cancelled_request_persists_elapsed_time_and_incomplete_totals] covers a cancelled request.
  • Available token usage is retained in fn[partial_failure_retains_available_totals_and_optional_measurements].
  • Incomplete totals are identified by tokens.complete. The tests assert it is false for in-flight, failed, cancelled and partially measured runs, and true when every request is measured.
  • Overlapping counters are not double counted. In the subsets test, input totals 200 (not 230 with cache added), cached totals 60, output 40 and reasoning 10.

Minor residual points that I do not treat as gaps

  • The failure object is not asserted when the provider reports neither status nor code (the Some((None, None)) calls). That condition belongs to the cited failures requirement, and the implementation is a plain pass-through of the optional values.
  • src/authoring/providers.rs#mod[tests]/fn[bedrock_sdk_retries_are_disabled] is marked against this requirement. It supports the rule that each retry is a separately recorded request.

No acknowledged or unacknowledged gaps were found.

Inputs

Tests

Input 3: outline src/authoring/mod.rs mod[tests]/fn[throttled_requests_retry_unchanged_and_record_every_attempt]
    // {test}`requirements.authoring.provider_backoff`
    // {test}`requirements.authoring.usage_requests`
    // {test}`requirements.authoring.usage_requests.failures`
    // {test}`requirements.authoring.usage_inputs`
    // {test}`requirements.ci.reference_set`
    #[tokio::test(start_paused = true)]
    async fn throttled_requests_retry_unchanged_and_record_every_attempt() {
        let (_project, _state, mut sources, mut usage) = retry_fixture();
        let provider = ThrottledProvider {
            failures: 5,
            status: 429,
            code: "ThrottlingException",
            requests: RefCell::default(),
        };
        let started = tokio::time::Instant::now();
        let (_, record) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        assert!(started.elapsed() >= Duration::from_millis(500));
        let requests = provider.requests.borrow();
        assert_eq!(requests.len(), 6);
        assert!(requests.iter().all(|request| request == &requests[0]));
        assert_eq!(record["inputs"], json!(sources.mandatory_inputs()));
        assert_eq!(record["references"], json!(sources.reference_set));

        let log: Value = serde_json::from_slice(&fs::read(&usage.path).unwrap()).unwrap();
        assert_eq!(log["request_count"], 6);
        for attempt in 0..5 {
            assert_eq!(log["requests"][attempt]["outcome"], "failed");
            assert_eq!(log["requests"][attempt]["tokens"]["complete"], false);
            assert_eq!(
                log["requests"][attempt]["failure"],
                json!({"http_status": 429, "error_code": "ThrottlingException", "retried": true})
            );
        }
        assert!(log["requests"][5].get("failure").is_none());
        assert_eq!(log["requests"][5]["outcome"], "completed");
        assert_eq!(log["tool_calls"]["submit_judgment"], 1);
        for input in log["inputs"].as_array().unwrap() {
            assert_eq!(input["submitted_in_request"], 0);
            assert_eq!(input["sent_in_request"], 5);
        }
    }
Input 4: outline src/authoring/mod.rs mod[tests]/fn[unanswered_requests_are_abandoned_and_retried]
    // {test}`requirements.authoring.provider_backoff`
    // {test}`requirements.authoring.usage_requests`
    #[tokio::test(start_paused = true)]
    async fn unanswered_requests_are_abandoned_and_retried() {
        let (_project, _state, mut sources, mut usage) = retry_fixture();
        let provider = HangingProvider {
            requests: RefCell::default(),
        };
        let started = tokio::time::Instant::now();
        let (judgment, _) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        assert_eq!(judgment.to_value(), json!(true));
        assert!(
            (Duration::from_secs(600)..=Duration::from_secs(601)).contains(&started.elapsed()),
            "{:?}",
            started.elapsed()
        );
        assert_eq!(*provider.requests.borrow(), 2);
        let log: Value = serde_json::from_slice(&fs::read(&usage.path).unwrap()).unwrap();
        assert_eq!(log["request_count"], 2);
        assert_eq!(log["requests"][0]["outcome"], "failed");
        assert_eq!(log["requests"][1]["outcome"], "completed");
    }
Input 5: outline src/authoring/mod.rs mod[tests]/fn[success_resets_backoff_and_retries_keep_history_without_repeating_tools]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[success_resets_backoff_and_retries_keep_history_without_repeating_tools]
  • Kind: fn
  • src/authoring/mod.rs:2429–2469
    // {test}`requirements.authoring.provider_backoff`
    // {test}`requirements.authoring.usage_requests`
    #[tokio::test(start_paused = true)]
    async fn success_resets_backoff_and_retries_keep_history_without_repeating_tools() {
        let (project, _state, mut sources, mut usage) = retry_fixture();
        fs::write(project.path().join("src/lib.rs"), "fn run() {}\n").unwrap();
        let provider = ThrottledToolProvider {
            requests: RefCell::default(),
        };
        let (_, record) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        let requests = provider.requests.borrow();
        assert_eq!(requests.len(), 4);
        // Each throttled request waits within the initial one-second window:
        // the successful tool turn reset the window doubled by the first failure.
        for (failed, retried) in [(0, 1), (2, 3)] {
            let delay = requests[retried].0 - requests[failed].0;
            assert!(
                delay >= Duration::from_millis(500) && delay <= Duration::from_secs(1),
                "{delay:?}"
            );
        }
        assert_eq!(requests[0].1, requests[1].1);
        // The retry after the tool turn resends the same history, tool
        // results, and tools.
        assert_eq!(requests[2].1, requests[3].1);
        assert_ne!(requests[1].1, requests[2].1);
        assert!(requests[3].1.to_string().contains("fn run()"));

        // The read ran once, and its input was recorded after the retried
        // request succeeded.
        let log: Value = serde_json::from_slice(&fs::read(&usage.path).unwrap()).unwrap();
        assert_eq!(log["tool_calls"]["habeas"], 1, "{log:#}");
        assert_eq!(log["request_count"], 4);
        let inputs = record["inputs"].as_array().unwrap();
        assert!(
            inputs
                .iter()
                .any(|input| input["file"] == "src/lib.rs" && input["item"] == "fn[run]"),
            "{inputs:#?}"
        );
    }
Input 6: outline src/authoring/providers.rs mod[tests]/fn[bedrock_sdk_retries_are_disabled]
    // {test}`requirements.authoring.provider_backoff`
    // {test}`requirements.authoring.usage_requests`
    #[tokio::test]
    async fn bedrock_sdk_retries_are_disabled() {
        let config: BedrockConfig =
            toml::from_str("model = 'test'\nregion = 'us-west-2'\n").unwrap();
        let sdk = bedrock_sdk_config(&config).await;
        let retry = sdk.retry_config().expect("retry configuration is set");
        assert_eq!(retry.max_attempts(), 1, "{retry:?}");
    }
Input 7: outline src/authoring/usage.rs mod[tests]/fn[token_totals_keep_subsets_separate_and_missing_counters_unknown]
  • File: src/authoring/usage.rs
  • Selector: mod[tests]/fn[token_totals_keep_subsets_separate_and_missing_counters_unknown]
  • Kind: fn
  • src/authoring/usage.rs:553–591
    // {test}`requirements.authoring.usage_requests`
    #[test]
    fn token_totals_keep_subsets_separate_and_missing_counters_unknown() {
        let state = tempfile::tempdir().unwrap();
        let mut log =
            UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
        let measured = Usage::new()
            .input_tokens(100)
            .output_tokens(20)
            .cached_input_tokens(30)
            .cache_creation_input_tokens(10)
            .reasoning_tokens(5);
        let first = log.begin_request().unwrap();
        log.end_request(first, 3, Some(&measured), None).unwrap();
        let second = log.begin_request().unwrap();
        let in_flight = persisted(&log);
        assert_eq!(in_flight["tokens"]["complete"], false);
        assert_eq!(in_flight["tokens"]["input"], 100);
        log.end_request(second, 4, Some(&measured), None).unwrap();
        let complete = persisted(&log);
        assert_eq!(complete["tokens"]["input"], 200);
        assert_eq!(complete["tokens"]["output"], 40);
        assert_eq!(complete["tokens"]["cached_input"], 60);
        assert_eq!(complete["tokens"]["cache_creation_input"], 20);
        assert_eq!(complete["tokens"]["reasoning"], 10);
        assert_eq!(complete["tokens"]["complete"], true);
        let third = log.begin_request().unwrap();
        log.end_request(third, 2, None, Some((None, None))).unwrap();
        log.finish("failed").unwrap();
        let failed = persisted(&log);
        assert_eq!(failed["request_count"], 3);
        assert_eq!(failed["requests"][2]["outcome"], "failed");
        assert_eq!(failed["outcome"], "failed");
        assert_eq!(failed["requests"][0]["tokens"]["input"], 100);
        assert!(failed["requests"][2]["tokens"]["input"].is_null());
        assert_eq!(failed["tokens"]["input"], 200);
        assert_eq!(failed["tokens"]["output"], 40);
        assert_eq!(failed["tokens"]["complete"], false);
    }
Input 8: outline src/authoring/usage.rs mod[tests]/fn[partial_failure_retains_available_totals_and_optional_measurements]
  • File: src/authoring/usage.rs
  • Selector: mod[tests]/fn[partial_failure_retains_available_totals_and_optional_measurements]
  • Kind: fn
  • src/authoring/usage.rs:593–651
    // {test}`requirements.authoring.usage_requests`
    #[test]
    fn partial_failure_retains_available_totals_and_optional_measurements() {
        let state = tempfile::tempdir().unwrap();
        let mut log =
            UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
        let first = log.begin_request().unwrap();
        log.end_request(
            first,
            2,
            Some(&Usage::new().input_tokens(10).output_tokens(3)),
            None,
        )
        .unwrap();
        let known = persisted(&log);
        assert_eq!(known["tokens"]["complete"], true);
        assert!(known["tokens"]["cached_input"].is_null());
        let failed = log.begin_request().unwrap();
        log.end_request(failed, 1, None, Some((None, None)))
            .unwrap();
        let partial = persisted(&log);
        assert_eq!(partial["tokens"]["input"], 10);
        assert_eq!(partial["tokens"]["output"], 3);
        assert_eq!(partial["tokens"]["complete"], false);
        assert!(partial["requests"][failed]["tokens"]["input"].is_null());
        assert!(partial["tokens"]["cached_input"].is_null());

        let mut optional =
            UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
        let first = optional.begin_request().unwrap();
        optional
            .end_request(
                first,
                1,
                Some(&Usage::new().input_tokens(10).output_tokens(3)),
                None,
            )
            .unwrap();
        let second = optional.begin_request().unwrap();
        optional
            .end_request(
                second,
                1,
                Some(
                    &Usage::new()
                        .input_tokens(5)
                        .output_tokens(2)
                        .cached_input_tokens(0),
                ),
                None,
            )
            .unwrap();
        let mixed = persisted(&optional);
        assert_eq!(mixed["tokens"]["input"], 15);
        assert_eq!(mixed["tokens"]["output"], 5);
        assert_eq!(mixed["tokens"]["cached_input"], 0);
        assert!(mixed["tokens"]["reasoning"].is_null());
        assert_eq!(mixed["tokens"]["complete"], false);
    }
Input 9: outline src/authoring/usage.rs mod[tests]/fn[cancelled_request_persists_elapsed_time_and_incomplete_totals]
    // {test}`requirements.authoring.usage_storage`
    // {test}`requirements.authoring.usage_requests`
    #[test]
    fn cancelled_request_persists_elapsed_time_and_incomplete_totals() {
        let state = tempfile::tempdir().unwrap();
        let mut log =
            UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
        let initial = persisted(&log);
        assert_eq!(initial["outcome"], "unfinished");
        assert!(initial["end_time_ms"].is_null());
        let first = log.begin_request().unwrap();
        log.end_request(
            first,
            2,
            Some(&Usage::new().input_tokens(2).output_tokens(3)),
            None,
        )
        .unwrap();
        let second = log.begin_request().unwrap();
        log.active_request = Some((second, Instant::now() - Duration::from_millis(12)));
        log.finish("cancelled").unwrap();
        let cancelled = persisted(&log);
        assert_eq!(cancelled["outcome"], "cancelled");
        assert!(!cancelled["end_time_ms"].is_null());
        assert_eq!(cancelled["requests"][second]["outcome"], "cancelled");
        assert!(
            cancelled["requests"][second]["elapsed_ms"]
                .as_u64()
                .unwrap()
                >= 12
        );
        assert_eq!(cancelled["tokens"]["complete"], false);
        assert_eq!(cancelled["tokens"]["input"], 2);
        assert_eq!(cancelled["tokens"]["output"], 3);
        assert_eq!(cancelled["requests"][first]["tokens"]["input"], 2);
    }
Input 10: outline src/authoring/usage.rs mod[tests]/fn[completed_requests_and_the_run_record_elapsed_time]
    // {test}`requirements.authoring.usage_requests`
    #[test]
    fn completed_requests_and_the_run_record_elapsed_time() {
        let state = tempfile::tempdir().unwrap();
        let mut log =
            UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
        assert_eq!(persisted(&log)["elapsed_ms"], 0);
        log.started = Instant::now() - Duration::from_millis(50);
        let request = log.begin_request().unwrap();
        // The caller measures each attempt, including its abandoned waits.
        log.end_request(
            request,
            20,
            Some(&Usage::new().input_tokens(1).output_tokens(1)),
            None,
        )
        .unwrap();
        let during = persisted(&log);
        assert_eq!(during["requests"][request]["outcome"], "completed");
        let request_elapsed = during["requests"][request]["elapsed_ms"].as_u64().unwrap();
        assert_eq!(request_elapsed, 20, "{during}");
        assert!(during["elapsed_ms"].as_u64().unwrap() >= 50, "{during}");
        log.finish("completed").unwrap();
        let finished = persisted(&log);
        let run_elapsed = finished["elapsed_ms"].as_u64().unwrap();
        assert!(run_elapsed >= 50, "{finished}");
        assert!(run_elapsed >= request_elapsed, "{finished}");
        assert_eq!(
            finished["requests"][request]["elapsed_ms"]
                .as_u64()
                .unwrap(),
            request_elapsed
        );
    }
Input 11: outline src/authoring/usage.rs mod[tests]/fn[tool_outcomes_are_distinct_and_unknown_names_do_not_leak_model_text]
  • File: src/authoring/usage.rs
  • Selector: mod[tests]/fn[tool_outcomes_are_distinct_and_unknown_names_do_not_leak_model_text]
  • Kind: fn
  • src/authoring/usage.rs:725–758
    // {test}`requirements.authoring.usage_requests`
    // {test}`requirements.authoring.usage_inputs`
    // {test}`requirements.authoring.usage_storage`
    #[test]
    fn tool_outcomes_are_distinct_and_unknown_names_do_not_leak_model_text() {
        let state = tempfile::tempdir().unwrap();
        let mut log =
            UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
        log.tool("list_files", false);
        log.tool("outline", false);
        log.tool("habeas", true);
        log.skipped_tool("ripgrep");
        log.tool("ast_grep", false);
        log.tool("github", false);
        log.tool("MODEL_TEXT_SHOULD_NOT_APPEAR", true);
        log.skipped_tool("OTHER_MODEL_TEXT");
        log.finish("completed").unwrap();
        let value = persisted(&log);
        assert_eq!(value["tool_call_count"], 8);
        assert_eq!(value["tool_calls"]["list_files"], 1);
        assert_eq!(value["tool_calls"]["ast_grep"], 1);
        assert_eq!(value["tool_calls"]["github"], 1);
        assert_eq!(value["tool_calls"]["outline"], 1);
        assert_eq!(value["tool_failures"]["habeas"], 1);
        assert_eq!(value["tool_skipped"]["ripgrep"], 1);
        assert_eq!(value["tool_calls"]["unknown"], 2);
        assert_eq!(value["tool_failures"]["unknown"], 1);
        assert_eq!(value["tool_skipped"]["unknown"], 1);
        assert!(value["inputs"].as_array().unwrap().is_empty());
        assert!(value["tokens"]["input"].is_null());
        assert_eq!(value["tokens"]["complete"], false);
        let serialized = fs::read_to_string(&log.path).unwrap();
        assert!(!serialized.contains("MODEL_TEXT"));
    }
Input 12: outline src/authoring/usage.rs mod[tests]/fn[failed_submission_can_be_confirmed_on_a_later_attempt]
    // {test}`requirements.authoring.usage_inputs`
    // {test}`requirements.authoring.usage_requests`
    // {test}`requirements.authoring.usage_requests.failures`
    #[test]
    fn failed_submission_can_be_confirmed_on_a_later_attempt() {
        let state = tempfile::tempdir().unwrap();
        let mut log =
            UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
        log.prepared(
            "mandatory",
            &[json!({"file": "source", "text": ["source content"]})],
        );
        let first = log.begin_request().unwrap();
        log.end_request(
            first,
            2,
            None,
            Some((Some(429), Some("ThrottlingException".to_owned()))),
        )
        .unwrap();
        assert!(persisted(&log)["inputs"][0]["sent_in_request"].is_null());
        // A failed request records its status, code, and retry, but no
        // message text.
        assert_eq!(
            persisted(&log)["requests"][first]["failure"],
            json!({"http_status": 429, "error_code": "ThrottlingException", "retried": false})
        );
        log.retried(first).unwrap();
        assert_eq!(
            persisted(&log)["requests"][first]["failure"]["retried"],
            true
        );
        let retry = log.begin_request().unwrap();
        log.end_request(retry, 3, Some(&Usage::new()), None)
            .unwrap();
        let value = persisted(&log);
        assert_eq!(value["inputs"][0]["submitted_in_request"], first);
        assert_eq!(value["inputs"][0]["sent_in_request"], retry);
        assert_eq!(value["request_count"], 2);
    }
Input 13: 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 14: outline tests/authoring_cli.rs fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues]
  • File: tests/authoring_cli.rs
  • Selector: fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues]
  • Kind: fn
  • tests/authoring_cli.rs:853–922
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.structural_search`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.read_denial.untracked`
// {test}`requirements.authoring.read_denial`
#[test]
fn explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues() {
    for (tool, arguments) in [
        ("habeas", json!({"file":"untracked.txt", "line_start":1})),
        (
            "ripgrep",
            json!({"path":"untracked.txt", "pattern":"hidden"}),
        ),
        (
            "ast_grep",
            json!({"path":"untracked.txt", "language":"rust", "rule":{"rule":{"pattern":"hidden"}}}),
        ),
        ("list_files", json!({"path":"untracked-directory"})),
    ] {
        let server = Server::start(vec![
            reply(vec![call("denied", tool, arguments)]),
            reply(vec![call(
                "submit",
                "submit_judgment",
                json!({"determination": true, "rationale": "The tracked sources support it."}),
            )]),
        ]);
        let fixture = Fixture::new(&server.endpoint);
        for args in [["init", "--quiet"], ["add", "."]] {
            let git = Command::new("git")
                .current_dir(&fixture.project)
                .args(args)
                .output()
                .unwrap();
            assert!(git.status.success(), "{git:?}");
        }
        fs::write(fixture.project.join("untracked.txt"), "hidden source\n").unwrap();
        fs::create_dir(fixture.project.join("untracked-directory")).unwrap();
        fs::write(
            fixture.project.join("untracked-directory/hidden.txt"),
            "hidden source\n",
        )
        .unwrap();

        let output = fixture.run(&["author", SUBJECT, "--stdout"]);
        assert!(output.status.success(), "{tool}: {output:?}");
        // The model was told the path is untracked and how to fix it, and
        // the file was neither delivered nor recorded.
        let requests = server.finish();
        assert_eq!(requests.len(), 2, "{tool}");
        let second = requests[1].body.to_string();
        assert!(
            second.contains("is untracked") || second.contains("untracked, so"),
            "{tool}: {second}"
        );
        assert!(second.contains("git add"), "{tool}: {second}");
        assert!(!second.contains("hidden source"), "{tool}: {second}");
        let evidence = String::from_utf8_lossy(&output.stdout);
        assert!(!evidence.contains("untracked"), "{tool}: {evidence}");
        let usage = fixture.usage();
        assert_eq!(usage["outcome"], "completed", "{tool}: {usage}");
        assert_eq!(usage["request_count"], 2, "{tool}: {usage}");
        assert_eq!(usage["tool_failures"][tool], 1, "{tool}: {usage}");
    }
}
Input 15: 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 16: 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 17: outline tests/authoring_cli.rs fn[openai_responses_replays_tool_calls_and_records_usage]
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.cache_checkpoints`
#[test]
// {test}`requirements.authoring.usage_storage`
fn openai_responses_replays_tool_calls_and_records_usage() {
    fn assert_no_checkpoints(value: &Value) {
        match value {
            Value::Object(fields) => {
                for (key, value) in fields {
                    assert!(
                        !matches!(key.as_str(), "cachePoint" | "cache_control"),
                        "explicit cache checkpoint: {key}"
                    );
                    if key == "type" {
                        assert!(
                            !matches!(value.as_str(), Some("cache_point" | "cache_checkpoint")),
                            "explicit cache checkpoint block: {value}"
                        );
                    }
                    assert_no_checkpoints(value);
                }
            }
            Value::Array(values) => {
                for value in values {
                    assert_no_checkpoints(value);
                }
            }
            _ => {}
        }
    }

    let response = |id: &str, name: &str, arguments: Value| {
        json!({
            "id": format!("resp_{id}"), "object":"response", "status":"completed",
            "model":"fixture-openai", "output":[{
                "type":"function_call", "id":format!("fc_{id}"), "call_id":id,
                "name":name, "arguments":arguments.to_string(), "status":"completed"
            }],
            "usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
                "input_tokens_details":{"cached_tokens":3},
                "output_tokens_details":{"reasoning_tokens":2}}
        })
    };
    let server = Server::start(vec![
        response(
            "read",
            "habeas",
            json!({"file":"extra.txt","line_start":10}),
        ),
        response(
            "submit",
            "submit_judgment",
            json!({"determination":false,"rationale":"Missing implementation."}),
        ),
    ]);
    let fixture = Fixture::new(&server.endpoint);
    fs::write(fixture.config.join("habeas/config.toml"), format!(
        "version = 1\n[authoring]\ndefault = 'mock'\n[authoring.configs.mock]\nbackend = 'openai'\nmodel = 'fixture-openai'\npolicy = 'once'\nendpoint = '{}'\napi_key_env = 'HABEAS_TEST_MODEL_KEY'\n[authoring.configs.mock.options]\nmax_output_tokens = 1024\nreasoning = {{ effort = 'low' }}\n", server.endpoint)).unwrap();
    let output = fixture.run(&["author-evidence", SUBJECT]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let requests = server.finish();
    assert_eq!(requests.len(), 2);
    for request in &requests {
        assert!(request.headers.starts_with("POST /responses HTTP/1.1\r\n"));
        assert!(request.headers.contains(&format!("Bearer {AUTH}")));
        assert_eq!(request.body["model"], "fixture-openai");
        assert_eq!(request.body["max_output_tokens"], 1024);
        assert_eq!(request.body["reasoning"]["effort"], "low");
        assert_eq!(request.body["tools"].as_array().unwrap().len(), 10);
        assert_no_checkpoints(&request.body);
    }
    assert!(
        !requests[0].body["instructions"]
            .as_str()
            .unwrap()
            .is_empty()
    );
    assert_eq!(
        requests[0].body["instructions"],
        requests[1].body["instructions"]
    );
    assert_eq!(requests[0].body["tools"], requests[1].body["tools"]);
    let initial_input = requests[0].body["input"].as_array().unwrap();
    let history = requests[1].body["input"].as_array().unwrap();
    assert_eq!(history.len(), initial_input.len() + 2);
    assert_eq!(&history[..initial_input.len()], initial_input.as_slice());
    assert_eq!(history[initial_input.len()]["type"], "function_call");
    assert_eq!(history[initial_input.len()]["call_id"], "read");
    assert_eq!(
        history[initial_input.len() + 1]["type"],
        "function_call_output"
    );
    assert_eq!(history[initial_input.len() + 1]["call_id"], "read");
    let usage = fixture.usage();
    assert_eq!(usage["backend"], "openai");
    assert_eq!(usage["outcome"], "completed");
    assert_eq!(usage["request_count"], 2);
    assert_eq!(usage["tokens"]["input"], 22);
    assert_eq!(usage["tokens"]["output"], 14);
    assert_eq!(usage["tokens"]["cached_input"], 6);
    assert_eq!(usage["tokens"]["reasoning"], 4);
    assert!(!usage.to_string().contains(AUTH));
}

Referenced definitions

Input 2: requirements selection requirements.authoring.usage_requests.failures
:::{req} usage_requests.failures
Usage MUST record, for each failed provider request, its HTTP status and
provider error code when the provider reports them, and whether the harness
retried it. It MUST NOT record the failure's message text.
:::

Other sources

Input 1: requirements selection requirements.authoring.usage_requests
:::{req} usage_requests
Usage MUST record each provider request's outcome and available input/output
token counts, including retries, with cached or reasoning-token counts when
provided, and for a failed request the failure under
{cite}`requirements.authoring.usage_requests.failures`. Missing measurements MUST be recorded as unavailable, not zero.
Run totals MUST include request and tool-call counts by tool, elapsed time, and
available token usage, identifying incomplete totals without double counting
provider counters that overlap.
:::
Input 18: outline src/authoring/usage.rs impl[UsageLog]/fn[end_request]
    pub(super) fn end_request(
        &mut self,
        index: usize,
        elapsed: u128,
        usage: Option<&Usage>,
        failure: Option<(Option<u16>, Option<String>)>,
    ) -> io::Result<()> {
        let tokens = usage.map(TokenCounts::from_usage).unwrap_or_default();
        if usage.is_some() {
            for input in &mut self.record.inputs {
                if input.sent_in_request.is_none() && input.submitted_in_request.is_some() {
                    input.sent_in_request = Some(index);
                }
            }
        }
        self.record.requests[index] = RequestUsage {
            outcome: if usage.is_some() {
                "completed"
            } else {
                "failed"
            }
            .into(),
            elapsed_ms: elapsed,
            tokens,
            failure: failure.map(|(http_status, error_code)| RequestFailure {
                http_status,
                error_code,
                retried: false,
            }),
        };
        self.record.tokens = TokenCounts::sum(&self.record.requests);
        self.active_request = None;
        self.record.elapsed_ms = self.started.elapsed().as_millis();
        if let Some(finished) = self.first_request_finished.take() {
            finished();
        }
        self.save()
    }
Input 19: outline src/authoring/usage.rs impl[TokenCounts]
impl TokenCounts {
    fn from_usage(usage: &Usage) -> Self {
        Self {
            input: usage.input_tokens,
            output: usage.output_tokens,
            cached_input: usage.cached_input_tokens,
            cache_creation_input: usage.cache_creation_input_tokens,
            reasoning: usage.reasoning_tokens,
            complete: usage.input_tokens.is_some() && usage.output_tokens.is_some(),
        }
    }

    fn sum(requests: &[RequestUsage]) -> Self {
        if requests.is_empty() {
            return Self::default();
        }
        // Cache and reasoning counters are subsets, never added to token totals.
        // Keep measured subtotals when another request has no measurement.
        let (input, _) = Self::sum_counter(requests, |tokens| tokens.input);
        let (output, _) = Self::sum_counter(requests, |tokens| tokens.output);
        let (cached_input, cached_complete) =
            Self::sum_counter(requests, |tokens| tokens.cached_input);
        let (cache_creation_input, creation_complete) =
            Self::sum_counter(requests, |tokens| tokens.cache_creation_input);
        let (reasoning, reasoning_complete) =
            Self::sum_counter(requests, |tokens| tokens.reasoning);
        Self {
            input,
            output,
            cached_input,
            cache_creation_input,
            reasoning,
            complete: requests.iter().all(|r| r.tokens.complete)
                && cached_complete
                && creation_complete
                && reasoning_complete,
        }
    }

    fn sum_counter(
        requests: &[RequestUsage],
        counter: fn(&Self) -> Option<u64>,
    ) -> (Option<u64>, bool) {
        let mut measured = 0;
        let mut total = 0;
        for request in requests {
            if let Some(value) = counter(&request.tokens) {
                measured += 1;
                total += value;
            }
        }
        (
            (measured > 0).then_some(total),
            measured == 0 || measured == requests.len(),
        )
    }
}