use anyhow::{Context, Result};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
const DEFAULT_EXCLUDES: &[&str] = &[
"**/*.test.ts",
"**/*.test.tsx",
"**/*.test.js",
"**/*.test.jsx",
"**/*.spec.ts",
"**/*.spec.tsx",
"**/*.spec.js",
"**/*.spec.jsx",
"**/__tests__/**",
"**/__mocks__/**",
"**/__snapshots__/**",
"**/test_*.py",
"**/*_test.py",
"**/*_test.go",
"**/vendor/**",
"**/*.pb.go",
"**/zz_generated*.go",
"**/mock_*.go",
"**/node_modules/**",
"**/dist/**",
"**/build/**",
"**/.next/**",
"**/.nuxt/**",
"**/.output/**",
"**/.cache/**",
"**/.turbo/**",
"**/storybook-static/**",
"**/*.min.js",
"**/*.min.ts",
"**/*.bundle.js",
"**/__generated__/**",
"**/generated/**",
"**/*.generated.ts",
"**/*.generated.js",
"**/*.pb.ts",
"**/*.pb.js",
"**/venv/**",
"**/.venv/**",
"**/__pycache__/**",
"**/migrations/**",
"**/target/**",
"**/out/**",
"**/deps/**",
"**/third_party/**",
"**/thirdparty/**",
"**/external/**",
"**/extern/**",
"**/contrib/**",
];
pub const CONFIG_SCHEMA_VERSION: u32 = 1;
fn default_config_schema_version() -> u32 {
CONFIG_SCHEMA_VERSION
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HotspotsConfig {
#[serde(default = "default_config_schema_version")]
pub schema_version: u32,
#[serde(default)]
pub include: Vec<String>,
#[serde(default)]
pub exclude: Vec<String>,
#[serde(default)]
pub min_lrs: Option<f64>,
#[serde(default)]
pub top: Option<usize>,
#[serde(default)]
pub policy: Option<PolicyConfig>,
#[serde(default)]
pub cold_start_gini_dead_zone: Option<f64>,
}
impl Default for HotspotsConfig {
fn default() -> Self {
HotspotsConfig {
schema_version: CONFIG_SCHEMA_VERSION,
include: Vec::new(),
exclude: Vec::new(),
min_lrs: None,
top: None,
policy: None,
cold_start_gini_dead_zone: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PolicyMode {
Block,
Warn,
Off,
}
impl PolicyMode {
fn parse(field: &str, s: &str) -> Result<Self> {
match s {
"block" => Ok(PolicyMode::Block),
"warn" => Ok(PolicyMode::Warn),
"off" => Ok(PolicyMode::Off),
other => anyhow::bail!(
"policy.{} must be one of \"block\", \"warn\", \"off\" (got \"{}\")",
field,
other
),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PolicyConfig {
pub critical_introduction: Option<String>,
pub critical_introduction_reason: Option<String>,
pub excessive_risk_regression: Option<String>,
pub excessive_risk_regression_reason: Option<String>,
}
#[derive(Debug)]
pub struct ResolvedConfig {
pub include: Option<GlobSet>,
pub exclude: GlobSet,
pub min_lrs: Option<f64>,
pub top_n: Option<usize>,
pub cold_start_gini_dead_zone: f64,
pub critical_introduction_mode: PolicyMode,
pub critical_introduction_reason: Option<String>,
pub excessive_risk_regression_mode: PolicyMode,
pub excessive_risk_regression_reason: Option<String>,
pub config_path: Option<PathBuf>,
pub exclude_is_custom: bool,
}
impl HotspotsConfig {
pub fn validate(&self) -> Result<()> {
if self.schema_version > CONFIG_SCHEMA_VERSION {
anyhow::bail!(
"config schema_version {} is newer than supported version {}; \
upgrade hotspots to read this config",
self.schema_version,
CONFIG_SCHEMA_VERSION
);
}
if let Some(ref p) = self.policy {
validate_policy_config(p)?;
}
validate_scalar_fields(self)?;
validate_glob_patterns(&self.include, &self.exclude)
}
}
fn validate_scalar_fields(c: &HotspotsConfig) -> Result<()> {
if let Some(min) = c.min_lrs {
if min < 0.0 {
anyhow::bail!("min_lrs must be non-negative (got {})", min);
}
}
if let Some(dz) = c.cold_start_gini_dead_zone {
if dz < 0.0 {
anyhow::bail!(
"cold_start_gini_dead_zone must be non-negative (got {})",
dz
);
}
if dz >= crate::trainer::LOW_GINI {
anyhow::bail!(
"cold_start_gini_dead_zone ({}) must be less than LOW_GINI ({})",
dz,
crate::trainer::LOW_GINI
);
}
}
Ok(())
}
fn validate_glob_patterns(include: &[String], exclude: &[String]) -> Result<()> {
for pattern in include {
Glob::new(pattern).with_context(|| format!("invalid include pattern: {}", pattern))?;
}
for pattern in exclude {
Glob::new(pattern).with_context(|| format!("invalid exclude pattern: {}", pattern))?;
}
Ok(())
}
fn validate_policy_config(p: &PolicyConfig) -> Result<()> {
if let Some(ref s) = p.critical_introduction {
let mode = PolicyMode::parse("critical_introduction", s)?;
require_reason_if_downgraded(
"critical_introduction",
mode,
p.critical_introduction_reason.as_deref(),
)?;
}
if let Some(ref s) = p.excessive_risk_regression {
let mode = PolicyMode::parse("excessive_risk_regression", s)?;
require_reason_if_downgraded(
"excessive_risk_regression",
mode,
p.excessive_risk_regression_reason.as_deref(),
)?;
}
Ok(())
}
fn require_reason_if_downgraded(field: &str, mode: PolicyMode, reason: Option<&str>) -> Result<()> {
if mode == PolicyMode::Block {
return Ok(());
}
match reason {
Some(r) if !r.trim().is_empty() => Ok(()),
_ => anyhow::bail!(
"policy.{field}_reason is required when policy.{field} is not \"block\" (explain why this gate is downgraded)",
field = field
),
}
}
impl HotspotsConfig {
pub fn resolve(&self) -> Result<ResolvedConfig> {
self.validate()?;
let include = if self.include.is_empty() {
None
} else {
let mut builder = GlobSetBuilder::new();
for pattern in &self.include {
builder.add(Glob::new(pattern)?);
}
Some(builder.build()?)
};
let exclude = {
let mut builder = GlobSetBuilder::new();
for pattern in DEFAULT_EXCLUDES {
builder.add(Glob::new(pattern)?);
}
for pattern in &self.exclude {
builder.add(Glob::new(pattern)?);
}
builder.build()?
};
let (
critical_introduction_mode,
critical_introduction_reason,
excessive_risk_regression_mode,
excessive_risk_regression_reason,
) = match &self.policy {
Some(p) => (
match &p.critical_introduction {
Some(s) => PolicyMode::parse("critical_introduction", s)?,
None => PolicyMode::Block,
},
p.critical_introduction_reason.clone(),
match &p.excessive_risk_regression {
Some(s) => PolicyMode::parse("excessive_risk_regression", s)?,
None => PolicyMode::Block,
},
p.excessive_risk_regression_reason.clone(),
),
None => (PolicyMode::Block, None, PolicyMode::Block, None),
};
Ok(ResolvedConfig {
include,
exclude,
min_lrs: self.min_lrs,
top_n: self.top,
critical_introduction_mode,
critical_introduction_reason,
excessive_risk_regression_mode,
excessive_risk_regression_reason,
cold_start_gini_dead_zone: self.cold_start_gini_dead_zone.unwrap_or(0.0),
config_path: None,
exclude_is_custom: !self.exclude.is_empty(),
})
}
}
impl ResolvedConfig {
pub fn should_include(&self, path: &Path) -> bool {
let path_str = path.to_string_lossy();
if self.exclude.is_match(path_str.as_ref()) {
return false;
}
if let Some(ref include) = self.include {
return include.is_match(path_str.as_ref());
}
true
}
pub fn defaults() -> Result<Self> {
HotspotsConfig::default().resolve()
}
}
pub fn discover_config(project_root: &Path) -> Result<Option<(HotspotsConfig, PathBuf)>> {
let rc_path = project_root.join(".hotspotsrc.json");
if rc_path.exists() {
let config = load_config_file(&rc_path)?;
return Ok(Some((config, rc_path)));
}
let config_path = project_root.join("hotspots.config.json");
if config_path.exists() {
let config = load_config_file(&config_path)?;
return Ok(Some((config, config_path)));
}
let pkg_path = project_root.join("package.json");
if pkg_path.exists() {
if let Some(config) = load_from_package_json(&pkg_path)? {
return Ok(Some((config, pkg_path)));
}
}
Ok(None)
}
pub fn load_config_file(path: &Path) -> Result<HotspotsConfig> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("failed to read config file: {}", path.display()))?;
let config: HotspotsConfig = serde_json::from_str(&content)
.with_context(|| format!("failed to parse config file: {}", path.display()))?;
config
.validate()
.with_context(|| format!("invalid config in: {}", path.display()))?;
Ok(config)
}
fn load_from_package_json(path: &Path) -> Result<Option<HotspotsConfig>> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("failed to read {}", path.display()))?;
let pkg: serde_json::Value = serde_json::from_str(&content)
.with_context(|| format!("failed to parse {}", path.display()))?;
match pkg.get("hotspots") {
Some(hotspots_value) => {
let config: HotspotsConfig = serde_json::from_value(hotspots_value.clone())
.with_context(|| format!("invalid hotspots config in {}", path.display()))?;
config
.validate()
.with_context(|| format!("invalid hotspots config in {}", path.display()))?;
Ok(Some(config))
}
None => Ok(None),
}
}
pub fn load_and_resolve(project_root: &Path, config_path: Option<&Path>) -> Result<ResolvedConfig> {
let (config, source_path) = if let Some(path) = config_path {
let config = load_config_file(path)?;
(config, Some(path.to_path_buf()))
} else {
match discover_config(project_root)? {
Some((config, path)) => (config, Some(path)),
None => (HotspotsConfig::default(), None),
}
};
let mut resolved = config.resolve()?;
resolved.config_path = source_path;
Ok(resolved)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn test_parse_minimal_config() {
let json = r#"{}"#;
let config: HotspotsConfig = serde_json::from_str(json).unwrap();
config.validate().unwrap();
}
#[test]
fn test_reject_unknown_fields() {
let json = r#"{"unknown_field": true}"#;
let result: Result<HotspotsConfig, _> = serde_json::from_str(json);
assert!(result.is_err(), "unknown fields should be rejected");
}
#[test]
fn test_schema_version_defaults_when_omitted() {
let json = r#"{}"#;
let config: HotspotsConfig = serde_json::from_str(json).unwrap();
assert_eq!(config.schema_version, CONFIG_SCHEMA_VERSION);
config.validate().unwrap();
}
#[test]
fn test_schema_version_newer_than_supported_rejected() {
let json = r#"{"schema_version": 999}"#;
let config: HotspotsConfig = serde_json::from_str(json).unwrap();
let err = config.validate().unwrap_err();
assert!(err.to_string().contains("schema_version"));
}
#[test]
fn test_accept_unset_weights_use_nonzero_defaults() {
let json = r#"{}"#;
let config: HotspotsConfig = serde_json::from_str(json).unwrap();
assert!(config.validate().is_ok());
}
#[test]
fn test_reject_invalid_glob_pattern() {
let json = r#"{"include": ["[invalid"]}"#;
let config: HotspotsConfig = serde_json::from_str(json).unwrap();
assert!(config.validate().is_err());
}
#[test]
fn test_should_include_default_excludes() {
let resolved = ResolvedConfig::defaults().unwrap();
assert!(!resolved.should_include(Path::new("src/foo.test.ts")));
assert!(!resolved.should_include(Path::new("node_modules/pkg/index.js")));
assert!(!resolved.should_include(Path::new("dist/bundle.js")));
assert!(resolved.should_include(Path::new("src/api.ts")));
assert!(resolved.should_include(Path::new("src/components/Button.tsx")));
assert!(!resolved.should_include(Path::new("deps/jemalloc/src/arena.c")));
assert!(!resolved.should_include(Path::new("third_party/abseil/absl/base/base.cc")));
assert!(!resolved.should_include(Path::new("thirdparty/openssl/ssl/ssl_lib.c")));
assert!(!resolved.should_include(Path::new("external/zlib/deflate.c")));
assert!(!resolved.should_include(Path::new("extern/lua/lvm.c")));
assert!(!resolved.should_include(Path::new("contrib/hiredis/net.c")));
assert!(resolved.should_include(Path::new("src/server.c")));
assert!(resolved.should_include(Path::new("src/networking.c")));
}
#[test]
fn test_should_include_custom_patterns() {
let config: HotspotsConfig = serde_json::from_str(
r#"{
"include": ["src/**/*.ts"],
"exclude": ["src/generated/**"]
}"#,
)
.unwrap();
let resolved = config.resolve().unwrap();
assert!(resolved.should_include(Path::new("src/api.ts")));
assert!(!resolved.should_include(Path::new("lib/util.ts")));
assert!(!resolved.should_include(Path::new("src/generated/types.ts")));
}
#[test]
fn test_discover_hotspotsrc() {
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join(".hotspotsrc.json");
fs::write(&config_path, r#"{"min_lrs": 5.0}"#).unwrap();
let result = discover_config(dir.path()).unwrap();
assert!(result.is_some());
let (config, path) = result.unwrap();
assert_eq!(config.min_lrs, Some(5.0));
assert_eq!(path, config_path);
}
#[test]
fn test_discover_hotspots_config_json() {
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("hotspots.config.json");
fs::write(&config_path, r#"{"top": 10}"#).unwrap();
let result = discover_config(dir.path()).unwrap();
assert!(result.is_some());
let (config, _) = result.unwrap();
assert_eq!(config.top, Some(10));
}
#[test]
fn test_discover_package_json() {
let dir = tempfile::tempdir().unwrap();
let pkg_path = dir.path().join("package.json");
fs::write(
&pkg_path,
r#"{
"name": "my-project",
"version": "1.0.0",
"hotspots": {
"exclude": ["**/*.test.ts"],
"min_lrs": 3.0
}
}"#,
)
.unwrap();
let result = discover_config(dir.path()).unwrap();
assert!(result.is_some());
let (config, _) = result.unwrap();
assert_eq!(config.min_lrs, Some(3.0));
assert_eq!(config.exclude, vec!["**/*.test.ts"]);
}
#[test]
fn test_discover_package_json_without_hotspots_key() {
let dir = tempfile::tempdir().unwrap();
let pkg_path = dir.path().join("package.json");
fs::write(&pkg_path, r#"{"name": "my-project", "version": "1.0.0"}"#).unwrap();
let result = discover_config(dir.path()).unwrap();
assert!(result.is_none());
}
#[test]
fn test_discover_priority_order() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(".hotspotsrc.json"), r#"{"min_lrs": 1.0}"#).unwrap();
fs::write(
dir.path().join("hotspots.config.json"),
r#"{"min_lrs": 2.0}"#,
)
.unwrap();
let result = discover_config(dir.path()).unwrap();
let (config, _) = result.unwrap();
assert_eq!(
config.min_lrs,
Some(1.0),
".hotspotsrc.json should take priority"
);
}
#[test]
fn test_no_config_returns_none() {
let dir = tempfile::tempdir().unwrap();
let result = discover_config(dir.path()).unwrap();
assert!(result.is_none());
}
#[test]
fn test_cold_start_gini_dead_zone_defaults_to_zero() {
let resolved = HotspotsConfig::default().resolve().unwrap();
assert_eq!(resolved.cold_start_gini_dead_zone, 0.0);
}
#[test]
fn test_cold_start_gini_dead_zone_resolves_from_config() {
let raw = HotspotsConfig {
cold_start_gini_dead_zone: Some(0.05),
..Default::default()
};
let resolved = raw.resolve().unwrap();
assert_eq!(resolved.cold_start_gini_dead_zone, 0.05);
}
#[test]
fn test_cold_start_gini_dead_zone_rejects_negative() {
let raw = HotspotsConfig {
cold_start_gini_dead_zone: Some(-0.1),
..Default::default()
};
assert!(raw.validate().is_err());
}
#[test]
fn test_cold_start_gini_dead_zone_rejects_at_or_above_low_gini() {
let raw = HotspotsConfig {
cold_start_gini_dead_zone: Some(crate::trainer::LOW_GINI),
..Default::default()
};
assert!(raw.validate().is_err());
}
#[test]
fn test_exclude_is_custom_when_config_sets_exclude() {
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("custom.json");
fs::write(&config_path, r#"{"exclude": ["**/legacy/**"]}"#).unwrap();
let resolved = load_and_resolve(dir.path(), Some(&config_path)).unwrap();
assert!(resolved.exclude_is_custom);
}
#[test]
fn test_exclude_is_not_custom_with_no_config_file() {
let dir = tempfile::tempdir().unwrap();
let resolved = load_and_resolve(dir.path(), None).unwrap();
assert!(!resolved.exclude_is_custom);
}
#[test]
fn test_default_config_resolves() {
let resolved = HotspotsConfig::default().resolve().unwrap();
assert!(resolved.min_lrs.is_none());
assert!(resolved.top_n.is_none());
}
#[test]
fn test_removed_tuning_keys_are_rejected() {
for key in [
r#"{"weights": {"cc": 1.0}}"#,
r#"{"thresholds": {"high": 6.0}}"#,
r#"{"warning_thresholds": {"rapid_growth_percent": 50.0}}"#,
r#"{"scoring": {"churn": 0.5}}"#,
r#"{"patterns": {}}"#,
r#"{"co_change_window_days": 90}"#,
r#"{"touch_window_days": 365}"#,
r#"{"driver_threshold_percentile": 75}"#,
] {
assert!(
serde_json::from_str::<HotspotsConfig>(key).is_err(),
"{key} should be rejected as an unknown key"
);
}
}
}