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_storage

Requirements index · View definition

evidence Valid

Requirement

impl requirements.configuration.feature_sections Configuration names MUST match [A-Za-z0-9][A-Za-z0-9_-]* and be case-sensitive. Project-selection keys MUST be canonical absolute project-root paths. Model IDs MUST be nonempty opaque strings, preserving tags and ARNs. api_key_env MUST name a nonempty environment variable without = or NUL.

Authoring MUST validate its fields under cite requirements.configuration.loading. The options map MUST accept backend-defined inference settings rather than a closed Habeas list; the adapter MUST pass them through Rig’s provider parameter mechanism and report rejection by Rig or the provider. These options MUST NOT replace the selected model, the assessment prompt, or tool definitions.

Rationale

The reviewed tests cover every obligation in requirements.authoring.configuration_storage.

Configuration names ([A-Za-z0-9][A-Za-z0-9_-]*, case-sensitive):

  • tests/configuration.rs#fn[storage_rules_reject_each_invalid_field_with_its_setting] rejects an empty name, a.b, a b, é, -x and _x.
  • It also rejects a bad authoring.default, and a bad config name in a project selection.
  • Each rejection asserts that the error names both the file and the setting.
  • Workspace files are checked too.
  • The same test accepts Local and local as distinct names, plus A-1_b.
  • tests/configuration.rs#fn[explicit_project_and_default_selections_choose_whole_configs] shows that selecting DEFAULT fails, which confirms case sensitivity.

Project-selection keys (canonical absolute paths):

  • The storage test rejects a relative key, .., /./, a trailing slash and a symlink.
  • It accepts both the canonical existing root and a canonical root that does not exist.
  • fn[user_and_workspace_authoring_tables_round_trip_every_map] checks that a canonical key survives a round trip.

Model IDs (nonempty, opaque, tags and ARNs preserved):

  • An empty bedrock model is rejected in the storage test, and an empty ollama model is rejected in fn[invalid_schema_and_feature_values_report_the_configuration_path].
  • name:tag@sha256:abc is accepted unchanged.
  • The ARN and us.…:0 bedrock IDs are preserved exactly by model_ref() in the round-trip test.
  • The account-model-id openai model is preserved in fn[openai_configuration_preserves_model_and_resolves_credentials].

api_key_env (nonempty, no =, no NUL): the storage test rejects '', A=B and an embedded NUL, and asserts the setting name in each error. The openai test also rejects an empty api_key_env. A valid MODEL_KEY_1 is accepted.

Validation under requirements.configuration.loading: every rejection case asserts that the error contains the file path and the setting identifier.

options accepted as backend-defined settings:

  • fn[backend_configuration_round_trips_without_materializing_defaults] round-trips arbitrary and nested options such as custom.arbitrary.
  • The storage tests accept options, and the workspace round-trip test keeps option counts.

Pass-through via Rig’s provider mechanism:

  • The ollama CLI test in tests/authoring_cli.rs#fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free] asserts options.temperature and options.num_ctx in the request body.
  • fn[bedrock_cli_uses_selected_profile_region_and_converse_tools] asserts inferenceConfig and that top_k reaches additionalModelRequestFields.
  • fn[openai_responses_replays_tool_calls_and_records_usage] asserts max_output_tokens and reasoning.effort.
  • src/authoring/providers.rs#mod[tests]/fn[bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted] checks Bedrock option typing.

Reporting rejection by Rig or the provider: fn[provider_rejection_of_inference_options_is_reported] checks two cases.

  • A provider 400 response containing PROVIDER_REJECTED_OPTION appears in stderr, the command fails, and the options were sent unchanged.
  • A Rig-side Bedrock rejection (temperature = 'hot') is reported before any request is made.

Options must not replace the model, prompt or tools:

  • The storage test rejects option keys model, modelId, model_id, prompt, messages, system, tools, tool_choice, toolChoice and toolConfig for both ollama and bedrock.
  • The openai test rejects input and instructions.
  • I checked src/config.rs#impl[BackendConfig]/fn[validate], which applies one backend-independent reserved-key list. The two-backend loop therefore exercises the shared rule. This was a check on how far the test coverage reaches, not an assessment of correctness.
  • The CLI tests also assert that the configured model and request structure stay as selected.

