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_structure

Requirements index · View definition

evidence Valid

Requirement

impl requirements.configuration.feature_sections Habeas MUST define its authoring configuration using these data structures:

UserAuthoringConfig {
    default: Optional<ConfigName>,
    configs: Map<ConfigName, AuthoringConfig>,
    projects: Map<CanonicalProjectRoot, ProjectSelection>,
}

WorkspaceAuthoringConfig {
    default: Optional<ConfigName>,
    configs: Map<ConfigName, AuthoringConfig>,  // omitted means empty
}

ProjectSelection {
    config: ConfigName,
}

AuthoringConfig {
    backend: BackendConfig,                   // tagged union, flattened in TOML
    concurrency: Optional<PositiveInteger>,   // simultaneous assessments
    policy: Optional<AssessmentPolicy>,       // default: Once for OpenAI; Confirm otherwise
}

AssessmentPolicy = Confirm | Once             // TOML: "confirm" or "once"

BackendConfig = Bedrock(BedrockConfig) | Ollama(OllamaConfig) | Openai(OpenAiConfig)

BedrockConfig {
    model: ModelId,                           // model ID or inference-profile ID/ARN
    aws_profile: Optional<String>,
    region: Optional<String>,
    credentials: Optional<BedrockCredentials>,
    options: Map<String, OptionValue>,
}

BedrockCredentials {
    access_key_id: SecretString,
    secret_access_key: SecretString,
    session_token: Optional<SecretString>,
}

OllamaConfig {
    model: ModelId,                           // exact identifier, including tag
    endpoint: Optional<String>,               // default: http://localhost:11434
    api_key_env: Optional<EnvironmentVariableName>,
    api_key: Optional<SecretString>,
    options: Map<String, OptionValue>,
}

OpenAiConfig {
    model: Optional<ModelId>,                 // default: gpt-6.1-sol
    endpoint: Optional<String>,               // default: https://api.openai.com/v1
    api_key_env: Optional<EnvironmentVariableName>, // default: OPENAI_API_KEY
    api_key: Optional<SecretString>,
    options: Map<String, OptionValue>,
}

OptionValue = String | Boolean | Integer | FiniteFloat
            | Array<OptionValue> | Map<String, OptionValue>

SecretString = String                         // serialized normally; redacted in Debug

ModelRef {
    backend: BackendKind,                     // Bedrock, Ollama, or Openai
    model: ModelId,
}

ModelRef MUST be derived from the selected backend configuration and MUST preserve the exact model identifier. It MUST identify the model without replacing connection settings such as AWS profile, region, or Ollama endpoint.

Rationale

The code defines every structure the requirement lists, and tests cover each obligation. I found no gaps.

Structures. Each one matches the spec’s shape, defaults and serialized form:

  • User and workspace configs. src/config.rs#struct[UserAuthoringConfig] has default, a required configs map and a projects map keyed by PathBuf. src/config.rs#struct[WorkspaceAuthoringConfig] has default and a configs map that is omitted when empty, so omitted means empty. src/config.rs#struct[ProjectSelection] holds config.
  • Authoring config. src/config.rs#struct[AuthoringConfig] has concurrency: Option<NonZeroUsize> and policy: Option<AssessmentPolicy>. Its backend is flattened and tagged by backend through src/config.rs#enum[BackendConfig], whose variants are Bedrock, Ollama and Openai.
  • Backend configs. BedrockConfig, BedrockCredentials, OllamaConfig and OpenAiConfig have the listed fields. OpenAiConfig.model is optional.
  • Policy and option values. AssessmentPolicy is lowercase confirm or once. OptionValue is an untagged enum of string, boolean, integer, float, array and map.
  • Secrets. SecretString is a transparent String, so it serializes normally. src/config.rs#impl[SecretString/fmt::Debug]/fn[fmt] redacts it in Debug output.
  • Defaults. OllamaConfig::endpoint defaults to http://localhost:11434. OpenAiConfig defaults the endpoint to https://api.openai.com/v1, the model to gpt-6.1-sol and the key variable to OPENAI_API_KEY. ResolvedAuthoringConfig::effective_policy defaults to Once for OpenAI and Confirm otherwise.
  • Validation.
    • src/config.rs#impl[UserAuthoringConfig]/fn[validate] checks configuration names and canonical absolute project roots.
    • src/config.rs#impl[BackendConfig]/fn[validate] checks non-empty model IDs and environment-variable names.
    • src/config.rs#impl[OptionValue]/fn[validate] enforces FiniteFloat, including inside nested arrays and maps.

ModelRef.

  • src/config.rs#impl[BackendConfig]/fn[model_ref] builds it from the selected backend. It carries only the backend kind and the exact model string, so AWS profile, region and endpoint are untouched.
  • ResolvedAuthoringConfig::model_ref only passes that value through unchanged, so it needs no test of its own.

Tests.

  • tests/configuration.rs#fn[backend_configuration_round_trips_without_materializing_defaults] checks the Ollama endpoint default, the ModelRef for Ollama, nested options and the round trip.
  • tests/configuration.rs#fn[user_and_workspace_authoring_tables_round_trip_every_map] checks the projects map, empty configs, and workspace configs with options. It also checks ModelRef for Bedrock IDs and ARNs with aws_profile and region kept, and for Ollama with endpoint kept.
  • tests/configuration.rs#fn[storage_rules_reject_each_invalid_field_with_its_setting] checks names, project keys, model IDs, api_key_env and non-finite floats, including nested ones.
  • tests/configuration.rs#fn[authoring_concurrency_defaults_overrides_and_invalid_values] checks the optional and positive concurrency field.
  • tests/configuration.rs#fn[authoring_policy_defaults_to_confirm_and_round_trips], tests/configuration.rs#fn[openai_policy_defaults_to_once_without_changing_explicit_policy] and tests/authoring_batch.rs#fn[policy_comes_from_the_flag_then_the_configuration_then_defaults_to_confirm] check the policy field and its backend-dependent default.
  • tests/configuration.rs#fn[openai_configuration_preserves_model_and_resolves_credentials] and tests/configuration.rs#fn[openai_defaults_are_effective_only_and_explicit_values_win] check the OpenAI model, endpoint and api_key_env defaults, and the OpenAiConfig fields.
  • tests/configuration.rs#fn[explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them] checks SecretString round-tripping, Debug redaction and credentials.
  • tests/configuration.rs#fn[explicit_project_and_default_selections_choose_whole_configs] checks default and ProjectSelection.
  • tests/configuration.rs#fn[workspace_discovery_uses_nearest_file_without_merging_or_rewriting_it] checks that a workspace file with no configs loads with an empty map.

All of these tests carry {test} references to the subject.

The extra validation rules in the backend validate function (options may not replace the model, prompt or tools; credentials and aws_profile are mutually exclusive) belong to the sibling requirements the same code marks with {impl}: requirements.authoring.configuration_storage and requirements.authoring.credentials. They are not unspecified behavior.

Inputs

Implementation

