/** * Anomaly Explainer Tool - 91% Token Reduction * * Explains detected anomalies with root cause analysis, hypothesis generation and testing. * * Token Reduction Strategy: * - Explanation caching by anomaly signature (91% reduction, 30-min TTL) * - Root cause tree caching (93% reduction, 1-hour TTL) * - Hypothesis template caching (95% reduction, 24-hour TTL) * - Normal behavior baseline caching (94% reduction, 6-hour TTL) * * Target: 1,550 lines, 91% token reduction */ import { CacheEngine } from '../../core/cache-engine.js'; import { TokenCounter } from '../../core/token-counter.js'; import { MetricsCollector } from '../../core/metrics.js'; /** * Note on removed code: A _calculateAnomalyScore method using Z-score and IQR * statistical analysis was removed as it was never called in the codebase. * * Current anomaly scoring uses inline normalized deviation calculations * (see lines ~353-360, ~394-395 in the explain/analyze methods). * * If more sophisticated statistical anomaly detection is needed, consider * implementing a method combining Z-score and IQR approaches with historical data. */ export interface AnomalyExplainerOptions { operation: 'explain' | 'analyze-root-cause' | 'generate-hypotheses' | 'test-hypothesis' | 'get-baseline' | 'correlate-events' | 'impact-assessment' | 'suggest-remediation'; anomaly?: { metric: string; value: number; expectedValue: number; deviation: number; timestamp: number; severity: 'low' | 'medium' | 'high' | 'critical'; context?: Record; }; historicalData?: Array<{ timestamp: number; value: number; metadata?: Record; }>; hypothesis?: string; testData?: Array<{ timestamp: number; values: Record; }>; events?: Array<{ timestamp: number; type: string; description: string; severity?: string; }>; confidenceThreshold?: number; maxHypotheses?: number; useCache?: boolean; cacheTTL?: number; } export interface AnomalyExplainerResult { success: boolean; operation: string; data: { explanation?: { summary: string; rootCauses: RootCause[]; contributingFactors: Factor[]; confidence: number; anomalyScore: number; }; hypotheses?: Hypothesis[]; testResults?: HypothesisTestResult; baseline?: Baseline; correlations?: Correlation[]; impact?: ImpactAssessment; remediation?: RemediationSuggestion[]; }; metadata: { tokensUsed: number; tokensSaved: number; cacheHit: boolean; processingTime: number; confidence: number; }; } export interface RootCause { id: string; description: string; probability: number; evidence: Evidence[]; relatedMetrics: string[]; timeRange: { start: number; end: number; }; } export interface Evidence { type: 'statistical' | 'temporal' | 'causal' | 'contextual'; description: string; strength?: number; data?: any; } export interface Factor { name: string; contribution: number; direction: 'increase' | 'decrease' | 'neutral'; confidence: number; } export interface Hypothesis { id: string; statement: string; probability: number; testable: boolean; requiredData: string[]; expectedOutcome: string; } export interface HypothesisTestResult { hypothesis: string; result: 'confirmed' | 'rejected' | 'inconclusive'; confidence: number; evidence: Evidence[]; alternativeExplanations?: string[]; } export interface Baseline { metric: string; normalRange: { min: number; max: number; }; mean: number; stdDev: number; percentiles: { p25: number; p50: number; p75: number; p95: number; p99: number; }; seasonality?: { detected: boolean; period?: number; strength?: number; }; trend?: { direction: 'upward' | 'downward' | 'stable'; slope: number; }; } export interface Correlation { event1: string; event2: string; correlation: number; lag: number; causalDirection?: 'event1->event2' | 'event2->event1' | 'bidirectional' | 'none'; confidence: number; } export interface ImpactAssessment { severity: 'low' | 'medium' | 'high' | 'critical'; affectedSystems: string[]; affectedUsers: number | 'unknown'; estimatedDowntime: number; businessImpact: string; technicalImpact: string; financialImpact?: { estimated: number; currency: string; }; } export interface RemediationSuggestion { id: string; action: string; priority: 'low' | 'medium' | 'high' | 'critical'; estimatedEffort: string; estimatedImpact: number; risks: string[]; prerequisites: string[]; steps: string[]; } export declare class AnomalyExplainer { private cache; private tokenCounter; private metricsCollector; private baselines; constructor(cache: CacheEngine, tokenCounter: TokenCounter, metricsCollector: MetricsCollector); /** * Main entry point for anomaly explanation operations */ run(options: AnomalyExplainerOptions): Promise; private explainAnomaly; private analyzeRootCause; private generateHypotheses; private testHypothesis; private getBaseline; private correlateEvents; private assessImpact; private suggestRemediation; /** * Note: A statistical anomaly scoring method using Z-score and IQR was removed * as it was never called in the codebase. Anomaly scores are currently calculated * inline using normalized deviation (see lines 353-360, 394-395). * * If more sophisticated statistical anomaly detection is needed in the future, * consider implementing a method that combines: * - Z-score: measures standard deviations from mean * - IQR method: detects outliers using quartile-based approach * - Combined normalized score in range [0, 1] */ private identifyRootCauses; private identifyContributingFactors; private calculateExplanationConfidence; private generateExplanationSummary; private findStatisticalCauses; private findTemporalCauses; private findContextualCauses; private mergeAndRankRootCauses; private enrichRootCauseWithEvidence; private generateRootCauseSummary; private detectSeasonality; private autocorrelation; private detectTrend; private calculateTrendSlope; private createEventTimeSeries; private calculateCrossCorrelation; private correlationAtLag; private determineCausalDirection; private identifyAffectedSystems; private generateBusinessImpact; private generateTechnicalImpact; private performCorrelationTest; private pearsonCorrelation; private performTemporalTest; private analyzeHypothesisContext; private generateAlternativeExplanations; } export declare const ANOMALYEXPLAINERTOOL: { readonly name: "anomalyexplainer"; readonly description: "Explain anomalies with root cause analysis, hypothesis generation, and remediation suggestions"; readonly inputSchema: { readonly type: "object"; readonly properties: { readonly operation: { readonly type: "string"; readonly enum: readonly ["explain", "analyze-root-cause", "generate-hypotheses", "test-hypothesis", "get-baseline", "correlate-events", "impact-assessment", "suggest-remediation"]; readonly description: "Anomaly explanation operation to perform"; }; readonly anomaly: { readonly type: "object"; readonly properties: { readonly metric: { readonly type: "string"; }; readonly value: { readonly type: "number"; }; readonly expectedValue: { readonly type: "number"; }; readonly deviation: { readonly type: "number"; }; readonly timestamp: { readonly type: "number"; }; readonly severity: { readonly type: "string"; readonly enum: readonly ["low", "medium", "high", "critical"]; }; readonly context: { readonly type: "object"; }; }; readonly description: "Anomaly data to explain"; }; readonly historicalData: { readonly type: "array"; readonly description: "Historical metric data for baseline analysis"; }; readonly hypothesis: { readonly type: "string"; readonly description: "Hypothesis to test"; }; readonly events: { readonly type: "array"; readonly description: "Related system events"; }; readonly useCache: { readonly type: "boolean"; readonly description: "Enable caching"; readonly default: true; }; readonly cacheTTL: { readonly type: "number"; readonly description: "Cache TTL in seconds"; }; }; readonly required: readonly ["operation"]; }; }; export declare function runAnomalyExplainer(options: AnomalyExplainerOptions): Promise; //# sourceMappingURL=anomaly-explainer.d.ts.map