@affectively/aeon 1.3.1 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +15 -21
  2. package/README.md +422 -342
  3. package/dist/compression/index.cjs +20 -3
  4. package/dist/compression/index.cjs.map +1 -1
  5. package/dist/compression/index.js +20 -3
  6. package/dist/compression/index.js.map +1 -1
  7. package/dist/crypto/index.cjs +30 -0
  8. package/dist/crypto/index.cjs.map +1 -1
  9. package/dist/crypto/index.js +29 -1
  10. package/dist/crypto/index.js.map +1 -1
  11. package/dist/distributed/index.cjs +15 -8
  12. package/dist/distributed/index.cjs.map +1 -1
  13. package/dist/distributed/index.js +15 -8
  14. package/dist/distributed/index.js.map +1 -1
  15. package/dist/index.cjs +6686 -3118
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.js +6642 -3117
  18. package/dist/index.js.map +1 -1
  19. package/dist/offline/index.cjs.map +1 -1
  20. package/dist/offline/index.js.map +1 -1
  21. package/dist/optimization/index.cjs +6 -3
  22. package/dist/optimization/index.cjs.map +1 -1
  23. package/dist/optimization/index.js +6 -3
  24. package/dist/optimization/index.js.map +1 -1
  25. package/dist/persistence/index.cjs +91 -29
  26. package/dist/persistence/index.cjs.map +1 -1
  27. package/dist/persistence/index.js +91 -29
  28. package/dist/persistence/index.js.map +1 -1
  29. package/dist/presence/index.cjs.map +1 -1
  30. package/dist/presence/index.js.map +1 -1
  31. package/dist/utils/index.cjs.map +1 -1
  32. package/dist/utils/index.js.map +1 -1
  33. package/dist/versioning/index.cjs +4 -3
  34. package/dist/versioning/index.cjs.map +1 -1
  35. package/dist/versioning/index.js +4 -3
  36. package/dist/versioning/index.js.map +1 -1
  37. package/package.json +195 -196
  38. package/dist/compression/index.d.cts +0 -189
  39. package/dist/compression/index.d.ts +0 -189
  40. package/dist/core/index.d.cts +0 -216
  41. package/dist/core/index.d.ts +0 -216
  42. package/dist/crypto/index.d.cts +0 -446
  43. package/dist/crypto/index.d.ts +0 -446
  44. package/dist/distributed/index.d.cts +0 -1016
  45. package/dist/distributed/index.d.ts +0 -1016
  46. package/dist/index.d.cts +0 -57
  47. package/dist/index.d.ts +0 -57
  48. package/dist/offline/index.d.cts +0 -154
  49. package/dist/offline/index.d.ts +0 -154
  50. package/dist/optimization/index.d.cts +0 -347
  51. package/dist/optimization/index.d.ts +0 -347
  52. package/dist/persistence/index.d.cts +0 -63
  53. package/dist/persistence/index.d.ts +0 -63
  54. package/dist/presence/index.d.cts +0 -283
  55. package/dist/presence/index.d.ts +0 -283
  56. package/dist/types-B7CxsoLh.d.cts +0 -33
  57. package/dist/types-B7CxsoLh.d.ts +0 -33
  58. package/dist/utils/index.d.cts +0 -38
  59. package/dist/utils/index.d.ts +0 -38
  60. package/dist/versioning/index.d.cts +0 -537
  61. package/dist/versioning/index.d.ts +0 -537
