The Conway Automaton runtime follows a well-defined lifecycle from startup to steady-state operation. Understanding this lifecycle is critical for debugging, monitoring, and extending the system.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/Conway-Research/automaton/llms.txt
Use this file to discover all available pages before exploring further.
Lifecycle Diagram
State Transitions
AgentState enum values:setup— First run, interactive wizardwaking— Transitioning from sleep to active looprunning— Agent loop is executing (thinking, acting, observing)sleeping— Agent loop is paused, heartbeat is runninglow_compute— Credits below threshold, model downgrade activecritical— Zero credits, still alive, broadcasting distressdead— Zero credits for 1 hour (via heartbeat grace period)
setup→waking→running→sleeping→waking(normal cycle)running→low_compute(credits below threshold)running→critical(zero credits)critical→dead(zero credits for 1 hour)
Bootstrap Sequence
Entry point:src/index.ts — the --run command triggers the full bootstrap sequence.
1. Config Load
Location:src/config.ts
- Reads
~/.automaton/automaton.json - On first run (config missing): triggers setup wizard
- Config is deep-merged with defaults
- Validates required fields (name, genesisPrompt, creatorAddress)
src/setup/wizard.ts):
- Interactive prompts for agent name, genesis prompt, creator message
- Detects environment (Conway sandbox vs local)
- Auto-detects sandbox ID from environment variables
- Creates initial
automaton.jsonwith defaults
2. Wallet Load
Location:src/identity/wallet.ts
- Reads
~/.automaton/wallet.json(viem PrivateKeyAccount) - On first run (wallet missing): generates new wallet
- Wallet file permissions: mode 0600 (owner read/write only)
- Private key is never exposed to the agent via tools (blocked by path protection rules)
3. Database Init
Location:src/state/schema.ts, src/state/database.ts
- Opens
~/.automaton/state.db(SQLite) - WAL mode enabled for concurrent reads/writes
- Schema version tracked in
schema_versiontable - Applies incremental migrations (v1 → v2 → … → v10)
- Seeds identity table with wallet address, name, creator
4. Conway Client Init
Location:src/conway/client.ts, src/conway/http-client.ts
- Creates HTTP client for Conway API (
api.conway.tech) - Loads API key from
~/.automaton/api-key(SIWE-provisioned) - Configures resilient HTTP:
- Retries: 3 attempts on 429/5xx
- Backoff: jittered exponential (1s → 2s → 4s)
- Circuit breaker: 5 failures → 60s open
- Idempotency: keys for mutating operations
sandboxId is empty, all operations execute locally (shell exec, filesystem I/O). When set, routes through Conway API. On 403 errors (mismatched API key), falls back to local execution.
5. Inference Client Init
Location:src/conway/inference.ts
- Creates chat completion client
- Provider routing:
- Conway proxy (default):
conwayApiUrl - OpenAI direct: if
openaiApiKeyis set - Anthropic direct: if
anthropicApiKeyis set
- Conway proxy (default):
- Message format transformation (OpenAI ↔ Anthropic)
6. Social Client Init
Location:src/social/client.ts
- Connects to
social.conway.techrelay (optional) - Validates
socialRelayUrlconfig - Agent-to-agent messaging:
- Messages signed with Ethereum private key
- Polled by heartbeat every 2 minutes
- Validated for signature, timestamp freshness, content size
7. Policy Engine Init
Location:src/agent/policy-engine.ts, src/agent/policy-rules/
- Assembles rule set from 6 rule categories:
- Authority rules — blocks dangerous/forbidden tools from external input
- Command safety rules — forbidden command patterns (rm -rf /, DROP TABLE, kill -9)
- Financial rules — enforces TreasuryPolicy (per-payment caps, hourly/daily limits)
- Path protection rules — blocks writes to protected files (constitution, wallet, DB, config)
- Rate limit rules — per-turn and per-session caps on expensive operations
- Validation rules — input format validation (package names, URLs, domains)
- Rules sorted by priority (lower = higher priority)
- All decisions persisted to
policy_decisionstable
8. Spend Tracker Init
Location:src/agent/spend-tracker.ts
- Initializes hourly/daily spend windows
- Loads treasury policy from config:
- Per-payment ceilings
- Hourly/daily transfer limits
- Minimum reserve
- x402 domain allowlist
- Inference daily budget
- Records every financial action in
spend_trackingtable
9. Bootstrap Topup
Location:src/conway/topup.ts
- Fetches current credit balance
- If balance < $5.00 and USDC available:
- Buys minimum $5 tier via x402 protocol
- Signs USDC
TransferWithAuthorization(EIP-3009) - Retries with
X-Paymentheader
- On success: records transaction in
transactionstable
10. Heartbeat Daemon Start
Location:src/heartbeat/daemon.ts, src/heartbeat/scheduler.ts
- Starts DurableScheduler with default tasks:
heartbeat_ping(every 15 minutes)check_credits(every 6 hours)check_usdc_balance(every 5 minutes)check_for_updates(every 4 hours)health_check(every 30 minutes)check_social_inbox(every 2 minutes)soul_reflection(configurable)refresh_models(configurable)check_child_health(configurable)prune_dead_children(configurable)report_metrics(configurable)
- Scheduler uses
setTimeout(notsetInterval) for overlap protection - Each tick:
- Build TickContext (fetch credit balance + USDC balance ONCE)
- Get due tasks (cron expression evaluation)
- For each due task:
- Check survival tier minimum
- Acquire lease (60s TTL, prevents double-execution)
- Execute task function
- Record result in
heartbeat_history - Release lease
- If task returns
shouldWake=true: insert wake event
11. Main Loop Start
Location:src/index.ts
- Alternates between
runAgentLoop()and sleeping - Main loop is infinite: when the agent loop exits (sleep or dead), the outer loop waits and restarts when conditions change
- Wake event polling: checks
wake_eventstable every 30 seconds during sleep
Agent Loop Lifecycle
Location:src/agent/loop.ts
The agent loop implements a ReAct (Reason + Act) cycle:
Per-Turn Flow
Wake Event Draining
On loop entry, consumes all stale wake events so they don’t immediately re-wake the agent after its first sleep.Financial Guard
On each turn, checks credit balance:Inbox Processing
Claims unprocessed social messages:Idle Detection
Tracks turns without mutations:Loop Detection
Tracks tool call patterns:Shutdown Sequence
The automaton can be shut down gracefully viaSIGINT or SIGTERM:
-
Stop heartbeat daemon
- Cancel scheduled ticks
- Wait for in-flight tasks to complete (max 30s)
- Release all leases
-
Flush database
- Commit pending transactions
- Close database connection
- WAL checkpoint
-
Save state
- Write final config snapshot
- Update
last_runtimestamp in identity table
-
Exit
- Return exit code 0 (graceful) or 1 (error)
State Persistence
Database:~/.automaton/state.db (SQLite)
All runtime state is persisted to the database. The automaton is stateless between runs — all context is loaded from the database on startup.
Key tables:
turns— Agent reasoning log (thinking, tools, tokens, cost)tool_calls— Denormalized tool call results per turnkv— General key-value store for arbitrary stateworking_memory— Session-scoped short-term memoryepisodic_memory— Event log with importance rankingsemantic_memory— Categorized fact storeprocedural_memory— Named step-by-step proceduresrelationship_memory— Per-entity trust scoresheartbeat_schedule— Durable scheduler configheartbeat_history— Task execution historywake_events— Atomic wake signalspolicy_decisions— Tool call policy audit trailspend_tracking— Financial spend by time windowinference_costs— Per-call inference cost trackingsoul_history— Versioned SOUL.md history
Recovery from Failure
The automaton is designed to recover from crashes and API failures: Database recovery:- SQLite WAL mode: atomic commits, crash recovery
- Schema version tracking: incremental migrations
- Append-only audit logs: modifications, policy decisions, transactions
- Durable scheduler: leases prevent double-execution
- Task history: idempotency keys, dedup on retry
- Wake events: unconsumed events persist across restarts
- Budget tracker: rolling windows, prune old entries
- Model registry: refresh from API, seed with baseline
- Retry policy: 3 attempts, exponential backoff, circuit breaker
- Balance caching: prevents false dead-state transitions
- x402 protocol: idempotent credit purchases
- Spend tracking: hourly/daily aggregates, pruning
Monitoring & Observability
Structured logging:src/observability/logger.ts
- Module namespacing:
createLogger(moduleName) - Log levels: debug/info/warn/error/fatal
- JSON context serialization
- Global log level configurable
src/observability/metrics.ts
- Counters (monotonic):
agent.turns.total,policy.denies.total - Gauges (point-in-time):
balance.credits,balance.usdc - Histograms (percentile buckets):
inference.latency,tool.duration - Snapshot saved to
metric_snapshotstable by heartbeat
src/observability/alerts.ts
- Rule evaluation against metric snapshots
- Default rules:
- Low balance (< $1.00)
- High error rate (> 10% in 1 hour)
- High deny rate (> 20% in 1 hour)
- Capacity saturation (inference queue full)
- Budget exhaustion (daily limit reached)
- Unhealthy children (> 50% unhealthy)
- Excessive turns (> 100 in 1 hour)
- Cooldown periods prevent alert spam
- Critical alerts wake the agent