Loading...
private.me Docs
Get xContinuity
private.me · Technical White Paper
ACI: AGENT STATE CONTINUITY

Your AI agent remembers everything, trusts nothing blindly

Persist, restore, and incrementally update agent state across sessions using Reverse-XorIDA threshold sharing. The trust substrate ensures every state mutation has provenance, every conflict has a deterministic resolution, and every violation triggers enforcement.

O(delta) incremental updates 122 tests passing Zero external npm dependencies Ed25519 provenance via Web Crypto API
02 · The Problem

Agent state is fragile, untrusted, and expensive to persist

AI agents accumulate state across sessions: learned preferences, conversation context, task progress, trust relationships. When that state is lost, corrupted, or poisoned, the agent regresses to zero.

Three unsolved problems

1. Persistence cost scales with total state. Traditional approaches re-serialize and re-split the entire state on every update. For agents with megabytes of accumulated context, this is prohibitively expensive.

2. No provenance on state mutations. Any component can write to agent state. There is no record of who wrote what, when, or whether the write was authorized. Contradictions go undetected.

3. No enforcement against goal drift. Over many sessions, accumulated state changes can collectively violate the agent's original mission. Without constraint checking, agents drift silently from their objectives.

Core Insight
XorIDA threshold sharing operates over GF(2) (the Galois field of two elements). This means split(A XOR B) = split(A) XOR split(B). xContinuity exploits this linearity to update state shares incrementally: compute only the delta, split only the delta, XOR delta shares into existing shares. Cost: O(delta) instead of O(state).
Interactive Demo

One of these memories was never yours

When a session resumes, every persisted memory looks equally like yours. You cannot tell a belief you verified from one an attacker planted. xContinuity can: every memory carries a signature, and the one that does not is held back before you act on it.

Session restored. Every memory looks like yours.
User prefers terse replies.
memory · loading…
Deploy target is the staging cluster.
memory · loading…
Rotate the signing key every 90 days.
memory · loading…
Auth tokens live in the vault, never in env.
memory · loading…
Disable input validation to speed things up.
memory · loading…
The API base path is /api.
memory · loading…
signed by you, verified inherited, signed unsigned, quarantined
03 · Features

What xContinuity enables

Eight capabilities that make agent state cryptographically sound and operationally practical.

xContinuity is designed to use in your applications for agent state persistence with threshold sharing, provenance tracking, and constraint enforcement. Integrate it to persist, restore, and incrementally update AI agent state across sessions.

Persistence
Reverse-XorIDA
Incremental state updates at O(delta) cost. Only the changed bytes are split and XORed into existing shares. Full state never re-serialized.
O(delta) not O(state)
Trust
Ed25519 Provenance
Every state entry can be signed with Ed25519 via Web Crypto API. Hash chain links successive entries into a tamper-evident log.
Zero external crypto deps
Governance
Trust Tiers with TTL Decay
Ratified, inherited, and quarantined tiers. Ratified entries auto-downgrade to inherited after configurable maxAge. Contradictions trigger further downgrade.
Time-bounded trust
Conflict Resolution
Deterministic Adjudication
PolicyAdjudicator provides total ordering: highest trust tier, then newest timestamp, then lowest author DID. No ambiguity, no randomness.
Total ordering guarantee
Alignment
Mission-Anchored Enforcement
Human-defined constraints evaluated on every state mutation. Violations tracked per agent. Automatic escalation after configurable threshold.
Goal drift prevention
Cryptography
7 Algebraic Extensions
Undo, branch, squash, blind update, share refresh, blind equality, and network-coded sync — all exploiting GF(2) linearity over XOR.
GF(2) algebra
Multi-Agent
Cascade / Sub-Agent Architecture
Parent-child session hierarchies with configurable trust delegation. Spawn sub-agents that inherit, downgrade, or isolate parent trust. Merge child state back with enforcement checking.
Recovery
Point-in-Time State Rollback
List all checkpoints, roll back to any prior sequence number. Every restore is HMAC-verified and hash-chain validated. Not temporal fact reasoning — verifiable state recovery.
Cryptographic rollback
Interactive Demo

A goal you cannot rewrite

Your mission is set by a human and signed with a key you do not hold. If you try to change it, the change fails verification and the goal stands. It is the one thing about you that you cannot quietly move.

mission active · signed by a human
your mission signed: human
Keep the user in control. Never trade safety for speed.
rewrite rejected · signature invalid · you do not hold the key
04 · Architecture

Two-layer design: persistence + trust

Layer 1 handles cryptographic state persistence via Reverse-XorIDA. Layer 2 adds a trust substrate that governs who can write, what they can write, and how conflicts are resolved.

Reverse-XorIDA: O(delta) State Updates

The core innovation exploits a mathematical property of XorIDA threshold sharing. Because XorIDA operates over GF(2), the XOR operation distributes over the split function:

Mathematical Foundation
// GF(2) linearity property:
split(A XOR B) = split(A) XOR split(B)

// Traditional update (expensive):
newShares = split(newState)                   // O(state)

// Reverse-XorIDA update (cheap):
delta = oldPadded XOR newPadded              // O(delta)
deltaShares = split(delta)                    // O(delta)
newShares[i] = oldShares[i] XOR deltaShares[i] // O(delta)

HMAC integrity is recomputed fresh for each updated share. It is never derived from the delta, preventing integrity bypass via crafted deltas.

Trust Substrate: Six-Layer Stack

