@johnhenry/browsermesh-sync 0.0.0
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.
- package/LICENSE +21 -0
- package/README.md +36 -0
- package/package.json +31 -0
- package/src/collab-bridge.mjs +661 -0
- package/src/collab.mjs +363 -0
- package/src/delta-sync.mjs +1059 -0
- package/src/files.mjs +640 -0
- package/src/index.mjs +8 -0
- package/src/memory-sync.mjs +712 -0
- package/src/migration.mjs +986 -0
- package/src/silent-catch.mjs +55 -0
- package/src/sync.mjs +419 -0
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
/**
|
|
2
|
+
// STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
|
|
3
|
+
* clawser-peer-memory-sync.js — CRDT-backed agent memory replication.
|
|
4
|
+
*
|
|
5
|
+
* Replicate agent memory across the mesh using CRDTs. An agent's memory
|
|
6
|
+
* survives device failure — when the user reconnects, memory resyncs
|
|
7
|
+
* from peers. Enables "living personal twin" and "immortal AI swarm".
|
|
8
|
+
*
|
|
9
|
+
* CRDT model: LWW-Element-Map (Last-Writer-Wins per key).
|
|
10
|
+
* Each entry has a key, value, timestamp, podId (origin), and tombstone flag.
|
|
11
|
+
* On merge, timestamps are compared per key. Tombstones with later
|
|
12
|
+
* timestamps win over values with earlier timestamps.
|
|
13
|
+
*
|
|
14
|
+
* Conflict strategies:
|
|
15
|
+
* - lww: latest timestamp wins (default)
|
|
16
|
+
* - keep_both: store both under suffixed keys
|
|
17
|
+
* - ask_user: add to conflicts list, don't auto-resolve
|
|
18
|
+
* - trust: use podId to look up trust scores
|
|
19
|
+
*
|
|
20
|
+
* Run tests:
|
|
21
|
+
* node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-memory-sync.test.mjs
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
// Constants
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
/** Conflict resolution strategies. */
|
|
29
|
+
export const CONFLICT_STRATEGIES = Object.freeze({
|
|
30
|
+
LAST_WRITE_WINS: 'lww',
|
|
31
|
+
TRUST_WEIGHTED: 'trust',
|
|
32
|
+
KEEP_BOTH: 'keep_both',
|
|
33
|
+
ASK_USER: 'ask_user',
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
/** Default configuration values. */
|
|
37
|
+
export const MEMORY_SYNC_DEFAULTS = Object.freeze({
|
|
38
|
+
syncIntervalMs: 30_000,
|
|
39
|
+
conflictStrategy: 'lww',
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
// MemoryEntry
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* A single entry in the CRDT memory map.
|
|
48
|
+
* Represents one key-value pair with LWW metadata.
|
|
49
|
+
*/
|
|
50
|
+
export class MemoryEntry {
|
|
51
|
+
/**
|
|
52
|
+
* @param {object} opts
|
|
53
|
+
* @param {string} opts.key - Memory key
|
|
54
|
+
* @param {*} opts.value - Memory value
|
|
55
|
+
* @param {string} [opts.category='core'] - Memory category
|
|
56
|
+
* @param {number} [opts.timestamp] - Unix timestamp in ms
|
|
57
|
+
* @param {string} [opts.podId] - Origin pod ID
|
|
58
|
+
* @param {boolean} [opts.tombstone=false] - Whether entry has been deleted
|
|
59
|
+
*/
|
|
60
|
+
constructor({ key, value, category = 'core', timestamp, podId, tombstone = false }) {
|
|
61
|
+
if (!key || typeof key !== 'string') {
|
|
62
|
+
throw new Error('key is required and must be a non-empty string')
|
|
63
|
+
}
|
|
64
|
+
this.key = key
|
|
65
|
+
this.value = value
|
|
66
|
+
this.category = category
|
|
67
|
+
this.timestamp = timestamp || Date.now()
|
|
68
|
+
this.podId = podId || ''
|
|
69
|
+
this.tombstone = Boolean(tombstone)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Serialize to a JSON-safe object.
|
|
74
|
+
* @returns {object}
|
|
75
|
+
*/
|
|
76
|
+
toJSON() {
|
|
77
|
+
return {
|
|
78
|
+
key: this.key,
|
|
79
|
+
value: this.value,
|
|
80
|
+
category: this.category,
|
|
81
|
+
timestamp: this.timestamp,
|
|
82
|
+
podId: this.podId,
|
|
83
|
+
tombstone: this.tombstone,
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Deserialize from a plain object.
|
|
89
|
+
* @param {object} json
|
|
90
|
+
* @returns {MemoryEntry}
|
|
91
|
+
*/
|
|
92
|
+
static fromJSON(json) {
|
|
93
|
+
return new MemoryEntry({
|
|
94
|
+
key: json.key,
|
|
95
|
+
value: json.value,
|
|
96
|
+
category: json.category,
|
|
97
|
+
timestamp: json.timestamp,
|
|
98
|
+
podId: json.podId,
|
|
99
|
+
tombstone: json.tombstone,
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ---------------------------------------------------------------------------
|
|
105
|
+
// ConflictEntry
|
|
106
|
+
// ---------------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Records a merge conflict between a local and remote MemoryEntry.
|
|
110
|
+
*/
|
|
111
|
+
export class ConflictEntry {
|
|
112
|
+
/**
|
|
113
|
+
* @param {object} opts
|
|
114
|
+
* @param {string} opts.key - The conflicting key
|
|
115
|
+
* @param {MemoryEntry} opts.local - Local entry
|
|
116
|
+
* @param {MemoryEntry} opts.remote - Remote entry
|
|
117
|
+
* @param {string} opts.strategy - Conflict strategy that was active
|
|
118
|
+
* @param {boolean} [opts.resolved=false] - Whether this conflict has been resolved
|
|
119
|
+
*/
|
|
120
|
+
constructor({ key, local, remote, strategy, resolved = false }) {
|
|
121
|
+
this.key = key
|
|
122
|
+
this.local = local
|
|
123
|
+
this.remote = remote
|
|
124
|
+
this.strategy = strategy
|
|
125
|
+
this.resolved = Boolean(resolved)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Serialize to a JSON-safe object.
|
|
130
|
+
* @returns {object}
|
|
131
|
+
*/
|
|
132
|
+
toJSON() {
|
|
133
|
+
return {
|
|
134
|
+
key: this.key,
|
|
135
|
+
local: this.local instanceof MemoryEntry ? this.local.toJSON() : this.local,
|
|
136
|
+
remote: this.remote instanceof MemoryEntry ? this.remote.toJSON() : this.remote,
|
|
137
|
+
strategy: this.strategy,
|
|
138
|
+
resolved: this.resolved,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
// SyncResult
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Result of a sync or merge operation.
|
|
149
|
+
*/
|
|
150
|
+
export class SyncResult {
|
|
151
|
+
/**
|
|
152
|
+
* @param {object} opts
|
|
153
|
+
* @param {number} opts.merged - Number of entries merged
|
|
154
|
+
* @param {ConflictEntry[]} opts.conflicts - Conflicts encountered
|
|
155
|
+
* @param {number} [opts.timestamp] - When the sync completed
|
|
156
|
+
*/
|
|
157
|
+
constructor({ merged, conflicts, timestamp }) {
|
|
158
|
+
this.merged = merged
|
|
159
|
+
this.conflicts = conflicts || []
|
|
160
|
+
this.timestamp = timestamp || Date.now()
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ---------------------------------------------------------------------------
|
|
165
|
+
// AgentMemorySync
|
|
166
|
+
// ---------------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* CRDT-backed agent memory synchronization.
|
|
170
|
+
*
|
|
171
|
+
* Maintains a LWW-Element-Map of agent memory entries, replicates them
|
|
172
|
+
* across the mesh via PeerSession-compatible sessions, and resolves
|
|
173
|
+
* conflicts using configurable strategies.
|
|
174
|
+
*/
|
|
175
|
+
export class AgentMemorySync {
|
|
176
|
+
/** @type {string} */
|
|
177
|
+
#agentId
|
|
178
|
+
|
|
179
|
+
/** @type {object} session with send(type, payload), registerHandler(type, cb), remotePodId */
|
|
180
|
+
#session
|
|
181
|
+
|
|
182
|
+
/** @type {Function} */
|
|
183
|
+
#onLog
|
|
184
|
+
|
|
185
|
+
/** @type {Map<string, MemoryEntry>} key -> MemoryEntry */
|
|
186
|
+
#state = new Map()
|
|
187
|
+
|
|
188
|
+
/** @type {Map<string, Set<Function>>} event -> Set<cb> */
|
|
189
|
+
#listeners = new Map()
|
|
190
|
+
|
|
191
|
+
/** @type {boolean} */
|
|
192
|
+
#enabled = false
|
|
193
|
+
|
|
194
|
+
/** @type {*} interval ID */
|
|
195
|
+
#syncInterval = null
|
|
196
|
+
|
|
197
|
+
/** @type {number} ms between syncs */
|
|
198
|
+
#syncIntervalMs = MEMORY_SYNC_DEFAULTS.syncIntervalMs
|
|
199
|
+
|
|
200
|
+
/** @type {string} conflict resolution strategy */
|
|
201
|
+
#conflictStrategy = MEMORY_SYNC_DEFAULTS.conflictStrategy
|
|
202
|
+
|
|
203
|
+
/** @type {number|null} timestamp of last successful sync */
|
|
204
|
+
#lastSync = null
|
|
205
|
+
|
|
206
|
+
/** @type {MemoryEntry[]} ops waiting to be synced */
|
|
207
|
+
#pendingOps = []
|
|
208
|
+
|
|
209
|
+
/** @type {ConflictEntry[]} unresolved conflicts */
|
|
210
|
+
#conflicts = []
|
|
211
|
+
|
|
212
|
+
/** @type {Map<string, number>} podId -> trust score (0-1) for trust strategy */
|
|
213
|
+
#trustScores = new Map()
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* @param {object} opts
|
|
217
|
+
* @param {string} opts.agentId - Identifier for this agent
|
|
218
|
+
* @param {object} opts.session - PeerSession-like object
|
|
219
|
+
* @param {Function} [opts.onLog] - Logging callback (level, msg)
|
|
220
|
+
*/
|
|
221
|
+
constructor({ agentId, session, onLog }) {
|
|
222
|
+
if (!agentId || typeof agentId !== 'string') {
|
|
223
|
+
throw new Error('agentId is required and must be a non-empty string')
|
|
224
|
+
}
|
|
225
|
+
if (!session || typeof session.send !== 'function') {
|
|
226
|
+
throw new Error('session with send() is required')
|
|
227
|
+
}
|
|
228
|
+
if (!session.registerHandler || typeof session.registerHandler !== 'function') {
|
|
229
|
+
throw new Error('session with registerHandler() is required')
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
this.#agentId = agentId
|
|
233
|
+
this.#session = session
|
|
234
|
+
this.#onLog = onLog || (() => {})
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// -- Lifecycle ------------------------------------------------------------
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Enable memory sync. Starts periodic sync and registers the
|
|
241
|
+
* session handler for incoming memory-sync messages.
|
|
242
|
+
*
|
|
243
|
+
* @param {object} [opts]
|
|
244
|
+
* @param {number} [opts.syncIntervalMs] - Milliseconds between syncs
|
|
245
|
+
* @param {string} [opts.conflictStrategy] - Conflict resolution strategy
|
|
246
|
+
* @param {Map<string, number>} [opts.trustScores] - Pod trust scores for trust strategy
|
|
247
|
+
*/
|
|
248
|
+
enable(opts) {
|
|
249
|
+
if (this.#enabled) return
|
|
250
|
+
|
|
251
|
+
if (opts?.syncIntervalMs != null) {
|
|
252
|
+
this.#syncIntervalMs = opts.syncIntervalMs
|
|
253
|
+
}
|
|
254
|
+
if (opts?.conflictStrategy != null) {
|
|
255
|
+
this.#conflictStrategy = opts.conflictStrategy
|
|
256
|
+
}
|
|
257
|
+
if (opts?.trustScores instanceof Map) {
|
|
258
|
+
this.#trustScores = opts.trustScores
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
this.#enabled = true
|
|
262
|
+
|
|
263
|
+
// Register handler for incoming memory-sync messages
|
|
264
|
+
this.#session.registerHandler('memory-sync', (envelope) => {
|
|
265
|
+
const remoteState = envelope.payload || envelope
|
|
266
|
+
this.#handleRemoteSync(remoteState)
|
|
267
|
+
})
|
|
268
|
+
|
|
269
|
+
// Start periodic sync
|
|
270
|
+
this.#syncInterval = setInterval(() => {
|
|
271
|
+
this.syncNow().catch((err) => {
|
|
272
|
+
this.#onLog(0, `Periodic sync failed: ${err.message}`)
|
|
273
|
+
})
|
|
274
|
+
}, this.#syncIntervalMs)
|
|
275
|
+
|
|
276
|
+
this.#onLog(2, `Memory sync enabled for agent ${this.#agentId} (interval=${this.#syncIntervalMs}ms)`)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Disable memory sync. Stops interval and removes handler.
|
|
281
|
+
*/
|
|
282
|
+
disable() {
|
|
283
|
+
if (!this.#enabled) return
|
|
284
|
+
|
|
285
|
+
this.#enabled = false
|
|
286
|
+
|
|
287
|
+
if (this.#syncInterval !== null) {
|
|
288
|
+
clearInterval(this.#syncInterval)
|
|
289
|
+
this.#syncInterval = null
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
this.#session.removeHandler('memory-sync')
|
|
293
|
+
this.#onLog(2, `Memory sync disabled for agent ${this.#agentId}`)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// -- Local operations -----------------------------------------------------
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Apply a local operation to the CRDT state.
|
|
300
|
+
*
|
|
301
|
+
* @param {object} op
|
|
302
|
+
* @param {string} op.type - 'store' | 'update' | 'forget'
|
|
303
|
+
* @param {string} op.key - Memory key
|
|
304
|
+
* @param {*} [op.value] - Memory value (for store/update)
|
|
305
|
+
* @param {string} [op.category] - Memory category
|
|
306
|
+
* @param {number} [op.timestamp] - Operation timestamp
|
|
307
|
+
*/
|
|
308
|
+
applyLocalOp(op) {
|
|
309
|
+
if (!op || !op.key) {
|
|
310
|
+
throw new Error('op.key is required')
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const timestamp = op.timestamp || Date.now()
|
|
314
|
+
const podId = this.#session.remotePodId
|
|
315
|
+
? `local-${this.#agentId}`
|
|
316
|
+
: this.#agentId
|
|
317
|
+
|
|
318
|
+
if (op.type === 'forget') {
|
|
319
|
+
// Create a tombstone entry
|
|
320
|
+
const entry = new MemoryEntry({
|
|
321
|
+
key: op.key,
|
|
322
|
+
value: undefined,
|
|
323
|
+
category: op.category || 'core',
|
|
324
|
+
timestamp,
|
|
325
|
+
podId,
|
|
326
|
+
tombstone: true,
|
|
327
|
+
})
|
|
328
|
+
this.#state.set(op.key, entry)
|
|
329
|
+
this.#pendingOps.push(entry)
|
|
330
|
+
this.#emit('op-applied', { op: 'forget', key: op.key, entry })
|
|
331
|
+
} else {
|
|
332
|
+
// store or update
|
|
333
|
+
const entry = new MemoryEntry({
|
|
334
|
+
key: op.key,
|
|
335
|
+
value: op.value,
|
|
336
|
+
category: op.category || 'core',
|
|
337
|
+
timestamp,
|
|
338
|
+
podId,
|
|
339
|
+
tombstone: false,
|
|
340
|
+
})
|
|
341
|
+
this.#state.set(op.key, entry)
|
|
342
|
+
this.#pendingOps.push(entry)
|
|
343
|
+
this.#emit('op-applied', { op: op.type, key: op.key, entry })
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// -- Sync -----------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Trigger an immediate sync with the remote peer.
|
|
351
|
+
* Sends local state to the peer. The response is handled by the
|
|
352
|
+
* registered 'memory-sync' handler which calls merge().
|
|
353
|
+
*
|
|
354
|
+
* @returns {Promise<SyncResult>}
|
|
355
|
+
*/
|
|
356
|
+
async syncNow() {
|
|
357
|
+
const serialized = this.#serializeState()
|
|
358
|
+
this.#session.send('memory-sync', serialized)
|
|
359
|
+
this.#pendingOps = []
|
|
360
|
+
this.#lastSync = Date.now()
|
|
361
|
+
|
|
362
|
+
const result = new SyncResult({
|
|
363
|
+
merged: 0,
|
|
364
|
+
conflicts: [],
|
|
365
|
+
timestamp: this.#lastSync,
|
|
366
|
+
})
|
|
367
|
+
|
|
368
|
+
this.#emit('synced', result)
|
|
369
|
+
return result
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Merge remote state into local state using the configured
|
|
374
|
+
* conflict resolution strategy.
|
|
375
|
+
*
|
|
376
|
+
* @param {object} remoteState - Map-like object or array of MemoryEntry JSON
|
|
377
|
+
* @returns {{ merged: number, conflicts: ConflictEntry[] }}
|
|
378
|
+
*/
|
|
379
|
+
merge(remoteState) {
|
|
380
|
+
let merged = 0
|
|
381
|
+
const conflicts = []
|
|
382
|
+
|
|
383
|
+
const entries = this.#deserializeRemoteState(remoteState)
|
|
384
|
+
|
|
385
|
+
for (const remote of entries) {
|
|
386
|
+
const local = this.#state.get(remote.key)
|
|
387
|
+
|
|
388
|
+
if (!local) {
|
|
389
|
+
// No local entry — accept remote unconditionally
|
|
390
|
+
this.#state.set(remote.key, remote)
|
|
391
|
+
merged++
|
|
392
|
+
continue
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// Same timestamp and same podId — skip (identical)
|
|
396
|
+
if (local.timestamp === remote.timestamp && local.podId === remote.podId) {
|
|
397
|
+
continue
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// Apply conflict strategy
|
|
401
|
+
const resolution = this.#resolveEntry(local, remote)
|
|
402
|
+
|
|
403
|
+
if (resolution.action === 'accept_remote') {
|
|
404
|
+
this.#state.set(remote.key, remote)
|
|
405
|
+
merged++
|
|
406
|
+
} else if (resolution.action === 'keep_both') {
|
|
407
|
+
// Keep local as-is, store remote under a suffixed key
|
|
408
|
+
const suffixedKey = `${remote.key}__conflict_1`
|
|
409
|
+
const suffixedEntry = new MemoryEntry({
|
|
410
|
+
...remote.toJSON(),
|
|
411
|
+
key: suffixedKey,
|
|
412
|
+
})
|
|
413
|
+
this.#state.set(suffixedKey, suffixedEntry)
|
|
414
|
+
merged++
|
|
415
|
+
} else if (resolution.action === 'conflict') {
|
|
416
|
+
const conflict = new ConflictEntry({
|
|
417
|
+
key: remote.key,
|
|
418
|
+
local,
|
|
419
|
+
remote,
|
|
420
|
+
strategy: this.#conflictStrategy,
|
|
421
|
+
resolved: false,
|
|
422
|
+
})
|
|
423
|
+
conflicts.push(conflict)
|
|
424
|
+
this.#conflicts.push(conflict)
|
|
425
|
+
this.#emit('conflict', conflict)
|
|
426
|
+
}
|
|
427
|
+
// 'keep_local' — do nothing
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
this.#lastSync = Date.now()
|
|
431
|
+
|
|
432
|
+
const result = { merged, conflicts }
|
|
433
|
+
if (merged > 0 || conflicts.length > 0) {
|
|
434
|
+
this.#emit('synced', new SyncResult({
|
|
435
|
+
merged,
|
|
436
|
+
conflicts,
|
|
437
|
+
timestamp: this.#lastSync,
|
|
438
|
+
}))
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
return result
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// -- Conflict resolution --------------------------------------------------
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Manually resolve a pending conflict.
|
|
448
|
+
*
|
|
449
|
+
* @param {string} key - The conflicting key
|
|
450
|
+
* @param {'keep_local'|'keep_remote'|'keep_both'} resolution
|
|
451
|
+
*/
|
|
452
|
+
resolveConflict(key, resolution) {
|
|
453
|
+
const idx = this.#conflicts.findIndex((c) => c.key === key && !c.resolved)
|
|
454
|
+
if (idx === -1) {
|
|
455
|
+
throw new Error(`No unresolved conflict for key "${key}"`)
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const conflict = this.#conflicts[idx]
|
|
459
|
+
conflict.resolved = true
|
|
460
|
+
|
|
461
|
+
if (resolution === 'keep_remote') {
|
|
462
|
+
this.#state.set(key, conflict.remote)
|
|
463
|
+
} else if (resolution === 'keep_both') {
|
|
464
|
+
// Keep local, store remote under suffixed key
|
|
465
|
+
const suffixedKey = `${key}__conflict_1`
|
|
466
|
+
const suffixedEntry = new MemoryEntry({
|
|
467
|
+
...conflict.remote.toJSON(),
|
|
468
|
+
key: suffixedKey,
|
|
469
|
+
})
|
|
470
|
+
this.#state.set(suffixedKey, suffixedEntry)
|
|
471
|
+
}
|
|
472
|
+
// 'keep_local' — local already in state, nothing to do
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// -- Queries --------------------------------------------------------------
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Return the current CRDT state — all live (non-tombstoned) entries.
|
|
479
|
+
* @returns {Map<string, MemoryEntry>}
|
|
480
|
+
*/
|
|
481
|
+
getState() {
|
|
482
|
+
const live = new Map()
|
|
483
|
+
for (const [key, entry] of this.#state) {
|
|
484
|
+
if (!entry.tombstone) {
|
|
485
|
+
live.set(key, entry)
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return live
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Return the full internal state including tombstones.
|
|
493
|
+
* @returns {Map<string, MemoryEntry>}
|
|
494
|
+
*/
|
|
495
|
+
getFullState() {
|
|
496
|
+
return new Map(this.#state)
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Return current sync status.
|
|
501
|
+
* @returns {{ enabled: boolean, lastSync: number|null, pendingOps: number, conflicts: number }}
|
|
502
|
+
*/
|
|
503
|
+
getSyncStatus() {
|
|
504
|
+
return {
|
|
505
|
+
enabled: this.#enabled,
|
|
506
|
+
lastSync: this.#lastSync,
|
|
507
|
+
pendingOps: this.#pendingOps.length,
|
|
508
|
+
conflicts: this.#conflicts.filter((c) => !c.resolved).length,
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// -- Events ---------------------------------------------------------------
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Register a listener for a sync event.
|
|
516
|
+
* Events: 'synced', 'conflict', 'op-applied'
|
|
517
|
+
*
|
|
518
|
+
* @param {string} event
|
|
519
|
+
* @param {Function} cb
|
|
520
|
+
*/
|
|
521
|
+
on(event, cb) {
|
|
522
|
+
if (!this.#listeners.has(event)) {
|
|
523
|
+
this.#listeners.set(event, new Set())
|
|
524
|
+
}
|
|
525
|
+
this.#listeners.get(event).add(cb)
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Remove a listener.
|
|
530
|
+
*
|
|
531
|
+
* @param {string} event
|
|
532
|
+
* @param {Function} cb
|
|
533
|
+
*/
|
|
534
|
+
off(event, cb) {
|
|
535
|
+
const set = this.#listeners.get(event)
|
|
536
|
+
if (set) set.delete(cb)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// -- Serialization --------------------------------------------------------
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Serialize the entire sync state to a JSON-safe object.
|
|
543
|
+
* @returns {object}
|
|
544
|
+
*/
|
|
545
|
+
toJSON() {
|
|
546
|
+
const stateEntries = []
|
|
547
|
+
for (const [, entry] of this.#state) {
|
|
548
|
+
stateEntries.push(entry.toJSON())
|
|
549
|
+
}
|
|
550
|
+
return {
|
|
551
|
+
agentId: this.#agentId,
|
|
552
|
+
state: stateEntries,
|
|
553
|
+
conflicts: this.#conflicts.map((c) => c.toJSON()),
|
|
554
|
+
lastSync: this.#lastSync,
|
|
555
|
+
conflictStrategy: this.#conflictStrategy,
|
|
556
|
+
syncIntervalMs: this.#syncIntervalMs,
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* Restore from a serialized snapshot.
|
|
562
|
+
*
|
|
563
|
+
* @param {object} json - Previously serialized state
|
|
564
|
+
* @param {object} deps - { agentId, session, onLog }
|
|
565
|
+
* @returns {AgentMemorySync}
|
|
566
|
+
*/
|
|
567
|
+
static fromJSON(json, deps) {
|
|
568
|
+
const sync = new AgentMemorySync({
|
|
569
|
+
agentId: deps.agentId || json.agentId,
|
|
570
|
+
session: deps.session,
|
|
571
|
+
onLog: deps.onLog,
|
|
572
|
+
})
|
|
573
|
+
|
|
574
|
+
// Restore state entries
|
|
575
|
+
if (Array.isArray(json.state)) {
|
|
576
|
+
for (const raw of json.state) {
|
|
577
|
+
const entry = MemoryEntry.fromJSON(raw)
|
|
578
|
+
sync.#state.set(entry.key, entry)
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// Restore conflicts
|
|
583
|
+
if (Array.isArray(json.conflicts)) {
|
|
584
|
+
for (const raw of json.conflicts) {
|
|
585
|
+
sync.#conflicts.push(new ConflictEntry({
|
|
586
|
+
key: raw.key,
|
|
587
|
+
local: MemoryEntry.fromJSON(raw.local),
|
|
588
|
+
remote: MemoryEntry.fromJSON(raw.remote),
|
|
589
|
+
strategy: raw.strategy,
|
|
590
|
+
resolved: raw.resolved,
|
|
591
|
+
}))
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// Restore settings
|
|
596
|
+
if (json.lastSync != null) sync.#lastSync = json.lastSync
|
|
597
|
+
if (json.conflictStrategy) sync.#conflictStrategy = json.conflictStrategy
|
|
598
|
+
if (json.syncIntervalMs != null) sync.#syncIntervalMs = json.syncIntervalMs
|
|
599
|
+
|
|
600
|
+
return sync
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// -- Private helpers ------------------------------------------------------
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Resolve a conflict between a local and remote entry.
|
|
607
|
+
*
|
|
608
|
+
* @param {MemoryEntry} local
|
|
609
|
+
* @param {MemoryEntry} remote
|
|
610
|
+
* @returns {{ action: 'accept_remote'|'keep_local'|'keep_both'|'conflict' }}
|
|
611
|
+
*/
|
|
612
|
+
#resolveEntry(local, remote) {
|
|
613
|
+
switch (this.#conflictStrategy) {
|
|
614
|
+
case CONFLICT_STRATEGIES.LAST_WRITE_WINS:
|
|
615
|
+
return remote.timestamp > local.timestamp
|
|
616
|
+
? { action: 'accept_remote' }
|
|
617
|
+
: { action: 'keep_local' }
|
|
618
|
+
|
|
619
|
+
case CONFLICT_STRATEGIES.KEEP_BOTH:
|
|
620
|
+
return { action: 'keep_both' }
|
|
621
|
+
|
|
622
|
+
case CONFLICT_STRATEGIES.ASK_USER:
|
|
623
|
+
return { action: 'conflict' }
|
|
624
|
+
|
|
625
|
+
case CONFLICT_STRATEGIES.TRUST_WEIGHTED: {
|
|
626
|
+
const localTrust = this.#trustScores.get(local.podId) ?? 0.5
|
|
627
|
+
const remoteTrust = this.#trustScores.get(remote.podId) ?? 0.5
|
|
628
|
+
if (remoteTrust > localTrust) return { action: 'accept_remote' }
|
|
629
|
+
if (remoteTrust < localTrust) return { action: 'keep_local' }
|
|
630
|
+
// Equal trust — fall back to LWW
|
|
631
|
+
return remote.timestamp > local.timestamp
|
|
632
|
+
? { action: 'accept_remote' }
|
|
633
|
+
: { action: 'keep_local' }
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
default:
|
|
637
|
+
// Unknown strategy — default to LWW
|
|
638
|
+
return remote.timestamp > local.timestamp
|
|
639
|
+
? { action: 'accept_remote' }
|
|
640
|
+
: { action: 'keep_local' }
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* Handle an incoming remote sync message.
|
|
646
|
+
* @param {object} remoteState
|
|
647
|
+
*/
|
|
648
|
+
#handleRemoteSync(remoteState) {
|
|
649
|
+
try {
|
|
650
|
+
const result = this.merge(remoteState)
|
|
651
|
+
this.#onLog(2, `Merged ${result.merged} entries, ${result.conflicts.length} conflicts`)
|
|
652
|
+
} catch (err) {
|
|
653
|
+
this.#onLog(0, `Error handling remote sync: ${err.message}`)
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* Serialize the internal state map for transmission.
|
|
659
|
+
* @returns {object[]}
|
|
660
|
+
*/
|
|
661
|
+
#serializeState() {
|
|
662
|
+
const entries = []
|
|
663
|
+
for (const [, entry] of this.#state) {
|
|
664
|
+
entries.push(entry.toJSON())
|
|
665
|
+
}
|
|
666
|
+
return entries
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Deserialize remote state into MemoryEntry instances.
|
|
671
|
+
*
|
|
672
|
+
* @param {*} remoteState - Array of entry objects, or Map-like
|
|
673
|
+
* @returns {MemoryEntry[]}
|
|
674
|
+
*/
|
|
675
|
+
#deserializeRemoteState(remoteState) {
|
|
676
|
+
if (Array.isArray(remoteState)) {
|
|
677
|
+
return remoteState.map((raw) => {
|
|
678
|
+
if (raw instanceof MemoryEntry) return raw
|
|
679
|
+
return MemoryEntry.fromJSON(raw)
|
|
680
|
+
})
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// Object with key->entry pairs
|
|
684
|
+
if (remoteState && typeof remoteState === 'object') {
|
|
685
|
+
return Object.values(remoteState).map((raw) => {
|
|
686
|
+
if (raw instanceof MemoryEntry) return raw
|
|
687
|
+
return MemoryEntry.fromJSON(raw)
|
|
688
|
+
})
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
return []
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* Emit an event to all registered listeners.
|
|
696
|
+
* Uses snapshot iteration so listeners can safely remove themselves.
|
|
697
|
+
*
|
|
698
|
+
* @param {string} event
|
|
699
|
+
* @param {*} data
|
|
700
|
+
*/
|
|
701
|
+
#emit(event, data) {
|
|
702
|
+
const set = this.#listeners.get(event)
|
|
703
|
+
if (!set) return
|
|
704
|
+
for (const cb of [...set]) {
|
|
705
|
+
try {
|
|
706
|
+
cb(data)
|
|
707
|
+
} catch {
|
|
708
|
+
/* listener errors do not propagate */
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|