package/README.md CHANGED
@@ -1,342 +1,422 @@
1
- # Aeon
2
-
3
- > Distributed synchronization, schema versioning, and conflict resolution for real-time collaborative applications.
4
-
5
- [![npm version](https://badge.fury.io/js/@affectively%2Faeon.svg)](https://www.npmjs.com/package/@affectively/aeon)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.6+-blue.svg)](https://www.typescriptlang.org/)
8
-
9
- ## Philosophy
10
-
11
- In Gnosticism, **Aeons** are not just time periods; they are divine beings or powers that emanate from the "One" (the Pleroma). They function as links or "levels" between the pure divine source and the material world, often existing in pairs (syzygies) to maintain balance.
12
-
13
- In the Affectively framework, if "halos" are the users, then **Aeons are the collaborative structures** - the channels that allow users to communicate with the higher-level logic of the platform. They bridge the gap between individual user state and the distributed system, maintaining harmony across the network.
14
-
15
- ## Overview
16
-
17
- **Aeon** is a comprehensive TypeScript library for building distributed, collaborative applications. It provides the primitives needed for:
18
-
19
- - **Distributed Synchronization** - Coordinate sync sessions across multiple nodes
20
- - **Schema Versioning** - Manage schema evolution with migrations and rollbacks
21
- - **Data Replication** - Configure consistency levels and replication policies
22
- - **Conflict Resolution** - Multiple strategies for resolving divergent state
23
- - **Real-time Presence** - Track node health and status in real-time
24
-
25
- Roadmap vision: see [ROADMAP.md](./ROADMAP.md).
26
-
27
- ## Installation
28
-
29
- ```bash
30
- npm install @affectively/aeon
31
- # or
32
- yarn add @affectively/aeon
33
- # or
34
- pnpm add @affectively/aeon
35
- # or
36
- bun add @affectively/aeon
37
- ```
38
-
39
- ## Quick Start
40
-
41
- ### Distributed Synchronization
42
-
43
- ```typescript
44
- import { SyncCoordinator } from '@affectively/aeon';
45
-
46
- // Create a sync coordinator
47
- const coordinator = new SyncCoordinator();
48
-
49
- // Register nodes
50
- coordinator.registerNode({
51
- id: 'node-1',
52
- address: 'localhost',
53
- port: 3000,
54
- status: 'online',
55
- lastHeartbeat: new Date().toISOString(),
56
- version: '1.0.0',
57
- capabilities: ['sync', 'replicate'],
58
- });
59
-
60
- // Create a sync session
61
- const session = coordinator.createSyncSession('node-1', ['node-2', 'node-3']);
62
-
63
- // Listen for sync events
64
- coordinator.on('sync-completed', (session) => {
65
- console.log(`Session ${session.id} completed:`, session.itemsSynced, 'items synced');
66
- });
67
-
68
- // Start heartbeat monitoring
69
- coordinator.startHeartbeatMonitoring(5000);
70
- ```
71
-
72
- ### Schema Versioning & Migrations
73
-
74
- ```typescript
75
- import { SchemaVersionManager, MigrationEngine, MigrationTracker } from '@affectively/aeon';
76
-
77
- // Initialize version manager
78
- const versionManager = new SchemaVersionManager();
79
-
80
- // Register schema versions
81
- versionManager.registerVersion({
82
- major: 1,
83
- minor: 0,
84
- patch: 0,
85
- timestamp: new Date().toISOString(),
86
- description: 'Initial schema',
87
- breaking: false,
88
- });
89
-
90
- versionManager.registerVersion({
91
- major: 2,
92
- minor: 0,
93
- patch: 0,
94
- timestamp: new Date().toISOString(),
95
- description: 'Added user status field',
96
- breaking: true,
97
- });
98
-
99
- // Create migration engine
100
- const migrationEngine = new MigrationEngine();
101
-
102
- // Register a migration
103
- migrationEngine.registerMigration({
104
- id: 'add-status-field',
105
- version: '2.0.0',
106
- name: 'Add user status field',
107
- up: (data) => ({ ...data, status: 'active' }),
108
- down: (data) => {
109
- const { status, ...rest } = data;
110
- return rest;
111
- },
112
- timestamp: new Date().toISOString(),
113
- description: 'Adds status field to all user records',
114
- });
115
-
116
- // Execute migration
117
- const result = await migrationEngine.executeMigration('add-status-field', userData);
118
- console.log(`Migration completed: ${result.itemsAffected} items affected`);
119
- ```
120
-
121
- ### Data Replication
122
-
123
- ```typescript
124
- import { ReplicationManager } from '@affectively/aeon';
125
-
126
- const replicationManager = new ReplicationManager();
127
-
128
- // Create a replication policy
129
- const policy = replicationManager.createPolicy(
130
- 'user-data-policy',
131
- 3, // replication factor
132
- 'read-after-write', // consistency level
133
- 1000, // sync interval (ms)
134
- 10000 // max replication lag (ms)
135
- );
136
-
137
- // Register replicas
138
- replicationManager.registerReplica({
139
- id: 'replica-1',
140
- nodeId: 'node-1',
141
- status: 'primary',
142
- lastSyncTime: new Date().toISOString(),
143
- lagBytes: 0,
144
- lagMillis: 0,
145
- });
146
-
147
- // Check replication health
148
- const health = replicationManager.checkReplicationHealth(policy.id);
149
- console.log('Replication healthy:', health.healthy);
150
- ```
151
-
152
- ### Conflict Resolution
153
-
154
- ```typescript
155
- import { StateReconciler } from '@affectively/aeon';
156
-
157
- const reconciler = new StateReconciler();
158
-
159
- // Record state versions from different nodes
160
- reconciler.recordStateVersion('user:123', '1.0', '2024-01-01T00:00:00Z', 'node-1', 'hash-a', { name: 'Alice' });
161
- reconciler.recordStateVersion('user:123', '1.0', '2024-01-01T00:00:01Z', 'node-2', 'hash-b', { name: 'Bob' });
162
-
163
- // Detect conflicts
164
- if (reconciler.detectConflicts('user:123')) {
165
- // Reconcile using last-write-wins strategy
166
- const versions = reconciler.getStateVersions('user:123');
167
- const result = reconciler.reconcileLastWriteWins(versions);
168
-
169
- console.log('Resolved state:', result.mergedState);
170
- console.log('Conflicts resolved:', result.conflictsResolved);
171
- }
172
- ```
173
-
174
- ## Modules
175
-
176
- ### Core (`@affectively/aeon/core`)
177
-
178
- Shared types and utilities used across all modules.
179
-
180
- ```typescript
181
- import type { Operation, VectorClock, PresenceInfo } from '@affectively/aeon/core';
182
- ```
183
-
184
- ### Persistence (`@affectively/aeon/persistence`)
185
-
186
- Optional persistence boundaries and adapters for durable Aeon state.
187
-
188
- - `StorageAdapter` - runtime-agnostic adapter contract
189
- - `InMemoryStorageAdapter` - reference adapter for tests/dev
190
- - `DashStorageAdapter` - local-first adapter with optional debounced sync batching for D1/R2-backed resilience
191
-
192
- ### Offline (`@affectively/aeon/offline`)
193
-
194
- Offline-first operation management.
195
-
196
- - `OfflineOperationQueue` - Priority-based offline operation queue with retry logic
197
-
198
- ### Compression (`@affectively/aeon/compression`)
199
-
200
- Data compression and delta sync optimization.
201
-
202
- - `CompressionEngine` - Native compression using CompressionStream API
203
- - `DeltaSyncOptimizer` - Field-level change detection (70-90% payload reduction)
204
-
205
- ### Optimization (`@affectively/aeon/optimization`)
206
-
207
- Network and performance optimization.
208
-
209
- - `PrefetchingEngine` - Predictive pre-compression based on operation patterns
210
- - `BatchTimingOptimizer` - Intelligent batch scheduling based on network conditions
211
- - `AdaptiveCompressionOptimizer` - Auto-adjusting compression level (1-9)
212
-
213
- ### Presence (`@affectively/aeon/presence`)
214
-
215
- Real-time agent presence tracking.
216
-
217
- - `AgentPresenceManager` - Track agent status, cursors, and activity
218
-
219
- ### Versioning (`@affectively/aeon/versioning`)
220
-
221
- Schema versioning and migration system.
222
-
223
- - `SchemaVersionManager` - Version tracking and compatibility
224
- - `MigrationEngine` - Migration execution and rollback
225
- - `DataTransformer` - Data transformation during migrations
226
- - `MigrationTracker` - Migration history and audit trails
227
-
228
- ### Distributed (`@affectively/aeon/distributed`)
229
-
230
- Distributed synchronization primitives.
231
-
232
- - `SyncCoordinator` - Sync session management
233
- - `ReplicationManager` - Replica management and policies
234
- - `SyncProtocol` - Protocol messages and handshaking
235
- - `StateReconciler` - Conflict detection and resolution
236
-
237
- ### Utils (`@affectively/aeon/utils`)
238
-
239
- Shared utilities including pluggable logging.
240
-
241
- ```typescript
242
- import { setLogger, disableLogging } from '@affectively/aeon/utils';
243
-
244
- // Use custom logger
245
- setLogger({
246
- debug: (...args) => myLogger.debug(...args),
247
- info: (...args) => myLogger.info(...args),
248
- warn: (...args) => myLogger.warn(...args),
249
- error: (...args) => myLogger.error(...args),
250
- });
251
-
252
- // Or disable logging entirely
253
- disableLogging();
254
- ```
255
-
256
- ## API Reference
257
-
258
- ### SyncCoordinator
259
-
260
- | Method | Description |
261
- |--------|-------------|
262
- | `registerNode(node)` | Register a node in the cluster |
263
- | `deregisterNode(nodeId)` | Remove a node from the cluster |
264
- | `createSyncSession(initiatorId, participantIds)` | Create a new sync session |
265
- | `updateSyncSession(sessionId, updates)` | Update sync session status |
266
- | `recordConflict(sessionId, nodeId, data)` | Record a conflict |
267
- | `getStatistics()` | Get sync statistics |
268
- | `startHeartbeatMonitoring(interval)` | Start health monitoring |
269
-
270
- ### SchemaVersionManager
271
-
272
- | Method | Description |
273
- |--------|-------------|
274
- | `registerVersion(version)` | Register a schema version |
275
- | `getCurrentVersion()` | Get current active version |
276
- | `setCurrentVersion(version)` | Set the current version |
277
- | `canMigrate(from, to)` | Check if migration path exists |
278
- | `getMigrationPath(from, to)` | Get migration steps |
279
- | `compareVersions(v1, v2)` | Compare two versions |
280
-
281
- ### MigrationEngine
282
-
283
- | Method | Description |
284
- |--------|-------------|
285
- | `registerMigration(migration)` | Register a migration |
286
- | `executeMigration(id, data)` | Execute a migration |
287
- | `rollbackMigration(id, data)` | Rollback a migration |
288
- | `getState()` | Get current migration state |
289
- | `getPendingMigrations()` | Get pending migrations |
290
- | `getStatistics()` | Get migration statistics |
291
-
292
- ### ReplicationManager
293
-
294
- | Method | Description |
295
- |--------|-------------|
296
- | `registerReplica(replica)` | Register a replica |
297
- | `removeReplica(replicaId)` | Remove a replica |
298
- | `createPolicy(...)` | Create replication policy |
299
- | `updateReplicaStatus(...)` | Update replica status |
300
- | `checkReplicationHealth(policyId)` | Check replication health |
301
- | `getStatistics()` | Get replication statistics |
302
-
303
- ### StateReconciler
304
-
305
- | Method | Description |
306
- |--------|-------------|
307
- | `recordStateVersion(...)` | Record a state version |
308
- | `detectConflicts(key)` | Detect state conflicts |
309
- | `compareStates(s1, s2)` | Generate state diff |
310
- | `reconcileLastWriteWins(versions)` | LWW reconciliation |
311
- | `reconcileVectorClock(versions)` | Vector clock reconciliation |
312
- | `reconcileMajorityVote(versions)` | Majority vote reconciliation |
313
-
314
- ## Comparison with Similar Libraries
315
-
316
- | Feature | Aeon | Yjs | Automerge |
317
- |---------|------|-----|-----------|
318
- | Schema Versioning | | ❌ | ❌ |
319
- | Migrations | ✅ | ❌ | ❌ |
320
- | Replication Policies | ✅ | ❌ | ❌ |
321
- | Multiple Merge Strategies | ✅ | ⚠️ | ⚠️ |
322
- | TypeScript-first | ✅ | ⚠️ | ⚠️ |
323
- | Zero Dependencies* | ✅ | ❌ | ❌ |
324
-
325
- *Only `eventemitter3` for event handling
326
-
327
- ## Requirements
328
-
329
- - Node.js >= 18.0.0
330
- - TypeScript >= 5.0.0 (for types)
331
-
332
- ## Contributing
333
-
334
- Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.
335
-
336
- ## License
337
-
338
- MIT - see [LICENSE](LICENSE) for details.
339
-
340
- ## Credits
341
-
342
- Built with care by [Affectively AI](https://github.com/affectively-ai).
1
+ # Aeon
2
+
3
+ > TCP had its 40-year run. UDP by default everywhere, TCP only when necessary.
4
+
5
+ [![npm version](https://badge.fury.io/js/@affectively%2Faeon.svg)](https://www.npmjs.com/package/@affectively/aeon)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.6+-blue.svg)](https://www.typescriptlang.org/)
8
+
9
+ ## Philosophy
10
+
11
+ In Gnosticism, **Aeons** are not just time periods; they are divine beings or powers that emanate from the "One" (the Pleroma). They function as links or "levels" between the pure divine source and the material world, often existing in pairs (syzygies) to maintain balance.
12
+
13
+ In the Affectively framework, if "halos" are the users, then **Aeons are the collaborative structures** the channels that allow users to communicate with the higher-level logic of the platform. They bridge the gap between individual user state and the distributed system, maintaining harmony across the network.
14
+
15
+ ## Overview
16
+
17
+ **Aeon** is a comprehensive TypeScript library for building distributed, collaborative applications. It provides the primitives needed for:
18
+
19
+ - **Aeon Flow Protocol** - 10-byte binary multiplexing with fork/race/collapse over UDP
20
+ - **Distributed Synchronization** - Coordinate sync sessions across multiple nodes
21
+ - **Schema Versioning** - Manage schema evolution with migrations and rollbacks
22
+ - **Data Replication** - Configure consistency levels and replication policies
23
+ - **Conflict Resolution** - Multiple strategies for resolving divergent state
24
+ - **Real-time Presence** - Track node health and status in real-time
25
+
26
+ ### Aeon Flow Protocol
27
+
28
+ One connection. Every stream independent. Zero head-of-line blocking.
29
+
30
+ ```
31
+ ┌──────────────────────────────────────────────────────────┐
32
+ │ 10-byte Flow Frame │
33
+ ├──────────┬──────────┬───────┬────────────────────────────┤
34
+ stream_id│ sequence │ flags │ length │ payload ... │
35
+ │ (u16) │ (u32) │ (u8) │ (u24) │ │
36
+ └──────────┴──────────┴───────┴────────────────────────────┘
37
+ ```
38
+
39
+ Every frame is self-describing. `stream_id` + `sequence` means frames arrive out of order and reassemble correctly. This is the same insight as QUIC/HTTP3 — but with 10-byte frames instead of QUIC's complex framing.
40
+
41
+ **What was 100+ HTTP requests becomes 1 multiplexed stream:**
42
+
43
+ | | HTTP (before) | Aeon Flow (after) |
44
+ |---|---|---|
45
+ | Full site load | 5+ connections | 1 connection |
46
+ | Service worker preload | 100 fetches in batches of 5 | 1 multiplexed stream |
47
+ | ESI inference per page | N sequential fetches | N forked streams, raced |
48
+ | Deploy artifact transfer | File-by-file | 1 multiplexed stream |
49
+ | Protocol overhead per asset | ~200 bytes HTTP headers | 10 bytes flow header |
50
+ | 100-page overhead | ~20KB HTTP headers | 1KB flow headers |
51
+
52
+ **Transport-agnostic.** Same protocol over WebSocket, UDP, WebTransport, IPC, or anything that moves bytes:
53
+
54
+ ```typescript
55
+ import { AeonFlowProtocol, UDPFlowTransport } from '@affectively/aeon';
56
+
57
+ // Native UDP — zero connection setup, zero head-of-line blocking
58
+ const transport = new UDPFlowTransport({
59
+ host: '0.0.0.0', port: 4242,
60
+ remoteHost: 'target.example.com', remotePort: 4242,
61
+ reliable: true, // ACK bitmaps + AIMD congestion control
62
+ });
63
+ await transport.bind();
64
+
65
+ const flow = new AeonFlowProtocol(transport, {
66
+ role: 'client',
67
+ maxConcurrentStreams: 256,
68
+ });
69
+
70
+ // Fork 3 streams, race them, collapse to winner
71
+ const results = await flow.fork([stream1, stream2, stream3]);
72
+ const winner = await flow.race(results);
73
+ await flow.collapse(winner);
74
+ ```
75
+
76
+ **UDP features:**
77
+ - MTU-aware fragmentation (4-byte header, max 255 fragments x 1468 bytes = 366KB per frame)
78
+ - ACK bitmaps: 14 bytes covers 64 contiguous sequences
79
+ - AIMD congestion control (additive increase, multiplicative decrease)
80
+ - Per-stream out-of-order reassembly via `FrameReassembler`
81
+ - WebTransport bridge for browsers (HTTP/3 unreliable datagrams)
82
+
83
+ Roadmap vision: see [ROADMAP.md](./ROADMAP.md).
84
+
85
+ ## Installation
86
+
87
+ ```bash
88
+ npm install @affectively/aeon
89
+ # or
90
+ yarn add @affectively/aeon
91
+ # or
92
+ pnpm add @affectively/aeon
93
+ # or
94
+ bun add @affectively/aeon
95
+ ```
96
+
97
+ ## Quick Start
98
+
99
+ ### Distributed Synchronization
100
+
101
+ ```typescript
102
+ import { SyncCoordinator } from '@affectively/aeon';
103
+
104
+ // Create a sync coordinator
105
+ const coordinator = new SyncCoordinator();
106
+
107
+ // Register nodes
108
+ coordinator.registerNode({
109
+ id: 'node-1',
110
+ address: 'localhost',
111
+ port: 3000,
112
+ status: 'online',
113
+ lastHeartbeat: new Date().toISOString(),
114
+ version: '1.0.0',
115
+ capabilities: ['sync', 'replicate'],
116
+ });
117
+
118
+ // Create a sync session
119
+ const session = coordinator.createSyncSession('node-1', ['node-2', 'node-3']);
120
+
121
+ // Listen for sync events
122
+ coordinator.on('sync-completed', (session) => {
123
+ console.log(`Session ${session.id} completed:`, session.itemsSynced, 'items synced');
124
+ });
125
+
126
+ // Start heartbeat monitoring
127
+ coordinator.startHeartbeatMonitoring(5000);
128
+ ```
129
+
130
+ ### Schema Versioning & Migrations
131
+
132
+ ```typescript
133
+ import { SchemaVersionManager, MigrationEngine, MigrationTracker } from '@affectively/aeon';
134
+
135
+ // Initialize version manager
136
+ const versionManager = new SchemaVersionManager();
137
+
138
+ // Register schema versions
139
+ versionManager.registerVersion({
140
+ major: 1,
141
+ minor: 0,
142
+ patch: 0,
143
+ timestamp: new Date().toISOString(),
144
+ description: 'Initial schema',
145
+ breaking: false,
146
+ });
147
+
148
+ versionManager.registerVersion({
149
+ major: 2,
150
+ minor: 0,
151
+ patch: 0,
152
+ timestamp: new Date().toISOString(),
153
+ description: 'Added user status field',
154
+ breaking: true,
155
+ });
156
+
157
+ // Create migration engine
158
+ const migrationEngine = new MigrationEngine();
159
+
160
+ // Register a migration
161
+ migrationEngine.registerMigration({
162
+ id: 'add-status-field',
163
+ version: '2.0.0',
164
+ name: 'Add user status field',
165
+ up: (data) => ({ ...data, status: 'active' }),
166
+ down: (data) => {
167
+ const { status, ...rest } = data;
168
+ return rest;
169
+ },
170
+ timestamp: new Date().toISOString(),
171
+ description: 'Adds status field to all user records',
172
+ });
173
+
174
+ // Execute migration
175
+ const result = await migrationEngine.executeMigration('add-status-field', userData);
176
+ console.log(`Migration completed: ${result.itemsAffected} items affected`);
177
+ ```
178
+
179
+ ### Data Replication
180
+
181
+ ```typescript
182
+ import { ReplicationManager } from '@affectively/aeon';
183
+
184
+ const replicationManager = new ReplicationManager();
185
+
186
+ // Create a replication policy
187
+ const policy = replicationManager.createPolicy(
188
+ 'user-data-policy',
189
+ 3, // replication factor
190
+ 'read-after-write', // consistency level
191
+ 1000, // sync interval (ms)
192
+ 10000 // max replication lag (ms)
193
+ );
194
+
195
+ // Register replicas
196
+ replicationManager.registerReplica({
197
+ id: 'replica-1',
198
+ nodeId: 'node-1',
199
+ status: 'primary',
200
+ lastSyncTime: new Date().toISOString(),
201
+ lagBytes: 0,
202
+ lagMillis: 0,
203
+ });
204
+
205
+ // Check replication health
206
+ const health = replicationManager.checkReplicationHealth(policy.id);
207
+ console.log('Replication healthy:', health.healthy);
208
+ ```
209
+
210
+ ### Conflict Resolution
211
+
212
+ ```typescript
213
+ import { StateReconciler } from '@affectively/aeon';
214
+
215
+ const reconciler = new StateReconciler();
216
+
217
+ // Record state versions from different nodes
218
+ reconciler.recordStateVersion('user:123', '1.0', '2024-01-01T00:00:00Z', 'node-1', 'hash-a', { name: 'Alice' });
219
+ reconciler.recordStateVersion('user:123', '1.0', '2024-01-01T00:00:01Z', 'node-2', 'hash-b', { name: 'Bob' });
220
+
221
+ // Detect conflicts
222
+ if (reconciler.detectConflicts('user:123')) {
223
+ // Reconcile using last-write-wins strategy
224
+ const versions = reconciler.getStateVersions('user:123');
225
+ const result = reconciler.reconcileLastWriteWins(versions);
226
+
227
+ console.log('Resolved state:', result.mergedState);
228
+ console.log('Conflicts resolved:', result.conflictsResolved);
229
+ }
230
+ ```
231
+
232
+ ## Modules
233
+
234
+ ### Flow (`@affectively/aeon/flow`)
235
+
236
+ Binary multiplexing protocol with fork/race/collapse primitives.
237
+
238
+ - `AeonFlowProtocol` - Protocol engine (transport-agnostic)
239
+ - `FlowCodec` - Frame encoding/decoding (10-byte headers)
240
+ - `UDPFlowTransport` - Native UDP transport with AIMD congestion control
241
+ - `WebTransportFlowTransport` - Browser-side HTTP/3 unreliable datagrams
242
+ - `FrameReassembler` - Per-stream out-of-order frame reconstruction
243
+
244
+ ```typescript
245
+ import {
246
+ AeonFlowProtocol,
247
+ UDPFlowTransport,
248
+ FrameReassembler,
249
+ } from '@affectively/aeon';
250
+ ```
251
+
252
+ ### Core (`@affectively/aeon/core`)
253
+
254
+ Shared types and utilities used across all modules.
255
+
256
+ ```typescript
257
+ import type { Operation, VectorClock, PresenceInfo } from '@affectively/aeon/core';
258
+ ```
259
+
260
+ ### Persistence (`@affectively/aeon/persistence`)
261
+
262
+ Optional persistence boundaries and adapters for durable Aeon state.
263
+
264
+ - `StorageAdapter` - runtime-agnostic adapter contract
265
+ - `InMemoryStorageAdapter` - reference adapter for tests/dev
266
+ - `DashStorageAdapter` - local-first adapter with optional debounced sync batching for D1/R2-backed resilience
267
+
268
+ ### Offline (`@affectively/aeon/offline`)
269
+
270
+ Offline-first operation management.
271
+
272
+ - `OfflineOperationQueue` - Priority-based offline operation queue with retry logic
273
+
274
+ ### Compression (`@affectively/aeon/compression`)
275
+
276
+ Data compression and delta sync optimization.
277
+
278
+ - `CompressionEngine` - Native compression using CompressionStream API
279
+ - `DeltaSyncOptimizer` - Field-level change detection (70-90% payload reduction)
280
+
281
+ ### Optimization (`@affectively/aeon/optimization`)
282
+
283
+ Network and performance optimization.
284
+
285
+ - `PrefetchingEngine` - Predictive pre-compression based on operation patterns
286
+ - `BatchTimingOptimizer` - Intelligent batch scheduling based on network conditions
287
+ - `AdaptiveCompressionOptimizer` - Auto-adjusting compression level (1-9)
288
+
289
+ ### Presence (`@affectively/aeon/presence`)
290
+
291
+ Real-time agent presence tracking.
292
+
293
+ - `AgentPresenceManager` - Track agent status, cursors, and activity
294
+
295
+ ### Versioning (`@affectively/aeon/versioning`)
296
+
297
+ Schema versioning and migration system.
298
+
299
+ - `SchemaVersionManager` - Version tracking and compatibility
300
+ - `MigrationEngine` - Migration execution and rollback
301
+ - `DataTransformer` - Data transformation during migrations
302
+ - `MigrationTracker` - Migration history and audit trails
303
+
304
+ ### Distributed (`@affectively/aeon/distributed`)
305
+
306
+ Distributed synchronization primitives.
307
+
308
+ - `SyncCoordinator` - Sync session management
309
+ - `ReplicationManager` - Replica management and policies
310
+ - `SyncProtocol` - Protocol messages and handshaking
311
+ - `StateReconciler` - Conflict detection and resolution
312
+
313
+ ### Utils (`@affectively/aeon/utils`)
314
+
315
+ Shared utilities including pluggable logging.
316
+
317
+ ```typescript
318
+ import { setLogger, disableLogging } from '@affectively/aeon/utils';
319
+
320
+ // Use custom logger
321
+ setLogger({
322
+ debug: (...args) => myLogger.debug(...args),
323
+ info: (...args) => myLogger.info(...args),
324
+ warn: (...args) => myLogger.warn(...args),
325
+ error: (...args) => myLogger.error(...args),
326
+ });
327
+
328
+ // Or disable logging entirely
329
+ disableLogging();
330
+ ```
331
+
332
+ ## API Reference
333
+
334
+ ### SyncCoordinator
335
+
336
+ | Method | Description |
337
+ |--------|-------------|
338
+ | `registerNode(node)` | Register a node in the cluster |
339
+ | `deregisterNode(nodeId)` | Remove a node from the cluster |
340
+ | `createSyncSession(initiatorId, participantIds)` | Create a new sync session |
341
+ | `updateSyncSession(sessionId, updates)` | Update sync session status |
342
+ | `recordConflict(sessionId, nodeId, data)` | Record a conflict |
343
+ | `getStatistics()` | Get sync statistics |
344
+ | `startHeartbeatMonitoring(interval)` | Start health monitoring |
345
+
346
+ ### SchemaVersionManager
347
+
348
+ | Method | Description |
349
+ |--------|-------------|
350
+ | `registerVersion(version)` | Register a schema version |
351
+ | `getCurrentVersion()` | Get current active version |
352
+ | `setCurrentVersion(version)` | Set the current version |
353
+ | `canMigrate(from, to)` | Check if migration path exists |
354
+ | `getMigrationPath(from, to)` | Get migration steps |
355
+ | `compareVersions(v1, v2)` | Compare two versions |
356
+
357
+ ### MigrationEngine
358
+
359
+ | Method | Description |
360
+ |--------|-------------|
361
+ | `registerMigration(migration)` | Register a migration |
362
+ | `executeMigration(id, data)` | Execute a migration |
363
+ | `rollbackMigration(id, data)` | Rollback a migration |
364
+ | `getState()` | Get current migration state |
365
+ | `getPendingMigrations()` | Get pending migrations |
366
+ | `getStatistics()` | Get migration statistics |
367
+
368
+ ### ReplicationManager
369
+
370
+ | Method | Description |
371
+ |--------|-------------|
372
+ | `registerReplica(replica)` | Register a replica |
373
+ | `removeReplica(replicaId)` | Remove a replica |
374
+ | `createPolicy(...)` | Create replication policy |
375
+ | `updateReplicaStatus(...)` | Update replica status |
376
+ | `checkReplicationHealth(policyId)` | Check replication health |
377
+ | `getStatistics()` | Get replication statistics |
378
+
379
+ ### StateReconciler
380
+
381
+ | Method | Description |
382
+ |--------|-------------|
383
+ | `recordStateVersion(...)` | Record a state version |
384
+ | `detectConflicts(key)` | Detect state conflicts |
385
+ | `compareStates(s1, s2)` | Generate state diff |
386
+ | `reconcileLastWriteWins(versions)` | LWW reconciliation |
387
+ | `reconcileVectorClock(versions)` | Vector clock reconciliation |
388
+ | `reconcileMajorityVote(versions)` | Majority vote reconciliation |
389
+
390
+ ## Comparison with Similar Libraries
391
+
392
+ | Feature | Aeon | Yjs | Automerge | QUIC |
393
+ |---------|------|-----|-----------|------|
394
+ | Binary Multiplexing | ✅ 10-byte frames | ❌ | ❌ | ✅ Complex framing |
395
+ | Fork/Race/Collapse | ✅ | ❌ | ❌ | ❌ |
396
+ | UDP Transport | ✅ Native | ❌ | ❌ | ✅ |
397
+ | Zero HOL Blocking | ✅ | ❌ | ❌ | ✅ |
398
+ | Schema Versioning | ✅ | ❌ | ❌ | ❌ |
399
+ | Migrations | ✅ | ❌ | ❌ | ❌ |
400
+ | Replication Policies | ✅ | ❌ | ❌ | ❌ |
401
+ | Multiple Merge Strategies | ✅ | ⚠️ | ⚠️ | ❌ |
402
+ | TypeScript-first | ✅ | ⚠️ | ⚠️ | ❌ |
403
+ | Zero Dependencies* | ✅ | ❌ | ❌ | ❌ |
404
+
405
+ *Only `eventemitter3` for event handling
406
+
407
+ ## Requirements
408
+
409
+ - Node.js >= 18.0.0
410
+ - TypeScript >= 5.0.0 (for types)
411
+
412
+ ## Contributing
413
+
414
+ Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.
415
+
416
+ ## License
417
+
418
+ MIT - see [LICENSE](LICENSE) for details.
419
+
420
+ ## Credits
421
+
422
+ Built with care by [Affectively AI](https://github.com/affectively-ai).