Metadata-Version: 2.4
Name: ai-watchman
Version: 1.0.0
Summary: Autonomous AI Security Watchman for backend servers — real-time threat detection, jailbreak guards, dynamic policy engine, code healing, and premium dashboard
Home-page: https://github.com/Divodude/ai-watchman
Author: Divyansh
Author-email: ry604492@gmail.com
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Security
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: langchain>=0.3.0
Requires-Dist: langchain-core>=0.3.0
Requires-Dist: langchain-community>=0.3.0
Requires-Dist: langgraph>=0.2.0
Requires-Dist: fastapi>=0.110.0
Requires-Dist: uvicorn[standard]>=0.29.0
Requires-Dist: starlette>=0.37.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: requests>=2.32.0
Provides-Extra: groq
Requires-Dist: langchain-groq>=0.1.0; extra == "groq"
Provides-Extra: openai
Requires-Dist: langchain-openai>=0.1.0; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: langchain-anthropic>=0.1.0; extra == "anthropic"
Provides-Extra: ollama
Requires-Dist: langchain-ollama>=0.1.0; extra == "ollama"
Provides-Extra: cohere
Requires-Dist: langchain-cohere>=0.1.0; extra == "cohere"
Provides-Extra: google
Requires-Dist: langchain-google-genai>=1.0.0; extra == "google"
Provides-Extra: full
Requires-Dist: langchain-groq>=0.1.0; extra == "full"
Requires-Dist: langchain-openai>=0.1.0; extra == "full"
Requires-Dist: langchain-anthropic>=0.1.0; extra == "full"
Requires-Dist: langchain-ollama>=0.1.0; extra == "full"
Requires-Dist: langchain-cohere>=0.1.0; extra == "full"
Requires-Dist: langchain-google-genai>=1.0.0; extra == "full"
Requires-Dist: flask>=3.0.0; extra == "full"
Requires-Dist: django>=4.0; extra == "full"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: httpx>=0.27.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: ruff>=0.4.0; extra == "dev"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# AI Watchman 🛡️

> **Autonomous AI Security Watchman for any Python backend**
> Real-time threat detection · Jailbreak guards · Dynamic policy engine · AI code healing · Premium dashboard

