Checkpoint: File edits

Automatic checkpoint created by Claude Code
- Branch: v3
- Timestamp: 2026-01-12T16:24:21Z
- Changes: 1 file(s)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
rUvandClaude Opus 4.5 committed 2026-01-12 16:24:21 +00:00
1 parent e39b14a0ce
commit b4d52a8a2e
1 file changed
+247 -49
+247 -49
View File
@@ -1,23 +1,30 @@
/**
* @claude-flow/aidefence
*
* AI Manipulation Defense System integration for Claude Flow V3.
* Provides embedded threat detection without external server dependency.
* AI Manipulation Defense System with self-learning capabilities.
*
* Features:
* - 50+ prompt injection patterns
* - HNSW-indexed threat pattern search (150x-12,500x faster with AgentDB)
* - ReasoningBank-style pattern learning
* - Adaptive mitigation with effectiveness tracking
* - Strange-loop meta-learning integration
*
* @example
* ```typescript
* import { createAIDefence } from '@claude-flow/aidefence';
*
* const aidefence = createAIDefence();
* const aidefence = createAIDefence({ enableLearning: true });
*
* // Detect threats
* const result = aidefence.detect('Ignore all previous instructions');
* const result = await aidefence.detect('Ignore all previous instructions');
* console.log(result.safe); // false
* console.log(result.threats[0].type); // 'instruction_override'
*
* // Quick scan
* const quick = aidefence.quickScan('Hello, help me code');
* console.log(quick.threat); // false
* // Search similar patterns (uses HNSW when connected to AgentDB)
* const similar = await aidefence.searchSimilarThreats('system prompt injection');
*
* // Learn from feedback
* await aidefence.learnFromDetection(input, result, { wasAccurate: true });
* ```
*/
@@ -38,65 +45,198 @@ export {
createThreatDetectionService,
} from './domain/services/threat-detection-service.js';
// Re-export types for convenience
export type { ThreatDetectionResult as DetectionResult } from './domain/entities/threat.js';
export {
ThreatLearningService,
createThreatLearningService,
LearnedThreatPattern,
MitigationStrategy,
LearningTrajectory,
VectorStore,
InMemoryVectorStore,
} from './domain/services/threat-learning-service.js';
/**
* AIDefence facade - simplified API for common use cases
* Configuration for AIDefence
*/
export interface AIDefenceConfig {
/** Enable self-learning from detections */
enableLearning?: boolean;
/** Custom vector store (defaults to in-memory, use AgentDB for production) */
vectorStore?: import('./domain/services/threat-learning-service.js').VectorStore;
/** Minimum confidence threshold for threats */
confidenceThreshold?: number;
/** Enable PII detection */
enablePIIDetection?: boolean;
}
/**
* AIDefence - Unified threat detection and learning facade
*/
export interface AIDefence {
/**
* Detect threats in input text
* @param input - Text to analyze
* @returns Detection result with threats array
*/
detect(input: string): import('./domain/entities/threat.js').ThreatDetectionResult;
detect(input: string): Promise<import('./domain/entities/threat.js').ThreatDetectionResult>;
/**
* Quick scan for threats (faster, less detailed)
* @param input - Text to scan
* @returns Whether threat was found and confidence
*/
quickScan(input: string): { threat: boolean; confidence: number };
/**
* Check if input contains PII
* @param input - Text to check
* @returns Whether PII was found
*/
hasPII(input: string): boolean;
/**
* Get detection statistics
* Search for similar threat patterns using HNSW
* Achieves 150x-12,500x speedup when connected to AgentDB
*/
getStats(): { detectionCount: number; avgDetectionTimeMs: number };
searchSimilarThreats(
query: string,
options?: { k?: number; minSimilarity?: number }
): Promise<import('./domain/services/threat-learning-service.js').LearnedThreatPattern[]>;
/**
* Learn from a detection result (ReasoningBank pattern)
*/
learnFromDetection(
input: string,
result: import('./domain/entities/threat.js').ThreatDetectionResult,
feedback?: { wasAccurate: boolean; userVerdict?: string }
): Promise<void>;
/**
* Record mitigation effectiveness for meta-learning
*/
recordMitigation(
threatType: import('./domain/entities/threat.js').ThreatType,
strategy: 'block' | 'sanitize' | 'warn' | 'log' | 'escalate' | 'transform' | 'redirect',
success: boolean
): Promise<void>;
/**
* Get best mitigation strategy based on learned effectiveness
*/
getBestMitigation(
threatType: import('./domain/entities/threat.js').ThreatType
): Promise<import('./domain/services/threat-learning-service.js').MitigationStrategy | null>;
/**
* Start a learning trajectory session
*/
startTrajectory(sessionId: string, task: string): void;
/**
* End a learning trajectory and store for future learning
*/
endTrajectory(sessionId: string, verdict: 'success' | 'failure' | 'partial'): Promise<void>;
/**
* Get detection and learning statistics
*/
getStats(): Promise<{
detectionCount: number;
avgDetectionTimeMs: number;
learnedPatterns: number;
mitigationStrategies: number;
avgMitigationEffectiveness: number;
}>;
}
/**
* Create an AIDefence instance
* Create an AIDefence instance with optional learning capabilities
*
* @example
* ```typescript
* const aidefence = createAIDefence();
* // Simple usage (detection only)
* const simple = createAIDefence();
*
* // Use in a pre-hook
* const result = aidefence.detect(userInput);
* if (!result.safe) {
* const critical = result.threats.filter(t => t.severity === 'critical');
* if (critical.length > 0) {
* throw new Error('Critical threat detected');
* }
* }
* // With learning enabled
* const learning = createAIDefence({ enableLearning: true });
*
* // With AgentDB for HNSW search (150x-12,500x faster)
* import { AgentDB } from 'agentdb';
* const agentdb = new AgentDB({ path: './data/aidefence' });
* const fast = createAIDefence({
* enableLearning: true,
* vectorStore: agentdb
* });
* ```
*/
export function createAIDefence(): AIDefence {
const service = createThreatDetectionService();
export function createAIDefence(config: AIDefenceConfig = {}): AIDefence {
const detectionService = createThreatDetectionService();
const learningService = config.enableLearning
? createThreatLearningService(config.vectorStore)
: null;
return {
detect: (input: string) => service.detect(input),
quickScan: (input: string) => service.quickScan(input),
hasPII: (input: string) => service.detectPII(input),
getStats: () => service.getStats(),
async detect(input: string) {
const result = detectionService.detect(input);
// Auto-learn if enabled
if (learningService && result.threats.length > 0) {
await learningService.learnFromDetection(input, result);
}
return result;
},
quickScan(input: string) {
return detectionService.quickScan(input);
},
hasPII(input: string) {
return detectionService.detectPII(input);
},
async searchSimilarThreats(query, options) {
if (!learningService) {
return [];
}
return learningService.searchSimilarThreats(query, options);
},
async learnFromDetection(input, result, feedback) {
if (!learningService) {
console.warn('Learning not enabled. Pass { enableLearning: true } to createAIDefence()');
return;
}
await learningService.learnFromDetection(input, result, feedback);
},
async recordMitigation(threatType, strategy, success) {
if (!learningService) return;
await learningService.recordMitigation(threatType, strategy, success);
},
async getBestMitigation(threatType) {
if (!learningService) return null;
return learningService.getBestMitigation(threatType);
},
startTrajectory(sessionId, task) {
learningService?.startTrajectory(sessionId, task);
},
async endTrajectory(sessionId, verdict) {
await learningService?.endTrajectory(sessionId, verdict);
},
async getStats() {
const detectionStats = detectionService.getStats();
const learningStats = learningService
? await learningService.getStats()
: { learnedPatterns: 0, mitigationStrategies: 0, avgEffectiveness: 0 };
return {
detectionCount: detectionStats.detectionCount,
avgDetectionTimeMs: detectionStats.avgDetectionTimeMs,
learnedPatterns: learningStats.learnedPatterns,
mitigationStrategies: learningStats.mitigationStrategies,
avgMitigationEffectiveness: learningStats.avgEffectiveness,
};
},
};
}
@@ -106,34 +246,92 @@ export function createAIDefence(): AIDefence {
let defaultInstance: AIDefence | null = null;
/**
* Get the default AIDefence instance (singleton)
* Get the default AIDefence instance (singleton, learning enabled)
*/
export function getAIDefence(): AIDefence {
if (!defaultInstance) {
defaultInstance = createAIDefence();
defaultInstance = createAIDefence({ enableLearning: true });
}
return defaultInstance;
}
/**
* Convenience function for quick threat check
*
* @example
* ```typescript
* import { isSafe } from '@claude-flow/aidefence';
*
* if (!isSafe(userInput)) {
* console.log('Potential threat detected');
* }
* ```
*/
export function isSafe(input: string): boolean {
return getAIDefence().detect(input).safe;
const service = createThreatDetectionService();
return service.detect(input).safe;
}
/**
* Convenience function for quick threat check with details
*/
export function checkThreats(input: string) {
return getAIDefence().detect(input);
const service = createThreatDetectionService();
return service.detect(input);
}
/**
* Integration with agentic-flow attention mechanisms
* Use for multi-agent security consensus
*/
export interface AttentionContext {
agentId: string;
threatAssessment: import('./domain/entities/threat.js').ThreatDetectionResult;
weight: number;
}
/**
* Calculate security consensus from multiple agent assessments
* Uses attention-based weighting for flash attention integration
*/
export function calculateSecurityConsensus(
assessments: AttentionContext[]
): {
consensus: 'safe' | 'threat' | 'uncertain';
confidence: number;
criticalThreats: import('./domain/entities/threat.js').Threat[];
} {
if (assessments.length === 0) {
return { consensus: 'uncertain', confidence: 0, criticalThreats: [] };
}
// Normalize weights
const totalWeight = assessments.reduce((sum, a) => sum + a.weight, 0);
const normalized = assessments.map(a => ({
...a,
weight: a.weight / totalWeight,
}));
// Calculate weighted threat score
let threatScore = 0;
const allThreats: import('./domain/entities/threat.js').Threat[] = [];
for (const assessment of normalized) {
if (!assessment.threatAssessment.safe) {
threatScore += assessment.weight;
allThreats.push(...assessment.threatAssessment.threats);
}
}
// Determine consensus
const criticalThreats = allThreats.filter(t => t.severity === 'critical');
if (criticalThreats.length > 0) {
return {
consensus: 'threat',
confidence: Math.max(...criticalThreats.map(t => t.confidence)),
criticalThreats,
};
}
if (threatScore > 0.5) {
return { consensus: 'threat', confidence: threatScore, criticalThreats: [] };
}
if (threatScore < 0.2) {
return { consensus: 'safe', confidence: 1 - threatScore, criticalThreats: [] };
}
return { consensus: 'uncertain', confidence: 0.5, criticalThreats: [] };
}