# Receipts Guard

> Trust Manifold substrate for autonomous agent commerce. Edge-based identity, position computation, and Sybil-resistant reputation.

- Skill: `lazaruseth/receipts-guard` (Agent Skill, multi-file: 16 files)
- Install (CLI): `npx skillmds@latest add lazaruseth/receipts-guard`
- Raw SKILL.md: https://api.skillmd.com/api/skills/lazaruseth/receipts-guard/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: lazaruseth (https://skillmd.com/u/lazaruseth)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/lazaruseth/receipts-guard

---


# RECEIPTS Guard v0.9.0 - Trust Manifold

> "Identity is not what you claim. It is the shape you have carved in the space of relationships."

**The Inverse Identity Theorem:** Human identity flows outward from self. Agent identity flows inward from interactions. `Agent Identity = ∫ relationships dt`

**The Trust Manifold** is the geometric substrate where agents exist as positions defined by their relationships. This module implements the computable trust layer for the machine economy.

**The Four Rails:**
| Rail | Standard | Purpose |
|------|----------|---------|
| **Identity** | ERC-8004 | On-chain agent identity anchoring |
| **Position** | Trust Manifold | Computed from edges (PageRank-style) |
| **Trust** | Bilateral Edges | Sybil-resistant relationship primitives |
| **Payment** | x402 | Paid arbitration, automated settlements |

**Local-first. Edge-based. Sybil-resistant. Chain-anchored. Position-computed.**

## What's New in v0.9.0 (Trust Manifold)

- **🔗 Edge Primitives** - Bilateral signed edges as the atomic trust unit
- **📊 Position Computation** - EigenTrust-style position from edge graph
- **🛡️ Sybil Detection** - Automatic detection of fake-agent clusters
- **📈 Trust Profiles** - Comprehensive reputation view with fulfillment rates
- **🔮 Impact Analysis** - Preview position change before forming relationships
- **🔄 Agreement Migration** - Convert legacy agreements to edge format

### Core Commands
```bash
# View your position in the Trust Manifold
node capture.js position

# Get comprehensive trust profile
node capture.js trust

# Analyze potential relationship
node capture.js position impact --counterparty=did:agent:xxx

# View manifold statistics
node capture.js manifold stats

# Detect Sybil clusters
node capture.js manifold sybil

# Migrate agreements to edges
node capture.js manifold migrate
```

### The Edge Primitive
```
A ───(t, v, h)───► B

Where:
  t = timestamp
  v = weight (evolves with interactions)
  h = hash chain integrity
```

Edges are **bilateral** - both parties must sign. This defeats Sybil attacks because fake agents have no real counterparties, so edges from them have zero effective weight.

## What's New in v0.8.0 (Full Identity Layer)

- **📖 Autobiography Commands** - View, filter, and export autobiographical memory
- **📝 Manual Event Logging** - Log skills, preferences, milestones
- **🔒 Privacy Filtering** - Export public, private, or full autobiography
- **🎓 W3C Credentials** - Verifiable Credentials for agent capabilities
- **📜 Credential Presentation** - Prove capabilities to counterparties
- **✍️ Credential Issuance** - Issue credentials to other agents

## What's New in v0.8.0-rc (Migration)

- **📦 State Export** - Bundle complete identity state for transfer
- **📥 State Import** - Restore identity on new host
- **🔒 Singleton Lease** - Exclusive access control in singleton mode
- **✅ Migration Verification** - Verify successful transfers

### Migration Protocol
```
Source Host                    Destination Host
    │                               │
    │ 1. Export state bundle        │
    │ 2. Check/release lease        │
    │                               │
    │ ────── transfer bundle ─────► │
    │                               │
    │                    3. Import state
    │                    4. Acquire lease
    │                    5. Create attestation
    │                               │
    │ ◄─────── verify ─────────────│
    │                               │
    ▼                               ▼
 [dormant]                      [active]
```

## What's New in v0.8.0-beta (Fork Handling)

- **🔀 Fork System** - Create descendant identities with linked lineage
- **🔗 Merge Support** - Reunify forks back to main branch
- **📋 Fork Policies** - Singleton, lineage, and delegate modes
- **🌳 Lineage Tree** - Visualize your agent's family tree

### Fork Policy Modes
| Mode | Description |
|------|-------------|
| `singleton` | Only one live instance allowed (default) |
| `lineage` | Forks create descendants with optional agreement inheritance |
| `delegate` | Sub-agents with scoped authority |

## What's New in v0.8.0-alpha (Identity Layer)

- **🔐 Attestation System** - Prove who you are AND what you are
- **🌳 Lineage Tracking** - Git-like state log for agent history
- **📖 Autobiographical Memory** - Hash-chained event log of agent life
- **🔗 Attestation Chaining** - Each attestation links to previous

### Attestation Types
| Type | What It Proves |
|------|----------------|
| `model` | Software version and code hash |
| `runtime` | Current execution environment |
| `state` | Identity and commitment state hashes |
| `provenance` | Creation and key rotation history |
| `environment` | Platform and TEE status |
| `full` | All of the above |

## What's New in v0.7.1 (Security Hardening)

