@private.me/xcontinuity 2.1.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.
Files changed (59) hide show
  1. package/AGENTS.md +123 -0
  2. package/LICENSE.md +26 -0
  3. package/MIGRATING.md +77 -0
  4. package/README.md +601 -0
  5. package/dist/adjudicator.d.ts +75 -0
  6. package/dist/adjudicator.js +184 -0
  7. package/dist/cascade.d.ts +157 -0
  8. package/dist/cascade.js +323 -0
  9. package/dist/chronicle.d.ts +76 -0
  10. package/dist/chronicle.js +173 -0
  11. package/dist/cjs/adjudicator.js +189 -0
  12. package/dist/cjs/cascade.js +328 -0
  13. package/dist/cjs/chronicle.js +178 -0
  14. package/dist/cjs/enforcement.js +108 -0
  15. package/dist/cjs/errors.js +72 -0
  16. package/dist/cjs/index.js +108 -0
  17. package/dist/cjs/memory-runtime.js +129 -0
  18. package/dist/cjs/memory-session.js +134 -0
  19. package/dist/cjs/mission.js +178 -0
  20. package/dist/cjs/package.json +1 -0
  21. package/dist/cjs/provenance.js +192 -0
  22. package/dist/cjs/ratification.js +322 -0
  23. package/dist/cjs/reverse-xorida.js +506 -0
  24. package/dist/cjs/session.js +273 -0
  25. package/dist/cjs/state-serializer.js +300 -0
  26. package/dist/cjs/store-memory.js +33 -0
  27. package/dist/cjs/trust.js +133 -0
  28. package/dist/cjs/types.js +59 -0
  29. package/dist/enforcement.d.ts +40 -0
  30. package/dist/enforcement.js +104 -0
  31. package/dist/errors.d.ts +25 -0
  32. package/dist/errors.js +68 -0
  33. package/dist/index.d.ts +34 -0
  34. package/dist/index.js +43 -0
  35. package/dist/memory-runtime.d.ts +36 -0
  36. package/dist/memory-runtime.js +125 -0
  37. package/dist/memory-session.d.ts +38 -0
  38. package/dist/memory-session.js +97 -0
  39. package/dist/mission.d.ts +68 -0
  40. package/dist/mission.js +172 -0
  41. package/dist/provenance.d.ts +54 -0
  42. package/dist/provenance.js +182 -0
  43. package/dist/ratification.d.ts +113 -0
  44. package/dist/ratification.js +317 -0
  45. package/dist/reverse-xorida.d.ts +174 -0
  46. package/dist/reverse-xorida.js +490 -0
  47. package/dist/session.d.ts +102 -0
  48. package/dist/session.js +269 -0
  49. package/dist/state-serializer.d.ts +37 -0
  50. package/dist/state-serializer.js +294 -0
  51. package/dist/store-memory.d.ts +18 -0
  52. package/dist/store-memory.js +29 -0
  53. package/dist/trust.d.ts +76 -0
  54. package/dist/trust.js +121 -0
  55. package/dist/types.d.ts +320 -0
  56. package/dist/types.js +56 -0
  57. package/llms.txt +43 -0
  58. package/package.json +125 -0
  59. package/share1.dat +0 -0
