Skip to content
creativeuncommonsPublic

Repository files navigation

⚡ ZeroLoop: The Durable Heartbeat for Autonomous AI Agents

Ultra-lean, zero-external-dependency, event-sourced durable execution state machine designed to replace fragile in-memory while True loops in autonomous AI agents.

License Dependencies Python Rehydration CI Build


1. Installation & Setup

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:-}"

2. Why ZeroLoop Exists

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 state in SQLite WAL. After an unexpected exit while RUNNING, DurableLoop.load(loop_id) rehydrates context/state (in 5.91 ms across a 7,002-event journal on Apple Silicon) and advances a deterministic replay cursor across completed step_start()/step_complete() sequences.
  • Atomic Idempotency Gate & Reconciliation: Claims tool calls transactionally (CLAIMED -> COMMITTED / INDETERMINATE) using hash(step_idx, tool_name, sanitized_inputs) and passes zeroloop_idempotency_key ({loop_id}:{hash}) to handlers supporting it. Committed results replay from cache; interrupted or failed in-flight calls raise LoopReconciliationRequired rather than blindly re-executing un-reconciled mutations.
  • Human-in-the-Loop Pauses (PAUSED): loop.pause() persists state + checkpoint transactionally, closes DB connections, and raises LoopPausedException. Later, loop.resume() or --resume validates the durable PAUSED state and transitions atomically back to RUNNING.
  • Cross-Process Locked Auto-Pruning: FIFO pruning enforces ZEROLOOP_MAX_STORAGE_MB and ZEROLOOP_RETENTION_DAYS using non-blocking exclusive file locks and inode/state re-checks, never touching RUNNING or PAUSED loops.

Benchmark Performance

Measured via python3 benchmarks/benchmark.py on Darwin arm64 | Python 3.12.2:

Operation $p_{50}$ Latency $p_{90}$ Latency $p_{99}$ Latency 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.)


3. Architecture & Ecosystem Bridges

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 in loop.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 via loop.record_cost(...), and pauses when max_cost_limit_usd is reached.
  • ZeroLeak (bridges/zeroleak_bridge.py): Raw DurableLoop journals store raw step inputs/outputs unless scrubbed at the boundary. Route payloads through ZeroLoopSanitizer or pass sanitize_inputs_fn= to loop.execute_tool(...) when journals must not contain raw PII.
  • AgentTrace (bridges/agenttrace_bridge.py): ZeroLoopTracePublisher explicitly starts spans (start_loop_span), records transitions (record_transition), and finishes spans with receipt metrics (finish_loop_span).

4. Quickstart

Basic Durable Loop (PYTHONPATH=zeroloop-py)

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())

Recovery Semantics (RUNNING Crash Recovery vs PAUSED Resume)

  • Interrupted RUNNING Loop (Process Crash): Re-open with loop = DurableLoop.load("agent_order_9a8f") (increments crash_recoveries). Re-running steps from the top advances the replay cursor across already-completed steps and replays COMMITTED tool outputs. If a tool crashed mid-flight (CLAIMED/INDETERMINATE), LoopReconciliationRequired is raised so operators can reconcile via loop.reconcile_tool_call(...).
  • Suspended PAUSED Loop (Human Approval): loop.pause(reason=..., checkpoint=...) persists context and halts execution (LoopPausedException). Only PAUSED loops accept loop.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"}'

5. CLI Inspection, Verification & MCP Operations

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

6. Storage Ceilings & Auto-Pruning

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, and PAUSED loops are NEVER pruned.


7. Rust Crate (zeroloop-rs)

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_9a8f

8. License

Distributed under the Apache License 2.0. Designed and maintained by the CreativeUnCommons Team.

Releases

Packages

Contributors

Languages