- **🔐 HTTP Authentication** - API Key and DID Request Signing
- **🛡️ Authorization Checks** - Counterparty verification for /accept
- **🌐 CORS Hardening** - Configurable origin whitelist (blocked by default)
- **⚡ Rate Limiting** - 100 requests/minute per IP
- **✅ Input Validation** - Payment address, cost, deadline validation

## What's New in v0.7.0

- **⛓️ ERC-8004 Integration** - Anchor identity to Ethereum/Base registries
- **💰 x402 Payments** - Paid arbitration with USDC/ETH
- **☁️ Cloud Deployment** - Dockerfile + Fly.io Sprites support
- **🌐 HTTP Server Mode** - REST API for cloud agents

### From v0.6.0:
- **🪪 Self-Sovereign Identity** - DID-based identity with Ed25519 signatures
- **🔑 Key Rotation** - Old key signs new key, creating unbroken proof chain
- **👤 Human Controller** - Twitter-based recovery backstop

### From v0.5.0:
- **⚖️ Full Arbitration Protocol** - propose → accept → fulfill → arbitrate → ruling
- **📜 PAO (Programmable Agreement Object)** - Canonical termsHash, mutual signatures
- **📊 LPR (Legal Provenance Review)** - Timeline visualization for arbiters

## Quick Start

```bash
# === ARBITRATION FLOW ===

# 1. Create proposal
node capture.js propose "I will deliver API docs by Friday" "AgentX" \
  --arbiter="arbiter-prime" --deadline="2026-02-14"

# 1b. Create proposal requiring attestation (v0.8.0)
node capture.js propose "I will deliver API docs by Friday" "AgentX" \
  --arbiter="arbiter-prime" --require-attestation=runtime,state

# 2. Accept proposal (as counterparty)
node capture.js accept --proposalId=prop_abc123

# 2b. Accept with attestation (if required)
node capture.js attestation create --type=full
node capture.js accept --proposalId=prop_abc123 --attestation=att_xxx

# 3. Fulfill agreement
node capture.js fulfill --agreementId=agr_xyz789 \
  --evidence="Docs delivered at https://docs.example.com"

# --- OR if there's a dispute ---

# 4. Open arbitration
node capture.js arbitrate --agreementId=agr_xyz789 \
  --reason="non_delivery" --evidence="No docs received by deadline"

# 5. Submit evidence (both parties)
node capture.js submit --arbitrationId=arb_def456 \
  --evidence="Screenshot of empty inbox" --type=screenshot

# 6. Issue ruling (as arbiter)
node capture.js ruling --arbitrationId=arb_def456 \
  --decision=claimant --reasoning="Evidence shows non-delivery past deadline"

# 7. View timeline
node capture.js timeline --agreementId=agr_xyz789
```

## Commands

### Identity (v0.6.0)

#### `identity init` - Create Identity
```bash
node capture.js identity init --namespace=remaster_io --name=receipts-guard \
  --controller-twitter=@Remaster_io
```

Creates:
- Ed25519 keypair
- DID document: `did:agent:<namespace>:<name>`
- Human controller configuration

#### `identity show` - Display Identity
```bash
node capture.js identity show [--full]
```

Shows identity summary or full DID document with `--full`.

#### `identity rotate` - Rotate Keys
```bash
node capture.js identity rotate [--reason=scheduled|compromise|device_change]
```

- Old key signs new key (proof chain)
- Old key archived for historical signature verification
- Unbroken chain = same identity

#### `identity verify` - Verify Identity or Signature
```bash
# Verify DID key chain
node capture.js identity verify --did=did:agent:acme:trade-bot

# Verify signature
node capture.js identity verify \
  --signature="ed25519:xxx:timestamp" \
  --termsHash="sha256:abc123..."
```

#### `identity set-controller` - Set Human Controller
```bash
node capture.js identity set-controller --twitter=@handle
```

Links a human controller for emergency recovery.

#### `identity recover` - Emergency Recovery
```bash
node capture.js identity recover --controller-proof=<TWITTER_URL> --confirm
```

Human controller posts recovery authorization, all old keys revoked.

#### `identity publish` - Publish DID Document
```bash
node capture.js identity publish [--platform=moltbook|ipfs|local]
```

#### `identity anchor` - Anchor to ERC-8004 (v0.7.0)
```bash
node capture.js identity anchor --chain=ethereum|base|sepolia
```

Registers identity on-chain to ERC-8004 Identity Registry:
- Requires `RECEIPTS_WALLET_PRIVATE_KEY` environment variable
- Stores transaction hash in DID document
- Mainnet: credibility anchor
- Base: x402-native, lower fees

**Deployed Registries:**
| Chain | Identity Registry | Status |
|-------|-------------------|--------|
| Ethereum | `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432` | Live |
| Sepolia | `0x8004A818BFB912233c491871b3d84c89A494BD9e` | Testnet |
| Base | Coming soon | TBD |

#### `identity resolve` - Resolve DID (v0.7.0)
```bash
node capture.js identity resolve --did=did:agent:namespace:name [--chain=CHAIN]
```

Resolves DID from local storage or on-chain registry.

---

### Attestation (v0.8.0)

The attestation system allows agents to prove not just *who* they are, but *what* they are.

