automorph 0.2.0

Derive macros for bidirectional Automerge-Rust struct synchronization
Documentation
# Automorph Examples

This directory contains standalone examples demonstrating various Automorph features. Each example is a self-contained learning tool that focuses on specific concepts.

## Examples vs Demo

| | Examples | [Demo]../demo/README.md |
|---|----------|------|
| **Purpose** | Learn individual features | See a complete application |
| **Size** | Single-file, focused | Multi-file, full architecture |
| **Complexity** | Beginner-friendly | Production-ready patterns |
| **UI** | Terminal output | Web interface (Yew/WASM) |
| **Best for** | Understanding concepts | Reference implementation |

**Start with the examples** to learn Automorph concepts, then study the **demo** to see how they combine in a real application.

---

## Example Catalog

### 1. `collaborative.rs` - Core Automorph Patterns

**What it demonstrates:**
- `Tracked<T>` wrapper for efficient change detection
- Version history with `load_at()` and `diff_versions()`
- Internally tagged enums (`#[automorph(tag = "type")]`)
- HashMap with custom struct values
- Hierarchical `ChangeReport` inspection

**Key concepts:**
```rust
// Tracked wrapper - remembers document location
let tracked = Tracked::<Document>::load(&doc, &ROOT, "doc")?;

// Version history - time travel
let old = Document::load_at(&doc, &ROOT, "doc", &checkpoint)?;

// Change detection
let changes = document.diff_versions(&doc, &ROOT, "doc", &v1, &v2)?;
```

**Run:**
```bash
cargo run --example collaborative
```

---

### 2. `crdt_collaboration.rs` - CRDT vs LWW Semantics

**What it demonstrates:**
- `Counter` CRDT for concurrent-safe numeric operations
- `Text` CRDT for character-level collaborative editing
- The difference between CRDT types and regular Rust types
- Concurrent editing simulation with document forking

**Key concepts:**
```rust
// Counter: concurrent increments merge correctly
post.likes.increment(5);  // User A
post.likes.increment(3);  // User B (concurrent)
// After merge: likes = 8 (both preserved!)

// Text: character-level merging
content.insert(5, "hello");  // User A at position 5
content.push_str("!");       // User B at end
// After merge: both insertions preserved
```

**When to use CRDT types:**
- `Counter` - view counts, likes, inventory quantities
- `Text` - document content, comments, notes

**Run:**
```bash
cargo run --example crdt_collaboration
```

---

### 3. `persistence.rs` - File Storage Patterns

**What it demonstrates:**
- Saving Automerge documents to files
- Loading documents from disk
- Incremental saves (append changes only)
- Backup and restore workflows
- Error handling for file operations

**Key concepts:**
```rust
// Save entire document
doc.save_to_file("data.automerge")?;

// Incremental save (only new changes)
doc.save_incremental_to_file("data.automerge")?;

// Load from file
let doc = AutoCommit::load_from_file("data.automerge")?;
```

**Run:**
```bash
cargo run --example persistence
```

---

### 4. `workspace.rs` - Nested Struct Patterns

**What it demonstrates:**
- Multiple related types in one document (TodoState + ChatState)
- Nested structs with individual change tracking
- Combining different data models in a shared document
- Property-level update detection

**Key concepts:**
```rust
#[derive(Automorph)]
struct Workspace {
    todos: TodoState,    // Nested struct
    chat: ChatState,     // Another nested struct
}

// Each nested struct has its own change tracking
let changes = workspace.update(&doc, &ROOT, "workspace")?;
if changes.todos.any() { /* todo changes */ }
if changes.chat.any() { /* chat changes */ }
```

**Run:**
```bash
cargo run --example workspace
```

---

### 5. `sync_tcp.rs` - TCP Sync Protocol

**What it demonstrates:**
- Bidirectional sync over TCP sockets
- Automerge's sync protocol (`SyncState`, `generate_sync_message`, `receive_sync_message`)
- Running sync in a loop until documents converge
- Two-terminal interactive demonstration

**Key concepts:**
```rust
// Generate sync message
if let Some(msg) = doc.sync().generate_sync_message(&mut sync_state) {
    socket.write_all(&msg)?;
}

// Receive sync message
let msg = read_message(&mut socket)?;
doc.sync().receive_sync_message(&mut sync_state, msg)?;
```

**Run (requires two terminals):**
```bash
# Terminal 1 (server)
cargo run --example sync_tcp -- server

# Terminal 2 (client)
cargo run --example sync_tcp -- client
```

---

### 6. `sync_websocket.rs` - WebSocket Sync Pattern

**What it demonstrates:**
- Sync protocol adapted for WebSocket transport
- Message framing for web environments
- Pattern for browser-to-server synchronization

**Note:** This is pseudocode/pattern demonstration. For a working WebSocket implementation, see the [demo](../demo/README.md).

**Run:**
```bash
cargo run --example sync_websocket
```

---

### 7. `notes_tutorial.rs` - Complete CLI Application

**What it demonstrates:**
- Full command-line notes application
- Peer-to-peer sync between instances
- Persistence (save/load notes to disk)
- CRDT text editing for note content
- ID-based note management

**Key concepts:**
```rust
#[derive(Automorph)]
struct NotesApp {
    notes: HashMap<String, Note>,  // ID -> Note mapping
}

#[derive(Automorph)]
struct Note {
    title: String,
    content: Text,  // CRDT for collaborative editing
    created_at: u64,
}
```

**Run:**
```bash
# Start first instance
cargo run --example notes_tutorial

# In another terminal, start second instance and sync
cargo run --example notes_tutorial -- --peer localhost:8080
```

---

## Full Web Application Demo

For a complete **Yew web application** with all the patterns above combined, see the [demo](../demo/README.md):

- Complete WASM-based UI with TodoList and ChatRoom
- HTTP-based sync between multiple browser tabs
- Performance benchmarking (value-based vs Tracked<T> diffing)
- Docker Compose setup for multi-container testing

---

## Running All Examples

To verify all examples compile:
```bash
cargo build --examples
```

To run a specific example with verbose output:
```bash
RUST_LOG=debug cargo run --example <name>
```

---

## Learning Path

**Recommended order for learning Automorph:**

1. **`collaborative.rs`** - Core patterns (Tracked, versioning, change detection)
2. **`crdt_collaboration.rs`** - When and how to use CRDT types
3. **`workspace.rs`** - Organizing complex state with nested structs
4. **`persistence.rs`** - Saving and loading documents
5. **`sync_tcp.rs`** - Understanding the sync protocol
6. **`notes_tutorial.rs`** - Putting it all together

After completing the examples, study the [demo](../demo/README.md) for production patterns.