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

Requirements index · View definition

evidence Valid

Requirement

impl requirements.configuration.feature_sections --config <name> MUST select a configuration for that invocation. Otherwise, authoring MUST use the user’s selection for the canonical project root, then the workspace default, then the user’s default. Named workspace configurations MUST override same-named user configurations as complete records. Backend, model, connection settings, and options MUST come from the selected record as a unit; fields MUST NOT be merged between records. Workspace-only authoring MUST work without a user configuration file. Missing configuration or an unknown selection MUST identify the relevant configuration file and point to documented examples.

An explicit Bedrock AWS profile or region MUST override the corresponding SDK default; omitted values MUST use standard AWS SDK resolution. Ollama MUST use its configured endpoint or http://localhost:11434. If api_key_env is set, its named variable MUST supply the credential; a missing or empty value MUST produce an error before a model request. OpenAI MUST use its configured endpoint or https://api.openai.com/v1, and MUST resolve OPENAI_API_KEY when neither api_key nor api_key_env is supplied.

Rationale

The marked tests cover every obligation in requirements.authoring.configuration_precedence.

Selection order and --config

  • tests/configuration.rs#fn[explicit_project_and_default_selections_choose_whole_configs] asserts three things. The user default is chosen when nothing else applies. A project selection is chosen once one exists for the root, and the root is passed as root.join("."), so canonicalisation is exercised. An explicit name wins over both the project selection and the default.
  • tests/configuration.rs#fn[workspace_defaults_and_configs_combine_with_existing_user_selections] covers the rest of the order. A workspace default beats the user default. A user project selection beats the workspace default. A workspace default naming a user config resolves to the user record. The user default is used when the workspace has no default. The explicit name workspace is selected even though a project selection exists.

Whole-record override and no merging

  • In workspace_defaults_and_configs_combine_with_existing_user_selections, the workspace shared config replaces the user one. The user record has a bedrock backend, concurrency 7 and temperature/top_p options. The resolved record has a model of replacement, no endpoint, concurrency None and options of only {temperature: 0.8}.
  • tests/configuration.rs#fn[workspace_configurations_accept_validate_and_override_concurrency] shows that concurrency from the user record does not leak through, for all three backends.

Workspace-only operation

  • tests/configuration.rs#fn[workspace_defaults_and_configs_combine_with_existing_user_selections] resolves with no user config.
  • tests/authoring_cli.rs#fn[authoring_uses_nearest_workspace_configuration_without_a_user_file] runs the CLI end to end with the user file deleted. It checks the model and the credential on the wire, and that no user file is created.

Missing configuration and unknown selection

  • explicit_project_and_default_selections_choose_whole_configs asserts that an unknown name or missing configuration yields an error naming config.toml and the editing-the-file documentation anchor.
  • tests/configuration.rs#fn[unknown_selections_name_the_file_that_made_them] covers a dangling user default, a dangling project selection and a dangling workspace default. It also covers an unknown --config name searched in both files, and the case with no workspace file.
  • tests/configuration.rs#fn[configurations_without_any_selection_report_how_to_choose_one] covers configurations that exist but are not selected.

Bedrock

  • src/authoring/providers.rs#mod[tests]/fn[omitted_bedrock_profile_and_region_use_standard_sdk_resolution] shows that omitted values match plain SDK resolution. It also shows that an explicit profile resolves as the SDK would and that an explicit region overrides the profile’s region.
  • explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain checks explicit credentials and region.
  • tests/authoring_cli.rs#fn[bedrock_cli_uses_selected_profile_region_and_converse_tools] is an end-to-end test. A profile and region are set against a wrong default profile, and the SigV4 credential and region on the wire are asserted.
  • all_adapters_preserve_prompt_tools_and_evidence_with_default_connections covers the default chain when neither value is given. It asserts the environment key and the ap-south-1 region.

Ollama and OpenAI

  • backend_configuration_round_trips_without_materializing_defaults asserts the Ollama default endpoint http://localhost:11434. tests/configuration.rs#fn[openai_configuration_preserves_model_and_resolves_credentials] asserts the OpenAI default endpoint https://api.openai.com/v1. It also asserts that OPENAI_API_KEY is the variable read when neither api_key nor api_key_env is set, and that a custom endpoint is used.
  • tests/configuration.rs#fn[ollama_authentication_resolves_separately_and_rejects_missing_values] and the OpenAI test show that a missing or empty api_key_env value is an error. A set value is returned.
  • tests/authoring_cli.rs#fn[missing_or_empty_api_key_env_fails_before_any_model_request] runs the CLI for ollama and openai with the variable unset and empty. It asserts a failure naming the variable and no connection to the listener.
  • all_adapters_preserve_prompt_tools_and_evidence_with_default_connections and openai_responses_replays_tool_calls_and_records_usage check the configured endpoints and keys on the wire.

Minor observation, not a gap tests/authoring_cli.rs#fn[an_explicit_configuration_selects_the_nondefault_workspace_profile] is the CLI-level test of the --config flag. It carries {test} references to requirements.authoring.invocation and requirements.authoring.configuration, but none to this requirement. The flag only passes the name to the resolver. The selection semantics are covered by the marked resolver tests above, so I treat this as not an adequacy gap.

Inputs

Tests

Input 2: outline src/authoring/providers.rs mod[tests]/fn[explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain]
    // {test}`requirements.authoring.credentials`
    // {test}`requirements.authoring.rig_configuration_mapping`
    // {test}`requirements.authoring.configuration_precedence`
    #[tokio::test]
    async fn explicit_bedrock_credentials_reach_the_sdk_without_the_default_chain() {
        let config: BedrockConfig = toml::from_str("model = 'test'\nregion = 'us-west-2'\n[credentials]\naccess_key_id = 'TEST_ACCESS'\nsecret_access_key = 'test-secret'\nsession_token = 'test-session'\n").unwrap();
        let sdk = bedrock_sdk_config(&config).await;
        let credentials = sdk
            .credentials_provider()
            .unwrap()
            .provide_credentials()
            .await
            .unwrap();
        assert_eq!(credentials.access_key_id(), "TEST_ACCESS");
        assert_eq!(credentials.secret_access_key(), "test-secret");
        assert_eq!(credentials.session_token(), Some("test-session"));
        assert_eq!(sdk.region().unwrap().as_ref(), "us-west-2");
    }