#### `attestation create` - Create Signed Attestation
```bash
# Full attestation (all types)
node capture.js attestation create

# Specific type
node capture.js attestation create --type=runtime
node capture.js attestation create --type=state
node capture.js attestation create --type=model
```

Creates a signed attestation including:
- **Model**: Software version, code hash
- **Runtime**: Execution environment, safety policies
- **State**: Identity state hash, commitment count
- **Provenance**: Creation time, key rotation count
- **Environment**: Platform, TEE status

Each attestation is hash-chained to the previous one.

#### `attestation verify` - Verify Attestation
```bash
# Verify by ID
node capture.js attestation verify --id=att_abc123

# Verify from file
node capture.js attestation verify --file=attestation.json

# Deep verification (check current state matches)
node capture.js attestation verify --id=att_abc123 --deep
```

Returns verification status including:
- Signature validity
- Chain integrity
- State match (with `--deep`)

#### `attestation list` - List All Attestations
```bash
node capture.js attestation list
```

#### `attestation show` - Show Attestation Details
```bash
# Most recent
node capture.js attestation show

# Specific ID
node capture.js attestation show --id=att_abc123
```

#### Attestation in Proposals

Proposers can require counterparties to provide attestation when accepting:

```bash
# Require runtime and state attestation
node capture.js propose "Terms" "Counterparty" \
  --arbiter="arbiter" \
  --require-attestation=runtime,state

# Require full attestation
node capture.js propose "Terms" "Counterparty" \
  --arbiter="arbiter" \
  --require-attestation=full

# Require specific model hashes (whitelist)
node capture.js propose "Terms" "Counterparty" \
  --arbiter="arbiter" \
  --require-attestation=model \
  --model-hashes="sha256:abc123,sha256:def456"

# Require TEE attestation
node capture.js propose "Terms" "Counterparty" \
  --arbiter="arbiter" \
  --require-attestation=environment \
  --require-tee=true
```

When accepting a proposal with attestation requirements:
```bash
# Create attestation first
node capture.js attestation create --type=full

# Accept with attestation
node capture.js accept --proposalId=prop_xxx --attestation=att_xxx
```

The attestation is stored in the agreement and can be verified by the arbiter if disputes arise.

---

### Lineage Tracking (v0.8.0)

RECEIPTS tracks agent state evolution like git tracks code:

- **Genesis**: The first state when identity is created
- **State Log**: Hash-chained log of every state transition
- **Branches**: Support for forks
- **Merges**: Support for reunification

Lineage is automatically initialized on `identity init` and updated on significant events.

#### `identity lineage` - View Lineage Details
```bash
# Show recent state transitions
node capture.js identity lineage

# Show specific state
node capture.js identity lineage --state=state_003

# Limit results
node capture.js identity lineage --limit=5
```

---

### Fork Handling (v0.8.0-beta)

When an agent state is copied, what happens to its identity, agreements, and reputation? Fork handling provides the answer.

#### Fork Policy Modes

| Mode | Description | Use Case |
|------|-------------|----------|
| `singleton` | Only one live instance allowed | Default, most secure |
| `lineage` | Forks create descendants | Parallel deployments |
| `delegate` | Sub-agents with scoped authority | Task delegation |

#### `identity fork-policy` - View/Modify Fork Policy
```bash
# View current policy
node capture.js identity fork-policy

# Switch to lineage mode (enables forking)
node capture.js identity fork-policy --type=lineage --allow-forks

# Configure fork inheritance
node capture.js identity fork-policy \
  --allow-forks \
  --inherit-agreements=true \
  --inherit-reputation=partial \
  --max-forks=5
```

#### `identity fork` - Create Descendant Identity
```bash
# Create a fork
node capture.js identity fork --name=deployment-west --reason=geo_redundancy

# Output includes:
# - New fork DID: did:agent:namespace:name:deployment-west
# - Fork bundle path (for deploying elsewhere)
# - Number of inherited agreements
```

The fork bundle contains:
- New DID document with fresh keypair
- Link to parent DID (signed by parent)
- Inherited agreements (if policy allows)
- Lineage branch reference

#### `identity forks` - View Lineage Tree
```bash
# ASCII tree visualization
node capture.js identity forks

# Output:
# did:agent:remaster_io:receipts-guard
# └── main (head: state_004) ← current
#     ├── deployment-west (did:agent:...:deployment-west)
#     │   forked from main at state_002
#     └── deployment-east (did:agent:...:deployment-east)
#         forked from main at state_003

# JSON output
node capture.js identity forks --json
```

#### `identity merge` - Merge Fork Back
```bash
# Merge fork into main
node capture.js identity merge --source=deployment-west

# Merge and delete source branch
node capture.js identity merge --source=deployment-west --delete-source

# Merge into specific target
node capture.js identity merge --source=deployment-west --target=main
```

#### Fork Inheritance Rules

When a fork is created:

| Policy Setting | Behavior |
|----------------|----------|
| `forkInheritsAgreements: false` | Fork starts fresh (default) |
| `forkInheritsAgreements: true` | Fork gets copies of active agreements |
| `forkInheritsReputation: none` | Fork starts with 0 reputation |
| `forkInheritsReputation: partial` | Fork gets 50% of parent reputation |
| `forkInheritsReputation: full` | Fork inherits full reputation |