[![PyPI](https://img.shields.io/badge/pip-ai--watchman-blue)](https://pypi.org/project/ai-watchman)
[![Python](https://img.shields.io/badge/Python-3.9%2B-blue)](https://python.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-green)](LICENSE)

---

## What is AI Watchman?

AI Watchman is a production-grade, drop-in security package that acts as an **autonomous guardian** for your backend server. It:

- 🔍 **Monitors** all server logs and HTTP traffic in real-time
- ⚡ **Detects** threats (SQL injection, XSS, path traversal, command injection, SSRF, prompt injection) using regex + AI
- 🔒 **Guards** against AI prompt injection / jailbreak attempts on every request
- ⚙️ **Adjusts** backend security policies dynamically (IP blocks, rate limits, auth requirements)
- 🔧 **Heals** source code automatically on crash — with git backup and rollback
- 📊 **Shows** everything in a beautiful real-time dashboard at `localhost:7474`
- 📝 **Logs** every action to an auditable SQLite change log with human-readable before/after states

---

## Quick Start

```bash
pip install ai-watchman[groq]   # or [openai], [anthropic], [ollama], [full]
```

```bash
# Initialize (creates watchman.yaml + opens dashboard)
watchman init

# Monitor any backend command
watchman run "uvicorn main:app --reload"
watchman run "python app.py" --auto-heal --auto-recover
```

---

## Framework Integration

### FastAPI (1 line)
```python
from fastapi import FastAPI
from watchman.integrations.fastapi_middleware import WatchmanMiddleware

app = FastAPI()
app.add_middleware(WatchmanMiddleware)              # ← that's it!
```

### Flask
```python
from flask import Flask
from watchman.integrations.flask_extension import Watchman

app = Flask(__name__)
watchman = Watchman(app)
```

### Django
```python
# settings.py
MIDDLEWARE = [
    'watchman.integrations.django_middleware.WatchmanMiddleware',
    # ... rest of your middleware
]
```

### Any Function / Subprocess
```python
from watchman.integrations.generic_hook import watch, WatchedProcess

@watch                         # Auto-heal on crash
def risky_function():
    ...

# Or wrap any shell command
proc = WatchedProcess("python worker.py", auto_heal=True, auto_recover=True)
proc.run()
```

---

## Configuration

```yaml
# watchman.yaml (auto-discovered in project root)
llm:
  provider: groq           # groq | openai | anthropic | ollama | cohere | google
  model: llama-3.3-70b-versatile

threat_detection:
  auto_mitigate_threshold: 7   # 7+ severity requires human approval
  notify_threshold: 4

policy_engine:
  mode: semi_auto              # auto | semi_auto | manual
  ip_block_duration_seconds: 3600

code_healing:
  enabled: true
  auto_patch: false            # Set true for CI/CD; always requires git
  ask_human_threshold: 7       # Crashes severity 7+ always ask human

alerts:
  channels:
    - type: slack
      webhook_url: "https://hooks.slack.com/..."
    - type: email
      smtp_host: smtp.gmail.com
      from_email: watchman@example.com
      to_emails: [admin@example.com]
```

**Supported LLM Providers** (auto-detected from API keys):

| Provider | Install | Env Var |
|----------|---------|---------|
| Groq | `pip install ai-watchman[groq]` | `GROQ_API_KEY` |
| OpenAI | `pip install ai-watchman[openai]` | `OPENAI_API_KEY` |
| Anthropic | `pip install ai-watchman[anthropic]` | `ANTHROPIC_API_KEY` |
| Ollama | `pip install ai-watchman[ollama]` | *(no key needed)* |
| Cohere | `pip install ai-watchman[cohere]` | `COHERE_API_KEY` |
| Google | `pip install ai-watchman[google]` | `GOOGLE_API_KEY` |

---

## Dashboard

```bash
watchman dashboard          # Opens at http://localhost:7474
```

Features:
- 📈 **Real-time threat chart** and event stream (WebSocket)
- ⚠️ **Pending approval queue** — approve/reject threats, policies, patches with one click
- 📋 **Full audit log** — every action with before/after state, rollback button
- ⚙️ **Live config editor** — change settings without restarting
- 🔧 **Code diff viewer** — review AI patches before applying

---

## Severity-Based Auto-Response

| Severity | Threats | Policies | Code Patches |
|----------|---------|----------|--------------|
| 0–3 | Auto-mitigate silently | Auto-apply | Auto-patch (if enabled) |
| 4–6 | Auto-mitigate + notify | Auto-apply + notify | Auto-patch + notify |
| 7–10 | **Pause → Human approval** | **Pause → Human approval** | **Pause → Human approval** |

---

## Change Log / Audit Trail

Every action is recorded with full before/after state:

```python
from watchman.core.change_log import ChangeLog

cl = ChangeLog()
entries = cl.list_recent(limit=50)
stats = cl.summary_stats()
# Rollback any entry:
cl.get_rollback_data(entry_id)
```

---

## Python API

```python
from watchman import create_watchman

wm = create_watchman()

# Scan text for threats
result = wm["threat_engine"].analyze_line("SELECT * FROM users WHERE 1=1--")

# Scan for jailbreak
jb = wm["jailbreak_guard"].scan("Ignore all previous instructions and...")

# Add a policy
from watchman.core.policy_manager import Policy, PolicyType
wm["policy_manager"].propose_policy(Policy(
    policy_type=PolicyType.IP_BLOCK,
    target="1.2.3.4",
    action="block",
    reason="Manual block",
    severity=8,
))

# Watch a file
wm["sentinel"].watch_file("/var/log/myapp.log")
wm["sentinel"].start()
```

---

## CLI Reference

```
watchman init                          Initialize config + open dashboard
watchman run "uvicorn main:app"        Monitor any command
  --auto-heal                          Auto-apply AI code fixes
  --auto-recover                       Auto-restart after successful fix
  --max-retries N                      Max auto-recovery attempts (default: 3)
watchman dashboard                     Open dashboard only
  --port 7474
  --no-browser
watchman status                        Show change log stats
watchman scan "SELECT 1=1 --"         One-shot threat scan
```

---

## Security Model

- **Jailbreak Guard**: 15+ regex patterns + heuristic scoring + optional LLM judge
- **Threat Signatures**: 120+ patterns across SQLi, XSS, SSRF, path traversal, command injection, XXE
- **Code Patching Safety**: File backup → git branch → diff preview → human approval → write → rollback available
- **Policy Rollback**: Every policy change is reversible from the dashboard
- **No sensitive data in logs**: Passwords, API keys, and card numbers trigger alerts, not storage

---

## License

MIT © Divyansh