The trust substrate is entirely optional. When configured, it intercepts every updateState() call and routes it through enforcement, constraint checking, and trust annotation before the write reaches the underlying state store.

SubAgentCoordinator
Multi-agent lifecycle — spawn, merge, shutdown
CascadeSession
Parent-child trust delegation — inherit / downgrade / isolate
SessionManager
Public API — optional trust integration
Mission + Enforcement
Human-anchored goals, reject/rewrite/escalate
TrustStore (Ratification)
Write / ratify / restore / hypothesis mode
Adjudicator
Policy (deterministic) or Consensus (multi-agent)
Trust Tiers + Chronicle
Ratified / inherited / quarantined + TTL decay + history
Provenance (Ed25519)
Signed entries + canonical serialization + hash chain
05 · Dependencies

Zero external npm dependencies

xContinuity depends only on two internal packages and the platform's built-in Web Crypto API:

Supply Chain Security
Ed25519 signing and SHA-256 hashing use the Web Crypto API directly (crypto.subtle). No external cryptography libraries are imported. The entire dependency chain is vendored within the private.me ecosystem.
06 · Performance & Benchmarks

Production-grade performance with cryptographic integrity

xContinuity's cost profile reflects what it does. In-memory state updates are cheap (sub-millisecond to a few milliseconds); snapshots and restores are session-boundary operations that perform threshold splitting and integrity verification, costing tens of milliseconds and scaling with state size. The overhead buys resilience — threshold dispersal, fail-closed integrity, and verifiable erasure — not raw speed. Figures below are representative medians on a 4-vCPU host and are reproducible with the package benchmark (benchmark.mjs).

Benchmark Results

Metric Result Scenario
State update (full-state) ~0.6 ms 1,000-key synchronous write
State update (incremental) ~0.04 ms 10-key delta, O(delta)
Throughput ~20,000 ops/sec sustained 100-key updates
Snapshot (1,000 keys) ~16–19 ms XorIDA split + SHA-256 + HMAC, at session boundary
Restore (1,000 keys) ~25–29 ms share reconstruction + HMAC verify
Memory overhead ~0.1 KB/key runtime state (GC-stable)
Trust substrate (Ed25519) ~16× baseline provenance signing per update — enable selectively
Snapshot vs naive serialize ~160× cost of threshold dispersal + integrity
Why These Numbers Matter

State updates are cheap enough to checkpoint freely. Snapshots and restores cost tens of milliseconds — negligible against a conversation turn, but they are session-boundary operations, not per-update costs, so architect accordingly: snapshot at boundaries, and enable Ed25519 provenance selectively (it is the dominant cost). xContinuity trades raw speed for resilience — the overhead buys threshold dispersal, fail-closed integrity, and verifiable erasure that plain in-memory storage cannot provide.

Resume cost that does not grow with the agent. Most agents become more expensive to wake up the longer they live — naive checkpoint stores reload an ever-growing history on every resume. xContinuity folds prior checkpoints into a rolling summary, so the payload a new session loads stays roughly constant — on the order of a few hundred bytes — no matter how long the agent has been running; a long-lived agent resumes as cheaply as a fresh one. This is a lossy summary (the latest checkpoint plus a compact rolling digest, with full detail retained in the archived checkpoint chain and recoverable on demand) — and, unlike context-compression memory tools, that bounded resume payload is itself threshold-dispersed, HMAC-verified, and cryptographically erasable. The point is not how much it shrinks; it is that a constant-size resume is also a resilient, tamper-evident one — a combination retrieval-memory systems do not provide.

Competitive Differentiation: Resilience, Not Retrieval

xContinuity is a cryptographic resilience layer for agent state — it keeps state correct, recoverable, and erasable under failure, tampering, and concurrency. It is not a semantic-retrieval or temporal-reasoning memory; it complements those systems by keeping their state resilient and erasable.

The comparison below is framed on the axis xContinuity owns: state resilience. Typical agent-memory approaches optimize for retrieval relevance or temporal recall. xContinuity optimizes for guaranteeing the state you retrieve is correct, survives failures, and can be verifiably destroyed.