Input 2: outline src/config.rs struct[WorkspaceAuthoringConfig]
// {impl}`requirements.authoring.configuration_structure`
// {impl}`requirements.configuration.feature_sections`
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspaceAuthoringConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub configs: BTreeMap<String, AuthoringConfig>,
}
Input 3: outline src/config.rs impl[SecretString/fmt::Debug]/fn[fmt]
    // {impl}`requirements.authoring.credentials`
    // {impl}`requirements.authoring.configuration_structure`
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("<redacted>")
    }
Input 4: outline src/config.rs struct[UserAuthoringConfig]
// {impl}`requirements.authoring.configuration_structure`
// {impl}`requirements.configuration.feature_sections`
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserAuthoringConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    pub configs: BTreeMap<String, AuthoringConfig>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub projects: BTreeMap<PathBuf, ProjectSelection>,
}
Input 5: outline src/config.rs impl[UserAuthoringConfig]/fn[validate]
    // {impl}`requirements.configuration.loading`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn validate(&self, path: &Path) -> io::Result<()> {
        if let Some(name) = &self.default {
            validate_name(path, "authoring.default", name)?;
        }
        for (name, config) in &self.configs {
            let setting = format!("authoring.configs.{name}");
            validate_name(path, &setting, name)?;
            config.backend.validate(path, &setting)?;
        }
        for (root, selection) in &self.projects {
            let setting = format!("authoring.projects.{}", root.display());
            if !root.is_absolute()
                || root
                    .components()
                    .any(|part| matches!(part, Component::CurDir | Component::ParentDir))
                // `Path` equality ignores `.` components and trailing
                // separators, so compare the spelled-out keys instead.
                || root.components().collect::<PathBuf>().as_os_str() != root.as_os_str()
                || fs::canonicalize(root)
                    .is_ok_and(|canonical| canonical.as_os_str() != root.as_os_str())
            {
                return Err(invalid(
                    path,
                    &setting,
                    "expected a canonical absolute project path",
                ));
            }
            validate_name(path, &format!("{setting}.config"), &selection.config)?;
        }
        Ok(())
    }
Input 6: 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(())
    }
Input 7: outline src/config.rs impl[OptionValue]/fn[validate]
    // {impl}`requirements.authoring.configuration_structure`
    fn validate(&self) -> io::Result<()> {
        match self {
            Self::Float(value) if !value.is_finite() => Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "inference option floats must be finite",
            )),
            Self::Array(values) => values.iter().try_for_each(Self::validate),
            Self::Map(values) => values.values().try_for_each(Self::validate),
            _ => Ok(()),
        }
    }
Input 8: outline src/config.rs impl[OllamaConfig]/fn[endpoint]
    // {impl}`requirements.configuration.serialization`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn endpoint(&self) -> &str {
        self.endpoint.as_deref().unwrap_or("http://localhost:11434")
    }
Input 9: outline src/config.rs impl[OpenAiConfig]/fn[endpoint]
    // {impl}`requirements.configuration.serialization`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn endpoint(&self) -> &str {
        self.endpoint
            .as_deref()
            .unwrap_or("https://api.openai.com/v1")
    }
Input 10: outline src/config.rs impl[OpenAiConfig]/fn[api_key_from]
    // {impl}`requirements.configuration.serialization`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn api_key_from(&self, lookup: impl Fn(&str) -> Option<OsString>) -> io::Result<String> {
        if let Some(key) = &self.api_key {
            return Ok(key.expose_secret().to_owned());
        }
        let name = self.api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
        lookup(name)
                .filter(|value| !value.is_empty())
                .and_then(|value| value.into_string().ok())
                .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput,
                    format!("authoring api_key_env {name:?} must name a set, nonempty UTF-8 environment variable")))
    }
Input 11: outline src/config.rs impl[ResolvedAuthoringConfig]/fn[model_ref]
    // {impl}`requirements.authoring.configuration_structure`
    pub fn model_ref(&self) -> ModelRef {
        self.backend.model_ref()
    }
Input 12: outline src/config.rs impl[ResolvedAuthoringConfig]/fn[effective_policy]
  • File: src/config.rs
  • Selector: impl[ResolvedAuthoringConfig]/fn[effective_policy]
  • Kind: fn
  • src/config.rs:763–775
    /// The policy from `--policy` when given, otherwise from this
    /// configuration, otherwise `once` for OpenAI and `confirm` for other backends.
    // {impl}`requirements.authoring.policy`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn effective_policy(&self, explicit: Option<AssessmentPolicy>) -> AssessmentPolicy {
        explicit.or(self.policy).unwrap_or({
            if matches!(self.backend, BackendConfig::Openai(_)) {
                AssessmentPolicy::Once
            } else {
                AssessmentPolicy::Confirm
            }
        })
    }
Input 25: outline src/config.rs (whole file)
//! Saved configuration and resolution for evidence authoring.

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::fmt;
use std::fs;
use std::io;
use std::num::NonZeroUsize;
use std::path::{Component, Path, PathBuf};

use serde::{Deserialize, Serialize, de::DeserializeOwned};

const CONFIG_EXAMPLES: &str = "see md/requirements/authoring.md#editing-the-file";

// {impl}`requirements.configuration.structure`
// {impl}`requirements.configuration.feature_sections`
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserConfig {
    pub version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authoring: Option<UserAuthoringConfig>,
}

// {impl}`requirements.configuration.workspace_structure`
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectConfig {}

// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.feature_sections`
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
// {impl}`requirements.configuration.evidence_paths`
pub struct WorkspaceConfig {
    pub version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authoring: Option<WorkspaceAuthoringConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub evidence: Option<EvidenceConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub coverage: Option<CoverageConfig>,
}

/// The workspace `[coverage]` table: how many committed versions of each
/// evidence file count toward recent coverage.
// {impl}`requirements.references.coverage.history`
// {impl}`requirements.configuration.workspace_structure`
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CoverageConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reauthorings: Option<u32>,
}

/// The number of committed versions counted when `[coverage] reauthorings`
/// is not set.
pub const DEFAULT_REAUTHORINGS: u32 = 3;

// {impl}`requirements.authoring.configuration_structure`
// {impl}`requirements.configuration.feature_sections`
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspaceAuthoringConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub configs: BTreeMap<String, AuthoringConfig>,
}

// {impl}`requirements.configuration.serialization`
// {impl}`requirements.configuration.evidence_paths`
// {impl}`requirements.configuration.feature_sections`
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EvidenceConfig {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allow: Vec<PathBuf>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub disallow: Vec<PathBuf>,
}

// {impl}`requirements.configuration.workspace_location`
#[derive(Clone, Debug)]
pub struct LoadedWorkspaceConfig {
    pub path: PathBuf,
    pub root: PathBuf,
    pub config: WorkspaceConfig,
}

// {impl}`requirements.configuration.evidence_paths`
#[derive(Clone, Debug)]
pub struct WorkspaceEvidenceConfig {
    pub path: PathBuf,
    pub root: PathBuf,
    pub evidence: EvidenceConfig,
    pub contains_credentials: bool,
}

/// A user-supplied credential value. Serialization preserves it; diagnostics do not.
// {impl}`requirements.configuration.serialization`
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SecretString(String);

