# Architecture Specification

> 3-layer star topology, five zero-cost lazy core extension slots, TypeScript and Rust invariants, and tsrs/tsc compiler pipeline.

This document specifies the **3-Layer Star-Topology Architecture** implemented identically across the **TypeScript (`@zwire/*`)** and **Rust (`zwire*`)** workspaces of `zwire`.

---

## 1. Design Principles

1. **Zero Module-Level Mutable State:** Every reactive graph runs inside an isolated scope (`ReactiveScope` in TypeScript; `Scope` / `SyncScope` in Rust). `defaultScope` provides zero-ceremony client ergonomics in TS, while `createScope({ mode: 'ssr' })` / `Scope::ssr()` isolates concurrent SSR/Edge requests with silent watcher registration.
2. **GC-Safe Unwatched Computeds Without `O(V+E)` Cliffs:** Unwatched derived nodes track dependencies using **forward-only links** (`comp._deps -> dep`, never inserted into `dep._subs`). In JS, abandoned computeds are immediately eligible for GC (`64/64` `WeakRef` collection); in Rust, generational arena handles cleanly detect disposal (`CoreError::Disposed`). A single-root version fast-path keeps repeated unwatched reads at `O(1)`, while subscribing promotes forward links into bidirectional `dep._subs` links and unsubscribing cascades `unlinkSub` back upstream.
3. **Zero-Try Happy-Path Flushing & Engine Monomorphism:**
   - **TypeScript (`ts/packages/core/src/core/`):** All core nodes share an identical prefix layout (`BaseNode`) initialized in fixed order with `declare` fields (zero ES2022 `[[DefineOwnProperty]]` overhead). `flushScope()` executes `_drain()` with zero `try/catch` inside the hot loop, falling back to `_drainErr()` only when an exception occurs so sibling subscribers drain cleanly without poisoning the queue.
   - **Rust (`rust/crates/zwire-core/`):** Generational arena `Scope` with `Copy` handles, zero-`Clone` closure reads (`with`, `get_rc`), RAII `Subscription` / `HookGuard` drops, panic-safe flush unwinding, and deadlock-free `SyncScope` releasing `MutexGuard` before every user callback.
4. **Strict 2-Tier Star Topology (0B Extension Overhead in Core):**
   - Core (`ts/packages/core/src/core/*`, `rust/crates/zwire-core/*`) never imports any companion subpath, adapter, or crate.
   - Companion subpaths and crates never import each other; cross-feature composition (`ObjectStore.field(k)` + `OptimisticLayer`, `focus()` + `Draft`, `Collection.topK(k)` + `batch()`, `SyncBridge` + `OptimisticLayer`) occurs solely through 5 lazy extension slots (`ts/packages/core/src/core/internal.ts`, `zwire_core::internal`).
   - UI framework adapters live in `ts/packages/adapters/{react,vue,solid,svelte}/` and depend only on published `@zwire/core` entry points. An adapter's root entry imports `@zwire/core` alone; an adapter subpath `@zwire/<fw>/<x>` may additionally import its mirror `@zwire/core/<x>` and nothing else from core. Adapters never import `core/internal.ts`, another core subpath, or another adapter, which keeps `@zwire/core` free of UI framework peer dependencies, compiler constraints, and version coupling ([ADR-002](/architecture/adr-002/)).

---

## 2. Layer Boundaries & Cross-Language Module Map