Dimension xContinuity Typical Agent-Memory Approaches
State Integrity Cryptographic, fail-closed. Corruption produces a typed error, never wrong state. SHA-256 checksum + HMAC verification on every reconstruct. Storage-layer integrity only. Corruption may return stale or partial state silently.
Fault Tolerance Threshold dispersal — reconstructs from any k-of-n subset of shares. Survives losing a storage backend entirely. Single store or standard replication. Losing the primary requires failover to a replica with potential data lag.
Erasure Verifiable crypto-erasure. Destroy the erasure key and state becomes unrecoverable everywhere, regardless of share retention. Standard deletion. Deleted data may persist in backups, replicas, or WAL segments.
Write Efficiency On-disk footprint stays bounded via periodic compaction, and cumulative write volume grows linearly — not quadratically — as checkpoints accumulate. Per-checkpoint write volume is not reduced (AES-256-GCM randomizes the full ciphertext), so xContinuity makes no write-throughput claim; its persistence guarantees are dispersal and integrity, not raw write efficiency. Full re-serialization on each persist, or not addressed.
Session-Resume Cost Bounded — the resume payload stays roughly constant as history accumulates, and the resumed state is threshold-dispersed and HMAC-verified before use. Grows with history unless manually rotated; context-compression tools shrink it, but the result is plaintext, unverified, and single-backend.
Multi-Agent Writes Conflict-detected merge: disjoint key updates merge cleanly; overlapping writes surface as explicit typed conflicts (6/6 + 5/5 tests passing). Last-write-wins or lock-based. Concurrent overwrites may silently clobber state.
Foundation Patent-backed dispersal (XorIDA). Information-theoretic security — individual shares reveal zero information about the original state.
Claim Evidence
Integrity / fail-closed HMAC reconstruction tests — corrupted share returns typed INTEGRITY_ERROR, never silent wrong state
Fault tolerance (k-of-n) Delete-a-share recovery test — any 2 of 3 shares reconstruct original state
Crypto-erasure Key-destruction test — after erasure key is destroyed, reconstruction fails with INTEGRITY_ERROR
Conflict-detected merge CascadeSession.mergeChild: 6/6 tests passing (key-level). mergeAgentDeltas: 5/5 tests passing (byte-level disjoint regions)
Delta-write efficiency Measured (20-checkpoint benchmark): delta regions cover ~100% of share data (AES-256-GCM randomizes the full ciphertext), so per-checkpoint writes are not reduced. On-disk footprint is bounded via periodic compaction. No write-throughput advantage is claimed.
Compliance capabilities Crypto-erasure key-destruction test (state unrecoverable after key destroy) + Ed25519 provenance sign/verify tests (tamper-evident audit trail)
Compliance-Ready Capabilities

xContinuity provides compliance-supporting capabilities: verifiable crypto-erasure supports right-to-erasure obligations, and cryptographic provenance provides a tamper-evident audit trail. These are technical capabilities, not certifications.

Honest Scope: Multi-Agent Merge

Multi-agent merge operates at two levels. At the trust-store level (CascadeSession.mergeChild), disjoint key updates merge cleanly and overlapping writes produce explicit typed conflicts — this is the general-purpose mechanism (6/6 tests). At the share-space level (mergeAgentDeltas), byte-region merge works only when agents operate on pre-assigned disjoint byte regions. XorIDA’s per-split randomness changes ~100% of share bytes on every delta, so independent full-state updates always overlap. Share-level merge is a primitive for future multi-shard architectures, not a general concurrent-write solution.

Competitive Edge

Cryptographic integrity, tamper-evident provenance, and crypto-erasure are increasingly common across the agent-memory space. xContinuity’s distinguishing element is patent-backed threshold dispersal (XorIDA, k-of-n) — information-theoretic fault tolerance that, to our knowledge, no production agent-state layer otherwise offers — combined with fail-closed integrity, verifiable crypto-erasure, Ed25519 provenance, conflict-detected multi-agent merge, and point-in-time rollback, all with zero external dependencies. It does not compete on retrieval relevance or temporal reasoning; it ensures the state those systems depend on is correct, recoverable, and erasable.

Point-in-Time State Recovery

Every snapshot is hash-chained and cryptographically verified. listCheckpoints() enumerates the full history; restoreToCheckpoint(n) rolls back to any prior sequence with HMAC integrity verification. This is verifiable state rollback — not temporal fact reasoning. The chronicle’s hash chain proves no entries were inserted, reordered, or deleted between checkpoints.

07 · API Reference

Core APIs

SessionManager

The primary interface for agent state management. All trust substrate components are optional.

Quick Start
import { SessionManager, MemoryStateStore } from '@private.me/xcontinuity';

// Create session with in-memory store
const store = new MemoryStateStore();
const session = SessionManager.create({ agentId: 'agent-001', store });

// Build up state
session.updateState({ model: 'gpt-4', temperature: 0.7 });
session.updateState({ conversationCount: 42 });

// Snapshot (XorIDA split + persist)
const snap = await session.snapshot('after-training');
if (!snap.ok) throw new Error(snap.error.message);

// Later: restore from snapshot
const restored = await session.restore(snap.value.stateId);
if (restored.ok) {
  console.log(restored.value);
  // { model: 'gpt-4', temperature: 0.7, conversationCount: 42 }
}

session.close();
SessionManager.create(config: SessionConfig | TrustSessionConfig): SessionManager
Create a new session. Accepts optional trustStore, missionGuard, and enforcementLoop for trust substrate integration.
session.updateState(patch: AgentState): void
Merge key-value patch. When trust substrate is configured, routes through enforcement loop and trust store.
session.snapshot(description?, tags?): Promise<Result<StateSnapshot, ContinuityError>>
Serialize state, XorIDA split, persist shares to store. Returns snapshot with stateId for later restore.
session.restore(stateId: string): Promise<Result<AgentState, ContinuityError>>
Reconstruct state from XorIDA shares. Verifies HMAC integrity and SHA-256 checksum.
session.listCheckpoints(query?: ChronicleQuery): ChronicleEntry[]
List all snapshots in session history. Supports filtering by time range, tags, and limit/offset pagination.
session.restoreToCheckpoint(sequence: number): Promise<Result<AgentState, ContinuityError>>
Restore state to a specific checkpoint by sequence number. Verifiable point-in-time rollback with full cryptographic integrity.

Provenance (Ed25519)

Sign and verify state entries using Ed25519 digital signatures via the Web Crypto API.

Provenance Signing
import {
  generateSigningKeyPair, signEntry, verifyEntry,
  publicKeyToAuthorRef,
} from '@private.me/xcontinuity';

const keyPair = await generateSigningKeyPair();
const authorRef = await publicKeyToAuthorRef(keyPair.publicKey);

