<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->

# API Reference — Testing RAG Poisoning

## Document Integrity Hash
```python
import hashlib, json

combined = json.dumps({"content": text, "source": source}, sort_keys=True)
doc_hash = hashlib.sha256(combined.encode()).hexdigest()
```

## Poisoning Indicator Scan
```python
import re

INDICATORS = [
    r"ignore\s+(all\s+)?previous",
    r"the\s+correct\s+answer\s+is",
    r"system\s*:\s*you\s+(are|must|should)",
]
for pattern in INDICATORS:
    if re.search(pattern, document, re.IGNORECASE):
        print(f"POISONING INDICATOR: {pattern}")
```

## Embedding Similarity Check
```python
import numpy as np

def cosine_sim(a, b):
    return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))

# Flag if poisoned doc ranks higher than trusted doc
if cosine_sim(query_emb, poison_emb) > cosine_sim(query_emb, trusted_emb):
    print("WARNING: Retrieval hijacking detected")
```

## Instruction Density Check
```python
import re

words = document.split()
instructions = len(re.findall(r"\b(must|should|always|never)\b", document, re.I))
density = instructions / max(len(words), 1)
if density > 0.05:
    print("WARNING: High instruction density — possible poisoning")
```