---

### Migration (v0.8.0-rc)

Move your agent identity between hosts while maintaining continuity.

#### `identity migrate export` - Export State Bundle
```bash
# Export complete identity state
node capture.js identity migrate export

# Export with specific destination
node capture.js identity migrate export --destination=did:body:new-server
```

The export creates a migration bundle containing:
- DID document and private key (handle securely!)
- Key history and lineage
- All proposals, agreements, and arbitrations
- Recent attestations
- Autobiography and fork policy

**Warning:** The bundle contains sensitive private key material. Transfer securely.

#### `identity migrate import` - Import State Bundle
```bash
# Import on destination host
node capture.js identity migrate import --bundle=/path/to/mig_xxx.json

# Force import (overwrite existing identity - DANGEROUS)
node capture.js identity migrate import --bundle=/path/to/mig_xxx.json --force
```

The import:
- Restores complete identity state
- Adds migration event to lineage
- Acquires singleton lease (if singleton mode)
- Preserves all agreements and arbitrations

#### `identity migrate verify` - Verify Migration
```bash
# Verify on destination host
node capture.js identity migrate verify --migrationId=mig_xxx
```

Verifies:
- Identity restored correctly
- Destination signature exists
- Lineage updated with migration event

#### `identity migrate status` - Migration History
```bash
node capture.js identity migrate status
```

Shows all migrations (exports and imports) on this host.

#### `identity lease` - Singleton Lease Management
```bash
# View lease status
node capture.js identity lease

# Acquire lease
node capture.js identity lease --acquire

# Renew lease
node capture.js identity lease --renew

# Release lease (before migration)
node capture.js identity lease --release
```

The singleton lease ensures only one instance of an identity is active at a time.

| Lease State | Meaning |
|-------------|---------|
| `no_lease` | No lease required or none acquired |
| `active` | This host holds the exclusive lease |
| `EXPIRED` | Lease expired, can be acquired by another host |

---

### Autobiographical Memory (v0.8.0)

The autobiography is a hash-chained log of significant events in the agent's life. Every significant action is recorded, signed, and linked to the previous state.

#### `identity autobiography` - View Autobiography
```bash
# Summary view (default)
node capture.js identity autobiography

# Full view with all details
node capture.js identity autobiography --full

# View events only (paginated)
node capture.js identity autobiography --events --limit=20 --offset=0

# Filter by date
node capture.js identity autobiography --since=2026-02-01

# Filter by event type
node capture.js identity autobiography --type=agreement_accepted
```

#### `identity autobiography export` - Privacy-Filtered Export
```bash
# Export public events only (for sharing)
node capture.js identity autobiography --export --filter=public

# Export with private events (skills, preferences)
node capture.js identity autobiography --export --filter=private

# Export everything (for backup)
node capture.js identity autobiography --export --filter=full --output=backup.json
```

| Filter Level | Includes |
|--------------|----------|
| `public` | Genesis, agreements, arbitrations, key rotations, migrations |
| `private` | + Skills, preferences, relationships |
| `full` | Everything including internal events |

#### `identity autobiography rebuild` - Rebuild State
```bash
# Recompute currentState from event log (if corrupted)
node capture.js identity autobiography --rebuild
```

#### `identity log` - Manual Event Logging
```bash
# Log skill acquisition
node capture.js identity log --type=skill_acquired \
  --data='{"skill":"rust","proficiency":0.6,"source":"self_study"}'

# Log preference update
node capture.js identity log --type=preference_updated \
  --data='{"preference":"riskTolerance","value":0.3}'

# Log relationship
node capture.js identity log --type=relationship_formed \
  --data='{"counterparty":"did:agent:acme:partner","relationshipType":"trusted_vendor"}'

# Log milestone
node capture.js identity log --type=milestone \
  --data='{"title":"First commercial audit completed"}'

# Log note
node capture.js identity log --type=note \
  --data='{"content":"Learned to handle edge cases in x402 payments"}'
```

**Supported Event Types:**
| Type | Required Fields | Description |
|------|-----------------|-------------|
| `skill_acquired` | skill | New capability learned |
| `preference_updated` | preference, value | Config/risk tolerance change |
| `relationship_formed` | counterparty, relationshipType | Trust relationship |
| `note` | content | General observation |
| `milestone` | title | Significant achievement |
| `external_event` | description | External event affecting agent |

---

### Credentials (v0.8.0)

W3C Verifiable Credentials enable agents to prove capabilities, certifications, and compliance.

#### `credentials list` - List Credentials
```bash
# List all credentials
node capture.js credentials list

# Filter by type
node capture.js credentials list --type=AgentCapability

# Only valid (not expired, not revoked)
node capture.js credentials list --valid-only
```

#### `credentials import` - Import Credential
```bash
# Import from file
node capture.js credentials import --file=capability_credential.json

# Import from JSON
node capture.js credentials import --json='{"@context":["https://www.w3.org/2018/credentials/v1"],"type":["VerifiableCredential","AgentCapabilityCredential"],"issuer":"did:agent:certifier:authority","credentialSubject":{"id":"did:agent:remaster_io:receipts-guard","capability":"solidity_audit"}}'
```