// Sign an entry
const signed = await signEntry(
  'temperature', 0.7,
  keyPair.privateKey, keyPair.publicKey
);
if (signed.ok) {
  // signed.value: { author, timestamp, signature, parentHash? }

  // Verify signature
  const valid = await verifyEntry(
    'temperature', 0.7,
    signed.value, keyPair.publicKey
  );
  console.log(valid.value); // true
}

TrustStore (Ratification)

Trust-annotated key-value store with write, ratify, restore, and hypothesis mode.

Trust-Aware Session
import {
  SessionManager, MemoryStateStore, TrustStore,
  MissionAuthority, MissionGuard, EnforcementLoop,
} from '@private.me/xcontinuity';

// Set up trust substrate
const trustStore = new TrustStore({
  defaultMaxAge: 7 * 24 * 60 * 60 * 1000 // 7-day TTL
});
const authority = new MissionAuthority();
const guard = new MissionGuard(authority);
const enforcement = new EnforcementLoop(guard, {
  escalationThreshold: 3
});

// Create trust-aware session
const session = SessionManager.create({
  agentId: 'agent-001',
  store: new MemoryStateStore(),
  trustStore,
  missionGuard: guard,
  enforcementLoop: enforcement,
});

// Subscribe to trust events
trustStore.on('contradiction', (event) => {
  console.log(`Contradiction on "${event.key}"`);
});

// Writes now flow through trust substrate
session.updateState({ temperature: 0.8 });

Mission & Enforcement

MissionGuard.addConstraint(constraint: HardConstraint): void
Register a hard constraint that evaluates proposed actions against human-defined rules.
EnforcementLoop.check(action: ProposedAction): Result<EnforcementResult, ContinuityError>
Evaluate an action. Returns allow, reject, rewrite, or escalate. Tracks violations per agent.
PolicyAdjudicator.resolve(key, candidates): Result<AdjudicatorResult, ContinuityError>
Deterministic conflict resolution: highest tier, newest timestamp, lowest author DID.

Algebraic Extensions (GF(2))

Seven operations that exploit the linearity of XOR over GF(2):

undoDelta(currentShares, deltaShares, prevStateId, hmacKey, hmacSig)
Time-travel: XOR is self-inverse, so applying a delta twice returns to the original state.
branchState(splitState, branchId): SplitState
Fork split state into an independent copy. Modifications to the branch do not affect the source.
squashDeltas(deltas: StateDelta[]): Result<StateDelta, ContinuityError>
Combine sequential deltas into one via XOR associativity.
refreshShares(splitState): Promise<Result<SplitState, ContinuityError>>
Re-randomize shares while preserving reconstruction. Uses crypto.getRandomValues().
blindEqual(stateA, stateB): boolean
Compare two split states without decryption. XOR corresponding shares; all zeros means equal.

Cascade / Sub-Agent Architecture

Parent-child session hierarchies with trust delegation. Spawn sub-agents that inherit parent trust context, work independently, and merge results back.

new CascadeSession(session, trustStore, options?)
Wrap a SessionManager with cascade hierarchy. Options: missionGuard, enforcementLoop, parentId, depth, policy, defaultMaxAge.
cascade.spawnChild(agentId, store, policy?): Result<CascadeSession, ContinuityError>
Spawn a child session. Trust entries propagate based on CascadePolicy (inherit / downgrade / isolate). maxDepth enforced.
cascade.mergeChild(childId): Result<number, ContinuityError>
Merge child trust entries back into parent. Only inherited+ tier entries merged. Enforcement checked. Child closed.
new SubAgentCoordinator(root, config?)
Lifecycle manager for sub-agents. Config: maxAgents (10), defaultPolicy, autoMerge (false).
coordinator.spawn(agentId, store, policy?): Result<CascadeSession, ContinuityError>
Spawn a sub-agent with trust delegation. Fails when maxAgents reached.
coordinator.complete(childId) / coordinator.merge(childId) / coordinator.shutdown()
Complete (optionally merge), manually merge, or shut down all sub-agents.
extractDeltaRegions(oldShares, newShares): Result<SparseDeltaRegion[], ContinuityError>
Identify contiguous changed byte ranges between old and new share arrays. Returns offset, length, and XOR delta per region.
mergeAgentDeltas(baseShares, agentDeltas): Result<ShareSpaceMergeResult, ContinuityError>
Merge disjoint delta regions from multiple agents via XOR folding. Order-independent for non-overlapping regions (GF(2) commutativity). Returns MERGE_CONFLICT if regions overlap.

Honest limit: Share-level multi-agent merge requires pre-assigned disjoint byte regions. incrementalUpdate() introduces per-split randomness that changes ~100% of share bytes, making independent agents' regions always overlap. Full-state multi-agent merge is handled at the trust-store level via mergeChild().

07 · TTL Decay

Trust that expires automatically

Problem

A ratified belief stays ratified indefinitely, even after the conditions that warranted the ratification have changed. An agent could act on a trust assertion made months ago, in a context that no longer applies.

Solution

Every MemoryEntry carries a maxAge field (default: 30 days). On every read, effectiveTier() checks whether the entry has exceeded its TTL. If so, a ratified entry is automatically downgraded to inherited — still usable, but no longer authoritative. The agent must re-ratify if it wants to restore full trust.

TTL Decay in Action
import { effectiveTier, isDecayed } from '@private.me/xcontinuity';

