Ultra-lean, zero-external-dependency, event-sourced durable execution state machine designed to replace fragile in-memory
while Trueloops in autonomous AI agents.
ZeroLoop has zero third-party runtime dependencies and runs directly on Python 3.10+ stdlib:
# Run directly from repository root (CLI)
python3 zeroloop-py/zeroloop.py --help
# Or set PYTHONPATH when running Python scripts from the repository root
export PYTHONPATH="$(pwd)/zeroloop-py:${PYTHONPATH:-}"In-memory while True loops lose progress when a process exits or crashes, burning duplicate tokens and risking repeated external side effects.
ZeroLoop provides SQLite WAL event-sourcing in a pure-stdlib Python module:
- Crash Recovery & Replay Cursor: Persists journaled steps, checkpoints, and
statein SQLite WAL. After an unexpected exit whileRUNNING,DurableLoop.load(loop_id)rehydrates context/state (in5.91 msacross a7,002-event journal on Apple Silicon) and advances a deterministic replay cursor across completedstep_start()/step_complete()sequences. - Atomic Idempotency Gate & Reconciliation: Claims tool calls transactionally (
CLAIMED->COMMITTED/INDETERMINATE) usinghash(step_idx, tool_name, sanitized_inputs)and passeszeroloop_idempotency_key({loop_id}:{hash}) to handlers supporting it. Committed results replay from cache; interrupted or failed in-flight calls raiseLoopReconciliationRequiredrather than blindly re-executing un-reconciled mutations. - Human-in-the-Loop Pauses (
PAUSED):loop.pause()persists state + checkpoint transactionally, closes DB connections, and raisesLoopPausedException. Later,loop.resume()or--resumevalidates the durablePAUSEDstate and transitions atomically back toRUNNING. - Cross-Process Locked Auto-Pruning: FIFO pruning enforces
ZEROLOOP_MAX_STORAGE_MBandZEROLOOP_RETENTION_DAYSusing non-blocking exclusive file locks and inode/state re-checks, never touchingRUNNINGorPAUSEDloops.
Measured via python3 benchmarks/benchmark.py on Darwin arm64 | Python 3.12.2:
| Operation |
|
|
|
Throughput | Command |
|---|---|---|---|---|---|
| Canonical Idempotency Hashing | 4.4 µs | 4.5 µs | 9.1 µs | ~226,450 ops/sec | python3 benchmarks/benchmark.py |
| Cryptographic Journal Append (SHA-256 v2) | 47.3 µs | 63.2 µs | 124.0 µs | ~21,145 events/sec | python3 benchmarks/benchmark.py |
| Complete Step Lifecycle | 343.8 µs | 390.4 µs | 2701.1 µs | ~2,909 steps/sec | python3 benchmarks/benchmark.py |
Rehydration (7,002 events, read-only) |
5.91 ms | — | — | ~169 loads/sec | python3 benchmarks/benchmark.py |
Full Rehydration + Chain Verification (7,002 events) |
31.37 ms | 34.72 ms | 35.20 ms | ~32 audits/sec | python3 benchmarks/benchmark.py |
(Run python3 benchmarks/benchmark.py locally to reproduce. No unmeasured Rust or external orchestrator figures are listed.)
ZeroLoop provides the durable state machine in the CreativeUnCommons suite. Integration with sister packages is explicitly configured via helper bridges or callbacks:
- ZeroMCP (
bridges/zeromcp_bridge.py):ZeroMCPSupervisor.dispatch(...)wraps tool calls inloop.execute_tool(...)using ZeroLoop's atomic idempotency gate. - HyperGate (
bridges/hypergate_bridge.py):ZeroLoopHyperGateInterceptor.route_and_execute_llm(...)calls your router/LLM callback, records spend vialoop.record_cost(...), and pauses whenmax_cost_limit_usdis reached. - ZeroLeak (
bridges/zeroleak_bridge.py): RawDurableLoopjournals store raw step inputs/outputs unless scrubbed at the boundary. Route payloads throughZeroLoopSanitizeror passsanitize_inputs_fn=toloop.execute_tool(...)when journals must not contain raw PII. - AgentTrace (
bridges/agenttrace_bridge.py):ZeroLoopTracePublisherexplicitly starts spans (start_loop_span), records transitions (record_transition), and finishes spans with receipt metrics (finish_loop_span).
from zeroloop import DurableLoop
# Initialize or rehydrate a durable loop session in .zeroloop/journals
loop = DurableLoop(loop_id="agent_order_9a8f", task_name="process_order")
loop.start()
# Step 1: Ingest and Validate
loop.step_start("validate_order", {"order_id": "ORD-123"})
loop.record_thought("Checking inventory and fraud scoring...")
loop.step_complete({"valid": True, "amount": 450.0})
# Step 2: Atomic Idempotent Dispatch (forward zeroloop_idempotency_key to external APIs)
loop.step_start("charge_payment")
def stripe_charge(amount: float, customer: str, zeroloop_idempotency_key: str) -> dict:
# External provider receives stable per-(loop, step, tool, inputs) idempotency key
return {"tx_id": "tx_999", "status": "succeeded", "idemp_key": zeroloop_idempotency_key[:12]}
payment_receipt = loop.execute_tool(
tool_name="stripe_charge",
tool_fn=stripe_charge,
inputs={"amount": 450.0, "customer": "cust_456"},
)
loop.step_complete({"payment": payment_receipt})
# Step 3: Complete and Render Value Receipt
receipt = loop.complete(final_output="Order successfully fulfilled")
print(receipt.render())- Interrupted
RUNNINGLoop (Process Crash): Re-open withloop = DurableLoop.load("agent_order_9a8f")(incrementscrash_recoveries). Re-running steps from the top advances the replay cursor across already-completed steps and replaysCOMMITTEDtool outputs. If a tool crashed mid-flight (CLAIMED/INDETERMINATE),LoopReconciliationRequiredis raised so operators can reconcile vialoop.reconcile_tool_call(...). - Suspended
PAUSEDLoop (Human Approval):loop.pause(reason=..., checkpoint=...)persists context and halts execution (LoopPausedException). OnlyPAUSEDloops acceptloop.resume(approval_payload)or--resume.
# Resume a PAUSED loop from repo root (non-secret approval metadata):
python3 zeroloop-py/zeroloop.py --resume agent_order_9a8f --approval '{"approved": true, "reviewer": "ops_oncall", "ticket": "CHG-4021"}'All CLI commands run directly from repository root against .zeroloop/journals (or --storage-dir <DIR>):
# List all active, paused, completed, and failed loops (read-only)
python3 zeroloop-py/zeroloop.py --list
# Read-only DAG & event inspection (never mutates journal or crash_recoveries)
python3 zeroloop-py/zeroloop.py --inspect agent_order_9a8f
# Read-only full unbounded SHA-256 chain verification (never mutates journal)
python3 zeroloop-py/zeroloop.py --verify agent_order_9a8f
# Resume a PAUSED loop with JSON object approval metadata
python3 zeroloop-py/zeroloop.py --resume agent_order_9a8f --approval '{"approved": true, "ticket": "CHG-4021"}'
# Trigger cross-process locked FIFO pruning of COMPLETED/FAILED journals
python3 zeroloop-py/zeroloop.py --prune
# Emit valid pure JSON MCP client configuration (points to --serve-mcp)
python3 zeroloop-py/zeroloop.py --print-config
# Run stdio JSON-RPC 2.0 MCP server directly
python3 zeroloop-py/zeroloop.py --serve-mcp| Setting | Environment Variable | Default | Description |
|---|---|---|---|
| Storage Directory | ZEROLOOP_STORAGE_DIR |
.zeroloop/journals |
Path containing SQLite WAL journals |
| Max Storage MB | ZEROLOOP_MAX_STORAGE_MB |
250.0 |
Storage ceiling before FIFO pruning |
| Retention Days | ZEROLOOP_RETENTION_DAYS |
7 |
Auto-prune finished sessions older than this |
| Min Disk Free GB | ZEROLOOP_MIN_DISK_FREE_GB |
5.0 |
Emergency floor triggering instant pruning |
| Hex Sharding | ZEROLOOP_SHARD_SUBDIRS |
unset (0) |
Set 1 for 2-level <aa>/<bb>/<loop_id>.db directories |
Invariant: Active (
RUNNING),PENDING, andPAUSEDloops are NEVER pruned.
ZeroLoop includes a companion Rust crate (zeroloop-rs/) supporting v1/v2 SHA-256 verification, read-only --inspect/--verify, strict state transitions, and --serve-mcp:
# Build native release binary locally (requires Rust/Cargo toolchain)
cd zeroloop-rs && cargo build --release
# Native CLI operations
./target/release/zeroloop --list
./target/release/zeroloop --inspect agent_order_9a8f
./target/release/zeroloop --verify agent_order_9a8fDistributed under the Apache License 2.0. Designed and maintained by the CreativeUnCommons Team.