Metadata-Version: 2.5
Name: revertx
Version: 0.2.0
Summary: Deterministic Execution Safety, Policy Enforcement, and Recovery Layer for AI Agents
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,mcp,policy-engine,rollback,saga,security
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.12
Requires-Dist: aiosqlite>=0.20
Requires-Dist: asyncpg>=0.29
Requires-Dist: fastapi>=0.115
Requires-Dist: fastmcp>=2.0
Requires-Dist: httpx>=0.27
Requires-Dist: jinja2>=3.1
Requires-Dist: pydantic-settings>=2.0
Requires-Dist: pydantic>=2.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: sqlalchemy[asyncio]>=2.0
Requires-Dist: uvicorn>=0.30
Description-Content-Type: text/markdown

# RevertX

**Deterministic Execution Safety, Policy Enforcement, and Recovery Layer for AI Agents.**

> **Release Status (`v0.2.0`):** **SQLite verified locally; PostgreSQL dialect-tested, live-cluster beta.**
>
> **Verified scope:** All 88 automated unit, integration, adversarial security, and OS `kill -9` crash-recovery tests pass against local WAL-mode SQLite (`aiosqlite`), alongside FastMCP, FastAPI/HTMX, and clean-room wheel installation.
> **PostgreSQL / live-cluster scope:** Async URL normalization, SQLAlchemy `postgresql+asyncpg` DDL compilation, dialect-guarded `SELECT ... FOR UPDATE` locking, and `asyncpg` engine construction are unit-tested; **end-to-end runtime execution against a live PostgreSQL server or multi-node cluster has not been run yet in local verification** and should be validated in staging before production rollout.

RevertX sits strictly in the execution path between autonomous AI agents (MCP clients, LangGraph, CrewAI, or custom Python scripts) and live databases or external APIs:

```text
AI Agent  ──▶  RevertX Safety Proxy  ──▶  Database / External API
                 ├─ Pre-State & OCC Snapshots (outside agent context)
                 ├─ 4-State Recovery Contracts & Policy Preconditions
                 ├─ Durable Sliding-Window Blast-Radius Breaker
                 ├─ Cryptographically Bound Telegram Approval Gate
                 └─ Idempotent Reverse-DAG Compensating Rollback
```

RevertX does **not** guess whether an LLM "hallucinated." It enforces **deterministic policy thresholds**, **business-record preconditions**, **Optimistic Concurrency Control (OCC)**, and **durable crash-safe Saga recovery**.

---

## Core Architecture Guarantees (`v0.2.0`)

1. **Explicit 4-State Recovery Contracts (`policies/policy.yaml`):** Every tool is classified as `read_only`, `transactional`, `compensatable`, `irreversible`, or `unsupported` with `operation_type` (`create` | `update` | `delete`), optional dot-path `created_id_field` extraction for cross-system `CREATE` sagas, and optional `verification.required: true` readback confirmation after compensation. Unclassified write tools fail closed.
2. **Shadow Mode Dry-Run (`--mode shadow` / `REVERTX_SHADOW_MODE`):** Executes `read_only` tools against live data while intercepting mutations after policy and isolated blast-radius checks into `WOULD_EXECUTE`, `WOULD_REQUIRE_APPROVAL`, or `WOULD_BLOCK` diff previews without touching external systems.
3. **Optimistic Concurrency Control (OCC):** Captures `version_before` / `version_after` (falling back to canonical SHA-256 `state_hash` when integer versions are unavailable). Before rolling back, RevertX checks live state—if an external actor modified the record, it halts immediately as `ROLLBACK_CONFLICT` instead of silently overwriting newer data.
4. **Durable Compensation State Machine & Crash Recovery:** Persists step states (`PENDING → EXECUTING → EXECUTED → COMPENSATION_PENDING → COMPENSATING → COMPENSATED / COMPENSATION_FAILED / ROLLBACK_CONFLICT`) in an isolated SQLite/PostgreSQL ledger and runs automatic startup recovery sweeps (`recover_stranded_compensations()`).
5. **Cryptographically Bound Single-Use Approvals & Two-Tier Redaction:** Computes `action_hash = sha256(canonical_json(tool_name, args, target_resource))` with hard `expires_at`, actor/chat allowlists, webhook secret checks, and atomic single-use consumption. Recursively redacts secrets before ledger persistence while also masking PII (`email`, `phone`, `ssn`) across Telegram prompts and dashboard views.
6. **Atomic Ledger-Backed Circuit Breaker & Transport Hardening:** Enforces sliding-window write velocity, row count, and cumulative per-run (`max_amount_per_run`) budgets atomically per run lock, alongside DNS-pinned SSRF protection, Streamable HTTP `Origin` checks, and explicit `REVERTX_TRUSTED_PROXIES` IP resolution.

