use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::collision::analyze_collisions;
use crate::model::{
round2, round4, AuditDiff, AuditReport, AuditSummary, Catalog, Dimension, Finding, Severity,
Tier, ToolScore, SCHEMA_VERSION,
};
use crate::rules::evaluate_rules;
fn default_collision_threshold() -> f32 {
0.72
}
fn default_sibling_threshold() -> f32 {
0.50
}
fn default_shadow_threshold() -> f32 {
0.30
}
fn default_max_tool_tokens() -> usize {
250
}
fn default_max_catalog_tokens() -> usize {
15_000
}
fn default_fail_on() -> Option<Severity> {
Some(Severity::Error)
}
fn default_input_price_per_million() -> f32 {
3.00
}
fn default_cached_price_per_million() -> f32 {
0.30
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditConfig {
#[serde(default = "default_collision_threshold")]
pub collision_threshold: f32,
#[serde(default = "default_sibling_threshold")]
pub sibling_disambiguation_threshold: f32,
#[serde(default = "default_shadow_threshold")]
pub shadow_similarity_threshold: f32,
#[serde(default = "default_max_tool_tokens")]
pub max_tool_tokens: usize,
#[serde(default = "default_max_catalog_tokens")]
pub max_catalog_tokens: usize,
#[serde(default = "default_fail_on")]
pub fail_on: Option<Severity>,
#[serde(default)]
pub disabled_rules: Vec<String>,
#[serde(default = "default_input_price_per_million")]
pub input_price_per_million_usd: f32,
#[serde(default = "default_cached_price_per_million")]
pub cached_price_per_million_usd: f32,
}
impl Default for AuditConfig {
fn default() -> Self {
Self {
collision_threshold: default_collision_threshold(),
sibling_disambiguation_threshold: default_sibling_threshold(),
shadow_similarity_threshold: default_shadow_threshold(),
max_tool_tokens: default_max_tool_tokens(),
max_catalog_tokens: default_max_catalog_tokens(),
fail_on: default_fail_on(),
disabled_rules: Vec::new(),
input_price_per_million_usd: default_input_price_per_million(),
cached_price_per_million_usd: default_cached_price_per_million(),
}
}
}
impl AuditConfig {
#[must_use]
pub fn with_collision_threshold(mut self, threshold: f32) -> Self {
self.collision_threshold = threshold;
self
}
#[must_use]
pub fn with_sibling_disambiguation_threshold(mut self, threshold: f32) -> Self {
self.sibling_disambiguation_threshold = threshold;
self
}
#[must_use]
pub fn with_max_tool_tokens(mut self, max_tokens: usize) -> Self {
self.max_tool_tokens = max_tokens;
self
}
#[must_use]
pub fn with_max_catalog_tokens(mut self, max_tokens: usize) -> Self {
self.max_catalog_tokens = max_tokens;
self
}
#[must_use]
pub fn with_fail_on(mut self, severity: Option<Severity>) -> Self {
self.fail_on = severity;
self
}
#[must_use]
pub fn disable_rule(mut self, code: impl Into<String>) -> Self {
self.disabled_rules.push(code.into());
self
}
#[must_use]
pub fn with_input_price_per_million(mut self, usd_per_million: f32) -> Self {
self.input_price_per_million_usd = usd_per_million;
self.cached_price_per_million_usd = usd_per_million * 0.10;
self
}
}
#[derive(Debug, Clone, Default)]
pub struct Auditor {
config: AuditConfig,
}
impl Auditor {
#[must_use]
pub fn new(config: AuditConfig) -> Self {
Self { config }
}
pub fn config(&self) -> &AuditConfig {
&self.config
}
#[must_use]
pub fn audit(&self, catalog: &Catalog) -> AuditReport {
let report_floor = self
.config
.sibling_disambiguation_threshold
.min(self.config.collision_threshold);
let collision_analysis = analyze_collisions(
catalog,
report_floor,
self.config.shadow_similarity_threshold,
);
let mut findings = evaluate_rules(catalog, &collision_analysis.pairs, &self.config);
for finding in &mut findings {
if let Some(tool) = catalog.get(&finding.tool) {
if finding.source_location.is_none() {
finding.source_location = tool.source_location.clone();
}
if finding.source_server.is_none() {
finding.source_server = tool.source_server.clone();
}
}
}
let mut tool_scores = Vec::with_capacity(catalog.len());
let mut tool_fingerprints = BTreeMap::new();
for tool in catalog.tools() {
tool_fingerprints.insert(tool.name.clone(), tool.fingerprint());
let mut dims: BTreeMap<Dimension, f32> =
Dimension::ALL.into_iter().map(|d| (d, 5.0_f32)).collect();
let mut errors = 0usize;
let mut warnings = 0usize;
let mut infos = 0usize;
let mut hard_cap_purpose = false;
let mut hard_cap_behavior = false;
for f in &findings {
let affects_tool = f.tool == tool.name
|| (f.code == "VOL014"
&& f.related_tool.as_deref() == Some(tool.name.as_str()));
if !affects_tool {
continue;
}
let penalty = match f.severity {
Severity::Error => {
errors += 1;
2.5
}
Severity::Warn => {
warnings += 1;
1.5
}
Severity::Info => {
infos += 1;
0.5
}
};
if let Some(score) = dims.get_mut(&f.dimension) {
*score = (*score - penalty).clamp(1.0, 5.0);
}
if f.code == "VOL001" {
hard_cap_purpose = true;
}
if f.code == "VOL006" || f.code == "VOL019" {
hard_cap_behavior = true;
}
}
if hard_cap_purpose {
dims.insert(Dimension::PurposeClarity, 1.0);
}
if hard_cap_behavior {
dims.insert(Dimension::BehavioralTransparency, 1.0);
}
let overall = round2(
dims.iter()
.map(|(d, &s)| d.weight() * s)
.sum::<f32>()
.clamp(1.0, 5.0),
);
let rounded_dims: BTreeMap<Dimension, f32> =
dims.into_iter().map(|(d, s)| (d, round2(s))).collect();
tool_scores.push(ToolScore {
tool: tool.name.clone(),
overall,
tier: Tier::from_score(overall),
estimated_tokens: tool.estimated_total_tokens(),
invocation_cost: tool.invocation_cost(),
dimension_scores: rounded_dims,
error_count: errors,
warning_count: warnings,
info_count: infos,
});
}
tool_scores.sort_by(|a, b| a.tool.cmp(&b.tool));
let mut catalog_dims = BTreeMap::new();
for dim in Dimension::ALL {
let mean = if tool_scores.is_empty() {
5.0
} else {
let sum: f32 = tool_scores
.iter()
.map(|ts| ts.dimension_scores.get(&dim).copied().unwrap_or(5.0))
.sum();
sum / tool_scores.len() as f32
};
catalog_dims.insert(dim, round2(mean));
}
for f in &findings {
if f.tool == "<catalog>" {
let pen = match f.severity {
Severity::Error => 2.5,
Severity::Warn => 1.5,
Severity::Info => 0.5,
};
if let Some(score) = catalog_dims.get_mut(&f.dimension) {
*score = round2((*score - pen).clamp(1.0, 5.0));
}
}
}
let weighted_mean = catalog_dims
.iter()
.map(|(d, &s)| d.weight() * s)
.sum::<f32>()
.clamp(1.0, 5.0);
let worst_tool_score = tool_scores
.iter()
.map(|t| t.overall)
.fold(5.0_f32, f32::min);
let overall_score =
round2((0.70 * weighted_mean + 0.30 * worst_tool_score).clamp(1.0, 5.0));
let error_count = findings
.iter()
.filter(|f| f.severity == Severity::Error)
.count();
let warning_count = findings
.iter()
.filter(|f| f.severity == Severity::Warn)
.count();
let info_count = findings
.iter()
.filter(|f| f.severity == Severity::Info)
.count();
let collision_count = collision_analysis
.pairs
.iter()
.filter(|p| p.tool_a == p.tool_b || p.score >= self.config.collision_threshold)
.count();
let shadowing_count = collision_analysis
.pairs
.iter()
.filter(|p| p.shadowing_risk)
.count();
let estimated_catalog_tokens = catalog.estimated_total_tokens();
let tokens_m = (estimated_catalog_tokens as f32) / 1_000_000.0;
let cost_per_turn = tokens_m * self.config.input_price_per_million_usd;
let session_uncached = cost_per_turn * 200.0;
let session_cached =
cost_per_turn + (tokens_m * self.config.cached_price_per_million_usd * 199.0);
let passed = match self.config.fail_on {
None => true,
Some(min_sev) => !findings.iter().any(|f| f.severity >= min_sev),
};
AuditReport {
schema_version: SCHEMA_VERSION.into(),
summary: AuditSummary {
passed,
tool_count: catalog.len(),
estimated_catalog_tokens,
estimated_cost_per_turn_usd: round4(cost_per_turn),
estimated_200_turn_session_usd: round2(session_uncached),
estimated_200_turn_cached_usd: round2(session_cached),
overall_score,
worst_tool_score: round2(worst_tool_score),
tier: Tier::from_score(overall_score),
error_count,
warning_count,
info_count,
collision_count,
shadowing_count,
},
dimension_scores: catalog_dims,
tool_scores,
findings,
collisions: collision_analysis.pairs,
tool_fingerprints,
}
}
}
#[must_use]
pub fn diff_reports(baseline: &AuditReport, current: &AuditReport) -> AuditDiff {
let key = |f: &Finding| {
(
f.code.clone(),
f.tool.clone(),
f.related_tool.clone(),
f.json_pointer.clone(),
)
};
let base_keys: BTreeSet<_> = baseline.findings.iter().map(key).collect();
let curr_keys: BTreeSet<_> = current.findings.iter().map(key).collect();
let new_findings: Vec<Finding> = current
.findings
.iter()
.filter(|f| !base_keys.contains(&key(f)))
.cloned()
.collect();
let resolved_findings: Vec<Finding> = baseline
.findings
.iter()
.filter(|f| !curr_keys.contains(&key(f)))
.cloned()
.collect();
let mut added_tools = Vec::new();
let mut removed_tools = Vec::new();
let mut modified_tools = Vec::new();
for (name, fp) in ¤t.tool_fingerprints {
match baseline.tool_fingerprints.get(name) {
None => added_tools.push(name.clone()),
Some(old_fp) if old_fp != fp => modified_tools.push(name.clone()),
Some(_) => {}
}
}
for name in baseline.tool_fingerprints.keys() {
if !current.tool_fingerprints.contains_key(name) {
removed_tools.push(name.clone());
}
}
added_tools.sort();
removed_tools.sort();
modified_tools.sort();
let score_delta = round2(current.summary.overall_score - baseline.summary.overall_score);
let token_delta = current.summary.estimated_catalog_tokens as i64
- baseline.summary.estimated_catalog_tokens as i64;
let session_cost_delta_usd = round2(
current.summary.estimated_200_turn_session_usd
- baseline.summary.estimated_200_turn_session_usd,
);
let error_delta = current.summary.error_count as i64 - baseline.summary.error_count as i64;
let warning_delta =
current.summary.warning_count as i64 - baseline.summary.warning_count as i64;
let cache_busting_change =
!added_tools.is_empty() || !removed_tools.is_empty() || !modified_tools.is_empty();
let has_new_error = new_findings.iter().any(|f| f.severity == Severity::Error);
let regressed = score_delta < -0.001 || error_delta > 0 || has_new_error;
AuditDiff {
schema_version: SCHEMA_VERSION.into(),
score_delta,
token_delta,
session_cost_delta_usd,
error_delta,
warning_delta,
new_findings,
resolved_findings,
added_tools,
removed_tools,
modified_tools,
cache_busting_change,
regressed,
}
}