HaltState AI: Complete Example
A production-ready autonomous agent with HaltState governance.
#!/usr/bin/env python3
"""
Autonomous maintenance agent with HaltState governance.
Runs nightly via cron, handles approval workflow gracefully.
"""
from haltstate import HaltStateClient, ApprovalPending, ActionDenied
from datetime import date
import logging
import sys
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("maintenance-agent")
def run_maintenance():
client = HaltStateClient(
tenant_id="acme-corp",
api_key="hs_your_api_key",
fail_open=False # Fail-closed for security
)
# Idempotency key includes date - same key on retry finds existing approval
op_key = f"maintenance-{date.today().isoformat()}"
try:
with client.guard(
action="system.maintenance",
params={
"tasks": ["prune_logs", "clear_cache", "rotate_keys"],
"estimated_duration": "5m"
},
idempotency_key=op_key,
agent_id="maintenance-bot-01"
) as permit:
# Approved - execute maintenance
log.info(f"Executing maintenance (approved by {permit.approver})")
prune_logs()
log.info("Logs pruned")
clear_cache()
log.info("Cache cleared")
rotate_keys()
log.info("Keys rotated")
log.info("Maintenance complete!")
except ApprovalPending as e:
# Human review required - exit cleanly
log.info(f"Maintenance pending approval: {e.approval_id}")
log.info("Approve in HaltState dashboard to proceed")
log.info("Script will execute on next scheduled run")
sys.exit(0)
except ActionDenied as e:
# Policy blocked this action
log.error(f"Maintenance denied by policy: {e}")
sys.exit(1)
finally:
client.close()
def prune_logs():
# Your log pruning logic
pass
def clear_cache():
# Your cache clearing logic
pass
def rotate_keys():
# Your key rotation logic
pass
if __name__ == "__main__":
run_maintenance()
Cron Configuration
# /etc/cron.d/maintenance-agent
# Run at 3 AM daily
0 3 * * * root /opt/agents/maintenance.py >> /var/log/maintenance.log 2>&1
What Happens
Day 1, 3:00 AM - First run
- Script calls guard() with key maintenance-2026-01-05
- Policy requires approval for system.maintenance
- ApprovalPending raised, script exits cleanly
Day 1, 9:00 AM - Admin approves in dashboard - Approval stored in HaltState
Day 2, 3:00 AM - Second run
- Script calls guard() with key maintenance-2026-01-06 (new day!)
- New approval cycle starts for today's maintenance
If admin had approved on Day 1:
- Script retries hourly (if configured), same key maintenance-2026-01-05
- Finds existing approval, executes maintenance