Input 3: outline src/authoring/providers.rs mod[tests]/fn[omitted_bedrock_profile_and_region_use_standard_sdk_resolution]
    // {test}`requirements.authoring.configuration_precedence`
    #[tokio::test]
    #[allow(deprecated)] // The non-deprecated profile-file names live in `aws-runtime`.
    // {test}`requirements.configuration.serialization`
    // {test}`requirements.authoring.credentials`
    async fn omitted_bedrock_profile_and_region_use_standard_sdk_resolution() {
        use aws_config::profile::profile_file::{ProfileFileKind, ProfileFiles};
        let dir = tempfile::tempdir().unwrap();
        let config_file = dir.path().join("config");
        let credentials_file = dir.path().join("credentials");
        std::fs::write(
            &config_file,
            "[default]\nregion = eu-west-1\n[profile other]\nregion = ap-south-1\n",
        )
        .unwrap();
        std::fs::write(
            &credentials_file,
            "[default]\naws_access_key_id = DEFAULT_KEY\naws_secret_access_key = DEFAULT_SECRET_VALUE\n\
             [other]\naws_access_key_id = OTHER_KEY\naws_secret_access_key = OTHER_SECRET_VALUE\n",
        )
        .unwrap();
        let files = ProfileFiles::builder()
            .with_file(ProfileFileKind::Config, &config_file)
            .with_file(ProfileFileKind::Credentials, &credentials_file)
            .build();
        let standard = || {
            aws_config::defaults(aws_config::BehaviorVersion::latest()).profile_files(files.clone())
        };
        let habeas = |text: &str| {
            let config: BedrockConfig = toml::from_str(text).unwrap();
            let before = toml::to_string(&config).unwrap();
            let loading = bedrock_sdk_loader(&config, standard()).load();
            async move {
                let sdk = loading.await;
                let credentials = sdk
                    .credentials_provider()
                    .unwrap()
                    .provide_credentials()
                    .await
                    .unwrap();
                let after = toml::to_string(&config).unwrap();
                assert_eq!(before, after);
                assert!(!after.contains(credentials.access_key_id()));
                assert!(!after.contains(credentials.secret_access_key()));
                sdk
            }
        };
        async fn resolved(sdk: aws_config::SdkConfig) -> (Option<String>, String) {
            let key = sdk
                .credentials_provider()
                .unwrap()
                .provide_credentials()
                .await
                .unwrap()
                .access_key_id()
                .to_owned();
            (sdk.region().map(|region| region.to_string()), key)
        }

        // Omitted values resolve exactly as the SDK would with no override.
        let omitted = resolved(habeas("model = 'test'").await).await;
        assert_eq!(omitted, resolved(standard().load().await).await);
        // An explicit profile is the one the SDK resolves from.
        let profile = resolved(habeas("model = 'test'\naws_profile = 'other'").await).await;
        assert_eq!(
            profile,
            resolved(standard().profile_name("other").load().await).await
        );
        // An explicit region overrides whatever the profile or environment says.
        let region =
            resolved(habeas("model = 'test'\naws_profile = 'other'\nregion = 'us-east-2'").await)
                .await;
        assert_eq!(region.0.as_deref(), Some("us-east-2"));
        assert_eq!(region.1, profile.1);
    }