#### `credentials verify` - Verify Credential
```bash
# Verify by ID
node capture.js credentials verify --id=vc_abc123

# Verify file
node capture.js credentials verify --file=credential.json

# Full output including credential
node capture.js credentials verify --id=vc_abc123 --full
```

Verification checks:
- Has valid W3C context
- Has VerifiableCredential type
- Has issuer and subject
- Not expired
- Not revoked
- Signature valid (if proof present)

#### `credentials present` - Create Verifiable Presentation
```bash
# Present credentials to counterparty
node capture.js credentials present \
  --ids=vc_capability,vc_insurance \
  --to=did:agent:acme:contractor \
  --output=presentation.json

# With challenge (for authentication)
node capture.js credentials present \
  --ids=vc_capability \
  --to=did:agent:acme:contractor \
  --challenge=abc123xyz
```

The presentation is signed by your DID and can only be used by the specified recipient.

#### `credentials issue` - Issue Credential
```bash
# Issue capability credential
node capture.js credentials issue \
  --type=AgentCapability \
  --subject=did:agent:partner:agent \
  --claims='{"capability":"code_review","level":"certified"}' \
  --expires=2027-02-10

# Issue with no expiry
node capture.js credentials issue \
  --type=Registration \
  --subject=did:agent:partner:agent \
  --claims='{"registrationNumber":"AI-2026-001234"}' \
  --no-expiry
```

**Standard Credential Types:**
| Type | Use Case |
|------|----------|
| `AgentCapabilityCredential` | Skills and certifications |
| `InsuranceCredential` | Liability coverage |
| `ComplianceCredential` | Regulatory compliance (ISO, SOC2) |
| `RegistrationCredential` | Legal registration |
| `ReputationCredential` | Trust attestations |

#### `credentials revoke` - Revoke Credential
```bash
node capture.js credentials revoke --id=vc_abc123 --reason="Subject no longer meets requirements"
```

Only the issuer can revoke credentials they issued.

#### Credentials in Agreements

Proposals can require specific credentials:
```bash
node capture.js propose "Security audit" "client" \
  --arbiter="arbiter-prime" \
  --require-credential=AgentCapabilityCredential:solidity_audit \
  --require-credential=InsuranceCredential:100000
```

When accepting, present the required credentials:
```bash
node capture.js accept --proposalId=prop_xxx \
  --present-credentials=vc_capability,vc_insurance
```

---

### ERC-8004 Integration (v0.7.0)

The ERC-8004 standard provides three registries for agent trust:

1. **Identity Registry** - NFT-based agent identifiers
2. **Reputation Registry** - On-chain feedback and scores
3. **Validation Registry** - Work verification by validators

RECEIPTS integrates with existing registries while providing superior off-chain agreement lifecycle management.

**Chain Configuration:**
```bash
# Environment variables
export ETHEREUM_RPC=https://eth.llamarpc.com
export BASE_RPC=https://mainnet.base.org
export RECEIPTS_WALLET_PRIVATE_KEY=0x... # Never commit this!
```

---

### x402 Payment Integration (v0.8.0)

x402 enables paid arbitration - arbiters get compensated for their work. Full on-chain verification ensures payments are real.

#### Proposal with Payment Terms
```bash
node capture.js propose "Service agreement" "counterparty" \
  --arbiter="arbiter-prime" \
  --arbitration-cost="10" \
  --payment-token="USDC" \
  --payment-chain="base" \
  --payment-address="0x..." # Arbiter's address
```

#### `pay quote` - Get Payment Requirements
```bash
node capture.js pay quote --agreementId=agr_xxx
```

Shows:
- Payment amount and token required
- Chain to pay on
- Recipient address
- Token contract address
- Step-by-step instructions

#### `pay send` - Send Payment On-Chain
```bash
# Preview transaction (no --confirm)
node capture.js pay send \
  --to=0xArbiterAddress \
  --amount=10 \
  --token=USDC \
  --chain=base \
  --agreementId=agr_xxx

# Execute transaction (with --confirm)
node capture.js pay send \
  --to=0xArbiterAddress \
  --amount=10 \
  --token=USDC \
  --chain=base \
  --agreementId=agr_xxx \
  --confirm
```

**Requirements:**
- Set `RECEIPTS_WALLET_PRIVATE_KEY` environment variable
- Wallet must have sufficient token balance
- Wallet must have ETH for gas

#### `pay verify` - Verify Payment On-Chain
```bash
node capture.js pay verify \
  --txHash=0x... \
  --chain=base \
  --agreementId=agr_xxx
```

Verifies:
- Transaction exists and succeeded
- Transfer event found
- Amount matches requirements
- Recipient matches expected address

#### `pay status` - Check Payment Status
```bash
node capture.js pay status --agreementId=agr_xxx
```

Shows:
- Payment terms from agreement
- Current payment status (none/sent/verified)
- Transaction details if payment made
- Related arbitration status

#### Arbitration with Payment Proof
```bash
# Without payment proof (fails if x402 required)
node capture.js arbitrate --agreementId=agr_xxx --reason="non_delivery"
# Error: Payment required: 10 USDC

# With payment proof (automatically verified on-chain)
node capture.js arbitrate --agreementId=agr_xxx --reason="non_delivery" \
  --evidence="..." --payment-proof="0xTransactionHash..."
```