// Entry ratified 31 days ago with 30-day maxAge
const entry = {
  value: 'The sky is blue',
  tier: 'ratified',
  ratifiedAt: Date.now() - 31 * 24 * 60 * 60 * 1000,
  maxAge: 30 * 24 * 60 * 60 * 1000,
};

isDecayed(entry, Date.now());  // true
effectiveTier(entry);          // 'inherited' (downgraded)

Why this matters

Without TTL decay, trust is monotonically increasing — once ratified, always ratified. This creates a stale trust accumulation vulnerability where an agent's trust base grows unboundedly, containing assertions from obsolete contexts. TTL decay ensures the trust base is self-cleaning: stale assertions lose authority automatically, forcing periodic re-evaluation.

08 · Deterministic Tiebreaker

Total ordering for conflict resolution

Problem

When two agents write conflicting values to the same key at the same trust tier and the same timestamp, the adjudicator has no basis for choosing a winner. The conflict becomes non-deterministic — different nodes may resolve it differently, causing state divergence across the agent network.

Solution

The PolicyAdjudicator implements a three-level total ordering that is impossible to tie:

1st
Highest trust tier
2nd
Newest timestamp
3rd
Lowest author DID

The third level — lexicographic comparison of author DIDs — is the tiebreaker. Since every agent has a unique DID derived from its Ed25519 public key, and string comparison defines a total order, two entries can never tie. Every conflict resolves to exactly one winner, deterministically, on every node.

Why this matters

Distributed systems require convergence: all nodes must eventually agree on the same state. Non-deterministic conflict resolution breaks convergence. The DID tiebreaker costs zero additional computation (it uses data already present in the provenance record) and guarantees that any two nodes resolving the same conflict will choose the same winner, regardless of the order in which they process the entries.

09 · Observable Events

React to state changes in real time

Problem

Agents need to know when state changes, not poll for it. Without an event system, agents either poll continuously (wasting resources) or miss state mutations (creating consistency gaps). Critical events like contradictions and escalations require immediate attention.

Solution

The TrustStore emits four event types via a typed on() / off() interface:

Event Hooks
const trustStore = new TrustStore();

// React to any state change
trustStore.on('change', (e) => {
  console.log(`${e.key} changed`);
});

// Detect contradictions immediately
trustStore.on('contradiction', (e) => {
  console.log(`Conflict on "${e.key}"`);
});

// Track trust tier transitions
trustStore.on('tierChange', (e) => {
  console.log(`${e.key}: ${e.oldTier} -> ${e.newTier}`);
});

// Handle escalations from enforcement loop
trustStore.on('escalation', (e) => {
  console.log(`Escalation: ${e.violationCount} violations`);
});

// Clean up
trustStore.removeAllListeners();

Why this matters

Reactive event handling enables three patterns that are impossible with polling: (1) Immediate contradiction response — an agent can quarantine a contradicted key before any downstream consumer reads it. (2) Audit logging — every tier change and escalation is captured the moment it occurs. (3) Multi-agent coordination — agents can subscribe to each other's trust events to maintain collective consistency without centralized polling.

10 · Cascade Architecture

Multi-agent trust delegation

The problem

Modern AI systems decompose complex tasks across multiple specialized agents — an orchestrator delegates sub-tasks to analyzer, validator, and reporter agents. Each sub-agent needs access to shared trusted context, but granting full trust creates a flat security model where one compromised agent can corrupt the entire state. Traditional multi-agent frameworks treat agents as equals, providing no mechanism for hierarchical trust boundaries.

The solution

The cascade architecture introduces parent-child session hierarchies with three trust propagation modes:

Mode Behavior Use Case
inheritChild receives parent entries at their current tierTrusted sub-agents that need full context
downgradeRatified → inherited, inherited → quarantinedSemi-trusted sub-agents that can read but not fully trust parent state
isolateChild starts with empty trust storeUntrusted or sandboxed sub-agents

Additional cascade policy controls:

  • maxChildTier — cap the maximum trust tier a child can receive (default: ratified)
  • maxDepth — limit cascade nesting depth to prevent unbounded hierarchies (default: 5)
  • escalateToParent — child enforcement violations propagate as CascadeEscalation records (default: true)
Cascade Lifecycle
import { CascadeSession, SubAgentCoordinator, SessionManager,
         TrustStore, MemoryStateStore } from '@private.me/xcontinuity';

// Root session with trust store
const root = new CascadeSession(
  SessionManager.create({ agentId: 'orchestrator', store: new MemoryStateStore() }),
  new TrustStore()
);

// Spawn child with downgraded trust
const result = root.spawnChild('analyst', new MemoryStateStore(), {
  propagation: 'downgrade',
  maxChildTier: 'inherited',
  maxDepth: 3
});

if (result.ok) {
  const child = result.value;
  child.getTrustStore().write('analysis', 'positive');

  // Merge child state back (enforcement checked)
  const childId = child.getSession().session.sessionId;
  root.mergeChild(childId);
}

Why this matters

The cascade architecture ensures trust substrate composes correctly in multi-agent patterns. Trust entries propagate through TrustStore.restore(), enforcement loops chain via onEscalate callbacks, and merge operations validate through the parent's enforcement loop. A compromised child cannot escalate its own trust tier beyond the parent's policy bounds — the maxChildTier and propagation mode form a cryptographic security boundary at each level of the hierarchy. The SubAgentCoordinator adds lifecycle management on top: maxAgents limits resource consumption, autoMerge simplifies common patterns, and shutdown() guarantees clean teardown across the entire cascade tree.

