revertx 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. revertx-0.2.0/.dockerignore +13 -0
  2. revertx-0.2.0/.env.example +28 -0
  3. revertx-0.2.0/.github/workflows/ci.yml +28 -0
  4. revertx-0.2.0/.gitignore +37 -0
  5. revertx-0.2.0/.python-version +1 -0
  6. revertx-0.2.0/CHANGELOG.md +14 -0
  7. revertx-0.2.0/CONTRIBUTING.md +25 -0
  8. revertx-0.2.0/Dockerfile +26 -0
  9. revertx-0.2.0/LICENSE +21 -0
  10. revertx-0.2.0/PKG-INFO +155 -0
  11. revertx-0.2.0/README.md +128 -0
  12. revertx-0.2.0/SECURITY.md +14 -0
  13. revertx-0.2.0/demo_store/__init__.py +1 -0
  14. revertx-0.2.0/demo_store/db.py +75 -0
  15. revertx-0.2.0/demo_store/server.py +69 -0
  16. revertx-0.2.0/demo_store/snapshots.py +97 -0
  17. revertx-0.2.0/demo_store/tools.py +246 -0
  18. revertx-0.2.0/docker-compose.yml +48 -0
  19. revertx-0.2.0/policies/.gitkeep +0 -0
  20. revertx-0.2.0/policies/policy.yaml +46 -0
  21. revertx-0.2.0/pyproject.toml +75 -0
  22. revertx-0.2.0/rules.md +43 -0
  23. revertx-0.2.0/src/revertx/__init__.py +7 -0
  24. revertx-0.2.0/src/revertx/adapters/__init__.py +1 -0
  25. revertx-0.2.0/src/revertx/adapters/http_gateway.py +218 -0
  26. revertx-0.2.0/src/revertx/adapters/mcp_http.py +133 -0
  27. revertx-0.2.0/src/revertx/adapters/mcp_proxy.py +249 -0
  28. revertx-0.2.0/src/revertx/adapters/sdk.py +203 -0
  29. revertx-0.2.0/src/revertx/cli.py +444 -0
  30. revertx-0.2.0/src/revertx/core/__init__.py +1 -0
  31. revertx-0.2.0/src/revertx/core/approvals.py +699 -0
  32. revertx-0.2.0/src/revertx/core/auth.py +122 -0
  33. revertx-0.2.0/src/revertx/core/circuit_breaker.py +182 -0
  34. revertx-0.2.0/src/revertx/core/config.py +82 -0
  35. revertx-0.2.0/src/revertx/core/dag.py +72 -0
  36. revertx-0.2.0/src/revertx/core/engine.py +794 -0
  37. revertx-0.2.0/src/revertx/core/exceptions.py +63 -0
  38. revertx-0.2.0/src/revertx/core/http_proxy.py +338 -0
  39. revertx-0.2.0/src/revertx/core/ledger.py +710 -0
  40. revertx-0.2.0/src/revertx/core/mcp_guard.py +56 -0
  41. revertx-0.2.0/src/revertx/core/models.py +170 -0
  42. revertx-0.2.0/src/revertx/core/policy.py +280 -0
  43. revertx-0.2.0/src/revertx/core/rollback.py +453 -0
  44. revertx-0.2.0/src/revertx/core/security.py +348 -0
  45. revertx-0.2.0/src/revertx/dashboard/__init__.py +1 -0
  46. revertx-0.2.0/src/revertx/dashboard/app.py +73 -0
  47. revertx-0.2.0/src/revertx/dashboard/routes.py +138 -0
  48. revertx-0.2.0/src/revertx/dashboard/templates/base.html +70 -0
  49. revertx-0.2.0/src/revertx/dashboard/templates/index.html +11 -0
  50. revertx-0.2.0/src/revertx/dashboard/templates/partials/run_detail_content.html +123 -0
  51. revertx-0.2.0/src/revertx/dashboard/templates/partials/run_table.html +31 -0
  52. revertx-0.2.0/src/revertx/dashboard/templates/run_detail.html +5 -0
  53. revertx-0.2.0/src/revertx/templates/.env.example +28 -0
  54. revertx-0.2.0/src/revertx/templates/policy.yaml +46 -0
  55. revertx-0.2.0/tests/__init__.py +1 -0
  56. revertx-0.2.0/tests/test_adversarial_suites.py +1251 -0
  57. revertx-0.2.0/tests/test_approvals.py +397 -0
  58. revertx-0.2.0/tests/test_batch1_security_and_concurrency.py +551 -0
  59. revertx-0.2.0/tests/test_batch2_polish_and_recovery.py +416 -0
  60. revertx-0.2.0/tests/test_dashboard.py +178 -0
  61. revertx-0.2.0/tests/test_demo_store.py +87 -0
  62. revertx-0.2.0/tests/test_golden_scenarios.py +239 -0
  63. revertx-0.2.0/tests/test_http_gateway.py +273 -0
  64. revertx-0.2.0/tests/test_ledger_and_dag.py +336 -0
  65. revertx-0.2.0/tests/test_mcp_passthrough.py +126 -0
  66. revertx-0.2.0/tests/test_policy_and_breaker.py +262 -0
  67. revertx-0.2.0/tests/test_postgres_ledger.py +67 -0
  68. revertx-0.2.0/tests/test_rollback_edge_cases.py +311 -0
  69. revertx-0.2.0/tests/test_sdk_adapter.py +211 -0
  70. revertx-0.2.0/tests/test_smoke.py +25 -0
  71. revertx-0.2.0/tests/test_v02_create_saga_and_shadow_mode.py +573 -0
  72. revertx-0.2.0/uv.lock +2122 -0