No obligation lacks a test with assertions, and there are no acknowledged gaps.

Inputs

Tests

Input 3: outline src/authoring/providers.rs mod[tests]/fn[bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted]
    // {test}`requirements.authoring.configuration_storage`
    // {test}`requirements.authoring.rig_configuration_mapping`
    // {test}`requirements.authoring.output_limit`
    #[test]
    fn bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted() {
        let mut request = CompletionRequest::new("prompt");
        let mut options = Map::from_iter([("top_k".into(), json!(12))]);
        apply_bedrock_options(&mut request, &mut options).unwrap();
        assert!(request.temperature.is_none());
        assert_eq!(request.max_tokens, Some(16_384));
        assert!(request.options.is_default());
        assert_eq!(options["top_k"], 12);
        for value in [
            json!({"temperature":"hot"}),
            json!({"maxTokens":-1}),
            json!({"maxTokens":2147483648_u64}),
            json!({"topP":true}),
            json!({"stopSequences":"stop"}),
            json!({"inferenceConfig":{}}),
        ] {
            let mut options = value.as_object().unwrap().clone();
            assert!(
                apply_bedrock_options(&mut CompletionRequest::new("prompt"), &mut options).is_err()
            );
        }
    }
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[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 6: outline tests/authoring_cli.rs fn[provider_rejection_of_inference_options_is_reported]
// {test}`requirements.authoring.configuration_storage`
#[test]
fn provider_rejection_of_inference_options_is_reported() {
    let (endpoint, server) = reject_once(
        "400 Bad Request",
        r#"{"error":"PROVIDER_REJECTED_OPTION num_ctx"}"#,
    );
    let fixture = Fixture::new(&endpoint);
    let output = fixture.run(&["author", SUBJECT]);
    assert!(!output.status.success());
    let body = server.join().unwrap();
    // The configured options were passed through to the provider unchanged.
    assert_eq!(body["options"]["num_ctx"], 4096);
    assert_eq!(body["options"]["temperature"], 0.25);
    assert_eq!(body["model"], MODEL);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("PROVIDER_REJECTED_OPTION"), "{stderr}");
    assert_eq!(
        fs::read_to_string(&fixture.evidence).unwrap(),
        fixture.original
    );
    assert_eq!(fixture.usage()["outcome"], "failed");

    // Rig-side rejection of a Bedrock option is reported before any request.
    let fixture = Fixture::new("http://unused");
    fs::write(
        fixture.config.join("habeas/config.toml"),
        "version = 1\n[authoring]\ndefault = 'cloud'\n[authoring.configs.cloud]\npolicy = 'once'\nbackend = 'bedrock'\nmodel = 'm'\nregion = 'us-west-2'\n[authoring.configs.cloud.options]\ntemperature = 'hot'\n",
    )
    .unwrap();
    let output = fixture
        .command()
        .env("AWS_ACCESS_KEY_ID", "FAKE")
        .env("AWS_SECRET_ACCESS_KEY", "fake")
        .env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", "http://127.0.0.1:9")
        .env("AWS_EC2_METADATA_DISABLED", "true")
        .args(["author", SUBJECT])
        .output()
        .unwrap();
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Bedrock options.temperature must be a number"),
        "{stderr}"
    );
    assert_eq!(
        fs::read_to_string(&fixture.evidence).unwrap(),
        fixture.original
    );
}
Input 7: 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 8: 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 9: 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 10: 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 11: outline tests/configuration.rs fn[invalid_schema_and_feature_values_report_the_configuration_path]
// {test}`requirements.configuration.structure`
// {test}`requirements.configuration.loading`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.configuration.feature_sections`
#[test]
fn invalid_schema_and_feature_values_report_the_configuration_path() {
    let path = Path::new("/settings/habeas/config.toml");
    for source in [
        "version = 2",
        "version = '1'",
        "",
        "version = 1\nunknown = true",
        "version = 1\n[authoring]",
        "version = 1\n[authoring]\nconfigs = {}\ndefault = '_bad'",
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = ''",
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\nunknown = true",
        "version = 1\n[authoring.configs.local]\nbackend = 'unsupported'\nmodel = 'm'",
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key_env = 'BAD=KEY'",
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\n[authoring.configs.local.options]\nvalue = nan",
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\n[authoring.configs.local.options]\nmodel = 'override'",
        "version = 1\n[authoring]\nconfigs = {}\n[authoring.projects.relative]\nconfig = 'local'",
    ] {
        let error = UserConfig::parse(source, path).unwrap_err().to_string();
        assert!(error.contains("/settings/habeas/config.toml"), "{error}");
    }
    let valid = UserConfig::parse("version = 1\n[authoring]\nconfigs = {}", path).unwrap();
    assert!(valid.authoring.unwrap().configs.is_empty());
}
Input 12: 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 13: outline tests/configuration.rs fn[user_and_workspace_authoring_tables_round_trip_every_map]
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.configuration.serialization`
// {test}`requirements.authoring.configuration_storage`
#[test]
fn user_and_workspace_authoring_tables_round_trip_every_map() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().canonicalize().unwrap();
    let path = root.join("config.toml");

    // A user section with a project selection keeps the canonical key.
    let source = format!(
        "version = 1\n[authoring]\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm:tag'\n[authoring.projects.{:?}]\nconfig = 'local'\n",
        root.display().to_string()
    );
    let user = UserConfig::parse(&source, &path).unwrap();
    let projects = &user.authoring.as_ref().unwrap().projects;
    assert_eq!(projects[&root].config, "local");
    let serialized = user.to_toml().unwrap();
    assert!(serialized.contains("[authoring.projects."), "{serialized}");
    assert_eq!(UserConfig::parse(&serialized, &path).unwrap(), user);

    // A present-but-empty `configs` is preserved and still parses.
    let empty = UserConfig::parse("version = 1\n[authoring]\nconfigs = {}\n", &path).unwrap();
    let serialized = empty.to_toml().unwrap();
    assert!(serialized.contains("configs"), "{serialized}");
    let reparsed = UserConfig::parse(&serialized, &path).unwrap();
    assert_eq!(reparsed, empty);
    assert!(reparsed.authoring.unwrap().configs.is_empty());

    // A workspace table with populated configs and options round-trips, and
    // the production loader decodes it exactly as `WorkspaceConfig::parse`.
    let workspace_path = root.join("habeas.toml");
    let workspace_text = "version = 1\n[authoring]\ndefault = 'cloud'\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'arn:aws:bedrock:us-east-1:123:inference-profile/us.model-v1:0'\nregion = 'us-east-1'\n[authoring.configs.cloud.options]\ntemperature = 0.5\n[authoring.configs.cloud.options.nested]\nflag = true\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'local:7b'\n[authoring.configs.local.options]\nnum_ctx = 2048\n";
    fs::write(&workspace_path, workspace_text).unwrap();
    let workspace = WorkspaceConfig::parse(workspace_text, &workspace_path).unwrap();
    let loaded = load_workspace_config(&root).unwrap().unwrap();
    assert_eq!(loaded.config, workspace);
    let configs = &workspace.authoring.as_ref().unwrap().configs;
    assert_eq!(configs["cloud"].backend.options().len(), 2);
    assert_eq!(configs["local"].backend.options().len(), 1);
    let serialized = workspace.to_toml().unwrap();
    assert!(serialized.contains("backend = \"bedrock\""), "{serialized}");
    assert!(
        serialized.contains("[authoring.configs.cloud.options"),
        "{serialized}"
    );
    assert_eq!(
        WorkspaceConfig::parse(&serialized, &workspace_path).unwrap(),
        workspace
    );

    // `ModelRef` keeps the exact Bedrock identifier and nothing else.
    for (model, region) in [
        (
            "arn:aws:bedrock:us-east-1:123:inference-profile/us.model-v1:0",
            "us-east-1",
        ),
        ("us.anthropic.claude-v1:0", "eu-west-1"),
    ] {
        let config = UserConfig::parse(
            &format!("version = 1\n[authoring.configs.c]\nbackend = 'bedrock'\nmodel = '{model}'\naws_profile = 'p'\nregion = '{region}'\n"),
            &path,
        )
        .unwrap();
        let backend = &config.authoring.as_ref().unwrap().configs["c"].backend;
        assert_eq!(
            backend.model_ref(),
            habeas::config::ModelRef {
                backend: BackendKind::Bedrock,
                model: model.to_owned(),
            }
        );
        let BackendConfig::Bedrock(bedrock) = backend else {
            panic!("wrong backend")
        };
        assert_eq!(bedrock.aws_profile.as_deref(), Some("p"));
        assert_eq!(bedrock.region.as_deref(), Some(region));
    }
    let configured = UserConfig::parse("version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'local:tag'\nendpoint = 'http://server:11434'\n", &path).unwrap();
    let backend = &configured.authoring.as_ref().unwrap().configs["local"].backend;
    assert_eq!(backend.model_ref().model, "local:tag");
    let BackendConfig::Ollama(local) = backend else {
        panic!("wrong backend")
    };
    assert_eq!(local.endpoint.as_deref(), Some("http://server:11434"));
}
Input 14: outline tests/configuration.rs fn[storage_rules_reject_each_invalid_field_with_its_setting]
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.configuration.loading`
#[test]
fn storage_rules_reject_each_invalid_field_with_its_setting() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().canonicalize().unwrap();
    let path = root.join("config.toml");
    let named = |name: &str| {
        format!("version = 1\n[authoring.configs.{name}]\nbackend = 'ollama'\nmodel = 'm'\n")
    };
    let ollama = |extra: &str| format!("{}{extra}", named("local"));
    let project = |key: &str, config: &str| {
        format!(
            "version = 1\n[authoring]\nconfigs = {{}}\n[authoring.projects.{key:?}]\nconfig = '{config}'\n"
        )
    };
    let root_text = root.display().to_string();
    let base = root.file_name().unwrap().to_string_lossy().into_owned();
    let mut cases = vec![
        // Configuration names.
        (named("\"\""), "authoring.configs."),
        (named("\"a.b\""), "authoring.configs.a.b"),
        (named("\"a b\""), "authoring.configs.a b"),
        (named("\"é\""), "authoring.configs.é"),
        (named("\"-x\""), "authoring.configs.-x"),
        (named("_x"), "authoring.configs._x"),
        (
            "version = 1\n[authoring]\nconfigs = {}\ndefault = 'a.b'\n".to_owned(),
            "authoring.default",
        ),
        (project(&root_text, "bad name"), ".config"),
        // Project-selection keys must be canonical absolute paths.
        (project("relative", "local"), "authoring.projects.relative"),
        (
            project(&format!("{root_text}/../{base}"), "local"),
            "authoring.projects.",
        ),
        (
            project(&format!("{root_text}/./"), "local"),
            "authoring.projects.",
        ),
        (
            project(&format!("{root_text}/"), "local"),
            "authoring.projects.",
        ),
        // Model IDs.
        (
            "version = 1\n[authoring.configs.c]\nbackend = 'bedrock'\nmodel = ''\n".to_owned(),
            "authoring.configs.c.model",
        ),
        // `api_key_env` names.
        (
            ollama("api_key_env = ''\n"),
            "authoring.configs.local.api_key_env",
        ),
        (
            ollama("api_key_env = 'A=B'\n"),
            "authoring.configs.local.api_key_env",
        ),
        (
            ollama("api_key_env = \"A\\u0000B\"\n"),
            "authoring.configs.local.api_key_env",
        ),
        // Non-finite floats, including nested ones.
        (
            ollama("[authoring.configs.local.options]\nvalue = nan\n"),
            "authoring.configs.local.options.value",
        ),
        (
            ollama("[authoring.configs.local.options]\nvalue = inf\n"),
            "authoring.configs.local.options.value",
        ),
        (
            ollama("[authoring.configs.local.options]\nvalue = [1.0, -inf]\n"),
            "authoring.configs.local.options.value",
        ),
        (
            ollama("[authoring.configs.local.options.value]\ninner = nan\n"),
            "authoring.configs.local.options.value",
        ),
    ];
    #[cfg(unix)]
    {
        let link = root.join("link");
        std::os::unix::fs::symlink(&root, &link).unwrap();
        cases.push((
            project(&link.display().to_string(), "local"),
            "authoring.projects.",
        ));
    }
    // Options may not replace the model, prompt, or tools.
    for key in [
        "model",
        "modelId",
        "model_id",
        "prompt",
        "messages",
        "system",
        "tools",
        "tool_choice",
        "toolChoice",
        "toolConfig",
    ] {
        for backend in ["ollama", "bedrock"] {
            cases.push((
                format!("version = 1\n[authoring.configs.c]\nbackend = '{backend}'\nmodel = 'm'\n[authoring.configs.c.options]\n{key} = 'x'\n"),
                "authoring.configs.c.options.",
            ));
        }
    }
    for (source, setting) in &cases {
        let error = UserConfig::parse(source, &path).unwrap_err().to_string();
        assert!(error.contains(path.to_str().unwrap()), "{source}: {error}");
        assert!(error.contains(setting), "{source}: {error}");
    }

    // Workspace files apply the same name and field rules.
    let workspace_path = root.join("habeas.toml");
    for (source, setting) in [
        (
            "version = 1\n[authoring]\ndefault = '_bad'\n".to_owned(),
            "authoring.default",
        ),
        (named("\"a.b\""), "authoring.configs.a.b"),
        (
            ollama("api_key_env = ''\n"),
            "authoring.configs.local.api_key_env",
        ),
    ] {
        let error = WorkspaceConfig::parse(&source, &workspace_path)
            .unwrap_err()
            .to_string();
        assert!(error.contains("habeas.toml"), "{source}: {error}");
        assert!(error.contains(setting), "{source}: {error}");
    }

    // Accepted values: case-sensitive distinct names, opaque model IDs with
    // tags, a canonical existing root, and a canonical root that does not exist.
    let missing = root.join("not-yet-created");
    let accepted = UserConfig::parse(
        &format!(
            "version = 1\n[authoring]\n[authoring.configs.Local]\nbackend = 'ollama'\nmodel = 'name:tag@sha256:abc'\napi_key_env = 'MODEL_KEY_1'\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\n[authoring.configs.A-1_b]\nbackend = 'bedrock'\nmodel = 'arn:aws:bedrock:us-east-1:1:x/y'\n[authoring.projects.{root_text:?}]\nconfig = 'Local'\n[authoring.projects.{:?}]\nconfig = 'A-1_b'\n",
            missing.display().to_string()
        ),
        &path,
    )
    .unwrap();
    let authoring = accepted.authoring.unwrap();
    assert_eq!(authoring.configs.len(), 3);
    assert_eq!(
        authoring.configs["Local"].backend.model_ref().model,
        "name:tag@sha256:abc"
    );
    assert_eq!(authoring.projects.len(), 2);
}
Input 15: 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"
    );
}