```mermaid
flowchart TB
    SPEC["spec/ (protocol.md · wire.schema.json · conformance.json)"]

    subgraph BRG["Optional Bridges (Dependency-Bearing)"]
        WASM["bridges/wasm (zwire-wasm: wasm-bindgen scope transport)"]
        SERDE["bridges/serde (zwire-serde: no_std serde WireValue/StatePatch bridge)"]
    end

    subgraph L2["Layer 2: Open Protocols & Specialized Engines"]
        PROTO["@zwire/core/protocol  <->  zwire-protocol (Hydration, ExternalSource, SyncBridge, Inspector)"]
        COL["@zwire/core/collections  <->  zwire-collections + zwire::{ReactiveCollection, PureReactiveCollection, SyncReactiveCollection, SyncPureReactiveCollection} (Collection · KeyedCollection)"]
    end

    subgraph L1_UI["Layer 1b: TS Framework Adapter Packages (peerDep: @zwire/core)"]
        RCT["@zwire/react (React 18/19 Compiler-Safe Hooks + SelectorStabilizer)"]
        VUE["@zwire/vue (Vue 3.5+ Read-Through customRef + v-model Atoms)"]
        SLD["@zwire/solid (Solid 2 Accessors + Owner-Scoped Subscriptions)"]
        SVT["@zwire/svelte (Svelte 5.7+ createSubscriber Refs + Store Contract)"]
    end

    subgraph L1["Layer 1a: Opt-In Tree-Shakeable Extensions (0B in Core)"]
        TX["@zwire/core/tx  <->  zwire-tx (OptimisticLayer, runOptimistic/OptimisticGuard, STM Draft)"]
        STR["@zwire/core/store  <->  zwire::store + #[derive(ReactiveStore)] (ObjectStore, DeepStore, createSelector, createProjection, reconcile · MapStore, projection)"]
        OPT["@zwire/core/optics  <->  zwire::optics (TS: createAtomMap, focus/lens · Rust: Lens)"]
        RES["@zwire/core/resource  <->  zwire::resource (TS: lazy resource, isPending, resolve · Rust: no_std Resource<T, E>)"]
        DEV["@zwire/core/devtools (TS: WeakRef createInspectableScope + inspectGraph)"]
    end

    subgraph L0["Layer 0: Core Engine"]
        CORE["@zwire/core  <->  zwire-core (Scoped Push-Pull · Split Effect · Optional Microtask Scheduler · Lexical Owner · NotReady · Disposal · 5 Lazy Slots · SyncScope)"]
    end

    SPEC -.-> PROTO & COL & TX
    BRG --> PROTO
    L2 --> CORE
    L1 --> CORE
    L1_UI --> CORE
```

---

## 3. Five Zero-Cost Core Extension Slots

Both `ts/packages/core/src/core/scope.ts` and `rust/crates/zwire-core/src/internal.rs` implement the same 5 lazy slots:

| Slot | Location | Initial Value | Consumers | Hot-Path Cost |
| :--- | :--- | :--- | :--- | :--- |
| **`_ext`** | Atom node | `undefined` / `None` | `tx` (OptimisticLayer intent folding), TS `store` (`field` CoW sync) | 1 null/option check in `set()` |
| **`_draft`** | Scope | `undefined` / `None` | `tx` (`Draft` CoW overlay & STM read-set tracking) | 1 null/option check in `get()`/`set()` |
| **`_flushHooks`** | Scope | `undefined` / empty | `collections` (1x/batch `topK` materialization), `protocol` (`SyncBridge` batch push) | 1 check in drain |
| **`_keyed` / `_hydrated`** | Scope | `undefined` / empty | `protocol` (out-of-order hydration w/ delete-on-consume + `SyncBridge`) | Only touched when keyed |
| **`_inst`** | Scope | `undefined` / empty | `protocol` (`attachInspector`), `devtools` (`createInspectableScope`), `tx` (`settle` / `try_settle` atomic rollback undo log) | 1 check; timing skipped when detached |

---

## 4. Key Architectural Invariants

