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

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

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.
v2.1.0
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 (v1.0.0) handles cryptographic state persistence via Reverse-XorIDA. Layer 2 (v2.0.0) 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 v2.1.0
Multi-agent lifecycle — spawn, merge, shutdown
CascadeSession v2.1.0
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 · 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.

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 }

  // 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 v2.1.0

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.
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(`Agent ${e.author} escalated`);
});

// 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 v2.1.0

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 proves that v2.0.0's 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 · 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
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.
12 · 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
13 · 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