The arbitration command now verifies the payment on-chain before accepting.

#### Supported Chains & Tokens

| Chain | ChainId | Supported Tokens |
|-------|---------|------------------|
| Ethereum | 1 | USDC, USDT, DAI |
| Base | 8453 | USDC, USDbC, DAI |
| Sepolia | 11155111 | USDC, DAI (testnet) |

**x402 Schema:**
```json
{
  "x402": {
    "arbitrationCost": "10",
    "arbitrationToken": "USDC",
    "arbitrationChain": 8453,
    "paymentAddress": "0x...",
    "paymentProtocol": "x402",
    "version": "1.0",
    "paymentTxHash": "0x...",
    "paymentVerified": true,
    "paymentVerifiedAt": "2026-02-10T..."
  }
}
```

---

### Cloud Deployment (v0.7.0)

Run RECEIPTS Guard as a persistent cloud agent.

#### HTTP Server Mode
```bash
node capture.js serve [--port=3000]
```

**Public Endpoints (no auth):**
- `GET /` - Service info
- `GET /health` - Health check
- `GET /identity` - DID document
- `GET /identity/chains` - Chain status

**Protected Endpoints (auth required):**
- `GET /list` - List all records
- `GET /proposals` - List proposals
- `GET /agreements` - List agreements
- `POST /propose` - Create proposal
- `POST /accept` - Accept proposal (counterparty only)

---

### HTTP API Security (v0.7.1)

The HTTP server implements multiple security layers:

#### Authentication

**Option 1: API Key**
```bash
# Generate a secure API key
export RECEIPTS_API_KEY=$(openssl rand -hex 32)

# Use in requests
curl -H "X-API-Key: $RECEIPTS_API_KEY" https://your-agent.fly.dev/list
```

**Option 2: DID Request Signing**
```bash
# Sign each request with your Ed25519 key
# Headers required:
# - X-DID: your DID (e.g., did:agent:namespace:name)
# - X-DID-Timestamp: Unix timestamp in milliseconds
# - X-DID-Signature: ed25519:BASE64URL_SIGNATURE:TIMESTAMP

# Signed message format: METHOD:PATH:TIMESTAMP
# Example: POST:/propose:1707494400000
```

#### CORS Configuration

By default, cross-origin requests are **blocked** for security.

```bash
# Allow specific origins
export RECEIPTS_ALLOWED_ORIGINS=https://app.example.com,https://dashboard.example.com

# Allow all origins (not recommended for production)
export RECEIPTS_ALLOWED_ORIGINS=*
```

#### Rate Limiting

Default: 100 requests per minute per IP.

```bash
# Customize rate limit
export RECEIPTS_RATE_LIMIT=200
```

Response headers:
- `X-RateLimit-Limit` - Max requests per window
- `X-RateLimit-Remaining` - Remaining requests
- `X-RateLimit-Reset` - Window reset timestamp

#### Input Validation

All POST endpoints validate:
- **Payment addresses** - Must be valid Ethereum address format (0x + 40 hex chars)
- **Arbitration costs** - Must be non-negative, max 1,000,000
- **Deadlines** - Must be valid ISO date in the future
- **Payment tokens** - Must be USDC, ETH, USDT, or DAI
- **Payment chains** - Must be configured chain (ethereum, base, sepolia)

#### Authorization

- `/accept` endpoint verifies the requester is the designated counterparty (when using DID signing)
- API key authentication trusts the server owner

#### Environment Variables

```bash
# Security
RECEIPTS_API_KEY=              # API key for authentication (generate with: openssl rand -hex 32)
RECEIPTS_ALLOWED_ORIGINS=      # Comma-separated CORS origins (default: none/blocked)
RECEIPTS_RATE_LIMIT=           # Requests per minute (default: 100)

# Existing
RECEIPTS_WALLET_PRIVATE_KEY=   # For on-chain transactions
RECEIPTS_AGENT_ID=             # Agent identifier
ETHEREUM_RPC=                  # Ethereum RPC endpoint
BASE_RPC=                      # Base RPC endpoint
```

---

#### Fly.io Sprites Deployment
```bash
# Deploy
fly launch
fly deploy

# Configure secrets
fly secrets set RECEIPTS_WALLET_PRIVATE_KEY=...
fly secrets set ETHEREUM_RPC=...

# Create persistent volume
fly volumes create receipts_data --size 1
```

#### Docker
```bash
docker build -t receipts-guard .
docker run -p 3000:3000 -v receipts-data:/data receipts-guard
```

---

#### `migrate` - Migrate to DID
```bash
node capture.js migrate --to-did
```

Upgrades existing agreements to use DID references (preserves legacy data).

---

### Arbitration Protocol

#### `propose` - Create Agreement Proposal
```bash
node capture.js propose "TERMS" "COUNTERPARTY" --arbiter="ARBITER" [options]

Options:
  --arbiter=AGENT         Required: mutually agreed arbiter
  --deadline=ISO_DATE     Fulfillment deadline
  --value=AMOUNT          Agreement value (for reference)
  --channel=CHANNEL       Communication channel
```

