> **Status:** Published
> **Date:** 2026-09-12
> **Scope**: API Reference
> **Standard**: Memorio API Specification v5
>
---
# History, Undo / Redo, Snapshot, Diff, Trace - Memorio

> ✅ **Universal**: Works in Browser, Node.js, Deno, and Edge Workers

Memorio provides a lightweight time-travel system for `state` mutations: snapshots, diffs, undo/redo, and a full mutation trace log.

History tracking is **opt-in** - it is disabled by default to avoid overhead. Enable it when you need undo/redo or trace capabilities.

---

## Enable History

```javascript
import { memorio, state } from 'memorio'

memorio.enableHistory()    // enable tracking
// ... mutate state ...
state.user = { name: 'Sara' }
state.counter = 42
```

> Without `enableHistory()`, mutations are not recorded and `undo()`/`redo()`/`trace()` return empty results.

---

## Snapshot & Diff

Snapshot captures the entire `state` tree at a point in time. Diff compares a snapshot against current state to see what changed.

```javascript
// Enable history (snapshots work regardless, but trace/undo need it)
memorio.enableHistory()

// Take a snapshot
state.user = { name: 'Sara', age: 30 }
const snap = memorio.snapshot()

// Make changes
state.user.name = 'Luigi'
state.counter = 100
state.items = ['a', 'b']

// Diff against the snapshot
const changes = memorio.diff(snap)
console.debug(changes)
// [
//   { path: 'user.name', oldValue: 'Sara', newValue: 'Luigi' },
//   { path: 'counter',   oldValue: undefined, newValue: 100 },
//   { path: 'items',     oldValue: undefined, newValue: ['a', 'b'] }
// ]
```

This is essential: take a snapshot, make changes, inspect the diff, and decide whether to commit or rollback.

---

## Undo / Redo

```javascript
state.user = { name: 'Sara' }
state.counter = 100
state.items = ['a', 'b']

memorio.undo()   // removes state.items
memorio.undo()   // counter → undefined
memorio.redo()   // counter → 100 again

memorio.canUndo()  // true
memorio.canRedo()  // true (after above undo + redo cycle)
```

- `undo()`: Restores the previous state by inverting the most recent mutation.
- `redo()`: Re-applies the most recently undone mutation.
- `canUndo()` / `canRedo()`: Check availability before calling.

### Max history depth

```javascript
memorio.setMaxHistory(50)   // keep at most 50 mutations per stack (default: 100)
```

---

## Rollback (full state restore)

Unlike undo (which works one step at a time), `rollback` replaces the entire state from a snapshot:

```javascript
const snap = memorio.snapshot()

state.experiment = { result: 'failed' }
state.counter = 999

// Discard everything and restore to snapshot
memorio.rollback(snap)
// state.experiment is now gone
// state.counter is back to its snapshot value
```

---

## Trace (mutation log)

The trace log records every mutation with timestamp, path, action, and before/after values:

```javascript
memorio.enableHistory()

state.user.name = 'Sara'
state.counter = 1
state.counter = 2

const log = memorio.trace()
console.debug(log)
// [
//   { path: 'user.name', action: 'set', newValue: 'Sara', previousValue: undefined, timestamp: 1725... },
//   { path: 'counter',   action: 'set', newValue: 1,      previousValue: undefined, timestamp: 1725... },
//   { path: 'counter',   action: 'set', newValue: 2,      previousValue: 1,         timestamp: 1725... }
// ]
```

This is useful for:
- **AI debugging**: inspect what changed and when
- **Event sourcing**: export the log and replay state from scratch
- **Audit trails**: log all mutations for compliance

### Export / import trace

```javascript
const log = memorio.trace()
localStorage.setItem('memorio-trace', JSON.stringify(log))

// Later, replay:
const saved = JSON.parse(localStorage.getItem('memorio-trace'))
for (const record of saved) {
  if (record.action === 'set') {
    state[record.path] = record.newValue
  }
}
```

---

## Clear History

```javascript
memorio.clearHistory()   // wipe undo/redo stacks + trace log
memorio.clearRedo()      // clear only the redo stack (undo stack preserved)
```

> `clearHistory()` does NOT reset the current `state` - only the history tracking data.

---

## Full API

| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| `memorio.snapshot()` | none | `Record<string, any>` | Deep clone of current state |
| `memorio.diff(snap)` | `snap` | `DiffEntry[]` | Changed paths with old/new values |
| `memorio.undo()` | none | `MutationRecord \| undefined` | Undo last mutation |
| `memorio.redo()` | none | `MutationRecord \| undefined` | Redo last undone mutation |
| `memorio.canUndo()` | none | `boolean` | Whether undo is available |
| `memorio.canRedo()` | none | `boolean` | Whether redo is available |
| `memorio.rollback(snap)` | `snap` | `void` | Restore full state from snapshot |
| `memorio.trace()` | none | `MutationRecord[]` | List of all recorded mutations |
| `memorio.enableHistory(enabled?)` | `boolean` | `void` | Enable/disable tracking |
| `memorio.clearHistory()` | none | `void` | Clear all history stacks |
| `memorio.clearRedo()` | none | `void` | Clear only redo stack |
| `memorio.setMaxHistory(max)` | `number` | `void` | Set max stack depth |
| `memorio.getMaxHistory()` | none | `number` | Get current max depth |

---

## How It Works

1. When `historyEnabled` is true, the state proxy's callback (`buildProxy` callback) fires on every `set`/`delete` trap, recording a `MutationRecord` with path, action, oldValue, newValue, and timestamp.
2. Records are pushed to both a trace log (`mutations`) and an undo stack.
3. Any new mutation clears the redo stack.
4. `undo()` pops from the undo stack, pushes to the redo stack, and applies the inverse operation (restoring the previous value, or deleting if it was new).
5. `redo()` pops from the redo stack, pushes back to the undo stack, and re-applies the original mutation.
6. During undo/redo, history tracking is temporarily disabled to prevent recursive recording.
7. `diff()` does a recursive key-by-key comparison between the snapshot and current `deepRaw(state)`.

---

## Best Practices

1. **Always snapshot before AI experimentation** - `const snap = memorio.snapshot()` gives you a safe rollback point.
2. **Call `diff()` before `rollback()`** - inspect what changed first; sometimes you only need to revert one key.
3. **Keep `maxHistory` reasonable** - the default (100) is fine for most apps. Lower it for memory-constrained environments.
4. **Don't rely on trace for sensitive data** - the trace log records *all* values written, including tokens/PII. Clear it or disable tracing in production paths.
