mod code;
mod comms;
mod documents;
pub(crate) mod layered;
mod overrides;
mod shells;
mod source;
mod v1;
mod validate;
use std::path::{Path, PathBuf};
use thiserror::Error;
pub use code::CodeSearchConfig;
pub use comms::CommsConfig;
pub use documents::{
ApiKey, DocLanguageConfig, DocumentsConfig, KeywordAlgorithm, KeywordsConfig, LlmConfig, NerBackend, NerConfig,
OcrBackend, OcrConfig, OutputConfig, OutputFormat, RerankerConfig, SecretString, SummarizationConfig,
SummarizationStrategy,
};
pub use layered::{ConfigLayers, LoadedConfig, defaults_only, merge_layers};
pub use overrides::DocumentsCliOverrides;
pub use shells::{ShellsConfig, TerminalChoice, VisualMode};
pub use source::{ConfigSource, ProvenanceMap};
pub use v1::{ConfigV1, CrawlConfig};
pub type Config = ConfigV1;
pub const CONFIG_FILE_NAME: &str = "basemind.toml";
pub const BASEMIND_DIR: &str = ".basemind";
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("config file not found at {0}")]
NotFound(PathBuf),
#[error("failed to read {path}: {source}")]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("invalid TOML in {path}: {source}")]
Toml {
path: PathBuf,
#[source]
source: toml::de::Error,
},
#[error("config is missing required \"$schema\" field — add `\"$schema\" = \"v1\"`")]
MissingSchema,
#[error("unknown schema version {0:?} — supported: v1")]
UnknownSchema(String),
#[error("schema validation failed:\n{0}")]
SchemaValidation(String),
#[error("config does not match v1 shape after validation: {0}")]
Deserialize(#[source] serde_json::Error),
}
pub fn load(root: &Path) -> Result<Config, ConfigError> {
let path = resolve_config_path(root);
if !path.exists() {
return Err(ConfigError::NotFound(path));
}
let raw = std::fs::read_to_string(&path).map_err(|source| ConfigError::Io {
path: path.clone(),
source,
})?;
parse_str(&raw).map_err(|e| annotate_path(e, &path))
}
pub fn load_with_overrides(
root: &Path,
env_overrides: Option<DocumentsCliOverrides>,
cli_overrides: Option<DocumentsCliOverrides>,
) -> Result<LoadedConfig, ConfigError> {
let toml_file = match load(root) {
Ok(cfg) => Some(cfg),
Err(ConfigError::NotFound(_)) => None,
Err(e) => return Err(e),
};
Ok(merge_layers(
ConfigV1::with_defaults(),
ConfigLayers {
toml_file,
env: env_overrides,
cli: cli_overrides,
},
))
}
pub fn discover_root_with_basemind(start: &Path) -> PathBuf {
let mut current = start;
loop {
if current.join(BASEMIND_DIR).is_dir() {
return current.to_path_buf();
}
match current.parent() {
Some(parent) if parent != current => current = parent,
_ => break,
}
}
match crate::git::Repo::discover(start) {
Ok(repo) => repo.workdir().to_path_buf(),
Err(_) => start.to_path_buf(),
}
}
pub fn config_path(root: &Path) -> PathBuf {
root.join(CONFIG_FILE_NAME)
}
pub fn legacy_config_path(root: &Path) -> PathBuf {
root.join(BASEMIND_DIR).join(CONFIG_FILE_NAME)
}
pub fn resolve_config_path(root: &Path) -> PathBuf {
let root_path = config_path(root);
if root_path.exists() {
return root_path;
}
let legacy = legacy_config_path(root);
if legacy.exists() {
return legacy;
}
root_path
}
pub fn parse_str(raw: &str) -> Result<Config, ConfigError> {
let toml_value: toml::Value = toml::from_str(raw).map_err(|source| ConfigError::Toml {
path: PathBuf::new(),
source,
})?;
let json_value: serde_json::Value =
serde_json::to_value(&toml_value).expect("toml::Value → serde_json::Value never fails");
let schema_tag = json_value
.as_object()
.and_then(|o| o.get("$schema"))
.and_then(|v| v.as_str())
.ok_or(ConfigError::MissingSchema)?;
match schema_tag {
"v1" | "https://basemind.dev/schema/v1.json" => {
validate::validate_v1(&json_value)?;
serde_json::from_value::<ConfigV1>(json_value).map_err(ConfigError::Deserialize)
}
other => Err(ConfigError::UnknownSchema(other.to_string())),
}
}
pub fn default_for_root(_root: &Path) -> Config {
ConfigV1::with_defaults()
}
fn annotate_path(err: ConfigError, path: &Path) -> ConfigError {
match err {
ConfigError::Toml { source, .. } => ConfigError::Toml {
path: path.to_path_buf(),
source,
},
other => other,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_extra_roots_through_schema_validation() {
let raw = "\"$schema\" = \"v1\"\n[scan]\nextra_roots = [\"/opt/ext\", \"/var/cache/bazel\"]\n";
let cfg = parse_str(raw).expect("extra_roots is a valid, schema-accepted scan field");
assert_eq!(
cfg.scan.extra_roots,
vec![PathBuf::from("/opt/ext"), PathBuf::from("/var/cache/bazel"),]
);
}
#[test]
fn extra_roots_defaults_to_empty() {
let cfg = parse_str("\"$schema\" = \"v1\"\n").unwrap();
assert!(cfg.scan.extra_roots.is_empty());
}
#[test]
fn discover_root_walks_up_to_ancestor_basemind() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path().canonicalize().expect("canonicalize");
std::fs::create_dir(root.join(BASEMIND_DIR)).expect("mkdir .basemind");
let sub = root.join("a").join("b");
std::fs::create_dir_all(&sub).expect("mkdir sub");
assert_eq!(discover_root_with_basemind(&sub), root);
}
#[test]
fn discover_root_returns_start_when_no_basemind_or_git() {
let tmp = tempfile::tempdir().expect("tempdir");
let start = tmp.path().canonicalize().expect("canonicalize");
assert_eq!(discover_root_with_basemind(&start), start);
}
}