1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
//! # Tool Compatibility Assessment Module
//!
//! This module assesses the risk of pattern recommendations and validates tool compatibility scoring.
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
mod analysis_helpers;
/// Tool compatibility assessment result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompatibilityAssessment {
/// Assessment ID
pub id: String,
/// Pattern being assessed
pub pattern_id: String,
/// Tool being assessed
pub tool_name: String,
/// Compatibility score (0-1)
pub compatibility_score: f64,
/// Confidence in assessment (0-1)
pub confidence: f64,
/// Risk factors identified
pub risk_factors: Vec<RiskFactor>,
/// Recommendations
pub recommendations: Vec<String>,
/// Overall risk level
pub risk_level: RiskLevel,
/// Confidence interval (lower, upper)
pub confidence_interval: (f64, f64),
}
/// Risk factor identified during assessment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiskFactor {
/// Factor type
pub factor_type: RiskFactorType,
/// Severity (0-1)
pub severity: f64,
/// Description
pub description: String,
/// Mitigation suggestions
pub mitigation: Option<String>,
}
/// Risk factor types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RiskFactorType {
/// Data quality risk (missing, noisy, inconsistent)
DataQuality,
/// Model performance risk (accuracy, precision)
ModelPerformance,
/// Domain mismatch risk
DomainMismatch,
/// Temporal drift risk (pattern changes over time)
TemporalDrift,
/// Resource constraint risk (computation, memory)
ResourceConstraint,
/// Compatibility risk (tool version, dependencies)
Compatibility,
}
/// Risk level classification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RiskLevel {
/// Low risk: safe to proceed
Low,
/// Medium risk: proceed with caution
Medium,
/// High risk: requires review
High,
/// Critical risk: do not proceed
Critical,
}
/// Compatibility assessment configuration
#[derive(Debug, Clone)]
pub struct AssessmentConfig {
/// Threshold for low risk (>= this score is low risk)
pub low_risk_threshold: f64,
/// Threshold for medium risk (>= this score is medium risk)
pub medium_risk_threshold: f64,
/// Confidence level for intervals (default: 0.95)
pub confidence_level: f64,
/// Minimum pattern occurrences for reliability
pub min_occurrences: usize,
}
impl Default for AssessmentConfig {
fn default() -> Self {
Self {
low_risk_threshold: 0.8,
medium_risk_threshold: 0.6,
confidence_level: 0.95,
min_occurrences: 3,
}
}
}
/// Tool compatibility assessor
pub struct CompatibilityAssessor {
config: AssessmentConfig,
/// Tool capabilities registry
tool_capabilities: HashMap<String, ToolCapabilities>,
}
/// Tool capabilities definition
#[derive(Debug, Clone)]
struct ToolCapabilities {
/// Supported data types
_supported_types: HashSet<String>,
/// Minimum data quality requirements
min_data_quality: f64,
/// Maximum resource usage (MB)
max_memory_mb: usize,
/// Supported domains
supported_domains: HashSet<String>,
/// Performance metrics
_avg_latency_ms: f64,
success_rate: f64,
}
impl CompatibilityAssessor {
/// Create a new compatibility assessor
pub fn new(config: AssessmentConfig) -> Self {
let mut assessor = Self {
config,
tool_capabilities: HashMap::new(),
};
// Initialize with known tools
assessor.initialize_tool_registry();
assessor
}
/// Create with default configuration
pub fn default_config() -> Self {
Self::new(AssessmentConfig::default())
}
/// Initialize tool registry with known capabilities
fn initialize_tool_registry(&mut self) {
// query_memory tool
self.tool_capabilities.insert(
"query_memory".to_string(),
ToolCapabilities {
_supported_types: vec!["episodic", "semantic", "temporal"]
.into_iter()
.map(String::from)
.collect(),
min_data_quality: 0.5,
max_memory_mb: 100,
supported_domains: vec!["web-api", "cli", "data-processing"]
.into_iter()
.map(String::from)
.collect(),
_avg_latency_ms: 10.0,
success_rate: 0.98,
},
);
// analyze_patterns tool
self.tool_capabilities.insert(
"analyze_patterns".to_string(),
ToolCapabilities {
_supported_types: vec!["statistical", "predictive", "causal"]
.into_iter()
.map(String::from)
.collect(),
min_data_quality: 0.7,
max_memory_mb: 200,
supported_domains: vec!["data-processing", "analytics"]
.into_iter()
.map(String::from)
.collect(),
_avg_latency_ms: 50.0,
success_rate: 0.92,
},
);
// advanced_pattern_analysis tool
self.tool_capabilities.insert(
"advanced_pattern_analysis".to_string(),
ToolCapabilities {
_supported_types: vec!["time_series", "multivariate", "temporal"]
.into_iter()
.map(String::from)
.collect(),
min_data_quality: 0.8,
max_memory_mb: 500,
supported_domains: vec!["analytics", "forecasting", "anomaly_detection"]
.into_iter()
.map(String::from)
.collect(),
_avg_latency_ms: 100.0,
success_rate: 0.88,
},
);
}
/// Assess tool compatibility for a pattern
pub fn assess_compatibility(
&self,
pattern_id: &str,
tool_name: &str,
pattern_context: &PatternContext,
) -> Result<CompatibilityAssessment> {
// Get tool capabilities
let tool_caps = self
.tool_capabilities
.get(tool_name)
.ok_or_else(|| anyhow::anyhow!("Unknown tool: {}", tool_name))?;
// Compute compatibility score
let compatibility_score = self.compute_compatibility_score(tool_caps, pattern_context);
// Compute confidence
let confidence = self.compute_confidence(tool_caps, pattern_context);
// Identify risk factors
let risk_factors = self.identify_risk_factors(tool_caps, pattern_context);
// Determine risk level
let risk_level = self.determine_risk_level(compatibility_score, &risk_factors);
// Generate recommendations
let recommendations = self.generate_recommendations(&risk_factors, tool_name);
// Compute confidence interval
let confidence_interval = self.compute_confidence_interval(
compatibility_score,
confidence,
pattern_context.occurrences,
);
Ok(CompatibilityAssessment {
id: format!("{}_{}", pattern_id, tool_name),
pattern_id: pattern_id.to_string(),
tool_name: tool_name.to_string(),
compatibility_score,
confidence,
risk_factors,
recommendations,
risk_level,
confidence_interval,
})
}
/// Compute compatibility score
fn compute_compatibility_score(
&self,
tool_caps: &ToolCapabilities,
context: &PatternContext,
) -> f64 {
let mut score = 0.0;
let mut total_weight = 0.0;
// Data quality compatibility (weight: 0.3)
let quality_score = if context.data_quality >= tool_caps.min_data_quality {
1.0
} else {
context.data_quality / tool_caps.min_data_quality
};
score += 0.3 * quality_score;
total_weight += 0.3;
// Domain compatibility (weight: 0.25)
let domain_score = if tool_caps.supported_domains.contains(&context.domain) {
1.0
} else {
0.5 // Partial credit if domain not directly supported
};
score += 0.25 * domain_score;
total_weight += 0.25;
// Occurrence reliability (weight: 0.2)
let occurrence_score = if context.occurrences >= self.config.min_occurrences {
1.0
} else {
context.occurrences as f64 / self.config.min_occurrences as f64
};
score += 0.2 * occurrence_score;
total_weight += 0.2;
// Temporal stability (weight: 0.15)
let stability_score = context.temporal_stability;
score += 0.15 * stability_score;
total_weight += 0.15;
// Resource availability (weight: 0.1)
let resource_score = if context.available_memory_mb >= tool_caps.max_memory_mb {
1.0
} else {
context.available_memory_mb as f64 / tool_caps.max_memory_mb as f64
};
score += 0.1 * resource_score;
total_weight += 0.1;
// Normalize score
if total_weight > 0.0 {
score / total_weight
} else {
0.5 // Default middle score
}
}
/// Compute confidence in assessment
fn compute_confidence(&self, tool_caps: &ToolCapabilities, context: &PatternContext) -> f64 {
let mut confidence = 0.5; // Base confidence
// Increase confidence based on tool success rate
confidence += 0.2 * tool_caps.success_rate;
// Increase confidence based on pattern occurrences
let occurrence_confidence = if context.occurrences >= 10 {
1.0
} else {
context.occurrences as f64 / 10.0
};
confidence += 0.2 * occurrence_confidence;
// Increase confidence based on data quality
confidence += 0.1 * context.data_quality;
confidence.clamp(0.0, 1.0)
}
/// Batch assess multiple tools
pub fn batch_assess(
&self,
pattern_id: &str,
tool_names: &[String],
context: &PatternContext,
) -> Result<Vec<CompatibilityAssessment>> {
let mut assessments = Vec::new();
for tool_name in tool_names {
let assessment = self.assess_compatibility(pattern_id, tool_name, context)?;
assessments.push(assessment);
}
Ok(assessments)
}
/// Get best tool for a pattern
pub fn get_best_tool(
&self,
pattern_id: &str,
tool_names: &[String],
context: &PatternContext,
) -> Result<Option<(String, CompatibilityAssessment)>> {
let assessments = self.batch_assess(pattern_id, tool_names, context)?;
let best = assessments
.into_iter()
.filter(|a| matches!(a.risk_level, RiskLevel::Low | RiskLevel::Medium))
.max_by(|a, b| {
a.compatibility_score
.partial_cmp(&b.compatibility_score)
.unwrap_or(std::cmp::Ordering::Equal)
});
Ok(best.map(|assessment| (assessment.tool_name.clone(), assessment)))
}
}
/// Pattern context for compatibility assessment
#[derive(Debug, Clone)]
pub struct PatternContext {
/// Domain of the pattern
pub domain: String,
/// Data quality score (0-1)
pub data_quality: f64,
/// Number of times pattern occurs
pub occurrences: usize,
/// Temporal stability (0-1, higher = more stable)
pub temporal_stability: f64,
/// Available memory in MB
pub available_memory_mb: usize,
/// Pattern complexity (0-1)
pub complexity: f64,
}
#[cfg(test)]
mod tests;