# Wire Protocol v3

> Canonical RFC-8259 JSON data model, lossless 64-bit integer safe-integer boundaries, out-of-order hydration, and StatePatch synchronization.

> Machine-readable artifacts published with this site: [`wire.schema.json`](/spec/v3/wire.schema.json) · [`conformance.json`](/spec/v3/conformance.json)

This document is the language-neutral specification shared by the official **TypeScript (`@zwire/core/protocol`)** and **Rust (`zwire-protocol`)** implementations of **zwire**. Both runtimes validate exact wire and behavioral parity against [`conformance.json`](https://github.com/kjmin-dev/zwire/blob/main/spec/conformance.json) and [`wire.schema.json`](https://github.com/kjmin-dev/zwire/blob/main/spec/wire.schema.json).

---

## 1. Design Goals

1. **Zero external codec dependencies:** Every message is strict RFC-8259 JSON with no binary framing requirements, enabling direct interop across browsers, Node.js, Bun, Rust servers, Tauri, WebSockets, SSE, and edge workers.
2. **Deterministic canonical output:** Object keys MUST be serialized in lexicographical UTF-8 / code-unit order (`BTreeMap` in Rust; sorted keys in JS when canonical comparison is required) so identical logical states produce byte-identical JSON.
3. **Lossless 64-bit integer transfer across JS IEEE-754 & Rust:** JavaScript `Number` loses integer precision outside `[-9007199254740991, 9007199254740991]` (`±(2^53 - 1)`). Signed (`i64`) and unsigned (`u64`) integers outside that range are encoded as base-10 decimal strings.
4. **Optimistic-safe synchronization:** Remote hydration and sync patches update the **committed base value** of keyed signals; active optimistic layers (`@zwire/core/tx`, `zwire-tx`) automatically rebase on top without losing local in-flight intents.

---

## 2. JSON Data Model & 64-Bit Integer Encoding

All wire values belong to the RFC-8259 JSON value set: `null`, `boolean`, `number`, `string`, `array`, `object`.

### 2.1 Safe-Integer Boundary Rules

| Rust Type | Value Range | Encoded JSON Representation | Decoding Rules |
| :--- | :--- | :--- | :--- |
| `i64` | `-9007199254740991 ..= 9007199254740991` | JSON number (e.g. `42`, `-9007199254740991`) | Accepts JSON integer, exact integral float in range, or decimal string in `i64` range |
| `i64` | `< -9007199254740991` or `> 9007199254740991` | Decimal JSON string (e.g. `"9007199254740992"`, `"-9223372036854775808"`) | JavaScript consumers pass directly to `BigInt(value)` |
| `u64` | `0 ..= 9007199254740991` | JSON number (e.g. `9007199254740991`) | Accepts non-negative JSON integer, exact integral float in range, or decimal string in `u64` range |
| `u64` | `> 9007199254740991` | Decimal JSON string (e.g. `"9007199254740992"`, `"18446744073709551615"`) | JavaScript consumers pass directly to `BigInt(value)` |
| `f64` | Finite IEEE-754 floats | JSON number | Non-finite values (`NaN`, `±Infinity`) MUST NOT be emitted as raw JSON tokens |

### 2.2 String & Key Safety

- Strings use standard RFC-8259 escaping (`\"`, `\\`, `\n`, `\r`, `\t`, `\b`, `\f`, `\uXXXX`) and preserve valid Unicode characters verbatim (e.g. `"한글/Ω"`).
- Implementations MUST treat object keys as plain data keys (`__proto__`, `constructor`, `prototype` MUST NOT trigger prototype pollution in JavaScript).

---

## 3. Out-of-Order Hydration (`HydratedState`)

A `HydratedState` payload is a JSON object mapping string keys to committed wire values:

```json
{
  "count": 42,
  "enabled": true,
  "user": "Ada"
}
```

### Semantics

1. **Committed base snapshot (`dehydrate`):** `dehydrate(scope)` snapshots ONLY the **committed base value** of every keyed signal registered in `scope`, ignoring active optimistic overlays (`tx` layers) and speculative drafts.
2. **Atomic batched apply (`hydrate`):** `hydrate(scope, state)` applies all entries in a single reactive batch while suppressing local `SyncBridge` outbound echo.
3. **Out-of-order delete-on-consume buffer:**
   - If `hydrate()` receives a key that has not yet been registered in `scope`, the value is stored in the scope's hydration buffer.
   - When a lazily loaded route or module subsequently calls `hydratable(key, initial)`, it immediately consumes the buffered value (deleting it from the buffer) instead of `initial`.
   - If a key is already registered when `hydrate()` runs, its committed base value is updated directly and any stale buffered entry for that key is cleared.

---

## 4. Incremental State Synchronization (`StatePatch`)

`SyncBridge` exchanges batches of `StatePatch` objects encoded as a JSON array:

```json
[
  { "key": "count", "origin": "remote", "txId": "srv_1", "value": 99 },
  { "key": "user", "origin": "remote", "txId": "srv_1", "value": "Grace" }
]
```

### Fields

| Field | Type | Required | Description |
| :--- | :--- | :---: | :--- |
| `key` | `string` | Yes | Logical signal key registered in the scope or explicit bridge map |
| `value` | JSON value | Yes | Committed base value for `key` |
| `origin` | `"local" \| "remote"` | Yes | Direction of the patch relative to the emitting peer |
| `txId` | `string` | Yes | Unique transaction identifier for batch correlation and echo suppression |

### Behavioral Invariants

1. **Coalesced per-batch outbound emission:** Multiple local writes to the same key within one `batch()` coalesce into a single `StatePatch` containing the latest committed value, flushed once at batch completion via the scope's flush hook.
2. **Echo suppression:** Every outbound batch records its `txId` in a bounded ring buffer (at least 64 recent IDs). Incoming patches whose `txId` matches a recently sent local `txId` MUST be ignored to prevent infinite sync loops. In bidirectional deployments, each peer MUST namespace its `txId` generator (e.g. `srv_<seq>`, `cli_<seq>`, or UUIDs) to prevent accidental ID collisions across peers.
3. **Remote rebase:** Applying a remote patch writes to the signal's committed base value, automatically rebasing any active optimistic layers (`OptimisticLayer`) in creation order.
4. **Unregistered remote keys:** Remote patches targeting keys not yet registered in the scope are buffered in the scope's hydration buffer so lazily initialized signals observe the latest remote state upon registration.
5. **Inbound replay window:** A delivery contains complete transactions. All patches carrying a fresh ID within that delivery apply in wire order. Record its distinct incoming IDs in first-seen order, retaining the latest 64 independently of outbound IDs. A later delivery bearing a remembered ID is ignored, even if the value has changed since the original delivery. `origin` is relative to the sender and does not identify an echo. Senders must use a new ID for every independent transaction and reuse the original ID and contents on retry.
6. **Push failures:** A rejected asynchronous push reports its error and original batch through the TypeScript bridge's `onPushError`, falling back to the scope inspector. The bridge performs one push per batch. Adapters that support retry preserve FIFO order and retry the same transaction IDs and payloads. A successful WebSocket send means the socket accepted the frame. End-to-end delivery guarantees require a transport-level acknowledgement. Acknowledgement and replay beyond the bounded history are application concerns.

---

## 5. Conformance Verification

Any change to:
- Optimistic layer rebasing, surgical rollback, or atomic `settle` rollback,
- STM `Draft` (`committed` vs `effective` reads and read-set conflict detection),
- Deterministic collection ordering, tie-breaking, filtered range windows, and Top-K boundary pruning,
- Inbound replay, outbound echo suppression, and stable transaction IDs across retries, or
- Wire JSON formatting (`HydratedState`, `StatePatch`, `i64`/`u64` boundaries, escaping)

MUST update [`conformance.json`](https://github.com/kjmin-dev/zwire/blob/main/spec/conformance.json), synchronize the packaged Rust test copy via `mise run sync:spec`, and pass both the TypeScript (`ts/tests/conformance.test.ts`) and Rust (`rust/crates/zwire/tests/conformance.rs`) conformance suites.