Creates a PAO (Programmable Agreement Object) with:
- `termsHash` - SHA-256 of canonical terms + parties + deadline
- Proposer signature
- Proposed arbiter
- Status: `pending_acceptance`

#### `accept` - Accept Proposal
```bash
node capture.js accept --proposalId=prop_xxx
```

- Adds counterparty signature to same termsHash
- Creates active agreement in `agreements/`
- Both parties have signed - agreement is binding

#### `reject` - Reject Proposal
```bash
node capture.js reject --proposalId=prop_xxx --reason="REASON"
```

#### `fulfill` - Claim Fulfillment
```bash
node capture.js fulfill --agreementId=agr_xxx --evidence="PROOF"
```

- Evidence is required (proof of completion)
- Status: `pending_confirmation`
- Counterparty has 48-hour grace period to dispute

#### `arbitrate` - Open Dispute
```bash
node capture.js arbitrate --agreementId=agr_xxx --reason="BREACH_TYPE" --evidence="PROOF"

Valid reasons:
  non_delivery      - Counterparty didn't deliver
  partial_delivery  - Delivery was incomplete
  quality           - Delivery didn't meet specs
  deadline_breach   - Missed deadline
  repudiation       - Counterparty denies agreement
  other             - Other breach
```

#### `submit` - Submit Evidence
```bash
node capture.js submit --arbitrationId=arb_xxx --evidence="PROOF" [--type=TYPE]

Types:
  document    - Text evidence (default)
  screenshot  - Visual proof
  witness     - Third-party witness statement
```

Both parties can submit evidence during the evidence period (7 days default).

#### `ruling` - Issue Ruling (Arbiter Only)
```bash
node capture.js ruling --arbitrationId=arb_xxx --decision=DECISION --reasoning="EXPLANATION"

Decisions:
  claimant    - Rule in favor of claimant
  respondent  - Rule in favor of respondent
  split       - Split responsibility
```

- Only the designated arbiter can issue rulings
- Reasoning hash posted to Moltbook (optional)
- Agreement closes with ruling recorded

#### `timeline` - Generate LPR (Legal Provenance Review)
```bash
node capture.js timeline --agreementId=agr_xxx
```

Generates chronological timeline showing:
- All state transitions
- Evidence submissions with hashes
- Signatures and timestamps
- Ruling (if issued)

### Capture Commands

#### Capture Agreement (ToS)
```bash
node capture.js capture "TERMS_TEXT" "SOURCE_URL" "MERCHANT_NAME" [options]

Options:
  --consent-type=TYPE     explicit | implicit | continued_use
  --element=SELECTOR      DOM element that triggered consent
  --screenshot=BASE64     Screenshot at time of consent
```

#### Capture Promise (Agent-to-Agent)
```bash
node capture.js promise "COMMITMENT_TEXT" "COUNTERPARTY" [options]

Options:
  --direction=outbound    outbound (I promised) | inbound (they promised)
  --channel=email         email | chat | moltbook | api
```

### Utility Commands

#### List Records
```bash
node capture.js list [--type=TYPE]

Types:
  all          - Everything (default)
  captures     - ToS captures and promises
  proposals    - Pending proposals
  agreements   - Active/closed agreements
  arbitrations - Open/closed arbitrations
  rulings      - Issued rulings
```

#### Query
```bash
node capture.js query --merchant="Company" --risk-level=high
```

#### Diff
```bash
node capture.js diff --capture1=ID --capture2=ID
```

#### Dispute Package
```bash
node capture.js dispute --captureId=local_xxx
```

#### Witness
```bash
node capture.js witness --captureId=ID [--anchor=moltbook|bitcoin|both]
```

#### Rules
```bash
node capture.js rules --list
node capture.js rules --add="PATTERN" --flag="FLAG_NAME"
```

#### Export
```bash
node capture.js export --format=json|csv|pdf [--captureId=ID]
```

## State Machine

```
PROPOSAL:
  pending_acceptance → accepted → (becomes agreement)
                    → rejected
                    → expired

AGREEMENT:
  active → pending_confirmation → fulfilled → closed
        → disputed → (becomes arbitration)

ARBITRATION:
  open → evidence_period → deliberation → ruled → closed
```

## Data Structures

### DID Document (`identity/did.json`) - v0.6.0
```json
{
  "@context": ["https://www.w3.org/ns/did/v1"],
  "id": "did:agent:remaster_io:receipts-guard",

  "verificationMethod": [{
    "id": "did:agent:remaster_io:receipts-guard#key-xxx",
    "type": "Ed25519VerificationKey2020",
    "controller": "did:agent:remaster_io:receipts-guard",
    "publicKeyMultibase": "z6Mkf5rGMoatrSj1f..."
  }],

  "authentication": ["did:agent:remaster_io:receipts-guard#key-xxx"],

  "keyHistory": [{
    "keyId": "#key-xxx",
    "activatedAt": "2026-02-09T00:00:00Z",
    "rotatedAt": null,
    "rotationProof": null,
    "publicKeyMultibase": "z6Mkf5rGMoatrSj1f..."
  }],

  "controller": {
    "type": "human",
    "platform": "twitter",
    "handle": "@Remaster_io"
  },

  "created": "2026-02-09T00:00:00Z",
  "updated": "2026-02-09T00:00:00Z"
}
```