Referenced definitions

Input 2: requirements selection requirements.configuration.loading
:::{req} loading
An operation MUST load user configuration only when its requirements call for
user settings. A missing user file MUST represent absent user configuration;
whether the operation can proceed MUST be defined by the feature. Loading MUST
NOT create a file, repair malformed input, or supply an undocumented selection.

When loading configuration, Habeas MUST report unreadable files, invalid TOML,
unsupported user-file versions, unknown common keys, and invalid common field
types. It MUST validate the feature sections used by that operation and report
invalid feature settings with the file and setting identified. Unknown keys in
an explicitly documented provider-owned options map MUST follow that feature's
validation rules.

An operation MUST NOT require or semantically validate configuration for a
feature it does not use. This isolation MUST NOT suppress TOML syntax errors in
a shared file that the operation otherwise needs to parse. In particular,
ordinary validation still requires a parseable `book.toml` while remaining
independent of authoring settings and the user configuration file. It MUST apply
the selected workspace's evidence path policy without loading its model clients
or credentials.
:::

Other sources

Input 1: requirements selection requirements.authoring.configuration_storage
:::{req} configuration_storage
{impl}`requirements.configuration.feature_sections`
Configuration names MUST match `[A-Za-z0-9][A-Za-z0-9_-]*` and be case-sensitive.
Project-selection keys MUST be canonical absolute project-root paths. Model IDs
MUST be nonempty opaque strings, preserving tags and ARNs. `api_key_env` MUST
name a nonempty environment variable without `=` or NUL.