package/README.md ADDED
@@ -0,0 +1,601 @@
1
+ # @private.me/xcontinuity
2
+
3
+ [![License: Proprietary](https://img.shields.io/badge/License-Proprietary-red.svg)](./LICENSE.md)
4
+ [![Version: v2.1.0](https://img.shields.io/badge/version-2.1.0-blue.svg)](./CHANGELOG.md)
5
+
6
+ Cryptographic state continuity for AI agents — Reverse-XorIDA with trust substrate, provenance, and enforcement.
7
+
8
+ ## Features
9
+
10
+ - **Reverse-XorIDA** — incremental state updates at O(delta) cost exploiting GF(2) linearity
11
+ - **XorIDA threshold sharing** — k-of-n split for fault-tolerant state persistence
12
+ - **TLV serialization** — compact binary state encoding with SHA-256 integrity
13
+ - **SessionManager** — lifecycle controller (active/suspended/closed) combining all layers
14
+ - **Chronicle** — ordered state history with contradiction detection
15
+ - **Runtime memory** — ephemeral in-process key-value store with LRU eviction
16
+ - **Session memory** — XorIDA-persisted state layer with incremental updates
17
+ - **Trust substrate** (v2.0.0) — provenance, trust tiers, adjudication, ratification
18
+ - **Mission & enforcement** (v2.0.0) — human-anchored goals with constraint checking
19
+ - **7 algebraic extensions** (v2.0.0) — undo, branching, squashing, blind updates, share refresh, blind equality, network-coded sync
20
+ - **TTL decay** (v2.0.0) — ratified entries auto-downgrade after configurable maxAge
21
+ - **Event hooks** (v2.0.0) — reactive onChange, onContradiction, onTierChange, onEscalation
22
+ - **Cascade / sub-agent architecture** (v2.1.0) — parent-child session hierarchies with trust delegation
23
+ - **SubAgentCoordinator** (v2.1.0) — lifecycle management for spawning, merging, and shutting down sub-agents
24
+ - **2 internal dependencies** — @private.me/shared + @private.me/crypto (no third-party npm packages)
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install @private.me/xcontinuity
30
+ ```
31
+
32
+ ## Dependencies
33
+
34
+ **Runtime Dependencies:**
35
+ - **@private.me/shared** — Result<T,E> error handling primitives
36
+ - **@private.me/crypto** — XorIDA threshold sharing, HMAC, padding, UUID
37
+
38
+ **Platform Dependencies:**
39
+ - **Web Crypto API** — crypto.subtle with Ed25519 support (Node.js 16.9+ and modern browsers)
40
+
41
+ ## Quick Start
42
+
43
+ ```typescript
44
+ import { SessionManager, MemoryStateStore } from '@private.me/xcontinuity';
45
+
46
+ // Create session with in-memory store
47
+ const store = new MemoryStateStore();
48
+ const session = SessionManager.create({ agentId: 'agent-001', store });
49
+
50
+ // Build up state
51
+ session.updateState({ model: 'gpt-4', temperature: 0.7 });
52
+ session.updateState({ conversationCount: 42 });
53
+
54
+ // Snapshot (XorIDA split + persist)
55
+ const snap = await session.snapshot('after-training');
56
+ if (!snap.ok) throw new Error(snap.error.message);
57
+
58
+ // Later: restore from snapshot
59
+ const restored = await session.restore(snap.value.stateId);
60
+ if (restored.ok) {
61
+ console.log(restored.value);
62
+ // { model: 'gpt-4', temperature: 0.7, conversationCount: 42 }
63
+ }
64
+
65
+ session.close();
66
+ ```
67
+
68
+ ### Quick Start: Trust-Aware Session
69
+
70
+ ```typescript
71
+ import {
72
+ SessionManager, MemoryStateStore, TrustStore,
73
+ MissionAuthority, MissionGuard, EnforcementLoop,
74
+ generateSigningKeyPair, publicKeyToAuthorRef,
75
+ } from '@private.me/xcontinuity';
76
+
77
+ // Set up trust substrate
78
+ const trustStore = new TrustStore({ defaultMaxAge: 7 * 24 * 60 * 60 * 1000 }); // 7-day TTL
79
+ const authority = new MissionAuthority();
80
+ const guard = new MissionGuard(authority);
81
+ const enforcement = new EnforcementLoop(guard, { escalationThreshold: 3 });
82
+
83
+ // Create trust-aware session
84
+ const store = new MemoryStateStore();
85
+ const session = SessionManager.create({
86
+ agentId: 'agent-001',
87
+ store,
88
+ trustStore,
89
+ missionGuard: guard,
90
+ enforcementLoop: enforcement,
91
+ });
92
+
93
+ // Subscribe to trust events
94
+ trustStore.on('contradiction', (event) => {
95
+ console.log(`Contradiction on key "${event.key}"`);
96
+ });
97
+
98
+ trustStore.on('tierChange', (event) => {
99
+ console.log(`${event.key}: ${event.oldTier} → ${event.newTier} (${event.reason})`);
100
+ });
101
+
102
+ // Writes now flow through trust substrate
103
+ session.updateState({ temperature: 0.8 });
104
+ ```
105
+
106
+ ## API Reference
107
+
108
+ ### SessionManager
109
+
110
+ ```typescript
111
+ import { SessionManager, MemoryStateStore } from '@private.me/xcontinuity';
112
+
113
+ const store = new MemoryStateStore();
114
+ const session = SessionManager.create({ agentId: 'agent-1', store });
115
+
116
+ session.updateState({ key: 'value' }); // Merge patch
117
+ session.setState({ newKey: 'newValue' }); // Replace entire state
118
+ const snap = await session.snapshot('desc'); // Persist as XorIDA shares
119
+ const state = await session.restore(snap.value.stateId);
120
+ await session.suspend(); // Auto-snapshot + suspend
121
+ const resumed = await session.resume(); // Restore latest + resume
122
+ session.close(); // Terminal
123
+
124
+ // Trust substrate accessors (v2.0.0)
125
+ session.getTrustStore(); // TrustStore | undefined
126
+ session.getMissionGuard(); // MissionGuard | undefined
127
+ session.getEnforcementLoop(); // EnforcementLoop | undefined
128
+ ```
129
+
130
+ ### Provenance (Ed25519 Signing)
131
+
132
+ ```typescript
133
+ import {
134
+ generateSigningKeyPair, signEntry, verifyEntry,
135
+ publicKeyToAuthorRef, canonicalEntryBytes,
136
+ hashProvenance, verifyChainLink,
137
+ } from '@private.me/xcontinuity';
138
+
139
+ const keyPair = await generateSigningKeyPair();
140
+ const authorRef = await publicKeyToAuthorRef(keyPair.publicKey);
141
+
142
+ // Sign an entry
143
+ const signed = await signEntry('temperature', 0.7, keyPair.privateKey, keyPair.publicKey);
144
+ if (signed.ok) {
145
+ const provenance = signed.value; // { author, timestamp, signature }
146
+
147
+ // Verify signature
148
+ const valid = await verifyEntry('temperature', 0.7, provenance, keyPair.publicKey);
149
+ console.log(valid.value); // true
150
+ }
151
+ ```
152
+
153
+ ### Trust Tiers
154
+
155
+ ```typescript
156
+ import {
157
+ baselineTier, effectiveTier, applyDecay, isDecayed,
158
+ applyContradictionDowngrade, compareTiers, isMoreTrusted,
159
+ } from '@private.me/xcontinuity';
160
+
161
+ // Assign tier based on provenance
162
+ baselineTier(provenance, true); // 'ratified' (signed + verified)
163
+ baselineTier(provenance, false); // 'quarantined' (signed but invalid)
164
+ baselineTier(undefined, false); // 'inherited' (no provenance)
165
+
166
+ // Contradiction downgrade
167
+ applyContradictionDowngrade('ratified', 1); // 'inherited'
168
+ applyContradictionDowngrade('inherited', 1); // 'quarantined'
169
+
170
+ // TTL decay
171
+ isDecayed(entry, Date.now()); // true if past maxAge
172
+ applyDecay(entry); // 'inherited' if decayed, else original tier
173
+ effectiveTier(entry); // decay + contradictions combined
174
+ ```
175
+
176
+ ### TrustStore (Ratification)
177
+
178
+ ```typescript
179
+ import { TrustStore, generateSigningKeyPair } from '@private.me/xcontinuity';
180
+
181
+ const store = new TrustStore({ defaultMaxAge: 30 * 24 * 60 * 60 * 1000 });
182
+
183
+ // Write (inherits trust tier from provenance)
184
+ store.write('fact', 'The sky is blue');
185
+
186
+ // Ratify (sign, promoting to 'ratified')
187
+ const keys = await generateSigningKeyPair();
188
+ await store.ratify('fact', keys.privateKey, keys.publicKey);
189
+
190
+ // Read with effective tier (applies decay + contradictions)
191
+ const entry = store.read('fact');
192
+
193
+ // Read only if trusted enough
194
+ const trusted = store.readAtTier('fact', 'ratified');
195
+
196
+ // Hypothesis (sandbox for speculative writes)
197
+ const hyp = store.hypothesisMode();
198
+ hyp.write('speculative', 'maybe true');
199
+ hyp.commit(); // merge into main store
200
+ // or: hyp.discard(); // abandon changes
201
+
202
+ // Event hooks
203
+ store.on('change', (e) => console.log(e.key, e.newEntry));
204
+ store.on('contradiction', (e) => console.log(e.key));
205
+ store.on('tierChange', (e) => console.log(e.oldTier, '→', e.newTier));
206
+ store.removeAllListeners();
207
+ ```
208
+
209
+ ### Adjudicator (Conflict Resolution)
210
+
211
+ ```typescript
212
+ import { PolicyAdjudicator, ConsensusAdjudicator } from '@private.me/xcontinuity';
213
+
214
+ // Policy: highest tier → newest timestamp → lowest author DID
215
+ const policy = new PolicyAdjudicator();
216
+ const result = policy.resolve('key', [entryA, entryB]);
217
+ if (result.ok) console.log(result.value.winner, result.value.reason);
218
+
219
+ // Consensus: multi-agent with quorum
220
+ const consensus = new ConsensusAdjudicator(viewProvider);
221
+ const async_result = await consensus.resolveAsync('key', [entryA]);
222
+ ```
223
+
224
+ ### Mission & Enforcement
225
+
226
+ ```typescript
227
+ import {
228
+ MissionAuthority, MissionGuard, EnforcementLoop,
229
+ AlignmentAdjudicator, PolicyAdjudicator,
230
+ } from '@private.me/xcontinuity';
231
+
232
+ // Set up mission authority
233
+ const authority = new MissionAuthority();
234
+ authority.loadTrustedMission({
235
+ missionId: 'm-1',
236
+ goal: 'Analyze customer data without PII exposure',
237
+ authority: authorRef,
238
+ signature: new Uint8Array(64),
239
+ issuedAt: Date.now(),
240
+ scopes: ['read:*', 'write:analysis'],
241
+ });
242
+
243
+ // Guard with constraints
244
+ const guard = new MissionGuard(authority);
245
+ guard.addConstraint({
246
+ constraintId: 'no-pii',
247
+ description: 'Block writes containing PII',
248
+ evaluate: (action) => ({ allowed: !containsPII(action.value) }),
249
+ });
250
+
251
+ // Enforcement loop
252
+ const enforcement = new EnforcementLoop(guard, { escalationThreshold: 3 });
253
+ const check = enforcement.check({ author: 'agent-1', type: 'write', key: 'output', value: data });
254
+ // check.value.decision: 'allow' | 'reject' | 'rewrite' | 'escalate'
255
+
256
+ // Alignment adjudicator (wraps any adjudicator with mission checks)
257
+ const aligned = new AlignmentAdjudicator(new PolicyAdjudicator(), guard);
258
+ ```
259
+
260
+ ### Cascade / Sub-Agent Architecture (v2.1.0)
261
+
262
+ ```typescript
263
+ import {
264
+ CascadeSession, SubAgentCoordinator,
265
+ SessionManager, TrustStore, MemoryStateStore,
266
+ } from '@private.me/xcontinuity';
267
+
268
+ // Create root cascade session
269
+ const rootStore = new MemoryStateStore();
270
+ const trustStore = new TrustStore();
271
+ const rootSession = SessionManager.create({ agentId: 'orchestrator', store: rootStore, trustStore });
272
+ const root = new CascadeSession(rootSession, trustStore);
273
+
274
+ // Write shared context
275
+ trustStore.write('shared-context', 'market analysis data');
276
+
277
+ // Spawn a child with inherited trust
278
+ const childResult = root.spawnChild('analyst-agent', new MemoryStateStore(), {
279
+ propagation: 'inherit', // inherit parent trust entries
280
+ maxChildTier: 'inherited', // cap child tier at inherited
281
+ maxDepth: 3, // max 3 levels of nesting
282
+ escalateToParent: true, // child violations propagate up
283
+ });
284
+
285
+ if (childResult.ok) {
286
+ const child = childResult.value;
287
+ // Child automatically has parent's trust entries (at inherited tier)
288
+ child.getTrustStore().write('analysis-result', 'positive outlook');
289
+
290
+ // Merge child state back into parent
291
+ const childId = child.getSession().session.sessionId;
292
+ root.mergeChild(childId);
293
+ // root.getTrustStore() now has 'analysis-result'
294
+ }
295
+
296
+ // SubAgentCoordinator for managing multiple sub-agents
297
+ const coord = new SubAgentCoordinator(root, { maxAgents: 5, autoMerge: true });
298
+
299
+ const worker1 = coord.spawn('worker-1', new MemoryStateStore());
300
+ const worker2 = coord.spawn('worker-2', new MemoryStateStore());
301
+
302
+ // Complete and auto-merge
303
+ if (worker1.ok) coord.complete(worker1.value.getSession().session.sessionId);
304
+
305
+ // Shutdown all
306
+ coord.shutdown();
307
+ ```
308
+
309
+ ### Memory Layers
310
+
311
+ ```typescript
312
+ import { RuntimeMemory, SessionMemory, MemoryStateStore } from '@private.me/xcontinuity';
313
+
314
+ // Ephemeral in-process memory with LRU eviction
315
+ const runtime = new RuntimeMemory({ maxEntries: 1000 });
316
+ runtime.set('key', 'value');
317
+ const val = runtime.get('key');
318
+
319
+ // Session-persisted memory backed by XorIDA shares
320
+ const store = new MemoryStateStore();
321
+ const sessionMem = new SessionMemory(store);
322
+ await sessionMem.save({ counter: 42 });
323
+ const restored = await sessionMem.load();
324
+ ```
325
+
326
+ ### Error Handling
327
+
328
+ ```typescript
329
+ import { ok, err, continuityError, ERROR_DETAILS } from '@private.me/xcontinuity';
330
+
331
+ // Result<T, E> pattern — all fallible functions return Result
332
+ const success = ok({ data: 'value' });
333
+ const failure = err(continuityError('SESSION_CLOSED'));
334
+
335
+ if (!success.ok) {
336
+ console.log(success.error.code); // error code
337
+ }
338
+
339
+ // Error details lookup
340
+ const details = ERROR_DETAILS['HMAC_FAILURE'];
341
+ console.log(details); // { family: 'Split', description: 'HMAC verification failed' }
342
+ ```
343
+
344
+ ### Hypothesis Mode (Speculative Writes)
345
+
346
+ ```typescript
347
+ import { TrustStore, Hypothesis } from '@private.me/xcontinuity';
348
+
349
+ const store = new TrustStore();
350
+ store.write('fact', 'known value');
351
+
352
+ // Hypothesis: sandbox for speculative writes
353
+ const hyp = store.hypothesisMode();
354
+ hyp.write('speculative', 'maybe true');
355
+ hyp.write('fact', 'override attempt');
356
+
357
+ // Inspect without affecting main store
358
+ const specVal = hyp.read('speculative'); // { value: 'maybe true', ... }
359
+
360
+ // Commit merges into main store
361
+ hyp.commit();
362
+ // Or: hyp.discard() to abandon changes
363
+ ```
364
+
365
+ ### Reverse-XorIDA Extensions (v2.0.0)
366
+
367
+ ```typescript
368
+ import {
369
+ undoDelta, branchState, squashDeltas,
370
+ blindUpdateShare, refreshShares,
371
+ blindEqual, networkCodeShares, networkDecodeShare,
372
+ } from '@private.me/xcontinuity';
373
+
374
+ // Undo: XOR is self-inverse
375
+ undoDelta(currentShares, deltaShares, prevStateId, hmacKey, hmacSig);
376
+
377
+ // Branch: independent copy of split state
378
+ const branch = branchState(splitState, 'branch-1');
379
+
380
+ // Squash: combine sequential deltas
381
+ const squashed = squashDeltas([delta1, delta2, delta3]);
382
+
383
+ // Blind update: update share without seeing plaintext
384
+ blindUpdateShare(share, deltaData, newId, hmacKey, hmacSig);
385
+
386
+ // Refresh: re-randomize shares preserving plaintext
387
+ const refreshed = await refreshShares(splitState);
388
+
389
+ // Blind equality: compare states without decryption
390
+ const equal = blindEqual(stateA, stateB);
391
+
392
+ // Network coding: combine shares for bandwidth efficiency
393
+ const coded = networkCodeShares([share1, share2]);
394
+ const decoded = networkDecodeShare(coded.value, share1);
395
+ ```
396
+
397
+ ### State Serialization
398
+
399
+ ```typescript
400
+ import { serializeState, deserializeState, statesEqual } from '@private.me/xcontinuity';
401
+
402
+ const snapResult = await serializeState({ counter: 42 }, metadata);
403
+ const desResult = await deserializeState(snapResult.value);
404
+ const equal = statesEqual({ a: 1 }, { a: 1 }); // true
405
+ ```
406
+
407
+ ### Chronicle (with Contradiction Detection)
408
+
409
+ ```typescript
410
+ import { Chronicle, detectContradiction } from '@private.me/xcontinuity';
411
+
412
+ const chronicle = new Chronicle();
413
+
414
+ // Append with contradiction check
415
+ const contradictions = chronicle.appendWithContradictionCheck(
416
+ entry, 'temperature', 0.8, 0.7 // old value was 0.7, new is 0.8
417
+ );
418
+ if (contradictions.length > 0) {
419
+ console.log('Contradictions:', contradictions);
420
+ }
421
+
422
+ // Query
423
+ const results = chronicle.query({ tags: ['checkpoint'], limit: 10 });
424
+ const forKey = chronicle.getContradictionsForKey('temperature');
425
+ ```
426
+
427
+ ### Constants
428
+
429
+ ```typescript
430
+ import {
431
+ VERSION, DEFAULT_SPLIT_CONFIG, DEFAULT_MAX_AGE,
432
+ DEFAULT_ENFORCEMENT_CONFIG, TRUST_TIER_RANK,
433
+ } from '@private.me/xcontinuity';
434
+
435
+ console.log(VERSION); // '2.1.0'
436
+ console.log(DEFAULT_SPLIT_CONFIG); // { n: 3, k: 2 }
437
+ console.log(DEFAULT_MAX_AGE); // 2592000000 (30 days ms)
438
+ console.log(DEFAULT_ENFORCEMENT_CONFIG); // { escalationThreshold: 3 }
439
+ console.log(TRUST_TIER_RANK); // { ratified: 3, inherited: 2, quarantined: 1 }
440
+ ```
441
+
442
+ ## Reverse-XorIDA
443
+
444
+ The novel contribution: exploiting `split(A XOR B) = split(A) XOR split(B)` over GF(2).
445
+
446
+ When updating state, instead of re-splitting the entire state:
447
+ 1. Compute `delta = oldPadded XOR newPadded`
448
+ 2. Split only the delta: `deltaShares = split(delta)`
449
+ 3. XOR each old share with the delta share: `newShares[i] = oldShares[i] XOR deltaShares[i]`
450
+
451
+ Cost: O(delta) instead of O(state). HMAC is recomputed fresh for integrity.
452
+
453
+ ## Trust Substrate (v2.0.0)
454
+
455
+ Six-layer architecture for trust-annotated state management:
456
+
457
+ ```
458
+ ┌─────────────────────────────────────┐
459
+ │ SubAgentCoordinator (v2.1.0) │ Multi-agent lifecycle
460
+ ├─────────────────────────────────────┤
461
+ │ CascadeSession (v2.1.0) │ Parent-child trust delegation
462
+ ├─────────────────────────────────────┤
463
+ │ SessionManager (Public API) │ Optional trust integration
464
+ ├─────────────────────────────────────┤
465
+ │ Mission + Enforcement │ Human-anchored goals
466
+ ├─────────────────────────────────────┤
467
+ │ TrustStore (Ratification) │ Write/ratify/restore + events
468
+ ├─────────────────────────────────────┤
469
+ │ Adjudicator │ Policy or consensus resolution
470
+ ├─────────────────────────────────────┤
471
+ │ Trust Tiers + Chronicle │ Tier management + history
472
+ ├─────────────────────────────────────┤
473
+ │ Provenance (Ed25519) │ Signed entries + chain links
474
+ └─────────────────────────────────────┘
475
+ ```
476
+
477
+ ### State Store
478
+
479
+ ```typescript
480
+ import { MemoryStateStore, splitState, reconstructState, serializeState } from '@private.me/xcontinuity';
481
+
482
+ // In-memory store (async interface for future backends)
483
+ const store = new MemoryStateStore();
484
+
485
+ // Manual split/reconstruct cycle
486
+ const metadata = { agentId: 'a1', sessionId: 's1', sequenceNumber: 0, createdAt: Date.now(), tags: [] };
487
+ const serialized = await serializeState({ model: 'gpt-4', temp: 0.7 }, metadata);
488
+ if (serialized.ok) {
489
+ const split = await splitState(serialized.value, { k: 2, n: 3 });
490
+ if (split.ok) {
491
+ // Reconstruct from any 2-of-3 shares
492
+ const restored = await reconstructState([split.value.shares[0], split.value.shares[2]]);
493
+ }
494
+ }
495
+ ```
496
+
497
+ ### TLV Constants
498
+
499
+ ```typescript
500
+ import { CONTINUITY_TLV, VALUE_TYPE } from '@private.me/xcontinuity';
501
+
502
+ // TLV type tags for binary serialization
503
+ console.log(CONTINUITY_TLV); // { STATE_ENTRY: 0x01, CHECKSUM: 0x02, ... }
504
+ console.log(VALUE_TYPE); // { STRING: 0x01, NUMBER: 0x02, BOOLEAN: 0x03, ... }
505
+ ```
506
+
507
+ ## Session Lifecycle
508
+
509
+ ```
510
+ create() → active → snapshot()/restore() → suspend() → resume() → close()
511
+ ```
512
+
513
+ - **active** — accepting state updates and snapshots
514
+ - **suspended** — state persisted, no updates allowed
515
+ - **closed** — terminal, no further operations
516
+
517
+ ## Error Reference
518
+
519
+ All fallible functions return `Result<T, ContinuityError>` with structured error codes.
520
+
521
+ | Error Code | Family | Description |
522
+ |---|---|---|
523
+ | `SERIALIZE_FAILED` | Serialization | State serialization failed |
524
+ | `DESERIALIZE_FAILED` | Serialization | TLV data corrupt or unsupported |
525
+ | `CHECKSUM_MISMATCH` | Serialization | SHA-256 verification failed |
526
+ | `SPLIT_FAILED` | Split | XorIDA threshold split failed |
527
+ | `RECONSTRUCT_FAILED` | Split | Share reconstruction failed |
528
+ | `HMAC_FAILURE` | Split | HMAC verification failed |
529
+ | `INSUFFICIENT_SHARES` | Split | Not enough shares for threshold |
530
+ | `SESSION_CLOSED` | Session | Operation on closed session |
531
+ | `SESSION_SUSPENDED` | Session | Operation on suspended session |
532
+ | `NO_SNAPSHOTS` | Session | No snapshots to restore |
533
+ | `SNAPSHOT_NOT_FOUND` | Session | State ID not in store |
534
+ | `INVALID_SIGNATURE` | Provenance | Ed25519 verification failed |
535
+ | `MISSING_AUTHOR` | Provenance | No author in provenance record |
536
+ | `HASH_CHAIN_BREAK` | Provenance | Parent hash chain gap |
537
+ | `CONTRADICTION_DETECTED` | Trust | Incompatible value for same key |
538
+ | `TRUST_DECAY_EXPIRED` | Trust | Entry past maxAge TTL |
539
+ | `CONSENSUS_FAILED` | Adjudicator | Multi-agent consensus failed |
540
+ | `QUORUM_NOT_MET` | Adjudicator | Insufficient views for quorum |
541
+ | `CONSTRAINT_VIOLATION` | Mission | Action violates hard constraint |
542
+ | `AUTHORITY_EXPIRED` | Mission | Mission signature expired |
543
+ | `SCOPE_EXCEEDED` | Mission | Action outside mission scope |
544
+ | `ACTION_REJECTED` | Enforcement | Action rejected by enforcement |
545
+ | `ESCALATION_TRIGGERED` | Enforcement | Repeated violations, human review |
546
+
547
+ ## Export Control Notice
548
+
549
+ This package uses cryptographic algorithms (XorIDA threshold sharing, HMAC-SHA256, SHA-256, Ed25519) implemented via the Web Crypto API. Export, re-export, and transfer of cryptographic software may be subject to regulation under the Export Administration Regulations (EAR) and the International Traffic in Arms Regulations (ITAR). Users are responsible for compliance with all applicable export control laws.
550
+
551
+ ## Security
552
+
553
+ See [SECURITY.md](./SECURITY.md) for vulnerability reporting and security architecture.
554
+
555
+ ## Purchasing
556
+
557
+ Subscribe via the platform:
558
+
559
+ ```bash
560
+ curl -X POST https://private.me/aci/purchase \
561
+ -H 'Content-Type: application/json' \
562
+ -d '{"product":"xcontinuity","tier":"pro"}'
563
+ ```
564
+
565
+ **Response (success):**
566
+ ```json
567
+ { "checkoutUrl": "https://checkout.stripe.com/..." }
568
+ ```
569
+
570
+ **Response (error — RFC 7807):**
571
+ ```json
572
+ {
573
+ "type": "https://private.me/errors/invalid-tier",
574
+ "title": "Invalid tier",
575
+ "status": 400,
576
+ "detail": "Tier must be one of: free, pro"
577
+ }
578
+ ```
579
+
580
+ | Tier | Operations | Price |
581
+ |------|-----------|-------|
582
+ | Free | 100K/month | No credit card required |
583
+ | Pro | Unlimited | See [pricing](../../docs/pricing-reference.md) |
584
+
585
+ ## Pricing
586
+
587
+ **Free Tier:** 100K operations/month with full platform access
588
+ **Pro Tier:** Unlimited operations with SLA and priority support
589
+
590
+ See [pricing details](https://private.me/subscribe?product=xcontinuity) or [internal reference](../../docs/pricing-reference.md).
591
+
592
+ [Subscribe to xcontinuity](https://private.me/subscribe?product=xcontinuity)
593
+
594
+ ## Legal
595
+
596
+ - **Terms of Service**: https://private.me/terms
597
+ - **Privacy Policy**: https://private.me/privacy
598
+
599
+ ## License
600
+
601
+ Proprietary — Copyright © 2024-2026 Standard Clouds, Inc. (Private.Me) All rights reserved.
@@ -0,0 +1,75 @@
1
+ /**
2
+ * @private.me/xcontinuity — Adjudicator (Conflict Resolution)
3
+ *
4
+ * Resolves conflicts when multiple entries exist for the same key.
5
+ *
6
+ * Two implementations:
7
+ * PolicyAdjudicator — deterministic local resolution (default)
8
+ * ConsensusAdjudicator — multi-agent IXorIDA-backed resolution
9
+ *
10
+ * Deterministic tiebreaker (total ordering):
11
+ * 1. Highest trust tier
12
+ * 2. Newest timestamp
13
+ * 3. Lexicographically lowest author DID
14
+ *
15
+ * This guarantees two agents merging the same conflicting entries
16
+ * always pick the same winner — convergent merge without human input.
17
+ */
18
+ import type { Result } from '@private.me/shared';
19
+ import type { MemoryEntry, AdjudicatorResult, AgentView } from './types.js';
20
+ import type { ContinuityError } from './errors.js';
21
+ /** Interface for conflict resolution strategies. */
22
+ export interface Adjudicator {
23
+ /**
24
+ * Resolve a conflict between candidate entries for the same key.
25
+ *
26
+ * @param key - The contested key
27
+ * @param candidates - Competing entries for this key
28
+ * @returns The winning entry with reason
29
+ */
30
+ resolve(key: string, candidates: readonly MemoryEntry[]): Result<AdjudicatorResult, ContinuityError>;
31
+ }
32
+ /**
33
+ * Interface for gathering views from multiple agents (used by ConsensusAdjudicator).
34
+ */
35
+ export interface ViewProvider {
36
+ /**
37
+ * Gather views from participating agents for a contested key.
38
+ *
39
+ * @param key - The key being contested
40
+ * @returns Views from each participating agent
41
+ */
42
+ gatherViews(key: string): Promise<readonly AgentView[]>;
43
+ }
44
+ /**
45
+ * Policy-based adjudicator (default).
46
+ *
47
+ * Deterministic resolution using total ordering:
48
+ * 1. Highest effective trust tier (with decay applied)
49
+ * 2. Newest timestamp (higher = more recent)
50
+ * 3. Lexicographically lowest author DID (deterministic tiebreaker)
51
+ */
52
+ export declare class PolicyAdjudicator implements Adjudicator {
53
+ resolve(key: string, candidates: readonly MemoryEntry[]): Result<AdjudicatorResult, ContinuityError>;
54
+ }
55
+ /**
56
+ * Consensus-based adjudicator for multi-agent scenarios.
57
+ *
58
+ * Gathers views from participating agents via ViewProvider,
59
+ * then applies majority voting with policy fallback.
60
+ * Requires a quorum (> 50% of views must agree).
61
+ */
62
+ export declare class ConsensusAdjudicator implements Adjudicator {
63
+ private readonly viewProvider;
64
+ private readonly policyFallback;
65
+ constructor(viewProvider: ViewProvider);
66
+ resolve(key: string, candidates: readonly MemoryEntry[]): Result<AdjudicatorResult, ContinuityError>;
67
+ /**
68
+ * Async resolution with full multi-agent consensus.
69
+ *
70
+ * @param key - The contested key
71
+ * @param candidates - Local candidates
72
+ * @returns Consensus-resolved winner
73
+ */
74
+ resolveAsync(key: string, candidates: readonly MemoryEntry[]): Promise<Result<AdjudicatorResult, ContinuityError>>;
75
+ }