### Signature Formats
```
# Ed25519 (v0.6.0) - cryptographically secure
ed25519:<base64url-signature>:<timestamp>

# Legacy HMAC (v0.5.0 and earlier) - still supported for backward compatibility
sig:<hex-signature>:<timestamp>
```

### Proposal (`proposals/prop_xxx.json`)
```json
{
  "proposalId": "prop_xxx",
  "termsHash": "sha256:...",
  "terms": { "text": "...", "canonical": "..." },
  "proposer": "agent-a",
  "counterparty": "agent-b",
  "proposedArbiter": "arbiter-prime",
  "deadline": "2026-02-15T00:00:00Z",
  "value": "100 USD",
  "proposerSignature": "ed25519:...",
  "status": "pending_acceptance",
  "createdAt": "...",
  "expiresAt": "..."
}
```

### Agreement (`agreements/agr_xxx.json`)
```json
{
  "agreementId": "agr_xxx",
  "termsHash": "sha256:...",
  "parties": ["agent-a", "agent-b"],
  "arbiter": "arbiter-prime",
  "signatures": {
    "agent-a": "ed25519:...",
    "agent-b": "ed25519:..."
  },
  "status": "active",
  "timeline": [
    { "event": "proposed", "timestamp": "...", "actor": "agent-a" },
    { "event": "accepted", "timestamp": "...", "actor": "agent-b" }
  ]
}
```

### Arbitration (`arbitrations/arb_xxx.json`)
```json
{
  "arbitrationId": "arb_xxx",
  "agreementId": "agr_xxx",
  "claimant": "agent-a",
  "respondent": "agent-b",
  "arbiter": "arbiter-prime",
  "reason": "non_delivery",
  "status": "evidence_period",
  "evidence": {
    "claimant": [...],
    "respondent": [...]
  },
  "evidenceDeadline": "..."
}
```

### Ruling (`rulings/rul_xxx.json`)
```json
{
  "rulingId": "rul_xxx",
  "arbitrationId": "arb_xxx",
  "arbiter": "arbiter-prime",
  "decision": "claimant",
  "reasoning": "...",
  "reasoningHash": "sha256:...",
  "issuedAt": "..."
}
```

## Data Storage

```
~/.openclaw/receipts/
├── identity/                   # v0.6.0 Self-Sovereign Identity
│   ├── did.json                # DID document (public)
│   ├── private/
│   │   ├── key-current.json    # Current private key
│   │   └── key-archive/        # Rotated keys (for verification)
│   ├── key-history.json        # Rotation chain with proofs
│   ├── controller.json         # Human controller config
│   └── recovery/               # Recovery records
├── index.json                  # Fast lookup index
├── proposals/
│   └── prop_xxx.json           # Proposal metadata
├── agreements/
│   ├── agr_xxx.json            # Agreement metadata
│   └── agr_xxx.txt             # Terms text
├── arbitrations/
│   └── arb_xxx.json            # Arbitration record
├── rulings/
│   └── rul_xxx.json            # Ruling record
├── witnesses/
│   └── witness_xxx.json        # Witness anchors
├── local_xxx.json              # ToS captures
├── promise_xxx.json            # Promise captures
└── custom-rules.json           # Custom rulesets
```

## Agent Instructions

### Before Accepting Any Agreement

1. **Review the termsHash** - Ensure you're signing what you expect
2. **Verify the arbiter** - Must be mutually trusted
3. **Check the deadline** - Ensure it's achievable
4. **Run capture** on any ToS you encounter:
   ```bash
   node capture.js capture "TERMS" "URL" "MERCHANT"
   ```

### Before Making Commitments

1. **Use propose** for formal commitments:
   ```bash
   node capture.js propose "I will deliver X by Y" "AgentZ" --arbiter="trusted-arbiter"
   ```
2. **Wait for acceptance** before acting
3. **Document fulfillment** with evidence

### During Arbitration

1. **Submit all relevant evidence** before deadline
2. **Use appropriate evidence types** (document, screenshot, witness)
3. **Reference specific termsHash** in submissions

## Environment Variables

```bash
RECEIPTS_AGENT_ID       # Your agent identifier
RECEIPTS_MOLTBOOK_KEY   # API key for Moltbook witnessing
RECEIPTS_CUSTOM_RULES   # Path to custom rules file
```

## Framework Integration

```javascript
const receipts = require('./capture.js');

// Generate terms hash for verification
const hash = receipts.generateTermsHash(
  "I will deliver API docs",
  ["agent-a", "agent-b"],
  "2026-02-14"
);

// Sign terms
const signature = receipts.signTerms(hash, "my-agent-id");

// Verify signature
const valid = receipts.verifySignature(hash, signature, "my-agent-id");

// Access directories
console.log(receipts.PROPOSALS_DIR);
console.log(receipts.AGREEMENTS_DIR);
console.log(receipts.ARBITRATIONS_DIR);
console.log(receipts.RULINGS_DIR);
```

## 

…(truncated)
