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.configuration.serialization

Requirements index · View definition

evidence Valid

Requirement

Saved configuration MUST remain distinct from resolved runtime configuration. Serializing and deserializing a valid configuration MUST preserve its semantic values, including explicit versus omitted settings. Optional fields MAY be omitted on serialization; defaults and environment-derived values MUST NOT be materialized into omitted fields. TOML comments and formatting need not round-trip.

Loading configuration or running a configured feature MUST NOT rewrite the user or project configuration as a side effect. Resolved credentials and live runtime objects MUST NOT enter the serialized data structures. Explicitly supplied credential values are permitted only in the fields documented by the authoring feature; credentials resolved from a profile or environment MUST NOT be written back to configuration.

Rationale

The reviewed tests cover every obligation in requirements.configuration.serialization. I judged this from the supplied test source alone and requested no implementation source.

Round-trip preserves semantic values, explicit versus omitted

  • tests/configuration.rs#fn[backend_configuration_round_trips_without_materializing_defaults] parses a rich Bedrock/Ollama config and asserts UserConfig::parse(&serialized) == config. It also checks that the Ollama endpoint stays None.
  • fn[authoring_concurrency_defaults_overrides_and_invalid_values] covers omitted and explicit concurrency. The omitted case round-trips with no concurrency key. The explicit concurrency = 7 case is serialized and re-parsed equal.
  • fn[authoring_policy_defaults_to_confirm_and_round_trips] covers omitted policy and explicit confirm and once. Explicit confirm equals the default, and the test asserts it is still serialized as policy = "confirm".
  • fn[user_and_workspace_authoring_tables_round_trip_every_map] covers a present-but-empty configs, project selections, and workspace options.
  • fn[workspace_discovery_uses_nearest_file_without_merging_or_rewriting_it] round-trips a workspace config where allow and configs are omitted, and asserts configs is not serialized.
  • fn[absent_and_minimal_configuration_are_distinct_and_read_only] covers the absent file versus the minimal file.

Defaults and environment-derived values not materialized

  • fn[openai_defaults_are_effective_only_and_explicit_values_win] shows the effective default model, effort and max_output_tokens are used at runtime. It asserts they are absent from the serialized output unless the config set them explicitly.
  • The concurrency, policy and endpoint tests above make the same assertion for their defaults.
  • fn[ollama_authentication_resolves_separately_and_rejects_missing_values] and fn[openai_configuration_preserves_model_and_resolves_credentials] show that environment-resolved keys are absent from the serialized output. The api_key_env variable name is kept and the resolved value is not.

Loading or running does not rewrite configuration

  • fn[absent_and_minimal_configuration_are_distinct_and_read_only] checks that loading creates no file, and leaves an existing file byte-identical, comments included. It makes the same check for a malformed file.
  • fn[workspace_discovery_uses_nearest_file_without_merging_or_rewriting_it] makes the same checks for workspace config files.
  • tests/authoring_cli.rs#fn[ollama_cli_delivers_sources_records_fixme_and_keeps_usage_content_free] runs the whole CLI with an environment-resolved key and asserts the user config bytes are unchanged afterwards.
  • fn[authoring_uses_nearest_workspace_configuration_without_a_user_file] checks that the project config files are unchanged after a run and that no user config is created. It also checks that the literal key reaches only the request headers, and does not appear in the request body, usage, stdout or stderr.

Resolved credentials and live objects kept out of serialized data; explicit credentials only in documented fields

  • src/authoring/providers.rs#mod[tests]/fn[omitted_bedrock_profile_and_region_use_standard_sdk_resolution] loads real profile credentials. It asserts the serialized config is identical before and after, and does not contain the resolved access key or secret.
  • fn[explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them] round-trips explicit credentials in their documented fields (credentials.* and api_key). It also rejects malformed or misplaced credential forms, such as credentials given as a string, and redacts them from errors and Debug output.

Saved versus resolved config distinct

  • The resolve_authoring_from and resolve_authoring_with_workspace_from tests assert that resolved values, such as effective concurrency and policy, are separate from the stored Option fields. They also assert that the workspace-resolved config path is separate from the saved config.

No obligation lacks a test that exercises it and asserts the outcome, and I found no gaps.

Inputs

Tests

