From 6bbc13d72c76323904b6e299e7804656d37245a8 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 08:09:37 +0800 Subject: [PATCH 1/4] feat(metrics): add boundary config, encapsulation, and check findings Add boundaries configuration (zones, patterns, public_files, allow/deny rules with optional reasons, strict_zones, source_sets) with strict load-time validation, evaluate boundary rules over resolved runtime imports in codeint-metrics, and emit boundary Findings in TOON, JSON, SARIF, and Markdown reports from codeint check. Closes #176 --- crates/cli/src/check.rs | 3 +- crates/cli/src/remedy.rs | 18 + crates/cli/tests/boundaries.rs | 419 ++++++++++++++++++++++ crates/cli/tests/check.rs | 4 +- crates/config/src/boundaries.rs | 387 ++++++++++++++++++++ crates/config/src/codeint_json.rs | 58 ++- crates/config/src/codeint_json/starter.rs | 1 + crates/config/src/lib.rs | 2 + crates/metrics/src/boundaries.rs | 235 ++++++++++++ crates/metrics/src/finding_id.rs | 10 +- crates/metrics/src/lib.rs | 4 + crates/report/src/diff.rs | 1 + crates/report/src/lib.rs | 153 +++++++- crates/report/src/markdown.rs | 59 ++- crates/report/src/sarif.rs | 65 +++- crates/report/src/sarif/tests.rs | 1 + docs/reference.md | 60 +++- schema/codeint.schema.json | 106 ++++++ 18 files changed, 1562 insertions(+), 24 deletions(-) create mode 100644 crates/cli/tests/boundaries.rs create mode 100644 crates/config/src/boundaries.rs create mode 100644 crates/metrics/src/boundaries.rs diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index d0a2725..f678623 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -202,12 +202,13 @@ fn check_loaded( ) -> Result { let tree = repository.working_tree()?; let languages = measure_with(&tree, plugins, configuration)?; - Ok(Report::summarize_with_metrics( + Ok(Report::summarize_with_metrics_and_boundaries( languages, tree.submodules().to_vec(), findings, &configuration.budgets, metric_plugins, + configuration.boundaries.as_ref(), )?) } diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 8dc91ef..da9eb2c 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -167,6 +167,24 @@ fn configuration_file_remedy(error: &ConfigurationFileError) -> &'static str { ConfigurationFileError::NewerSchemaVersion { .. } => { "Run codeint update (or upgrade the codeint npm package) to match or exceed the $schema version, or lower the $schema tag in codeint.json." } + ConfigurationFileError::InvalidBoundaryZoneName { .. } => { + "Give each boundary zone in codeint.json a non-empty name other than \"*\"." + } + ConfigurationFileError::EmptyBoundaryZonePatterns { .. } => { + "Add at least one path glob under patterns for every zone in boundaries.zones." + } + ConfigurationFileError::UnknownBoundaryZone { .. } => { + "Reference only zones defined under boundaries.zones (or \"*\") in boundaries.rules." + } + ConfigurationFileError::ConflictingBoundaryRule { .. } => { + "Set either allow or deny on each rule in boundaries.rules, not both." + } + ConfigurationFileError::MissingBoundaryRuleDirective { .. } => { + "Set either allow or deny on each rule in boundaries.rules." + } + ConfigurationFileError::ConflictingBoundaryDirectives { .. } => { + "Use either allow rules or deny rules for a given source zone in boundaries.rules, not both." + } _ => "Check codeint.json against the JSON schema that $schema links to.", } } diff --git a/crates/cli/tests/boundaries.rs b/crates/cli/tests/boundaries.rs new file mode 100644 index 0000000..8b0896a --- /dev/null +++ b/crates/cli/tests/boundaries.rs @@ -0,0 +1,419 @@ +use std::fs; +use std::process::{Command, Output}; + +use serde_json::Value; +use tempfile::TempDir; + +struct BoundaryFixture(TempDir); + +impl BoundaryFixture { + fn init(files: &[(&str, &str)]) -> BoundaryFixture { + let dir = tempfile::tempdir().expect("tempdir"); + let init = Command::new("git") + .args(["init", "--quiet", "--initial-branch", "main"]) + .current_dir(dir.path()) + .status() + .expect("git init"); + assert!(init.success()); + for &(rel, body) in files { + let dst = dir.path().join(rel); + if let Some(parent) = dst.parent() { + fs::create_dir_all(parent).expect("mkdir"); + } + fs::write(dst, body).expect("write"); + } + BoundaryFixture(dir) + } + + fn run(&self, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .args(args) + .current_dir(self.0.path()) + .output() + .expect("run codeint") + } + + fn check_json(&self, expected_code: i32) -> Value { + let out = self.run(&["check", "--format", "json"]); + assert_eq!( + out.status.code(), + Some(expected_code), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + serde_json::from_slice(&out.stdout).expect("valid JSON") + } +} + +#[test] +fn check_reports_directional_deny_allow_and_public_files_findings_across_formats() { + let fixture = BoundaryFixture::init(&[ + ( + "codeint.json", + r#"{ + "boundaries": { + "zones": { + "domain": { + "patterns": ["src/domain/**"], + "public_files": ["src/domain/index.ts"] + }, + "infra": { + "patterns": ["src/infra/**"] + }, + "app": { + "patterns": ["src/app/**"] + } + }, + "rules": [ + { + "from": "domain", + "deny": ["infra"], + "reason": "Domain logic must not depend on infrastructure" + }, + { + "from": "app", + "allow": ["domain"], + "reason": "App layer may only import domain" + } + ] + } +} +"#, + ), + ("src/infra/db.ts", "export const db = 1;\n"), + ( + "src/domain/internal.ts", + "import { db } from '../infra/db';\nexport const secret = db;\n", + ), + ( + "src/domain/index.ts", + "import { secret } from './internal';\nexport const api = secret;\n", + ), + ( + "src/app/ok.ts", + "import { api } from '../domain/index';\nexport const ok = api;\n", + ), + ( + "src/app/deep.ts", + "import { secret } from '../domain/internal';\nexport const deep = secret;\n", + ), + ( + "src/app/bad_infra.ts", + "import { db } from '../infra/db';\nexport const bad = db;\n", + ), + ( + "src/app/deep.test.ts", + "import { secret } from '../domain/internal';\nexport const tested = secret;\n", + ), + ]); + + let json = fixture.check_json(0); + let prod_boundaries = &json["source_sets"]["production"]["boundaries"]; + assert!(prod_boundaries.is_object()); + assert!(json["source_sets"]["test"].get("boundaries").is_none()); + let findings = prod_boundaries["findings"].as_array().expect("findings"); + assert_eq!(findings.len(), 3, "got: {findings:?}"); + + let domain_to_infra = findings + .iter() + .find(|f| f["importer"] == "src/domain/internal.ts" && f["target"] == "src/infra/db.ts") + .expect("domain -> infra deny finding"); + assert_eq!(domain_to_infra["kind"], "zone_rule"); + assert_eq!(domain_to_infra["source_zone"], "domain"); + assert_eq!(domain_to_infra["target_zone"], "infra"); + assert_eq!( + domain_to_infra["reason"], + "Domain logic must not depend on infrastructure" + ); + + let app_to_infra = findings + .iter() + .find(|f| f["importer"] == "src/app/bad_infra.ts" && f["target"] == "src/infra/db.ts") + .expect("app -> infra allow-violation finding"); + assert_eq!(app_to_infra["kind"], "zone_rule"); + assert_eq!(app_to_infra["source_zone"], "app"); + assert_eq!(app_to_infra["target_zone"], "infra"); + assert_eq!(app_to_infra["reason"], "App layer may only import domain"); + + let app_deep_import = findings + .iter() + .find(|f| f["importer"] == "src/app/deep.ts" && f["target"] == "src/domain/internal.ts") + .expect("app -> domain/internal public_files finding"); + assert_eq!(app_deep_import["kind"], "public_files"); + assert_eq!(app_deep_import["source_zone"], "app"); + assert_eq!(app_deep_import["target_zone"], "domain"); + + let toon = fixture.run(&["check"]); + assert_eq!(toon.status.code(), Some(0)); + let toon_text = String::from_utf8(toon.stdout).expect("utf8"); + assert!(toon_text.contains("boundaries:")); + assert!(toon_text.contains("src/domain/internal.ts")); + assert!(toon_text.contains("src/infra/db.ts")); + assert!(toon_text.contains("Domain logic must not depend on infrastructure")); + + let sarif_out = fixture.run(&["check", "--format", "sarif"]); + assert_eq!(sarif_out.status.code(), Some(0)); + let sarif: Value = serde_json::from_slice(&sarif_out.stdout).expect("valid SARIF"); + let boundary_sarif: Vec<&Value> = sarif["runs"][0]["results"] + .as_array() + .expect("SARIF results") + .iter() + .filter(|result| result["ruleId"] == "boundaries") + .collect(); + assert_eq!(boundary_sarif.len(), 3); + assert!(boundary_sarif.iter().any(|result| { + let text = result["message"]["text"].as_str().unwrap_or_default(); + text.contains("domain") + && text.contains("infra") + && text.contains("Domain logic must not depend on infrastructure") + })); + + let md = fixture.run(&["check", "--format", "markdown"]); + assert_eq!(md.status.code(), Some(0)); + let md_text = String::from_utf8(md.stdout).expect("utf8"); + assert!(md_text.contains("### Boundaries")); + assert!(md_text.contains("`src/domain/internal.ts`")); + assert!(md_text.contains("`src/infra/db.ts`")); + assert!(md_text.contains("Domain logic must not depend on infrastructure")); +} + +#[test] +fn check_rejects_invalid_boundary_configurations_with_exit_code_two() { + let cases = [ + ( + "unknown_from_zone", + r#"{ + "boundaries": { + "zones": { "domain": { "patterns": ["src/domain/**"] } }, + "rules": [{ "from": "missing", "deny": ["domain"] }] + } +}"#, + "missing", + ), + ( + "unknown_target_zone", + r#"{ + "boundaries": { + "zones": { "domain": { "patterns": ["src/domain/**"] } }, + "rules": [{ "from": "domain", "allow": ["ghost"] }] + } +}"#, + "ghost", + ), + ( + "invalid_glob", + r#"{ + "boundaries": { + "zones": { "domain": { "patterns": ["src/[unclosed"] } }, + "rules": [] + } +}"#, + "glob", + ), + ( + "conflicting_allow_and_deny_on_same_rule", + r#"{ + "boundaries": { + "zones": { + "domain": { "patterns": ["src/domain/**"] }, + "infra": { "patterns": ["src/infra/**"] } + }, + "rules": [{ "from": "domain", "allow": ["domain"], "deny": ["infra"] }] + } +}"#, + "allow", + ), + ( + "missing_allow_and_deny_on_rule", + r#"{ + "boundaries": { + "zones": { "domain": { "patterns": ["src/domain/**"] } }, + "rules": [{ "from": "domain" }] + } +}"#, + "allow", + ), + ( + "conflicting_allow_and_deny_across_rules_for_same_from", + r#"{ + "boundaries": { + "zones": { + "domain": { "patterns": ["src/domain/**"] }, + "infra": { "patterns": ["src/infra/**"] } + }, + "rules": [ + { "from": "domain", "allow": ["domain"] }, + { "from": "domain", "deny": ["infra"] } + ] + } +}"#, + "domain", + ), + ]; + + for (name, config_json, expected_substring) in cases { + let fixture = BoundaryFixture::init(&[ + ("codeint.json", config_json), + ("src/domain/a.ts", "export const a = 1;\n"), + ]); + let output = fixture.run(&["check"]); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "case {name}: {err}"); + assert!( + err.contains(expected_substring), + "case {name}: expected {expected_substring:?} in {err}" + ); + } +} + +#[test] +fn check_strict_zones_flags_unzoned_production_files() { + let fixture = BoundaryFixture::init(&[ + ( + "codeint.json", + r#"{ + "boundaries": { + "zones": { "domain": { "patterns": ["src/domain/**"] } }, + "strict_zones": true + } +} +"#, + ), + ("src/domain/a.ts", "export const a = 1;\n"), + ("src/orphan.ts", "export const orphan = 2;\n"), + ]); + + let json = fixture.check_json(0); + let findings = json["source_sets"]["production"]["boundaries"]["findings"] + .as_array() + .expect("findings"); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0]["kind"], "unzoned_file"); + assert_eq!(findings[0]["importer"], "src/orphan.ts"); +} + +#[test] +fn check_leaves_output_unchanged_when_boundaries_not_configured() { + let fixture = BoundaryFixture::init(&[("src/a.ts", "export const a = 1;\n")]); + let json = fixture.check_json(0); + assert!( + json["source_sets"]["production"] + .get("boundaries") + .is_none() + ); +} + +#[test] +fn check_enforces_boundaries_across_python_and_typescript() { + let fixture = BoundaryFixture::init(&[ + ( + "codeint.json", + r#"{ + "boundaries": { + "zones": { + "domain": { "patterns": ["py/domain/**", "ts/domain/**"] }, + "infra": { "patterns": ["py/infra/**", "ts/infra/**"] } + }, + "rules": [ + { + "from": "domain", + "deny": ["infra"], + "reason": "Domain cannot import infra in any language" + } + ] + } +} +"#, + ), + ("py/infra/db.py", "VALUE = 1\n"), + ( + "py/domain/service.py", + "from py.infra.db import VALUE\nX = VALUE\n", + ), + ("ts/infra/db.ts", "export const value = 1;\n"), + ( + "ts/domain/service.ts", + "import { value } from '../infra/db';\nexport const x = value;\n", + ), + ]); + + let json = fixture.check_json(0); + let findings = json["source_sets"]["production"]["boundaries"]["findings"] + .as_array() + .expect("findings"); + assert_eq!(findings.len(), 2, "got: {findings:?}"); + assert!( + findings + .iter() + .any(|f| f["importer"] == "py/domain/service.py") + ); + assert!( + findings + .iter() + .any(|f| f["importer"] == "ts/domain/service.ts") + ); +} + +#[test] +fn check_enforces_boundary_budget_overlap_precedence_and_optional_test_source_set() { + let fixture = BoundaryFixture::init(&[ + ( + "codeint.json", + r#"{ + "budgets": { + "production": { + "boundaries": 0 + } + }, + "boundaries": { + "zones": { + "core": { "patterns": ["src/**"] }, + "domain": { + "patterns": ["src/domain/**"], + "public_files": ["src/domain/index.ts"] + }, + "infra": { "patterns": ["src/infra/**"] } + }, + "rules": [ + { + "from": "domain", + "deny": ["infra"], + "reason": "Domain must stay independent of infra" + } + ], + "source_sets": ["production", "test"] + } +} +"#, + ), + ("src/infra/db.ts", "export const db = 1;\n"), + ( + "src/domain/service.ts", + "import { db } from '../infra/db';\nexport const svc = db;\n", + ), + ( + "src/domain/index.ts", + "import { svc } from './service';\nexport const api = svc;\n", + ), + ( + "src/app.test.ts", + "import { svc } from './domain/service';\nexport const tested = svc;\n", + ), + ]); + + let json = fixture.check_json(1); + let prod_findings = json["source_sets"]["production"]["boundaries"]["findings"] + .as_array() + .expect("production boundaries findings"); + assert_eq!(prod_findings.len(), 1); + assert_eq!(prod_findings[0]["source_zone"], "domain"); + assert_eq!(prod_findings[0]["target_zone"], "infra"); + + let test_findings = json["source_sets"]["test"]["boundaries"]["findings"] + .as_array() + .expect("test boundaries findings"); + assert_eq!(test_findings.len(), 1); + assert_eq!(test_findings[0]["kind"], "public_files"); + assert_eq!(test_findings[0]["source_zone"], "core"); + assert_eq!(test_findings[0]["target_zone"], "domain"); +} diff --git a/crates/cli/tests/check.rs b/crates/cli/tests/check.rs index 7231954..56d57b0 100644 --- a/crates/cli/tests/check.rs +++ b/crates/cli/tests/check.rs @@ -2719,7 +2719,7 @@ fn an_unknown_key_in_codeint_json_is_named_with_the_allowed_keys_and_exits_2() { fn an_unknown_top_level_key_in_codeint_json_is_named_and_exits_2() { assert_codeint_json_is_rejected( r#"{ "budget": {} }"#, - "codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits", + "codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries", UNKNOWN_KEY_REMEDY, ); } @@ -3937,7 +3937,7 @@ fn a_budget_for_an_unknown_metric_names_the_metrics_and_exits_2() { assert_codeint_json_is_rejected( r#"{ "budgets": { "production": { "complexity": 0.1 } } }"#, "codeint.json has an unknown key budgets.production.complexity; \ - the keys allowed there are erosion, duplication, verbosity, import_cycles", + the keys allowed there are erosion, duplication, verbosity, import_cycles, boundaries", UNKNOWN_KEY_REMEDY, ); } diff --git a/crates/config/src/boundaries.rs b/crates/config/src/boundaries.rs new file mode 100644 index 0000000..b176be3 --- /dev/null +++ b/crates/config/src/boundaries.rs @@ -0,0 +1,387 @@ +use std::collections::BTreeMap; + +use codeint_model::{RepoPath, SourceSet}; +use globset::{GlobBuilder, GlobMatcher, GlobSet}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::codeint_json::{ConfigurationFileError, KeyPath, KeySegment, glob_set}; + +const WILDCARD_ZONE: &str = "*"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BoundaryDirective { + Allow, + Deny, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BoundaryRuleDecision { + Allowed, + Denied { + directive: BoundaryDirective, + reason: Option, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum BoundarySourceSet { + Production, + Test, + Generated, + Vendored, +} + +impl From for SourceSet { + fn from(value: BoundarySourceSet) -> SourceSet { + match value { + BoundarySourceSet::Production => SourceSet::Production, + BoundarySourceSet::Test => SourceSet::Test, + BoundarySourceSet::Generated => SourceSet::Generated, + BoundarySourceSet::Vendored => SourceSet::Vendored, + } + } +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub(crate) struct BoundariesFile { + #[serde(default)] + #[schemars( + description = "Named architectural zones, each defined by repository-relative path globs and optional public_files globs." + )] + zones: BTreeMap, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[schemars( + description = "Directional allow or deny import rules between architectural zones." + )] + rules: Vec, + #[serde(default, skip_serializing_if = "is_false")] + #[schemars( + description = "When true, report files in evaluated Source sets that do not match any configured zone." + )] + strict_zones: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[schemars( + description = "Source sets evaluated by boundary rules; defaults to [\"production\"] when omitted or empty." + )] + source_sets: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct BoundaryZoneFile { + #[schemars( + description = "Repository-relative path globs that assign files to this architectural zone." + )] + patterns: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[schemars( + description = "Optional repository-relative path globs naming the only files in this zone that other zones may import." + )] + public_files: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct BoundaryRuleFile { + #[schemars( + description = "Source zone name, or \"*\" to match any zone without a specific rule." + )] + from: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars( + with = "Vec", + description = "Target zone names (or \"*\") that the source zone is allowed to import. Mutually exclusive with deny." + )] + allow: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars( + with = "Vec", + description = "Target zone names (or \"*\") that the source zone is forbidden to import. Mutually exclusive with allow." + )] + deny: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars( + with = "String", + description = "Optional human-readable explanation shown in boundary Findings." + )] + reason: Option, +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[derive(Debug, Clone)] +struct CompiledPattern { + matcher: GlobMatcher, + literal_chars: usize, + pattern_len: usize, +} + +#[derive(Debug, Clone)] +struct CompiledZone { + patterns: Vec, + public_files: Option, +} + +#[derive(Debug, Clone)] +struct CompiledRule { + from: String, + directive: BoundaryDirective, + targets: Vec, + reason: Option, +} + +#[derive(Debug, Clone)] +pub struct Boundaries { + zones: BTreeMap, + rules: Vec, + strict_zones: bool, + source_sets: Vec, +} + +impl Boundaries { + pub(crate) fn from_file(file: BoundariesFile) -> Result { + let boundaries_key = KeyPath::default().child(KeySegment::Key("boundaries".to_owned())); + let zones_key = boundaries_key.child(KeySegment::Key("zones".to_owned())); + let mut zones = BTreeMap::new(); + for (name, zone_file) in file.zones { + let zone_key = zones_key.child(KeySegment::Key(name.clone())); + if name.trim().is_empty() || name == WILDCARD_ZONE { + return Err(ConfigurationFileError::InvalidBoundaryZoneName { + key: zone_key, + name, + }); + } + if zone_file.patterns.is_empty() { + return Err(ConfigurationFileError::EmptyBoundaryZonePatterns { + key: zone_key.child(KeySegment::Key("patterns".to_owned())), + zone: name, + }); + } + let patterns_key = zone_key.child(KeySegment::Key("patterns".to_owned())); + let patterns = compile_patterns(&patterns_key, &zone_file.patterns)?; + let public_files = if zone_file.public_files.is_empty() { + None + } else { + let public_key = zone_key.child(KeySegment::Key("public_files".to_owned())); + Some(glob_set(&public_key, &zone_file.public_files)?) + }; + zones.insert( + name, + CompiledZone { + patterns, + public_files, + }, + ); + } + + let known_zones: Vec = zones.keys().cloned().collect(); + let rules_key = boundaries_key.child(KeySegment::Key("rules".to_owned())); + let mut rules = Vec::with_capacity(file.rules.len()); + let mut directive_by_from: BTreeMap = BTreeMap::new(); + + for (index, rule) in file.rules.into_iter().enumerate() { + let rule_key = rules_key.child(KeySegment::Index(index)); + if rule.from != WILDCARD_ZONE && !zones.contains_key(&rule.from) { + return Err(ConfigurationFileError::UnknownBoundaryZone { + key: rule_key.child(KeySegment::Key("from".to_owned())), + zone: rule.from, + known: known_zones, + }); + } + let (directive, targets, targets_key_name) = match (rule.allow, rule.deny) { + (Some(allow), None) => (BoundaryDirective::Allow, allow, "allow"), + (None, Some(deny)) => (BoundaryDirective::Deny, deny, "deny"), + (Some(_), Some(_)) => { + return Err(ConfigurationFileError::ConflictingBoundaryRule { + key: rule_key, + from: rule.from, + }); + } + (None, None) => { + return Err(ConfigurationFileError::MissingBoundaryRuleDirective { + key: rule_key, + from: rule.from, + }); + } + }; + if let Some(&previous) = directive_by_from.get(&rule.from) + && previous != directive + { + return Err(ConfigurationFileError::ConflictingBoundaryDirectives { + key: rule_key, + from: rule.from, + }); + } + directive_by_from.insert(rule.from.clone(), directive); + + let targets_key = rule_key.child(KeySegment::Key(targets_key_name.to_owned())); + for (target_index, target) in targets.iter().enumerate() { + if target != WILDCARD_ZONE && !zones.contains_key(target) { + return Err(ConfigurationFileError::UnknownBoundaryZone { + key: targets_key.child(KeySegment::Index(target_index)), + zone: target.clone(), + known: known_zones, + }); + } + } + rules.push(CompiledRule { + from: rule.from, + directive, + targets, + reason: rule.reason.filter(|text| !text.trim().is_empty()), + }); + } + + let source_sets = if file.source_sets.is_empty() { + vec![SourceSet::Production] + } else { + file.source_sets.into_iter().map(SourceSet::from).collect() + }; + + Ok(Boundaries { + zones, + rules, + strict_zones: file.strict_zones, + source_sets, + }) + } + + pub fn applies_to_source_set(&self, source_set: SourceSet) -> bool { + self.source_sets.contains(&source_set) + } + + pub fn strict_zones(&self) -> bool { + self.strict_zones + } + + pub fn zone_of(&self, path: &RepoPath) -> Option<&str> { + let mut best: Option<(&str, usize, usize)> = None; + for (zone_name, zone) in &self.zones { + for pattern in &zone.patterns { + if pattern.matcher.is_match(path.as_str()) { + let candidate = ( + zone_name.as_str(), + pattern.literal_chars, + pattern.pattern_len, + ); + let replaces = match best { + None => true, + Some((best_name, best_literals, best_len)) => { + (candidate.1, candidate.2) > (best_literals, best_len) + || ((candidate.1, candidate.2) == (best_literals, best_len) + && candidate.0 < best_name) + } + }; + if replaces { + best = Some(candidate); + } + } + } + } + best.map(|(name, _, _)| name) + } + + pub fn has_public_files(&self, zone: &str) -> bool { + self.zones + .get(zone) + .is_some_and(|compiled| compiled.public_files.is_some()) + } + + pub fn is_public_file(&self, zone: &str, path: &RepoPath) -> bool { + match self.zones.get(zone).and_then(|z| z.public_files.as_ref()) { + Some(globs) => globs.is_match(path.as_str()), + None => true, + } + } + + pub fn check_import(&self, source_zone: &str, target_zone: &str) -> BoundaryRuleDecision { + if source_zone == target_zone { + return BoundaryRuleDecision::Allowed; + } + let specific: Vec<&CompiledRule> = self + .rules + .iter() + .filter(|rule| rule.from == source_zone) + .collect(); + let applicable: Vec<&CompiledRule> = if specific.is_empty() { + self.rules + .iter() + .filter(|rule| rule.from == WILDCARD_ZONE) + .collect() + } else { + specific + }; + let Some(first) = applicable.first() else { + return BoundaryRuleDecision::Allowed; + }; + match first.directive { + BoundaryDirective::Allow => { + let permitted = applicable.iter().any(|rule| { + rule.targets + .iter() + .any(|target| target == target_zone || target == WILDCARD_ZONE) + }); + if permitted { + BoundaryRuleDecision::Allowed + } else { + let reason = applicable.iter().find_map(|rule| rule.reason.clone()); + BoundaryRuleDecision::Denied { + directive: BoundaryDirective::Allow, + reason, + } + } + } + BoundaryDirective::Deny => { + let denied_by = applicable.iter().find(|rule| { + rule.targets + .iter() + .any(|target| target == target_zone || target == WILDCARD_ZONE) + }); + match denied_by { + Some(rule) => BoundaryRuleDecision::Denied { + directive: BoundaryDirective::Deny, + reason: rule.reason.clone(), + }, + None => BoundaryRuleDecision::Allowed, + } + } + } + } +} + +fn compile_patterns( + key: &KeyPath, + globs: &[String], +) -> Result, ConfigurationFileError> { + globs + .iter() + .enumerate() + .map(|(index, glob)| { + let compiled = GlobBuilder::new(glob) + .literal_separator(true) + .backslash_escape(true) + .build() + .map_err(|source| ConfigurationFileError::InvalidGlob { + key: key.child(KeySegment::Index(index)), + source, + })?; + Ok(CompiledPattern { + matcher: compiled.compile_matcher(), + literal_chars: literal_char_count(glob), + pattern_len: glob.len(), + }) + }) + .collect() +} + +fn literal_char_count(pattern: &str) -> usize { + pattern + .chars() + .filter(|character| !matches!(character, '*' | '?' | '[' | ']' | '{' | '}')) + .count() +} diff --git a/crates/config/src/codeint_json.rs b/crates/config/src/codeint_json.rs index 4fd1df3..4e36d8e 100644 --- a/crates/config/src/codeint_json.rs +++ b/crates/config/src/codeint_json.rs @@ -5,6 +5,7 @@ use std::path::{Path, PathBuf}; use codeint_model::{Metric, RepoPath, SourceSet}; use crate::RegressionLimits; +use crate::boundaries::{Boundaries, BoundariesFile}; use crate::regression_limits::RegressionLimitSetting; use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; use schemars::JsonSchema; @@ -52,6 +53,7 @@ pub struct Configuration { pub regression_limits: RegressionLimits, pub plugins: Vec, pub plugin_limits: PluginLimits, + pub boundaries: Option, effective: ConfigurationFile, } @@ -128,12 +130,16 @@ impl Configuration { let allowed_metrics = || -> Vec { Metric::BUILT_IN_KEYS .iter() + .chain(["boundaries"].iter()) .chain(external_metric_keys.iter()) .map(|key| (*key).to_owned()) .collect() }; - let is_known = - |key: &str| Metric::BUILT_IN_KEYS.contains(&key) || external_metric_keys.contains(&key); + let is_known = |key: &str| { + Metric::BUILT_IN_KEYS.contains(&key) + || key == "boundaries" + || external_metric_keys.contains(&key) + }; for (source_set, metric_key, _) in &self.budgets.set { if !is_known(metric_key) { return Err(ConfigurationFileError::UnknownKey { @@ -403,6 +409,33 @@ pub enum ConfigurationFileError { config_version: String, binary_version: String, }, + #[error("{CONFIGURATION_FILE_NAME}: {key} has invalid boundary zone name {name:?}")] + InvalidBoundaryZoneName { key: KeyPath, name: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} for boundary zone {zone:?} must list at least one glob pattern" + )] + EmptyBoundaryZonePatterns { key: KeyPath, zone: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} references unknown boundary zone {zone:?}; known zones are {}", + known.join(", ") + )] + UnknownBoundaryZone { + key: KeyPath, + zone: String, + known: Vec, + }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} for boundary zone {from:?} must set either allow or deny, not both" + )] + ConflictingBoundaryRule { key: KeyPath, from: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} for boundary zone {from:?} must set either allow or deny" + )] + MissingBoundaryRuleDirective { key: KeyPath, from: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} mixes allow and deny directives for boundary zone {from:?}" + )] + ConflictingBoundaryDirectives { key: KeyPath, from: String }, } #[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] @@ -447,6 +480,12 @@ struct ConfigurationFile { description = "Memory cap and time limit enforced on each WebAssembly Plugin. Defaults are 64 MiB and 5000 ms." )] plugin_limits: PluginLimitsFile, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars( + with = "BoundariesFile", + description = "Architectural import boundaries defining named zones, optional public_files entry points, directional allow or deny rules, and optional strict_zones mode." + )] + boundaries: Option, } #[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] @@ -628,6 +667,13 @@ struct MetricBudgets { description = "The highest Import cycles ratio, from 0 to 1." )] import_cycles: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars( + with = "f64", + range(min = 0, max = 1), + description = "The highest Boundaries ratio, from 0 to 1." + )] + boundaries: Option, #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")] external: BTreeMap, } @@ -686,6 +732,7 @@ fn parse(text: &str) -> Result { let file: ConfigurationFile = serde_json::from_value(value).map_err(ConfigurationFileError::NotJson)?; let effective = file.without_schema_address(); + let parsed_boundaries = file.boundaries.map(Boundaries::from_file).transpose()?; Ok(Configuration { effective, source_set_overrides: source_set_overrides(file.source_sets)?, @@ -694,6 +741,7 @@ fn parse(text: &str) -> Result { regression_limits: regression_limits(file.regression_limits), plugins: plugins(file.plugins)?, plugin_limits: plugin_limits(file.plugin_limits), + boundaries: parsed_boundaries, }) } @@ -846,6 +894,7 @@ fn budgets(file: SourceSetBudgets) -> Budgets { duplication, verbosity, import_cycles, + boundaries, external, } = metric_budgets; [ @@ -853,6 +902,7 @@ fn budgets(file: SourceSetBudgets) -> Budgets { (Metric::Duplication.key().to_owned(), duplication), (Metric::Verbosity.key().to_owned(), verbosity), (Metric::ImportCycles.key().to_owned(), import_cycles), + ("boundaries".to_owned(), boundaries), ] .into_iter() .filter_map(move |(metric, ratio)| Some((source_set, metric, ratio?))) @@ -922,7 +972,7 @@ fn source_set_overrides( Ok(SourceSetOverrides { by_precedence }) } -fn glob_set(key: &KeyPath, globs: &[String]) -> Result { +pub(crate) fn glob_set(key: &KeyPath, globs: &[String]) -> Result { let mut builder = GlobSetBuilder::new(); for (index, glob) in globs.iter().enumerate() { let compiled = GlobBuilder::new(glob) @@ -944,7 +994,7 @@ fn glob_set(key: &KeyPath, globs: &[String]) -> Result KeyPath { + pub(crate) fn child(&self, segment: KeySegment) -> KeyPath { let mut segments = self.0.clone(); segments.push(segment); KeyPath(segments) diff --git a/crates/config/src/codeint_json/starter.rs b/crates/config/src/codeint_json/starter.rs index 2d8d85d..c991ddc 100644 --- a/crates/config/src/codeint_json/starter.rs +++ b/crates/config/src/codeint_json/starter.rs @@ -68,6 +68,7 @@ fn starter_configuration_text(languages: &[DetectedLanguage]) -> String { regression_limits: Default::default(), plugins: Vec::new(), plugin_limits: Default::default(), + boundaries: None, languages: (!languages.is_empty()).then(|| { languages .iter() diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 5f9a88b..11102d1 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -4,11 +4,13 @@ use std::path::{Path, PathBuf}; use clap::{Parser, Subcommand}; +mod boundaries; mod calendar_day; mod codeint_json; mod regression_limits; mod result_cache_folder; +pub use boundaries::{Boundaries, BoundaryDirective, BoundaryRuleDecision, BoundarySourceSet}; pub use calendar_day::{CalendarDay, CalendarDayError}; pub use codeint_json::{ Budget, Budgets, Configuration, ConfigurationFileError, DetectedLanguage, JsonType, KeyPath, diff --git a/crates/metrics/src/boundaries.rs b/crates/metrics/src/boundaries.rs new file mode 100644 index 0000000..f3af495 --- /dev/null +++ b/crates/metrics/src/boundaries.rs @@ -0,0 +1,235 @@ +use codeint_model::{CodeModel, ImportResolution, RepoPath, token_text_hash}; + +use crate::FindingId; +use crate::finding_id::FindingIds; + +const BOUNDARIES_METRIC_KEY: &str = "boundaries"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum BoundaryEdgeCheck { + Allowed, + DeniedByAllowRule { reason: Option }, + DeniedByDenyRule { reason: Option }, +} + +pub trait BoundaryPolicy { + fn zone_of(&self, path: &RepoPath) -> Option<&str>; + + fn has_public_files(&self, zone: &str) -> bool; + + fn is_public_file(&self, zone: &str, path: &RepoPath) -> bool; + + fn check_import(&self, source_zone: &str, target_zone: &str) -> BoundaryEdgeCheck; + + fn strict_zones(&self) -> bool; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum BoundaryFindingKind { + ZoneRule, + PublicFiles, + UnzonedFile, +} + +impl BoundaryFindingKind { + pub fn key(self) -> &'static str { + match self { + BoundaryFindingKind::ZoneRule => "zone_rule", + BoundaryFindingKind::PublicFiles => "public_files", + BoundaryFindingKind::UnzonedFile => "unzoned_file", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BoundaryFinding { + pub id: FindingId, + pub kind: BoundaryFindingKind, + pub importer: RepoPath, + pub target: Option, + pub specifier: Option, + pub source_zone: Option, + pub target_zone: Option, + pub reason: Option, + pub message: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Boundaries { + resolved_imports: usize, + findings: Vec, +} + +struct PendingFinding { + kind: BoundaryFindingKind, + importer: RepoPath, + target: Option, + specifier: Option, + source_zone: Option, + target_zone: Option, + reason: Option, + message: String, +} + +impl Boundaries { + pub fn measure(model: &CodeModel, policy: &dyn BoundaryPolicy) -> Boundaries { + let mut resolved_imports = 0usize; + let mut pending = Vec::new(); + + for runtime_import in &model.runtime_imports { + let ImportResolution::Resolved(target) = &runtime_import.resolution else { + continue; + }; + resolved_imports += 1; + let (Some(source_zone), Some(target_zone)) = ( + policy.zone_of(&runtime_import.importer), + policy.zone_of(target), + ) else { + continue; + }; + if source_zone == target_zone { + continue; + } + match policy.check_import(source_zone, target_zone) { + BoundaryEdgeCheck::DeniedByDenyRule { reason } => { + pending.push(PendingFinding { + kind: BoundaryFindingKind::ZoneRule, + importer: runtime_import.importer.clone(), + target: Some(target.clone()), + specifier: Some(runtime_import.specifier.clone()), + source_zone: Some(source_zone.to_owned()), + target_zone: Some(target_zone.to_owned()), + message: format_zone_rule_message( + source_zone, + target_zone, + "is denied from importing", + reason.as_deref(), + ), + reason, + }); + } + BoundaryEdgeCheck::DeniedByAllowRule { reason } => { + pending.push(PendingFinding { + kind: BoundaryFindingKind::ZoneRule, + importer: runtime_import.importer.clone(), + target: Some(target.clone()), + specifier: Some(runtime_import.specifier.clone()), + source_zone: Some(source_zone.to_owned()), + target_zone: Some(target_zone.to_owned()), + message: format_zone_rule_message( + source_zone, + target_zone, + "is not allowed to import", + reason.as_deref(), + ), + reason, + }); + } + BoundaryEdgeCheck::Allowed => { + if policy.has_public_files(target_zone) + && !policy.is_public_file(target_zone, target) + { + pending.push(PendingFinding { + kind: BoundaryFindingKind::PublicFiles, + importer: runtime_import.importer.clone(), + target: Some(target.clone()), + specifier: Some(runtime_import.specifier.clone()), + source_zone: Some(source_zone.to_owned()), + target_zone: Some(target_zone.to_owned()), + reason: None, + message: format!( + "zone {source_zone:?} deep-imports non-public file {target} of zone {target_zone:?}" + ), + }); + } + } + } + } + + if policy.strict_zones() { + for file in &model.files { + if policy.zone_of(&file.path).is_none() { + pending.push(PendingFinding { + kind: BoundaryFindingKind::UnzonedFile, + importer: file.path.clone(), + target: None, + specifier: None, + source_zone: None, + target_zone: None, + reason: None, + message: format!( + "file {} does not belong to any configured zone", + file.path + ), + }); + } + } + } + + pending.sort_by(|left, right| { + left.importer + .cmp(&right.importer) + .then_with(|| left.target.cmp(&right.target)) + .then_with(|| left.kind.cmp(&right.kind)) + .then_with(|| left.specifier.cmp(&right.specifier)) + }); + + let mut ids = FindingIds::for_key(BOUNDARIES_METRIC_KEY); + let findings = pending + .into_iter() + .map(|item| { + let kind_hash = token_text_hash(item.kind.key()); + let id = match &item.target { + Some(target) => ids.next_in_source_order([&item.importer, target], [kind_hash]), + None => ids.next_in_source_order([&item.importer], [kind_hash]), + }; + BoundaryFinding { + id, + kind: item.kind, + importer: item.importer, + target: item.target, + specifier: item.specifier, + source_zone: item.source_zone, + target_zone: item.target_zone, + reason: item.reason, + message: item.message, + } + }) + .collect(); + + Boundaries { + resolved_imports, + findings, + } + } + + pub fn ratio(&self) -> f64 { + if self.findings.is_empty() { + 0.0 + } else if self.resolved_imports == 0 { + 1.0 + } else { + (self.findings.len() as f64 / self.resolved_imports as f64).min(1.0) + } + } + + pub fn resolved_imports(&self) -> usize { + self.resolved_imports + } + + pub fn findings(&self) -> &[BoundaryFinding] { + &self.findings + } +} + +fn format_zone_rule_message( + source_zone: &str, + target_zone: &str, + verb: &str, + reason: Option<&str>, +) -> String { + match reason { + Some(reason) => format!("zone {source_zone:?} {verb} zone {target_zone:?}: {reason}"), + None => format!("zone {source_zone:?} {verb} zone {target_zone:?}"), + } +} diff --git a/crates/metrics/src/finding_id.rs b/crates/metrics/src/finding_id.rs index 802f033..e75e70d 100644 --- a/crates/metrics/src/finding_id.rs +++ b/crates/metrics/src/finding_id.rs @@ -13,14 +13,18 @@ impl fmt::Display for FindingId { } pub(crate) struct FindingIds { - metric: Metric, + metric_key: &'static str, occurrences: HashMap, } impl FindingIds { pub(crate) fn new(metric: Metric) -> FindingIds { + FindingIds::for_key(metric.key()) + } + + pub(crate) fn for_key(metric_key: &'static str) -> FindingIds { FindingIds { - metric, + metric_key, occurrences: HashMap::new(), } } @@ -30,7 +34,7 @@ impl FindingIds { paths: impl IntoIterator, content: impl IntoIterator, ) -> FindingId { - let with_metric = length_prefixed(StableHasher::new(), self.metric.key().as_bytes()); + let with_metric = length_prefixed(StableHasher::new(), self.metric_key.as_bytes()); let mut path_count = 0; let with_paths = paths.into_iter().fold(with_metric, |hasher, path| { path_count += 1; diff --git a/crates/metrics/src/lib.rs b/crates/metrics/src/lib.rs index a168e66..3262502 100644 --- a/crates/metrics/src/lib.rs +++ b/crates/metrics/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod boundaries; mod duplication; mod erosion; mod finding_id; @@ -7,6 +8,9 @@ mod import_cycles; mod line_share; mod verbosity; +pub use boundaries::{ + Boundaries, BoundaryEdgeCheck, BoundaryFinding, BoundaryFindingKind, BoundaryPolicy, +}; pub use duplication::{ CloneGroup, CloneLines, Duplication, Fragment, MinimumCloneTokens, MinimumDistinctTokens, }; diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index a5248a4..fd4e026 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -199,6 +199,7 @@ impl DiffReport { clone_groups: &changes.duplication.new.listed, flagged_lines: &changes.verbosity.new.listed, import_cycles: &changes.import_cycles.new.listed, + boundaries: &[], external_metrics: changes .external_metrics .iter() diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index 9d01d58..291c85e 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -2,10 +2,14 @@ use std::collections::BTreeMap; -use codeint_config::{Budgets, FindingsShown, ReportFormat}; +use codeint_config::{ + Boundaries as BoundariesConfig, BoundaryDirective, BoundaryRuleDecision, Budgets, + FindingsShown, ReportFormat, +}; use codeint_metrics::{ - CloneGroup, Duplication, ErodedFunction, Erosion, FlaggedLineFinding, Fragment, ImportCycle, - ImportCycles, MinimumCloneTokens, MinimumDistinctTokens, UnresolvedImport, Verbosity, + Boundaries, BoundaryEdgeCheck, BoundaryFinding, BoundaryPolicy, CloneGroup, Duplication, + ErodedFunction, Erosion, FlaggedLineFinding, Fragment, ImportCycle, ImportCycles, + MinimumCloneTokens, MinimumDistinctTokens, UnresolvedImport, Verbosity, }; use codeint_model::{ CodeModel, ExternalFinding, Metric, MetricPlugin, MetricPluginError, Package, ReferenceRange, @@ -114,12 +118,40 @@ struct SourceSetSection { duplication: DuplicationSection, verbosity: VerbositySection, import_cycles: ImportCyclesSection, + #[serde(skip_serializing_if = "Option::is_none")] + boundaries: Option, #[serde(flatten)] external_metrics: BTreeMap, #[serde(skip_serializing_if = "Vec::is_empty")] packages: Vec, } +#[derive(Debug, Serialize)] +struct BoundariesSection { + ratio: Decimal, + resolved_imports: usize, + #[serde(flatten)] + findings: Findings, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct BoundaryFindingRow { + id: String, + kind: String, + importer: String, + #[serde(skip_serializing_if = "Option::is_none")] + target: Option, + #[serde(skip_serializing_if = "Option::is_none")] + specifier: Option, + #[serde(skip_serializing_if = "Option::is_none")] + source_zone: Option, + #[serde(skip_serializing_if = "Option::is_none")] + target_zone: Option, + #[serde(skip_serializing_if = "Option::is_none")] + reason: Option, + message: String, +} + #[derive(Debug, Serialize)] struct ExternalMetricSection { #[serde(skip)] @@ -406,6 +438,73 @@ impl FindingKind for ExternalMetricFinding { const LIST_KEY: &'static str = "findings"; } +impl FindingKind for BoundaryFindingRow { + const LIST_KEY: &'static str = "findings"; +} + +struct ConfigBoundaryPolicy<'config>(&'config BoundariesConfig); + +impl BoundaryPolicy for ConfigBoundaryPolicy<'_> { + fn zone_of(&self, path: &RepoPath) -> Option<&str> { + self.0.zone_of(path) + } + + fn has_public_files(&self, zone: &str) -> bool { + self.0.has_public_files(zone) + } + + fn is_public_file(&self, zone: &str, path: &RepoPath) -> bool { + self.0.is_public_file(zone, path) + } + + fn check_import(&self, source_zone: &str, target_zone: &str) -> BoundaryEdgeCheck { + match self.0.check_import(source_zone, target_zone) { + BoundaryRuleDecision::Allowed => BoundaryEdgeCheck::Allowed, + BoundaryRuleDecision::Denied { + directive: BoundaryDirective::Allow, + reason, + } => BoundaryEdgeCheck::DeniedByAllowRule { reason }, + BoundaryRuleDecision::Denied { + directive: BoundaryDirective::Deny, + reason, + } => BoundaryEdgeCheck::DeniedByDenyRule { reason }, + } + } + + fn strict_zones(&self) -> bool { + self.0.strict_zones() + } +} + +impl BoundariesSection { + fn new(boundaries: &Boundaries, shown: FindingsShown) -> BoundariesSection { + BoundariesSection { + ratio: Decimal::rounded(boundaries.ratio()), + resolved_imports: boundaries.resolved_imports(), + findings: Findings::worst_first( + boundaries.findings().iter().map(BoundaryFindingRow::from), + shown, + ), + } + } +} + +impl From<&BoundaryFinding> for BoundaryFindingRow { + fn from(finding: &BoundaryFinding) -> BoundaryFindingRow { + BoundaryFindingRow { + id: finding.id.to_string(), + kind: finding.kind.key().to_owned(), + importer: finding.importer.to_string(), + target: finding.target.as_ref().map(RepoPath::to_string), + specifier: finding.specifier.clone(), + source_zone: finding.source_zone.clone(), + target_zone: finding.target_zone.clone(), + reason: finding.reason.clone(), + message: finding.message.clone(), + } + } +} + impl ExternalMetricFinding { fn from_model(finding: &ExternalFinding) -> ExternalMetricFinding { ExternalMetricFinding { @@ -424,15 +523,19 @@ impl SourceSetSections { ranges: &ReferenceRangeScope, findings: FindingsShown, metric_plugins: &[&dyn MetricPlugin], + boundaries: Option<&BoundariesConfig>, ) -> Result { let mut sections = SourceSetSections::default(); for (source_set, model) in source_sets.iter() { if !model.files.is_empty() { + let source_set_boundaries = + boundaries.filter(|config| config.applies_to_source_set(source_set)); *sections.slot(source_set) = Some(SourceSetSection::new( model, ranges, findings, metric_plugins, + source_set_boundaries, )?); } } @@ -473,6 +576,12 @@ impl SourceSetSections { ), ] .into_iter() + .chain( + section + .boundaries + .iter() + .map(move |boundaries| (source_set, "boundaries", boundaries.ratio.0)), + ) .chain( section .external_metrics @@ -499,8 +608,13 @@ impl SourceSetSection { ranges: &ReferenceRangeScope, findings: FindingsShown, metric_plugins: &[&dyn MetricPlugin], + boundaries: Option<&BoundariesConfig>, ) -> Result { let measured = Measured::new(model); + let boundaries = boundaries.map(|config| { + let evaluated = Boundaries::measure(model, &ConfigBoundaryPolicy(config)); + BoundariesSection::new(&evaluated, findings) + }); let mut external_metrics = BTreeMap::new(); for plugin in metric_plugins { let result = plugin.measure(model)?; @@ -530,6 +644,7 @@ impl SourceSetSection { duplication: DuplicationSection::new(&measured.duplication, ranges, findings), verbosity: VerbositySection::new(&measured.verbosity, ranges, findings), import_cycles: ImportCyclesSection::new(&measured.import_cycles, ranges, findings), + boundaries, external_metrics, packages: package_sections(model, &measured), }) @@ -782,11 +897,17 @@ impl MeasuredSection { ranges: &ReferenceRangeScope, findings: FindingsShown, metric_plugins: &[&dyn MetricPlugin], + boundaries: Option<&BoundariesConfig>, ) -> Result { let files = model.files.len(); let lines = source_lines(&model); - let source_sets = - SourceSetSections::new(&model.into_source_sets(), ranges, findings, metric_plugins)?; + let source_sets = SourceSetSections::new( + &model.into_source_sets(), + ranges, + findings, + metric_plugins, + boundaries, + )?; Ok(MeasuredSection { files, source_lines: lines, @@ -812,6 +933,24 @@ impl Report { findings: FindingsShown, budgets: &Budgets, metric_plugins: &[&dyn MetricPlugin], + ) -> Result { + Report::summarize_with_metrics_and_boundaries( + languages, + submodules, + findings, + budgets, + metric_plugins, + None, + ) + } + + pub fn summarize_with_metrics_and_boundaries( + languages: Vec, + submodules: Vec, + findings: FindingsShown, + budgets: &Budgets, + metric_plugins: &[&dyn MetricPlugin], + boundaries: Option<&BoundariesConfig>, ) -> Result { let (measured, unmeasured): (Vec, Vec) = languages .into_iter() @@ -835,6 +974,7 @@ impl Report { &ReferenceRangeScope::OneLanguage(language.reference_ranges.clone()), findings, metric_plugins, + boundaries, )?, ); } @@ -853,7 +993,8 @@ impl Report { .iter() .map(RepoPath::to_string) .collect(); - let measured = MeasuredSection::new(model, &total_ranges, findings, metric_plugins)?; + let measured = + MeasuredSection::new(model, &total_ranges, findings, metric_plugins, boundaries)?; Ok(Report { over_budget: measured.source_sets.over_budget(budgets), skipped, diff --git a/crates/report/src/markdown.rs b/crates/report/src/markdown.rs index 0c067b9..c2d0fe0 100644 --- a/crates/report/src/markdown.rs +++ b/crates/report/src/markdown.rs @@ -1,8 +1,8 @@ use crate::{ - CloneGroupFinding, CloneLocation, DuplicationSection, ErodedFunctionFinding, ErosionSection, - ExternalMetricFinding, Findings, FlaggedLineRow, ImportCycleFinding, ImportCyclesSection, - MeasuredSection, PackageSection, ReferenceRangeEntry, Report, SourceSetSection, - SourceSetSections, UnresolvedImportRow, VerbositySection, + BoundaryFindingRow, CloneGroupFinding, CloneLocation, DuplicationSection, + ErodedFunctionFinding, ErosionSection, ExternalMetricFinding, Findings, FlaggedLineRow, + ImportCycleFinding, ImportCyclesSection, MeasuredSection, PackageSection, ReferenceRangeEntry, + Report, SourceSetSection, SourceSetSections, UnresolvedImportRow, VerbositySection, }; #[cfg(test)] @@ -34,6 +34,14 @@ const PACKAGE_COLUMNS: [&str; 8] = [ ]; pub(crate) const FLAGGED_LINE_COLUMNS: [&str; 2] = ["Flagged line", "Rule"]; pub(crate) const EXTERNAL_FINDING_COLUMNS: [&str; 2] = ["Location", "Message"]; +const BOUNDARY_FINDING_COLUMNS: [&str; 6] = [ + "Importer", + "Target", + "Source zone", + "Target zone", + "Rule", + "Reason", +]; const UNRESOLVED_IMPORT_COLUMNS: [&str; 3] = ["Importer", "Specifier", "Reason"]; pub(crate) struct Noun { @@ -294,6 +302,20 @@ fn metric_rows(source_set: &str, section: &SourceSetSection) -> Vec> &import_cycles.reference_range, ), ]; + if let Some(boundaries) = §ion.boundaries { + let total_findings = boundaries.findings.listed.len() + boundaries.findings.left_out; + rows.push(vec![ + source_set.to_string(), + "Boundaries".to_string(), + boundaries.ratio.0.to_string(), + format!( + "{} across {} resolved imports", + FINDING.counted(total_findings as u64), + boundaries.resolved_imports + ), + "not applicable".to_string(), + ]); + } for external in section.external_metrics.values() { rows.push(row( &external.name, @@ -382,6 +404,20 @@ fn findings_blocks(section: &SourceSetSection) -> Vec { ) }, ); + if let Some(boundaries) = §ion.boundaries { + push_findings( + &mut blocks, + "Boundaries", + &boundaries.findings, + &FINDING, + |listed| { + table( + &BOUNDARY_FINDING_COLUMNS, + listed.iter().map(boundary_finding_row).collect(), + ) + }, + ); + } for external in section.external_metrics.values() { push_findings( &mut blocks, @@ -477,6 +513,21 @@ fn unresolved_import_row(row: &UnresolvedImportRow) -> Vec { ] } +fn boundary_finding_row(row: &BoundaryFindingRow) -> Vec { + vec![ + code(&row.importer), + row.target.as_deref().map_or_else(|| "-".to_owned(), code), + row.source_zone + .as_deref() + .map_or_else(|| "-".to_owned(), prose), + row.target_zone + .as_deref() + .map_or_else(|| "-".to_owned(), prose), + prose(&row.kind), + prose(row.reason.as_deref().unwrap_or(&row.message)), + ] +} + fn files_not_measured(report: &Report) -> Vec { let skipped = report .skipped diff --git a/crates/report/src/sarif.rs b/crates/report/src/sarif.rs index 0c8d7d5..a28ca62 100644 --- a/crates/report/src/sarif.rs +++ b/crates/report/src/sarif.rs @@ -5,8 +5,8 @@ use serde::Serialize; use codeint_model::{Metric, SourceSet}; use crate::{ - CloneGroupFinding, CloneLocation, ErodedFunctionFinding, ExternalMetricFinding, FlaggedLineRow, - ImportCycleFinding, Report, SourceSetSection, + BoundaryFindingRow, CloneGroupFinding, CloneLocation, ErodedFunctionFinding, + ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, Report, SourceSetSection, }; #[cfg(test)] @@ -141,6 +141,7 @@ pub(crate) struct ListedFindings<'findings> { pub(crate) clone_groups: &'findings [CloneGroupFinding], pub(crate) flagged_lines: &'findings [FlaggedLineRow], pub(crate) import_cycles: &'findings [ImportCycleFinding], + pub(crate) boundaries: &'findings [BoundaryFindingRow], pub(crate) external_metrics: Vec>, } @@ -159,6 +160,9 @@ impl SarifLog { findings: impl Iterator)>, ) -> SarifLog { let collected: Vec<(SourceSet, ListedFindings<'findings>)> = findings.collect(); + let has_boundaries = collected + .iter() + .any(|(_, listed)| !listed.boundaries.is_empty()); let mut external_rules: BTreeMap = BTreeMap::new(); for (_, listed) in &collected { for external in &listed.external_metrics { @@ -168,6 +172,11 @@ impl SarifLog { } } let mut rules: Vec = RULES.map(descriptor).into(); + let boundaries_rule_index = has_boundaries.then(|| { + let index = rules.len(); + rules.push(boundaries_descriptor()); + index + }); let mut external_rule_indices: BTreeMap = BTreeMap::new(); for (key, (name, description)) in external_rules { let index = rules.len(); @@ -202,7 +211,12 @@ impl SarifLog { results: collected .iter() .flat_map(|(source_set, listed)| { - results(*source_set, listed, &external_rule_indices) + results( + *source_set, + listed, + boundaries_rule_index, + &external_rule_indices, + ) }) .collect(), }], @@ -313,6 +327,22 @@ impl Location { } } +fn boundaries_descriptor() -> Rule { + Rule { + id: "boundaries".to_owned(), + name: "Boundaries".to_owned(), + short_description: Text::from( + "An import or file that breaks configured architectural boundaries", + ), + full_description: Text::from( + "Boundaries checks resolved runtime imports against configured architectural zones, directional allow or deny rules, public_files encapsulation, and optional strict_zones coverage.", + ), + help: Text::from( + "Import through an allowed zone or a target zone's public_files entry point, or assign the file to a configured zone.", + ), + } +} + impl<'findings> ListedFindings<'findings> { fn of_section(section: &'findings SourceSetSection) -> ListedFindings<'findings> { ListedFindings { @@ -320,6 +350,10 @@ impl<'findings> ListedFindings<'findings> { clone_groups: §ion.duplication.clone_groups.listed, flagged_lines: §ion.verbosity.findings.listed, import_cycles: §ion.import_cycles.findings.listed, + boundaries: section + .boundaries + .as_ref() + .map_or(&[], |boundaries| boundaries.findings.listed.as_slice()), external_metrics: section .external_metrics .iter() @@ -337,6 +371,7 @@ impl<'findings> ListedFindings<'findings> { fn results( source_set: SourceSet, listed: &ListedFindings<'_>, + boundaries_rule_index: Option, external_rule_indices: &BTreeMap, ) -> Vec { let eroded_functions = listed.eroded_functions.iter().map(|function| { @@ -370,6 +405,29 @@ fn results( .import_cycles .iter() .filter_map(|cycle| import_cycle_result(source_set, cycle)); + let boundaries = listed.boundaries.iter().map(|finding| { + let related_locations = finding + .target + .as_deref() + .map(|target| vec![Location::in_repository(target, 1, None).related(1)]) + .unwrap_or_default(); + SarifResult { + rule_id: "boundaries".to_owned(), + rule_index: boundaries_rule_index.unwrap_or_default(), + level: "note", + message: Text { + text: finding.message.clone(), + }, + locations: [Location::in_repository(&finding.importer, 1, None)], + related_locations, + partial_fingerprints: PartialFingerprints { + codeint_finding_id: finding.id.clone(), + }, + properties: ResultProperties { + source_set: source_set.key(), + }, + } + }); let external_findings = listed.external_metrics.iter().flat_map(|external| { let rule_index = external_rule_indices .get(external.key) @@ -400,6 +458,7 @@ fn results( .chain(clone_groups) .chain(flagged_lines) .chain(import_cycles) + .chain(boundaries) .chain(external_findings) .collect() } diff --git a/crates/report/src/sarif/tests.rs b/crates/report/src/sarif/tests.rs index f60971d..78d134d 100644 --- a/crates/report/src/sarif/tests.rs +++ b/crates/report/src/sarif/tests.rs @@ -70,6 +70,7 @@ fn every_sarif_result_carries_its_finding_id_in_partial_fingerprints() { clone_groups: &clones, flagged_lines: &flagged, import_cycles: &cycles, + boundaries: &[], external_metrics: Vec::new(), }; diff --git a/docs/reference.md b/docs/reference.md index a0bd3b8..2dac966 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -522,6 +522,7 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `budgets` | object | The Budgets of each Source set; see [Budgets](#budgets) | | `budgets.{source_set}` | object | The Budgets of this Source set; empty by default | | `budgets.{source_set}.{metric}` | number from 0 to 1 | The highest ratio of this Metric in this Source set | +| `budgets.{source_set}.boundaries` | number from 0 to 1 | The highest Boundaries ratio in this Source set | | `regression_limits` | object | How much each Metric may get worse in `codeint diff`; see [Regression limits](#regression-limits) | | `regression_limits.{metric}` | object | The Regression limit of this Metric in every Source set | | `regression_limits.{metric}.ratio_rise` | number from 0 to 1 | The highest ratio rise that passes | @@ -543,6 +544,15 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `plugin_limits` | object | Memory cap and time limit enforced on each WebAssembly Plugin; see [Plugins](#plugins) | | `plugin_limits.memory_mb` | integer from 1 to 4096 | Maximum linear memory in MiB that a WebAssembly Plugin may allocate; `64` by default | | `plugin_limits.timeout_ms` | integer from 1 to 300000 | Maximum wall-clock time in milliseconds for each WebAssembly Plugin call; `5000` by default | +| `boundaries` | object | Architectural import boundaries defining named zones, optional `public_files` entry points, directional `allow` or `deny` rules, and optional `strict_zones` mode | +| `boundaries.zones` | object | Map of zone name to zone definition (`patterns` globs and optional `public_files` globs) | +| `boundaries.rules` | list of objects | Directional import rules between architectural zones | +| `boundaries.rules[].from` | string | Source zone name, or `*` to match any zone without a specific rule | +| `boundaries.rules[].allow` | list of strings | Target zone names (or `*`) that the source zone is allowed to import; mutually exclusive with `deny` | +| `boundaries.rules[].deny` | list of strings | Target zone names (or `*`) that the source zone is forbidden to import; mutually exclusive with `allow` | +| `boundaries.rules[].reason` | string | Optional human-readable explanation shown in boundary Findings | +| `boundaries.strict_zones` | boolean | When `true`, report files in evaluated Source sets that do not match any configured zone; `false` by default | +| `boundaries.source_sets` | list of strings | Source sets evaluated by boundary rules; defaults to `["production"]` when omitted or empty | A key that the schema does not have, or a value of the wrong type, stops the run with exit code 2 and names the key. With this `codeint.json`: @@ -558,7 +568,7 @@ codeint check ``` ```text stderr -codeint: codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits +codeint: codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries Remove the key, or correct its spelling to one of the allowed keys. ``` @@ -761,6 +771,54 @@ Use `plugin_limits` to raise or adjust these limits: codeint check ``` +### Boundaries + +`boundaries` enforces directional import rules and `public_files` encapsulation over resolved runtime imports across every supported Language plugin. +When `boundaries` is omitted, boundary evaluation is completely inactive. +Each zone in `boundaries.zones` declares repository-relative `patterns` globs and optional `public_files` globs naming the only files external zones may import. +When a file matches patterns in multiple zones, the most specific pattern (most literal characters, then longest pattern, then zone name alphabetically) wins. +Each rule in `boundaries.rules` sets `from` (a zone name or `*`), either `allow` or `deny` (mutually exclusive), and an optional `reason`. +By default, `boundaries` evaluates the `production` Source set only; set `source_sets` to evaluate additional Source sets, and set `strict_zones` to `true` to report files matching no zone. + +```json codeint.json +{ + "budgets": { + "production": { + "boundaries": 0 + } + }, + "boundaries": { + "zones": { + "app": { + "patterns": ["src/**"], + "public_files": ["src/**"] + }, + "infra": { + "patterns": ["infra/**"] + } + }, + "rules": [ + { + "from": "app", + "allow": ["app"], + "reason": "App layer stays independent of infrastructure" + }, + { + "from": "infra", + "deny": ["app"], + "reason": "Infrastructure must not import application code" + } + ], + "strict_zones": false, + "source_sets": ["production"] + } +} +``` + +```sh exit=0 +codeint check +``` + ## Result cache codeint caches the measurement of each commit it reads from Git objects, so a second `codeint diff` against the same base reads it back instead of measuring the commit again. diff --git a/schema/codeint.schema.json b/schema/codeint.schema.json index 7777aaa..1fbda44 100644 --- a/schema/codeint.schema.json +++ b/schema/codeint.schema.json @@ -55,6 +55,10 @@ "plugin_limits": { "$ref": "#/$defs/PluginLimitsFile", "description": "Memory cap and time limit enforced on each WebAssembly Plugin. Defaults are 64 MiB and 5000 ms." + }, + "boundaries": { + "$ref": "#/$defs/BoundariesFile", + "description": "Architectural import boundaries defining named zones, optional public_files entry points, directional allow or deny rules, and optional strict_zones mode." } }, "title": "codeint.json", @@ -155,6 +159,13 @@ "description": "The highest Import cycles ratio, from 0 to 1.", "minimum": 0, "maximum": 1 + }, + "boundaries": { + "type": "number", + "format": "double", + "description": "The highest Boundaries ratio, from 0 to 1.", + "minimum": 0, + "maximum": 1 } }, "additionalProperties": { @@ -348,6 +359,101 @@ "maximum": 300000 } } + }, + "BoundariesFile": { + "type": "object", + "additionalProperties": false, + "properties": { + "zones": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/BoundaryZoneFile" + }, + "description": "Named architectural zones, each defined by repository-relative path globs and optional public_files globs.", + "default": {} + }, + "rules": { + "type": "array", + "items": { + "$ref": "#/$defs/BoundaryRuleFile" + }, + "description": "Directional allow or deny import rules between architectural zones." + }, + "strict_zones": { + "type": "boolean", + "description": "When true, report files in evaluated Source sets that do not match any configured zone." + }, + "source_sets": { + "type": "array", + "items": { + "$ref": "#/$defs/BoundarySourceSet" + }, + "description": "Source sets evaluated by boundary rules; defaults to [\"production\"] when omitted or empty." + } + } + }, + "BoundaryZoneFile": { + "type": "object", + "additionalProperties": false, + "properties": { + "patterns": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Repository-relative path globs that assign files to this architectural zone." + }, + "public_files": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Optional repository-relative path globs naming the only files in this zone that other zones may import." + } + }, + "required": [ + "patterns" + ] + }, + "BoundaryRuleFile": { + "type": "object", + "additionalProperties": false, + "properties": { + "from": { + "type": "string", + "description": "Source zone name, or \"*\" to match any zone without a specific rule." + }, + "allow": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Target zone names (or \"*\") that the source zone is allowed to import. Mutually exclusive with deny." + }, + "deny": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Target zone names (or \"*\") that the source zone is forbidden to import. Mutually exclusive with allow." + }, + "reason": { + "type": "string", + "description": "Optional human-readable explanation shown in boundary Findings." + } + }, + "required": [ + "from" + ] + }, + "BoundarySourceSet": { + "type": "string", + "enum": [ + "production", + "test", + "generated", + "vendored" + ] } } } From f5b4b9ae275a24050539bd2bb2b0548cc69a1508 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 08:22:19 +0800 Subject: [PATCH 2/4] feat(config): add boundary presets, budgets, and diff regressions Add built-in layered and hexagonal presets under boundaries.preset with zone and rule override semantics, expose per-Source-set boundary regression limits (defaulting to any_new_finding), and wire boundary Findings into CommitMeasurement and DiffReport across JSON, TOON, SARIF, and Markdown outputs. Closes #177 --- crates/cli/src/commit_measurement.rs | 3 +- crates/cli/tests/boundaries.rs | 381 +++++++++++++++++++++++++ crates/config/src/boundaries.rs | 195 ++++++++++++- crates/config/src/codeint_json.rs | 11 + crates/config/src/lib.rs | 4 +- crates/config/src/regression_limits.rs | 2 +- crates/report/src/diff.rs | 36 ++- crates/report/src/diff/markdown.rs | 19 +- crates/report/src/markdown.rs | 4 +- crates/report/src/measurement.rs | 39 ++- docs/reference.md | 22 ++ schema/codeint.schema.json | 19 ++ 12 files changed, 716 insertions(+), 19 deletions(-) diff --git a/crates/cli/src/commit_measurement.rs b/crates/cli/src/commit_measurement.rs index 00ef066..abf6308 100644 --- a/crates/cli/src/commit_measurement.rs +++ b/crates/cli/src/commit_measurement.rs @@ -95,8 +95,9 @@ pub(crate) fn measure_all_languages( let named = plugins.as_named(); let metric_plugins = plugins.metric_plugins(); let languages = measure_with(tree, &named, configuration)?; - Ok(CommitMeasurement::of_with_metrics( + Ok(CommitMeasurement::of_with_metrics_and_boundaries( CodeModel::merge(languages.into_iter().map(|language| language.model)), &metric_plugins, + configuration.boundaries.as_ref(), )?) } diff --git a/crates/cli/tests/boundaries.rs b/crates/cli/tests/boundaries.rs index 8b0896a..81a685c 100644 --- a/crates/cli/tests/boundaries.rs +++ b/crates/cli/tests/boundaries.rs @@ -417,3 +417,384 @@ fn check_enforces_boundary_budget_overlap_precedence_and_optional_test_source_se assert_eq!(test_findings[0]["source_zone"], "core"); assert_eq!(test_findings[0]["target_zone"], "domain"); } + +const GIT_ENV: [(&str, &str); 6] = [ + ("GIT_CONFIG_GLOBAL", "/dev/null"), + ("GIT_CONFIG_NOSYSTEM", "1"), + ("GIT_AUTHOR_NAME", "Fixture"), + ("GIT_AUTHOR_EMAIL", "fixture@example.invalid"), + ("GIT_COMMITTER_NAME", "Fixture"), + ("GIT_COMMITTER_EMAIL", "fixture@example.invalid"), +]; + +impl BoundaryFixture { + fn write(&self, rel: &str, body: &str) { + let dst = self.0.path().join(rel); + if let Some(parent) = dst.parent() { + fs::create_dir_all(parent).expect("mkdir"); + } + fs::write(dst, body).expect("write"); + } + + fn git(&self, args: &[&str]) { + let mut command = Command::new("git"); + command.args(args).current_dir(self.0.path()); + for (key, value) in GIT_ENV { + command.env(key, value); + } + let output = command.output().expect("run git"); + assert!( + output.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + + fn commit(&self, message: &str) { + self.git(&["add", "--all"]); + self.git(&["commit", "--quiet", "--message", message]); + } + + fn run_with_cache(&self, cache_dir: &std::path::Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .args(args) + .env("CODEINT_CACHE_DIR", cache_dir) + .current_dir(self.0.path()) + .output() + .expect("run codeint") + } +} + +#[test] +fn check_supports_layered_and_hexagonal_presets_with_user_overrides() { + let layered = BoundaryFixture::init(&[ + ( + "codeint.json", + r#"{ + "boundaries": { + "preset": "layered" + } +} +"#, + ), + ("src/infrastructure/db.ts", "export const db = 1;\n"), + ( + "src/domain/order.ts", + "import { db } from '../infrastructure/db';\nexport const order = db;\n", + ), + ( + "src/application/service.ts", + "import { order } from '../domain/order';\nexport const service = order;\n", + ), + ( + "src/presentation/view.ts", + "import { db } from '../infrastructure/db';\nexport const view = db;\n", + ), + ]); + + let layered_json = layered.check_json(0); + let layered_findings = layered_json["source_sets"]["production"]["boundaries"]["findings"] + .as_array() + .expect("layered findings"); + assert_eq!(layered_findings.len(), 2, "got: {layered_findings:?}"); + assert!(layered_findings.iter().any(|f| { + f["importer"] == "src/domain/order.ts" + && f["source_zone"] == "domain" + && f["target_zone"] == "infrastructure" + })); + assert!(layered_findings.iter().any(|f| { + f["importer"] == "src/presentation/view.ts" + && f["source_zone"] == "presentation" + && f["target_zone"] == "infrastructure" + })); + + let layered_override = BoundaryFixture::init(&[ + ( + "codeint.json", + r#"{ + "boundaries": { + "preset": "layered", + "zones": { + "domain": { + "patterns": ["src/business/**"], + "public_files": ["src/business/index.ts"] + }, + "shared": { + "patterns": ["src/shared/**"] + } + }, + "rules": [ + { + "from": "domain", + "allow": ["shared"], + "reason": "Domain may import shared helpers only" + } + ] + } +} +"#, + ), + ("src/shared/id.ts", "export const id = 1;\n"), + ("src/infrastructure/db.ts", "export const db = 2;\n"), + ( + "src/business/internal.ts", + "import { id } from '../shared/id';\nexport const secret = id;\n", + ), + ( + "src/business/index.ts", + "import { secret } from './internal';\nexport const api = secret;\n", + ), + ( + "src/business/bad.ts", + "import { db } from '../infrastructure/db';\nexport const bad = db;\n", + ), + ( + "src/application/deep.ts", + "import { secret } from '../business/internal';\nexport const deep = secret;\n", + ), + ]); + + let override_json = layered_override.check_json(0); + let override_findings = override_json["source_sets"]["production"]["boundaries"]["findings"] + .as_array() + .expect("override findings"); + assert_eq!(override_findings.len(), 2, "got: {override_findings:?}"); + assert!(override_findings.iter().any(|f| { + f["importer"] == "src/business/bad.ts" + && f["kind"] == "zone_rule" + && f["reason"] == "Domain may import shared helpers only" + })); + assert!(override_findings.iter().any(|f| { + f["importer"] == "src/application/deep.ts" + && f["kind"] == "public_files" + && f["target"] == "src/business/internal.ts" + })); + + let hexagonal = BoundaryFixture::init(&[ + ( + "codeint.json", + r#"{ + "boundaries": { + "preset": "hexagonal" + } +} +"#, + ), + ("src/domain/model.ts", "export const model = 1;\n"), + ( + "src/ports/repo.ts", + "import { model } from '../domain/model';\nexport const repo = model;\n", + ), + ( + "src/adapters/http.ts", + "import { repo } from '../ports/repo';\nexport const http = repo;\n", + ), + ( + "src/application/usecase.ts", + "import { repo } from '../ports/repo';\nimport { http } from '../adapters/http';\nexport const run = repo + http;\n", + ), + ]); + + let hex_json = hexagonal.check_json(0); + let hex_findings = hex_json["source_sets"]["production"]["boundaries"]["findings"] + .as_array() + .expect("hexagonal findings"); + assert_eq!(hex_findings.len(), 1, "got: {hex_findings:?}"); + assert_eq!(hex_findings[0]["importer"], "src/application/usecase.ts"); + assert_eq!(hex_findings[0]["target"], "src/adapters/http.ts"); + assert_eq!(hex_findings[0]["source_zone"], "application"); + assert_eq!(hex_findings[0]["target_zone"], "adapters"); +} + +#[test] +fn check_enforces_per_source_set_boundary_budgets() { + let fixture = BoundaryFixture::init(&[ + ( + "codeint.json", + r#"{ + "budgets": { + "production": { + "boundaries": 1 + }, + "test": { + "boundaries": 0 + } + }, + "boundaries": { + "preset": "layered", + "source_sets": ["production", "test"] + } +} +"#, + ), + ("src/infrastructure/db.ts", "export const db = 1;\n"), + ( + "src/domain/order.ts", + "import { db } from '../infrastructure/db';\nexport const order = db;\n", + ), + ( + "src/domain/order.test.ts", + "import { db } from '../infrastructure/db';\nexport const tested = db;\n", + ), + ]); + + let json = fixture.check_json(1); + let over_budget = json["over_budget"].as_array().expect("over_budget"); + assert_eq!(over_budget.len(), 1, "got: {over_budget:?}"); + assert_eq!(over_budget[0]["source_set"], "test"); + assert_eq!(over_budget[0]["metric"], "boundaries"); + assert_eq!(over_budget[0]["budget"], 0.0); +} + +#[test] +fn diff_classifies_boundary_findings_and_gates_new_regressions_without_failing_on_preexisting() { + let cache = tempfile::tempdir().expect("cache tempdir"); + let fixture = BoundaryFixture::init(&[ + ( + "codeint.json", + r#"{ + "boundaries": { + "preset": "layered" + } +} +"#, + ), + ("src/infrastructure/db.ts", "export const db = 1;\n"), + ( + "src/domain/legacy.ts", + "import { db } from '../infrastructure/db';\nexport const legacy = db;\n", + ), + ( + "src/application/clean.ts", + "import { legacy } from '../domain/legacy';\nexport const clean = legacy;\n", + ), + ]); + fixture.commit("base with legacy boundary violation"); + + fixture.write( + "src/domain/legacy.ts", + "\n\nimport { db } from '../infrastructure/db';\nexport const legacy = db + 1;\n", + ); + let no_regression = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "json"]); + assert_eq!( + no_regression.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&no_regression.stderr) + ); + let no_reg_json: Value = serde_json::from_slice(&no_regression.stdout).expect("valid JSON"); + let prod_diff = &no_reg_json["source_sets"]["production"]["boundaries"]; + assert_eq!(prod_diff["new"].as_array().expect("new").len(), 0); + assert_eq!(prod_diff["resolved"].as_array().expect("resolved").len(), 0); + assert_eq!(prod_diff["unchanged"], 1); + assert!(no_reg_json.get("regressions").is_none()); + + fixture.write( + "src/domain/new_feature.ts", + "import { db } from '../infrastructure/db';\nexport const feature = db;\n", + ); + let with_regression = + fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "json"]); + assert_eq!( + with_regression.status.code(), + Some(1), + "stderr: {}", + String::from_utf8_lossy(&with_regression.stderr) + ); + let reg_json: Value = serde_json::from_slice(&with_regression.stdout).expect("valid JSON"); + let prod_reg_diff = ®_json["source_sets"]["production"]["boundaries"]; + let new_findings = prod_reg_diff["new"].as_array().expect("new findings"); + assert_eq!(new_findings.len(), 1, "got: {new_findings:?}"); + assert_eq!(new_findings[0]["importer"], "src/domain/new_feature.ts"); + assert_eq!(new_findings[0]["target"], "src/infrastructure/db.ts"); + assert_eq!(prod_reg_diff["unchanged"], 1); + let regressions = reg_json["regressions"].as_array().expect("regressions"); + assert!( + regressions + .iter() + .any(|r| r["source_set"] == "production" && r["metric"] == "boundaries"), + "got: {regressions:?}" + ); + + let sarif_out = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "sarif"]); + assert_eq!(sarif_out.status.code(), Some(1)); + let sarif: Value = serde_json::from_slice(&sarif_out.stdout).expect("valid SARIF"); + let sarif_results: Vec<&Value> = sarif["runs"][0]["results"] + .as_array() + .expect("results") + .iter() + .filter(|r| r["ruleId"] == "boundaries") + .collect(); + assert_eq!(sarif_results.len(), 1); + assert_eq!( + sarif_results[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"], + "src/domain/new_feature.ts" + ); + + let md_out = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "markdown"]); + assert_eq!(md_out.status.code(), Some(1)); + let md_text = String::from_utf8(md_out.stdout).expect("utf8"); + assert!(md_text.contains("| Production | Boundaries |")); + assert!(md_text.contains("### New Boundaries Findings")); + assert!(md_text.contains("`src/domain/new_feature.ts`")); + + let toon_out = fixture.run_with_cache(cache.path(), &["diff", "main"]); + assert_eq!(toon_out.status.code(), Some(1)); + let toon_text = String::from_utf8(toon_out.stdout).expect("utf8"); + assert!(toon_text.contains("boundaries:")); + assert!(toon_text.contains("src/domain/new_feature.ts")); + + fixture.write( + "codeint.json", + r#"{ + "boundaries": { + "preset": "layered" + }, + "regression_limits": { + "production": { + "boundaries": { + "ratio_rise": 1, + "new_findings": "never" + } + } + } +} +"#, + ); + let relaxed = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "json"]); + assert_eq!( + relaxed.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&relaxed.stderr) + ); + + fixture.write( + "codeint.json", + r#"{ + "boundaries": { + "preset": "layered" + } +} +"#, + ); + fixture.write("src/domain/legacy.ts", "export const legacy = 1;\n"); + fixture.write("src/domain/new_feature.ts", "export const feature = 2;\n"); + let resolved_out = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "json"]); + assert_eq!(resolved_out.status.code(), Some(0)); + let resolved_json: Value = serde_json::from_slice(&resolved_out.stdout).expect("valid JSON"); + let resolved_diff = &resolved_json["source_sets"]["production"]["boundaries"]; + assert_eq!(resolved_diff["new"].as_array().expect("new").len(), 0); + assert_eq!( + resolved_diff["resolved"] + .as_array() + .expect("resolved") + .len(), + 1 + ); + assert_eq!( + resolved_diff["resolved"][0]["importer"], + "src/domain/legacy.ts" + ); + assert_eq!(resolved_diff["unchanged"], 0); +} diff --git a/crates/config/src/boundaries.rs b/crates/config/src/boundaries.rs index b176be3..76a6f7b 100644 --- a/crates/config/src/boundaries.rs +++ b/crates/config/src/boundaries.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use codeint_model::{RepoPath, SourceSet}; use globset::{GlobBuilder, GlobMatcher, GlobSet}; @@ -9,6 +9,13 @@ use crate::codeint_json::{ConfigurationFileError, KeyPath, KeySegment, glob_set} const WILDCARD_ZONE: &str = "*"; +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum BoundaryPreset { + Layered, + Hexagonal, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BoundaryDirective { Allow, @@ -47,6 +54,12 @@ impl From for SourceSet { #[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] #[serde(deny_unknown_fields)] pub(crate) struct BoundariesFile { + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars( + with = "BoundaryPreset", + description = "Optional built-in architecture preset (\"layered\" or \"hexagonal\") providing default zones and rules that can be overridden or extended by zones and rules." + )] + preset: Option, #[serde(default)] #[schemars( description = "Named architectural zones, each defined by repository-relative path globs and optional public_files globs." @@ -145,10 +158,11 @@ pub struct Boundaries { impl Boundaries { pub(crate) fn from_file(file: BoundariesFile) -> Result { + let (merged_zones, merged_rules) = merge_preset(file.preset, file.zones, file.rules); let boundaries_key = KeyPath::default().child(KeySegment::Key("boundaries".to_owned())); let zones_key = boundaries_key.child(KeySegment::Key("zones".to_owned())); let mut zones = BTreeMap::new(); - for (name, zone_file) in file.zones { + for (name, zone_file) in merged_zones { let zone_key = zones_key.child(KeySegment::Key(name.clone())); if name.trim().is_empty() || name == WILDCARD_ZONE { return Err(ConfigurationFileError::InvalidBoundaryZoneName { @@ -181,10 +195,10 @@ impl Boundaries { let known_zones: Vec = zones.keys().cloned().collect(); let rules_key = boundaries_key.child(KeySegment::Key("rules".to_owned())); - let mut rules = Vec::with_capacity(file.rules.len()); + let mut rules = Vec::with_capacity(merged_rules.len()); let mut directive_by_from: BTreeMap = BTreeMap::new(); - for (index, rule) in file.rules.into_iter().enumerate() { + for (index, rule) in merged_rules.into_iter().enumerate() { let rule_key = rules_key.child(KeySegment::Index(index)); if rule.from != WILDCARD_ZONE && !zones.contains_key(&rule.from) { return Err(ConfigurationFileError::UnknownBoundaryZone { @@ -385,3 +399,176 @@ fn literal_char_count(pattern: &str) -> usize { .filter(|character| !matches!(character, '*' | '?' | '[' | ']' | '{' | '}')) .count() } + +fn merge_preset( + preset: Option, + user_zones: BTreeMap, + user_rules: Vec, +) -> (BTreeMap, Vec) { + let Some(preset) = preset else { + return (user_zones, user_rules); + }; + let (mut zones, preset_rules) = preset_defaults(preset); + for (name, zone) in user_zones { + zones.insert(name, zone); + } + let overridden_from: BTreeSet = + user_rules.iter().map(|rule| rule.from.clone()).collect(); + let mut rules: Vec = preset_rules + .into_iter() + .filter(|rule| !overridden_from.contains(&rule.from)) + .collect(); + rules.extend(user_rules); + (zones, rules) +} + +fn preset_defaults( + preset: BoundaryPreset, +) -> (BTreeMap, Vec) { + match preset { + BoundaryPreset::Layered => layered_preset(), + BoundaryPreset::Hexagonal => hexagonal_preset(), + } +} + +fn zone_patterns(patterns: &[&str]) -> BoundaryZoneFile { + BoundaryZoneFile { + patterns: patterns + .iter() + .map(|pattern| (*pattern).to_owned()) + .collect(), + public_files: Vec::new(), + } +} + +fn allow_rule(from: &str, allow: &[&str], reason: &str) -> BoundaryRuleFile { + BoundaryRuleFile { + from: from.to_owned(), + allow: Some(allow.iter().map(|target| (*target).to_owned()).collect()), + deny: None, + reason: Some(reason.to_owned()), + } +} + +fn layered_preset() -> (BTreeMap, Vec) { + let mut zones = BTreeMap::new(); + zones.insert( + "presentation".to_owned(), + zone_patterns(&[ + "**/presentation/**", + "**/ui/**", + "**/web/**", + "**/api/**", + "**/controllers/**", + "**/routes/**", + ]), + ); + zones.insert( + "application".to_owned(), + zone_patterns(&[ + "**/application/**", + "**/app/**", + "**/services/**", + "**/usecases/**", + "**/use-cases/**", + "**/use_cases/**", + ]), + ); + zones.insert( + "domain".to_owned(), + zone_patterns(&[ + "**/domain/**", + "**/core/**", + "**/entities/**", + "**/models/**", + ]), + ); + zones.insert( + "infrastructure".to_owned(), + zone_patterns(&[ + "**/infrastructure/**", + "**/infra/**", + "**/adapters/**", + "**/repositories/**", + "**/db/**", + "**/persistence/**", + ]), + ); + let rules = vec![ + allow_rule( + "domain", + &["domain"], + "Layered preset: domain layer must not depend on outer layers", + ), + allow_rule( + "application", + &["domain"], + "Layered preset: application layer may only depend on domain", + ), + allow_rule( + "infrastructure", + &["domain", "application"], + "Layered preset: infrastructure layer may only depend on domain and application", + ), + allow_rule( + "presentation", + &["application", "domain"], + "Layered preset: presentation layer must not depend directly on infrastructure", + ), + ]; + (zones, rules) +} + +fn hexagonal_preset() -> (BTreeMap, Vec) { + let mut zones = BTreeMap::new(); + zones.insert( + "domain".to_owned(), + zone_patterns(&["**/domain/**", "**/core/**", "**/entities/**"]), + ); + zones.insert("ports".to_owned(), zone_patterns(&["**/ports/**"])); + zones.insert( + "application".to_owned(), + zone_patterns(&[ + "**/application/**", + "**/app/**", + "**/usecases/**", + "**/use-cases/**", + "**/use_cases/**", + ]), + ); + zones.insert( + "adapters".to_owned(), + zone_patterns(&[ + "**/adapters/**", + "**/infrastructure/**", + "**/infra/**", + "**/driving/**", + "**/driven/**", + "**/inbound/**", + "**/outbound/**", + ]), + ); + let rules = vec![ + allow_rule( + "domain", + &["domain"], + "Hexagonal preset: domain must stay independent of ports, application, and adapters", + ), + allow_rule( + "ports", + &["domain"], + "Hexagonal preset: ports may only depend on domain", + ), + allow_rule( + "application", + &["domain", "ports"], + "Hexagonal preset: application may only depend on domain and ports, not adapters", + ), + allow_rule( + "adapters", + &["domain", "ports", "application"], + "Hexagonal preset: adapters may depend on domain, ports, and application", + ), + ]; + (zones, rules) +} diff --git a/crates/config/src/codeint_json.rs b/crates/config/src/codeint_json.rs index 4e36d8e..d54e891 100644 --- a/crates/config/src/codeint_json.rs +++ b/crates/config/src/codeint_json.rs @@ -553,6 +553,9 @@ struct RegressionLimitsFile { #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] #[schemars(description = "The Regression limit of Import cycles in every Source set.")] import_cycles: RegressionLimitSetting, + #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] + #[schemars(description = "The Regression limit of Boundaries in every Source set.")] + boundaries: RegressionLimitSetting, #[serde(default, skip_serializing_if = "MetricRegressionLimits::is_unset")] #[schemars(description = "The Regression limits of the Production Source set.")] production: MetricRegressionLimits, @@ -583,6 +586,9 @@ struct MetricRegressionLimits { #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] #[schemars(description = "The Regression limit of Import cycles in this Source set.")] import_cycles: RegressionLimitSetting, + #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] + #[schemars(description = "The Regression limit of Boundaries in this Source set.")] + boundaries: RegressionLimitSetting, #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")] external: BTreeMap, } @@ -594,6 +600,7 @@ impl MetricRegressionLimits { &self.duplication, &self.verbosity, &self.import_cycles, + &self.boundaries, ] .into_iter() .chain(self.external.values()) @@ -606,6 +613,7 @@ impl MetricRegressionLimits { duplication, verbosity, import_cycles, + boundaries, external, } = self; [ @@ -613,6 +621,7 @@ impl MetricRegressionLimits { (Metric::Duplication.key().to_owned(), duplication), (Metric::Verbosity.key().to_owned(), verbosity), (Metric::ImportCycles.key().to_owned(), import_cycles), + ("boundaries".to_owned(), boundaries), ] .into_iter() .chain(external) @@ -834,6 +843,7 @@ fn regression_limits(file: RegressionLimitsFile) -> RegressionLimits { duplication, verbosity, import_cycles, + boundaries, production, test, generated, @@ -845,6 +855,7 @@ fn regression_limits(file: RegressionLimitsFile) -> RegressionLimits { duplication, verbosity, import_cycles, + boundaries, external, } .by_metric() diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 11102d1..24149ab 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -10,7 +10,9 @@ mod codeint_json; mod regression_limits; mod result_cache_folder; -pub use boundaries::{Boundaries, BoundaryDirective, BoundaryRuleDecision, BoundarySourceSet}; +pub use boundaries::{ + Boundaries, BoundaryDirective, BoundaryPreset, BoundaryRuleDecision, BoundarySourceSet, +}; pub use calendar_day::{CalendarDay, CalendarDayError}; pub use codeint_json::{ Budget, Budgets, Configuration, ConfigurationFileError, DetectedLanguage, JsonType, KeyPath, diff --git a/crates/config/src/regression_limits.rs b/crates/config/src/regression_limits.rs index 0a5666e..5d9cbdf 100644 --- a/crates/config/src/regression_limits.rs +++ b/crates/config/src/regression_limits.rs @@ -68,7 +68,7 @@ impl RegressionLimit { }; fn default_for_key(metric_key: &str) -> RegressionLimit { - if metric_key == Metric::ImportCycles.key() { + if metric_key == Metric::ImportCycles.key() || metric_key == "boundaries" { RegressionLimit::DEFAULT_FOR_IMPORT_CYCLES } else { RegressionLimit::DEFAULT diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index fd4e026..cf82cf1 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -11,8 +11,8 @@ use serde::{Serialize, Serializer}; use crate::measurement::{CommitMeasurement, MetricMeasurement, SourceSetMeasurement}; use crate::sarif::{ListedExternalMetric, ListedFindings, SarifLog}; use crate::{ - BudgetFailure, CloneGroupFinding, Decimal, ErodedFunctionFinding, ExternalMetricFinding, - Findings, FlaggedLineRow, ImportCycleFinding, ReportError, + BoundaryFindingRow, BudgetFailure, CloneGroupFinding, Decimal, ErodedFunctionFinding, + ExternalMetricFinding, Findings, FlaggedLineRow, ImportCycleFinding, ReportError, }; mod markdown; @@ -104,6 +104,8 @@ struct SourceSetChanges { duplication: MetricChanges, verbosity: MetricChanges, import_cycles: MetricChanges, + #[serde(skip_serializing_if = "Option::is_none")] + boundaries: Option>, #[serde(flatten)] external_metrics: BTreeMap, } @@ -199,7 +201,10 @@ impl DiffReport { clone_groups: &changes.duplication.new.listed, flagged_lines: &changes.verbosity.new.listed, import_cycles: &changes.import_cycles.new.listed, - boundaries: &[], + boundaries: changes + .boundaries + .as_ref() + .map_or(&[], |boundaries| boundaries.new.listed.as_slice()), external_metrics: changes .external_metrics .iter() @@ -285,6 +290,12 @@ fn over_budget(source_sets: &SourceSetChangesSections, budgets: &Budgets) -> Vec ), ] .into_iter() + .chain( + changes + .boundaries + .iter() + .map(move |boundaries| (source_set, "boundaries", boundaries.head_ratio.0)), + ) .chain( changes.external_metrics.iter().map(move |(key, metric)| { (source_set, key.as_str(), metric.changes.head_ratio.0) @@ -319,6 +330,9 @@ impl SourceSetChanges { .into_iter() .flatten() .collect(); + if let Some(boundaries) = &self.boundaries { + found.extend(boundaries.regressions(source_set, "boundaries", limits)); + } for (key, external) in &self.external_metrics { found.extend(external.changes.regressions(source_set, key, limits)); } @@ -444,6 +458,7 @@ fn numerator_key(metric_key: &str) -> &'static str { "duplication" => "clone_lines", "verbosity" => "verbose_lines", "import_cycles" => "modules_in_import_cycles", + "boundaries" => "boundary_findings", _ => "numerator", } } @@ -509,11 +524,20 @@ fn source_set_changes( }, ); } + let boundaries = match (base.boundaries, head.boundaries) { + (None, None) => None, + (base_boundaries, head_boundaries) => Some(classify( + base_boundaries.unwrap_or_default(), + head_boundaries.unwrap_or_default(), + shown, + )), + }; SourceSetChanges { erosion: classify(base.erosion, head.erosion, shown), duplication: classify(base.duplication, head.duplication, shown), verbosity: classify(base.verbosity, head.verbosity, shown), import_cycles: classify(base.import_cycles, head.import_cycles, shown), + boundaries, external_metrics, } } @@ -576,6 +600,12 @@ impl Identified for ExternalMetricFinding { } } +impl Identified for BoundaryFindingRow { + fn id(&self) -> &str { + &self.id + } +} + fn source_set_name(source_set: SourceSet) -> &'static str { match source_set { SourceSet::Production => "Production", diff --git a/crates/report/src/diff/markdown.rs b/crates/report/src/diff/markdown.rs index f875959..4d75479 100644 --- a/crates/report/src/diff/markdown.rs +++ b/crates/report/src/diff/markdown.rs @@ -1,10 +1,10 @@ use super::{DiffReport, HeadEntry, MetricChanges, Regression, SourceSetChanges}; use crate::Findings; use crate::markdown::{ - CLONE_GROUP, ERODED_FUNCTION, ERODED_FUNCTION_COLUMNS, EXTERNAL_FINDING_COLUMNS, FINDING, - FLAGGED_LINE, FLAGGED_LINE_COLUMNS, IMPORT_CYCLE, Noun, clone_group_item, code, - eroded_function_row, external_finding_row, flagged_line_row, import_cycle_item, list, - push_findings, sentence_item, table, + BOUNDARY_FINDING_COLUMNS, CLONE_GROUP, ERODED_FUNCTION, ERODED_FUNCTION_COLUMNS, + EXTERNAL_FINDING_COLUMNS, FINDING, FLAGGED_LINE, FLAGGED_LINE_COLUMNS, IMPORT_CYCLE, Noun, + boundary_finding_row, clone_group_item, code, eroded_function_row, external_finding_row, + flagged_line_row, import_cycle_item, list, push_findings, sentence_item, table, }; const TITLE: &str = "# codeint diff"; @@ -72,6 +72,9 @@ fn metric_rows(source_set: &str, changes: &SourceSetChanges) -> Vec> metric_row(source_set, "Verbosity", &changes.verbosity), metric_row(source_set, "Import cycles", &changes.import_cycles), ]; + if let Some(boundaries) = &changes.boundaries { + rows.push(metric_row(source_set, "Boundaries", boundaries)); + } for external in changes.external_metrics.values() { rows.push(metric_row(source_set, &external.name, &external.changes)); } @@ -134,6 +137,14 @@ fn findings_blocks(changes: &SourceSetChanges) -> Vec { &IMPORT_CYCLE, |listed| list(listed.iter().map(import_cycle_item)), ); + if let Some(boundaries) = &changes.boundaries { + push_changes(&mut blocks, "Boundaries", boundaries, &FINDING, |listed| { + table( + &BOUNDARY_FINDING_COLUMNS, + listed.iter().map(boundary_finding_row).collect(), + ) + }); + } for external in changes.external_metrics.values() { push_changes( &mut blocks, diff --git a/crates/report/src/markdown.rs b/crates/report/src/markdown.rs index c2d0fe0..5b45835 100644 --- a/crates/report/src/markdown.rs +++ b/crates/report/src/markdown.rs @@ -34,7 +34,7 @@ const PACKAGE_COLUMNS: [&str; 8] = [ ]; pub(crate) const FLAGGED_LINE_COLUMNS: [&str; 2] = ["Flagged line", "Rule"]; pub(crate) const EXTERNAL_FINDING_COLUMNS: [&str; 2] = ["Location", "Message"]; -const BOUNDARY_FINDING_COLUMNS: [&str; 6] = [ +pub(crate) const BOUNDARY_FINDING_COLUMNS: [&str; 6] = [ "Importer", "Target", "Source zone", @@ -513,7 +513,7 @@ fn unresolved_import_row(row: &UnresolvedImportRow) -> Vec { ] } -fn boundary_finding_row(row: &BoundaryFindingRow) -> Vec { +pub(crate) fn boundary_finding_row(row: &BoundaryFindingRow) -> Vec { vec![ code(&row.importer), row.target.as_deref().map_or_else(|| "-".to_owned(), code), diff --git a/crates/report/src/measurement.rs b/crates/report/src/measurement.rs index bd27ae5..d5db469 100644 --- a/crates/report/src/measurement.rs +++ b/crates/report/src/measurement.rs @@ -1,11 +1,13 @@ use std::collections::BTreeMap; +use codeint_config::Boundaries as BoundariesConfig; +use codeint_metrics::Boundaries; use codeint_model::{CodeModel, MetricPlugin, MetricPluginError, SourceSet}; use serde::{Deserialize, Serialize}; use crate::{ - CloneGroupFinding, ErodedFunctionFinding, ExternalMetricFinding, FlaggedLineRow, - ImportCycleFinding, Measured, + BoundaryFindingRow, CloneGroupFinding, ConfigBoundaryPolicy, ErodedFunctionFinding, + ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, Measured, }; #[derive(Debug, Serialize, Deserialize)] @@ -23,6 +25,8 @@ pub(crate) struct SourceSetMeasurement { pub(crate) duplication: MetricMeasurement, pub(crate) verbosity: MetricMeasurement, pub(crate) import_cycles: MetricMeasurement, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) boundaries: Option>, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(crate) external_metrics: BTreeMap, } @@ -59,21 +63,36 @@ impl CommitMeasurement { pub fn of_with_metrics( model: CodeModel, metric_plugins: &[&dyn MetricPlugin], + ) -> Result { + CommitMeasurement::of_with_metrics_and_boundaries(model, metric_plugins, None) + } + + pub fn of_with_metrics_and_boundaries( + model: CodeModel, + metric_plugins: &[&dyn MetricPlugin], + boundaries: Option<&BoundariesConfig>, ) -> Result { let source_sets = model.into_source_sets(); Ok(CommitMeasurement { production: SourceSetMeasurement::of( source_sets.get(SourceSet::Production), metric_plugins, + boundaries.filter(|config| config.applies_to_source_set(SourceSet::Production)), + )?, + test: SourceSetMeasurement::of( + source_sets.get(SourceSet::Test), + metric_plugins, + boundaries.filter(|config| config.applies_to_source_set(SourceSet::Test)), )?, - test: SourceSetMeasurement::of(source_sets.get(SourceSet::Test), metric_plugins)?, generated: SourceSetMeasurement::of( source_sets.get(SourceSet::Generated), metric_plugins, + boundaries.filter(|config| config.applies_to_source_set(SourceSet::Generated)), )?, vendored: SourceSetMeasurement::of( source_sets.get(SourceSet::Vendored), metric_plugins, + boundaries.filter(|config| config.applies_to_source_set(SourceSet::Vendored)), )?, }) } @@ -92,8 +111,21 @@ impl SourceSetMeasurement { fn of( model: &CodeModel, metric_plugins: &[&dyn MetricPlugin], + boundaries: Option<&BoundariesConfig>, ) -> Result { let measured = Measured::new(model); + let boundaries = boundaries.map(|config| { + let evaluated = Boundaries::measure(model, &ConfigBoundaryPolicy(config)); + MetricMeasurement { + ratio: evaluated.ratio(), + numerator: evaluated.findings().len() as f64, + findings_worst_first: evaluated + .findings() + .iter() + .map(BoundaryFindingRow::from) + .collect(), + } + }); let mut external_metrics = BTreeMap::new(); for plugin in metric_plugins { let result = plugin.measure(model)?; @@ -120,6 +152,7 @@ impl SourceSetMeasurement { duplication: duplication(&measured), verbosity: verbosity(&measured), import_cycles: import_cycles(&measured), + boundaries, external_metrics, }) } diff --git a/docs/reference.md b/docs/reference.md index 2dac966..203fe97 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -527,10 +527,16 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `regression_limits.{metric}` | object | The Regression limit of this Metric in every Source set | | `regression_limits.{metric}.ratio_rise` | number from 0 to 1 | The highest ratio rise that passes | | `regression_limits.{metric}.new_findings` | string | When new Findings are a Regression: `any_new_finding`, `numerator_rise_with_new_findings`, or `never` | +| `regression_limits.boundaries` | object | The Regression limit of Boundaries in every Source set | +| `regression_limits.boundaries.ratio_rise` | number from 0 to 1 | The highest Boundaries ratio rise that passes | +| `regression_limits.boundaries.new_findings` | string | When new Boundaries Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | | `regression_limits.{source_set}` | object | The Regression limits of this Source set only | | `regression_limits.{source_set}.{metric}` | object | The Regression limit of this Metric in this Source set | | `regression_limits.{source_set}.{metric}.ratio_rise` | number from 0 to 1 | The highest ratio rise that passes | | `regression_limits.{source_set}.{metric}.new_findings` | string | When new Findings are a Regression: `any_new_finding`, `numerator_rise_with_new_findings`, or `never` | +| `regression_limits.{source_set}.boundaries` | object | The Regression limit of Boundaries in this Source set | +| `regression_limits.{source_set}.boundaries.ratio_rise` | number from 0 to 1 | The highest Boundaries ratio rise that passes | +| `regression_limits.{source_set}.boundaries.new_findings` | string | When new Boundaries Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | | `languages` | list of objects | Which Language plugin measures which folders; see [Languages](#languages) | | `languages[].plugin` | string | The name of the Language plugin, such as `typescript-javascript` | | `languages[].include` | list of strings | Globs of repository-relative folders or files that the Language plugin measures; a folder covers every file below it | @@ -545,6 +551,7 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `plugin_limits.memory_mb` | integer from 1 to 4096 | Maximum linear memory in MiB that a WebAssembly Plugin may allocate; `64` by default | | `plugin_limits.timeout_ms` | integer from 1 to 300000 | Maximum wall-clock time in milliseconds for each WebAssembly Plugin call; `5000` by default | | `boundaries` | object | Architectural import boundaries defining named zones, optional `public_files` entry points, directional `allow` or `deny` rules, and optional `strict_zones` mode | +| `boundaries.preset` | string | Optional built-in architecture preset (`layered` or `hexagonal`) providing default zones and rules that can be overridden or extended | | `boundaries.zones` | object | Map of zone name to zone definition (`patterns` globs and optional `public_files` globs) | | `boundaries.rules` | list of objects | Directional import rules between architectural zones | | `boundaries.rules[].from` | string | Source zone name, or `*` to match any zone without a specific rule | @@ -775,10 +782,12 @@ codeint check `boundaries` enforces directional import rules and `public_files` encapsulation over resolved runtime imports across every supported Language plugin. When `boundaries` is omitted, boundary evaluation is completely inactive. +Set `boundaries.preset` to `layered` (`presentation`, `application`, `domain`, `infrastructure`) or `hexagonal` (`domain`, `ports`, `application`, `adapters`) to start from built-in zone globs and directional rules; entries in `boundaries.zones` override matching preset zones or add new ones, and rules in `boundaries.rules` replace preset rules for matching `from` zones. Each zone in `boundaries.zones` declares repository-relative `patterns` globs and optional `public_files` globs naming the only files external zones may import. When a file matches patterns in multiple zones, the most specific pattern (most literal characters, then longest pattern, then zone name alphabetically) wins. Each rule in `boundaries.rules` sets `from` (a zone name or `*`), either `allow` or `deny` (mutually exclusive), and an optional `reason`. By default, `boundaries` evaluates the `production` Source set only; set `source_sets` to evaluate additional Source sets, and set `strict_zones` to `true` to report files matching no zone. +In `codeint diff`, each boundary Finding carries a stable content-based identifier so pre-existing Findings are classified as unchanged while any newly introduced boundary Finding fails by default (`new_findings: "any_new_finding"`). ```json codeint.json { @@ -787,7 +796,20 @@ By default, `boundaries` evaluates the `production` Source set only; set `source "boundaries": 0 } }, + "regression_limits": { + "boundaries": { + "ratio_rise": 0.01, + "new_findings": "any_new_finding" + }, + "production": { + "boundaries": { + "ratio_rise": 0, + "new_findings": "any_new_finding" + } + } + }, "boundaries": { + "preset": "layered", "zones": { "app": { "patterns": ["src/**"], diff --git a/schema/codeint.schema.json b/schema/codeint.schema.json index 1fbda44..1e269a7 100644 --- a/schema/codeint.schema.json +++ b/schema/codeint.schema.json @@ -197,6 +197,10 @@ "$ref": "#/$defs/RegressionLimitSetting", "description": "The Regression limit of Import cycles in every Source set." }, + "boundaries": { + "$ref": "#/$defs/RegressionLimitSetting", + "description": "The Regression limit of Boundaries in every Source set." + }, "production": { "$ref": "#/$defs/MetricRegressionLimits", "description": "The Regression limits of the Production Source set." @@ -261,6 +265,10 @@ "import_cycles": { "$ref": "#/$defs/RegressionLimitSetting", "description": "The Regression limit of Import cycles in this Source set." + }, + "boundaries": { + "$ref": "#/$defs/RegressionLimitSetting", + "description": "The Regression limit of Boundaries in this Source set." } }, "additionalProperties": { @@ -364,6 +372,10 @@ "type": "object", "additionalProperties": false, "properties": { + "preset": { + "$ref": "#/$defs/BoundaryPreset", + "description": "Optional built-in architecture preset (\"layered\" or \"hexagonal\") providing default zones and rules that can be overridden or extended by zones and rules." + }, "zones": { "type": "object", "additionalProperties": { @@ -392,6 +404,13 @@ } } }, + "BoundaryPreset": { + "type": "string", + "enum": [ + "layered", + "hexagonal" + ] + }, "BoundaryZoneFile": { "type": "object", "additionalProperties": false, From 3e2894fec692a34297d423fe8ad7834e74d4d089 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 08:24:00 +0800 Subject: [PATCH 3/4] feat(cli): add pre-edit guard command and MCP tool Add codeint guard (text, toon, json) and the matching read-only guard tool in codeint mcp so developers and coding agents can inspect architectural zone membership, allowed and denied target zones, public_files constraints, allowed importers, and rule reasons for existing or planned files. Closes #178 --- crates/cli/src/guard.rs | 132 ++++++++++++++++ crates/cli/src/lib.rs | 23 ++- crates/cli/src/mcp.rs | 35 ++++- crates/cli/src/remedy.rs | 9 ++ crates/cli/tests/guard.rs | 204 ++++++++++++++++++++++++ crates/cli/tests/mcp.rs | 114 +++++++++++++- crates/config/src/boundaries.rs | 66 ++++++-- crates/config/src/lib.rs | 36 ++++- crates/report/src/guard.rs | 266 ++++++++++++++++++++++++++++++++ crates/report/src/lib.rs | 2 + docs/reference.md | 25 ++- 11 files changed, 889 insertions(+), 23 deletions(-) create mode 100644 crates/cli/src/guard.rs create mode 100644 crates/cli/tests/guard.rs create mode 100644 crates/report/src/guard.rs diff --git a/crates/cli/src/guard.rs b/crates/cli/src/guard.rs new file mode 100644 index 0000000..05544a3 --- /dev/null +++ b/crates/cli/src/guard.rs @@ -0,0 +1,132 @@ +use std::path::{Component, Path, PathBuf}; + +use codeint_config::{ConfigurationFileError, read_configuration}; +use codeint_git::{GitError, Repository}; +use codeint_model::{InvalidRepoPath, RepoPath}; +use codeint_report::GuardReport; + +#[derive(Debug, thiserror::Error)] +pub(crate) enum GuardError { + #[error(transparent)] + Git(#[from] GitError), + #[error(transparent)] + Configuration(#[from] ConfigurationFileError), + #[error("{} is outside the Git repository at {}", path.display(), root.display())] + OutsideRepository { path: PathBuf, root: PathBuf }, + #[error("{} is not a valid UTF-8 repository path", path.display())] + NonUtf8Path { path: PathBuf }, + #[error("{} is not a valid repository path: {source}", path.display())] + InvalidPath { + path: PathBuf, + #[source] + source: InvalidRepoPath, + }, +} + +pub(crate) fn guard(folder: &Path, target: &Path) -> Result { + let absolute_target = normalize_lexically(&if target.is_absolute() { + target.to_path_buf() + } else { + folder.join(target) + }); + let discovery_start = nearest_existing_ancestor(&absolute_target).unwrap_or(folder); + let repository = match Repository::discover(discovery_start) { + Ok(repo) => repo, + Err(_) if discovery_start != folder => Repository::discover(folder)?, + Err(err) => return Err(GuardError::Git(err)), + }; + + let canonical_root = std::fs::canonicalize(repository.root()) + .unwrap_or_else(|_| repository.root().to_path_buf()); + let resolved_target = canonicalize_with_tail(&absolute_target); + let relative = resolved_target + .strip_prefix(&canonical_root) + .or_else(|_| resolved_target.strip_prefix(repository.root())) + .map_err(|_| GuardError::OutsideRepository { + path: target.to_path_buf(), + root: repository.root().to_path_buf(), + })?; + + let repo_path = to_repo_path(relative, target)?; + let exists = resolved_target.exists(); + let configuration = read_configuration(repository.root())?; + Ok(GuardReport::evaluate( + &repo_path, + exists, + configuration.boundaries.as_ref(), + )) +} + +fn nearest_existing_ancestor(path: &Path) -> Option<&Path> { + let mut cursor = Some(path); + while let Some(candidate) = cursor { + if candidate.exists() { + if candidate.is_dir() { + return Some(candidate); + } + return candidate.parent(); + } + cursor = candidate.parent(); + } + None +} + +fn canonicalize_with_tail(path: &Path) -> PathBuf { + let mut missing = Vec::new(); + let mut cursor = path; + loop { + if cursor.exists() { + let mut base = std::fs::canonicalize(cursor).unwrap_or_else(|_| cursor.to_path_buf()); + for segment in missing.into_iter().rev() { + base.push(segment); + } + return base; + } + match (cursor.parent(), cursor.file_name()) { + (Some(parent), Some(name)) => { + missing.push(name.to_os_string()); + cursor = parent; + } + _ => return path.to_path_buf(), + } + } +} + +fn normalize_lexically(path: &Path) -> PathBuf { + let mut normalized = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + normalized.pop(); + } + other => normalized.push(other.as_os_str()), + } + } + normalized +} + +fn to_repo_path(relative: &Path, original: &Path) -> Result { + let mut segments = Vec::new(); + for component in relative.components() { + match component { + Component::Normal(part) => { + let text = part.to_str().ok_or_else(|| GuardError::NonUtf8Path { + path: original.to_path_buf(), + })?; + segments.push(text); + } + Component::CurDir => {} + _ => { + return Err(GuardError::NonUtf8Path { + path: original.to_path_buf(), + }); + } + } + } + let joined = segments.join("/"); + RepoPath::new(&joined).map_err(|source| GuardError::InvalidPath { + path: original.to_path_buf(), + source, + }) +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index bec0ed4..c3c9d6d 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -3,6 +3,7 @@ mod check; mod commit_measurement; mod diff; +mod guard; mod init; mod mcp; mod remedy; @@ -20,9 +21,10 @@ use codeint_git::ResultCache; use codeint_report::ReportError; pub use codeint_config::{ - CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, + CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, + TrendRange, }; -pub use codeint_report::{DiffReport, Report, TrendReport}; +pub use codeint_report::{DiffReport, GuardReport, Report, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -182,6 +184,10 @@ pub fn init(folder: &Path) -> Result { init::init(folder).map_err(|err| CodeintError::from_cli_error(CliError::Init(err))) } +pub fn guard(folder: &Path, target: &Path) -> Result { + guard::guard(folder, target).map_err(|err| CodeintError::from_cli_error(CliError::Guard(err))) +} + #[derive(Debug, thiserror::Error)] enum CliError { #[error(transparent)] @@ -189,6 +195,8 @@ enum CliError { #[error(transparent)] Check(#[from] check::CheckError), #[error(transparent)] + Guard(#[from] guard::GuardError), + #[error(transparent)] Init(#[from] init::InitError), #[error(transparent)] Update(#[from] update::UpdateError), @@ -291,9 +299,20 @@ fn run() -> Result { result_cache, plugin_host, } => run_mcp(&folder, result_cache, plugin_host), + Command::Guard { + folder, + target, + format, + } => run_guard(&folder, &target, format), } } +fn run_guard(folder: &Path, target: &Path, format: GuardFormat) -> Result { + let report = guard::guard(folder, target)?; + print_report(&format!("{}\n", report.render(format)?))?; + Ok(Outcome::Passed) +} + fn run_init(folder: &Path) -> Result { let written = init::init(folder)?; print_report(&format!("Wrote {}\n", written.display()))?; diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index e8553c7..948a4e8 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -3,11 +3,12 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use codeint_config::{ - CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, + CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, + TrendRange, }; use serde_json::{Value, json}; -use crate::{CheckOptions, DiffOptions, TrendOptions, check, diff, trend}; +use crate::{CheckOptions, DiffOptions, TrendOptions, check, diff, guard, trend}; const DEFAULT_PROTOCOL_VERSION: &str = "2024-11-05"; @@ -157,6 +158,18 @@ fn handle_tools_list() -> Value { "since": { "type": "string", "description": "UTC date YYYY-MM-DD to start the trend from." } } } + }, + { + "name": "guard", + "description": "Query the architectural boundary zone, allowed and denied target zones, public_files constraints, and allowed importers for an existing or planned file path.", + "inputSchema": { + "type": "object", + "required": ["file"], + "properties": { + "file": { "type": "string", "description": "Repository-relative or absolute path to the existing or planned file." }, + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." } + } + } } ] }) @@ -175,6 +188,7 @@ fn handle_tools_call( "check" => Ok(call_check(args, ctx)), "diff" => Ok(call_diff(args, ctx)), "trend" => Ok(call_trend(args, ctx)), + "guard" => Ok(call_guard(args, ctx)), other => Err((-32602, format!("Unknown tool: {other}"))), } } @@ -263,6 +277,23 @@ fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { } } +fn call_guard(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { + let Some(file) = args.and_then(|a| a.get("file")).and_then(Value::as_str) else { + return tool_err("Missing required argument: file"); + }; + let folder = resolve_folder(args, ctx.default_folder); + match guard(&folder, Path::new(file)) { + Ok(report) => match report.render(GuardFormat::Json) { + Ok(rendered) => { + let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null); + tool_ok(payload) + } + Err(err) => tool_err(&err.to_string()), + }, + Err(err) => tool_err(&err.to_string()), + } +} + fn resolve_folder(args: Option<&Value>, default_folder: &Path) -> PathBuf { match args.and_then(|a| a.get("path")).and_then(Value::as_str) { Some(p) if !p.is_empty() => { diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index da9eb2c..71542d3 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -5,6 +5,7 @@ use codeint_plugin_host::PluginHostError; use crate::CliError; use crate::check::CheckError; +use crate::guard::GuardError; use crate::init::InitError; use crate::update::UpdateError; @@ -25,6 +26,14 @@ pub(crate) fn remedy(error: &CliError) -> &'static str { CliError::Check(CheckError::ExtensionConflict { .. }) => { "Assign separate directories to each Language plugin in the languages setting of codeint.json." } + CliError::Guard(GuardError::Git(error)) => git_remedy(error), + CliError::Guard(GuardError::Configuration(error)) => configuration_file_remedy(error), + CliError::Guard(GuardError::OutsideRepository { .. }) => { + "Pass a file path inside the Git repository, such as src/domain/service.ts." + } + CliError::Guard(GuardError::NonUtf8Path { .. } | GuardError::InvalidPath { .. }) => { + "Pass a valid UTF-8 file path inside the Git repository." + } CliError::Init(InitError::Git(GitError::NotInRepository { .. })) => { "Run codeint init inside a Git repository; it writes codeint.json at the root of the repository." } diff --git a/crates/cli/tests/guard.rs b/crates/cli/tests/guard.rs new file mode 100644 index 0000000..029841d --- /dev/null +++ b/crates/cli/tests/guard.rs @@ -0,0 +1,204 @@ +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +fn create_guard_repo(config: Option, files: &[(&str, &str)]) -> TempDir { + let repo = TempDir::new().expect("create tempdir"); + assert!( + Command::new("git") + .args(["init", "-q", "-b", "main"]) + .current_dir(repo.path()) + .status() + .expect("git init") + .success() + ); + if let Some(cfg) = config { + fs::write(repo.path().join("codeint.json"), cfg.to_string()).expect("write config"); + } + for (relative, contents) in files { + let target = repo.path().join(relative); + if let Some(parent) = target.parent() { + fs::create_dir_all(parent).expect("create parent dirs"); + } + fs::write(target, contents).expect("write source"); + } + repo +} + +fn run_codeint(cwd: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .args(args) + .current_dir(cwd) + .output() + .expect("run codeint") +} + +fn guard_json(cwd: &Path, target: &str) -> Value { + let out = run_codeint(cwd, &["guard", target, "--format", "json"]); + assert_eq!( + out.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + serde_json::from_slice(&out.stdout).expect("valid JSON") +} + +fn layered_guard_config() -> Value { + json!({ + "boundaries": { + "zones": { + "core": { "patterns": ["src/core/**"], "public_files": ["src/core/public.ts"] }, + "storage": { "patterns": ["src/storage/**"] }, + "ui": { "patterns": ["src/ui/**"] } + }, + "rules": [ + { "from": "core", "deny": ["storage"], "reason": "Core logic cannot depend on storage" }, + { "from": "ui", "allow": ["core"], "reason": "UI may only import core" } + ] + } + }) +} + +#[test] +fn guard_reports_zone_rules_public_files_and_importers_for_existing_and_planned_files() { + let repo = create_guard_repo( + Some(layered_guard_config()), + &[ + ("src/core/public.ts", "export const api = 1;\n"), + ("src/core/internal.ts", "export const secret = 2;\n"), + ("src/storage/db.ts", "export const db = 3;\n"), + ], + ); + + let internal = guard_json(repo.path(), "src/core/internal.ts"); + assert_eq!(internal["path"], "src/core/internal.ts"); + assert_eq!(internal["exists"], true); + assert_eq!(internal["configured"], true); + assert_eq!(internal["zone"], "core"); + assert_eq!(internal["is_public_file"], false); + assert_eq!(internal["public_files"], json!(["src/core/public.ts"])); + assert_eq!(internal["allowed_importers"], json!(["core"])); + let denied = internal["denied_targets"] + .as_array() + .expect("denied_targets"); + assert_eq!(denied.len(), 1); + assert_eq!(denied[0]["zone"], "storage"); + assert_eq!(denied[0]["directive"], "deny"); + assert_eq!(denied[0]["reason"], "Core logic cannot depend on storage"); + + let public_entry = guard_json(repo.path(), "src/core/public.ts"); + assert_eq!(public_entry["is_public_file"], true); + assert_eq!( + public_entry["allowed_importers"], + json!(["core", "storage", "ui"]) + ); + + let planned = guard_json(repo.path(), "src/ui/planned/dashboard.ts"); + assert_eq!(planned["path"], "src/ui/planned/dashboard.ts"); + assert_eq!(planned["exists"], false); + assert_eq!(planned["configured"], true); + assert_eq!(planned["zone"], "ui"); + let allowed = planned["allowed_targets"] + .as_array() + .expect("allowed_targets"); + let core_target = allowed + .iter() + .find(|target| target["zone"] == "core") + .expect("core allowed target"); + assert_eq!(core_target["public_files"], json!(["src/core/public.ts"])); + assert_eq!(core_target["reason"], "UI may only import core"); + let planned_denied = planned["denied_targets"] + .as_array() + .expect("denied_targets"); + assert_eq!(planned_denied.len(), 1); + assert_eq!(planned_denied[0]["zone"], "storage"); + assert_eq!(planned_denied[0]["directive"], "allow"); + assert_eq!(planned_denied[0]["reason"], "UI may only import core"); + + let text_out = run_codeint(repo.path(), &["guard", "src/ui/planned/dashboard.ts"]); + assert_eq!(text_out.status.code(), Some(0)); + let text = String::from_utf8(text_out.stdout).expect("utf8"); + assert!(text.contains("src/ui/planned/dashboard.ts")); + assert!(text.contains("zone: ui")); + assert!(text.contains("core")); + assert!(text.contains("src/core/public.ts")); + assert!(text.contains("UI may only import core")); + + let toon_out = run_codeint( + repo.path(), + &["guard", "src/core/internal.ts", "--format", "toon"], + ); + assert_eq!(toon_out.status.code(), Some(0)); + let toon = String::from_utf8(toon_out.stdout).expect("utf8"); + assert!(toon.contains("zone: core")); + assert!(toon.contains("Core logic cannot depend on storage")); +} + +#[test] +fn guard_handles_unzoned_files_and_unconfigured_repositories_deterministically() { + let strict_repo = create_guard_repo( + Some(json!({ + "boundaries": { + "zones": { "domain": { "patterns": ["src/domain/**"] } }, + "strict_zones": true + } + })), + &[("src/orphan.ts", "export const orphan = 1;\n")], + ); + + let unzoned = guard_json(strict_repo.path(), "src/orphan.ts"); + assert_eq!(unzoned["configured"], true); + assert_eq!(unzoned["strict_zones"], true); + assert!(unzoned.get("zone").is_none()); + assert_eq!(unzoned["allowed_targets"], json!([])); + assert_eq!(unzoned["denied_targets"], json!([])); + assert!( + unzoned["note"] + .as_str() + .unwrap_or_default() + .contains("strict_zones") + ); + + let unconfigured_repo = create_guard_repo(None, &[("src/app.ts", "export const a = 1;\n")]); + let unconfigured = guard_json(unconfigured_repo.path(), "src/app.ts"); + assert_eq!(unconfigured["configured"], false); + assert_eq!(unconfigured["exists"], true); + assert!(unconfigured.get("zone").is_none()); + assert!( + unconfigured["note"] + .as_str() + .unwrap_or_default() + .contains("No boundaries") + ); +} + +#[test] +fn guard_resolves_subdirectory_and_absolute_paths_and_rejects_outside_repo() { + let repo = create_guard_repo( + Some(layered_guard_config()), + &[("src/core/public.ts", "export const api = 1;\n")], + ); + + let sub_json = guard_json(&repo.path().join("src/core"), "planned.ts"); + assert_eq!(sub_json["path"], "src/core/planned.ts"); + assert_eq!(sub_json["zone"], "core"); + assert_eq!(sub_json["exists"], false); + + let abs_target = repo.path().join("src/storage/new_adapter.ts"); + let abs_json = guard_json(repo.path(), abs_target.to_str().expect("utf8 path")); + assert_eq!(abs_json["path"], "src/storage/new_adapter.ts"); + assert_eq!(abs_json["zone"], "storage"); + assert_eq!(abs_json["exists"], false); + + let outside = run_codeint(repo.path(), &["guard", "../outside.ts"]); + assert_eq!(outside.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&outside.stderr); + assert!( + stderr.contains("outside the Git repository"), + "stderr: {stderr}" + ); +} diff --git a/crates/cli/tests/mcp.rs b/crates/cli/tests/mcp.rs index 0ef1089..d6156b3 100644 --- a/crates/cli/tests/mcp.rs +++ b/crates/cli/tests/mcp.rs @@ -77,7 +77,7 @@ fn mcp_initialize_list_and_call_tools() { assert_eq!(responses[0]["result"]["serverInfo"]["name"], "codeint"); let tools = responses[1]["result"]["tools"].as_array().unwrap(); let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["check", "diff", "trend"]); + assert_eq!(names, ["check", "diff", "trend", "guard"]); assert_eq!(responses[2]["result"]["isError"], false); let check_payload: Value = serde_json::from_str( @@ -93,3 +93,115 @@ fn mcp_initialize_list_and_call_tools() { assert_eq!(responses[4]["result"]["isError"], false); assert_eq!(responses[5]["error"]["code"], -32601); } + +#[test] +fn mcp_guard_tool_reports_existing_planned_unzoned_and_unconfigured_paths() { + let repo = init_sample_repo(); + let unconfigured = send_mcp_requests( + repo.path(), + &[json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": {"name": "guard", "arguments": {"file": "app.ts"}} + })], + ); + assert_eq!(unconfigured[0]["result"]["isError"], false); + let unconfigured_payload: Value = serde_json::from_str( + unconfigured[0]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(unconfigured_payload["configured"], false); + assert_eq!(unconfigured_payload["exists"], true); + + std::fs::write( + repo.path().join("codeint.json"), + json!({ + "boundaries": { + "zones": { + "core": { "patterns": ["src/core/**"], "public_files": ["src/core/api.ts"] }, + "adapter": { "patterns": ["src/adapter/**"] }, + "web": { "patterns": ["src/web/**"] } + }, + "rules": [ + { "from": "core", "deny": ["adapter"], "reason": "Core must stay independent of adapters" }, + { "from": "web", "allow": ["core"], "reason": "Web may only import core" } + ] + } + }) + .to_string(), + ) + .unwrap(); + std::fs::create_dir_all(repo.path().join("src/core")).unwrap(); + std::fs::write( + repo.path().join("src/core/internal.ts"), + "export const internal = 1;\n", + ) + .unwrap(); + + let responses = send_mcp_requests( + repo.path(), + &[ + json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": {"name": "guard", "arguments": {"file": "src/core/internal.ts"}} + }), + json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": {"name": "guard", "arguments": {"file": "src/web/planned/view.ts"}} + }), + json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": {"name": "guard", "arguments": {"file": "app.ts"}} + }), + ], + ); + + assert_eq!(responses.len(), 3); + for response in &responses { + assert_eq!(response["result"]["isError"], false); + } + + let existing: Value = serde_json::from_str( + responses[0]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(existing["zone"], "core"); + assert_eq!(existing["exists"], true); + assert_eq!(existing["is_public_file"], false); + assert_eq!(existing["allowed_importers"], json!(["core"])); + assert_eq!(existing["denied_targets"][0]["zone"], "adapter"); + assert_eq!( + existing["denied_targets"][0]["reason"], + "Core must stay independent of adapters" + ); + + let planned: Value = serde_json::from_str( + responses[1]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(planned["zone"], "web"); + assert_eq!(planned["exists"], false); + assert_eq!(planned["denied_targets"][0]["zone"], "adapter"); + + let unzoned: Value = serde_json::from_str( + responses[2]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(unzoned["configured"], true); + assert!(unzoned.get("zone").is_none()); +} diff --git a/crates/config/src/boundaries.rs b/crates/config/src/boundaries.rs index b176be3..e10925c 100644 --- a/crates/config/src/boundaries.rs +++ b/crates/config/src/boundaries.rs @@ -125,6 +125,7 @@ struct CompiledPattern { struct CompiledZone { patterns: Vec, public_files: Option, + public_file_patterns: Vec, } #[derive(Debug, Clone)] @@ -164,17 +165,19 @@ impl Boundaries { } let patterns_key = zone_key.child(KeySegment::Key("patterns".to_owned())); let patterns = compile_patterns(&patterns_key, &zone_file.patterns)?; - let public_files = if zone_file.public_files.is_empty() { + let public_file_patterns = zone_file.public_files; + let public_files = if public_file_patterns.is_empty() { None } else { let public_key = zone_key.child(KeySegment::Key("public_files".to_owned())); - Some(glob_set(&public_key, &zone_file.public_files)?) + Some(glob_set(&public_key, &public_file_patterns)?) }; zones.insert( name, CompiledZone { patterns, public_files, + public_file_patterns, }, ); } @@ -259,6 +262,51 @@ impl Boundaries { self.strict_zones } + pub fn zone_names(&self) -> Vec<&str> { + self.zones.keys().map(String::as_str).collect() + } + + pub fn public_file_patterns(&self, zone: &str) -> &[String] { + self.zones + .get(zone) + .map_or(&[], |compiled| compiled.public_file_patterns.as_slice()) + } + + pub fn allow_reason(&self, source_zone: &str, target_zone: &str) -> Option<&str> { + if source_zone == target_zone { + return None; + } + let applicable = self.applicable_rules(source_zone); + let first = applicable.first()?; + if first.directive != BoundaryDirective::Allow { + return None; + } + applicable + .iter() + .find(|rule| { + rule.targets + .iter() + .any(|target| target == target_zone || target == WILDCARD_ZONE) + }) + .and_then(|rule| rule.reason.as_deref()) + } + + fn applicable_rules(&self, source_zone: &str) -> Vec<&CompiledRule> { + let specific: Vec<&CompiledRule> = self + .rules + .iter() + .filter(|rule| rule.from == source_zone) + .collect(); + if specific.is_empty() { + self.rules + .iter() + .filter(|rule| rule.from == WILDCARD_ZONE) + .collect() + } else { + specific + } + } + pub fn zone_of(&self, path: &RepoPath) -> Option<&str> { let mut best: Option<(&str, usize, usize)> = None; for (zone_name, zone) in &self.zones { @@ -303,19 +351,7 @@ impl Boundaries { if source_zone == target_zone { return BoundaryRuleDecision::Allowed; } - let specific: Vec<&CompiledRule> = self - .rules - .iter() - .filter(|rule| rule.from == source_zone) - .collect(); - let applicable: Vec<&CompiledRule> = if specific.is_empty() { - self.rules - .iter() - .filter(|rule| rule.from == WILDCARD_ZONE) - .collect() - } else { - specific - }; + let applicable = self.applicable_rules(source_zone); let Some(first) = applicable.first() else { return BoundaryRuleDecision::Allowed; }; diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 11102d1..419f7f9 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -95,6 +95,13 @@ pub enum TrendFormat { Markdown, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum GuardFormat { + Text, + Toon, + Json, +} + const LATEST_COMMITS_OF_A_TREND: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -143,6 +150,11 @@ pub enum Command { result_cache: Option, plugin_host: PluginHostConfig, }, + Guard { + folder: PathBuf, + target: PathBuf, + format: GuardFormat, + }, } #[derive(Debug)] @@ -233,9 +245,26 @@ enum CommandArguments { version: Option, }, #[command( - about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, and trend tools" + about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, trend, and guard tools" )] Mcp, + #[command( + about = "Show the architectural boundary zone, allowed and denied target zones, public_files constraints, and allowed importers for a file path" + )] + Guard { + #[arg( + value_name = "PATH", + help = "Path to an existing or planned file inside the Git repository" + )] + path: PathBuf, + #[arg( + long, + value_enum, + default_value_t = GuardFormat::Text, + help = "The format of the output" + )] + format: GuardFormat, + }, } #[derive(Debug, clap::Args)] @@ -293,6 +322,11 @@ pub fn read_invocation() -> Result { plugin_host: plugin_host_config_of_this_process(¤t_folder), folder: current_folder, }, + CommandArguments::Guard { path, format } => Command::Guard { + folder: current_folder, + target: path, + format, + }, }; Ok(Invocation { command }) } diff --git a/crates/report/src/guard.rs b/crates/report/src/guard.rs new file mode 100644 index 0000000..ede13a3 --- /dev/null +++ b/crates/report/src/guard.rs @@ -0,0 +1,266 @@ +use std::fmt::Write as _; + +use codeint_config::{ + Boundaries as BoundariesConfig, BoundaryDirective, BoundaryRuleDecision, GuardFormat, +}; +use codeint_model::RepoPath; +use serde::Serialize; + +use crate::ReportError; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct GuardReport { + path: String, + exists: bool, + configured: bool, + strict_zones: bool, + #[serde(skip_serializing_if = "Option::is_none")] + zone: Option, + #[serde(skip_serializing_if = "Option::is_none")] + is_public_file: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + public_files: Vec, + allowed_targets: Vec, + denied_targets: Vec, + allowed_importers: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + note: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct GuardAllowedTarget { + zone: String, + #[serde(skip_serializing_if = "Vec::is_empty")] + public_files: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + reason: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct GuardDeniedTarget { + zone: String, + directive: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + reason: Option, +} + +impl GuardReport { + pub fn evaluate( + path: &RepoPath, + exists: bool, + boundaries: Option<&BoundariesConfig>, + ) -> GuardReport { + let Some(boundaries) = boundaries else { + return GuardReport { + path: path.as_str().to_owned(), + exists, + configured: false, + strict_zones: false, + zone: None, + is_public_file: None, + public_files: Vec::new(), + allowed_targets: Vec::new(), + denied_targets: Vec::new(), + allowed_importers: Vec::new(), + note: Some("No boundaries are configured in codeint.json.".to_owned()), + }; + }; + + let strict_zones = boundaries.strict_zones(); + let Some(matched_zone) = boundaries.zone_of(path) else { + let note = if strict_zones { + "Path does not match any configured zone; strict_zones is enabled, so this file will be flagged as unzoned." + } else { + "Path does not match any configured zone; no boundary rules apply." + }; + return GuardReport { + path: path.as_str().to_owned(), + exists, + configured: true, + strict_zones, + zone: None, + is_public_file: None, + public_files: Vec::new(), + allowed_targets: Vec::new(), + denied_targets: Vec::new(), + allowed_importers: Vec::new(), + note: Some(note.to_owned()), + }; + }; + + let public_files = boundaries.public_file_patterns(matched_zone).to_vec(); + let is_public_file = boundaries.is_public_file(matched_zone, path); + let all_zones = boundaries.zone_names(); + + let mut allowed_targets = Vec::new(); + let mut denied_targets = Vec::new(); + for &target_zone in &all_zones { + match boundaries.check_import(matched_zone, target_zone) { + BoundaryRuleDecision::Allowed => { + let target_public_files = if target_zone == matched_zone { + Vec::new() + } else { + boundaries.public_file_patterns(target_zone).to_vec() + }; + let reason = boundaries + .allow_reason(matched_zone, target_zone) + .map(str::to_owned); + allowed_targets.push(GuardAllowedTarget { + zone: target_zone.to_owned(), + public_files: target_public_files, + reason, + }); + } + BoundaryRuleDecision::Denied { directive, reason } => { + denied_targets.push(GuardDeniedTarget { + zone: target_zone.to_owned(), + directive: directive_label(directive), + reason, + }); + } + } + } + + let mut allowed_importers = Vec::new(); + for &importer_zone in &all_zones { + if importer_zone == matched_zone { + allowed_importers.push(importer_zone.to_owned()); + continue; + } + if is_public_file + && matches!( + boundaries.check_import(importer_zone, matched_zone), + BoundaryRuleDecision::Allowed + ) + { + allowed_importers.push(importer_zone.to_owned()); + } + } + + let note = if !is_public_file { + Some(format!( + "This file is private to zone \"{matched_zone}\"; other zones may only import files matching public_files." + )) + } else { + None + }; + + GuardReport { + path: path.as_str().to_owned(), + exists, + configured: true, + strict_zones, + zone: Some(matched_zone.to_owned()), + is_public_file: Some(is_public_file), + public_files, + allowed_targets, + denied_targets, + allowed_importers, + note, + } + } + + pub fn render(&self, format: GuardFormat) -> Result { + match format { + GuardFormat::Text => Ok(self.render_text()), + GuardFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), + GuardFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), + } + } + + fn render_text(&self) -> String { + let mut out = String::new(); + let status = if self.exists { + "exists" + } else { + "planned, does not exist on disk" + }; + let _ = writeln!(out, "path: {} ({status})", self.path); + if !self.configured { + let _ = writeln!(out, "boundaries: not configured"); + if let Some(note) = &self.note { + let _ = write!(out, "note: {note}"); + } + return out.trim_end_matches('\n').to_owned(); + } + match &self.zone { + Some(zone) => { + let _ = writeln!(out, "zone: {zone}"); + if !self.public_files.is_empty() { + let visibility = if self.is_public_file == Some(true) { + "this file is public" + } else { + "this file is private" + }; + let _ = writeln!( + out, + "public_files: {} ({visibility})", + self.public_files.join(", ") + ); + } + if self.allowed_targets.is_empty() { + let _ = writeln!(out, "allowed_targets: none"); + } else { + let _ = writeln!(out, "allowed_targets:"); + for target in &self.allowed_targets { + let mut details = Vec::new(); + if !target.public_files.is_empty() { + details + .push(format!("public_files: {}", target.public_files.join(", "))); + } + if let Some(reason) = &target.reason { + details.push(format!("reason: {reason}")); + } + if details.is_empty() { + let _ = writeln!(out, " - {}", target.zone); + } else { + let _ = writeln!(out, " - {} ({})", target.zone, details.join("; ")); + } + } + } + if self.denied_targets.is_empty() { + let _ = writeln!(out, "denied_targets: none"); + } else { + let _ = writeln!(out, "denied_targets:"); + for target in &self.denied_targets { + match &target.reason { + Some(reason) => { + let _ = writeln!( + out, + " - {} ({}: {reason})", + target.zone, target.directive + ); + } + None => { + let _ = writeln!(out, " - {} ({})", target.zone, target.directive); + } + } + } + } + if self.allowed_importers.is_empty() { + let _ = writeln!(out, "allowed_importers: none"); + } else { + let _ = writeln!( + out, + "allowed_importers: {}", + self.allowed_importers.join(", ") + ); + } + } + None => { + let _ = writeln!(out, "zone: none"); + } + } + if let Some(note) = &self.note { + let _ = writeln!(out, "note: {note}"); + } + out.trim_end_matches('\n').to_owned() + } +} + +fn directive_label(directive: BoundaryDirective) -> &'static str { + match directive { + BoundaryDirective::Allow => "allow", + BoundaryDirective::Deny => "deny", + } +} diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index 291c85e..28b0821 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -19,6 +19,7 @@ use serde::ser::SerializeMap; use serde::{Deserialize, Serialize, Serializer}; mod diff; +mod guard; mod markdown; mod measurement; mod sarif; @@ -27,6 +28,7 @@ mod tests; mod trend; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; +pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use measurement::CommitMeasurement; pub use trend::{TrendPoint, TrendReport}; diff --git a/docs/reference.md b/docs/reference.md index 2dac966..f7675b7 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -28,7 +28,8 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `trend` | Measure each commit of the main line and print each Metric over time; see [`codeint trend`](#codeint-trend) | | `init` | Write a starter `codeint.json`; see [`codeint init`](#codeint-init) | | `update` | Update a standalone codeint binary in place from GitHub Releases; see [`codeint update`](#codeint-update) | -| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, and `trend` tools; see [`codeint mcp`](#codeint-mcp) | +| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, and `guard` tools; see [`codeint mcp`](#codeint-mcp) | +| `guard` | Show the architectural boundary zone, allowed and denied target zones, `public_files` constraints, and allowed importers for a file path; see [`codeint guard`](#codeint-guard) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -486,13 +487,33 @@ codeint 0.5.0 is already up to date (v0.5.0) | `-h, --help` | Print the help of `codeint mcp` | `codeint mcp` runs a local Model Context Protocol (MCP) server over standard input and standard output with no open network port. -It exposes three read-only tools (`check`, `diff`, and `trend`) so coding agents can measure Software entropy and fix Regressions before opening a pull request. +It exposes four read-only tools (`check`, `diff`, `trend`, and `guard`) so coding agents can measure Software entropy, inspect architectural boundaries, and fix Regressions before opening a pull request. When standard input closes, the server exits with code 0: ```sh exit=0 codeint mcp ``` +### `codeint guard` + +| Argument | Meaning | +| -------- | ------- | +| `` | Path to an existing or planned file inside the Git repository | + +| Option | Meaning | +| ------ | ------- | +| `--format ` | The format of the output: `text`, the default, `toon`, or `json` | +| `-h, --help` | Print the help of `codeint guard` | + +`codeint guard ` evaluates the architectural boundary rules in `codeint.json` for an existing or planned file path without requiring the file to exist on disk. + +```sh exit=0 +codeint guard src/route.ts +codeint guard src/route.ts --format text +codeint guard src/route.ts --format toon +codeint guard src/route.ts --format json +``` + ## Exit codes | Exit code | Meaning | From 5525aa3eef4fd9d29548ad95bcbe398c2355561a Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 08:38:55 +0800 Subject: [PATCH 4/4] refactor(metrics): resolve codeint diff regressions on Spec #169 --- crates/cli/src/mcp.rs | 58 ++-- crates/cli/src/remedy.rs | 182 +++++++----- crates/cli/tests/boundaries.rs | 474 ++++++++++++++---------------- crates/config/src/boundaries.rs | 257 +++++++++------- crates/config/src/codeint_json.rs | 233 +-------------- crates/config/src/config_error.rs | 232 +++++++++++++++ crates/config/src/lib.rs | 81 +++-- crates/metrics/src/boundaries.rs | 295 +++++++++++-------- crates/report/src/guard.rs | 144 +++++---- crates/report/src/lib.rs | 14 +- 10 files changed, 1061 insertions(+), 909 deletions(-) create mode 100644 crates/config/src/config_error.rs diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 948a4e8..55e02b3 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -210,8 +210,9 @@ fn call_check(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { } fn call_diff(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let Some(base_ref) = args.and_then(|a| a.get("base_ref")).and_then(Value::as_str) else { - return tool_err("Missing required argument: base_ref"); + let base_ref = match required_str_arg(args, "base_ref") { + Ok(value) => value, + Err(err) => return err, }; let folder = resolve_folder(args, ctx.default_folder); let options = DiffOptions { @@ -251,6 +252,28 @@ fn render_outcome( } } +fn render_json_tool( + result: Result, + render: impl FnOnce(T) -> Result, +) -> Value { + match result { + Ok(report) => match render(report) { + Ok(rendered) => { + let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null); + tool_ok(payload) + } + Err(err) => tool_err(&err.to_string()), + }, + Err(err) => tool_err(&err.to_string()), + } +} + +fn required_str_arg<'a>(args: Option<&'a Value>, name: &str) -> Result<&'a str, Value> { + args.and_then(|a| a.get(name)) + .and_then(Value::as_str) + .ok_or_else(|| tool_err(&format!("Missing required argument: {name}"))) +} + fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { let folder = resolve_folder(args, ctx.default_folder); let range = match args.and_then(|a| a.get("since")).and_then(Value::as_str) { @@ -265,33 +288,20 @@ fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { result_cache: ctx.result_cache.clone(), plugin_host: ctx.plugin_host.clone(), }; - match trend(&folder, &options) { - Ok(report) => match report.render(TrendFormat::Json) { - Ok(rendered) => { - let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null); - tool_ok(payload) - } - Err(err) => tool_err(&err.to_string()), - }, - Err(err) => tool_err(&err.to_string()), - } + render_json_tool(trend(&folder, &options), |report| { + report.render(TrendFormat::Json) + }) } fn call_guard(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let Some(file) = args.and_then(|a| a.get("file")).and_then(Value::as_str) else { - return tool_err("Missing required argument: file"); + let file = match required_str_arg(args, "file") { + Ok(value) => value, + Err(err) => return err, }; let folder = resolve_folder(args, ctx.default_folder); - match guard(&folder, Path::new(file)) { - Ok(report) => match report.render(GuardFormat::Json) { - Ok(rendered) => { - let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null); - tool_ok(payload) - } - Err(err) => tool_err(&err.to_string()), - }, - Err(err) => tool_err(&err.to_string()), - } + render_json_tool(guard(&folder, Path::new(file)), |report| { + report.render(GuardFormat::Json) + }) } fn resolve_folder(args: Option<&Value>, default_folder: &Path) -> PathBuf { diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 71542d3..9747e89 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -12,43 +12,59 @@ use crate::update::UpdateError; pub(crate) fn remedy(error: &CliError) -> &'static str { match error { CliError::Config(error) => config_remedy(error), - CliError::Check(CheckError::Git(error)) => git_remedy(error), - CliError::Check(CheckError::Configuration(error)) => configuration_file_remedy(error), - CliError::Check(CheckError::Workspace(error)) => workspace_remedy(error), - CliError::Check(CheckError::Resolve(_)) => { + CliError::Check(error) => check_remedy(error), + CliError::Guard(error) => guard_remedy(error), + CliError::Init(error) => init_remedy(error), + CliError::Update(error) => update_remedy(error), + CliError::Report(_) => { + "This is a defect in codeint; report it at https://github.com/avidianity/codeint/issues." + } + CliError::Output(_) => "Keep standard output open until codeint exits.", + CliError::OutputFile { .. } => { + "Pass --output a file path that you have permission to write, not a folder." + } + } +} + +fn check_remedy(error: &CheckError) -> &'static str { + match error { + CheckError::Git(error) => git_remedy(error), + CheckError::Configuration(error) => configuration_file_remedy(error), + CheckError::Workspace(error) => workspace_remedy(error), + CheckError::Resolve(_) => { "This is a defect in the Language plugin; report it to the author of the Language plugin." } - CliError::Check(CheckError::ReferenceRange(_)) => { + CheckError::ReferenceRange(_) => { "Fix the Reference ranges that the Language plugin supplies, or report the defect to its author." } - CliError::Check(CheckError::PluginHost(error)) => plugin_host_remedy(error), - CliError::Check(CheckError::MetricPlugin(error)) => metric_plugin_remedy(error), - CliError::Check(CheckError::ExtensionConflict { .. }) => { + CheckError::PluginHost(error) => plugin_host_remedy(error), + CheckError::MetricPlugin(error) => metric_plugin_remedy(error), + CheckError::ExtensionConflict { .. } => { "Assign separate directories to each Language plugin in the languages setting of codeint.json." } - CliError::Guard(GuardError::Git(error)) => git_remedy(error), - CliError::Guard(GuardError::Configuration(error)) => configuration_file_remedy(error), - CliError::Guard(GuardError::OutsideRepository { .. }) => { + } +} + +fn guard_remedy(error: &GuardError) -> &'static str { + match error { + GuardError::Git(error) => git_remedy(error), + GuardError::Configuration(error) => configuration_file_remedy(error), + GuardError::OutsideRepository { .. } => { "Pass a file path inside the Git repository, such as src/domain/service.ts." } - CliError::Guard(GuardError::NonUtf8Path { .. } | GuardError::InvalidPath { .. }) => { + GuardError::NonUtf8Path { .. } | GuardError::InvalidPath { .. } => { "Pass a valid UTF-8 file path inside the Git repository." } - CliError::Init(InitError::Git(GitError::NotInRepository { .. })) => { + } +} + +fn init_remedy(error: &InitError) -> &'static str { + match error { + InitError::Git(GitError::NotInRepository { .. }) => { "Run codeint init inside a Git repository; it writes codeint.json at the root of the repository." } - CliError::Init(InitError::Git(error)) => git_remedy(error), - CliError::Init(InitError::StarterConfiguration(error)) => { - starter_configuration_remedy(error) - } - CliError::Update(error) => update_remedy(error), - CliError::Report(_) => { - "This is a defect in codeint; report it at https://github.com/avidianity/codeint/issues." - } - CliError::Output(_) => "Keep standard output open until codeint exits.", - CliError::OutputFile { .. } => { - "Pass --output a file path that you have permission to write, not a folder." - } + InitError::Git(error) => git_remedy(error), + InitError::StarterConfiguration(error) => starter_configuration_remedy(error), } } @@ -143,82 +159,100 @@ fn workspace_remedy(error: &WorkspaceError) -> &'static str { } fn configuration_file_remedy(error: &ConfigurationFileError) -> &'static str { - if let Some(message) = plugin_config_remedy(error) { - return message; - } + plugin_config_remedy(error) + .or_else(|| boundary_config_remedy(error)) + .or_else(|| file_access_remedy(error)) + .or_else(|| json_shape_remedy(error)) + .unwrap_or("Check codeint.json against the JSON schema that $schema links to.") +} + +fn file_access_remedy(error: &ConfigurationFileError) -> Option<&'static str> { + use ConfigurationFileError as E; match error { - ConfigurationFileError::Unreadable(_) => { - "Check that codeint.json is a file you have permission to read, then run codeint again." - } - ConfigurationFileError::NotJson(_) => { - "Fix the JSON syntax of codeint.json at that line and column." - } - ConfigurationFileError::UnknownKey { .. } => { - "Remove the key, or correct its spelling to one of the allowed keys." - } - ConfigurationFileError::WrongType { .. } => { + E::Unreadable(_) => Some( + "Check that codeint.json is a file you have permission to read, then run codeint again.", + ), + E::NotJson(_) => Some("Fix the JSON syntax of codeint.json at that line and column."), + E::NewerSchemaVersion { .. } => Some( + "Run codeint update (or upgrade the codeint npm package) to match or exceed the $schema version, or lower the $schema tag in codeint.json.", + ), + _ => None, + } +} + +fn json_shape_remedy(error: &ConfigurationFileError) -> Option<&'static str> { + use ConfigurationFileError::*; + Some(match error { + UnknownKey { .. } => "Remove the key, or correct its spelling to one of the allowed keys.", + WrongType { .. } => { "Change the value to the expected type; the JSON schema that $schema links to describes every key." } - ConfigurationFileError::OutOfRange { + OutOfRange { minimum, maximum, .. - } if *minimum == 0.0 && *maximum == 1.0 => { - "Set the value to a ratio from 0 to 1, as the report shows ratios." - } - ConfigurationFileError::OutOfRange { .. } => { - "Set the value within the allowed range; the JSON schema that $schema links to describes every key." - } - ConfigurationFileError::NotOneOf { .. } => { + } => out_of_range_remedy(*minimum, *maximum), + NotOneOf { .. } => { "Set the value to one of the allowed values; the JSON schema that $schema links to describes each one." } - ConfigurationFileError::MissingKey { .. } => { + MissingKey { .. } => { "Add the key; the JSON schema that $schema links to describes every key." } - ConfigurationFileError::NewerSchemaVersion { .. } => { - "Run codeint update (or upgrade the codeint npm package) to match or exceed the $schema version, or lower the $schema tag in codeint.json." - } - ConfigurationFileError::InvalidBoundaryZoneName { .. } => { - "Give each boundary zone in codeint.json a non-empty name other than \"*\"." - } - ConfigurationFileError::EmptyBoundaryZonePatterns { .. } => { - "Add at least one path glob under patterns for every zone in boundaries.zones." - } - ConfigurationFileError::UnknownBoundaryZone { .. } => { - "Reference only zones defined under boundaries.zones (or \"*\") in boundaries.rules." + _ => return None, + }) +} + +fn out_of_range_remedy(minimum: f64, maximum: f64) -> &'static str { + if minimum == 0.0 && maximum == 1.0 { + "Set the value to a ratio from 0 to 1, as the report shows ratios." + } else { + "Set the value within the allowed range; the JSON schema that $schema links to describes every key." + } +} + +fn boundary_config_remedy(error: &ConfigurationFileError) -> Option<&'static str> { + use ConfigurationFileError::*; + match error { + InvalidBoundaryZoneName { .. } => { + Some("Give each boundary zone in codeint.json a non-empty name other than \"*\".") } - ConfigurationFileError::ConflictingBoundaryRule { .. } => { - "Set either allow or deny on each rule in boundaries.rules, not both." + EmptyBoundaryZonePatterns { .. } => { + Some("Add at least one path glob under patterns for every zone in boundaries.zones.") } - ConfigurationFileError::MissingBoundaryRuleDirective { .. } => { - "Set either allow or deny on each rule in boundaries.rules." + UnknownBoundaryZone { .. } => Some( + "Reference only zones defined under boundaries.zones (or \"*\") in boundaries.rules.", + ), + ConflictingBoundaryRule { .. } => { + Some("Set either allow or deny on each rule in boundaries.rules, not both.") } - ConfigurationFileError::ConflictingBoundaryDirectives { .. } => { - "Use either allow rules or deny rules for a given source zone in boundaries.rules, not both." + MissingBoundaryRuleDirective { .. } => { + Some("Set either allow or deny on each rule in boundaries.rules.") } - _ => "Check codeint.json against the JSON schema that $schema links to.", + ConflictingBoundaryDirectives { .. } => Some( + "Use either allow rules or deny rules for a given source zone in boundaries.rules, not both.", + ), + _ => None, } } fn plugin_config_remedy(error: &ConfigurationFileError) -> Option<&'static str> { + use ConfigurationFileError::*; Some(match error { - ConfigurationFileError::UnknownLanguagePlugin { .. } => { + UnknownLanguagePlugin { .. } => { "Name one of the Language plugins listed, or remove the entry from languages." } - ConfigurationFileError::InvalidGlob { .. } => { + InvalidGlob { .. } => { "Fix the glob: * matches within one folder, ** matches across folders, and {a,b} matches either a or b." } - ConfigurationFileError::InvalidSha256 { .. } => { + InvalidSha256 { .. } => { "Set sha256 to the 64-character hexadecimal SHA-256 digest of the plugin file." } - ConfigurationFileError::EmptyPluginField { .. } => { - "Set a non-empty value for the plugin field in codeint.json." - } - ConfigurationFileError::MissingPluginSource { .. } => { + EmptyPluginField { .. } => "Set a non-empty value for the plugin field in codeint.json.", + MissingPluginSource { .. } => { "Set either path (for a local file) or url (for an https:// download) on the plugin entry in codeint.json." } - ConfigurationFileError::AmbiguousPluginSource { .. } => { + AmbiguousPluginSource { .. } => { "Keep either path or url on the plugin entry in codeint.json and remove the other." } - ConfigurationFileError::NonHttpsPluginUrl { .. } => { + NonHttpsPluginUrl { .. } => { "Use an https:// URL for the plugin in codeint.json; plain HTTP and other schemes are refused." } _ => return None, diff --git a/crates/cli/tests/boundaries.rs b/crates/cli/tests/boundaries.rs index 81a685c..d958034 100644 --- a/crates/cli/tests/boundaries.rs +++ b/crates/cli/tests/boundaries.rs @@ -1,9 +1,19 @@ use std::fs; +use std::path::Path; use std::process::{Command, Output}; use serde_json::Value; use tempfile::TempDir; +const GIT_ENV: [(&str, &str); 6] = [ + ("GIT_CONFIG_GLOBAL", "/dev/null"), + ("GIT_CONFIG_NOSYSTEM", "1"), + ("GIT_AUTHOR_NAME", "Fixture"), + ("GIT_AUTHOR_EMAIL", "fixture@example.invalid"), + ("GIT_COMMITTER_NAME", "Fixture"), + ("GIT_COMMITTER_EMAIL", "fixture@example.invalid"), +]; + struct BoundaryFixture(TempDir); impl BoundaryFixture { @@ -15,34 +25,117 @@ impl BoundaryFixture { .status() .expect("git init"); assert!(init.success()); + let fixture = BoundaryFixture(dir); for &(rel, body) in files { - let dst = dir.path().join(rel); - if let Some(parent) = dst.parent() { - fs::create_dir_all(parent).expect("mkdir"); - } - fs::write(dst, body).expect("write"); + fixture.write(rel, body); + } + fixture + } + + fn write(&self, rel: &str, body: &str) { + let dst = self.0.path().join(rel); + if let Some(parent) = dst.parent() { + fs::create_dir_all(parent).expect("mkdir"); + } + fs::write(dst, body).expect("write"); + } + + fn git(&self, args: &[&str]) { + let mut command = Command::new("git"); + command.args(args).current_dir(self.0.path()); + for (key, value) in GIT_ENV { + command.env(key, value); } - BoundaryFixture(dir) + let output = command.output().expect("run git"); + assert!( + output.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + + fn commit(&self, message: &str) { + self.git(&["add", "--all"]); + self.git(&["commit", "--quiet", "--message", message]); } fn run(&self, args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_codeint")) - .args(args) - .current_dir(self.0.path()) - .output() - .expect("run codeint") + self.run_with_optional_cache(None, args) } - fn check_json(&self, expected_code: i32) -> Value { - let out = self.run(&["check", "--format", "json"]); + fn run_with_optional_cache(&self, cache_dir: Option<&Path>, args: &[&str]) -> Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_codeint")); + command.args(args).current_dir(self.0.path()); + if let Some(cache) = cache_dir { + command.env("CODEINT_CACHE_DIR", cache); + } + command.output().expect("run codeint") + } + + fn run_stdout(&self, cache_dir: Option<&Path>, args: &[&str], expected_code: i32) -> String { + let out = self.run_with_optional_cache(cache_dir, args); assert_eq!( out.status.code(), Some(expected_code), "stderr: {}", String::from_utf8_lossy(&out.stderr) ); - serde_json::from_slice(&out.stdout).expect("valid JSON") + String::from_utf8(out.stdout).expect("utf8") + } + + fn run_json(&self, cache_dir: Option<&Path>, args: &[&str], expected_code: i32) -> Value { + let stdout = self.run_stdout(cache_dir, args, expected_code); + serde_json::from_str(&stdout).expect("valid JSON") + } + + fn check_json(&self, expected_code: i32) -> Value { + self.run_json(None, &["check", "--format", "json"], expected_code) + } + + fn diff_json(&self, cache_dir: &Path, expected_code: i32) -> Value { + self.run_json( + Some(cache_dir), + &["diff", "main", "--format", "json"], + expected_code, + ) } + + fn sarif_boundary_results( + &self, + cache_dir: Option<&Path>, + args: &[&str], + expected_code: i32, + ) -> Vec { + let sarif = self.run_json(cache_dir, args, expected_code); + sarif["runs"][0]["results"] + .as_array() + .expect("SARIF results") + .iter() + .filter(|result| result["ruleId"] == "boundaries") + .cloned() + .collect() + } +} + +fn boundary_findings(report: &Value, source_set: &str) -> Vec { + report["source_sets"][source_set]["boundaries"]["findings"] + .as_array() + .expect("boundaries findings") + .clone() +} + +fn assert_diff_counts( + diff: &Value, + expected_new: usize, + expected_resolved: usize, + expected_unchanged: u64, +) { + assert_eq!(diff["new"].as_array().expect("new").len(), expected_new); + assert_eq!( + diff["resolved"].as_array().expect("resolved").len(), + expected_resolved + ); + assert_eq!(diff["unchanged"], expected_unchanged); } #[test] @@ -108,10 +201,9 @@ fn check_reports_directional_deny_allow_and_public_files_findings_across_formats ]); let json = fixture.check_json(0); - let prod_boundaries = &json["source_sets"]["production"]["boundaries"]; - assert!(prod_boundaries.is_object()); + assert!(json["source_sets"]["production"]["boundaries"].is_object()); assert!(json["source_sets"]["test"].get("boundaries").is_none()); - let findings = prod_boundaries["findings"].as_array().expect("findings"); + let findings = boundary_findings(&json, "production"); assert_eq!(findings.len(), 3, "got: {findings:?}"); let domain_to_infra = findings @@ -143,23 +235,13 @@ fn check_reports_directional_deny_allow_and_public_files_findings_across_formats assert_eq!(app_deep_import["source_zone"], "app"); assert_eq!(app_deep_import["target_zone"], "domain"); - let toon = fixture.run(&["check"]); - assert_eq!(toon.status.code(), Some(0)); - let toon_text = String::from_utf8(toon.stdout).expect("utf8"); + let toon_text = fixture.run_stdout(None, &["check"], 0); assert!(toon_text.contains("boundaries:")); assert!(toon_text.contains("src/domain/internal.ts")); assert!(toon_text.contains("src/infra/db.ts")); assert!(toon_text.contains("Domain logic must not depend on infrastructure")); - let sarif_out = fixture.run(&["check", "--format", "sarif"]); - assert_eq!(sarif_out.status.code(), Some(0)); - let sarif: Value = serde_json::from_slice(&sarif_out.stdout).expect("valid SARIF"); - let boundary_sarif: Vec<&Value> = sarif["runs"][0]["results"] - .as_array() - .expect("SARIF results") - .iter() - .filter(|result| result["ruleId"] == "boundaries") - .collect(); + let boundary_sarif = fixture.sarif_boundary_results(None, &["check", "--format", "sarif"], 0); assert_eq!(boundary_sarif.len(), 3); assert!(boundary_sarif.iter().any(|result| { let text = result["message"]["text"].as_str().unwrap_or_default(); @@ -168,9 +250,7 @@ fn check_reports_directional_deny_allow_and_public_files_findings_across_formats && text.contains("Domain logic must not depend on infrastructure") })); - let md = fixture.run(&["check", "--format", "markdown"]); - assert_eq!(md.status.code(), Some(0)); - let md_text = String::from_utf8(md.stdout).expect("utf8"); + let md_text = fixture.run_stdout(None, &["check", "--format", "markdown"], 0); assert!(md_text.contains("### Boundaries")); assert!(md_text.contains("`src/domain/internal.ts`")); assert!(md_text.contains("`src/infra/db.ts`")); @@ -283,10 +363,7 @@ fn check_strict_zones_flags_unzoned_production_files() { ("src/orphan.ts", "export const orphan = 2;\n"), ]); - let json = fixture.check_json(0); - let findings = json["source_sets"]["production"]["boundaries"]["findings"] - .as_array() - .expect("findings"); + let findings = boundary_findings(&fixture.check_json(0), "production"); assert_eq!(findings.len(), 1); assert_eq!(findings[0]["kind"], "unzoned_file"); assert_eq!(findings[0]["importer"], "src/orphan.ts"); @@ -337,10 +414,7 @@ fn check_enforces_boundaries_across_python_and_typescript() { ), ]); - let json = fixture.check_json(0); - let findings = json["source_sets"]["production"]["boundaries"]["findings"] - .as_array() - .expect("findings"); + let findings = boundary_findings(&fixture.check_json(0), "production"); assert_eq!(findings.len(), 2, "got: {findings:?}"); assert!( findings @@ -402,112 +476,64 @@ fn check_enforces_boundary_budget_overlap_precedence_and_optional_test_source_se ]); let json = fixture.check_json(1); - let prod_findings = json["source_sets"]["production"]["boundaries"]["findings"] - .as_array() - .expect("production boundaries findings"); + let prod_findings = boundary_findings(&json, "production"); assert_eq!(prod_findings.len(), 1); assert_eq!(prod_findings[0]["source_zone"], "domain"); assert_eq!(prod_findings[0]["target_zone"], "infra"); - let test_findings = json["source_sets"]["test"]["boundaries"]["findings"] - .as_array() - .expect("test boundaries findings"); + let test_findings = boundary_findings(&json, "test"); assert_eq!(test_findings.len(), 1); assert_eq!(test_findings[0]["kind"], "public_files"); assert_eq!(test_findings[0]["source_zone"], "core"); assert_eq!(test_findings[0]["target_zone"], "domain"); } -const GIT_ENV: [(&str, &str); 6] = [ - ("GIT_CONFIG_GLOBAL", "/dev/null"), - ("GIT_CONFIG_NOSYSTEM", "1"), - ("GIT_AUTHOR_NAME", "Fixture"), - ("GIT_AUTHOR_EMAIL", "fixture@example.invalid"), - ("GIT_COMMITTER_NAME", "Fixture"), - ("GIT_COMMITTER_EMAIL", "fixture@example.invalid"), -]; - -impl BoundaryFixture { - fn write(&self, rel: &str, body: &str) { - let dst = self.0.path().join(rel); - if let Some(parent) = dst.parent() { - fs::create_dir_all(parent).expect("mkdir"); - } - fs::write(dst, body).expect("write"); - } - - fn git(&self, args: &[&str]) { - let mut command = Command::new("git"); - command.args(args).current_dir(self.0.path()); - for (key, value) in GIT_ENV { - command.env(key, value); - } - let output = command.output().expect("run git"); - assert!( - output.status.success(), - "git {args:?} failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - - fn commit(&self, message: &str) { - self.git(&["add", "--all"]); - self.git(&["commit", "--quiet", "--message", message]); - } - - fn run_with_cache(&self, cache_dir: &std::path::Path, args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_codeint")) - .args(args) - .env("CODEINT_CACHE_DIR", cache_dir) - .current_dir(self.0.path()) - .output() - .expect("run codeint") +fn check_preset_findings(preset: &str, files: &[(&str, &str)]) -> Vec { + let config = format!(r#"{{"boundaries":{{"preset":"{preset}"}}}}"#); + let fixture = BoundaryFixture::init(&[("codeint.json", &config)]); + for &(rel, body) in files { + fixture.write(rel, body); } + boundary_findings(&fixture.check_json(0), "production") } #[test] -fn check_supports_layered_and_hexagonal_presets_with_user_overrides() { - let layered = BoundaryFixture::init(&[ - ( - "codeint.json", - r#"{ - "boundaries": { - "preset": "layered" - } +fn check_supports_layered_preset() { + let findings = check_preset_findings( + "layered", + &[ + ("src/infrastructure/db.ts", "export const db = 1;\n"), + ( + "src/domain/order.ts", + "import { db } from '../infrastructure/db';\nexport const order = db;\n", + ), + ( + "src/application/service.ts", + "import { order } from '../domain/order';\nexport const service = order;\n", + ), + ( + "src/presentation/view.ts", + "import { db } from '../infrastructure/db';\nexport const view = db;\n", + ), + ], + ); + assert_eq!(findings.len(), 2, "got: {findings:?}"); + let pairs: Vec<(&str, &str, &str)> = findings + .iter() + .map(|f| { + ( + f["importer"].as_str().unwrap_or_default(), + f["source_zone"].as_str().unwrap_or_default(), + f["target_zone"].as_str().unwrap_or_default(), + ) + }) + .collect(); + assert!(pairs.contains(&("src/domain/order.ts", "domain", "infrastructure"))); + assert!(pairs.contains(&("src/presentation/view.ts", "presentation", "infrastructure"))); } -"#, - ), - ("src/infrastructure/db.ts", "export const db = 1;\n"), - ( - "src/domain/order.ts", - "import { db } from '../infrastructure/db';\nexport const order = db;\n", - ), - ( - "src/application/service.ts", - "import { order } from '../domain/order';\nexport const service = order;\n", - ), - ( - "src/presentation/view.ts", - "import { db } from '../infrastructure/db';\nexport const view = db;\n", - ), - ]); - - let layered_json = layered.check_json(0); - let layered_findings = layered_json["source_sets"]["production"]["boundaries"]["findings"] - .as_array() - .expect("layered findings"); - assert_eq!(layered_findings.len(), 2, "got: {layered_findings:?}"); - assert!(layered_findings.iter().any(|f| { - f["importer"] == "src/domain/order.ts" - && f["source_zone"] == "domain" - && f["target_zone"] == "infrastructure" - })); - assert!(layered_findings.iter().any(|f| { - f["importer"] == "src/presentation/view.ts" - && f["source_zone"] == "presentation" - && f["target_zone"] == "infrastructure" - })); +#[test] +fn check_supports_layered_preset_with_user_overrides() { let layered_override = BoundaryFixture::init(&[ ( "codeint.json", @@ -554,56 +580,45 @@ fn check_supports_layered_and_hexagonal_presets_with_user_overrides() { ), ]); - let override_json = layered_override.check_json(0); - let override_findings = override_json["source_sets"]["production"]["boundaries"]["findings"] - .as_array() - .expect("override findings"); - assert_eq!(override_findings.len(), 2, "got: {override_findings:?}"); - assert!(override_findings.iter().any(|f| { + let findings = boundary_findings(&layered_override.check_json(0), "production"); + assert_eq!(findings.len(), 2, "got: {findings:?}"); + assert!(findings.iter().any(|f| { f["importer"] == "src/business/bad.ts" && f["kind"] == "zone_rule" && f["reason"] == "Domain may import shared helpers only" })); - assert!(override_findings.iter().any(|f| { + assert!(findings.iter().any(|f| { f["importer"] == "src/application/deep.ts" && f["kind"] == "public_files" && f["target"] == "src/business/internal.ts" })); - - let hexagonal = BoundaryFixture::init(&[ - ( - "codeint.json", - r#"{ - "boundaries": { - "preset": "hexagonal" - } } -"#, - ), - ("src/domain/model.ts", "export const model = 1;\n"), - ( - "src/ports/repo.ts", - "import { model } from '../domain/model';\nexport const repo = model;\n", - ), - ( - "src/adapters/http.ts", - "import { repo } from '../ports/repo';\nexport const http = repo;\n", - ), - ( - "src/application/usecase.ts", - "import { repo } from '../ports/repo';\nimport { http } from '../adapters/http';\nexport const run = repo + http;\n", - ), - ]); - let hex_json = hexagonal.check_json(0); - let hex_findings = hex_json["source_sets"]["production"]["boundaries"]["findings"] - .as_array() - .expect("hexagonal findings"); - assert_eq!(hex_findings.len(), 1, "got: {hex_findings:?}"); - assert_eq!(hex_findings[0]["importer"], "src/application/usecase.ts"); - assert_eq!(hex_findings[0]["target"], "src/adapters/http.ts"); - assert_eq!(hex_findings[0]["source_zone"], "application"); - assert_eq!(hex_findings[0]["target_zone"], "adapters"); +#[test] +fn check_supports_hexagonal_preset() { + let findings = check_preset_findings( + "hexagonal", + &[ + ("src/domain/model.ts", "export const model = 1;\n"), + ( + "src/ports/repo.ts", + "import { model } from '../domain/model';\nexport const repo = model;\n", + ), + ( + "src/adapters/http.ts", + "import { repo } from '../ports/repo';\nexport const http = repo;\n", + ), + ( + "src/application/usecase.ts", + "import { repo } from '../ports/repo';\nimport { http } from '../adapters/http';\nexport const run = repo + http;\n", + ), + ], + ); + assert_eq!(findings.len(), 1, "got: {findings:?}"); + assert_eq!(findings[0]["importer"], "src/application/usecase.ts"); + assert_eq!(findings[0]["target"], "src/adapters/http.ts"); + assert_eq!(findings[0]["source_zone"], "application"); + assert_eq!(findings[0]["target_zone"], "adapters"); } #[test] @@ -650,15 +665,7 @@ fn check_enforces_per_source_set_boundary_budgets() { fn diff_classifies_boundary_findings_and_gates_new_regressions_without_failing_on_preexisting() { let cache = tempfile::tempdir().expect("cache tempdir"); let fixture = BoundaryFixture::init(&[ - ( - "codeint.json", - r#"{ - "boundaries": { - "preset": "layered" - } -} -"#, - ), + ("codeint.json", r#"{"boundaries":{"preset":"layered"}}"#), ("src/infrastructure/db.ts", "export const db = 1;\n"), ( "src/domain/legacy.ts", @@ -675,39 +682,30 @@ fn diff_classifies_boundary_findings_and_gates_new_regressions_without_failing_o "src/domain/legacy.ts", "\n\nimport { db } from '../infrastructure/db';\nexport const legacy = db + 1;\n", ); - let no_regression = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "json"]); - assert_eq!( - no_regression.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&no_regression.stderr) + let no_reg_json = fixture.diff_json(cache.path(), 0); + assert_diff_counts( + &no_reg_json["source_sets"]["production"]["boundaries"], + 0, + 0, + 1, ); - let no_reg_json: Value = serde_json::from_slice(&no_regression.stdout).expect("valid JSON"); - let prod_diff = &no_reg_json["source_sets"]["production"]["boundaries"]; - assert_eq!(prod_diff["new"].as_array().expect("new").len(), 0); - assert_eq!(prod_diff["resolved"].as_array().expect("resolved").len(), 0); - assert_eq!(prod_diff["unchanged"], 1); assert!(no_reg_json.get("regressions").is_none()); fixture.write( "src/domain/new_feature.ts", "import { db } from '../infrastructure/db';\nexport const feature = db;\n", ); - let with_regression = - fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "json"]); + let reg_json = fixture.diff_json(cache.path(), 1); + let prod_reg_diff = ®_json["source_sets"]["production"]["boundaries"]; + assert_diff_counts(prod_reg_diff, 1, 0, 1); assert_eq!( - with_regression.status.code(), - Some(1), - "stderr: {}", - String::from_utf8_lossy(&with_regression.stderr) + prod_reg_diff["new"][0]["importer"], + "src/domain/new_feature.ts" + ); + assert_eq!( + prod_reg_diff["new"][0]["target"], + "src/infrastructure/db.ts" ); - let reg_json: Value = serde_json::from_slice(&with_regression.stdout).expect("valid JSON"); - let prod_reg_diff = ®_json["source_sets"]["production"]["boundaries"]; - let new_findings = prod_reg_diff["new"].as_array().expect("new findings"); - assert_eq!(new_findings.len(), 1, "got: {new_findings:?}"); - assert_eq!(new_findings[0]["importer"], "src/domain/new_feature.ts"); - assert_eq!(new_findings[0]["target"], "src/infrastructure/db.ts"); - assert_eq!(prod_reg_diff["unchanged"], 1); let regressions = reg_json["regressions"].as_array().expect("regressions"); assert!( regressions @@ -716,85 +714,51 @@ fn diff_classifies_boundary_findings_and_gates_new_regressions_without_failing_o "got: {regressions:?}" ); - let sarif_out = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "sarif"]); - assert_eq!(sarif_out.status.code(), Some(1)); - let sarif: Value = serde_json::from_slice(&sarif_out.stdout).expect("valid SARIF"); - let sarif_results: Vec<&Value> = sarif["runs"][0]["results"] - .as_array() - .expect("results") - .iter() - .filter(|r| r["ruleId"] == "boundaries") - .collect(); + let sarif_results = fixture.sarif_boundary_results( + Some(cache.path()), + &["diff", "main", "--format", "sarif"], + 1, + ); assert_eq!(sarif_results.len(), 1); assert_eq!( sarif_results[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"], "src/domain/new_feature.ts" ); - let md_out = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "markdown"]); - assert_eq!(md_out.status.code(), Some(1)); - let md_text = String::from_utf8(md_out.stdout).expect("utf8"); + let md_text = fixture.run_stdout( + Some(cache.path()), + &["diff", "main", "--format", "markdown"], + 1, + ); assert!(md_text.contains("| Production | Boundaries |")); assert!(md_text.contains("### New Boundaries Findings")); assert!(md_text.contains("`src/domain/new_feature.ts`")); - let toon_out = fixture.run_with_cache(cache.path(), &["diff", "main"]); - assert_eq!(toon_out.status.code(), Some(1)); - let toon_text = String::from_utf8(toon_out.stdout).expect("utf8"); + let toon_text = fixture.run_stdout(Some(cache.path()), &["diff", "main"], 1); assert!(toon_text.contains("boundaries:")); assert!(toon_text.contains("src/domain/new_feature.ts")); fixture.write( "codeint.json", r#"{ - "boundaries": { - "preset": "layered" - }, + "boundaries": { "preset": "layered" }, "regression_limits": { "production": { - "boundaries": { - "ratio_rise": 1, - "new_findings": "never" - } + "boundaries": { "ratio_rise": 1, "new_findings": "never" } } } -} -"#, - ); - let relaxed = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "json"]); - assert_eq!( - relaxed.status.code(), - Some(0), - "stderr: {}", - String::from_utf8_lossy(&relaxed.stderr) +}"#, ); + fixture.diff_json(cache.path(), 0); - fixture.write( - "codeint.json", - r#"{ - "boundaries": { - "preset": "layered" - } -} -"#, - ); + fixture.write("codeint.json", r#"{"boundaries":{"preset":"layered"}}"#); fixture.write("src/domain/legacy.ts", "export const legacy = 1;\n"); fixture.write("src/domain/new_feature.ts", "export const feature = 2;\n"); - let resolved_out = fixture.run_with_cache(cache.path(), &["diff", "main", "--format", "json"]); - assert_eq!(resolved_out.status.code(), Some(0)); - let resolved_json: Value = serde_json::from_slice(&resolved_out.stdout).expect("valid JSON"); + let resolved_json = fixture.diff_json(cache.path(), 0); let resolved_diff = &resolved_json["source_sets"]["production"]["boundaries"]; - assert_eq!(resolved_diff["new"].as_array().expect("new").len(), 0); - assert_eq!( - resolved_diff["resolved"] - .as_array() - .expect("resolved") - .len(), - 1 - ); + assert_diff_counts(resolved_diff, 0, 1, 0); assert_eq!( resolved_diff["resolved"][0]["importer"], "src/domain/legacy.ts" ); - assert_eq!(resolved_diff["unchanged"], 0); } diff --git a/crates/config/src/boundaries.rs b/crates/config/src/boundaries.rs index c68df8b..66145b6 100644 --- a/crates/config/src/boundaries.rs +++ b/crates/config/src/boundaries.rs @@ -5,7 +5,7 @@ use globset::{GlobBuilder, GlobMatcher, GlobSet}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use crate::codeint_json::{ConfigurationFileError, KeyPath, KeySegment, glob_set}; +use crate::config_error::{ConfigurationFileError, KeyPath, KeySegment, glob_set}; const WILDCARD_ZONE: &str = "*"; @@ -161,105 +161,9 @@ impl Boundaries { pub(crate) fn from_file(file: BoundariesFile) -> Result { let (merged_zones, merged_rules) = merge_preset(file.preset, file.zones, file.rules); let boundaries_key = KeyPath::default().child(KeySegment::Key("boundaries".to_owned())); - let zones_key = boundaries_key.child(KeySegment::Key("zones".to_owned())); - let mut zones = BTreeMap::new(); - for (name, zone_file) in merged_zones { - let zone_key = zones_key.child(KeySegment::Key(name.clone())); - if name.trim().is_empty() || name == WILDCARD_ZONE { - return Err(ConfigurationFileError::InvalidBoundaryZoneName { - key: zone_key, - name, - }); - } - if zone_file.patterns.is_empty() { - return Err(ConfigurationFileError::EmptyBoundaryZonePatterns { - key: zone_key.child(KeySegment::Key("patterns".to_owned())), - zone: name, - }); - } - let patterns_key = zone_key.child(KeySegment::Key("patterns".to_owned())); - let patterns = compile_patterns(&patterns_key, &zone_file.patterns)?; - let public_file_patterns = zone_file.public_files; - let public_files = if public_file_patterns.is_empty() { - None - } else { - let public_key = zone_key.child(KeySegment::Key("public_files".to_owned())); - Some(glob_set(&public_key, &public_file_patterns)?) - }; - zones.insert( - name, - CompiledZone { - patterns, - public_files, - public_file_patterns, - }, - ); - } - - let known_zones: Vec = zones.keys().cloned().collect(); - let rules_key = boundaries_key.child(KeySegment::Key("rules".to_owned())); - let mut rules = Vec::with_capacity(merged_rules.len()); - let mut directive_by_from: BTreeMap = BTreeMap::new(); - - for (index, rule) in merged_rules.into_iter().enumerate() { - let rule_key = rules_key.child(KeySegment::Index(index)); - if rule.from != WILDCARD_ZONE && !zones.contains_key(&rule.from) { - return Err(ConfigurationFileError::UnknownBoundaryZone { - key: rule_key.child(KeySegment::Key("from".to_owned())), - zone: rule.from, - known: known_zones, - }); - } - let (directive, targets, targets_key_name) = match (rule.allow, rule.deny) { - (Some(allow), None) => (BoundaryDirective::Allow, allow, "allow"), - (None, Some(deny)) => (BoundaryDirective::Deny, deny, "deny"), - (Some(_), Some(_)) => { - return Err(ConfigurationFileError::ConflictingBoundaryRule { - key: rule_key, - from: rule.from, - }); - } - (None, None) => { - return Err(ConfigurationFileError::MissingBoundaryRuleDirective { - key: rule_key, - from: rule.from, - }); - } - }; - if let Some(&previous) = directive_by_from.get(&rule.from) - && previous != directive - { - return Err(ConfigurationFileError::ConflictingBoundaryDirectives { - key: rule_key, - from: rule.from, - }); - } - directive_by_from.insert(rule.from.clone(), directive); - - let targets_key = rule_key.child(KeySegment::Key(targets_key_name.to_owned())); - for (target_index, target) in targets.iter().enumerate() { - if target != WILDCARD_ZONE && !zones.contains_key(target) { - return Err(ConfigurationFileError::UnknownBoundaryZone { - key: targets_key.child(KeySegment::Index(target_index)), - zone: target.clone(), - known: known_zones, - }); - } - } - rules.push(CompiledRule { - from: rule.from, - directive, - targets, - reason: rule.reason.filter(|text| !text.trim().is_empty()), - }); - } - - let source_sets = if file.source_sets.is_empty() { - vec![SourceSet::Production] - } else { - file.source_sets.into_iter().map(SourceSet::from).collect() - }; - + let zones = compile_zones(&boundaries_key, merged_zones)?; + let rules = compile_rules(&boundaries_key, &zones, merged_rules)?; + let source_sets = resolve_source_sets(file.source_sets); Ok(Boundaries { zones, rules, @@ -404,6 +308,159 @@ impl Boundaries { } } +fn compile_zones( + boundaries_key: &KeyPath, + merged_zones: BTreeMap, +) -> Result, ConfigurationFileError> { + let zones_key = boundaries_key.child(KeySegment::Key("zones".to_owned())); + let mut zones = BTreeMap::new(); + for (name, zone_file) in merged_zones { + let (compiled_name, compiled_zone) = compile_zone(&zones_key, name, zone_file)?; + zones.insert(compiled_name, compiled_zone); + } + Ok(zones) +} + +fn compile_zone( + zones_key: &KeyPath, + name: String, + zone_file: BoundaryZoneFile, +) -> Result<(String, CompiledZone), ConfigurationFileError> { + let zone_key = zones_key.child(KeySegment::Key(name.clone())); + if name.trim().is_empty() || name == WILDCARD_ZONE { + return Err(ConfigurationFileError::InvalidBoundaryZoneName { + key: zone_key, + name, + }); + } + let patterns_key = zone_key.child(KeySegment::Key("patterns".to_owned())); + if zone_file.patterns.is_empty() { + return Err(ConfigurationFileError::EmptyBoundaryZonePatterns { + key: patterns_key, + zone: name, + }); + } + let patterns = compile_patterns(&patterns_key, &zone_file.patterns)?; + let public_file_patterns = zone_file.public_files; + let public_files = if public_file_patterns.is_empty() { + None + } else { + let public_key = zone_key.child(KeySegment::Key("public_files".to_owned())); + Some(glob_set(&public_key, &public_file_patterns)?) + }; + Ok(( + name, + CompiledZone { + patterns, + public_files, + public_file_patterns, + }, + )) +} + +fn compile_rules( + boundaries_key: &KeyPath, + zones: &BTreeMap, + merged_rules: Vec, +) -> Result, ConfigurationFileError> { + let known_zones: Vec = zones.keys().cloned().collect(); + let rules_key = boundaries_key.child(KeySegment::Key("rules".to_owned())); + let mut rules = Vec::with_capacity(merged_rules.len()); + let mut directive_by_from: BTreeMap = BTreeMap::new(); + for (index, rule) in merged_rules.into_iter().enumerate() { + let rule_key = rules_key.child(KeySegment::Index(index)); + rules.push(compile_rule( + &rule_key, + rule, + zones, + &known_zones, + &mut directive_by_from, + )?); + } + Ok(rules) +} + +fn compile_rule( + rule_key: &KeyPath, + rule: BoundaryRuleFile, + zones: &BTreeMap, + known_zones: &[String], + directive_by_from: &mut BTreeMap, +) -> Result { + if rule.from != WILDCARD_ZONE && !zones.contains_key(&rule.from) { + return Err(ConfigurationFileError::UnknownBoundaryZone { + key: rule_key.child(KeySegment::Key("from".to_owned())), + zone: rule.from, + known: known_zones.to_vec(), + }); + } + let (directive, targets, targets_key_name) = + extract_rule_directive(rule_key, &rule.from, rule.allow, rule.deny)?; + if let Some(&previous) = directive_by_from.get(&rule.from) + && previous != directive + { + return Err(ConfigurationFileError::ConflictingBoundaryDirectives { + key: rule_key.clone(), + from: rule.from, + }); + } + directive_by_from.insert(rule.from.clone(), directive); + let targets_key = rule_key.child(KeySegment::Key(targets_key_name.to_owned())); + validate_rule_targets(&targets_key, &targets, zones, known_zones)?; + Ok(CompiledRule { + from: rule.from, + directive, + targets, + reason: rule.reason.filter(|text| !text.trim().is_empty()), + }) +} + +fn extract_rule_directive( + rule_key: &KeyPath, + from: &str, + allow: Option>, + deny: Option>, +) -> Result<(BoundaryDirective, Vec, &'static str), ConfigurationFileError> { + match (allow, deny) { + (Some(allow), None) => Ok((BoundaryDirective::Allow, allow, "allow")), + (None, Some(deny)) => Ok((BoundaryDirective::Deny, deny, "deny")), + (Some(_), Some(_)) => Err(ConfigurationFileError::ConflictingBoundaryRule { + key: rule_key.clone(), + from: from.to_owned(), + }), + (None, None) => Err(ConfigurationFileError::MissingBoundaryRuleDirective { + key: rule_key.clone(), + from: from.to_owned(), + }), + } +} + +fn validate_rule_targets( + targets_key: &KeyPath, + targets: &[String], + zones: &BTreeMap, + known_zones: &[String], +) -> Result<(), ConfigurationFileError> { + for (target_index, target) in targets.iter().enumerate() { + if target != WILDCARD_ZONE && !zones.contains_key(target) { + return Err(ConfigurationFileError::UnknownBoundaryZone { + key: targets_key.child(KeySegment::Index(target_index)), + zone: target.clone(), + known: known_zones.to_vec(), + }); + } + } + Ok(()) +} + +fn resolve_source_sets(source_sets: Vec) -> Vec { + if source_sets.is_empty() { + vec![SourceSet::Production] + } else { + source_sets.into_iter().map(SourceSet::from).collect() + } +} + fn compile_patterns( key: &KeyPath, globs: &[String], diff --git a/crates/config/src/codeint_json.rs b/crates/config/src/codeint_json.rs index d54e891..98d2f2d 100644 --- a/crates/config/src/codeint_json.rs +++ b/crates/config/src/codeint_json.rs @@ -1,13 +1,15 @@ use std::collections::BTreeMap; -use std::fmt; use std::path::{Path, PathBuf}; use codeint_model::{Metric, RepoPath, SourceSet}; use crate::RegressionLimits; use crate::boundaries::{Boundaries, BoundariesFile}; +use crate::config_error::{ + CONFIGURATION_FILE_NAME, ConfigurationFileError, JsonType, KeyPath, KeySegment, glob_set, +}; use crate::regression_limits::RegressionLimitSetting; -use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; +use globset::GlobSet; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -20,7 +22,6 @@ pub use starter::{ write_starter_configuration, }; -const CONFIGURATION_FILE_NAME: &str = "codeint.json"; const DEFAULT_PLUGIN_MEMORY_MB: u64 = 64; const DEFAULT_PLUGIN_TIMEOUT_MS: u64 = 5_000; @@ -306,138 +307,6 @@ impl SourceSetOverrides { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum JsonType { - Object, - Array, - String, - Number, - Integer, - Boolean, - Null, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum KeySegment { - Key(String), - Index(usize), -} - -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct KeyPath(Vec); - -#[derive(Debug, thiserror::Error)] -pub enum ConfigurationFileError { - #[error("cannot read {CONFIGURATION_FILE_NAME}")] - Unreadable(#[source] std::io::Error), - #[error("{CONFIGURATION_FILE_NAME} is not valid JSON")] - NotJson(#[source] serde_json::Error), - #[error( - "{CONFIGURATION_FILE_NAME} has an unknown key {key}; the keys allowed there are {}", - allowed.join(", ") - )] - UnknownKey { key: KeyPath, allowed: Vec }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} must be {}, not {}", - any_of(expected), - found.with_article() - )] - WrongType { - key: KeyPath, - expected: Vec, - found: JsonType, - }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} must be between {minimum} and {maximum}, not {found}" - )] - OutOfRange { - key: KeyPath, - minimum: f64, - maximum: f64, - found: f64, - }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} must be one of {}, not {found}", - allowed.join(", ") - )] - NotOneOf { - key: KeyPath, - allowed: Vec, - found: Value, - }, - #[error("{CONFIGURATION_FILE_NAME}: {key} needs the key {missing}")] - MissingKey { key: KeyPath, missing: String }, - #[error( - "{CONFIGURATION_FILE_NAME} names an unknown Language plugin {name} at {key}; the Language plugins are {}", - known.join(", ") - )] - UnknownLanguagePlugin { - key: KeyPath, - name: String, - known: Vec, - }, - #[error("{CONFIGURATION_FILE_NAME}: {key} is not a valid glob")] - InvalidGlob { - key: KeyPath, - #[source] - source: globset::Error, - }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} must be a 64-character hexadecimal SHA-256 digest, not {found:?}" - )] - InvalidSha256 { key: KeyPath, found: String }, - #[error("{CONFIGURATION_FILE_NAME}: {key} must not be empty")] - EmptyPluginField { key: KeyPath }, - #[error("{CONFIGURATION_FILE_NAME}: {key} for Plugin {name:?} must set either path or url")] - MissingPluginSource { key: KeyPath, name: String }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} for Plugin {name:?} must set either path or url, not both" - )] - AmbiguousPluginSource { key: KeyPath, name: String }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} for Plugin {name:?} must use an HTTPS URL (https://), not {url:?}" - )] - NonHttpsPluginUrl { - key: KeyPath, - name: String, - url: String, - }, - #[error( - "{CONFIGURATION_FILE_NAME} targets codeint v{config_version} via $schema, which is newer than this binary (v{binary_version})" - )] - NewerSchemaVersion { - config_version: String, - binary_version: String, - }, - #[error("{CONFIGURATION_FILE_NAME}: {key} has invalid boundary zone name {name:?}")] - InvalidBoundaryZoneName { key: KeyPath, name: String }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} for boundary zone {zone:?} must list at least one glob pattern" - )] - EmptyBoundaryZonePatterns { key: KeyPath, zone: String }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} references unknown boundary zone {zone:?}; known zones are {}", - known.join(", ") - )] - UnknownBoundaryZone { - key: KeyPath, - zone: String, - known: Vec, - }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} for boundary zone {from:?} must set either allow or deny, not both" - )] - ConflictingBoundaryRule { key: KeyPath, from: String }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} for boundary zone {from:?} must set either allow or deny" - )] - MissingBoundaryRuleDirective { key: KeyPath, from: String }, - #[error( - "{CONFIGURATION_FILE_NAME}: {key} mixes allow and deny directives for boundary zone {from:?}" - )] - ConflictingBoundaryDirectives { key: KeyPath, from: String }, -} - #[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] #[serde(deny_unknown_fields)] #[schemars( @@ -983,100 +852,6 @@ fn source_set_overrides( Ok(SourceSetOverrides { by_precedence }) } -pub(crate) fn glob_set(key: &KeyPath, globs: &[String]) -> Result { - let mut builder = GlobSetBuilder::new(); - for (index, glob) in globs.iter().enumerate() { - let compiled = GlobBuilder::new(glob) - .literal_separator(true) - .backslash_escape(true) - .build() - .map_err(|source| ConfigurationFileError::InvalidGlob { - key: key.child(KeySegment::Index(index)), - source, - })?; - builder.add(compiled); - } - builder - .build() - .map_err(|source| ConfigurationFileError::InvalidGlob { - key: key.clone(), - source, - }) -} - -impl KeyPath { - pub(crate) fn child(&self, segment: KeySegment) -> KeyPath { - let mut segments = self.0.clone(); - segments.push(segment); - KeyPath(segments) - } -} - -impl fmt::Display for KeyPath { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - for (position, segment) in self.0.iter().enumerate() { - match segment { - KeySegment::Key(key) if position == 0 => write!(formatter, "{key}")?, - KeySegment::Key(key) => write!(formatter, ".{key}")?, - KeySegment::Index(index) => write!(formatter, "[{index}]")?, - } - } - Ok(()) - } -} - -impl JsonType { - fn of(value: &Value) -> JsonType { - match value { - Value::Object(_) => JsonType::Object, - Value::Array(_) => JsonType::Array, - Value::String(_) => JsonType::String, - Value::Number(number) if number.is_i64() || number.is_u64() => JsonType::Integer, - Value::Number(_) => JsonType::Number, - Value::Bool(_) => JsonType::Boolean, - Value::Null => JsonType::Null, - } - } - - fn from_schema_name(name: &str) -> Option { - match name { - "object" => Some(JsonType::Object), - "array" => Some(JsonType::Array), - "string" => Some(JsonType::String), - "number" => Some(JsonType::Number), - "integer" => Some(JsonType::Integer), - "boolean" => Some(JsonType::Boolean), - "null" => Some(JsonType::Null), - _ => None, - } - } - - fn accepts(self, value: &Value) -> bool { - let found = JsonType::of(value); - found == self || (self == JsonType::Number && found == JsonType::Integer) - } - - fn with_article(self) -> &'static str { - match self { - JsonType::Object => "an object", - JsonType::Array => "an array", - JsonType::String => "a string", - JsonType::Number => "a number", - JsonType::Integer => "an integer", - JsonType::Boolean => "a boolean", - JsonType::Null => "null", - } - } -} - -fn any_of(types: &[JsonType]) -> String { - types - .iter() - .map(|json_type| json_type.with_article()) - .collect::>() - .join(" or ") -} - const OFFICIAL_SCHEMA_PREFIX: &str = "https://raw.githubusercontent.com/avidianity/codeint/v"; const OFFICIAL_SCHEMA_SUFFIX: &str = "/schema/codeint.schema.json"; diff --git a/crates/config/src/config_error.rs b/crates/config/src/config_error.rs new file mode 100644 index 0000000..1b2a8a2 --- /dev/null +++ b/crates/config/src/config_error.rs @@ -0,0 +1,232 @@ +use std::fmt; + +use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; +use serde_json::Value; + +pub(crate) const CONFIGURATION_FILE_NAME: &str = "codeint.json"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JsonType { + Object, + Array, + String, + Number, + Integer, + Boolean, + Null, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeySegment { + Key(String), + Index(usize), +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct KeyPath(Vec); + +#[derive(Debug, thiserror::Error)] +pub enum ConfigurationFileError { + #[error("cannot read {CONFIGURATION_FILE_NAME}")] + Unreadable(#[source] std::io::Error), + #[error("{CONFIGURATION_FILE_NAME} is not valid JSON")] + NotJson(#[source] serde_json::Error), + #[error( + "{CONFIGURATION_FILE_NAME} has an unknown key {key}; the keys allowed there are {}", + allowed.join(", ") + )] + UnknownKey { key: KeyPath, allowed: Vec }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} must be {}, not {}", + any_of(expected), + found.with_article() + )] + WrongType { + key: KeyPath, + expected: Vec, + found: JsonType, + }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} must be between {minimum} and {maximum}, not {found}" + )] + OutOfRange { + key: KeyPath, + minimum: f64, + maximum: f64, + found: f64, + }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} must be one of {}, not {found}", + allowed.join(", ") + )] + NotOneOf { + key: KeyPath, + allowed: Vec, + found: Value, + }, + #[error("{CONFIGURATION_FILE_NAME}: {key} needs the key {missing}")] + MissingKey { key: KeyPath, missing: String }, + #[error( + "{CONFIGURATION_FILE_NAME} names an unknown Language plugin {name} at {key}; the Language plugins are {}", + known.join(", ") + )] + UnknownLanguagePlugin { + key: KeyPath, + name: String, + known: Vec, + }, + #[error("{CONFIGURATION_FILE_NAME}: {key} is not a valid glob")] + InvalidGlob { + key: KeyPath, + #[source] + source: globset::Error, + }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} must be a 64-character hexadecimal SHA-256 digest, not {found:?}" + )] + InvalidSha256 { key: KeyPath, found: String }, + #[error("{CONFIGURATION_FILE_NAME}: {key} must not be empty")] + EmptyPluginField { key: KeyPath }, + #[error("{CONFIGURATION_FILE_NAME}: {key} for Plugin {name:?} must set either path or url")] + MissingPluginSource { key: KeyPath, name: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} for Plugin {name:?} must set either path or url, not both" + )] + AmbiguousPluginSource { key: KeyPath, name: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} for Plugin {name:?} must use an HTTPS URL (https://), not {url:?}" + )] + NonHttpsPluginUrl { + key: KeyPath, + name: String, + url: String, + }, + #[error( + "{CONFIGURATION_FILE_NAME} targets codeint v{config_version} via $schema, which is newer than this binary (v{binary_version})" + )] + NewerSchemaVersion { + config_version: String, + binary_version: String, + }, + #[error("{CONFIGURATION_FILE_NAME}: {key} has invalid boundary zone name {name:?}")] + InvalidBoundaryZoneName { key: KeyPath, name: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} for boundary zone {zone:?} must list at least one glob pattern" + )] + EmptyBoundaryZonePatterns { key: KeyPath, zone: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} references unknown boundary zone {zone:?}; known zones are {}", + known.join(", ") + )] + UnknownBoundaryZone { + key: KeyPath, + zone: String, + known: Vec, + }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} for boundary zone {from:?} must set either allow or deny, not both" + )] + ConflictingBoundaryRule { key: KeyPath, from: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} for boundary zone {from:?} must set either allow or deny" + )] + MissingBoundaryRuleDirective { key: KeyPath, from: String }, + #[error( + "{CONFIGURATION_FILE_NAME}: {key} mixes allow and deny directives for boundary zone {from:?}" + )] + ConflictingBoundaryDirectives { key: KeyPath, from: String }, +} + +pub(crate) fn glob_set(key: &KeyPath, globs: &[String]) -> Result { + let mut builder = GlobSetBuilder::new(); + for (index, glob) in globs.iter().enumerate() { + let compiled = GlobBuilder::new(glob) + .literal_separator(true) + .backslash_escape(true) + .build() + .map_err(|source| ConfigurationFileError::InvalidGlob { + key: key.child(KeySegment::Index(index)), + source, + })?; + builder.add(compiled); + } + builder + .build() + .map_err(|source| ConfigurationFileError::InvalidGlob { + key: key.clone(), + source, + }) +} + +impl KeyPath { + pub(crate) fn child(&self, segment: KeySegment) -> KeyPath { + let mut segments = self.0.clone(); + segments.push(segment); + KeyPath(segments) + } +} + +impl fmt::Display for KeyPath { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + for (position, segment) in self.0.iter().enumerate() { + match segment { + KeySegment::Key(key) if position == 0 => write!(formatter, "{key}")?, + KeySegment::Key(key) => write!(formatter, ".{key}")?, + KeySegment::Index(index) => write!(formatter, "[{index}]")?, + } + } + Ok(()) + } +} + +impl JsonType { + pub(crate) fn of(value: &Value) -> JsonType { + match value { + Value::Object(_) => JsonType::Object, + Value::Array(_) => JsonType::Array, + Value::String(_) => JsonType::String, + Value::Number(number) if number.is_i64() || number.is_u64() => JsonType::Integer, + Value::Number(_) => JsonType::Number, + Value::Bool(_) => JsonType::Boolean, + Value::Null => JsonType::Null, + } + } + + pub(crate) fn from_schema_name(name: &str) -> Option { + match name { + "object" => Some(JsonType::Object), + "array" => Some(JsonType::Array), + "string" => Some(JsonType::String), + "number" => Some(JsonType::Number), + "integer" => Some(JsonType::Integer), + "boolean" => Some(JsonType::Boolean), + "null" => Some(JsonType::Null), + _ => None, + } + } + + pub(crate) fn accepts(self, value: &Value) -> bool { + let found = JsonType::of(value); + found == self || (self == JsonType::Number && found == JsonType::Integer) + } + + pub(crate) fn with_article(self) -> &'static str { + match self { + JsonType::Object => "an object", + JsonType::Array => "an array", + JsonType::String => "a string", + JsonType::Number => "a number", + JsonType::Integer => "an integer", + JsonType::Boolean => "a boolean", + JsonType::Null => "null", + } + } +} + +fn any_of(types: &[JsonType]) -> String { + types + .iter() + .map(|json_type| json_type.with_article()) + .collect::>() + .join(" or ") +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 83f5639..642a0b3 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -7,6 +7,7 @@ use clap::{Parser, Subcommand}; mod boundaries; mod calendar_day; mod codeint_json; +mod config_error; mod regression_limits; mod result_cache_folder; @@ -15,12 +16,12 @@ pub use boundaries::{ }; pub use calendar_day::{CalendarDay, CalendarDayError}; pub use codeint_json::{ - Budget, Budgets, Configuration, ConfigurationFileError, DetectedLanguage, JsonType, KeyPath, - KeySegment, LanguageCoverage, Languages, PluginDeclaration, PluginKind, PluginLimits, - PluginSource, Sha256Digest, SourceSetOverrides, StarterConfigurationError, - configuration_schema, published_schema_address, read_configuration, + Budget, Budgets, Configuration, DetectedLanguage, LanguageCoverage, Languages, + PluginDeclaration, PluginKind, PluginLimits, PluginSource, Sha256Digest, SourceSetOverrides, + StarterConfigurationError, configuration_schema, published_schema_address, read_configuration, write_starter_configuration, }; +pub use config_error::{ConfigurationFileError, JsonType, KeyPath, KeySegment}; pub use regression_limits::{NewFindingsRule, RatioRise, RegressionLimit, RegressionLimits}; const DEFAULT_PLUGIN_DOWNLOAD_TIMEOUT_SECONDS: u64 = 60; @@ -291,46 +292,62 @@ struct ReportArguments { pub fn read_invocation() -> Result { let arguments = Arguments::parse(); let current_folder = std::env::current_dir().map_err(ConfigError::CurrentFolder)?; - let command = match arguments.command { + let command = build_command(¤t_folder, arguments.command)?; + Ok(Invocation { command }) +} + +fn build_command( + current_folder: &Path, + arguments: CommandArguments, +) -> Result { + match arguments { CommandArguments::Check { path, report } => { - build_check_command(¤t_folder, path, report)? + build_check_command(current_folder, path, report) } CommandArguments::Diff { base_ref, head_ref, report, - } => build_diff_command(¤t_folder, base_ref, head_ref, report)?, + } => build_diff_command(current_folder, base_ref, head_ref, report), CommandArguments::Trend { since, output, format, - } => Command::Trend { - folder: current_folder.clone(), - range: since.map_or( - TrendRange::Latest(LATEST_COMMITS_OF_A_TREND), - TrendRange::Since, - ), - destination: report_destination(¤t_folder, output)?, - format, - result_cache: result_cache_folder_of_this_process(¤t_folder), - plugin_host: plugin_host_config_of_this_process(¤t_folder), - }, - CommandArguments::Init => Command::Init { - folder: current_folder, - }, - CommandArguments::Update { check, version } => build_update_command(check, version), - CommandArguments::Mcp => Command::Mcp { - result_cache: result_cache_folder_of_this_process(¤t_folder), - plugin_host: plugin_host_config_of_this_process(¤t_folder), - folder: current_folder, - }, - CommandArguments::Guard { path, format } => Command::Guard { - folder: current_folder, + } => build_trend_command(current_folder, since, output, format), + CommandArguments::Init => Ok(Command::Init { + folder: current_folder.to_path_buf(), + }), + CommandArguments::Update { check, version } => Ok(build_update_command(check, version)), + CommandArguments::Mcp => Ok(Command::Mcp { + result_cache: result_cache_folder_of_this_process(current_folder), + plugin_host: plugin_host_config_of_this_process(current_folder), + folder: current_folder.to_path_buf(), + }), + CommandArguments::Guard { path, format } => Ok(Command::Guard { + folder: current_folder.to_path_buf(), target: path, format, - }, - }; - Ok(Invocation { command }) + }), + } +} + +fn build_trend_command( + current_folder: &Path, + since: Option, + output: Option, + format: TrendFormat, +) -> Result { + Ok(Command::Trend { + folder: current_folder.to_path_buf(), + range: since.map_or( + TrendRange::Latest(LATEST_COMMITS_OF_A_TREND), + TrendRange::Since, + ), + destination: report_destination(current_folder, output)?, + format, + result_cache: result_cache_folder_of_this_process(current_folder), + plugin_host: plugin_host_config_of_this_process(current_folder), + }) } fn build_check_command( diff --git a/crates/metrics/src/boundaries.rs b/crates/metrics/src/boundaries.rs index f3af495..0188a42 100644 --- a/crates/metrics/src/boundaries.rs +++ b/crates/metrics/src/boundaries.rs @@ -73,130 +73,9 @@ struct PendingFinding { impl Boundaries { pub fn measure(model: &CodeModel, policy: &dyn BoundaryPolicy) -> Boundaries { - let mut resolved_imports = 0usize; - let mut pending = Vec::new(); - - for runtime_import in &model.runtime_imports { - let ImportResolution::Resolved(target) = &runtime_import.resolution else { - continue; - }; - resolved_imports += 1; - let (Some(source_zone), Some(target_zone)) = ( - policy.zone_of(&runtime_import.importer), - policy.zone_of(target), - ) else { - continue; - }; - if source_zone == target_zone { - continue; - } - match policy.check_import(source_zone, target_zone) { - BoundaryEdgeCheck::DeniedByDenyRule { reason } => { - pending.push(PendingFinding { - kind: BoundaryFindingKind::ZoneRule, - importer: runtime_import.importer.clone(), - target: Some(target.clone()), - specifier: Some(runtime_import.specifier.clone()), - source_zone: Some(source_zone.to_owned()), - target_zone: Some(target_zone.to_owned()), - message: format_zone_rule_message( - source_zone, - target_zone, - "is denied from importing", - reason.as_deref(), - ), - reason, - }); - } - BoundaryEdgeCheck::DeniedByAllowRule { reason } => { - pending.push(PendingFinding { - kind: BoundaryFindingKind::ZoneRule, - importer: runtime_import.importer.clone(), - target: Some(target.clone()), - specifier: Some(runtime_import.specifier.clone()), - source_zone: Some(source_zone.to_owned()), - target_zone: Some(target_zone.to_owned()), - message: format_zone_rule_message( - source_zone, - target_zone, - "is not allowed to import", - reason.as_deref(), - ), - reason, - }); - } - BoundaryEdgeCheck::Allowed => { - if policy.has_public_files(target_zone) - && !policy.is_public_file(target_zone, target) - { - pending.push(PendingFinding { - kind: BoundaryFindingKind::PublicFiles, - importer: runtime_import.importer.clone(), - target: Some(target.clone()), - specifier: Some(runtime_import.specifier.clone()), - source_zone: Some(source_zone.to_owned()), - target_zone: Some(target_zone.to_owned()), - reason: None, - message: format!( - "zone {source_zone:?} deep-imports non-public file {target} of zone {target_zone:?}" - ), - }); - } - } - } - } - - if policy.strict_zones() { - for file in &model.files { - if policy.zone_of(&file.path).is_none() { - pending.push(PendingFinding { - kind: BoundaryFindingKind::UnzonedFile, - importer: file.path.clone(), - target: None, - specifier: None, - source_zone: None, - target_zone: None, - reason: None, - message: format!( - "file {} does not belong to any configured zone", - file.path - ), - }); - } - } - } - - pending.sort_by(|left, right| { - left.importer - .cmp(&right.importer) - .then_with(|| left.target.cmp(&right.target)) - .then_with(|| left.kind.cmp(&right.kind)) - .then_with(|| left.specifier.cmp(&right.specifier)) - }); - - let mut ids = FindingIds::for_key(BOUNDARIES_METRIC_KEY); - let findings = pending - .into_iter() - .map(|item| { - let kind_hash = token_text_hash(item.kind.key()); - let id = match &item.target { - Some(target) => ids.next_in_source_order([&item.importer, target], [kind_hash]), - None => ids.next_in_source_order([&item.importer], [kind_hash]), - }; - BoundaryFinding { - id, - kind: item.kind, - importer: item.importer, - target: item.target, - specifier: item.specifier, - source_zone: item.source_zone, - target_zone: item.target_zone, - reason: item.reason, - message: item.message, - } - }) - .collect(); - + let (resolved_imports, mut pending) = evaluate_imports(model, policy); + collect_unzoned_files(model, policy, &mut pending); + let findings = assign_finding_ids(pending); Boundaries { resolved_imports, findings, @@ -222,6 +101,174 @@ impl Boundaries { } } +fn evaluate_imports( + model: &CodeModel, + policy: &dyn BoundaryPolicy, +) -> (usize, Vec) { + let mut resolved_imports = 0usize; + let mut pending = Vec::new(); + for runtime_import in &model.runtime_imports { + let ImportResolution::Resolved(target) = &runtime_import.resolution else { + continue; + }; + resolved_imports += 1; + if let Some(finding) = check_import_edge( + &runtime_import.importer, + target, + &runtime_import.specifier, + policy, + ) { + pending.push(finding); + } + } + (resolved_imports, pending) +} + +fn check_import_edge( + importer: &RepoPath, + target: &RepoPath, + specifier: &str, + policy: &dyn BoundaryPolicy, +) -> Option { + let (Some(source_zone), Some(target_zone)) = (policy.zone_of(importer), policy.zone_of(target)) + else { + return None; + }; + if source_zone == target_zone { + return None; + } + match policy.check_import(source_zone, target_zone) { + BoundaryEdgeCheck::DeniedByDenyRule { reason } => Some(zone_rule_finding( + importer, + target, + specifier, + source_zone, + target_zone, + "is denied from importing", + reason, + )), + BoundaryEdgeCheck::DeniedByAllowRule { reason } => Some(zone_rule_finding( + importer, + target, + specifier, + source_zone, + target_zone, + "is not allowed to import", + reason, + )), + BoundaryEdgeCheck::Allowed => check_public_files_edge( + importer, + target, + specifier, + source_zone, + target_zone, + policy, + ), + } +} + +fn zone_rule_finding( + importer: &RepoPath, + target: &RepoPath, + specifier: &str, + source_zone: &str, + target_zone: &str, + verb: &str, + reason: Option, +) -> PendingFinding { + PendingFinding { + kind: BoundaryFindingKind::ZoneRule, + importer: importer.clone(), + target: Some(target.clone()), + specifier: Some(specifier.to_owned()), + source_zone: Some(source_zone.to_owned()), + target_zone: Some(target_zone.to_owned()), + message: format_zone_rule_message(source_zone, target_zone, verb, reason.as_deref()), + reason, + } +} + +fn check_public_files_edge( + importer: &RepoPath, + target: &RepoPath, + specifier: &str, + source_zone: &str, + target_zone: &str, + policy: &dyn BoundaryPolicy, +) -> Option { + if !policy.has_public_files(target_zone) || policy.is_public_file(target_zone, target) { + return None; + } + Some(PendingFinding { + kind: BoundaryFindingKind::PublicFiles, + importer: importer.clone(), + target: Some(target.clone()), + specifier: Some(specifier.to_owned()), + source_zone: Some(source_zone.to_owned()), + target_zone: Some(target_zone.to_owned()), + reason: None, + message: format!( + "zone {source_zone:?} deep-imports non-public file {target} of zone {target_zone:?}" + ), + }) +} + +fn collect_unzoned_files( + model: &CodeModel, + policy: &dyn BoundaryPolicy, + pending: &mut Vec, +) { + if !policy.strict_zones() { + return; + } + for file in &model.files { + if policy.zone_of(&file.path).is_none() { + pending.push(PendingFinding { + kind: BoundaryFindingKind::UnzonedFile, + importer: file.path.clone(), + target: None, + specifier: None, + source_zone: None, + target_zone: None, + reason: None, + message: format!("file {} does not belong to any configured zone", file.path), + }); + } + } +} + +fn assign_finding_ids(mut pending: Vec) -> Vec { + pending.sort_by(|left, right| { + left.importer + .cmp(&right.importer) + .then_with(|| left.target.cmp(&right.target)) + .then_with(|| left.kind.cmp(&right.kind)) + .then_with(|| left.specifier.cmp(&right.specifier)) + }); + let mut ids = FindingIds::for_key(BOUNDARIES_METRIC_KEY); + pending + .into_iter() + .map(|item| { + let kind_hash = token_text_hash(item.kind.key()); + let id = match &item.target { + Some(target) => ids.next_in_source_order([&item.importer, target], [kind_hash]), + None => ids.next_in_source_order([&item.importer], [kind_hash]), + }; + BoundaryFinding { + id, + kind: item.kind, + importer: item.importer, + target: item.target, + specifier: item.specifier, + source_zone: item.source_zone, + target_zone: item.target_zone, + reason: item.reason, + message: item.message, + } + }) + .collect() +} + fn format_zone_rule_message( source_zone: &str, target_zone: &str, diff --git a/crates/report/src/guard.rs b/crates/report/src/guard.rs index ede13a3..f3a9e47 100644 --- a/crates/report/src/guard.rs +++ b/crates/report/src/guard.rs @@ -184,69 +184,7 @@ impl GuardReport { return out.trim_end_matches('\n').to_owned(); } match &self.zone { - Some(zone) => { - let _ = writeln!(out, "zone: {zone}"); - if !self.public_files.is_empty() { - let visibility = if self.is_public_file == Some(true) { - "this file is public" - } else { - "this file is private" - }; - let _ = writeln!( - out, - "public_files: {} ({visibility})", - self.public_files.join(", ") - ); - } - if self.allowed_targets.is_empty() { - let _ = writeln!(out, "allowed_targets: none"); - } else { - let _ = writeln!(out, "allowed_targets:"); - for target in &self.allowed_targets { - let mut details = Vec::new(); - if !target.public_files.is_empty() { - details - .push(format!("public_files: {}", target.public_files.join(", "))); - } - if let Some(reason) = &target.reason { - details.push(format!("reason: {reason}")); - } - if details.is_empty() { - let _ = writeln!(out, " - {}", target.zone); - } else { - let _ = writeln!(out, " - {} ({})", target.zone, details.join("; ")); - } - } - } - if self.denied_targets.is_empty() { - let _ = writeln!(out, "denied_targets: none"); - } else { - let _ = writeln!(out, "denied_targets:"); - for target in &self.denied_targets { - match &target.reason { - Some(reason) => { - let _ = writeln!( - out, - " - {} ({}: {reason})", - target.zone, target.directive - ); - } - None => { - let _ = writeln!(out, " - {} ({})", target.zone, target.directive); - } - } - } - } - if self.allowed_importers.is_empty() { - let _ = writeln!(out, "allowed_importers: none"); - } else { - let _ = writeln!( - out, - "allowed_importers: {}", - self.allowed_importers.join(", ") - ); - } - } + Some(zone) => self.write_zone_details(&mut out, zone), None => { let _ = writeln!(out, "zone: none"); } @@ -256,6 +194,86 @@ impl GuardReport { } out.trim_end_matches('\n').to_owned() } + + fn write_zone_details(&self, out: &mut String, zone: &str) { + let _ = writeln!(out, "zone: {zone}"); + self.write_public_files(out); + self.write_allowed_targets(out); + self.write_denied_targets(out); + self.write_allowed_importers(out); + } + + fn write_public_files(&self, out: &mut String) { + if self.public_files.is_empty() { + return; + } + let visibility = if self.is_public_file == Some(true) { + "this file is public" + } else { + "this file is private" + }; + let _ = writeln!( + out, + "public_files: {} ({visibility})", + self.public_files.join(", ") + ); + } + + fn write_allowed_targets(&self, out: &mut String) { + if self.allowed_targets.is_empty() { + let _ = writeln!(out, "allowed_targets: none"); + return; + } + let _ = writeln!(out, "allowed_targets:"); + for target in &self.allowed_targets { + let _ = writeln!(out, " - {}", format_allowed_target(target)); + } + } + + fn write_denied_targets(&self, out: &mut String) { + if self.denied_targets.is_empty() { + let _ = writeln!(out, "denied_targets: none"); + return; + } + let _ = writeln!(out, "denied_targets:"); + for target in &self.denied_targets { + match &target.reason { + Some(reason) => { + let _ = writeln!(out, " - {} ({}: {reason})", target.zone, target.directive); + } + None => { + let _ = writeln!(out, " - {} ({})", target.zone, target.directive); + } + } + } + } + + fn write_allowed_importers(&self, out: &mut String) { + if self.allowed_importers.is_empty() { + let _ = writeln!(out, "allowed_importers: none"); + } else { + let _ = writeln!( + out, + "allowed_importers: {}", + self.allowed_importers.join(", ") + ); + } + } +} + +fn format_allowed_target(target: &GuardAllowedTarget) -> String { + let mut details = Vec::new(); + if !target.public_files.is_empty() { + details.push(format!("public_files: {}", target.public_files.join(", "))); + } + if let Some(reason) = &target.reason { + details.push(format!("reason: {reason}")); + } + if details.is_empty() { + target.zone.clone() + } else { + format!("{} ({})", target.zone, details.join("; ")) + } } fn directive_label(directive: BoundaryDirective) -> &'static str { diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index 28b0821..ec6083c 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -478,15 +478,16 @@ impl BoundaryPolicy for ConfigBoundaryPolicy<'_> { } } +fn mapped_findings<'a, T: 'a, R: From<&'a T>>(items: &'a [T], shown: FindingsShown) -> Findings { + Findings::worst_first(items.iter().map(R::from), shown) +} + impl BoundariesSection { fn new(boundaries: &Boundaries, shown: FindingsShown) -> BoundariesSection { BoundariesSection { ratio: Decimal::rounded(boundaries.ratio()), resolved_imports: boundaries.resolved_imports(), - findings: Findings::worst_first( - boundaries.findings().iter().map(BoundaryFindingRow::from), - shown, - ), + findings: mapped_findings(boundaries.findings(), shown), } } } @@ -746,10 +747,7 @@ impl VerbositySection { verbose_lines: verbosity.verbose_lines(), flagged_lines: verbosity.flagged_line_count(), clone_lines: verbosity.clone_line_count(), - findings: Findings::worst_first( - verbosity.flagged_lines().iter().map(FlaggedLineRow::from), - shown, - ), + findings: mapped_findings(verbosity.flagged_lines(), shown), } } }