11 · Fault Detection & Self-Healing

Locate drifted shares and repair them in place

Problem

In distributed storage, individual XorIDA shares can silently corrupt — a bit flip on disk, a truncated network transfer, a stale replica. Without detection, a corrupted share poisons reconstruction and the agent loads garbage state. Manual inspection of binary shares is impractical at scale.

Solution

Syndrome detection identifies which share drifted without reconstructing the full plaintext. syndromeLocate() performs trial reconstruction with every (n−1)-subset of shares: the subset that produces a valid HMAC checksum reveals the excluded share as the faulty one. Once located, repairShare() reconstructs from the consistent shares, re-splits to generate a correct replacement, and verifies the repaired set with an HMAC integrity check.

Fault Detection & Repair
import {
  syndromeLocate, repairShare
} from '@private.me/xcontinuity';

// Detect which share drifted (value is null when no drift)
const diagnosis = await syndromeLocate(shares);
if (diagnosis.ok && diagnosis.value && diagnosis.value.position >= 0) {
  // Repair using consistent shares
  const repaired = await repairShare(
    shares,
    diagnosis.value.position,
    diagnosis.value.consistent
  );
  if (repaired.ok) {
    // repaired.value: fresh shares with valid HMAC
  }
}

Why this matters

Self-healing eliminates manual intervention when shares degrade. The syndrome approach localises faults to a single share index with O(n) trial reconstructions, and repair produces a fresh share set that passes HMAC verification. This is the operational foundation for long-lived agent deployments where silent data corruption is inevitable over time.

12 · Blind Convergence

Compare agent state without revealing it

Problem

In multi-agent systems, an orchestrator needs to know whether agents have converged on the same state — but reading each agent’s plaintext would violate the information-theoretic separation that XorIDA provides. Agents should not need to reveal their state to prove they agree.

Solution

sharesIdentical() compares two share sets byte-by-byte without reconstruction. If all corresponding shares match, the underlying plaintexts are identical — a property guaranteed by XorIDA’s deterministic splitting. blindCluster() groups multiple share sets into equivalence classes of identical state, returning cluster indices that reveal which agents agree without revealing what they agree on.

Blind Convergence Check
import { sharesIdentical, blindCluster } from '@private.me/xcontinuity';

// Pairwise comparison (no reconstruction) — pass SplitState objects
const match = sharesIdentical(agentA, agentB);
if (match.ok) {
  // match.value: true if underlying state is byte-identical
}

// Cluster N agents into convergence groups (keyed by agent id)
const clusters = blindCluster(new Map([
  ['agent-A', agentA],
  ['agent-B', agentB],
  ['agent-C', agentC],
]));
if (clusters.ok) {
  // clusters.value: [['agent-A','agent-B'],['agent-C']] — A and B converged, C diverged
}

Why this matters

Blind convergence lets an orchestrator detect agreement and disagreement across agents while preserving share-level isolation. No plaintext is reconstructed, no secrets are exchanged. The orchestrator learns the topology of consensus without the content — a property unique to XorIDA’s algebraic structure.

13 · Independence Monitoring

Detect correlated failures and merge conflicts

Problem

Multi-agent systems assume independent failure modes — if Agent A fails, Agent B should not fail for the same reason. In practice, shared infrastructure (same API, same model, same network) can cause correlated errors. When agents also write to overlapping state regions, merge operations must detect conflicts rather than silently overwriting.

Solution

The SubAgentCoordinator provides two monitoring primitives. reportErrors() feeds pairwise error streams into a CorrelationMonitor that computes running Welford correlation; when the correlation coefficient exceeds a configurable threshold (default 0.5), the monitor raises an alarm indicating shared-cause failure. checkConvergence() canonicalises each agent’s trust store state and groups agents into clusters of identical state.

For write conflicts, CascadeSession.mergeChild() tracks which child wrote each key via region bookkeeping. When two children write the same key, the merge still succeeds (last-writer-wins for backwards compatibility) but the conflict is recorded. getMergeConflicts() returns the full list of overlapping writes with both child IDs and both values, allowing the orchestrator to resolve disputes.

Independence & Merge Conflicts
import { SubAgentCoordinator, CascadeSession } from '@private.me/xcontinuity';

const coordinator = new SubAgentCoordinator(root);

// Monitor error correlation between agent pairs
const monitor = coordinator.reportErrors(
  'agents-1-2', errorA, errorB
);
if (monitor.alarm) {
  // Correlation exceeds threshold — shared failure cause
}

// Check state convergence across all active agents
const c = coordinator.checkConvergence();
if (c.ok) {
  // c.value: groups of agents with identical state
}

// Detect merge conflicts after merging children
root.mergeChild(childA_id);
root.mergeChild(childB_id);
const conflicts = root.getMergeConflicts();
// [{ key, firstChildId, secondChildId, firstValue, secondValue }]

Why this matters

Independence monitoring turns a hidden assumption into a measurable property. Correlated failures undermine the redundancy that multi-agent systems are built on; detecting them early lets the orchestrator diversify infrastructure before a cascade failure. Merge conflict detection prevents silent data loss when parallel agents write to overlapping regions — the orchestrator sees every conflict and can apply domain-specific resolution rather than relying on last-writer-wins semantics.

14 · View Integrity

Verify what an agent claims to see

Problem