---

## Quickstart (`uv` / `uvx`)

```powershell
# 1. Install dependencies
uv sync

# 2. (Standalone projects) Scaffold starter policies/policy.yaml & .env.example
uv run revertx init

# 3. Validate policies/policy.yaml fail-closed
uv run revertx check-policy

# 4. Run the MCP safety proxy against the local demo e-commerce store (live or shadow)
uv run revertx proxy --target demo
uv run revertx proxy --target demo --mode shadow

# 5. Launch the FastAPI + HTMX Safety Console (1-click Undo & OCC Conflicts)
uv run revertx dashboard
```

When published to PyPI, run zero-install via `uvx revertx` or install via `pip install revertx`.

---

## Python `@protect` SDK Quickstart

```python
import asyncio
from revertx import RevertXClient
from revertx.core.ledger import LedgerStore
from revertx.core.models import RecoveryContract, SnapshotData
from revertx.core.policy import load_policy

async def main() -> None:
    ledger = LedgerStore("sqlite+aiosqlite:///./revertx_ledger.db")
    await ledger.init_schema()
    policy = load_policy("policies/policy.yaml")
    client = RevertXClient(ledger, policy=policy)

    async def snapshot_order(args: dict, phase: str) -> SnapshotData:
        # Read live record state & version from your DB before/after mutation
        ...

    async def restore_order(args: dict, before_state: dict) -> None:
        # Idempotent compensator restoring prior state
        ...

    @client.protect(
        tool_name="update_order_status",
        recovery_contract=RecoveryContract.COMPENSATABLE,
        snapshot_fn=snapshot_order,
        compensator_fn=restore_order,
    )
    async def update_order_status(order_id: int, new_status: str) -> str:
        ...

    async with client.session("billing-agent") as run_id:
        await update_order_status(402, "Cancelled")
        # Trigger manual reverse-DAG rollback if needed:
        await client.rollback(run_id)

    await ledger.close()
```

---

## Golden Scenarios Verified Continuously

- **Scenario A (Policy Gate + Verified Rollback):** Agent updates `Order #402` (`Shipped` → `Cancelled`), then attempts `issue_refund(order_id=402, amount=15000)`. Deterministic policy checks (`15000 > approval_required_above: 1000` and `15000 > verified order amount 1500`) freeze the call in `PENDING_APPROVAL` with an `action_hash`-bound Telegram alert. Tapping **🛑 Reject & Undo** blocks the payout permanently and restores `Order #402` back to `Shipped`.
- **Scenario B (Blast-Radius Circuit Breaker):** Attempting >5 row mutations or >5 write calls within 60 seconds trips the durable circuit breaker **before** hitting the database, logs `BLOCKED`, and dispatches a Telegram safety alert.

---

## Telegram Setup

Copy `.env.example` to `.env` and configure:
```env
REVERTX_TELEGRAM_BOT_TOKEN=your_bot_token
REVERTX_TELEGRAM_CHAT_ID=your_chat_id
REVERTX_APPROVAL_TIMEOUT_SECONDS=120
```
Never commit `.env`.

---

## Verification

```powershell
uv run ruff check .
uv run mypy src/
uv run pytest -v
uv build
```