impl SecretString {
    pub fn expose_secret(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for SecretString {
    // {impl}`requirements.authoring.credentials`
    // {impl}`requirements.authoring.configuration_structure`
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("<redacted>")
    }
}

// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BedrockCredentials {
    pub access_key_id: SecretString,
    pub secret_access_key: SecretString,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_token: Option<SecretString>,
}

// {impl}`requirements.authoring.configuration_structure`
// {impl}`requirements.configuration.feature_sections`
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserAuthoringConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    pub configs: BTreeMap<String, AuthoringConfig>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub projects: BTreeMap<PathBuf, ProjectSelection>,
}

// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectSelection {
    pub config: String,
}

// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AuthoringConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub concurrency: Option<NonZeroUsize>,
    // {impl}`requirements.authoring.policy`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy: Option<AssessmentPolicy>,
    #[serde(flatten)]
    pub backend: BackendConfig,
}

// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "backend", rename_all = "lowercase")]
pub enum BackendConfig {
    Bedrock(BedrockConfig),
    Ollama(OllamaConfig),
    Openai(OpenAiConfig),
}

// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BedrockConfig {
    pub model: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aws_profile: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credentials: Option<BedrockCredentials>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub options: BTreeMap<String, OptionValue>,
}

// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OllamaConfig {
    pub model: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key_env: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<SecretString>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub options: BTreeMap<String, OptionValue>,
}

// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenAiConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key_env: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<SecretString>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub options: BTreeMap<String, OptionValue>,
}

// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OptionValue {
    String(String),
    Boolean(bool),
    Integer(i64),
    Float(f64),
    Array(Vec<OptionValue>),
    Map(BTreeMap<String, OptionValue>),
}

/// How each subject is assessed: `confirm` checks a `true` or FIXME result
/// with further independent conversations; `once` records a single
/// assessment.
// {impl}`requirements.configuration.serialization`
// {impl}`requirements.authoring.policy`
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AssessmentPolicy {
    #[default]
    Confirm,
    Once,
}

impl AssessmentPolicy {
    /// The policy's name, as written in TOML and on the command line.
    // {impl}`requirements.authoring.policy`
    pub fn name(self) -> &'static str {
        match self {
            Self::Confirm => "confirm",
            Self::Once => "once",
        }
    }
}

impl std::str::FromStr for AssessmentPolicy {
    type Err = String;

    /// Parses `--policy <name>`, rejecting an unknown name.
    // {impl}`requirements.authoring.policy`
    fn from_str(name: &str) -> Result<Self, Self::Err> {
        match name {
            "confirm" => Ok(Self::Confirm),
            "once" => Ok(Self::Once),
            _ => Err(format!(
                "unknown assessment policy {name:?}; expected \"confirm\" or \"once\""
            )),
        }
    }
}

impl fmt::Display for AssessmentPolicy {
    // {impl}`requirements.authoring.policy`
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.name())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BackendKind {
    Bedrock,
    Ollama,
    Openai,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelRef {
    pub backend: BackendKind,
    pub model: String,
}

// {impl}`requirements.configuration.serialization`
/// The selected saved values together with their source, without resolved secrets.
#[derive(Clone, Debug)]
pub struct ResolvedAuthoringConfig {
    pub config_path: PathBuf,
    pub project_root: PathBuf,
    pub name: String,
    pub concurrency: Option<NonZeroUsize>,
    // {impl}`requirements.authoring.policy`
    pub policy: Option<AssessmentPolicy>,
    pub backend: BackendConfig,
}

// {impl}`requirements.configuration.user_location`
// {impl}`requirements.configuration.state_location`
#[derive(Clone, Copy, Debug)]
pub enum ConfigPlatform {
    Unix,
    Windows,
}

impl ConfigPlatform {
    // {impl}`requirements.configuration.user_location`
    // {impl}`requirements.configuration.state_location`
    pub fn current() -> Self {
        if cfg!(windows) {
            Self::Windows
        } else {
            Self::Unix
        }
    }
}

impl UserConfig {
    // {impl}`requirements.configuration.structure`
    // {impl}`requirements.configuration.loading`
    // {impl}`requirements.authoring.configuration_storage`
    // {impl}`requirements.authoring.configuration_serialization`
    // {impl}`requirements.authoring.credentials`
    // {impl}`requirements.configuration.serialization`
    pub fn parse(text: &str, path: &Path) -> io::Result<Self> {
        let config: Self = decode(toml::Value::Table(parse_document(text, path)?), path, "")?;
        config.validate(path)?;
        Ok(config)
    }

    // {impl}`requirements.configuration.structure`
    // {impl}`requirements.configuration.serialization`
    // {impl}`requirements.authoring.configuration_serialization`
    pub fn to_toml(&self) -> io::Result<String> {
        self.validate(Path::new("user configuration"))?;
        toml::to_string_pretty(self)
            .map_err(|error| invalid(Path::new("user configuration"), "", error))
    }

    // {impl}`requirements.configuration.structure`
    // {impl}`requirements.configuration.loading`
    pub fn validate(&self, path: &Path) -> io::Result<()> {
        if self.version != 1 {
            return Err(invalid(path, "version", "expected version = 1"));
        }
        if let Some(authoring) = &self.authoring {
            authoring.validate(path)?;
        }
        Ok(())
    }
}

impl WorkspaceConfig {
    // {impl}`requirements.configuration.workspace_structure`
    // {impl}`requirements.configuration.loading`
    // {impl}`requirements.authoring.credentials`
    // {impl}`requirements.authoring.configuration_serialization`
    // {impl}`requirements.authoring.concurrency`
    // {impl}`requirements.configuration.serialization`
    pub fn parse(text: &str, path: &Path) -> io::Result<Self> {
        let table = parse_document(text, path)?;
        validate_workspace_common(&table, path)?;
        let config: Self = decode(toml::Value::Table(table), path, "")?;
        config.validate(path)?;
        Ok(config)
    }

    // {impl}`requirements.configuration.workspace_structure`
    // {impl}`requirements.configuration.serialization`
    // {impl}`requirements.authoring.configuration_serialization`
    // {impl}`requirements.configuration.evidence_paths`
    pub fn to_toml(&self) -> io::Result<String> {
        self.validate(Path::new("workspace configuration"))?;
        toml::to_string_pretty(self).map_err(|_| {
            invalid(
                Path::new("workspace configuration"),
                "",
                "cannot serialize configuration",
            )
        })
    }

    // {impl}`requirements.configuration.workspace_structure`
    // {impl}`requirements.configuration.loading`
    pub fn validate(&self, path: &Path) -> io::Result<()> {
        if self.version != 1 {
            return Err(invalid(path, "version", "expected version = 1"));
        }
        if let Some(authoring) = &self.authoring {
            if let Some(name) = &authoring.default {
                validate_name(path, "authoring.default", name)?;
            }
            for (name, config) in &authoring.configs {
                let setting = format!("authoring.configs.{name}");
                validate_name(path, &setting, name)?;
                config.backend.validate(path, &setting)?;
            }
        }
        if let Some(evidence) = &self.evidence {
            evidence.validate(path)?;
        }
        if let Some(coverage) = &self.coverage {
            coverage.validate(path)?;
        }
        Ok(())
    }
}

impl CoverageConfig {
    /// Checks that `reauthorings`, when set, is a positive integer.
    // {impl}`requirements.references.coverage.history`
    // {impl}`requirements.configuration.loading`
    pub fn validate(&self, path: &Path) -> io::Result<()> {
        if self.reauthorings == Some(0) {
            return Err(invalid(
                path,
                "coverage.reauthorings",
                "expected a positive integer",
            ));
        }
        Ok(())
    }
}

impl EvidenceConfig {
    // {impl}`requirements.configuration.workspace_structure`
    // {impl}`requirements.configuration.evidence_paths`
    // {impl}`requirements.configuration.loading`
    pub fn validate(&self, path: &Path) -> io::Result<()> {
        for (field, paths) in [("allow", &self.allow), ("disallow", &self.disallow)] {
            for (index, entry) in paths.iter().enumerate() {
                if entry.as_os_str().is_empty() || entry.to_string_lossy().contains('\0') {
                    return Err(invalid(
                        path,
                        &format!("evidence.{field}[{index}]"),
                        "expected a nonempty path without NUL",
                    ));
                }
            }
        }
        Ok(())
    }
}

impl ProjectConfig {
    // {impl}`requirements.configuration.loading`
    // {impl}`requirements.configuration.workspace_structure`
    pub fn from_book_toml(text: &str, path: &Path) -> io::Result<Option<Self>> {
        let book: toml::Table = toml::from_str(text).map_err(|error| invalid(path, "", error))?;
        book.get("habeas")
            .map(|value| {
                value
                    .clone()
                    .try_into()
                    .map_err(|error| invalid(path, "habeas", error))
            })
            .transpose()
    }
}

impl UserAuthoringConfig {
    // {impl}`requirements.configuration.loading`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn validate(&self, path: &Path) -> io::Result<()> {
        if let Some(name) = &self.default {
            validate_name(path, "authoring.default", name)?;
        }
        for (name, config) in &self.configs {
            let setting = format!("authoring.configs.{name}");
            validate_name(path, &setting, name)?;
            config.backend.validate(path, &setting)?;
        }
        for (root, selection) in &self.projects {
            let setting = format!("authoring.projects.{}", root.display());
            if !root.is_absolute()
                || root
                    .components()
                    .any(|part| matches!(part, Component::CurDir | Component::ParentDir))
                // `Path` equality ignores `.` components and trailing
                // separators, so compare the spelled-out keys instead.
                || root.components().collect::<PathBuf>().as_os_str() != root.as_os_str()
                || fs::canonicalize(root)
                    .is_ok_and(|canonical| canonical.as_os_str() != root.as_os_str())
            {
                return Err(invalid(
                    path,
                    &setting,
                    "expected a canonical absolute project path",
                ));
            }
            validate_name(path, &format!("{setting}.config"), &selection.config)?;
        }
        Ok(())
    }
}