Input 4: 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 5: outline tests/authoring_cli.rs fn[authoring_uses_nearest_workspace_configuration_without_a_user_file]
// {test}`requirements.configuration.workspace_location`
// {test}`requirements.authoring.configuration`
// {test}`requirements.configuration.workspace_structure`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.configuration.serialization`
#[test]
// {test}`requirements.configuration.documentation`
fn authoring_uses_nearest_workspace_configuration_without_a_user_file() {
    let server = Server::start(vec![reply(vec![call(
        "submit",
        "submit_judgment",
        json!({"determination":true,"rationale":"The supplied sources support the subject."}),
    )])]);
    let fixture = Fixture::new(&server.endpoint);
    fs::remove_file(fixture.config.join("habeas/config.toml")).unwrap();
    fs::write(
        fixture.project.join("habeas.toml"),
        "version = 1\n[authoring]\ndefault = 'missing-parent-choice'\n",
    )
    .unwrap();
    let nested = fixture.project.join("src/nested");
    fs::create_dir(&nested).unwrap();
    let workspace = nested.join("habeas.toml");
    fs::write(
        &workspace,
        format!(
            "version = 1\n[authoring]\ndefault = 'workspace'\n[authoring.configs.workspace]\npolicy = 'once'\nbackend = 'ollama'\nmodel = 'workspace-model'\nendpoint = '{}'\napi_key = 'WORKSPACE_LITERAL_KEY'\n",
            server.endpoint
        ),
    )
    .unwrap();
    let configurations = [fixture.project.join("habeas.toml"), workspace.clone()];
    let before = configurations
        .iter()
        .map(|path| fs::read(path).unwrap())
        .collect::<Vec<_>>();
    let output = fixture
        .command()
        .current_dir(&nested)
        .args(["author", SUBJECT])
        .output()
        .unwrap();
    assert!(output.status.success(), "{output:?}");
    // Running the configured feature rewrites neither configuration file,
    // and creates no user configuration.
    for (path, before) in configurations.iter().zip(&before) {
        assert_eq!(&fs::read(path).unwrap(), before, "{}", path.display());
    }
    assert!(!fixture.config.join("habeas/config.toml").exists());
    let requests = server.finish();
    assert_eq!(requests.len(), 1);
    assert_eq!(requests[0].body["model"], "workspace-model");
    assert!(requests[0].headers.contains("WORKSPACE_LITERAL_KEY"));
    assert!(
        !requests[0]
            .body
            .to_string()
            .contains("WORKSPACE_LITERAL_KEY")
    );
    let usage = fixture.usage();
    assert_eq!(usage["model"], "workspace-model");
    for text in [
        usage.to_string(),
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    ] {
        assert!(!text.contains("WORKSPACE_LITERAL_KEY"), "{text}");
    }
}
Input 6: 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 7: outline tests/authoring_cli.rs fn[all_adapters_preserve_prompt_tools_and_evidence_with_default_connections]
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.configuration_precedence`
#[test]
fn all_adapters_preserve_prompt_tools_and_evidence_with_default_connections() {
    let submit =
        json!({"determination":true,"rationale":"The supplied sources support the subject."});

    // Ollama with no authentication configured sends no credential.
    let server = Server::start(vec![reply(vec![call(
        "submit",
        "submit_judgment",
        submit.clone(),
    )])]);
    let fixture = Fixture::new(&server.endpoint);
    fs::write(
        fixture.config.join("habeas/config.toml"),
        format!(
            "version = 1\n[authoring]\ndefault = 'local'\n[authoring.configs.local]\npolicy = 'once'\nbackend = 'ollama'\nmodel = '{MODEL}'\nendpoint = '{}'\n",
            server.endpoint
        ),
    )
    .unwrap();
    let output = fixture.run(&["author", SUBJECT]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let requests = server.finish();
    assert_eq!(requests.len(), 1);
    assert!(
        !requests[0]
            .headers
            .to_ascii_lowercase()
            .contains("authorization:")
    );
    assert_eq!(requests[0].body["model"], MODEL);
    let ollama = prompt_and_tools(&requests[0].body);
    let ollama_evidence: Value =
        serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();

    // Bedrock without a profile or region uses the SDK default chain.
    let server = Server::start(vec![json!({
        "output":{"message":{"role":"assistant","content":[{"toolUse":
            {"toolUseId":"submit","name":"submit_judgment","input":submit.clone()}}]}},
        "stopReason":"tool_use",
        "usage":{"inputTokens":1,"outputTokens":1,"totalTokens":2},
        "metrics":{"latencyMs":1}
    })]);
    let fixture = Fixture::new(&server.endpoint);
    fs::write(
        fixture.config.join("habeas/config.toml"),
        "version = 1\n[authoring]\ndefault = 'cloud'\n[authoring.configs.cloud]\npolicy = 'once'\nbackend = 'bedrock'\nmodel = 'default-chain-model'\n",
    )
    .unwrap();
    let mut command = fixture.command();
    for key in [
        "AWS_SESSION_TOKEN",
        "AWS_SECURITY_TOKEN",
        "AWS_PROFILE",
        "AWS_DEFAULT_PROFILE",
        "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", fixture.temp.path().join("no-aws-config"))
        .env(
            "AWS_SHARED_CREDENTIALS_FILE",
            fixture.temp.path().join("no-aws-credentials"),
        )
        .env("AWS_ACCESS_KEY_ID", "DEFAULT_CHAIN_ACCESS_KEY")
        .env("AWS_SECRET_ACCESS_KEY", "default-chain-secret")
        .env("AWS_REGION", "ap-south-1")
        .env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", &server.endpoint)
        .env("AWS_EC2_METADATA_DISABLED", "true")
        .args(["author", SUBJECT])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let requests = server.finish();
    assert_eq!(requests.len(), 1);
    let headers = &requests[0].headers;
    assert!(headers.starts_with("POST /model/default-chain-model/converse HTTP/1.1\r\n"));
    assert!(headers.contains("Credential=DEFAULT_CHAIN_ACCESS_KEY/"));
    assert!(headers.contains("/ap-south-1/bedrock/aws4_request"));
    let bedrock = prompt_and_tools(&requests[0].body);

    let bedrock_evidence: Value =
        serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();

    // OpenAI uses its default credential environment variable.
    let server = Server::start(vec![json!({
        "id":"resp_submit", "object":"response", "status":"completed",
        "model":"fixture-openai", "output":[{
            "type":"function_call", "id":"fc_submit", "call_id":"submit",
            "name":"submit_judgment", "arguments":submit.to_string(), "status":"completed"
        }],
        "usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}
    })]);
    let fixture = Fixture::new(&server.endpoint);
    fs::write(
        fixture.config.join("habeas/config.toml"),
        format!("version = 1\n[authoring]\ndefault = 'api'\n[authoring.configs.api]\npolicy = 'once'\nbackend = 'openai'\nmodel = 'fixture-openai'\nendpoint = '{}'\n", server.endpoint),
    ).unwrap();
    let output = fixture
        .command()
        .env("OPENAI_API_KEY", AUTH)
        .args(["author", SUBJECT])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let requests = server.finish();
    assert_eq!(requests.len(), 1);
    assert!(
        requests[0]
            .headers
            .starts_with("POST /responses HTTP/1.1\r\n")
    );
    assert!(requests[0].headers.contains(&format!("Bearer {AUTH}")));
    assert_eq!(requests[0].body["model"], "fixture-openai");
    let openai = prompt_and_tools(&requests[0].body);
    let openai_evidence: Value =
        serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();

    // Identical projects and submissions must preserve both request semantics
    // and the entire evidence document, including inputs and reference hashes.
    assert_eq!(ollama, bedrock);
    assert_eq!(ollama, openai);
    assert_eq!(ollama.1.len(), 10);
    assert_eq!(ollama_evidence["requirement"], REQUIREMENT);
    assert_eq!(ollama_evidence["determination"], true);
    assert_eq!(ollama_evidence["rationale"], submit["rationale"]);
    assert_eq!(ollama_evidence, bedrock_evidence);
    assert_eq!(ollama_evidence, openai_evidence);
}
Input 8: outline tests/authoring_cli.rs fn[missing_or_empty_api_key_env_fails_before_any_model_request]
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
#[test]
fn missing_or_empty_api_key_env_fails_before_any_model_request() {
    let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
    listener.set_nonblocking(true).unwrap();
    let fixture = Fixture::new(&format!("http://{}", listener.local_addr().unwrap()));
    let config_path = fixture.config.join("habeas/config.toml");
    let original_config = fs::read_to_string(&config_path).unwrap();
    for backend in ["ollama", "openai"] {
        fs::write(
            &config_path,
            original_config.replace("backend = 'ollama'", &format!("backend = '{backend}'")),
        )
        .unwrap();
        for value in [None, Some("")] {
            let mut command = fixture.command();
            match value {
                None => command.env_remove("HABEAS_TEST_MODEL_KEY"),
                Some(value) => command.env("HABEAS_TEST_MODEL_KEY", value),
            };
            let output = command.args(["author", SUBJECT]).output().unwrap();
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(!output.status.success(), "{value:?}: {stderr}");
            assert!(
                stderr.contains("HABEAS_TEST_MODEL_KEY"),
                "{value:?}: {stderr}"
            );
            assert!(
                matches!(listener.accept(), Err(error) if error.kind() == std::io::ErrorKind::WouldBlock),
                "{value:?}: the model endpoint was contacted"
            );
            assert_eq!(
                fs::read_to_string(&fixture.evidence).unwrap(),
                fixture.original
            );
        }
    }
}
Input 9: 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));
}
Input 10: outline tests/configuration.rs fn[backend_configuration_round_trips_without_materializing_defaults]
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.concurrency`
// {test}`requirements.configuration.serialization`
#[test]
// {test}`requirements.configuration.loading`
fn backend_configuration_round_trips_without_materializing_defaults() {
    let source = r#"
version = 1
[authoring]
default = "Cloud"
[authoring.configs.Cloud]
backend = "bedrock"
model = "arn:aws:bedrock:us-west-2:123:inference-profile/exact-id"
aws_profile = "research"
region = "us-west-2"
[authoring.configs.Cloud.options]
temperature = 0.2
max_tokens = 777
enabled = true
labels = ["a", "b"]
[authoring.configs.Cloud.options.custom]
arbitrary = "provider-defined"
[authoring.configs.local]
backend = "ollama"
model = "tiny:latest"
"#;
    let path = Path::new("settings.toml");
    let config = UserConfig::parse(source, path).unwrap();
    let authoring = config.authoring.as_ref().unwrap();
    assert!(authoring.projects.is_empty());
    let local = &authoring.configs["local"].backend;
    let BackendConfig::Ollama(ollama) = local else {
        panic!("wrong backend")
    };
    assert_eq!(ollama.endpoint(), "http://localhost:11434");
    assert_eq!(ollama.endpoint, None);
    assert!(ollama.options.is_empty());
    assert_eq!(local.model_ref().model, "tiny:latest");
    assert_eq!(local.model_ref().backend, BackendKind::Ollama);
    let json = authoring.configs["Cloud"].backend.options_json().unwrap();
    assert_eq!(json["custom"]["arbitrary"], "provider-defined");
    assert_eq!(json["max_tokens"], 777);
    let serialized = config.to_toml().unwrap();
    assert!(!serialized.contains("endpoint"));
    assert!(!serialized.contains("http://localhost"));
    assert!(!serialized.contains("concurrency"));
    assert_eq!(UserConfig::parse(&serialized, path).unwrap(), config);
}
Input 11: outline tests/configuration.rs fn[authoring_concurrency_defaults_overrides_and_invalid_values]
// {test}`requirements.authoring.concurrency`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.configuration.loading`
// {test}`requirements.configuration.serialization`
#[test]
fn authoring_concurrency_defaults_overrides_and_invalid_values() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    for backend in ["bedrock", "ollama", "openai"] {
        let base =
            format!("version = 1\n[authoring.configs.model]\nbackend = '{backend}'\nmodel = 'm'\n");
        let defaults = UserConfig::parse(&base, &path).unwrap();
        let resolved =
            resolve_authoring_from(&path, Some(&defaults), dir.path(), Some("model")).unwrap();
        assert_eq!(resolved.concurrency, None);
        let expected = if backend != "ollama" {
            std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(1)
        } else {
            1
        };
        assert_eq!(resolved.effective_concurrency(), expected);
        assert!(!defaults.to_toml().unwrap().contains("concurrency"));

        let configured = UserConfig::parse(&format!("{base}concurrency = 7\n"), &path).unwrap();
        let resolved =
            resolve_authoring_from(&path, Some(&configured), dir.path(), Some("model")).unwrap();
        assert_eq!(resolved.concurrency.unwrap().get(), 7);
        assert_eq!(resolved.effective_concurrency(), 7);
        let serialized = configured.to_toml().unwrap();
        assert!(serialized.contains("concurrency = 7"));
        assert_eq!(UserConfig::parse(&serialized, &path).unwrap(), configured);
        assert!(resolved.backend.options().is_empty());

        for invalid in ["0", "-1", "1.5", "'2'"] {
            let error = UserConfig::parse(&format!("{base}concurrency = {invalid}\n"), &path)
                .unwrap_err()
                .to_string();
            assert!(error.contains(&path.display().to_string()), "{error}");
            assert!(error.contains("concurrency"), "{error}");
        }
    }
}
Input 12: outline tests/configuration.rs fn[explicit_project_and_default_selections_choose_whole_configs]
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration`
// {test}`requirements.configuration.loading`
// {test}`requirements.configuration.structure`
#[test]
// {test}`requirements.authoring.configuration_structure`
fn explicit_project_and_default_selections_choose_whole_configs() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().canonicalize().unwrap();
    let config_path = root.join("config.toml");
    let mut config = UserConfig::parse(
        r#"
version = 1
[authoring]
default = "default"
[authoring.configs.default]
backend = "bedrock"
model = "cloud-id"
aws_profile = "named"
[authoring.configs.project]
backend = "ollama"
model = "project:tag"
endpoint = "http://server:11434"
[authoring.configs.explicit]
backend = "ollama"
model = "explicit:tag"
"#,
        &config_path,
    )
    .unwrap();
    assert_eq!(
        resolve_authoring_from(&config_path, Some(&config), &root, None)
            .unwrap()
            .name,
        "default"
    );
    config.authoring.as_mut().unwrap().projects.insert(
        root.clone(),
        habeas::config::ProjectSelection {
            config: "project".to_owned(),
        },
    );
    let project =
        resolve_authoring_from(&config_path, Some(&config), &root.join("."), None).unwrap();
    assert_eq!(project.name, "project");
    assert_eq!(project.project_root, root);
    let BackendConfig::Ollama(ollama) = project.backend else {
        panic!("wrong backend")
    };
    assert_eq!(ollama.endpoint(), "http://server:11434");
    let explicit =
        resolve_authoring_from(&config_path, Some(&config), &root, Some("explicit")).unwrap();
    let BackendConfig::Ollama(ollama) = explicit.backend else {
        panic!("wrong backend")
    };
    assert_eq!(ollama.model, "explicit:tag");
    assert_eq!(ollama.endpoint, None);
    let error = resolve_authoring_from(&config_path, Some(&config), &root, Some("DEFAULT"))
        .unwrap_err()
        .to_string();
    assert!(error.contains("DEFAULT"));
    assert!(error.contains("config.toml"));
    assert!(error.contains("editing-the-file"));
    // Missing configuration names the file and points to documented examples.
    let missing = resolve_authoring_from(&config_path, None, &root, None)
        .unwrap_err()
        .to_string();
    assert!(missing.contains("no authoring configuration"), "{missing}");
    assert!(
        missing.contains(&config_path.display().to_string()),
        "{missing}"
    );
    assert!(missing.contains("editing-the-file"), "{missing}");
}
Input 13: outline tests/configuration.rs fn[configurations_without_any_selection_report_how_to_choose_one]
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.configuration.loading`
#[test]
fn configurations_without_any_selection_report_how_to_choose_one() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().canonicalize().unwrap();
    let config_path = root.join("config.toml");
    // Configurations exist, but no name, project entry, or default selects one.
    let unselected = UserConfig::parse(
        "version = 1\n[authoring.configs.only]\nbackend = 'ollama'\nmodel = 'm:tag'\n",
        &config_path,
    )
    .unwrap();
    let error = resolve_authoring_from(&config_path, Some(&unselected), &root, None)
        .unwrap_err()
        .to_string();
    assert!(error.contains("no configuration selected"), "{error}");
    assert!(error.contains("editing-the-file"), "{error}");
}
Input 14: outline tests/configuration.rs fn[ollama_authentication_resolves_separately_and_rejects_missing_values]
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
// {test}`requirements.configuration.serialization`
#[test]
fn ollama_authentication_resolves_separately_and_rejects_missing_values() {
    let config = UserConfig::parse(
        "version = 1\n[authoring.configs.remote]\nbackend = 'ollama'\nmodel = 'm'\napi_key_env = 'MODEL_KEY'",
        Path::new("config.toml"),
    ).unwrap();
    let BackendConfig::Ollama(ollama) =
        &config.authoring.as_ref().unwrap().configs["remote"].backend
    else {
        panic!("wrong backend")
    };
    assert!(ollama.api_key_from(|_| None).is_err());
    assert!(ollama.api_key_from(|_| Some(OsString::new())).is_err());
    assert_eq!(
        ollama
            .api_key_from(|name| (name == "MODEL_KEY").then(|| OsString::from("private-value")))
            .unwrap()
            .as_deref(),
        Some("private-value")
    );
    let serialized = config.to_toml().unwrap();
    assert!(serialized.contains("MODEL_KEY"));
    assert!(!serialized.contains("private-value"));
}
Input 15: outline tests/configuration.rs fn[workspace_defaults_and_configs_combine_with_existing_user_selections]
// {test}`requirements.configuration.workspace_structure`
// {test}`requirements.authoring.configuration`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.configuration.serialization`
#[test]
fn workspace_defaults_and_configs_combine_with_existing_user_selections() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().canonicalize().unwrap();
    let user_path = root.join("user.toml");
    let mut user = UserConfig::parse("version = 1\n[authoring]\ndefault = 'user'\n[authoring.configs.user]\nbackend = 'bedrock'\nmodel = 'user-model'\naws_profile = 'user-profile'\n[authoring.configs.shared]\nbackend = 'bedrock'\nmodel = 'old-model'\nregion = 'us-west-2'\nconcurrency = 7\noptions = { temperature = 0.25, top_p = 0.5 }\n", &user_path).unwrap();
    let path = root.join("habeas.toml");
    fs::write(&path, "version = 1\n[authoring]\ndefault = 'workspace'\n[authoring.configs.workspace]\nbackend = 'ollama'\nmodel = 'workspace-model'\n[authoring.configs.shared]\nbackend = 'ollama'\nmodel = 'replacement'\noptions = { temperature = 0.8 }\n").unwrap();
    let mut workspace = load_workspace_config(&root).unwrap().unwrap();
    let selected = resolve_authoring_with_workspace_from(
        &user_path,
        Some(&user),
        Some(&workspace),
        &root,
        None,
    )
    .unwrap();
    assert_eq!(selected.name, "workspace");
    assert_eq!(selected.config_path, path);
    let replaced = resolve_authoring_with_workspace_from(
        &user_path,
        Some(&user),
        Some(&workspace),
        &root,
        Some("shared"),
    )
    .unwrap();
    assert_eq!(replaced.config_path, path);
    assert_eq!(replaced.concurrency, None);
    assert_eq!(
        replaced.backend.options_json().unwrap(),
        serde_json::json!({"temperature":0.8})
    );
    assert!(
        matches!(&replaced.backend, BackendConfig::Ollama(config) if config.model == "replacement" && config.endpoint.is_none())
    );

    user.authoring.as_mut().unwrap().projects.insert(
        root.clone(),
        habeas::config::ProjectSelection {
            config: "user".into(),
        },
    );
    let project = resolve_authoring_with_workspace_from(
        &user_path,
        Some(&user),
        Some(&workspace),
        &root,
        None,
    )
    .unwrap();
    assert_eq!(project.name, "user");
    assert_eq!(project.config_path, user_path);
    let explicit = resolve_authoring_with_workspace_from(
        &user_path,
        Some(&user),
        Some(&workspace),
        &root,
        Some("workspace"),
    )
    .unwrap();
    assert_eq!(explicit.name, "workspace");
    user.authoring.as_mut().unwrap().projects.clear();
    workspace.config.authoring.as_mut().unwrap().default = Some("user".into());
    let user_reference = resolve_authoring_with_workspace_from(
        &user_path,
        Some(&user),
        Some(&workspace),
        &root,
        None,
    )
    .unwrap();
    assert_eq!(user_reference.name, "user");
    assert_eq!(user_reference.config_path, user_path);
    workspace.config.authoring.as_mut().unwrap().default = None;
    assert_eq!(
        resolve_authoring_with_workspace_from(
            &user_path,
            Some(&user),
            Some(&workspace),
            &root,
            None
        )
        .unwrap()
        .name,
        "user"
    );
    workspace.config.authoring.as_mut().unwrap().default = Some("workspace".into());
    let workspace_only =
        resolve_authoring_with_workspace_from(&user_path, None, Some(&workspace), &root, None)
            .unwrap();
    assert_eq!(workspace_only.name, "workspace");
    let error = resolve_authoring_with_workspace_from(
        &user_path,
        Some(&user),
        Some(&workspace),
        &root,
        Some("missing"),
    )
    .unwrap_err()
    .to_string();
    assert!(
        error.contains(path.to_str().unwrap()) && error.contains("missing"),
        "{error}"
    );
}
Input 16: outline tests/configuration.rs fn[unknown_selections_name_the_file_that_made_them]
// {test}`requirements.authoring.configuration_precedence`
#[test]
fn unknown_selections_name_the_file_that_made_them() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().canonicalize().unwrap();
    let user_path = root.join("user.toml");
    let workspace_path = root.join("habeas.toml");
    let user_text = user_path.to_str().unwrap();
    let workspace_text = workspace_path.to_str().unwrap();
    fs::write(
        &workspace_path,
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\n",
    )
    .unwrap();
    let mut workspace = load_workspace_config(&root).unwrap().unwrap();
    let mut user = UserConfig::parse(
        "version = 1\n[authoring]\ndefault = 'user-default'\n[authoring.configs.other]\nbackend = 'ollama'\nmodel = 'm'\n",
        &user_path,
    )
    .unwrap();
    let resolve = |user: &UserConfig,
                   workspace: Option<&habeas::config::LoadedWorkspaceConfig>,
                   explicit: Option<&str>| {
        resolve_authoring_with_workspace_from(&user_path, Some(user), workspace, &root, explicit)
            .unwrap_err()
            .to_string()
    };

    // A dangling user default is reported against the user file even though a
    // workspace file exists, and both searched files are listed.
    let error = resolve(&user, Some(&workspace), None);
    assert!(error.starts_with(&format!("{user_text}: ")), "{error}");
    assert!(error.contains("\"user-default\""), "{error}");
    assert!(error.contains(workspace_text), "{error}");
    assert!(error.contains("editing-the-file"), "{error}");

    // So is a dangling project selection, which outranks the default.
    user.authoring.as_mut().unwrap().projects.insert(
        root.clone(),
        habeas::config::ProjectSelection {
            config: "project-choice".into(),
        },
    );
    let error = resolve(&user, Some(&workspace), None);
    assert!(error.starts_with(&format!("{user_text}: ")), "{error}");
    assert!(error.contains("\"project-choice\""), "{error}");
    user.authoring.as_mut().unwrap().projects.clear();

    // A dangling workspace default is reported against the workspace file.
    workspace.config.authoring.as_mut().unwrap().default = Some("gone".into());
    let error = resolve(&user, Some(&workspace), None);
    assert!(error.starts_with(&format!("{workspace_text}: ")), "{error}");
    assert!(error.contains("\"gone\""), "{error}");
    assert!(error.contains(user_text), "{error}");

    // An unknown `--config` name was searched for in both files.
    let error = resolve(&user, Some(&workspace), Some("absent"));
    assert!(error.contains("\"absent\""), "{error}");
    assert!(
        error.contains(user_text) && error.contains(workspace_text),
        "{error}"
    );

    // With no workspace file, only the user file is named.
    let error = resolve(&user, None, Some("absent"));
    assert!(error.starts_with(&format!("{user_text}: ")), "{error}");
    assert!(!error.contains(workspace_text), "{error}");
}
Input 17: outline tests/configuration.rs fn[workspace_configurations_accept_validate_and_override_concurrency]
// {test}`requirements.authoring.concurrency`
// {test}`requirements.authoring.configuration_precedence`
#[test]
fn workspace_configurations_accept_validate_and_override_concurrency() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().canonicalize().unwrap();
    let user_path = root.join("user.toml");
    let user = UserConfig::parse(
        "version = 1\n[authoring.configs.shared]\nbackend = 'bedrock'\nmodel = 'user'\nconcurrency = 5\n",
        &user_path,
    )
    .unwrap();
    let path = root.join("habeas.toml");
    for (workspace, expected) in [("concurrency = 3\n", Some(3)), ("", None)] {
        for backend in ["bedrock", "ollama", "openai"] {
            fs::write(
                &path,
                format!("version = 1\n[authoring.configs.shared]\nbackend = '{backend}'\nmodel = 'local'\n{workspace}"),
            )
            .unwrap();
            let loaded = load_workspace_config(&root).unwrap().unwrap();
            let resolved = resolve_authoring_with_workspace_from(
                &user_path,
                Some(&user),
                Some(&loaded),
                &root,
                Some("shared"),
            )
            .unwrap();
            // The workspace config replaces the user config as a whole,
            // including its concurrency.
            assert_eq!(resolved.config_path, path);
            assert_eq!(resolved.concurrency.map(|value| value.get()), expected);
            let default = if backend != "ollama" {
                std::thread::available_parallelism()
                    .map(|n| n.get())
                    .unwrap_or(1)
            } else {
                1
            };
            assert_eq!(
                resolved.effective_concurrency(),
                expected.unwrap_or(default)
            );
            let serialized = loaded.config.to_toml().unwrap();
            assert_eq!(serialized.contains("concurrency = 3"), expected.is_some());
        }
    }
    for invalid in ["0", "-1", "1.5", "'2'"] {
        let text = format!(
            "version = 1\n[authoring.configs.shared]\nbackend = 'ollama'\nmodel = 'm'\nconcurrency = {invalid}\n"
        );
        let error = WorkspaceConfig::parse(&text, &path)
            .unwrap_err()
            .to_string();
        assert!(error.contains("concurrency"), "{error}");
        fs::write(&path, text).unwrap();
        let error = load_workspace_config(&root).unwrap_err().to_string();
        assert!(error.contains(path.to_str().unwrap()), "{error}");
        assert!(error.contains("concurrency"), "{error}");
    }
}
Input 18: outline tests/configuration.rs fn[openai_configuration_preserves_model_and_resolves_credentials]
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.configuration.serialization`
#[test]
fn openai_configuration_preserves_model_and_resolves_credentials() {
    let source =
        "version = 1\n[authoring.configs.api]\nbackend = 'openai'\nmodel = 'account-model-id'\n";
    let path = Path::new("settings.toml");
    let config = UserConfig::parse(source, path).unwrap();
    let backend = &config.authoring.as_ref().unwrap().configs["api"].backend;
    assert_eq!(backend.model_ref().backend, BackendKind::Openai);
    assert_eq!(backend.model_ref().model, "account-model-id");
    let BackendConfig::Openai(openai) = backend else {
        panic!("wrong backend")
    };
    assert_eq!(openai.endpoint(), "https://api.openai.com/v1");
    assert!(openai.api_key_from(|_| None).is_err());
    assert_eq!(
        openai
            .api_key_from(|name| {
                assert_eq!(name, "OPENAI_API_KEY");
                Some("test-key".into())
            })
            .unwrap()
            .as_str(),
        "test-key"
    );
    let serialized = config.to_toml().unwrap();
    assert!(!serialized.contains("api_key"));
    assert_eq!(UserConfig::parse(&serialized, path).unwrap(), config);
    for extra in [
        "api_key = 'secret'\napi_key_env = 'KEY'",
        "api_key_env = ''",
        "api_key = ''",
        "[authoring.configs.api.options]\ninput = 'override'",
        "[authoring.configs.api.options]\ninstructions = 'override'",
    ] {
        assert!(UserConfig::parse(&format!("{source}{extra}\n"), path).is_err());
    }
    let mut custom = openai.clone();
    custom.endpoint = Some("https://example.invalid/v1".into());
    custom.api_key_env = Some("CUSTOM_OPENAI_KEY".into());
    assert_eq!(custom.endpoint(), "https://example.invalid/v1");
    assert!(custom.api_key_from(|_| None).is_err());
    assert!(custom.api_key_from(|_| Some("".into())).is_err());
    assert_eq!(
        custom
            .api_key_from(|name| {
                assert_eq!(name, "CUSTOM_OPENAI_KEY");
                Some("custom-key".into())
            })
            .unwrap(),
        "custom-key"
    );
}
Input 19: outline tests/live_bedrock.rs fn[selected_config]
// {test}`requirements.authoring.configuration_precedence`
fn selected_config() -> Result<Option<LiveSelection>, Box<dyn Error>> {
    let root = fs::canonicalize(env!("CARGO_MANIFEST_DIR"))?;
    let explicit = match std::env::var("HABEAS_LIVE_CONFIG") {
        Ok(name) => Some(name),
        Err(std::env::VarError::NotPresent) => None,
        Err(error) => return Err(error.into()),
    };
    select_config(&config::user_config_path()?, &root, explicit.as_deref())
}
Input 20: outline tests/live_bedrock.rs fn[select_config]
/// Selects a Bedrock configuration from the user file at `path` and the
/// workspace configuration of `root`: an explicit name, else the selection
/// authoring would make for `root` when it is Bedrock, else the first Bedrock
/// configuration in name order.
// {test}`requirements.authoring.configuration_precedence`
fn select_config(
    path: &Path,
    root: &Path,
    explicit: Option<&str>,
) -> Result<Option<LiveSelection>, Box<dyn Error>> {
    let user = config::load_user_config(path)?;
    let workspace = config::load_workspace_config(root)?;
    let resolve = |name: &str| {
        config::resolve_authoring_with_workspace_from(
            path,
            user.as_ref(),
            workspace.as_ref(),
            root,
            Some(name),
        )
    };
    let bedrock =
        |selected: &ResolvedAuthoringConfig| matches!(selected.backend, BackendConfig::Bedrock(_));
    let authoring = user.as_ref().and_then(|user| user.authoring.as_ref());
    let local = workspace
        .as_ref()
        .and_then(|workspace| workspace.config.authoring.as_ref());
    let selected = if let Some(name) = explicit {
        let selected = resolve(name)?;
        if !bedrock(&selected) {
            return Err(
                format!("HABEAS_LIVE_CONFIG={name:?} must select a Bedrock configuration").into(),
            );
        }
        Some(selected)
    } else {
        // The same precedence as authoring: the user's selection for this
        // project, then the workspace default, then the user default.
        let preferred = authoring
            .and_then(|authoring| authoring.projects.get(root))
            .map(|selection| selection.config.as_str())
            .or_else(|| local.and_then(|local| local.default.as_deref()))
            .or_else(|| authoring.and_then(|authoring| authoring.default.as_deref()));
        let preferred = preferred
            .map(resolve)
            .transpose()?
            .filter(|selected| bedrock(selected));
        match preferred {
            Some(selected) => Some(selected),
            None => {
                let names = local
                    .into_iter()
                    .flat_map(|local| local.configs.keys())
                    .chain(
                        authoring
                            .into_iter()
                            .flat_map(|authoring| authoring.configs.keys()),
                    )
                    .collect::<std::collections::BTreeSet<_>>();
                let mut first = None;
                for name in names {
                    let selected = resolve(name)?;
                    if bedrock(&selected) {
                        first = Some(selected);
                        break;
                    }
                }
                first
            }
        }
    };
    let Some(config) = selected else {
        return Ok(None);
    };
    // The fixture project resolves `--config` against the same workspace
    // configurations as the checkout; other workspace settings stay behind.
    let workspace = match &workspace {
        Some(workspace) if workspace.config.authoring.is_some() => {
            let text = fs::read_to_string(&workspace.path)?;
            let mut table: toml::Table = toml::from_str(&text)?;
            table.retain(|key, _| key == "version" || key == "authoring");
            Some(toml::to_string(&table)?)
        }
        _ => None,
    };
    Ok(Some(LiveSelection { config, workspace }))
}
Input 21: outline tests/live_bedrock.rs fn[credentials_available]
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.credentials`
fn credentials_available(config: &BedrockConfig) -> bool {
    tokio::runtime::Runtime::new().unwrap().block_on(async {
        let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest());
        if let Some(profile) = &config.aws_profile {
            loader = loader.profile_name(profile);
        }
        if let Some(region) = &config.region {
            loader = loader.region(aws_config::Region::new(region.clone()));
        }
        if let Some(credentials) = &config.credentials {
            loader = loader.credentials_provider(aws_sdk_bedrockruntime::config::Credentials::new(
                credentials.access_key_id.expose_secret(),
                credentials.secret_access_key.expose_secret(),
                credentials.session_token.as_ref().map(|value| value.expose_secret().to_owned()),
                None,
                "Habeas configuration",
            ));
        }
        let sdk = loader.load().await;
        let Some(provider) = sdk.credentials_provider() else {
            report("warning: skipping live Bedrock test: no AWS credential provider");
            return false;
        };
        if let Err(error) = provider.provide_credentials().await {
            report(format!(
                "warning: skipping live Bedrock test: AWS credentials unavailable: {error}"
            ));
            return false;
        }
        assert!(
            sdk.region().is_some(),
            "live Bedrock test has credentials but no AWS region; set a profile region or the authoring configuration's region"
        );
        true
    })
}