Input 2: 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 3: 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 4: 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 5: outline tests/configuration.rs fn[absent_and_minimal_configuration_are_distinct_and_read_only]
// {test}`requirements.configuration.structure`
// {test}`requirements.configuration.loading`
// {test}`requirements.configuration.serialization`
// {test}`requirements.configuration.workspace_structure`
#[test]
// {test}`requirements.configuration.documentation`
fn absent_and_minimal_configuration_are_distinct_and_read_only() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("user.toml");
    assert!(load_user_config(&path).unwrap().is_none());
    assert!(!path.exists());
    let original = "# keep this comment\nversion = 1\n";
    fs::write(&path, original).unwrap();
    let config = load_user_config(&path).unwrap().unwrap();
    assert!(config.authoring.is_none());
    assert_eq!(fs::read_to_string(&path).unwrap(), original);
    assert_eq!(
        UserConfig::parse(&config.to_toml().unwrap(), &path).unwrap(),
        config
    );
    let book = "[book]\nsrc = 'docs'\n";
    assert!(
        ProjectConfig::from_book_toml(book, &path)
            .unwrap()
            .is_none()
    );
    assert_eq!(
        ProjectConfig::from_book_toml(&format!("{book}\n[habeas]\n"), &path).unwrap(),
        Some(ProjectConfig {})
    );
    assert!(ProjectConfig::from_book_toml("[habeas]\nversion = 1\n", &path).is_err());
    let malformed = "version = [\n";
    fs::write(&path, malformed).unwrap();
    let error = load_user_config(&path).unwrap_err().to_string();
    assert!(error.contains("invalid TOML syntax"), "{error}");
    assert!(error.contains(path.to_str().unwrap()), "{error}");
    assert_eq!(fs::read_to_string(&path).unwrap(), malformed);
}
Input 6: 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 7: 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 8: outline tests/configuration.rs fn[authoring_policy_defaults_to_confirm_and_round_trips]
// {test}`requirements.authoring.policy`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.configuration.serialization`
#[test]
fn authoring_policy_defaults_to_confirm_and_round_trips() {
    use habeas::config::AssessmentPolicy;
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let base = "version = 1\n[authoring.configs.model]\nbackend = 'ollama'\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.policy, None);
    assert_eq!(resolved.effective_policy(None), AssessmentPolicy::Confirm);
    assert_eq!(
        resolved.effective_policy(Some(AssessmentPolicy::Once)),
        AssessmentPolicy::Once
    );
    assert!(!defaults.to_toml().unwrap().contains("policy"));
    for (name, policy) in [
        ("confirm", AssessmentPolicy::Confirm),
        ("once", AssessmentPolicy::Once),
    ] {
        let configured = UserConfig::parse(&format!("{base}policy = '{name}'\n"), &path).unwrap();
        let resolved =
            resolve_authoring_from(&path, Some(&configured), dir.path(), Some("model")).unwrap();
        assert_eq!(resolved.policy, Some(policy));
        assert_eq!(resolved.effective_policy(None), policy);
        // `--policy` overrides the configuration.
        let other = match policy {
            AssessmentPolicy::Confirm => AssessmentPolicy::Once,
            AssessmentPolicy::Once => AssessmentPolicy::Confirm,
        };
        assert_eq!(resolved.effective_policy(Some(other)), other);
        let serialized = configured.to_toml().unwrap();
        assert!(
            serialized.contains(&format!("policy = \"{name}\"")),
            "{serialized}"
        );
        assert_eq!(UserConfig::parse(&serialized, &path).unwrap(), configured);
        assert_eq!(name.parse::<AssessmentPolicy>(), Ok(policy));
        assert_eq!(policy.to_string(), name);
    }
    for invalid in ["'twice'", "'Confirm'", "true"] {
        let error = UserConfig::parse(&format!("{base}policy = {invalid}\n"), &path)
            .unwrap_err()
            .to_string();
        assert!(error.contains(&path.display().to_string()), "{error}");
        assert!(error.contains("policy"), "{error}");
    }
    assert!("twice".parse::<AssessmentPolicy>().is_err());
}
Input 9: 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 10: outline tests/configuration.rs fn[workspace_discovery_uses_nearest_file_without_merging_or_rewriting_it]
// {test}`requirements.configuration.workspace_location`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.configuration.workspace_structure`
// {test}`requirements.configuration.loading`
// {test}`requirements.configuration.serialization`
#[test]
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.configuration.documentation`
fn workspace_discovery_uses_nearest_file_without_merging_or_rewriting_it() {
    let temp = tempfile::tempdir().unwrap();
    let project = temp.path().join("project");
    let nested = project.join("nested/deep");
    fs::create_dir_all(&nested).unwrap();
    let outer = temp.path().join("habeas.toml");
    fs::write(&outer, "version = 1\n[evidence]\nallow = ['outer']\n").unwrap();
    let inherited = load_workspace_config(&project).unwrap().unwrap();
    assert_eq!(inherited.path, outer);
    assert_eq!(inherited.root, temp.path().canonicalize().unwrap());
    let path = project.join("nested/habeas.toml");
    let text = "# preserved\nversion = 1\n[authoring]\ndefault = 'cloud'\n[evidence]\ndisallow = ['private']\n";
    fs::write(&path, text).unwrap();
    let closest = load_workspace_config(&nested).unwrap().unwrap();
    assert_eq!(closest.path, path);
    assert_eq!(closest.root, path.parent().unwrap());
    assert!(
        closest
            .config
            .authoring
            .as_ref()
            .unwrap()
            .configs
            .is_empty()
    );
    assert!(closest.config.evidence.as_ref().unwrap().allow.is_empty());
    assert_eq!(
        closest.config.evidence.as_ref().unwrap().disallow,
        vec![Path::new("private")]
    );
    assert_eq!(fs::read_to_string(&path).unwrap(), text);
    let serialized = closest.config.to_toml().unwrap();
    assert!(!serialized.contains("configs"));
    assert_eq!(
        WorkspaceConfig::parse(&serialized, &path).unwrap(),
        closest.config
    );

    fs::write(&path, "version = 1\n[evidence\n").unwrap();
    let error = load_workspace_config(&nested).unwrap_err().to_string();
    assert!(error.contains(path.to_str().unwrap()), "{error}");
    assert!(error.contains("invalid TOML"), "{error}");
    assert_eq!(
        fs::read_to_string(&path).unwrap(),
        "version = 1\n[evidence\n"
    );
    fs::remove_file(path).unwrap();
    fs::remove_file(outer).unwrap();
    assert!(load_workspace_config(&nested).unwrap().is_none());
}
Input 11: 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 12: outline tests/configuration.rs fn[explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them]
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.configuration.serialization`
// {test}`requirements.configuration.loading`
// {test}`requirements.authoring.configuration_structure`
#[test]
fn explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them() {
    let path = Path::new("habeas.toml");
    let source = "version = 1\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'm'\n[authoring.configs.cloud.credentials]\naccess_key_id = 'PRIVATE_ACCESS_KEY'\nsecret_access_key = 'PRIVATE_SECRET_KEY'\nsession_token = 'PRIVATE_SESSION'\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 'PRIVATE_OLLAMA_KEY'\n[authoring.configs.openai]\nbackend = 'openai'\napi_key = 'PRIVATE_OPENAI_KEY'\n";
    let config = WorkspaceConfig::parse(source, path).unwrap();
    let debug = format!("{config:?}");
    for secret in [
        "PRIVATE_ACCESS_KEY",
        "PRIVATE_SECRET_KEY",
        "PRIVATE_SESSION",
        "PRIVATE_OLLAMA_KEY",
        "PRIVATE_OPENAI_KEY",
    ] {
        assert!(!debug.contains(secret), "{debug}");
    }
    assert_eq!(
        WorkspaceConfig::parse(&config.to_toml().unwrap(), path).unwrap(),
        config
    );
    let BackendConfig::Ollama(local) = &config.authoring.as_ref().unwrap().configs["local"].backend
    else {
        panic!("wrong backend");
    };
    assert_eq!(
        local.api_key_from(|_| None).unwrap().as_deref(),
        Some("PRIVATE_OLLAMA_KEY")
    );
    for invalid_source in [
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = ['PRIVATE_OLLAMA_KEY']\n",
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 'PRIVATE_OLLAMA_KEY' unexpected\n",
        "version = 1\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'm'\ncredentials = 'PRIVATE_SECRET_KEY'\n",
        "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 123456789\n",
    ] {
        for error in [
            WorkspaceConfig::parse(invalid_source, path).unwrap_err(),
            UserConfig::parse(invalid_source, path).unwrap_err(),
        ] {
            let error = error.to_string();
            assert!(error.contains("habeas.toml"), "{error}");
            assert!(!error.contains("PRIVATE_"), "{error}");
            assert!(!error.contains("123456789"), "{error}");
        }
    }
    for invalid_source in [
        source.replace(
            "model = 'm'\n[authoring.configs.cloud.credentials]",
            "model = 'm'\naws_profile = 'p'\n[authoring.configs.cloud.credentials]",
        ),
        source.replace(
            "api_key = 'PRIVATE_OLLAMA_KEY'",
            "api_key = 'PRIVATE_OLLAMA_KEY'\napi_key_env = 'KEY'",
        ),
        source.replace(
            "secret_access_key = 'PRIVATE_SECRET_KEY'",
            "secret_access_key = ''",
        ),
        source.replace("access_key_id = 'PRIVATE_ACCESS_KEY'", "access_key_id = ''"),
        source.replace("session_token = 'PRIVATE_SESSION'", "session_token = ''"),
        source.replace("api_key = 'PRIVATE_OLLAMA_KEY'", "api_key = ''"),
    ] {
        assert!(WorkspaceConfig::parse(&invalid_source, path).is_err());
    }
}
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[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 15: outline tests/configuration.rs fn[openai_defaults_are_effective_only_and_explicit_values_win]
// {test}`requirements.authoring.openai_defaults`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.configuration.serialization`
#[test]
fn openai_defaults_are_effective_only_and_explicit_values_win() {
    let path = Path::new("settings.toml");
    let base =
        "version = 1\n[authoring.configs.api]\nbackend = 'openai'\napi_key = 'fixture-key'\n";
    for (extra, model, effort) in [
        ("", "gpt-6.1-sol", Some("low")),
        (
            "[authoring.configs.api.options.reasoning]\nsummary = 'auto'\n",
            "gpt-6.1-sol",
            Some("low"),
        ),
        (
            "[authoring.configs.api.options.reasoning]\neffort = 'medium'\n",
            "gpt-6.1-sol",
            Some("medium"),
        ),
        ("model = 'gpt-6-luna'\n", "gpt-6-luna", Some("low")),
        ("model = 'adaptive'\n", "adaptive", Some("low")),
        (
            "model = 'gpt-6-luna'\n[authoring.configs.api.options.reasoning]\neffort = 'high'\n",
            "gpt-6-luna",
            Some("high"),
        ),
    ] {
        let config = UserConfig::parse(&format!("{base}{extra}"), path).unwrap();
        let backend = &config.authoring.as_ref().unwrap().configs["api"].backend;
        assert_eq!(backend.model_ref().model, model);
        let options = backend.options_json().unwrap();
        assert_eq!(options["reasoning"]["effort"].as_str(), effort);
        assert_eq!(options["max_output_tokens"], 16_384);
        if extra.contains("summary") {
            assert_eq!(options["reasoning"]["summary"], "auto");
        }
        let serialized = config.to_toml().unwrap();
        assert!(!serialized.contains("max_output_tokens"));
        assert_eq!(serialized.contains("model ="), extra.contains("model ="));
        assert_eq!(serialized.contains("effort ="), extra.contains("effort ="));
        if extra.contains("options.reasoning") {
            assert!(
                serialized.contains("[authoring.configs.api.options.reasoning]"),
                "{serialized}"
            );
        }
        assert_eq!(UserConfig::parse(&serialized, path).unwrap(), config);
    }
    assert!(UserConfig::parse(&format!("{base}model = ''\n"), path).is_err());
}

Other sources

Input 1: requirements selection requirements.configuration.serialization
:::{req} serialization
Saved configuration MUST remain distinct from resolved runtime configuration.
Serializing and deserializing a valid configuration MUST preserve its semantic
values, including explicit versus omitted settings. Optional fields MAY be
omitted on serialization; defaults and environment-derived values MUST NOT be
materialized into omitted fields. TOML comments and formatting need not
round-trip.

Loading configuration or running a configured feature MUST NOT rewrite the user
or project configuration as a side effect. Resolved credentials and live runtime
objects MUST NOT enter the serialized data structures. Explicitly supplied
credential values are permitted only in the fields documented by the authoring
feature; credentials resolved from a profile or environment MUST NOT be written
back to configuration.
:::