impl BackendConfig {
    pub fn model_ref(&self) -> ModelRef {
        match self {
            Self::Bedrock(config) => ModelRef {
                backend: BackendKind::Bedrock,
                model: config.model.clone(),
            },
            Self::Openai(config) => ModelRef {
                backend: BackendKind::Openai,
                model: config.model().to_owned(),
            },
            Self::Ollama(config) => ModelRef {
                backend: BackendKind::Ollama,
                model: config.model.clone(),
            },
        }
    }

    pub fn options(&self) -> &BTreeMap<String, OptionValue> {
        match self {
            Self::Bedrock(config) => &config.options,
            Self::Ollama(config) => &config.options,
            Self::Openai(config) => &config.options,
        }
    }

    // {impl}`requirements.authoring.configuration_storage`
    // {impl}`requirements.authoring.openai_defaults`
    pub fn options_json(&self) -> io::Result<serde_json::Value> {
        for value in self.options().values() {
            value.validate()?;
        }
        let mut options = serde_json::to_value(self.options()).map_err(io::Error::other)?;
        if let Self::Openai(_) = self {
            let options = options
                .as_object_mut()
                .expect("configuration options are a map");
            options
                .entry("max_output_tokens")
                .or_insert_with(|| serde_json::json!(16_384));
            let reasoning = options
                .entry("reasoning")
                .or_insert_with(|| serde_json::json!({}));
            if let Some(reasoning) = reasoning.as_object_mut() {
                reasoning
                    .entry("effort")
                    .or_insert_with(|| serde_json::json!("low"));
            }
        }
        Ok(options)
    }

    // {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(())
    }
}

impl OptionValue {
    // {impl}`requirements.authoring.configuration_structure`
    fn validate(&self) -> io::Result<()> {
        match self {
            Self::Float(value) if !value.is_finite() => Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "inference option floats must be finite",
            )),
            Self::Array(values) => values.iter().try_for_each(Self::validate),
            Self::Map(values) => values.values().try_for_each(Self::validate),
            _ => Ok(()),
        }
    }
}

impl OllamaConfig {
    // {impl}`requirements.configuration.serialization`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn endpoint(&self) -> &str {
        self.endpoint.as_deref().unwrap_or("http://localhost:11434")
    }

    // {impl}`requirements.configuration.serialization`
    pub fn api_key(&self) -> io::Result<Option<String>> {
        self.api_key_from(|name| std::env::var_os(name))
    }

    // {impl}`requirements.configuration.serialization`
    pub fn api_key_from(
        &self,
        lookup: impl Fn(&str) -> Option<OsString>,
    ) -> io::Result<Option<String>> {
        if let Some(key) = &self.api_key {
            return Ok(Some(key.expose_secret().to_owned()));
        }
        self.api_key_env.as_ref().map(|name| {
            lookup(name)
                .filter(|value| !value.is_empty())
                .and_then(|value| value.into_string().ok())
                .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput,
                    format!("authoring api_key_env {name:?} must name a set, nonempty UTF-8 environment variable")))
        }).transpose()
    }
}

impl OpenAiConfig {
    // {impl}`requirements.authoring.openai_defaults`
    pub fn model(&self) -> &str {
        self.model.as_deref().unwrap_or("gpt-6.1-sol")
    }

    // {impl}`requirements.configuration.serialization`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn endpoint(&self) -> &str {
        self.endpoint
            .as_deref()
            .unwrap_or("https://api.openai.com/v1")
    }

    // {impl}`requirements.configuration.serialization`
    pub fn api_key(&self) -> io::Result<String> {
        self.api_key_from(|name| std::env::var_os(name))
    }

    // {impl}`requirements.configuration.serialization`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn api_key_from(&self, lookup: impl Fn(&str) -> Option<OsString>) -> io::Result<String> {
        if let Some(key) = &self.api_key {
            return Ok(key.expose_secret().to_owned());
        }
        let name = self.api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
        lookup(name)
                .filter(|value| !value.is_empty())
                .and_then(|value| value.into_string().ok())
                .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput,
                    format!("authoring api_key_env {name:?} must name a set, nonempty UTF-8 environment variable")))
    }
}

impl ResolvedAuthoringConfig {
    // {impl}`requirements.authoring.configuration_structure`
    pub fn model_ref(&self) -> ModelRef {
        self.backend.model_ref()
    }

