> **Status:** Published
> **Date:** 2026-09-17
> **Scope**: API Reference
> **Standard**: Memorio API Specification v5
>
---
# Temporal Memory - Time-Travel for State

> ✅ **Universal**: Works in Browser, Node.js, Deno, and Edge Workers

Memorio's temporal engine provides immutable, point-in-time query, diffing, and branching over state mutations. Unlike the undo/redo system (which is linear and single-step), the temporal engine maintains a full log of every mutation with causal ordering via Hybrid Logical Clocks (HLC), enabling sophisticated time-travel queries.

Temporal tracking is **enabled by default** and independent from `historyEnabled` (undo/redo). The temporal log is stored separately and indexed by path for efficient lookups.

---

## Quick Start

```javascript
import { state, memorio } from 'memorio'

// Temporal tracking is on by default
state.counter = 1
state.counter = 2
state.counter = 3

// Query the value at a point in time
const history = memorio.temporal.history('counter')
const ts = history[0].hlc

console.log(memorio.temporal.at('counter', ts))  // 1
console.log(memorio.temporal.at('counter', Date.now())) // 3

// Diff between two points in time
const hlc2 = history[1].hlc
const changes = memorio.temporal.diff('counter', hlc2, Date.now())
console.debug(changes)
// [{ path: 'counter', before: 2, after: 3, operation: 'set', hlc: 'hlc:...', timestamp: ... }]
```

---

## Core Concepts

### Hybrid Logical Clock (HLC) Timestamps

Every mutation is stamped with an HLC timestamp, which combines:
- **Physical time** (milliseconds since epoch) - coarse ordering across devices
- **Logical counter** - disambiguates mutations within the same millisecond on the same node
- **Node ID** - stable per origin, ensures total causal ordering

This means multiple mutations that happen within the same millisecond are still uniquely and correctly ordered. When passing timestamps to temporal queries:
- **HLC strings** (`"hlc:1725...:0:abc123"`) are parsed and compared using physical + logical for precise per-mutation resolution
- **Numeric timestamps** (epoch ms) are treated as "include all mutations up to and including this physical millisecond"

```javascript
// HLC string: precise to the individual mutation
memorio.temporal.at('counter', 'hlc:1725123456789:0:abc123')

// Numeric: includes all mutations at this physical time
memorio.temporal.at('counter', 1725123456789)
```

### Path Indexing

Mutations are indexed by dotted path (e.g. `user.name`). The `history()`, `at()`, `diff()`, and `explain()` methods accept path queries:
- **Exact path** (`'user.name'`): returns mutations to that exact path
- **Parent path** (`'user'`): returns mutations to `user` and any sub-paths (`user.name`, `user.role`, etc.)
- **No path** (`history()`): returns all mutations

### Immutable Snapshots

All temporal queries return **deep clones** of the historical state. Modifying the returned value does **not** affect live state.

---

## API

### `memorio.temporal.history(path?)`

Returns all mutations matching the path, sorted chronologically by HLC.

```javascript
state.user = { name: 'Alice' }
state.user.name = 'Bob'
state.counter = 1

memorio.temporal.history()           // all mutations
memorio.temporal.history('user.name')  // mutations to user.name (2)
memorio.temporal.history('user')       // mutations to user and sub-paths (2)
memorio.temporal.history('counter')    // mutations to counter (1)
```

Each entry is a `Mutation` record with `id`, `path`, `operation`, `before`, `after`, `timestamp`, `hlc`, and optional `source`/`context`/`transactionId`.

### `memorio.temporal.at(path, timestamp)`

Returns the value at a path at a specific point in time. Never mutates live state.

```javascript
state.counter = 1
state.counter = 2

const mutations = memorio.temporal.history('counter')
const hlc1 = mutations[0].hlc

console.log(memorio.temporal.at('counter', hlc1))  // 1
console.log(memorio.temporal.at('counter', Date.now())) // 2

// Works with HLC strings for precise queries
console.log(memorio.temporal.at('counter', mutations[1].hlc)) // 2

// Returns undefined if no mutation existed at that time
console.log(memorio.temporal.at('counter', mutations[0].timestamp - 1)) // undefined
```

### `memorio.temporal.diff(path, from, to)`

Returns the individual mutation changes that occurred within a time range.

```javascript
state.counter = 1
const hlc1 = memorio.temporal.history('counter')[0].hlc

state.counter = 2
state.counter = 3

const diffs = memorio.temporal.diff('counter', hlc1, Date.now())
// [
//   { path: 'counter', before: 1, after: 2, operation: 'set', ... },
//   { path: 'counter', before: 2, after: 3, operation: 'set', ... }
// ]
```

The `from` timestamp is exclusive; the `to` timestamp is inclusive. Both accept HLC strings or epoch ms numbers.

### `memorio.temporal.replay(options)`

Reconstructs the full state tree from the temporal log, optionally limited to a time range.