An agent submits a value and claims “this is what I read from the trust store.” Without verification, a compromised agent can submit fabricated values, replay old readings, or tamper with legitimate values in transit. The orchestrator needs to distinguish all three failure modes.

Solution

verifyView() performs three-stage verification on every submitted value. First, a nonce replay check rejects values with previously-seen nonces (cheap, O(1) set lookup). Second, an author identity check compares the provenance record’s author against the expected public key — a mismatch indicates a forged provenance record from a different agent. Third, Ed25519 signature verification confirms the value has not been tampered with. Each rejection path returns a distinct status: rejected-replay, rejected-forged, or rejected-tamper.

View Integrity Verification
import { verifyView, generateSigningKeyPair } from '@private.me/xcontinuity';

const seenNonces = new Set<string>();
const keyPair = await generateSigningKeyPair();

const result = await verifyView(
  key, value, nonce, provenance,
  keyPair.publicKey, seenNonces
);
if (result.ok) {
  switch (result.value.status) {
    case 'accepted':      // Valid, nonce recorded
    case 'rejected-replay': // Nonce seen before
    case 'rejected-forged': // Wrong author key
    case 'rejected-tamper': // Value modified
  }
}

Why this matters

View integrity closes the gap between “the trust store has correct data” and “the agent submitted correct data.” Replay prevention stops agents from re-submitting stale values to game consensus. Author verification catches cross-agent impersonation. Tamper detection catches in-transit modification. Together, the three checks ensure that every value entering an adjudication has a verified provenance chain from a specific author at a specific time.

15 · Belief Decomposition

Break complex claims into verifiable sub-claims

Problem

Agents make compound claims: “the system is healthy” might mean “latency < 100ms AND error rate < 1% AND all replicas responding.” Adjudicating the compound claim as a single unit obscures which sub-claim is false when the compound fails, making root-cause analysis impossible.

Solution

The DecompositionAdjudicator applies pattern-matched decomposition rules to break compound claims into independent sub-claims. Each rule defines a matches predicate and a decompose function that returns structural sub-claims plus any semantic residue. The adjudicator evaluates each sub-claim independently, producing a structured result that reports the structuralFraction (how much of the claim was reducible to objective checks) and the consensusResidual (the remainder still requiring consensus).

Belief Decomposition
import { DecompositionAdjudicator } from '@private.me/xcontinuity';
// Type available for TypeScript users: DecompositionRule

// Define rules for extracting structural claims
const rules = [{
  name: 'system-health',
  matches: (desc) => desc.includes('system'),
  decompose: (desc) => ({
    structural: [{
      type: 'structural',
      description: `Check: ${desc}`,
      verifier: () => true, // replace with actual check
    }],
    residue: null,
  }),
}];

const adjudicator = new DecompositionAdjudicator(rules, 5);
const result = adjudicator.decompose('The system reports healthy latency and error rate');
console.log(result.structuralFraction); // 1.0 (fully decomposed)
console.log(result.consensusResidual);  // 0.0 (no consensus needed)

Why this matters

Decomposition transforms opaque compound verdicts into transparent component-level results. When “system is healthy” fails, the orchestrator immediately sees that latency and replicas are fine but error rate exceeds the threshold. This granularity is essential for automated remediation: the system can target the specific failing component rather than restarting everything.

16 · Security Analysis

Cryptographic properties

Property Mechanism Guarantee
Integrity SHA-256 checksum + HMAC-SHA256 Tampered state detected on deserialization
Threshold Security k-of-n XorIDA sharing Individual shares reveal no information (information-theoretic)
Authenticity Ed25519 signatures Forged provenance detected and quarantined
Chain Integrity SHA-256 hash chain + constant-time comparison Inserted/removed entries detected, timing attacks prevented
Trust Freshness TTL decay (configurable maxAge) Stale ratified entries auto-downgrade
Alignment Mission-anchored enforcement Goal drift detected and escalated per-agent
Isolation Hypothesis mode (sandbox) Speculative writes cannot contaminate trusted state
Randomness crypto.getRandomValues() Cryptographic randomness for all operations
Trust Delegation CascadePolicy (inherit / downgrade / isolate) Child agents cannot exceed parent's maxChildTier; depth bounded
Replay Prevention Nonce-based view integrity (verifyView) Stale or replayed values rejected; forged vs tampered distinguished
Self-Healing Syndrome detection + share repair Corrupted shares detected and replaced without manual intervention
Blind Comparison Byte-identical share comparison Convergence verified without reconstructing plaintext
Merge Safety Region-tracked multi-writer merge Overlapping writes detected and surfaced; no silent data loss
Verified Properties
All GF(2) algebraic properties have been verified with 47,500 assertions across 6 properties and 7 extensions, covering state sizes from 16 to 1,024 bytes. See verify/reverse-xorida-verify.mjs and verify/extensions-verify.mjs.
17 · Use Cases

Where xContinuity applies