1. **Snapshot Immutability (`@zwire/core/store`):** `createObjectStore` uses `_sh` (`snapshotShared`) lazy Copy-on-Write: `setKey()` mutates in-place ONLY while no caller has observed the current snapshot; once `get()` exposes the snapshot, the next `setKey()` clones once, guaranteeing React 19 `useSyncExternalStore` immutability without eager per-write cloning.
2. **Concurrent-Abort-Safe React 19 Selectors (`@zwire/react`):** `SelectorStabilizer` (`ts/packages/adapters/react/src/stabilizer.ts`) separates uncommitted render-phase memoization from committed subscription state (synced strictly inside `useInsertionEffect`). An aborted concurrent render can never corrupt `shouldNotify()`.
3. **Zero-Flicker Atomic `settle()` / `try_settle()` (`tx`):** Snapshots committed values/versions of touched atoms, intercepts any writes inside the settle closure via `_inst`, strips the layer inside `batch()`, and restores every base atom atomically if the settle callback throws/returns `Err`/panics.
4. **External Pull Bitflag (`F_EXTERNAL`):** Propagates bitwise during dependency linking so unwatched computeds reading `fromExternalSource()` or `col.topK(k)` always observe fresh external snapshots.
5. **Deterministic Total-Order Collection Index (`collections`):** Wraps user `compare(a, b)` with deterministic key tie-breaking over a 2-level Chunked Sorted Block Index (`BLOCK_TARGET = 128`, split `> 256`, merge `< 32`), paired with `O(1)` Top-K boundary checks; Rust also provides `KeyedCollection` (`BTreeSet<(S, K, u32)>`), `PureReactiveCollection`, and thread-safe `SyncReactiveCollection` / `SyncPureReactiveCollection`. The thread-safe pair mutates its index under an `RwLock` and, after releasing it, publishes each Top-K view and range revision as an immutable versioned snapshot through `zwire_core::internal::sync_publish_external_versioned`: `SyncScope` compares the version, checks for subscribers, and writes in one critical section, so racing writers, unwatched pull-on-read refreshes, and new subscribers can never regress a signal or miss a committed write.
6. **Read-Through UI Framework Adapters (`@zwire/{vue,solid,svelte}`):** Each adapter holds only a notification primitive in the host framework and reads values directly from `signal.get()`, never copying or deeply proxying snapshots, and releasing listeners with the host component's ownership scope.
7. **Re-entrancy & Deadlock Freedom (Rust):** Every `RefCell` borrow and `MutexGuard` is dropped before invoking user callbacks; scope-owned closures store `WeakScope` / `WeakSyncScope` (never strong clones) to guarantee zero `Rc`/`Arc` cycles.

---

## 5. Shared Cross-Language Spec & Parity

- [`spec/protocol.md`](/protocol/specification/) and [`spec/wire.schema.json`](/spec/v3/wire.schema.json) define the canonical RFC-8259 wire representation (including lossless `i64`/`u64` safe-integer string encoding above `±(2^53 - 1)`).
- [`spec/conformance.json`](/spec/v3/conformance.json) validates identical optimistic rebase, STM draft, Top-K ordering/pruning, and JSON wire round-trips across TypeScript (`ts/tests/conformance.test.ts`) and Rust (`rust/crates/zwire/tests/conformance.rs`), synchronized via `scripts/sync-spec.ts`.
- [`examples/rust-ts-sync/`](/examples/rust-ts-sync/) verifies live cross-process Rust ↔ TypeScript sync in CI.

---

## 6. TypeScript Compiler Pipeline (`tsrs` + `tsc` Parity & `.d.ts` Rewrite)

- Source files use explicit `.ts` relative specifiers for native TypeScript execution on Node 26+ and Bun 1.3+, with `"rewriteRelativeImportExtensions": true` and `"isolatedDeclarations": true`.
- Because both `tsrs@7.1.0-beta.tsrs9` and stock `tsc` preserve `.ts` specifiers in emitted `.d.ts` files, `ts/scripts/build.ts` runs `ts/scripts/rewrite-dts-extensions.ts` immediately after `tsrs` emit.
- `ts/scripts/verify-dist.ts` continuously enforces producer parity (`tsc --emitDeclarationOnly` matching `tsrs` file sets and exported symbol surfaces across all 5 packages) and consumer parity (`NodeNext` + `Bundler` typechecks under both `tsrs` and `tsc` for both a `@zwire/core`-only consumer and a full adapter consumer).
