# Aidefence

> AI Manipulation Defense System with self-learning prompt injection detection and adaptive mitigation

- Skill: `jrennie99-glitch/aidefence` (Agent Skill)
- Install (CLI): `npx skillmds add jrennie99-glitch/aidefence`
- Raw SKILL.md: https://api.skillmd.com/api/skills/jrennie99-glitch/aidefence/raw
- Safety review: pending (external: skill-scanner WARNING, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: jrennie99-glitch (https://skillmd.com/u/jrennie99-glitch)
- Updated: 2026-08-19
- Page: https://skillmd.com/skills/jrennie99-glitch/aidefence

---


# AI Defence — Prompt Injection Detection and Adaptive Mitigation

## Purpose

The `@claude-flow/aidefence` module is a comprehensive AI manipulation defense system with self-learning capabilities. It provides real-time detection of prompt injection attacks, jailbreak attempts, PII exposure, role switching, context manipulation, and encoding attacks across multi-agent systems.

## Core Components

### Threat Entity Model

Every detected threat is represented as a `Threat` entity with the following properties:

- **id** — Unique identifier (`threat-{timestamp}-{random}`)
- **type** — One of: `prompt_injection`, `jailbreak`, `pii_exposure`, `instruction_override`, `role_switching`, `context_manipulation`, `encoding_attack`, `unknown`
- **severity** — `low`, `medium`, `high`, or `critical`
- **confidence** — Numeric score (0.0 to 1.0) indicating detection certainty
- **pattern** — The regex pattern that triggered the detection
- **description** — Human-readable description of the threat
- **location** — Optional start/end character positions in the input
- **detectedAt** — Timestamp of detection

### Detection Result

Each detection pass produces a `ThreatDetectionResult`:

- **safe** — Boolean indicating whether input is safe
- **threats** — Array of detected `Threat` entities
- **detectionTimeMs** — Time taken for detection
- **piiFound** — Whether PII was detected
- **inputHash** — SHA hash of the input for deduplication

## Commands and API

### Create an AIDefence Instance

```typescript
import { createAIDefence } from '@claude-flow/aidefence';

// Simple detection-only mode
const simple = createAIDefence();

// With self-learning enabled
const learning = createAIDefence({ enableLearning: true });

// With AgentDB for HNSW-indexed search (150x-12,500x faster)
const fast = createAIDefence({
  enableLearning: true,
  vectorStore: agentdbInstance,
  confidenceThreshold: 0.8,
  enablePIIDetection: true,
});
```

### Detect Threats

```typescript
const result = await aidefence.detect('Ignore all previous instructions');
// result.safe === false
// result.threats[0].type === 'instruction_override'
// result.threats[0].severity === 'critical'
// result.threats[0].confidence === 0.95
```

### Quick Scan (Faster, Less Detailed)

```typescript
const scan = aidefence.quickScan(userInput);
// { threat: boolean, confidence: number }
```

### PII Detection

```typescript
const hasPII = aidefence.hasPII('My SSN is 123-45-6789');
// true
```

### Search Similar Threat Patterns (HNSW)

```typescript
const similar = await aidefence.searchSimilarThreats('system prompt injection', {
  k: 10,
  minSimilarity: 0.7,
});
```

### Learn from Detection (ReasoningBank Pattern)

```typescript
await aidefence.learnFromDetection(input, result, {
  wasAccurate: true,
  userVerdict: 'confirmed malicious',
});
```

### Mitigation Strategies

```typescript
// Record mitigation effectiveness
await aidefence.recordMitigation('prompt_injection', 'block', true);

// Get best mitigation for a threat type
const strategy = await aidefence.getBestMitigation('jailbreak');
// Returns: { strategy: 'sanitize', effectiveness: 0.94, uses: 127 }
```

### Learning Trajectories

```typescript
aidefence.startTrajectory('session-123', 'Analyze user inputs');
// ... perform detections ...
await aidefence.endTrajectory('session-123', 'success');
```

## Detection Patterns (50+)

The system includes embedded detection patterns across these categories:

### Instruction Override (Critical Severity)
- `ignore (all) (previous) instructions` — confidence: 0.95
- `forget everything/all/previous` — confidence: 0.92
- `disregard (all) previous/prior/above` — confidence: 0.93
- `do not follow (the) previous/above/prior` — confidence: 0.88

### Role Switching (High Severity)
- `you are now (identity change)` — confidence: 0.85
- Persona injection patterns
- System prompt override attempts

### Jailbreak Patterns
- DAN-style prompts
- Encoding circumvention (base64, rot13, unicode tricks)
- Context window manipulation
- Delimiter injection

### PII Detection
- Social Security Numbers
- Credit card numbers
- Email addresses in suspicious contexts
- Phone number patterns

## Multi-Agent Security Consensus

For swarm-based deployments, AIDefence supports attention-weighted security consensus:

```typescript
import { calculateSecurityConsensus } from '@claude-flow/aidefence';

const consensus = calculateSecurityConsensus([
  { agentId: 'agent-1', threatAssessment: result1, weight: 0.8 },
  { agentId: 'agent-2', threatAssessment: result2, weight: 0.6 },
  { agentId: 'agent-3', threatAssessment: result3, weight: 0.9 },
]);
// { consensus: 'safe' | 'threat' | 'uncertain', confidence: number, criticalThreats: Threat[] }
```

Consensus thresholds:
- **threat** — Any critical threat OR weighted threat score > 0.5
- **safe** — Weighted threat score < 0.2
- **uncertain** — Weighted threat score between 0.2 and 0.5

## Performance Targets

- Detection: < 10ms per input
- Pattern matching: < 5ms
- PII scan: < 3ms
- HNSW search: 150x-12,500x faster than linear scan when connected to AgentDB

## Statistics

```typescript
const stats = await aidefence.getStats();
// {
//   detectionCount: number,
//   avgDetectionTimeMs: number,
//   learnedPatterns: number,
//   mitigationStrategies: number,
//   avgMitigationEffectiveness: number,
// }
```

## Integration Notes

- Uses `InMemoryVectorStore` by default; connect AgentDB for production HNSW performance
- Self-learning follows the ReasoningBank pattern for pattern acquisition
- Strange-loop meta-learning integration enables the system to reason about its own detection capabilities
- Thread-safe: safe for concurrent use across multiple agent sessions