    /// The policy from `--policy` when given, otherwise from this
    /// configuration, otherwise `once` for OpenAI and `confirm` for other backends.
    // {impl}`requirements.authoring.policy`
    // {impl}`requirements.authoring.configuration_structure`
    pub fn effective_policy(&self, explicit: Option<AssessmentPolicy>) -> AssessmentPolicy {
        explicit.or(self.policy).unwrap_or({
            if matches!(self.backend, BackendConfig::Openai(_)) {
                AssessmentPolicy::Once
            } else {
                AssessmentPolicy::Confirm
            }
        })
    }

    pub fn effective_concurrency(&self) -> usize {
        self.concurrency
            .map(NonZeroUsize::get)
            .unwrap_or_else(|| match &self.backend {
                BackendConfig::Bedrock(_) | BackendConfig::Openai(_) => {
                    std::thread::available_parallelism()
                        .map(NonZeroUsize::get)
                        .unwrap_or(1)
                }
                BackendConfig::Ollama(_) => 1,
            })
    }
}

// {impl}`requirements.configuration.user_location`
pub fn user_config_path() -> io::Result<PathBuf> {
    user_config_path_from(ConfigPlatform::current(), |name| std::env::var_os(name))
}

// {impl}`requirements.configuration.user_location`
pub fn user_config_path_from(
    platform: ConfigPlatform,
    lookup: impl Fn(&str) -> Option<OsString>,
) -> io::Result<PathBuf> {
    let base = match platform {
        ConfigPlatform::Windows => required_directory(&lookup, "APPDATA")?,
        ConfigPlatform::Unix => match absolute_directory(&lookup, "XDG_CONFIG_HOME") {
            Some(path) => path,
            None => required_directory(&lookup, "HOME")?.join(".config"),
        },
    };
    Ok(base.join("habeas/config.toml"))
}

// {impl}`requirements.configuration.state_location`
pub fn state_root() -> io::Result<PathBuf> {
    state_root_from(ConfigPlatform::current(), |name| std::env::var_os(name))
}

// {impl}`requirements.configuration.state_location`
pub fn state_root_from(
    platform: ConfigPlatform,
    lookup: impl Fn(&str) -> Option<OsString>,
) -> io::Result<PathBuf> {
    match platform {
        ConfigPlatform::Windows => {
            Ok(required_directory(&lookup, "LOCALAPPDATA")?.join("habeas/state"))
        }
        ConfigPlatform::Unix => Ok(match absolute_directory(&lookup, "XDG_STATE_HOME") {
            Some(path) => path.join("habeas"),
            None => required_directory(&lookup, "HOME")?.join(".local/state/habeas"),
        }),
    }
}

/// Whether the state root `state` lies inside the project at the canonical
/// path `root`, once symlinks in its nearest existing ancestor are
/// resolved. State is never stored there.
// {impl}`requirements.configuration.state_location`
pub(crate) fn state_in_project(state: &Path, root: &Path) -> io::Result<bool> {
    Ok(resolved_location(state)?.starts_with(root))
}

/// Resolves symlinks in the nearest existing ancestor of `path`, keeping the
/// components that do not exist yet.
// {impl}`requirements.configuration.state_location`
fn resolved_location(path: &Path) -> io::Result<PathBuf> {
    let path = std::path::absolute(path)?;
    let existing = path
        .ancestors()
        .find(|ancestor| ancestor.exists())
        .expect("an absolute path has an existing root");
    let missing = path
        .strip_prefix(existing)
        .expect("ancestor is a prefix of its path");
    Ok(fs::canonicalize(existing)?.join(missing))
}

// {impl}`requirements.configuration.user_location`
// {impl}`requirements.configuration.state_location`
fn absolute_directory(lookup: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<PathBuf> {
    lookup(name)
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
}

// {impl}`requirements.configuration.user_location`
// {impl}`requirements.configuration.state_location`
fn required_directory(
    lookup: &impl Fn(&str) -> Option<OsString>,
    name: &str,
) -> io::Result<PathBuf> {
    absolute_directory(lookup, name).ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            format!("cannot determine Habeas directory: {name} must be an absolute, nonempty path"),
        )
    })
}

// {impl}`requirements.configuration.structure`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.serialization`
pub fn load_user_config(path: &Path) -> io::Result<Option<UserConfig>> {
    match fs::read_to_string(path) {
        Ok(text) => UserConfig::parse(&text, path).map(Some),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(io::Error::new(
            error.kind(),
            format!("{}: {error}", path.display()),
        )),
    }
}

// {impl}`requirements.configuration.workspace_location`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.serialization`
// {impl}`requirements.authoring.configuration_serialization`
pub fn load_workspace_config(root: &Path) -> io::Result<Option<LoadedWorkspaceConfig>> {
    let Some((path, mut table)) = workspace_document(root)? else {
        return Ok(None);
    };
    // Authoring does not use `[coverage]`, so it must not fail on an invalid
    // table (requirements.configuration.loading): the table is dropped
    // before decoding, and only the coverage report decodes and validates it,
    // through `load_coverage_reauthorings` and `CoverageConfig::validate`.
    table.remove("coverage");
    let config: WorkspaceConfig = decode(toml::Value::Table(table), &path, "")?;
    config.validate(&path)?;
    Ok(Some(LoadedWorkspaceConfig {
        root: path
            .parent()
            .expect("configuration has a parent")
            .to_owned(),
        path,
        config,
    }))
}

// {impl}`requirements.configuration.workspace_location`
// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.evidence_paths`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.authoring.deterministic_validation`
// {impl}`requirements.configuration.feature_sections`
pub fn load_workspace_evidence(root: &Path) -> io::Result<Option<WorkspaceEvidenceConfig>> {
    let Some((path, table)) = workspace_document(root)? else {
        return Ok(None);
    };
    let evidence: EvidenceConfig = table
        .get("evidence")
        .map(|value| decode(value.clone(), &path, "evidence"))
        .transpose()?
        .unwrap_or_default();
    evidence.validate(&path)?;
    let contains_credentials = table
        .get("authoring")
        .and_then(|value| value.get("configs"))
        .and_then(toml::Value::as_table)
        .is_some_and(|configs| {
            configs.values().any(|config| {
                config.get("credentials").is_some() || config.get("api_key").is_some()
            })
        });
    Ok(Some(WorkspaceEvidenceConfig {
        root: path
            .parent()
            .expect("configuration has a parent")
            .to_owned(),
        path,
        evidence,
        contains_credentials,
    }))
}

/// The workspace `[coverage] reauthorings` setting, or its default.
// {impl}`requirements.references.coverage.history`
// {impl}`requirements.configuration.loading`
pub fn load_coverage_reauthorings(root: &Path) -> io::Result<u32> {
    let Some((path, table)) = workspace_document(root)? else {
        return Ok(DEFAULT_REAUTHORINGS);
    };
    coverage_reauthorings(&path, &table)
}