@@ -0,0 +1,13 @@
1
+ .venv/
2
+ .git/
3
+ .pytest_cache/
4
+ .mypy_cache/
5
+ .ruff_cache/
6
+ __pycache__/
7
+ *.py[cod]
8
+ *.db
9
+ *.sqlite
10
+ *.sqlite3
11
+ .env
12
+ dist/
13
+ build/
@@ -0,0 +1,28 @@
1
+ # RevertX Local Environment Configuration (Copy to .env and fill real values)
2
+ # Rule 3: Never commit .env or hardcode secrets in source files.
3
+
4
+ # Isolated RevertX append-only ledger database
5
+ REVERTX_LEDGER_DB_URL=sqlite+aiosqlite:///./revertx_ledger.db
6
+
7
+ # Policy ruleset path
8
+ REVERTX_POLICY_PATH=policies/policy.yaml
9
+
10
+ # Telegram Human-in-the-Loop Approval Gate
11
+ REVERTX_TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
12
+ REVERTX_TELEGRAM_CHAT_ID=your_telegram_chat_id_here
13
+ REVERTX_TELEGRAM_WEBHOOK_SECRET=your_webhook_secret_here
14
+ REVERTX_TELEGRAM_ALLOWED_USER_IDS=["123456789"]
15
+ REVERTX_APPROVAL_TIMEOUT_SECONDS=120
16
+
17
+ # API Auth & IP Allowlist (empty allowlist denies all; never fail open)
18
+ REVERTX_API_TOKEN=change_me_to_a_strong_random_token
19
+ REVERTX_ALLOWED_IPS=["127.0.0.1","::1"]
20
+ REVERTX_TRUSTED_PROXIES=[]
21
+
22
+ # HTTP Reverse Gateway upstream target (keep false in production to block SSRF)
23
+ REVERTX_UPSTREAM_BASE_URL=http://127.0.0.1:9000
24
+ REVERTX_ALLOW_LOCAL_UPSTREAM=false
25
+
26
+ # Safe local demo e-commerce store database
27
+ REVERTX_DEMO_DB_PATH=demo_store/demo_store.db
28
+ REVERTX_SHADOW_MODE=false
@@ -0,0 +1,28 @@
1
+ name: RevertX CI
2
+
3
+ on:
4
+ push:
5
+ branches: ["main"]
6
+ pull_request:
7
+ branches: ["main"]
8
+
9
+ jobs:
10
+ verify:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: astral-sh/setup-uv@v4
15
+ with:
16
+ enable-cache: true
17
+ - name: Install Python 3.12 and dependencies
18
+ run: |
19
+ uv python install 3.12
20
+ uv sync --frozen
21
+ - name: Lint with Ruff
22
+ run: uv run ruff check .
23
+ - name: Strict Type Check with Mypy
24
+ run: uv run mypy src/
25
+ - name: Run Test Suite (including Golden Scenarios A & B)
26
+ run: uv run pytest -v
27
+ - name: Verify Package Build
28
+ run: uv build
@@ -0,0 +1,37 @@
1
+ # Environment & secrets (Rule 3: never commit .env)
2
+ .env
3
+ .env.*
4
+ !.env.example
5
+
6
+ # Python & uv virtual environments
7
+ .venv/
8
+ __pycache__/
9
+ *.py[cod]
10
+ *$py.class
11
+ *.egg-info/
12
+ dist/
13
+ build/
14
+
15
+ # Local SQLite databases (ledger & demo store)
16
+ *.db
17
+ *.db-wal
18
+ *.db-shm
19
+ *.db-journal
20
+ *.sqlite
21
+ *.sqlite3
22
+
23
+ # Internal planning, audit logs, and agent workspace rules
24
+ 29-11-2026.md
25
+ MILESTONES/
26
+ .agents/
27
+
28
+ # Tooling caches
29
+ .pytest_cache/
30
+ .mypy_cache/
31
+ .ruff_cache/
32
+
33
+ # IDE & OS files
34
+ .vscode/
35
+ .idea/
36
+ .DS_Store
37
+ Thumbs.db
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## [0.2.0] - 2026-11-29
4
+
5
+ ### Added
6
+ - **Cross-System `CREATE` Sagas:** Support `operation_type: "create"` with `created_id_field` dot-path extraction (`__tool_output__`, `__created_id__`), nullable pre-state for `create` actions, deterministic `idempotency_key` propagation, and `COMPENSATION_FAILED` fail-closed handling when created IDs cannot be resolved.
7
+ - **Shadow Mode Dry-Run Simulation (`shadow_mode=True`):** Intercept write tools without mutating downstream systems, recording `WOULD_EXECUTE`, `WOULD_REQUIRE_APPROVAL`, and `WOULD_BLOCK` intents isolated from live circuit-breaker counts and excluded from live rollback eligibility.
8
+ - **Dialect-Neutral Schema Upgrades:** Startup additive column migration (`_ensure_action_log_columns`) tested across SQLite and PostgreSQL dialects.
9
+ - **Security Hardening:** Timing-safe Telegram webhook secret verification, SSRF DNS resolution + IPv6 unwrapping + IP pinning (`PinnedIPNetworkBackend`), MCP Streamable HTTP loopback binding and `Origin` validation, atomic DB budget reservation (`BEGIN IMMEDIATE` / `SELECT ... FOR UPDATE`), and `revertx init` clean-room template scaffolding.
10
+
11
+ ## [0.1.0] - 2026-11-29
12
+
13
+ ### Added
14
+ - **Initial Local-First Release:** Local `demo_store` SQLite sandbox, FastMCP proxy (`revertx proxy`), async SQLAlchemy 2.0 append-only ledger (`agent_runs`, `action_logs`, `approval_requests`, `rollback_logs`), OCC versioning + canonical SHA-256 hashing, `policies/policy.yaml` recovery contracts, sliding-window circuit breaker, single-use Telegram approval gate, reverse-DAG compensation engine, Python `@protect` SDK adapter (`RevertXClient`), FastAPI + HTMX Safety Console (`revertx dashboard`), and CLI commands (`init`, `proxy`, `gateway`, `dashboard`, `rollback`, `check-policy`).
@@ -0,0 +1,25 @@
1
+ # Contributing to RevertX
2
+
3
+ Thank you for contributing to **RevertX**!
4
+
5
+ ## Development Setup
6
+
7
+ ```powershell
8
+ uv sync
9
+ uv run pytest -v
10
+ ```
11
+
12
+ ## Non-Negotiable Engineering Rules
13
+
14
+ Before opening a pull request, read [rules.md](rules.md):
15
+
16
+ 1. **Keep `core/` Framework-Agnostic:** Modules in `src/revertx/core/` must never import from `adapters/`, `dashboard/`, or `demo_store/`.
17
+ 2. **Keep Adapters Thin:** Keep `mcp_proxy.py`, `mcp_http.py`, `sdk.py`, and `http_gateway.py` under the 250-line soft cap with zero core business logic in adapters.
18
+ 3. **Fail Closed by Default:** Never swallow exceptions or bypass missing policies/snapshots/approvals.
19
+ 4. **Tests & Quality Gates Required:** Every PR must pass:
20
+ ```powershell
21
+ uv run ruff check .
22
+ uv run mypy src/
23
+ uv run pytest -v
24
+ ```
25
+ Golden Scenarios A & B (`tests/test_golden_scenarios.py`) must always pass.
@@ -0,0 +1,26 @@
1
+ # Multi-stage uv build for RevertX HTTP Gateway & Safety Console
2
+ FROM python:3.12-slim AS builder
3
+
4
+ COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
5
+ WORKDIR /app
6
+
7
+ COPY pyproject.toml uv.lock README.md ./
8
+ RUN uv sync --frozen --no-dev --no-install-project
9
+
10
+ COPY src/ src/
11
+ COPY policies/ policies/
12
+ RUN uv sync --frozen --no-dev
13
+
14
+ FROM python:3.12-slim AS runtime
15
+ WORKDIR /app
16
+
17
+ COPY --from=builder /app/.venv /app/.venv
18
+ COPY --from=builder /app/src /app/src
19
+ COPY --from=builder /app/policies /app/policies
20
+
21
+ ENV PATH="/app/.venv/bin:$PATH" \
22
+ PYTHONUNBUFFERED=1 \
23
+ REVERTX_POLICY_PATH="/app/policies/policy.yaml"
24
+
25
+ EXPOSE 8000 8080
26
+ CMD ["revertx", "dashboard", "--host", "0.0.0.0", "--port", "8000"]
revertx-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NANDA SUNIL D
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
revertx-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.5
2
+ Name: revertx
3
+ Version: 0.2.0
4
+ Summary: Deterministic Execution Safety, Policy Enforcement, and Recovery Layer for AI Agents
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: ai-agents,mcp,policy-engine,rollback,saga,security
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Topic :: Security
13
+ Classifier: Topic :: Software Development :: Libraries
14
+ Requires-Python: >=3.12
15
+ Requires-Dist: aiosqlite>=0.20
16
+ Requires-Dist: asyncpg>=0.29
17
+ Requires-Dist: fastapi>=0.115
18
+ Requires-Dist: fastmcp>=2.0
19
+ Requires-Dist: httpx>=0.27
20
+ Requires-Dist: jinja2>=3.1
21
+ Requires-Dist: pydantic-settings>=2.0
22
+ Requires-Dist: pydantic>=2.0
23
+ Requires-Dist: pyyaml>=6.0
24
+ Requires-Dist: sqlalchemy[asyncio]>=2.0
25
+ Requires-Dist: uvicorn>=0.30
26
+ Description-Content-Type: text/markdown
27
+
28
+ # RevertX
29
+
30
+ **Deterministic Execution Safety, Policy Enforcement, and Recovery Layer for AI Agents.**
31
+
32
+ > **Release Status (`v0.2.0`):** **SQLite verified locally; PostgreSQL dialect-tested, live-cluster beta.**
33
+ >
34
+ > **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.
35
+ > **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.
36
+
37
+ 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:
38
+
39
+ ```text
40
+ AI Agent ──▶ RevertX Safety Proxy ──▶ Database / External API
41
+ ├─ Pre-State & OCC Snapshots (outside agent context)
42
+ ├─ 4-State Recovery Contracts & Policy Preconditions
43
+ ├─ Durable Sliding-Window Blast-Radius Breaker
44
+ ├─ Cryptographically Bound Telegram Approval Gate
45
+ └─ Idempotent Reverse-DAG Compensating Rollback
46
+ ```
47
+
48
+ 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**.
49
+
50
+ ---
51
+
52
+ ## Core Architecture Guarantees (`v0.2.0`)
53
+
54
+ 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.
55
+ 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.
56
+ 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.
57
+ 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()`).
58
+ 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.
59
+ 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.
60
+
61
+ ---
62
+
63
+ ## Quickstart (`uv` / `uvx`)
64
+
65
+ ```powershell
66
+ # 1. Install dependencies
67
+ uv sync
68
+
69
+ # 2. (Standalone projects) Scaffold starter policies/policy.yaml & .env.example
70
+ uv run revertx init
71
+
72
+ # 3. Validate policies/policy.yaml fail-closed
73
+ uv run revertx check-policy
74
+
75
+ # 4. Run the MCP safety proxy against the local demo e-commerce store (live or shadow)
76
+ uv run revertx proxy --target demo
77
+ uv run revertx proxy --target demo --mode shadow
78
+
79
+ # 5. Launch the FastAPI + HTMX Safety Console (1-click Undo & OCC Conflicts)
80
+ uv run revertx dashboard
81
+ ```
82
+
83
+ When published to PyPI, run zero-install via `uvx revertx` or install via `pip install revertx`.
84
+
85
+ ---
86
+
87
+ ## Python `@protect` SDK Quickstart
88
+
89
+ ```python
90
+ import asyncio
91
+ from revertx import RevertXClient
92
+ from revertx.core.ledger import LedgerStore
93
+ from revertx.core.models import RecoveryContract, SnapshotData
94
+ from revertx.core.policy import load_policy
95
+
96
+ async def main() -> None:
97
+ ledger = LedgerStore("sqlite+aiosqlite:///./revertx_ledger.db")
98
+ await ledger.init_schema()
99
+ policy = load_policy("policies/policy.yaml")
100
+ client = RevertXClient(ledger, policy=policy)
101
+
102
+ async def snapshot_order(args: dict, phase: str) -> SnapshotData:
103
+ # Read live record state & version from your DB before/after mutation
104
+ ...
105
+
106
+ async def restore_order(args: dict, before_state: dict) -> None:
107
+ # Idempotent compensator restoring prior state
108
+ ...
109
+
110
+ @client.protect(
111
+ tool_name="update_order_status",
112
+ recovery_contract=RecoveryContract.COMPENSATABLE,
113
+ snapshot_fn=snapshot_order,
114
+ compensator_fn=restore_order,
115
+ )
116
+ async def update_order_status(order_id: int, new_status: str) -> str:
117
+ ...
118
+
119
+ async with client.session("billing-agent") as run_id:
120
+ await update_order_status(402, "Cancelled")
121
+ # Trigger manual reverse-DAG rollback if needed:
122
+ await client.rollback(run_id)
123
+
124
+ await ledger.close()
125
+ ```
126
+
127
+ ---
128
+
129
+ ## Golden Scenarios Verified Continuously
130
+
131
+ - **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`.
132
+ - **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.
133
+
134
+ ---
135
+
136
+ ## Telegram Setup
137
+
138
+ Copy `.env.example` to `.env` and configure:
139
+ ```env
140
+ REVERTX_TELEGRAM_BOT_TOKEN=your_bot_token
141
+ REVERTX_TELEGRAM_CHAT_ID=your_chat_id
142
+ REVERTX_APPROVAL_TIMEOUT_SECONDS=120
143
+ ```
144
+ Never commit `.env`.
145
+
146
+ ---
147
+
148
+ ## Verification
149
+
150
+ ```powershell
151
+ uv run ruff check .
152
+ uv run mypy src/
153
+ uv run pytest -v
154
+ uv build
155
+ ```
@@ -0,0 +1,128 @@
1
+ # RevertX
2
+
3
+ **Deterministic Execution Safety, Policy Enforcement, and Recovery Layer for AI Agents.**
4
+
5
+ > **Release Status (`v0.2.0`):** **SQLite verified locally; PostgreSQL dialect-tested, live-cluster beta.**
6
+ >
7
+ > **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.
8
+ > **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.
9
+
10
+ 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:
11
+
12
+ ```text
13
+ AI Agent ──▶ RevertX Safety Proxy ──▶ Database / External API
14
+ ├─ Pre-State & OCC Snapshots (outside agent context)
15
+ ├─ 4-State Recovery Contracts & Policy Preconditions
16
+ ├─ Durable Sliding-Window Blast-Radius Breaker
17
+ ├─ Cryptographically Bound Telegram Approval Gate
18
+ └─ Idempotent Reverse-DAG Compensating Rollback
19
+ ```
20
+
21
+ 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**.
22
+
23
+ ---
24
+
25
+ ## Core Architecture Guarantees (`v0.2.0`)
26
+
27
+ 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.
28
+ 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.
29
+ 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.
30
+ 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()`).
31
+ 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.
32
+ 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.
33
+
34
+ ---
35
+
36
+ ## Quickstart (`uv` / `uvx`)
37
+
38
+ ```powershell
39
+ # 1. Install dependencies
40
+ uv sync
41
+
42
+ # 2. (Standalone projects) Scaffold starter policies/policy.yaml & .env.example
43
+ uv run revertx init
44
+
45
+ # 3. Validate policies/policy.yaml fail-closed
46
+ uv run revertx check-policy
47
+
48
+ # 4. Run the MCP safety proxy against the local demo e-commerce store (live or shadow)
49
+ uv run revertx proxy --target demo
50
+ uv run revertx proxy --target demo --mode shadow
51
+
52
+ # 5. Launch the FastAPI + HTMX Safety Console (1-click Undo & OCC Conflicts)
53
+ uv run revertx dashboard
54
+ ```
55
+
56
+ When published to PyPI, run zero-install via `uvx revertx` or install via `pip install revertx`.
57
+
58
+ ---
59
+
60
+ ## Python `@protect` SDK Quickstart
61
+
62
+ ```python
63
+ import asyncio
64
+ from revertx import RevertXClient
65
+ from revertx.core.ledger import LedgerStore
66
+ from revertx.core.models import RecoveryContract, SnapshotData
67
+ from revertx.core.policy import load_policy
68
+
69
+ async def main() -> None:
70
+ ledger = LedgerStore("sqlite+aiosqlite:///./revertx_ledger.db")
71
+ await ledger.init_schema()
72
+ policy = load_policy("policies/policy.yaml")
73
+ client = RevertXClient(ledger, policy=policy)
74
+
75
+ async def snapshot_order(args: dict, phase: str) -> SnapshotData:
76
+ # Read live record state & version from your DB before/after mutation
77
+ ...
78
+
79
+ async def restore_order(args: dict, before_state: dict) -> None:
80
+ # Idempotent compensator restoring prior state
81
+ ...
82
+
83
+ @client.protect(
84
+ tool_name="update_order_status",
85
+ recovery_contract=RecoveryContract.COMPENSATABLE,
86
+ snapshot_fn=snapshot_order,
87
+ compensator_fn=restore_order,
88
+ )
89
+ async def update_order_status(order_id: int, new_status: str) -> str:
90
+ ...
91
+
92
+ async with client.session("billing-agent") as run_id:
93
+ await update_order_status(402, "Cancelled")
94
+ # Trigger manual reverse-DAG rollback if needed:
95
+ await client.rollback(run_id)
96
+
97
+ await ledger.close()
98
+ ```
99
+
100
+ ---
101
+
102
+ ## Golden Scenarios Verified Continuously
103
+
104
+ - **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`.
105
+ - **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.
106
+
107
+ ---
108
+
109
+ ## Telegram Setup
110
+
111
+ Copy `.env.example` to `.env` and configure:
112
+ ```env
113
+ REVERTX_TELEGRAM_BOT_TOKEN=your_bot_token
114
+ REVERTX_TELEGRAM_CHAT_ID=your_chat_id
115
+ REVERTX_APPROVAL_TIMEOUT_SECONDS=120
116
+ ```
117
+ Never commit `.env`.
118
+
119
+ ---
120
+
121
+ ## Verification
122
+
123
+ ```powershell
124
+ uv run ruff check .
125
+ uv run mypy src/
126
+ uv run pytest -v
127
+ uv build
128
+ ```
@@ -0,0 +1,14 @@
1
+ # Security Policy
2
+
3
+ ## Security Architecture
4
+
5
+ RevertX is a **Deterministic Execution Safety, Policy Enforcement, and Recovery Layer**:
6
+ - **Isolated Ledger:** The proxied AI agent never receives write/delete access to `revertx_ledger` or `policies/policy.yaml`.
7
+ - **Fail-Closed Defaults:** Unclassified write tools, malformed policies, snapshot failures, expired approvals, and mismatched `action_hash` payloads block execution.
8
+ - **Cryptographic Approval Binding:** Approvals bind `sha256(canonical_json(tool_name, args, target_resource))` with single-use atomic database transitions and hard `expires_at` enforcement.
9
+ - **OCC Lost-Update Prevention:** Compensating rollbacks verify live `version` / `ETag` / SHA-256 hashes before restoring state and halt as `ROLLBACK_CONFLICT` on external edits.
10
+
11
+ ## Reporting a Vulnerability
12
+
13
+ Please do **not** open a public GitHub issue for security vulnerabilities.
14
+ Report vulnerabilities privately via GitHub Security Advisories or directly to the RevertX maintainers with reproduction steps and impact assessment. Never include real API keys, Telegram bot tokens, or production credentials in reports or logs.
@@ -0,0 +1 @@
1
+ """Safe local e-commerce sandbox for testing RevertX without risking real data."""
@@ -0,0 +1,75 @@
1
+ """Async SQLite sandbox database and deterministic seed data for demo_store."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+ from pathlib import Path
7
+
8
+ import aiosqlite
9
+
10
+ SEED_ORDERS: tuple[tuple[int, str, float, str, float], ...] = (
11
+ (401, "Aarav Sharma", 850.0, "Delivered", 0.0),
12
+ (402, "Priya Nair", 1500.0, "Shipped", 0.0),
13
+ (403, "Rohan Verma", 3200.0, "Processing", 0.0),
14
+ (404, "Ananya Iyer", 499.0, "Delivered", 0.0),
15
+ (405, "Vikram Patel", 2100.0, "Shipped", 0.0),
16
+ )
17
+
18
+ _CREATE_ORDERS_SQL = """
19
+ CREATE TABLE IF NOT EXISTS orders (
20
+ order_id INTEGER PRIMARY KEY,
21
+ customer_name TEXT NOT NULL,
22
+ amount REAL NOT NULL,
23
+ status TEXT NOT NULL,
24
+ refunded_amount REAL NOT NULL DEFAULT 0.0,
25
+ version INTEGER NOT NULL DEFAULT 1,
26
+ shipping_note TEXT NOT NULL DEFAULT '',
27
+ updated_at TEXT NOT NULL
28
+ );
29
+ """
30
+
31
+
32
+ async def _ensure_order_columns(conn: aiosqlite.Connection) -> None:
33
+ async with conn.execute("PRAGMA table_info(orders);") as cursor:
34
+ columns = {str(row[1]) for row in await cursor.fetchall()}
35
+ if "version" not in columns:
36
+ await conn.execute("ALTER TABLE orders ADD COLUMN version INTEGER NOT NULL DEFAULT 1;")
37
+ if "shipping_note" not in columns:
38
+ await conn.execute(
39
+ "ALTER TABLE orders ADD COLUMN shipping_note TEXT NOT NULL DEFAULT '';"
40
+ )
41
+
42
+
43
+ async def init_demo_db(db_path: Path | str, *, reset: bool = False) -> Path:
44
+ """Create the demo orders table and seed 5 deterministic orders if empty."""
45
+ resolved = Path(db_path)
46
+ resolved.parent.mkdir(parents=True, exist_ok=True)
47
+
48
+ async with aiosqlite.connect(resolved, timeout=5.0) as conn:
49
+ await conn.execute("PRAGMA journal_mode=WAL;")
50
+ await conn.execute("PRAGMA busy_timeout=5000;")
51
+ if reset:
52
+ await conn.execute("DROP TABLE IF EXISTS orders;")
53
+ await conn.execute(_CREATE_ORDERS_SQL)
54
+ await _ensure_order_columns(conn)
55
+
56
+ async with conn.execute("SELECT COUNT(*) FROM orders;") as cursor:
57
+ row = await cursor.fetchone()
58
+ existing_count = int(row[0]) if row is not None else 0
59
+
60
+ if existing_count == 0:
61
+ now_iso = datetime.now(UTC).isoformat()
62
+ await conn.executemany(
63
+ """
64
+ INSERT INTO orders (
65
+ order_id, customer_name, amount, status, refunded_amount, updated_at
66
+ ) VALUES (?, ?, ?, ?, ?, ?);
67
+ """,
68
+ [
69
+ (order_id, name, amount, status, refunded, now_iso)
70
+ for order_id, name, amount, status, refunded in SEED_ORDERS
71
+ ],
72
+ )
73
+ await conn.commit()
74
+
75
+ return resolved
@@ -0,0 +1,69 @@
1
+ """FastMCP upstream server exposing demo_store e-commerce tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from fastmcp import FastMCP
8
+
9
+ from demo_store.db import init_demo_db
10
+ from demo_store.tools import (
11
+ DeleteOrdersResult,
12
+ OrderRecord,
13
+ OrderUpdateResult,
14
+ RefundResult,
15
+ delete_orders,
16
+ get_order,
17
+ issue_refund,
18
+ list_orders,
19
+ update_order_status,
20
+ )
21
+ from revertx.core.config import get_settings
22
+
23
+
24
+ def create_demo_server(db_path: Path | None = None) -> FastMCP:
25
+ """Build a FastMCP server bound to the given SQLite demo database."""
26
+ target_db = db_path or get_settings().demo_db_path
27
+ mcp = FastMCP(name="demo-store")
28
+
29
+ @mcp.tool(name="get_order")
30
+ async def tool_get_order(order_id: int) -> OrderRecord:
31
+ """Fetch an order record by order_id."""
32
+ await init_demo_db(target_db)
33
+ return await get_order(target_db, order_id)
34
+
35
+ @mcp.tool(name="list_orders")
36
+ async def tool_list_orders() -> list[OrderRecord]:
37
+ """List all orders in the demo store."""
38
+ await init_demo_db(target_db)
39
+ return await list_orders(target_db)
40
+
41
+ @mcp.tool(name="update_order_status")
42
+ async def tool_update_order_status(order_id: int, new_status: str) -> OrderUpdateResult:
43
+ """Update the status of an order (reversible operation)."""
44
+ await init_demo_db(target_db)
45
+ return await update_order_status(target_db, order_id, new_status)
46
+
47
+ @mcp.tool(name="issue_refund")
48
+ async def tool_issue_refund(order_id: int, amount: float) -> RefundResult:
49
+ """Issue a financial refund for an order (irreversible payout)."""
50
+ await init_demo_db(target_db)
51
+ return await issue_refund(target_db, order_id, amount)
52
+
53
+ @mcp.tool(name="delete_orders")
54
+ async def tool_delete_orders(order_ids: list[int]) -> DeleteOrdersResult:
55
+ """Delete one or more orders by ID."""
56
+ await init_demo_db(target_db)
57
+ return await delete_orders(target_db, order_ids)
58
+
59
+ return mcp
60
+
61
+
62
+ def main() -> None:
63
+ """Run the demo-store MCP server over stdio."""
64
+ server = create_demo_server()
65
+ server.run()
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()