Authoring MUST validate its fields under {cite}`requirements.configuration.loading`.
The `options` map MUST accept backend-defined inference settings rather than a
closed Habeas list; the adapter MUST pass them through Rig's provider parameter
mechanism and report rejection by Rig or the provider. These options MUST NOT
replace the selected model, the assessment prompt, or tool definitions.
:::
Input 16: outline src/config.rs impl[BackendConfig]/fn[validate]
    // {impl}`requirements.configuration.loading`
    // {impl}`requirements.configuration.feature_sections`
    // {impl}`requirements.authoring.openai_defaults`
    // {impl}`requirements.authoring.configuration_structure`
    fn validate(&self, path: &Path, setting: &str) -> io::Result<()> {
        if self.model_ref().model.is_empty() {
            return Err(invalid(
                path,
                &format!("{setting}.model"),
                "expected a nonempty model ID",
            ));
        }
        let api_key_env = match self {
            Self::Ollama(config) => &config.api_key_env,
            Self::Openai(config) => &config.api_key_env,
            Self::Bedrock(_) => &None,
        };
        if let Some(name) = api_key_env
            && (name.is_empty() || name.contains(['=', '\0']))
        {
            return Err(invalid(
                path,
                &format!("{setting}.api_key_env"),
                "expected a nonempty environment variable name without '=' or NUL",
            ));
        }
        match self {
            Self::Bedrock(config) => {
                if let Some(credentials) = &config.credentials {
                    if config.aws_profile.is_some() {
                        return Err(invalid(
                            path,
                            &format!("{setting}.credentials"),
                            "credentials and aws_profile cannot both be set",
                        ));
                    }
                    for (field, value) in [
                        ("access_key_id", Some(&credentials.access_key_id)),
                        ("secret_access_key", Some(&credentials.secret_access_key)),
                        ("session_token", credentials.session_token.as_ref()),
                    ] {
                        if value.is_some_and(|value| value.expose_secret().is_empty()) {
                            return Err(invalid(
                                path,
                                &format!("{setting}.credentials.{field}"),
                                "credential values must be nonempty",
                            ));
                        }
                    }
                }
            }
            Self::Ollama(config) => {
                if let Some(key) = &config.api_key {
                    if config.api_key_env.is_some() {
                        return Err(invalid(
                            path,
                            &format!("{setting}.api_key"),
                            "api_key and api_key_env cannot both be set",
                        ));
                    }
                    if key.expose_secret().is_empty() {
                        return Err(invalid(
                            path,
                            &format!("{setting}.api_key"),
                            "credential values must be nonempty",
                        ));
                    }
                }
            }
            Self::Openai(config) => {
                if let Some(key) = &config.api_key {
                    if config.api_key_env.is_some() {
                        return Err(invalid(
                            path,
                            &format!("{setting}.api_key"),
                            "api_key and api_key_env cannot both be set",
                        ));
                    }
                    if key.expose_secret().is_empty() {
                        return Err(invalid(
                            path,
                            &format!("{setting}.api_key"),
                            "credential values must be nonempty",
                        ));
                    }
                }
            }
        }
        for (key, value) in self.options() {
            let field = format!("{setting}.options.{key}");
            if matches!(
                key.as_str(),
                "model"
                    | "modelId"
                    | "model_id"
                    | "input"
                    | "instructions"
                    | "previous_response_id"
                    | "conversation"
                    | "prompt"
                    | "messages"
                    | "system"
                    | "tools"
                    | "tool_choice"
                    | "toolChoice"
                    | "toolConfig"
            ) {
                return Err(invalid(
                    path,
                    &field,
                    "options cannot replace the model, prompt, or tools",
                ));
            }
            value
                .validate()
                .map_err(|error| invalid(path, &field, error))?;
        }
        Ok(())
    }