Other sources

Input 1: requirements selection requirements.authoring.configuration_precedence
:::{req} configuration_precedence
{impl}`requirements.configuration.feature_sections`
`--config <name>` MUST select a configuration for that invocation. Otherwise,
authoring MUST use the user's selection for the canonical project root, then the
workspace default, then the user's default. Named workspace configurations MUST
override same-named user configurations as complete records. Backend, model,
connection settings, and options MUST come from the selected record as a unit;
fields MUST NOT be merged between records. Workspace-only authoring MUST work
without a user configuration file. Missing configuration or an unknown selection
MUST identify the relevant configuration file and point to documented examples.

An explicit Bedrock AWS profile or region MUST override the corresponding SDK
default; omitted values MUST use standard AWS SDK resolution. Ollama MUST use
its configured endpoint or `http://localhost:11434`. If `api_key_env` is set, its
named variable MUST supply the credential; a missing or empty value MUST produce
an error before a model request. OpenAI MUST use its configured endpoint or
`https://api.openai.com/v1`, and MUST resolve `OPENAI_API_KEY` when neither
`api_key` nor `api_key_env` is supplied.
:::
Input 22: outline tests/authoring_cli.rs fn[an_explicit_configuration_selects_the_nondefault_workspace_profile]
// {test}`requirements.authoring.invocation`
// {test}`requirements.authoring.configuration`
#[test]
fn an_explicit_configuration_selects_the_nondefault_workspace_profile() {
    let server = Server::start(vec![reply(vec![call(
        "submit",
        "submit_judgment",
        json!({"determination":true,"rationale":"The supplied sources support the subject."}),
    )])]);
    let fixture = Fixture::new(&server.endpoint);
    fs::remove_file(fixture.config.join("habeas/config.toml")).unwrap();
    let nested = fixture.project.join("src/nested");
    fs::create_dir(&nested).unwrap();
    fs::write(nested.join("habeas.toml"), format!(
        "version = 1\n[authoring]\ndefault = 'default'\n[authoring.configs.default]\nbackend = 'ollama'\nmodel = 'WRONG_DEFAULT_MODEL'\nendpoint = 'http://127.0.0.1:9'\n[authoring.configs.alternate]\npolicy = 'once'\nbackend = 'ollama'\nmodel = 'alternate-model'\nendpoint = '{}'\napi_key = 'ALTERNATE_TEST_KEY'\n", server.endpoint
    )).unwrap();
    let output = fixture
        .command()
        .current_dir(&nested)
        .args(["author", SUBJECT, "--config", "alternate", "--force"])
        .output()
        .unwrap();
    assert!(output.status.success(), "{output:?}");
    let requests = server.finish();
    assert_eq!(requests.len(), 1);
    assert_eq!(requests[0].body["model"], "alternate-model");
    assert!(requests[0].headers.contains("ALTERNATE_TEST_KEY"));
    assert_eq!(fixture.usage()["model"], "alternate-model");
    assert_eq!(fixture.usage()["backend"], "ollama");
}