requirements.authoring.configuration_serialization
Requirements index · View definition
Requirement
The user
[authoring]table MUST serialize UserAuthoringConfig, and the workspace table MUST serialize WorkspaceAuthoringConfig. Each[authoring.configs.<name>]table MUST serialize one AuthoringConfig, withbackend = "bedrock",backend = "ollama", orbackend = "openai"and that variant’s fields in the same table. Backend-specific inference options MUST appear in itsoptionssubtable. Within a present user authoring section,configsMUST be present but MAY be empty; workspaceconfigsMAY be omitted, allowing a workspace default to select a named user configuration. omittedprojectsandoptionstables MUST deserialize as empty maps. Serialization MUST follow the common rules in.
Rationale
The requirement is satisfied. Its obligations map to reachable code and subject-marked tests as follows:
| Obligation | Implementation | Verification in tests/configuration.rs |
|---|---|---|
The user authoring table serializes UserAuthoringConfig. | src/config.rs#struct[UserConfig] types authoring as Option<UserAuthoringConfig>; impl[UserConfig]/fn[parse] and impl[UserConfig]/fn[to_toml] use Serde. | fn[user_and_workspace_authoring_tables_round_trip_every_map] checks populated projects and configurations, serialization, and reparsed equality. |
The workspace authoring table serializes WorkspaceAuthoringConfig. | src/config.rs#struct[WorkspaceConfig], impl[WorkspaceConfig]/fn[parse], impl[WorkspaceConfig]/fn[to_toml], and fn[load_workspace_config] use that typed section. | fn[user_and_workspace_authoring_tables_round_trip_every_map] checks the production loader against direct parsing and round-trips populated workspace authoring settings. |
Each named configuration serializes one AuthoringConfig. | The maps in src/config.rs#struct[UserAuthoringConfig] and src/config.rs#struct[WorkspaceAuthoringConfig] have AuthoringConfig values. | fn[user_and_workspace_authoring_tables_round_trip_every_map] and fn[backend_configuration_round_trips_without_materializing_defaults] round-trip multiple named configurations. |
The backend discriminator supports bedrock, ollama, and openai. | src/config.rs#enum[BackendConfig] uses an internally tagged, lowercase Serde representation. | Bedrock and Ollama are exercised by the map and backend round-trip tests; fn[openai_configuration_preserves_model_and_resolves_credentials] round-trips OpenAI. fn[invalid_schema_and_feature_values_report_the_configuration_path] rejects an unsupported backend. |
| Each variant’s fields are in the named configuration table. | src/config.rs#struct[AuthoringConfig] flattens BackendConfig; its internally tagged variants carry the backend-specific structs. | The preceding round-trip tests parse fields alongside backend, then serialize and reparse them. fn[explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them] additionally round-trips workspace fields for all three variants. |
Backend-specific inference options occupy the options subtable. | src/config.rs#struct[BedrockConfig], src/config.rs#struct[OllamaConfig], and src/config.rs#struct[OpenAiConfig] each contain a named options map. | fn[user_and_workspace_authoring_tables_round_trip_every_map] checks populated Bedrock/Ollama options and the serialized options-table heading; fn[openai_defaults_are_effective_only_and_explicit_values_win] checks OpenAI’s serialized nested options table and round-trip equality. |
A present user section requires configs. | src/config.rs#struct[UserAuthoringConfig] gives configs no deserialization default and does not skip its serialization. | fn[invalid_schema_and_feature_values_report_the_configuration_path] rejects a bare [authoring]; fn[user_and_workspace_authoring_tables_round_trip_every_map] confirms an explicitly empty map remains serialized and reparses. |
Omitted projects deserializes as an empty map. | src/config.rs#struct[UserAuthoringConfig] applies serde(default) to projects. | fn[backend_configuration_round_trips_without_materializing_defaults] explicitly asserts the omitted map is empty. |
Omitted options deserializes as an empty map. | All three backend structs apply serde(default) to options. | fn[backend_configuration_round_trips_without_materializing_defaults] asserts this for Ollama; fn[authoring_concurrency_defaults_overrides_and_invalid_values] exercises all three backends and asserts their saved options remain empty after resolution. |
Serialization follows requirements.configuration.serialization in the authoring case. | Both to_toml methods serialize the saved typed configuration directly. Optional saved fields are represented as Option and skipped when absent; backend maps contain saved OptionValue data rather than runtime clients. These types are reachable from the marked parse/serialization roots. | The backend round-trip test checks equality and absence of materialized endpoint/concurrency defaults; the concurrency test checks explicit values survive; the OpenAI defaults test checks model and inference defaults are not materialized; the credential round-trip test preserves explicitly supplied credentials. The OpenAI credential test resolves a supplied lookup value and verifies it does not appear as an api_key in serialized configuration. The workspace discovery test checks loading leaves file contents unchanged. |
The MAY clauses impose no additional mandatory behavior, but both permissions are exercised: empty user configs is accepted and retained, and fn[workspace_discovery_uses_nearest_file_without_merging_or_rewriting_it] accepts and round-trips a workspace default with omitted configs.
The Serde types above are reachable through the subject’s marked entry points and need no additional implementation references. All tests named in the table carry a test reference to the subject. Validation, schema diagnostics, and workspace discovery behavior in those entry points are specified by their other marked configuration requirements; they do not introduce an unspecified behavior gap here. No acknowledged or unacknowledged gap was found.
Inputs
Implementation
Input 3: outline src/config.rs impl[UserConfig]/fn[parse]
- File:
src/config.rs - Selector:
impl[UserConfig]/fn[parse] - Kind:
fn src/config.rs:327–337
// {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)
}
Input 4: outline src/config.rs impl[UserConfig]/fn[to_toml]
- File:
src/config.rs - Selector:
impl[UserConfig]/fn[to_toml] - Kind:
fn src/config.rs:339–346
// {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))
}
Input 5: outline src/config.rs impl[WorkspaceConfig]/fn[parse]
- File:
src/config.rs - Selector:
impl[WorkspaceConfig]/fn[parse] - Kind:
fn src/config.rs:362–374
// {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)
}
Input 6: outline src/config.rs impl[WorkspaceConfig]/fn[to_toml]
- File:
src/config.rs - Selector:
impl[WorkspaceConfig]/fn[to_toml] - Kind:
fn src/config.rs:376–389
// {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",
)
})
}
Input 7: outline src/config.rs fn[load_workspace_config]
- File:
src/config.rs - Selector:
fn[load_workspace_config] - Kind:
fn src/config.rs:891–915
// {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,
}))
}
Input 16: outline src/config.rs (whole file)
- File:
src/config.rs - Selector:
(root) - Kind:
file src/config.rs:1–1286
//! 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 8: outline tests/configuration.rs fn[backend_configuration_round_trips_without_materializing_defaults]
- File:
tests/configuration.rs - Selector:
fn[backend_configuration_round_trips_without_materializing_defaults] - Kind:
fn tests/configuration.rs:108–158
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.concurrency`
// {test}`requirements.configuration.serialization`
#[test]
// {test}`requirements.configuration.loading`
fn backend_configuration_round_trips_without_materializing_defaults() {
let source = r#"
version = 1
[authoring]
default = "Cloud"
[authoring.configs.Cloud]
backend = "bedrock"
model = "arn:aws:bedrock:us-west-2:123:inference-profile/exact-id"
aws_profile = "research"
region = "us-west-2"
[authoring.configs.Cloud.options]
temperature = 0.2
max_tokens = 777
enabled = true
labels = ["a", "b"]
[authoring.configs.Cloud.options.custom]
arbitrary = "provider-defined"
[authoring.configs.local]
backend = "ollama"
model = "tiny:latest"
"#;
let path = Path::new("settings.toml");
let config = UserConfig::parse(source, path).unwrap();
let authoring = config.authoring.as_ref().unwrap();
assert!(authoring.projects.is_empty());
let local = &authoring.configs["local"].backend;
let BackendConfig::Ollama(ollama) = local else {
panic!("wrong backend")
};
assert_eq!(ollama.endpoint(), "http://localhost:11434");
assert_eq!(ollama.endpoint, None);
assert!(ollama.options.is_empty());
assert_eq!(local.model_ref().model, "tiny:latest");
assert_eq!(local.model_ref().backend, BackendKind::Ollama);
let json = authoring.configs["Cloud"].backend.options_json().unwrap();
assert_eq!(json["custom"]["arbitrary"], "provider-defined");
assert_eq!(json["max_tokens"], 777);
let serialized = config.to_toml().unwrap();
assert!(!serialized.contains("endpoint"));
assert!(!serialized.contains("http://localhost"));
assert!(!serialized.contains("concurrency"));
assert_eq!(UserConfig::parse(&serialized, path).unwrap(), config);
}
Input 9: outline tests/configuration.rs fn[authoring_concurrency_defaults_overrides_and_invalid_values]
- File:
tests/configuration.rs - Selector:
fn[authoring_concurrency_defaults_overrides_and_invalid_values] - Kind:
fn tests/configuration.rs:160–206
// {test}`requirements.authoring.concurrency`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.configuration.loading`
// {test}`requirements.configuration.serialization`
#[test]
fn authoring_concurrency_defaults_overrides_and_invalid_values() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
for backend in ["bedrock", "ollama", "openai"] {
let base =
format!("version = 1\n[authoring.configs.model]\nbackend = '{backend}'\nmodel = 'm'\n");
let defaults = UserConfig::parse(&base, &path).unwrap();
let resolved =
resolve_authoring_from(&path, Some(&defaults), dir.path(), Some("model")).unwrap();
assert_eq!(resolved.concurrency, None);
let expected = if backend != "ollama" {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
} else {
1
};
assert_eq!(resolved.effective_concurrency(), expected);
assert!(!defaults.to_toml().unwrap().contains("concurrency"));
let configured = UserConfig::parse(&format!("{base}concurrency = 7\n"), &path).unwrap();
let resolved =
resolve_authoring_from(&path, Some(&configured), dir.path(), Some("model")).unwrap();
assert_eq!(resolved.concurrency.unwrap().get(), 7);
assert_eq!(resolved.effective_concurrency(), 7);
let serialized = configured.to_toml().unwrap();
assert!(serialized.contains("concurrency = 7"));
assert_eq!(UserConfig::parse(&serialized, &path).unwrap(), configured);
assert!(resolved.backend.options().is_empty());
for invalid in ["0", "-1", "1.5", "'2'"] {
let error = UserConfig::parse(&format!("{base}concurrency = {invalid}\n"), &path)
.unwrap_err()
.to_string();
assert!(error.contains(&path.display().to_string()), "{error}");
assert!(error.contains("concurrency"), "{error}");
}
}
}
Input 10: outline tests/configuration.rs fn[invalid_schema_and_feature_values_report_the_configuration_path]
- File:
tests/configuration.rs - Selector:
fn[invalid_schema_and_feature_values_report_the_configuration_path] - Kind:
fn tests/configuration.rs:358–386
// {test}`requirements.configuration.structure`
// {test}`requirements.configuration.loading`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.configuration.feature_sections`
#[test]
fn invalid_schema_and_feature_values_report_the_configuration_path() {
let path = Path::new("/settings/habeas/config.toml");
for source in [
"version = 2",
"version = '1'",
"",
"version = 1\nunknown = true",
"version = 1\n[authoring]",
"version = 1\n[authoring]\nconfigs = {}\ndefault = '_bad'",
"version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = ''",
"version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\nunknown = true",
"version = 1\n[authoring.configs.local]\nbackend = 'unsupported'\nmodel = 'm'",
"version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key_env = 'BAD=KEY'",
"version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\n[authoring.configs.local.options]\nvalue = nan",
"version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\n[authoring.configs.local.options]\nmodel = 'override'",
"version = 1\n[authoring]\nconfigs = {}\n[authoring.projects.relative]\nconfig = 'local'",
] {
let error = UserConfig::parse(source, path).unwrap_err().to_string();
assert!(error.contains("/settings/habeas/config.toml"), "{error}");
}
let valid = UserConfig::parse("version = 1\n[authoring]\nconfigs = {}", path).unwrap();
assert!(valid.authoring.unwrap().configs.is_empty());
}
Input 11: outline tests/configuration.rs fn[workspace_discovery_uses_nearest_file_without_merging_or_rewriting_it]
- File:
tests/configuration.rs - Selector:
fn[workspace_discovery_uses_nearest_file_without_merging_or_rewriting_it] - Kind:
fn tests/configuration.rs:416–474
// {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 12: outline tests/configuration.rs fn[explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them]
- File:
tests/configuration.rs - Selector:
fn[explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them] - Kind:
fn tests/configuration.rs:700–767
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.configuration.serialization`
// {test}`requirements.configuration.loading`
// {test}`requirements.authoring.configuration_structure`
#[test]
fn explicit_credentials_round_trip_but_diagnostics_and_debug_redact_them() {
let path = Path::new("habeas.toml");
let source = "version = 1\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'm'\n[authoring.configs.cloud.credentials]\naccess_key_id = 'PRIVATE_ACCESS_KEY'\nsecret_access_key = 'PRIVATE_SECRET_KEY'\nsession_token = 'PRIVATE_SESSION'\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 'PRIVATE_OLLAMA_KEY'\n[authoring.configs.openai]\nbackend = 'openai'\napi_key = 'PRIVATE_OPENAI_KEY'\n";
let config = WorkspaceConfig::parse(source, path).unwrap();
let debug = format!("{config:?}");
for secret in [
"PRIVATE_ACCESS_KEY",
"PRIVATE_SECRET_KEY",
"PRIVATE_SESSION",
"PRIVATE_OLLAMA_KEY",
"PRIVATE_OPENAI_KEY",
] {
assert!(!debug.contains(secret), "{debug}");
}
assert_eq!(
WorkspaceConfig::parse(&config.to_toml().unwrap(), path).unwrap(),
config
);
let BackendConfig::Ollama(local) = &config.authoring.as_ref().unwrap().configs["local"].backend
else {
panic!("wrong backend");
};
assert_eq!(
local.api_key_from(|_| None).unwrap().as_deref(),
Some("PRIVATE_OLLAMA_KEY")
);
for invalid_source in [
"version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = ['PRIVATE_OLLAMA_KEY']\n",
"version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 'PRIVATE_OLLAMA_KEY' unexpected\n",
"version = 1\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'm'\ncredentials = 'PRIVATE_SECRET_KEY'\n",
"version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = 123456789\n",
] {
for error in [
WorkspaceConfig::parse(invalid_source, path).unwrap_err(),
UserConfig::parse(invalid_source, path).unwrap_err(),
] {
let error = error.to_string();
assert!(error.contains("habeas.toml"), "{error}");
assert!(!error.contains("PRIVATE_"), "{error}");
assert!(!error.contains("123456789"), "{error}");
}
}
for invalid_source in [
source.replace(
"model = 'm'\n[authoring.configs.cloud.credentials]",
"model = 'm'\naws_profile = 'p'\n[authoring.configs.cloud.credentials]",
),
source.replace(
"api_key = 'PRIVATE_OLLAMA_KEY'",
"api_key = 'PRIVATE_OLLAMA_KEY'\napi_key_env = 'KEY'",
),
source.replace(
"secret_access_key = 'PRIVATE_SECRET_KEY'",
"secret_access_key = ''",
),
source.replace("access_key_id = 'PRIVATE_ACCESS_KEY'", "access_key_id = ''"),
source.replace("session_token = 'PRIVATE_SESSION'", "session_token = ''"),
source.replace("api_key = 'PRIVATE_OLLAMA_KEY'", "api_key = ''"),
] {
assert!(WorkspaceConfig::parse(&invalid_source, path).is_err());
}
}
Input 13: outline tests/configuration.rs fn[user_and_workspace_authoring_tables_round_trip_every_map]
- File:
tests/configuration.rs - Selector:
fn[user_and_workspace_authoring_tables_round_trip_every_map] - Kind:
fn tests/configuration.rs:769–855
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.configuration.serialization`
// {test}`requirements.authoring.configuration_storage`
#[test]
fn user_and_workspace_authoring_tables_round_trip_every_map() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().canonicalize().unwrap();
let path = root.join("config.toml");
// A user section with a project selection keeps the canonical key.
let source = format!(
"version = 1\n[authoring]\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm:tag'\n[authoring.projects.{:?}]\nconfig = 'local'\n",
root.display().to_string()
);
let user = UserConfig::parse(&source, &path).unwrap();
let projects = &user.authoring.as_ref().unwrap().projects;
assert_eq!(projects[&root].config, "local");
let serialized = user.to_toml().unwrap();
assert!(serialized.contains("[authoring.projects."), "{serialized}");
assert_eq!(UserConfig::parse(&serialized, &path).unwrap(), user);
// A present-but-empty `configs` is preserved and still parses.
let empty = UserConfig::parse("version = 1\n[authoring]\nconfigs = {}\n", &path).unwrap();
let serialized = empty.to_toml().unwrap();
assert!(serialized.contains("configs"), "{serialized}");
let reparsed = UserConfig::parse(&serialized, &path).unwrap();
assert_eq!(reparsed, empty);
assert!(reparsed.authoring.unwrap().configs.is_empty());
// A workspace table with populated configs and options round-trips, and
// the production loader decodes it exactly as `WorkspaceConfig::parse`.
let workspace_path = root.join("habeas.toml");
let workspace_text = "version = 1\n[authoring]\ndefault = 'cloud'\n[authoring.configs.cloud]\nbackend = 'bedrock'\nmodel = 'arn:aws:bedrock:us-east-1:123:inference-profile/us.model-v1:0'\nregion = 'us-east-1'\n[authoring.configs.cloud.options]\ntemperature = 0.5\n[authoring.configs.cloud.options.nested]\nflag = true\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'local:7b'\n[authoring.configs.local.options]\nnum_ctx = 2048\n";
fs::write(&workspace_path, workspace_text).unwrap();
let workspace = WorkspaceConfig::parse(workspace_text, &workspace_path).unwrap();
let loaded = load_workspace_config(&root).unwrap().unwrap();
assert_eq!(loaded.config, workspace);
let configs = &workspace.authoring.as_ref().unwrap().configs;
assert_eq!(configs["cloud"].backend.options().len(), 2);
assert_eq!(configs["local"].backend.options().len(), 1);
let serialized = workspace.to_toml().unwrap();
assert!(serialized.contains("backend = \"bedrock\""), "{serialized}");
assert!(
serialized.contains("[authoring.configs.cloud.options"),
"{serialized}"
);
assert_eq!(
WorkspaceConfig::parse(&serialized, &workspace_path).unwrap(),
workspace
);
// `ModelRef` keeps the exact Bedrock identifier and nothing else.
for (model, region) in [
(
"arn:aws:bedrock:us-east-1:123:inference-profile/us.model-v1:0",
"us-east-1",
),
("us.anthropic.claude-v1:0", "eu-west-1"),
] {
let config = UserConfig::parse(
&format!("version = 1\n[authoring.configs.c]\nbackend = 'bedrock'\nmodel = '{model}'\naws_profile = 'p'\nregion = '{region}'\n"),
&path,
)
.unwrap();
let backend = &config.authoring.as_ref().unwrap().configs["c"].backend;
assert_eq!(
backend.model_ref(),
habeas::config::ModelRef {
backend: BackendKind::Bedrock,
model: model.to_owned(),
}
);
let BackendConfig::Bedrock(bedrock) = backend else {
panic!("wrong backend")
};
assert_eq!(bedrock.aws_profile.as_deref(), Some("p"));
assert_eq!(bedrock.region.as_deref(), Some(region));
}
let configured = UserConfig::parse("version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'local:tag'\nendpoint = 'http://server:11434'\n", &path).unwrap();
let backend = &configured.authoring.as_ref().unwrap().configs["local"].backend;
assert_eq!(backend.model_ref().model, "local:tag");
let BackendConfig::Ollama(local) = backend else {
panic!("wrong backend")
};
assert_eq!(local.endpoint.as_deref(), Some("http://server:11434"));
}
Input 14: outline tests/configuration.rs fn[openai_configuration_preserves_model_and_resolves_credentials]
- File:
tests/configuration.rs - Selector:
fn[openai_configuration_preserves_model_and_resolves_credentials] - Kind:
fn tests/configuration.rs:1742–1799
// {test}`requirements.authoring.configuration_serialization`
// {test}`requirements.authoring.credentials`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.configuration_structure`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.configuration.serialization`
#[test]
fn openai_configuration_preserves_model_and_resolves_credentials() {
let source =
"version = 1\n[authoring.configs.api]\nbackend = 'openai'\nmodel = 'account-model-id'\n";
let path = Path::new("settings.toml");
let config = UserConfig::parse(source, path).unwrap();
let backend = &config.authoring.as_ref().unwrap().configs["api"].backend;
assert_eq!(backend.model_ref().backend, BackendKind::Openai);
assert_eq!(backend.model_ref().model, "account-model-id");
let BackendConfig::Openai(openai) = backend else {
panic!("wrong backend")
};
assert_eq!(openai.endpoint(), "https://api.openai.com/v1");
assert!(openai.api_key_from(|_| None).is_err());
assert_eq!(
openai
.api_key_from(|name| {
assert_eq!(name, "OPENAI_API_KEY");
Some("test-key".into())
})
.unwrap()
.as_str(),
"test-key"
);
let serialized = config.to_toml().unwrap();
assert!(!serialized.contains("api_key"));
assert_eq!(UserConfig::parse(&serialized, path).unwrap(), config);
for extra in [
"api_key = 'secret'\napi_key_env = 'KEY'",
"api_key_env = ''",
"api_key = ''",
"[authoring.configs.api.options]\ninput = 'override'",
"[authoring.configs.api.options]\ninstructions = 'override'",
] {
assert!(UserConfig::parse(&format!("{source}{extra}\n"), path).is_err());
}
let mut custom = openai.clone();
custom.endpoint = Some("https://example.invalid/v1".into());
custom.api_key_env = Some("CUSTOM_OPENAI_KEY".into());
assert_eq!(custom.endpoint(), "https://example.invalid/v1");
assert!(custom.api_key_from(|_| None).is_err());
assert!(custom.api_key_from(|_| Some("".into())).is_err());
assert_eq!(
custom
.api_key_from(|name| {
assert_eq!(name, "CUSTOM_OPENAI_KEY");
Some("custom-key".into())
})
.unwrap(),
"custom-key"
);
}
Input 15: outline tests/configuration.rs fn[openai_defaults_are_effective_only_and_explicit_values_win]
- File:
tests/configuration.rs - Selector:
fn[openai_defaults_are_effective_only_and_explicit_values_win] - Kind:
fn tests/configuration.rs:1836–1887
// {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());
}
Referenced definitions
Input 2: requirements selection requirements.configuration.serialization
requirements.configuration.serialization:md/requirements/configuration.md:199–213
:::{req} serialization
Saved configuration MUST remain distinct from resolved runtime configuration.
Serializing and deserializing a valid configuration MUST preserve its semantic
values, including explicit versus omitted settings. Optional fields MAY be
omitted on serialization; defaults and environment-derived values MUST NOT be
materialized into omitted fields. TOML comments and formatting need not
round-trip.
Loading configuration or running a configured feature MUST NOT rewrite the user
or project configuration as a side effect. Resolved credentials and live runtime
objects MUST NOT enter the serialized data structures. Explicitly supplied
credential values are permitted only in the fields documented by the authoring
feature; credentials resolved from a profile or environment MUST NOT be written
back to configuration.
:::
Other sources
Input 1: requirements selection requirements.authoring.configuration_serialization
requirements.authoring.configuration_serialization:md/requirements/authoring.md:1678–1691
:::{req} configuration_serialization
{impl}`requirements.configuration.feature_sections`
The user `[authoring]` table MUST serialize UserAuthoringConfig, and the workspace
table MUST serialize WorkspaceAuthoringConfig. Each
`[authoring.configs.<name>]` table MUST serialize one AuthoringConfig, with
`backend = "bedrock"`, `backend = "ollama"`, or `backend = "openai"` and that variant's fields in the same
table. Backend-specific inference options MUST appear in its `options` subtable.
Within a present user authoring section, `configs` MUST be present but MAY be empty;
workspace `configs` MAY be omitted, allowing a workspace default to select a
named user configuration.
omitted `projects` and `options` tables MUST deserialize as empty maps.
Serialization MUST follow the common rules in
{cite}`requirements.configuration.serialization`.
:::
Input 17: requirements selection requirements.configuration.*
requirements.configuration.documentation:md/requirements/configuration.md:241–253requirements.configuration.evidence_paths:md/requirements/configuration.md:126–150requirements.configuration.feature_sections:md/requirements/configuration.md:185–197requirements.configuration.loading:md/requirements/configuration.md:217–237requirements.configuration.serialization:md/requirements/configuration.md:199–213requirements.configuration.state_location:md/requirements/configuration.md:46–59requirements.configuration.structure:md/requirements/configuration.md:97–108requirements.configuration.user_location:md/requirements/configuration.md:14–28requirements.configuration.workspace_location:md/requirements/configuration.md:30–39requirements.configuration.workspace_structure:md/requirements/configuration.md:110–124
:::{req} documentation
Habeas MUST document the user and project configuration locations, the common
file structure and schema version, and how to create and edit the files by hand.
Each configurable feature MUST document its fields, defaults, resolution rules,
and credential-source references, with complete, copyable examples identifying
all placeholders and the file to edit. Documentation MUST explain how to change
or remove optional settings and selections.
Configuration MUST NOT require a configuration-management command or generated
state beyond the documented files. Primary examples MUST use credential-source
references; examples explaining explicit credential fields MUST use clearly
identified placeholders, never real secrets.
:::
:::{req} evidence_paths
The workspace `[evidence]` table MUST serialize EvidenceConfig. `allow` and
`disallow` MUST be arrays of nonempty literal paths, each naming a file or a
directory subtree. Relative paths MUST resolve from the selected `habeas.toml`
directory; absolute paths MUST be supported. These paths are not glob patterns.
An omitted `allow` or `disallow` MUST mean an empty array, and an absent
`[evidence]` table MUST mean both are empty, so only the default source-access
rules apply. No operation requires the section. The table has no user-file
counterpart, and these rules have no invocation options. This section refines
{impl}`requirements.configuration.feature_sections` for the evidence feature.
For authoring reads, a matching disallow MUST reject the path; otherwise a
matching allow MUST permit it; otherwise the default source-access rules MUST
apply. Explicit allow MUST override every default, including Git tracking,
project containment, generated-evidence exclusion, and automatic generated-output
rules. Disallow MUST win even when an allow or generated-output rule also matches.
Both the requested path and its resolved symlink target MUST be checked for
disallow, so an allowed alias cannot expose a disallowed target.
The same explicit disallow rules and external-path exceptions MUST apply when
resolving recorded evidence inputs, including ordinary validation. Validation MUST
remain independent of Git index membership: it
checks the recorded inputs' existence and contents. Loading path policy MUST NOT
resolve credentials or validate unused authoring settings.
:::
:::{req} feature_sections
Each configurable feature MUST define the name and typed data structure of its
user section and any supported project section, citing these common configuration
requirements. The feature MUST specify its supported keys, value types, defaults,
validation rules, and the precedence or combination rules for user settings,
project settings, and invocation options. It MUST specify the behavior of an
absent section and which operations require that section.
Feature-specific fields MUST stay within the feature's section. A feature MUST
NOT reinterpret another feature's settings or change the shared file locations
or schema version. A feature MAY define a provider-owned options map, but MUST
document that boundary and how those options are validated.
:::
:::{req} loading
An operation MUST load user configuration only when its requirements call for
user settings. A missing user file MUST represent absent user configuration;
whether the operation can proceed MUST be defined by the feature. Loading MUST
NOT create a file, repair malformed input, or supply an undocumented selection.
When loading configuration, Habeas MUST report unreadable files, invalid TOML,
unsupported user-file versions, unknown common keys, and invalid common field
types. It MUST validate the feature sections used by that operation and report
invalid feature settings with the file and setting identified. Unknown keys in
an explicitly documented provider-owned options map MUST follow that feature's
validation rules.
An operation MUST NOT require or semantically validate configuration for a
feature it does not use. This isolation MUST NOT suppress TOML syntax errors in
a shared file that the operation otherwise needs to parse. In particular,
ordinary validation still requires a parseable `book.toml` while remaining
independent of authoring settings and the user configuration file. It MUST apply
the selected workspace's evidence path policy without loading its model clients
or credentials.
:::
:::{req} serialization
Saved configuration MUST remain distinct from resolved runtime configuration.
Serializing and deserializing a valid configuration MUST preserve its semantic
values, including explicit versus omitted settings. Optional fields MAY be
omitted on serialization; defaults and environment-derived values MUST NOT be
materialized into omitted fields. TOML comments and formatting need not
round-trip.
Loading configuration or running a configured feature MUST NOT rewrite the user
or project configuration as a side effect. Resolved credentials and live runtime
objects MUST NOT enter the serialized data structures. Explicitly supplied
credential values are permitted only in the fields documented by the authoring
feature; credentials resolved from a profile or environment MUST NOT be written
back to configuration.
:::
:::{req} state_location
Habeas MUST store persistent per-user activity state under
`$XDG_STATE_HOME/habeas` on Unix when XDG_STATE_HOME is an absolute, nonempty path,
otherwise under `$HOME/.local/state/habeas`. On Windows it MUST use
`%LOCALAPPDATA%/habeas/state`. `HOME` and `LOCALAPPDATA` MUST likewise be
absolute, nonempty paths to be used. Features MUST use a named subdirectory under that
state root and document their record formats and locations.
State MUST persist across invocations and MUST NOT be stored in the project
repository, the configuration file, or a disposable cache directory. Habeas MUST
create the required directories when recording state. If it cannot determine or
write the state location, the operation requiring that state MUST report the
failure and MUST NOT claim that its history was recorded.
:::
:::{req} structure
The user configuration file MUST be UTF-8 TOML serializing UserConfig. It MUST
contain `version = 1` and MAY contain the documented feature tables. The common
root MUST contain only the schema version and those feature tables; feature
settings MUST NOT occupy unscoped root keys. A user file containing only
`version = 1` MUST be valid common configuration.
Workspace configuration MUST follow {cite}`requirements.configuration.workspace_structure`.
The absence of an optional feature section MUST be distinguishable
from that feature's explicit settings and interpreted according to its own
requirements.
:::
:::{req} user_location
Habeas MUST locate its per-user configuration at
`$XDG_CONFIG_HOME/habeas/config.toml` on Unix when XDG_CONFIG_HOME is an absolute,
nonempty path, otherwise at `$HOME/.config/habeas/config.toml`. On Windows it MUST
use `%APPDATA%/habeas/config.toml`. `HOME` and `APPDATA` MUST likewise be
absolute, nonempty paths to be used. If no usable base directory can be
determined, an operation requiring user configuration MUST fail with an
explanatory diagnostic naming the variable.
The same user configuration MUST be usable across projects. Its location MUST
NOT be selected relative to the current project or changed by project settings.
User-local preferences for a project MAY remain in the user configuration;
workspace settings MUST use `habeas.toml` under
{cite}`requirements.configuration.workspace_location`.
:::
:::{req} workspace_location
Habeas MUST search from its invocation directory upward for the nearest enclosing
`habeas.toml`. It MUST use that file alone, without merging ancestor workspace
files. A library operation given a project root MUST search from that root unless
its current directory is inside the project, in which case it MUST start there.
The directory containing the selected file defines the base for its relative
paths; it does not replace the Cargo and mdBook project root. A missing file MUST
mean absent workspace settings. Discovery MUST report unreadable candidate files
rather than silently selecting an ancestor. Loading MUST NOT create the file.
:::
:::{req} workspace_structure
{impl}`requirements.configuration.feature_sections`
`habeas.toml` MUST serialize WorkspaceConfig as UTF-8 TOML with `version = 1`.
Its supported feature tables are `[authoring]`, `[coverage]`, and
`[evidence]`; each MAY be absent. `[coverage]` has one optional key,
`reauthorings`, under {cite}`requirements.references.coverage.history`; it has
no user-file counterpart or invocation option, and no operation requires it. Unknown keys, unsupported versions, and invalid field types MUST produce
a diagnostic identifying the file and setting. Invalid TOML, including content
that is not UTF-8, MUST produce a diagnostic identifying the file, with the line
and column of a syntax error.
Features MUST define their own data structures and loading rules under
{cite}`requirements.configuration.feature_sections`. A file containing only
`version = 1` MUST be valid. Habeas settings MUST NOT require a `[habeas]` table
inside `book.toml`.
:::