```javascript
state.user = { name: 'Alice' }
state.user.name = 'Bob'
state.counter = 42

state.user.name = 'Charlie'

const replayed = memorio.temporal.replay()
// { user: { name: 'Charlie' }, counter: 42 }

// Time-range replay
const mutations = memorio.temporal.history('counter')
const hlc1 = mutations[0].hlc
const hlc2 = mutations[1].hlc
memorio.temporal.replay({ from: hlc1, to: hlc2 })  // state at the second counter mutation
```

### `memorio.temporal.explain(path)`

Returns provenance metadata for how a value at a path came to exist.

```javascript
state.user = { role: 'user' }
state.user.role = 'admin'

const explanation = memorio.temporal.explain('user.role')
// {
//   path: 'user.role',
//   currentValue: 'admin',
//   previousValue: 'user',         // value before the last mutation
//   history: [ /* mutations affecting this path */ ],
//   createdAt: 'hlc:...',           // when the path was first set
//   lastChangedAt: 'hlc:...',       // when the path was last modified
//   source: undefined,              // optional source attribution
//   ...
// }
```

### `memorio.temporal.branch()`

Creates an isolated temporal branch. Mutations to the branch's state do **not** affect live state or the main temporal log.

```javascript
state.user = { role: 'user' }
state.counter = 1

const branch = memorio.temporal.branch()

// Branch state starts from a snapshot of live state
console.log(branch.state.user.role) // 'user'
console.log(branch.state.counter)    // 1

// Mutations to branch state are isolated
branch.state.user.role = 'admin'
branch.state.counter = 99

console.log(state.user.role) // 'user' (unchanged)
console.log(state.counter)    // 1 (unchanged)

// Branch has its own temporal history
const branchHistory = branch.temporal.history('counter')
console.log(branchHistory.length) // 4 (3 from main + 1 from branch)

// Clean up
branch.discard()  // or branch.commit() to merge
```

### `memorio.temporal.enable(enabled?)` / `memorio.temporal.isEnabled()`

Enable or disable temporal tracking.

```javascript
memorio.temporal.enable(false)  // stop recording
state.x = 1
memorio.temporal.history('x')  // [] - no new mutations recorded

memorio.temporal.enable(true)   // resume
state.x = 2
memorio.temporal.history('x')  // [mutation for x=2]
```

### `memorio.temporal.configure(config)`

Configure temporal engine settings.

```javascript
memorio.temporal.configure({
  maxEntries: 50000,   // max mutations retained in the log (default: 10000)
  snapshots: false,     // reserved for future snapshot checkpointing
  snapshotInterval: 100 // reserved for future snapshot checkpointing
})
```

### `memorio.temporal.stats()`

Returns statistics about the temporal log.

```javascript
console.log(memorio.temporal.stats())
// {
//   total: 42,           // total mutations in the log
//   byPath: {            // mutation count per path
//     'user.name': 3,
//     'counter': 5,
//     ...
//   }
// }
```

### `memorio.temporal.size()`

Returns the total number of mutations in the temporal log.

### `memorio.temporal.clear()`

Clears the entire temporal log. Does **not** affect live state.

```javascript
memorio.temporal.clear()
memorio.temporal.size() // 0
```

---

## Temporal vs. History (Undo/Redo)

| Feature | Temporal (`temporal`) | History (`enableHistory`/`undo`/`trace`) |
|---|---|---|
| **Enabled by default** | Yes | No |
| **Log** | Full, immutable, indexed by path | Undo/redo stacks + trace |
| **Timestamps** | HLC (physical + logical + node) | Epoch ms |
| **Time-travel** | Point-in-time queries (`at`, `diff`, `replay`) | Linear undo/redo only |
| **Branching** | Yes (`branch()`) | No |
| **Provenance** | `explain()` | No |
| **Memory limit** | `maxEntries` (default: 10000) | `maxHistory` (default: 100) |
| **Mutations** | Deep-cloned snapshots | References to live values |

Both systems record mutations independently. Enabling one does not enable the other.

---

## How It Works

1. When `state` is mutated, the proxy callback in `buildProxy` fires, creating a `Mutation` via `createMutation()`.
2. `createMutation()` assigns an HLC timestamp (`physical`, `logical`, `node`) and deep-clones the `after`/`before` values to ensure immutability.
3. The mutation is recorded into `internal.temporalLog` (shared via `globalThis` for ESM/CJS deduplication).
4. Queries like `at()`, `diff()`, `replay()`, and `explain()` reconstruct historical state by replaying mutations up to the requested timestamp using the combined HLC sort key (physical * 1e9 + logical).
5. Branch engines use their own local log arrays and isolated state proxies.

---

## Best Practices

1. **Use HLC strings for precise queries**: When you need to query the exact state after a specific mutation, use the mutation's `hlc` string. Numeric timestamps include all mutations at the same physical millisecond.
2. **Don't trust temporal log for security**: The temporal log is inspectable and can be cleared. It's a debugging and time-travel tool, not an audit trail.
3. **Branches are isolated**: Mutations in a branch do not affect the main log. Use `commit()` to persist changes (when implemented) or `discard()` to clean up.
4. **Clear when done**: For long-running apps, `memorio.temporal.clear()` frees memory. The log is capped at `maxEntries` by default, but clearing is faster.