/// An invalid workspace `[coverage]` table, for repository validation to
/// report without reading Git history. A workspace file that cannot be read
/// or fails the common checks is reported by evidence configuration loading,
/// so it is not reported again here.
// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.workspace_structure`
pub(crate) fn coverage_error(root: &Path) -> Option<io::Error> {
    let Ok(Some((path, table))) = workspace_document(root) else {
        return None;
    };
    coverage_reauthorings(&path, &table).err()
}

/// Decodes and validates the `[coverage]` table of a workspace file.
// {impl}`requirements.references.coverage.history`
fn coverage_reauthorings(path: &Path, table: &toml::Table) -> io::Result<u32> {
    let coverage: CoverageConfig = table
        .get("coverage")
        .map(|value| decode(value.clone(), path, "coverage"))
        .transpose()?
        .unwrap_or_default();
    coverage.validate(path)?;
    Ok(coverage.reauthorings.unwrap_or(DEFAULT_REAUTHORINGS))
}

// {impl}`requirements.configuration.workspace_location`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.workspace_structure`
fn workspace_document(root: &Path) -> io::Result<Option<(PathBuf, toml::Table)>> {
    let root = fs::canonicalize(root)?;
    let start = std::env::current_dir()
        .and_then(fs::canonicalize)
        .ok()
        .filter(|cwd| cwd.starts_with(&root))
        .unwrap_or(root);
    for directory in start.ancestors() {
        let path = directory.join("habeas.toml");
        match fs::symlink_metadata(&path) {
            Ok(_) => {
                let text = fs::read_to_string(&path).map_err(|error| {
                    io::Error::new(error.kind(), format!("{}: {error}", path.display()))
                })?;
                let table = parse_document(&text, &path)?;
                validate_workspace_common(&table, &path)?;
                return Ok(Some((path, table)));
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => {
                return Err(io::Error::new(
                    error.kind(),
                    format!("{}: {error}", path.display()),
                ));
            }
        }
    }
    Ok(None)
}

// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.feature_sections`
fn validate_workspace_common(table: &toml::Table, path: &Path) -> io::Result<()> {
    if table.get("version").and_then(toml::Value::as_integer) != Some(1) {
        return Err(invalid(path, "version", "expected version = 1"));
    }
    if let Some(key) = table.keys().find(|key| {
        !matches!(
            key.as_str(),
            "version" | "authoring" | "evidence" | "coverage"
        )
    }) {
        return Err(invalid(path, key, "unknown workspace configuration field"));
    }
    Ok(())
}

// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.workspace_structure`
fn parse_document(text: &str, path: &Path) -> io::Result<toml::Table> {
    toml::from_str(text).map_err(|error: toml::de::Error| {
        let position = error
            .span()
            .map(|span| {
                let prefix = text.get(..span.start).unwrap_or(text);
                let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
                let column = prefix.rsplit('\n').next().unwrap_or("").chars().count() + 1;
                format!(" at line {line}, column {column}")
            })
            .unwrap_or_default();
        invalid(path, "", format!("invalid TOML syntax{position}"))
    })
}

// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.workspace_structure`
fn decode<T: DeserializeOwned>(value: toml::Value, path: &Path, setting: &str) -> io::Result<T> {
    let mut secrets = Vec::new();
    credential_values(&value, false, &mut secrets);
    secrets.sort_by_key(|secret| std::cmp::Reverse(secret.len()));
    value.try_into().map_err(|mut error: toml::de::Error| {
        error.set_input(None);
        let (mut message, setting) = decoded_setting(&error.to_string(), setting);
        for secret in secrets {
            if !secret.is_empty() {
                message = message
                    .replace(&format!("{secret:?}"), "<redacted>")
                    .replace(&secret, "<redacted>");
            }
        }
        invalid(path, &setting, message)
    })
}

/// Splits a TOML decoding message into its explanation and the full setting
/// it concerns: the decoder's trailing "in `key`" location joined to `prefix`,
/// plus the field name of an unknown-field error.
// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.workspace_structure`
fn decoded_setting(message: &str, prefix: &str) -> (String, String) {
    let message = message.trim_end();
    let (message, location) = match message.rsplit_once("\nin `") {
        Some((message, location)) => (message, location.strip_suffix('`').unwrap_or(location)),
        None => (message, ""),
    };
    let unknown = message
        .strip_prefix("unknown field `")
        .and_then(|rest| rest.split_once('`'))
        .map_or("", |(field, _)| field);
    let setting = [prefix, location, unknown]
        .into_iter()
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join(".");
    (message.trim().to_owned(), setting)
}

fn credential_values(value: &toml::Value, secret: bool, output: &mut Vec<String>) {
    match value {
        toml::Value::String(value) if secret => output.push(value.clone()),
        toml::Value::Integer(_)
        | toml::Value::Float(_)
        | toml::Value::Boolean(_)
        | toml::Value::Datetime(_)
            if secret =>
        {
            output.push(value.to_string())
        }
        toml::Value::Table(table) => {
            for (key, value) in table {
                credential_values(
                    value,
                    secret || matches!(key.as_str(), "credentials" | "api_key"),
                    output,
                );
            }
        }
        toml::Value::Array(values) => {
            for value in values {
                credential_values(value, secret, output);
            }
        }
        _ => {}
    }
}

// {impl}`requirements.configuration.structure`
// {impl}`requirements.configuration.loading`
pub fn resolve_authoring(
    root: &Path,
    explicit: Option<&str>,
) -> io::Result<ResolvedAuthoringConfig> {
    let workspace = load_workspace_config(root)?;
    let path = user_config_path()?;
    let config = load_user_config(&path)?;
    resolve_authoring_with_workspace_from(
        &path,
        config.as_ref(),
        workspace.as_ref(),
        root,
        explicit,
    )
}

// {impl}`requirements.authoring.configuration_precedence`
// {impl}`requirements.authoring.configuration_storage`
// {impl}`requirements.configuration.serialization`
// {impl}`requirements.authoring.concurrency`
// {impl}`requirements.authoring.configuration`
// {impl}`requirements.configuration.loading`
pub fn resolve_authoring_from(
    path: &Path,
    user: Option<&UserConfig>,
    root: &Path,
    explicit: Option<&str>,
) -> io::Result<ResolvedAuthoringConfig> {
    resolve_authoring_with_workspace_from(path, user, None, root, explicit)
}

// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.serialization`
pub fn resolve_authoring_with_workspace_from(
    path: &Path,
    user: Option<&UserConfig>,
    workspace: Option<&LoadedWorkspaceConfig>,
    root: &Path,
    explicit: Option<&str>,
) -> io::Result<ResolvedAuthoringConfig> {
    let project_root = fs::canonicalize(root).map_err(|error| {
        io::Error::new(
            error.kind(),
            format!("cannot resolve project root {}: {error}", root.display()),
        )
    })?;
    if let Some(user) = user {
        user.validate(path)?;
    }
    if let Some(workspace) = workspace {
        workspace.config.validate(&workspace.path)?;
    }
    let authoring = user.and_then(|config| config.authoring.as_ref());
    let local = workspace.and_then(|workspace| workspace.config.authoring.as_ref());
    let workspace_path = workspace.map(|workspace| workspace.path.as_path());
    // Errors that concern both files name the workspace file, when there is
    // one, and also list every file that was searched.
    let diagnostic_path = workspace_path.unwrap_or(path);
    let searched = match workspace_path {
        Some(workspace_path) => format!(
            "searched {} and {}",
            path.display(),
            workspace_path.display()
        ),
        None => format!("searched {}", path.display()),
    };
    if authoring.is_none() && local.is_none() {
        return Err(invalid(
            diagnostic_path,
            "authoring",
            format!("no authoring configuration ({searched}); {CONFIG_EXAMPLES}"),
        ));
    }
    // Each selection records the file it came from, so an unknown name is
    // reported against the file that chose it.
    let selected = explicit
        .map(|name| (name, diagnostic_path))
        .or_else(|| {
            authoring?
                .projects
                .get(&project_root)
                .map(|selection| (selection.config.as_str(), path))
        })
        .or_else(|| {
            local
                .and_then(|local| local.default.as_deref())
                .zip(workspace_path)
        })
        .or_else(|| {
            authoring
                .and_then(|authoring| authoring.default.as_deref())
                .map(|name| (name, path))
        });
    let Some((selected, selection_path)) = selected else {
        return Err(invalid(
            diagnostic_path,
            "authoring",
            format!("no configuration selected ({searched}); {CONFIG_EXAMPLES}"),
        ));
    };
    let configured = local
        .and_then(|local| local.configs.get(selected))
        .map(|config| {
            (
                workspace_path.expect("local configuration has a file"),
                config,
            )
        })
        .or_else(|| {
            authoring
                .and_then(|authoring| authoring.configs.get(selected))
                .map(|config| (path, config))
        });
    let (source_path, config) = configured.ok_or_else(|| {
        invalid(
            selection_path,
            "authoring",
            format!("unknown configuration {selected:?} ({searched}); {CONFIG_EXAMPLES}"),
        )
    })?;
    Ok(ResolvedAuthoringConfig {
        config_path: source_path.to_owned(),
        project_root,
        name: selected.to_owned(),
        concurrency: config.concurrency,
        policy: config.policy,
        backend: config.backend.clone(),
    })
}

fn validate_name(path: &Path, setting: &str, name: &str) -> io::Result<()> {
    if name
        .as_bytes()
        .first()
        .is_none_or(|first| !first.is_ascii_alphanumeric())
        || !name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
    {
        return Err(invalid(
            path,
            setting,
            "configuration names must match [A-Za-z0-9][A-Za-z0-9_-]*",
        ));
    }
    Ok(())
}

// {impl}`requirements.configuration.loading`
// {impl}`requirements.configuration.workspace_structure`
fn invalid(path: &Path, setting: &str, message: impl std::fmt::Display) -> io::Error {
    io::Error::new(
        io::ErrorKind::InvalidInput,
        format!("{}: {setting}: {message}", path.display()),
    )
}

Tests

Input 13: outline tests/authoring_batch.rs fn[policy_comes_from_the_flag_then_the_configuration_then_defaults_to_confirm]
/// The policy comes from `--policy`, then the configuration's `policy`,
/// then defaults to `confirm`; the report and every usage record name it,
/// and an unknown name is rejected before any model request.
// {test}`requirements.authoring.policy`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.authoring.confirmation`
#[test]
// {test}`requirements.authoring.refresh`
fn policy_comes_from_the_flag_then_the_configuration_then_defaults_to_confirm() {
    let server = Server::start(false, None);
    let fixture = Fixture::new(&server.endpoint, None);
    let unconfigured = fixture.config_text.replace("policy = 'once'\n", "");
    let cases: [(&str, &[&str], &str, usize); 4] = [
        (&unconfigured, &[], "confirm", 2),
        (&unconfigured, &["--policy", "once"], "once", 1),
        (
            &fixture.config_text.replace("'once'", "'confirm'"),
            &["--policy", "once"],
            "once",
            1,
        ),
        (&fixture.config_text, &[], "once", 1),
    ];
    let run_ids = || {
        if fixture.state.exists() {
            fixture
                .usage()
                .into_iter()
                .map(|run| run["run_id"].as_str().unwrap().to_owned())
                .collect::<Vec<_>>()
        } else {
            Vec::new()
        }
    };
    for (config, policy, expected, conversations) in cases {
        fs::write(&fixture.config, config).unwrap();
        let before = server.subjects().len();
        let earlier = run_ids();
        let mut args = vec!["author", "requirements.alpha", "--force"];
        args.extend_from_slice(policy);
        let output = fixture.run(&args);
        assert!(
            output.status.success(),
            "{args:?}: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            String::from_utf8_lossy(&output.stdout).contains(&format!("; policy {expected}")),
            "{args:?}: {}",
            String::from_utf8_lossy(&output.stdout)
        );
        assert!(String::from_utf8_lossy(&output.stdout).contains("0 skipped as current"));
        assert_eq!(server.subjects().len() - before, conversations, "{args:?}");
        // Each conversation's usage record identifies the policy.
        let usage = fixture
            .usage()
            .into_iter()
            .filter(|run| !earlier.contains(&run["run_id"].as_str().unwrap().to_owned()))
            .collect::<Vec<_>>();
        assert_eq!(usage.len(), conversations, "{args:?}");
        assert!(
            usage.iter().all(|run| run["policy"] == expected),
            "{args:?}: {usage:?}"
        );
    }
    let stdout = fixture.run(&[
        "author",
        "requirements.alpha",
        "--stdout",
        "--policy",
        "once",
    ]);
    assert!(stdout.status.success(), "{stdout:?}");
    assert!(String::from_utf8_lossy(&stdout.stderr).contains("policy once"));
    assert!(String::from_utf8_lossy(&stdout.stderr).contains("0 skipped as current"));
    let printed: Value = serde_json::from_slice(&stdout.stdout).unwrap();
    assert_eq!(printed["determination"], true);
    // The batch summary names the policy too.
    fs::write(&fixture.config, &unconfigured).unwrap();
    let batch = fixture.run(&["author", "--all", "--force", "--policy", "once"]);
    assert_eq!(
        String::from_utf8_lossy(&batch.stdout).trim(),
        "6 authored; 0 skipped as current; 0 failed; policy once"
    );

    let before = server.subjects().len();
    let flag = fixture.run(&[
        "author",
        "requirements.alpha",
        "--force",
        "--policy",
        "twice",
    ]);
    assert!(!flag.status.success());
    let stderr = String::from_utf8_lossy(&flag.stderr);
    assert!(
        stderr.contains("unknown assessment policy \"twice\""),
        "{stderr}"
    );
    fs::write(
        &fixture.config,
        fixture.config_text.replace("'once'", "'twice'"),
    )
    .unwrap();
    for args in [
        &["author", "requirements.alpha", "--force"][..],
        &["author", "--all", "--force"],
    ] {
        let output = fixture.run(args);
        assert!(!output.status.success(), "{args:?}");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains(&fixture.config.display().to_string()) && stderr.contains("policy"),
            "{args:?}: {stderr}"
        );
    }
    assert_eq!(
        server.subjects().len(),
        before,
        "rejected before any request"
    );
}
Input 14: 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 15: 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 16: 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 17: 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 18: 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 19: 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 20: 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 21: 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 22: 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 23: outline tests/configuration.rs fn[openai_policy_defaults_to_once_without_changing_explicit_policy]
// {test}`requirements.authoring.policy`
// {test}`requirements.authoring.openai_defaults`
// {test}`requirements.authoring.configuration_structure`
#[test]
fn openai_policy_defaults_to_once_without_changing_explicit_policy() {
    use habeas::config::AssessmentPolicy;
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    for (extra, expected) in [
        ("", AssessmentPolicy::Once),
        ("policy = 'confirm'\n", AssessmentPolicy::Confirm),
    ] {
        let config = UserConfig::parse(
            &format!("version = 1\n[authoring.configs.api]\nbackend = 'openai'\n{extra}"),
            &path,
        )
        .unwrap();
        let resolved =
            resolve_authoring_from(&path, Some(&config), dir.path(), Some("api")).unwrap();
        assert_eq!(resolved.effective_policy(None), expected);
        assert_eq!(
            resolved.effective_policy(Some(AssessmentPolicy::Confirm)),
            AssessmentPolicy::Confirm
        );
        assert_eq!(
            resolved.effective_policy(Some(AssessmentPolicy::Once)),
            AssessmentPolicy::Once
        );
        assert_eq!(
            config.to_toml().unwrap().contains("policy ="),
            !extra.is_empty()
        );
    }
}
Input 24: 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.authoring.configuration_structure
:::{req} configuration_structure
{impl}`requirements.configuration.feature_sections`
Habeas MUST define its authoring configuration using these data structures:

```text
UserAuthoringConfig {
    default: Optional<ConfigName>,
    configs: Map<ConfigName, AuthoringConfig>,
    projects: Map<CanonicalProjectRoot, ProjectSelection>,
}

WorkspaceAuthoringConfig {
    default: Optional<ConfigName>,
    configs: Map<ConfigName, AuthoringConfig>,  // omitted means empty
}

ProjectSelection {
    config: ConfigName,
}

AuthoringConfig {
    backend: BackendConfig,                   // tagged union, flattened in TOML
    concurrency: Optional<PositiveInteger>,   // simultaneous assessments
    policy: Optional<AssessmentPolicy>,       // default: Once for OpenAI; Confirm otherwise
}

AssessmentPolicy = Confirm | Once             // TOML: "confirm" or "once"

BackendConfig = Bedrock(BedrockConfig) | Ollama(OllamaConfig) | Openai(OpenAiConfig)

BedrockConfig {
    model: ModelId,                           // model ID or inference-profile ID/ARN
    aws_profile: Optional<String>,
    region: Optional<String>,
    credentials: Optional<BedrockCredentials>,
    options: Map<String, OptionValue>,
}

BedrockCredentials {
    access_key_id: SecretString,
    secret_access_key: SecretString,
    session_token: Optional<SecretString>,
}

OllamaConfig {
    model: ModelId,                           // exact identifier, including tag
    endpoint: Optional<String>,               // default: http://localhost:11434
    api_key_env: Optional<EnvironmentVariableName>,
    api_key: Optional<SecretString>,
    options: Map<String, OptionValue>,
}

OpenAiConfig {
    model: Optional<ModelId>,                 // default: gpt-6.1-sol
    endpoint: Optional<String>,               // default: https://api.openai.com/v1
    api_key_env: Optional<EnvironmentVariableName>, // default: OPENAI_API_KEY
    api_key: Optional<SecretString>,
    options: Map<String, OptionValue>,
}

OptionValue = String | Boolean | Integer | FiniteFloat
            | Array<OptionValue> | Map<String, OptionValue>

SecretString = String                         // serialized normally; redacted in Debug

ModelRef {
    backend: BackendKind,                     // Bedrock, Ollama, or Openai
    model: ModelId,
}
```