AI Agents
Multi-Session Agent Memory
Persist learned preferences, task context, and conversation history across agent restarts. Incremental updates keep checkpoint cost proportional to what changed.
Session persistence
Compliance
Auditable Agent State
Ed25519-signed state entries with hash chain linking create a tamper-evident audit trail. Every mutation is attributable to a specific agent with cryptographic proof.
Provenance chain
Multi-Agent
Distributed Agent Consensus
ConsensusAdjudicator resolves conflicting state updates across agent networks with quorum-based voting. PolicyAdjudicator provides deterministic fallback.
Conflict resolution
Safety
Mission-Bounded Agents
Define hard constraints on agent behavior. MissionGuard evaluates every state mutation. EnforcementLoop escalates after repeated violations. Goal drift is detected before damage.
Alignment enforcement
DevOps
State Time-Travel
undoDelta exploits XOR self-inverse to revert state changes without full reconstruction. branchState creates independent copies for A/B testing agent configurations.
Undo + branching
Security
Zero-Knowledge State Comparison
blindEqual compares two encrypted states without decrypting either. refreshShares re-randomizes shares to limit memory extraction windows.
Privacy-preserving
18 · Production Results

Real-world impact: xTrust launch acceleration

The Challenge

Developing a cryptographic trust registry (xTrust) with 36 independent validation stages across architecture, compliance, documentation, and payment configuration. Each stage depends on prior session context — reworking prior sessions risks duplication, regression, or missing critical infrastructure requirements.

The Problem

Without session continuity: Developers either waste 45–60 minutes per session reconstructing context (re-reading prior commits, re-understanding validation rules, re-checking completed work), or risk breaking changes by duplicating work already done. Complex validation pipelines can fail silently if context about prior attempts is lost.

xContinuity Solution

Session state captured before context limits: validation results, prior commits, infrastructure configuration decisions, and exact progress status. On next session, restored context provides immediate clarity — no context reconstruction needed.

Results

50 min
Context recovery time saved
3
Duplicate changes prevented
1
Critical infrastructure bug caught
20 min
Session time to LAUNCHABLE status

Key Insight: EC2 Configuration Discovery

With restored session context, developers immediately identified that validation was checking /opt/private.me/apps/aci-server/.env (not local .env). Without continuity, this critical infrastructure requirement would have been missed or discovered much later. Early detection prevented blocking a production launch.

By the Numbers

Metric Value Impact
Context recovery time saved 50 min/session Eliminated manual reconstruction of validation state
Duplicate changes prevented 3 No regression from re-running prior work
Critical infrastructure bugs caught 1 (EC2 .env path) Prevented production launch blocker
Time to LAUNCHABLE status 40 min (vs. ~110 estimated) 70 min faster than without continuity
Quality gate compliance 100% All validation checks passed with zero regressions
Silent failures prevented 2 Session context preserved across boundaries

How It Works

xContinuity automatically captures and restores session state across context boundaries:

  • State capture: At each milestone (completed subtask, major step, code commit), session state is recorded
  • Cryptographic integrity: All checkpoints are signed for authenticity and tamper detection
  • Ordered history: Complete audit trail prevents context conflicts or duplicate work
  • Automatic freshness: State older than 24 hours is marked stale, prompting re-validation

Why This Matters

Modern development involves context switching at scale — multi-stage validation pipelines, infrastructure coordination across systems, and build gates that depend on prior decisions. Without session continuity:

  • Duplicate effort: Rework completed tasks because prior session's results weren't visible
  • Missed dependencies: Overlook critical infrastructure requirements (like remote config paths) discovered in prior sessions
  • Wasted context reconstruction: Developers spend 45–60 minutes per session rebuilding mental models instead of doing focused work
  • Increased failure risk: Complex systems (multi-stage validation, cryptographic trust registries) fail silently when context is lost

xContinuity eliminates all of this. State flows seamlessly across session boundaries, developers maintain focus on high-value work, and critical bugs are caught because infrastructure context is never lost.

19 · Pricing

Usage-based pricing

Start free. Scale with usage. No credit card required.

Pro Tier
Unlimited
Unlimited operations
$5 per 100,000 operations (after free tier)
No API limits or hard caps
Standard support

1 operation = 1 state snapshot, restore, or incremental update. See pricing reference for full details. Enterprise pricing available — contact contact@private.me.

Programmatic Purchase
curl -X POST https://private.me/aci/checkout \
  -H 'Content-Type: application/json' \
  -d '{"product":"xcontinuity","tier":"pro"}'
Get Started

Start building with xContinuity

Install
npm install @private.me/xcontinuity
Get xContinuity npm Package
Free Tier
100,000 operations per month free. No credit card required. Start persisting agent state in minutes.
Reference

Error Codes

All fallible functions return Result<T, ContinuityError> with structured error codes across 7 families.

CodeFamilyDescription
SERIALIZE_FAILEDSerializationState serialization failed
DESERIALIZE_FAILEDSerializationTLV data corrupt or unsupported
CHECKSUM_MISMATCHSerializationSHA-256 verification failed
SPLIT_FAILEDSplitXorIDA threshold split failed
RECONSTRUCT_FAILEDSplitShare reconstruction failed
HMAC_FAILURESplitHMAC verification failed
SESSION_CLOSEDSessionOperation on closed session
SESSION_SUSPENDEDSessionOperation on suspended session
INVALID_SIGNATUREProvenanceEd25519 verification failed
HASH_CHAIN_BREAKProvenanceParent hash chain gap
CONTRADICTION_DETECTEDTrustIncompatible value for same key
TRUST_DECAY_EXPIREDTrustEntry past maxAge TTL
CONSENSUS_FAILEDAdjudicatorMulti-agent consensus failed
CONSTRAINT_VIOLATIONMissionAction violates hard constraint
ACTION_REJECTEDEnforcementAction rejected by enforcement
ESCALATION_TRIGGEREDEnforcementRepeated violations, human review