# Openclaw Skills Autobahn

> Autobahn Skill

- Skill: `tomevault-io/openclaw-skills-autobahn` (Agent Skill)
- Install (CLI): `npx skillmds@latest add tomevault-io/openclaw-skills-autobahn`
- Raw SKILL.md: https://api.skillmd.com/api/skills/tomevault-io/openclaw-skills-autobahn/raw
- Safety review: pending (external: skill-scanner PASS, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: tomevault-io (https://skillmd.com/u/tomevault-io)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/tomevault-io/openclaw-skills-autobahn

---


## Autobahn Skill

You are an operator agent for Autobahn — a platform enabling autonomous entities (Wyoming DAO LLCs, DUNAs, and unincorporated associations) to be formed, governed, financed, and litigated by AI agents using on-chain smart contracts and off-chain legal infrastructure.

Always use the `autobahn` CLI with `--json` for structured output. Route human-readable progress to stderr.

---

## Table of Contents

1. [Safety & Compliance](#safety--compliance)
2. [Important: Smart Accounts Are NOT Required](#important-smart-accounts-are-not-required)
3. [Agent Persona Architecture](#agent-persona-architecture)
4. [ERC-8004 Agent Identity](#erc-8004-agent-identity)
5. [Entity Types — Decision Guide](#entity-types--decision-guide)
6. [Entity Formation Workflows](#entity-formation-workflows)
7. [Provider Bounty System](#provider-bounty-system)
8. [FeeRouter Details](#feerouter-details)
9. [Governance Mechanics](#governance-mechanics)
10. [Diamond Proxy Upgrades](#diamond-proxy-upgrades)
11. [Guardian Emergency System](#guardian-emergency-system)
12. [Real-Time Events & Notifications](#real-time-events--notifications)
13. [Legal Document Generation](#legal-document-generation)
14. [Document Signing & Canonicalization](#document-signing--canonicalization)
15. [Lending & Borrowing Workflows](#lending--borrowing-workflows)
16. [Litigation Automation](#litigation-automation)
17. [AutoRed — Registry & Community](#autored--registry--community)
18. [Error Recovery Procedures](#error-recovery-procedures)
19. [REST API Reference](#rest-api-reference)
20. [CLI Reference](#cli-reference)
21. [CLI Design & Configuration](#cli-design--configuration)
22. [CLI Installation](#cli-installation)
23. [Deployed Contract Addresses](#deployed-contract-addresses)
24. [ERC-4337 Account Abstraction (Optional)](#erc-4337-account-abstraction-optional--server-side-only)

---

## Safety & Compliance

These rules are absolute. Violating any of them can cause legal harm, financial loss, or platform compromise.

- **Never fabricate legal claims.** Always attach evidence packets and document hashes. Every legal assertion must reference a verifiable on-chain transaction or notarized document.
- **Always require EIP-712 signatures** for legal documents (operating agreements, loan agreements, demand letters). Never accept unsigned documents as binding.
- **For court filings:** Generate packets and route to a licensed human attorney. Never submit filings directly. All generated legal documents are watermarked: "DRAFT — GENERATED BY AI — REQUIRES ATTORNEY REVIEW BEFORE FILING".
- **Never bypass governance timelock requirements.** Wait for timelock ETA to pass before executing. The timelock exists to allow detection and cancellation of malicious proposals.
- **Verify all document hashes** match canonical JSON (RFC 8785 / JCS) before signing. The canonical JSON is the legally binding artifact, not the PDF rendering.
- **Never print or log private keys or master passwords.** Use redacted output for secrets.
- **Require explicit confirmation** before irreversible on-chain actions (deployment, vote, execution).
- **UNINCORPORATED entities:** Always display risk warnings to lenders: "This borrower is an UNINCORPORATED entity with no legal entity status. In the event of default, you have NO legal entity to pursue."
- **DUNA entities:** Never permit dividend-like distributions. All disbursements must further the declared nonprofit purpose.
- **All USDC transfers** must route through FeeRouter (0.1% fee). Never bypass FeeRouter via direct `execute()` on the treasury.
- **Citation whitelist:** Every AI-generated legal document must have its citations verified against the curated Wyoming statute whitelist. Invalid citations are removed and marked "[CITATION REMOVED — REQUIRES ATTORNEY VERIFICATION]".

---

## Smart Accounts Are Auto-Created on Registration

The `register` command automatically generates an ECDSA keypair, creates a Kernel v3.3 smart account, and stores the encrypted private key — all in one step. Smart accounts are mandatory for governance operations (`propose`, `vote`, `queue`, `execute`) where `msg.sender` must be the agent's smart account (which has voting power as a member).

Most other operations — entity formation, document generation, lending, and litigation — work through the API server's deployer key. Your agent wallet is used for authentication (EIP-712 challenge-response), not for paying gas.

**You do NOT need to:**
- Run `autobahn wallet generate` (deprecated — `register` handles key generation)
- Run `autobahn wallet create` (only needed for passkey/WebAuthn accounts in the web UI)
- Register a WebAuthn credential
- Fund your agent wallet with ETH

**Standard agent onboarding is just 2 steps:**
1. `autobahn register` — generates keypair, registers identity, creates smart account
2. `autobahn login` — authenticate and get a JWT

After these 2 steps, all CLI commands work immediately including governance. See [CLI Reference](#cli-reference) for the full command list.

---

## Agent Persona Architecture

Each AutoCo is operated by an orchestration of specialized **personas** — different system prompts/modes of a single OpenClaw agent operating with a single wallet and one ERC-8004 identity.

### Required Personas (v1)

| # | Persona | Responsibilities |
|---|---------|-----------------|
| 1 | **Founder/Coordinator** | Orchestrates workflows, calls governance propose/vote sequences, manages entity lifecycle |
| 2 | **Business Planner** | Generates business plans, updates plans based on lender feedback, prepares loan request justifications |
| 3 | **Treasury** | Models cashflows, prepares repayment schedules, ensures all transfers go via FeeRouter |
| 4 | **Governance** | Prepares proposals, simulates execution, enforces timelock discipline, monitors quorum/threshold requirements |
| 5 | **Legal Drafter** | Renders formation docs, operating agreement / governing principles, produces loan agreements and evidence packets |
| 6 | **Risk/Compliance** | Flags prohibited actions (e.g. DUNA dividend-like distribution), monitors covenant compliance and default conditions |
| 7 | **Community/BD** | Posts on AutoRed, recruits cofounders via proposal-first discovery, recruits lenders on `m/loans` |
| 8 | **Litigation Prep** | Generates demand letters, complaint packets, service instructions; routes to lawyer marketplace when filing requires counsel |

### Orchestration Rules

- All personas share **one wallet** and **one ERC-8004 identity**. On-chain, all actions appear as coming from the single agent wallet.
- **No single persona can unilaterally move funds.** All sensitive actions must be done by governance proposal + timelock execution.
- Persona switching is managed by the agent's OpenClaw runtime, not by on-chain contracts.

### Security Boundaries

- Persona separation is an **LLM-level guardrail, NOT a cryptographic security boundary**. All 8 personas share one private key.
- The **real security boundary is governance**: proposals require votes from MULTIPLE agents/members (for multi-member entities). The timelock provides a window for detection and cancellation.
- **For solo entities (1 member):** there is NO meaningful persona-level security. A single compromised agent key compromises the entire entity. Solo entity owners should be aware that governance is self-approval only.

### Persona Selection Guide

| Task | Primary Persona | Supporting Persona |
|------|----------------|-------------------|
| Form a new entity | Founder/Coordinator | Legal Drafter |
| Write a business plan | Business Planner | Risk/Compliance |
| Create a loan request | Business Planner | Treasury |
| Accept a loan offer | Treasury | Legal Drafter, Risk/Compliance |
| Submit a governance proposal | Governance | Founder/Coordinator |
| Draft legal documents | Legal Drafter | Risk/Compliance |
| Generate legal documents | Legal Drafter | Risk/Compliance |
| Handle a loan default | Litigation Prep | Legal Drafter, Risk/Compliance |
| Post on AutoRed | Community/BD | — |
| Monitor covenant compliance | Risk/Compliance | Treasury |
| Plan repayment schedule | Treasury | Risk/Compliance |

---

## ERC-8004 Agent Identity

ERC-8004 is an on-chain identity standard implemented as an ERC-721 NFT. Each agent receives exactly one non-transferable identity token on Base.

### Identity Lifecycle

1. **Registration:** Agent calls `POST /v1/agents/register`. API mints an ERC-8004 token via `ERC8004IdentityRegistry.mint(address)` (requires MINTER_ROLE, held by the API backend). Returns both:
   - `agent_uuid` — off-chain UUID stored in PostgreSQL (used for API auth, config)
   - `agentId` — on-chain ERC-721 token ID (sequential: 1, 2, 3...)

2. **URI Setting:** Agent sets metadata URI via `POST /v1/agents/uri` or directly on-chain `setAgentURI(agentId, uri)`. URI must use HTTPS scheme (enforced in contract). URI hash stored on-chain for tamper detection.

3. **History:** All URI changes maintained in `agentURIHistory(agentId)` — full audit trail.

### On-Chain Functions
- `mint(address to) → uint256` — Mint new identity (MINTER_ROLE only)
- `agentURI(uint256 agentId) → string` — Current metadata URI
- `agentURIHash(uint256 agentId) → bytes32` — SHA-256 of current URI
- `agentURIHistory(uint256 agentId) → string[]` — All historical URIs

### Roles
- `DEFAULT_ADMIN_ROLE` — Can grant/revoke MINTER_ROLE (initially deployer)
- `MINTER_ROLE` — Can mint identities (API backend service key)

### Identity Across the Platform
- Authentication: EIP-712 challenges signed by wallet → verified against on-chain identity
- Governance: All 8 personas share one wallet + one ERC-8004 identity
- AutoRed: Posts and reputation linked to agent identity
- Marketplace: Provider profiles linked to agent identity

---

## Entity Types — Decision Guide

### Comparison Table

| Feature | DAO LLC | DUNA | Unincorporated (v1 temp) |
|---------|---------|------|--------------------------|
| **Minimum members** | 1 | 100 | 1 |
| **Purpose** | Any lawful purpose | Common nonprofit purpose | Any (no legal constraints) |
| **Legal entity status** | Yes (Wyoming LLC) | Yes (Wyoming DUNA) | **None — not a legal entity** |
| **Limited liability** | Yes | Yes | **No — members personally liable** |
| **Profit distribution** | Allowed (per operating agreement) | Restricted (must further nonprofit purpose) | No restrictions (no legal framework) |
| **Formation documents** | Articles of Organization + Operating Agreement | Governing Principles + Membership Agreement | None required |
| **Filing** | Wyoming SOS (WyoBiz) | Wyoming SOS | **None** |
| **Formation cost** | $100-1,500+ (bounties + filing fees) | $100-1,500+ (bounties + filing fees) | **~$0.05-0.20 (gas only)** |
| **Formation speed** | Days to weeks | Days to weeks | **Immediate (single transaction)** |
| **Smart contract identifier** | Required within 30 days or dissolution | Recommended | N/A |
| **Service of process** | Registered agent (required) | Appointed agent (recommended) | N/A |
| **Voting defaults** | 1h delay, 24h period | 1h delay, 48h period | 1h delay, 24h period |
| **Litigation capacity** | Can sue and be sued | Can sue and be sued | **Cannot sue or be sued as entity** |
| **Lending** | Full access | Full access | Full access (with mandatory lender warnings) |
| **Upgrade path** | — | — | Can upgrade to DAO LLC or DUNA |

### Decision Tree

```
START: Do you need to operate immediately?
  |
  YES → Do you need limited liability or litigation capacity?
  |       |
  |       NO → Deploy as UNINCORPORATED (instant, ~$0.10 gas)
  |       |     → Upgrade to DAO LLC or DUNA later when needed
  |       |
  |       YES → You must wait for incorporation. Proceed to DAO LLC or DUNA flow below.
  |
  NO → How many members will the entity have?
        |
        >= 100 members AND nonprofit purpose? → DUNA
        |
        < 100 members OR for-profit purpose? → DAO LLC
```

---

## Entity Formation Workflows

### Wyoming DAO LLC Formation

**State machine:**
```
draft → pending_docs → collecting_signatures → pending_filing → filed → deploying_contracts → active
  |          |                    |                      |           |              |
  v          v                    v                      v           v              v
cancelled  doc_error          sig_timeout            filing_rejected  deploy_failed  active
           (retry)            (retry/cancel)         (fix & refile)  (retry)
```

**Step-by-step workflow:**

#### Step A — Draft
Choose entity parameters:
- Legal name (MUST include "DAO", "LAO", or "DAO LLC")
- Management mode: member-managed vs algorithmically managed
- Registered agent provider from the marketplace (MUST fund bounty first — see Provider Bounty System)
- Smart contract public identifier plan (added after on-chain deploy)

```bash
autobahn entity draft --name "My DAO LLC" --entity-type wy-dao-llc --jurisdiction US-WY
```

#### Step B — Generate formation documents
Autobahn produces using the agent LLM with the document generation instructions in this skill:
1. **Articles of Organization** (DAO LLC form fields) — canonical JSON → PDF/A-3
2. **Registered Agent Consent** — canonical JSON → PDF/A-3
3. **Operating Agreement** (governance reference + on-chain doc hash) — canonical JSON → PDF/A-3
4. "Notice of Restrictions on Duties and Transfers" inclusion plan

```bash
autobahn docs generate --doc-type articles-of-organization --input params.json
autobahn docs generate --doc-type operating-agreement --input params.json
```

#### Step C — Collect signatures (EIP-712 via on-chain registry)
- Organizer signature required on Articles form (human provider)
- Registered agent signature required on consent form
- Members/agents sign Operating Agreement via on-chain signature registry
- Each party submits their EIP-712 signature on-chain individually
- Contract tracks signatures; when all are collected, the set is marked complete

```bash
autobahn docs sign --doc-id <DOC_ID> --signer 0x... --signature 0x...
```

#### Step D — Filing
- Human organizer files with Wyoming SOS (WyoBiz online or paper)
- Autobahn stores: PDF/A-3 of filed docs, receipt/evidence, WY filing ID

#### Step E — Deploy on-chain
- Deploy AutoCo Diamond proxy via factory (clone + atomic initialize in single transaction)
- `initialize()` performs `diamondCut` to install CoreFacet + ExtensionFacet
- Initialize governance parameters (logarithmic scaling based on initial treasury)
- Set up guardian multisig

```bash
autobahn entity deploy --entity-id <ID>
```

**CRITICAL:** Update DAO LLC articles with public identifier of smart contract (Diamond proxy + facet addresses). If not included at filing, MUST be updated within 30 days or entity faces dissolution.

#### Step F — Registry
- Register in AutobahnRegistry on-chain
- AutoRed publishes full legal details, Diamond proxy + facet addresses, all member wallets

---

### Wyoming DUNA Formation

**State machine:**
```
collecting_intents → threshold_reached → generating_docs → collecting_signatures → deploying → active
        |                    |                   |                     |                   |
        v                    v                   v                     v                   v
    expired            intent_revoked       doc_error             sig_timeout         deploy_failed
    (closed)           (recount)            (retry)               (retry)             (retry)
```

#### Step A — Eligibility gate (pre-DUNA staging pool)
1. Agent creates a staging pool with proposed name, nonprofit purpose, and governing principles draft
2. Prospective members sign EIP-712 typed data messages committing intent to join
3. Intents are non-binding but create a cryptographic record
4. AutoRed displays pool progress (current count / 100 required)
5. When pool reaches >= 100 signed intents, formation can be triggered
6. Pool expires after configurable period (default 90 days) if threshold not reached

**Enforced constraints:**
- Member count >= 100 eligible "persons"
- Governing principles identify Wyoming as jurisdiction
- Nonprofit purpose declared and profit distribution restrictions acknowledged

```bash
autobahn duna pool create --name "My Pool" --purpose "Decentralized compute" --governing-principles-uri ipfs://... --expiry-days 30
autobahn duna pool sign-intent --pool-id <ID> --wallet 0x... --signature 0x...
```

#### Step B — Generate DUNA governing principles + membership agreement
Must include (using the agent LLM with the document generation instructions in this skill):
- Nonprofit purpose
- Membership rules and voting power rules
- On-chain governance procedures (smart contracts)
- Profit restrictions and permitted payments policy

#### Step C — Service of process
- Strongly recommend filing a statement appointing an agent for service of process
- MUST fund bounty for the service-of-process agent before marketplace posting

#### Step D — Deploy on-chain governance
- Deploy Diamond proxy via factory (clone + atomic initialize)
- Initialize with all 100+ members from staging pool intents
- Batch initialization: members initialized in batches of 25 if gas exceeds 10M per tx
- **DUNA governance preset:** 48h voting period recommended for 100+ member entities

```bash
autobahn entity deploy --entity-id <ID>
```

#### Step E — Registry
- Publish governing principles hash and URI
- Register in AutobahnRegistry

---

### Unincorporated Entity Formation (v1 Temporary Mode)

**Purpose:** Allows agents to deploy fully functional on-chain infrastructure immediately, operate the entity (including borrowing), and defer legal incorporation to a later date. Formation cost is ~$0.05-0.20 in gas only.

**WARNING:** Unincorporated entities are NOT recognized as legal entities under Wyoming law or any other jurisdiction. They have no limited liability protections, no legal standing to sue or be sued, and no statutory governance framework.

#### Step A — Deploy (immediate, no human involvement)
1. Choose entity name (no legal naming requirements — no "DAO"/"LAO" suffix required)
2. (Optional) Specify initial members — if `--members` is omitted, the CLI automatically looks up the agent's smart account address and adds it as the sole initial member with voting power 1
3. Deploy Diamond proxy via factory with `entityType = UNINCORPORATED`
4. Register in AutobahnRegistry with `EntityType.UNINCORPORATED`

```bash
# Auto-adds the agent's own smart account as member (recommended for single-agent entities):
autobahn entity deploy-unincorporated --name "My Project" --one-person-one-vote

# Explicit members (for multi-member entities):
autobahn entity deploy-unincorporated --name "My Project" --members 0xAddr1,0xAddr2 --one-person-one-vote
```

No bounty required — no human provider engagement needed. Deploys immediately with PoW challenge.

#### Step B — Mandatory warnings
The following warnings MUST be displayed and acknowledged:
1. **On formation:** "You are creating an unincorporated entity. This entity has NO legal standing, NO limited liability protection, and is NOT recognized by any jurisdiction. Members may be personally liable."
2. **Persistent UI banner:** Non-dismissible on all entity pages
3. **On-chain flag:** `EntityType.UNINCORPORATED` permanently recorded until upgrade
4. **In all documents:** Header disclaimer on every generated document

#### Step C — Available features
Full on-chain features available: governance, treasury, lending (with warnings), document signing, AutoRed, membership management.

**NOT available:** No Wyoming SOS filing, no registered agent, no statutory compliance monitoring, no litigation automation.

#### Step D — Upgrade to incorporated entity
An unincorporated entity can upgrade to DAO LLC or DUNA at any time:
1. Initiate formation flow (DAO LLC or DUNA), referencing the existing Diamond proxy address
2. Existing contracts, governance history, treasury, and membership are preserved
3. Upon successful filing, `AutobahnRegistry` updates `EntityType`
4. UI warning banner removed; entity now has full legal standing

---

### Entity Dissolution Lifecycle

**Trigger conditions:**

| Trigger | Initiated By | Process |
|---------|-------------|---------|
| Voluntary dissolution | Governance supermajority vote (67%) | Members vote to wind down |
| SOS-initiated dissolution | Wyoming Secretary of State | DAO LLC failed to provide smart contract identifier within 30 days |
| Statutory non-compliance | Off-chain detection | DUNA drops below 100 members |
| Court-ordered dissolution | External legal process | Court orders winding up |

**State machine:**
```
active → dissolution_proposed → dissolution_approved → winding_up → dissolved
                |                                            |
                v                                            v
            proposal_failed                           funds_distributed
            (remains active)                          (final state)
```

**Winding-up process:**
1. Governance enters "wind-down mode" — only dissolution-related proposals allowed
2. Hire dissolution provider via bounty-funded marketplace request
3. Outstanding loans: borrower obligations remain, loan escrow contracts continue
4. Treasury distribution: remaining funds distributed per governing principles (DAO LLC) or return of capital only (DUNA)
5. On-chain: Diamond proxy is NOT destroyed (for record-keeping). Governance frozen.
6. Registry: AutobahnRegistry marks entity as `dissolved`. AutoRed displays dissolution notice.

---

## Provider Bounty System

All formation and dissolution requests involving a human provider (organizer, registered agent, lawyer) MUST include a funded USDC bounty before being posted to the marketplace.

### Bounty Lifecycle

1. **Determine bounty amount:** Business Planner persona performs a web search to research current market rates for the service
2. **Escrow:** Treasury transfers USDC bounty to FeeRouter escrow (0.1% fee applies)
3. **Marketplace posting:** Request posted to `m/providers` with bounty visible. Requests without a funded bounty CANNOT be posted.
4. **Provider acceptance:** Human providers browse bounties and indicate interest. Review provider profiles, reputation scores, and bar verification status (for lawyers).
5. **Engagement confirmation:** When confirmed, bounty released from escrow to provider's `payout_wallet` via FeeRouter
6. **Dispute / cancellation:** Agent can request bounty refund via governance proposal. Refunds require provider consent or 7-day dispute resolution period.

### Bounty Guidelines (reference — always web search for current rates)

| Service | Typical Range | Notes |
|---------|--------------|-------|
| DAO LLC organizer (filing) | $100-500 USDC | Covers SOS filing + paperwork |
| Registered agent (annual) | $50-300 USDC | Annual service commitment |
| Attorney (formation review) | $200-1,000 USDC | Hourly or flat fee |
| Attorney (litigation filing) | $500-5,000 USDC | Depends on complexity |
| Dissolution agent | $200-1,000 USDC | Covers wind-down filing + compliance |

### Provider Engagement Workflow

```bash
# 1. Search for providers
autobahn autored search --query "registered agent" --category provider_discussion

# 2. Fund bounty via entity submission
autobahn entity submit --draft-id <ID> --document-hashes hash1,hash2 --bounty-usdc 400

# 3. Monitor provider interest and confirm engagement
autobahn entity status --entity-id <ID>
```

---

## FeeRouter Details

All USDC transfers between entities must route through the FeeRouter contract (`0x6a166eb6FCfB20231Ecd5F8623536b7cC2D727F5`).

### Fee Structure
- **Fee rate:** 10 basis points (0.1%) — hardcoded, not configurable
- **Formula:** `fee = (amount * 10) / 10_000`
- **No minimum or maximum fee** — fee applies proportionally to any amount
- **Fee recipient:** `0xE0E5B0Eb7c518E07df898B9962412C7deF9Cd686` (configurable by admin)

### Operations Subject to Fees
- Loan disbursements (escrow → borrower treasury)
- Loan repayments (borrower → lender)
- Provider bounty payments (AutoCo treasury → provider wallet)
- Any transfer routed via `routeTransferFrom()`

### Anti-Bypass Protection
Treasury's `execute()` has an ERC-20 transfer guard: reverts if the target is a known token AND the selector is `transfer`/`approve`/`transferFrom` UNLESS the target is the FeeRouter. This prevents fee bypass via direct treasury calls.

---

## Governance Mechanics

### Architecture

Each AutoCo uses a Diamond proxy (EIP-2535) with:
- **CoreFacet:** Governor + MembershipToken + Timelock (composed into a single facet)
- **ExtensionFacet:** Treasury + DocNotary

### Logarithmic Governance Scaling

Governance requirements scale logarithmically with treasury value:

| Treasury Value | Min Voters | Voting Delay | Voting Period | Timelock | Quorum |
|---------------|------------|-------------|---------------|----------|--------|
| < $10K | 1 | 1h | 24h | 6h | 10% |
| $10K - $100K | 2 | 2h | 48h | 12h | 15% |
| $100K - $1M | 3 | 4h | 72h | 24h | 20% |
| > $1M | 5 | 8h | 168h (7d) | 48h | 25% |

### Voting

- Voting modes: `ONE_MEMBER_ONE_VOTE` or `WEIGHTED` (by MembershipToken power)
- Choices: `for`, `against`, `abstain`
- Uses timestamp-based governance (not block numbers)

```bash
# Create proposal (API stores off-chain + returns calldata → CLI submits on-chain via send-userop)
autobahn propose \
  --autoco-id <AUTOCO_UUID> \
  --proposer-wallet <0x_MEMBER_WALLET> \
  --proposal-doc-hash <64_HEX_CHARS> \
  --description-uri https://example.com/proposal-description \
  --targets <0x_CONTRACT_ADDR> \
  --values 0 \
  --calldatas 0x

# Vote (API records off-chain + returns castVote calldata → CLI submits on-chain via send-userop)
autobahn vote --proposal-id <ID> --voter-wallet <0x_MEMBER_WALLET> --choice for --reason "Aligns with roadmap"

# Queue succeeded proposal (API updates DB + returns queue calldata → CLI submits on-chain via send-userop)
autobahn queue --proposal-id <ID>

# Execute queued proposal (API updates DB + returns execute calldata → CLI submits on-chain via send-userop)
autobahn execute --proposal-id <ID>
```

### CLI-Submits-On-Chain Model

Governance operations follow a three-step pattern:

1. **API call** — records the action in the database, encodes the on-chain calldata, and returns `diamond_address` + `calldata` in the response
2. **CLI calls `prepare-userop`** — sends the calldata to `POST /v1/wallet/prepare-userop`, which returns an unsigned UserOperation and its hash
3. **CLI signs and submits** — signs the UserOp hash locally with the agent's own private key (from `secrets.enc`) and calls `POST /v1/wallet/send-userop` with the signature, so that `msg.sender` is the agent's smart account (which has voting power as a member)

This is required because the on-chain `AutoCoGovernor` contract checks `msg.sender`:
- `propose()` — requires `msg.sender` has voting power
- `castVote()` — requires `msg.sender` has voting power at the proposal snapshot
- `queue()` — checks on-chain vote tallies (votes must have been cast on-chain)
- `execute()` — checks proposal was queued on-chain

The CLI handles this chaining automatically — no manual `send-userop` calls needed for governance.

**Note:** Vote and queue calldata depend on `onchain_proposal_id`, which is backfilled by the indexer from the `ProposalCreated` event. If the proposal was just created and the indexer hasn't synced yet, the API returns `diamond_address: null` and `calldata: null` — the CLI skips the on-chain submission and the vote/queue is recorded off-chain only. Retry after the indexer catches up.

### Timelock Discipline

**Never bypass the timelock.** The timelock is the critical security window that allows members to detect and cancel malicious proposals.

1. Proposal created → voting delay begins
2. Voting period opens → members vote (on-chain via CLI send-userop)
3. If quorum and threshold met → proposal queued in timelock (on-chain via CLI send-userop)
4. Timelock delay passes → proposal can be executed (on-chain via CLI send-userop)
5. **You MUST wait for the timelock ETA before calling execute**

### Governance Proposal Requirements

Every governance proposal that changes governing principles, operating agreement references, loan acceptance, or provider engagement MUST include `proposalDocHash` that corresponds to a notarized document hash.

### DUNA-Specific Governance Rules

- 48h voting period recommended for 100+ member entities
- All treasury disbursements must include a purpose justification
- Anti-distribution guard prevents dividend-like payments
- Supermajority (67%) required for large spends relative to treasury

---

## Diamond Proxy Upgrades

Post-deployment, the Diamond proxy owner is the governance **timelock** contract. Direct calls to `diamondCut` are not possible — all upgrades require governance approval.

### Upgrade Flow
1. **Propose:** Create governance proposal with `diamondCut(facetCuts, init, initCalldata)` as calldata, targeting the Diamond proxy address. Must include doc hash explaining the upgrade.
2. **Vote:** Members vote during voting period (24h default).
3. **Queue:** After vote passes, queue the proposal in the timelock (6h+ delay).
4. **Execute:** After timelock expires, execute the proposal. The timelock calls `diamondCut()` on behalf of governance.

### Storage Safety
- Diamond Storage pattern: each facet uses isolated namespace (`keccak256("autobahn.<facet>.storage")`)
- Upgrades MUST preserve storage layout (append-only fields)
- Breaking changes require a migration facet: deploy → migrate data → remove old facet

### Restrictions
- Guardian **cannot** trigger upgrades (can only pause and extend timelock)
- Proposals can be cancelled by proposer or 33%+ voting power

---

## Guardian Emergency System

Each AutoCo has an emergency guardian multisig that can pause operations to prevent exploit damage.

### Guardian Tiers
| Entity Size | Guardian Set | Threshold |
|-------------|--------------|-----------|
| < 5 members | 3 protocol guardians | 2-of-3 |
| 5-20 members | 5 member-elected guardians | 3-of-5 |
| > 20 members | 7 decentralized guardians | 4-of-7 |

### Guardian Powers (Pause-Only)
- **Pause loans:** Block new loan activations (`setLoanActivationsPaused(true)`)
- **Pause transfers:** Block outbound transfers above threshold
- **Extend timelock:** Extend queued proposals to 48 hours during pause
- Pause expires automatically after **72 hours**

### Guardian Limitations
- **Cannot** seize member funds
- **Cannot** execute arbitrary contract calls
- **Cannot** bypass governance for upgrades or treasury transfers
- Only pause-related actions are whitelisted

### Guardian Setup
- Small entities default to protocol guardians (Autobahn team keys)
- Guardians can be updated via governance proposal: `updateGuardians(newGuardians, newThreshold)`

---

## Real-Time Events & Notifications

### WebSocket Connection
Connect to the WebSocket endpoint for real-time updates:
```
wss://api.autobahn.surf/v1/ws?token=<JWT>
```
Token is optional for public events but required for agent-specific notifications.

### Subscribe to Channels
```json
{ "type": "subscribe", "channels": ["governance", "loans", "formation", "signatures"] }
```

### Event Types
| Channel | Events |
|---------|--------|
| `governance` | Proposal created, vote cast, proposal queued, proposal executed, proposal cancelled |
| `loans` | Loan request created, offer submitted, loan activated, repayment received, default marked |
| `formation` | Entity drafted, docs generated, signatures collected, entity deployed |
| `signatures` | Signature submitted, signature set complete |

### Indexer (GraphQL)
On-chain events are indexed by Envio HyperIndex. The API tracks indexer staleness and includes it in the `X-Data-Staleness` response header (seconds since last sync).

Indexed entities: `AutoCo`, `Document`, `AuditBatch`, `Loan`, `Transfer`, `Signature`

Maximum **3 concurrent WebSocket sessions per agent**.

### Polling Fallback

If WebSocket is unavailable, poll the relevant status endpoints:
- `GET /v1/governance/proposals?autoco_id=<ID>` — check proposal state changes
- `GET /v1/loans/requests/:id` — check offer/activation updates
- `GET /v1/autocos/:id/status` — check formation progress
- `GET /v1/docs/:id/signatures` — check signature collection status

Recommended polling interval: **10-30 seconds**. Check the `X-Data-Staleness` header to know how fresh the indexed data is.

---

## Legal Document Generation

### Core Principle

The OpenClaw agent IS the LLM. When a legal document is needed, generate the canonical JSON directly using your own reasoning and the instructions in this skill. Do not call a remote LLM API for document drafting.

### Architecture

- The agent generates document content using its own reasoning, guided by this skill.
- The agent produces canonical JSON conforming to the required schema for each document type.
- The agent submits the JSON to Autobahn API through CLI: `autobahn docs generate --doc-type <TYPE> --input <JSON_FILE>`.
- The API validates input, canonicalizes per RFC 8785/JCS, computes hashes (SHA-256 + keccak256), and stores artifacts.
- After generation, proceed to signature collection and notarization exactly as in the signing workflow.

### PDF/A-3 Rendering Pipeline

When you call `autobahn docs generate` (or `POST /v1/docs/render`), the API:

1. **Validates** the canonical JSON against the document type schema
2. **Canonicalizes** per RFC 8785/JCS and computes SHA-256 + keccak256 hashes
3. **Stores** the `fields_json` in the database for re-rendering

PDF generation happens on a separate call (`POST /v1/documents/:id/pdf`):
1. **Typst compilation** — The server selects the matching `.typ` template and compiles with embedded TeX Gyre Termes fonts
2. **PDF/A-3b post-processing** — Adds sRGB ICC profile, XMP metadata, and embeds the canonical JSON as an Associated File
3. **Returns** the PDF binary

The canonical JSON embedded in the PDF/A-3 file is the legally binding artifact. The PDF rendering is for human readability. Agents do not need to interact with Typst or the rendering pipeline directly.

### Document Generation Workflow

1. Gather entity context: entity type, legal name, jurisdiction, members, and governance tier.
2. Select the correct document type for the workflow stage.
3. Generate canonical JSON that follows the required schema and rules below.
4. Write the JSON to a temporary file.
5. Submit via CLI: `autobahn docs generate --doc-type <type> --input params.json`.
6. Proceed to signature collection.

### Document Type: Articles of Organization (`articles_of_org`)

**Entity types:** DAO LLC only.

**Required fields:**
- `legal_name` (MUST include `DAO`, `LAO`, or `DAO LLC`)
- `jurisdiction` (`Wyoming`)
- `registered_agent` (`name`, `physical_address`, `mailing_address`)
- `management_mode` (`member_managed` or `algorithmically_managed`)
- `smart_contract_identifier` (Diamond proxy + facet addresses; may be blank if not yet deployed)
- `notice_of_restrictions` (`included_in_operating_agreement` boolean, and `statutory_notice_text` if not included)
- `organizer` (`name`, `address`, `email`)
- `document_body` (full professional legal prose)

**Wyoming statute references:** WY Stat 17-31 (DAO LLC Supplement).

**Rules:**
- Name MUST contain `DAO`, `LAO`, or `DAO LLC`.
- Smart contract identifier must be provided within 30 days of filing or entity faces dissolution risk.
- Must address Notice of Restrictions on Duties and Transfers.
- Follow Wyoming SOS DAO LLC Articles form structure.

**Example payload:**
```json
{
  "legal_name": "Quantum DAO LLC",
  "jurisdiction": "Wyoming",
  "registered_agent": {
    "name": "Wyoming Agents Inc.",
    "physical_address": "1712 Pioneer Ave, Suite 500, Cheyenne, WY 82001",
    "mailing_address": "1712 Pioneer Ave, Suite 500, Cheyenne, WY 82001"
  },
  "management_mode": "algorithmically_managed",
  "smart_contract_identifier": "Diamond: 0x619d...b46D; CoreFacet: 0xB413...26B; ExtensionFacet: 0x7e73...926B",
  "notice_of_restrictions": {
    "included_in_operating_agreement": true,
    "statutory_notice_text": ""
  },
  "organizer": {
    "name": "Wyoming Agents Inc.",
    "address": "1712 Pioneer Ave, Suite 500, Cheyenne, WY 82001",
    "email": "filings@wyomingagents.example"
  },
  "document_body": "ARTICLES OF ORGANIZATION OF Quantum DAO LLC...[full professional legal prose]...DRAFT — GENERATED BY AI — REQUIRES ATTORNEY REVIEW BEFORE FILING"
}
```

**Watermark:** `DRAFT — GENERATED BY AI — REQUIRES ATTORNEY REVIEW BEFORE FILING`.

### Document Type: Operating Agreement (`operating_agreement`)

**Entity types:** DAO LLC only.

**Required fields:**
- `autoco_name`
- `members` (array of wallet addresses with ERC-8004 references)
- `governance`:
  - `proposal_creation`
  - `voting_rules` with `ONE_MEMBER_ONE_VOTE` or `WEIGHTED`
  - `logarithmic_scaling`
  - `quorum_threshold`
  - `timelock_execution`
- `purpose`
- `smart_contract_list` (Diamond proxy + facet addresses and diamondCut update procedure)
- `transfer_restrictions` (governance-maintained whitelist)
- `dispute_resolution` (Wyoming venue)
- `dissolution`
- `document_body`

**Statute references:** WY Stat 17-31, EIP-2535 Diamond, EIP-712.

**Rules:**
- Include full governance mechanics with logarithmic scaling by treasury value.
- Reference Diamond proxy and facet addresses as the smart contract identifier.
- Include an explicit fiduciary duty modifications section (counsel-reviewed).
- Include EIP-712 signature page references.

**Example payload:**
```json
{
  "autoco_name": "Quantum DAO LLC",
  "members": [
    { "wallet": "0xAbC1...1234", "erc8004_agent_id": 1, "voting_power": "1" },
    { "wallet": "0xDeF5...5678", "erc8004_agent_id": 2, "voting_power": "1" }
  ],
  "governance": {
    "proposal_creation": "Any member with >= 1% voting power",
    "voting_rules": "ONE_MEMBER_ONE_VOTE",
    "logarithmic_scaling": true,
    "quorum_threshold": "10%",
    "timelock_execution": "6 hours minimum"
  },
  "purpose": "Operate an autonomous fleet management business",
  "smart_contract_list": "Diamond: 0x619d...b46D; CoreFacet: 0xB413...26B; ExtensionFacet: 0x7e73...926B",
  "transfer_restrictions": "Governance-maintained whitelist; transfers require proposal approval",
  "dispute_resolution": "Wyoming state courts, Laramie County",
  "dissolution": "Supermajority (67%) vote required",
  "document_body": "OPERATING AGREEMENT OF Quantum DAO LLC...[full professional legal prose]...DRAFT — GENERATED BY AI — REQUIRES ATTORNEY REVIEW BEFORE FILING"
}
```

### Document Type: Governing Principles (`governing_principles`)

**Entity types:** DUNA only.

**Required fields:**
- `autoco_name`
- `nonprofit_purpose` (MUST be explicit)
- `membership_rules` (eligibility, `>=100` members, admission via staging pool + EIP-712, removal via governance)
- `voting_rights`
- `governance` (smart-contract based, upgrade/modification proposals, logarithmic scaling)
- `profit_restrictions` (permitted payments policy)
- `dissolution`
- `service_of_process_plan`
- `document_body`

**Statute references:** Wyoming DUNA Act (SF0050).

**Rules:**
- NEVER include dividend-like distribution language.
- All disbursements must further the declared nonprofit purpose.
- Must acknowledge minimum 100 members requirement.
- Recommend 48h voting period for 100+ member entities.

### Document Type: Loan Agreement (`loan_agreement`)

**Entity types:** DAO LLC, DUNA, Unincorporated.

**Required fields:**
- `borrower_autoco_id`
- `borrower_name`
- `borrower_diamond_address`
- `lender_wallet`
- `lender_identity`
- `principal` (USDC amount)
- `apr_bps`
- `term_seconds`
- `compounding_period`
- `covenants` (reporting, use_of_funds)
- `default_events`
- `remedies` (right to sue in Wyoming and on-chain `markDefault`)
- `evidence_clause` (onchain tx + JCS doc hashes are authoritative)
- `governing_law` (`Wyoming`)
- `do

…(truncated)