`ModelRef` MUST be derived from the selected backend configuration and MUST
preserve the exact model identifier. It MUST identify the model without replacing
connection settings such as AWS profile, region, or Ollama endpoint.
:::
Input 26: outline src/config.rs struct[SecretString]
/// A user-supplied credential value. Serialization preserves it; diagnostics do not.
// {impl}`requirements.configuration.serialization`
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SecretString(String);
Input 27: outline src/config.rs struct[BedrockCredentials]
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BedrockCredentials {
    pub access_key_id: SecretString,
    pub secret_access_key: SecretString,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_token: Option<SecretString>,
}
Input 28: outline src/config.rs struct[ProjectSelection]
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectSelection {
    pub config: String,
}
Input 29: outline src/config.rs struct[AuthoringConfig]
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AuthoringConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub concurrency: Option<NonZeroUsize>,
    // {impl}`requirements.authoring.policy`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy: Option<AssessmentPolicy>,
    #[serde(flatten)]
    pub backend: BackendConfig,
}
Input 30: outline src/config.rs enum[BackendConfig]
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "backend", rename_all = "lowercase")]
pub enum BackendConfig {
    Bedrock(BedrockConfig),
    Ollama(OllamaConfig),
    Openai(OpenAiConfig),
}
Input 31: outline src/config.rs struct[BedrockConfig]
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BedrockConfig {
    pub model: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aws_profile: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credentials: Option<BedrockCredentials>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub options: BTreeMap<String, OptionValue>,
}
Input 32: outline src/config.rs struct[OllamaConfig]
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OllamaConfig {
    pub model: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key_env: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<SecretString>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub options: BTreeMap<String, OptionValue>,
}
Input 33: outline src/config.rs struct[OpenAiConfig]
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenAiConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key_env: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<SecretString>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub options: BTreeMap<String, OptionValue>,
}
Input 34: outline src/config.rs enum[OptionValue]
// {impl}`requirements.configuration.serialization`
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OptionValue {
    String(String),
    Boolean(bool),
    Integer(i64),
    Float(f64),
    Array(Vec<OptionValue>),
    Map(BTreeMap<String, OptionValue>),
}
Input 35: outline src/config.rs enum[AssessmentPolicy]
/// How each subject is assessed: `confirm` checks a `true` or FIXME result
/// with further independent conversations; `once` records a single
/// assessment.
// {impl}`requirements.configuration.serialization`
// {impl}`requirements.authoring.policy`
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AssessmentPolicy {
    #[default]
    Confirm,
    Once,
}
Input 36: outline src/config.rs enum[BackendKind]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BackendKind {
    Bedrock,
    Ollama,
    Openai,
}
Input 37: outline src/config.rs struct[ModelRef]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelRef {
    pub backend: BackendKind,
    pub model: String,
}
Input 38: outline src/config.rs impl[BackendConfig]/fn[model_ref]
    pub fn model_ref(&self) -> ModelRef {
        match self {
            Self::Bedrock(config) => ModelRef {
                backend: BackendKind::Bedrock,
                model: config.model.clone(),
            },
            Self::Openai(config) => ModelRef {
                backend: BackendKind::Openai,
                model: config.model().to_owned(),
            },
            Self::Ollama(config) => ModelRef {
                backend: BackendKind::Ollama,
                model: config.model.clone(),
            },
        }
    }