Context sync
Long agent sessions resend the same state on every turn. Send it once as a snapshot, then only what changed as a delta. Versions are checked, snapshots carry a hash, envelopes are signed, and Java, Python and TypeScript write the same bytes.
Experimental: Context sync is marked experimental in JDogo 2.1. Wire format, delta layout and session synchronization APIs are subject to stabilization in 2.2.
In Python jdogo.context, in TypeScript context from "jdogo", in Java jdogo-context-core plus the store modules. Agents get the same operations through the MCP server tools jdogo_diff and jdogo_patch. Shared vectors in context_vectors.json check all three languages byte for byte on every build.
Snapshot, diff, apply
from jdogo import context
v1 = context.create_snapshot("acme", "session-42", {"user": "ana", "step": 1})
delta = context.diff(v1, {"user": "ana", "step": 2, "cart": ["sku-1"]})
v2 = context.apply(v1, delta)
context.resolve(v2, "cart") # ["sku-1"]
text = delta.to_wire() # send this
same = context.ContextDelta.from_wire(text)import { context } from "jdogo";
const v1 = context.createSnapshot("acme", "session-42", { user: "ana", step: 1 });
const delta = context.diff(v1, { user: "ana", step: 2, cart: ["sku-1"] });
const v2 = context.apply(v1, delta);
context.resolve(v2, "cart"); // ["sku-1"]
const text = context.deltaToWire(delta);
const same = context.deltaFromWire(text);import com.jdogo.context.core.*;
var engine = new ContextEngine();
ContextSnapshot v1 = engine.createSnapshot("acme", "session-42", Map.of("user", "ana", "step", 1));
ContextDelta delta = engine.diff(v1, Map.of("user", "ana", "step", 2, "cart", List.of("sku-1")));
ContextSnapshot v2 = engine.apply(v1, delta); // version 2, same state on both sides
Object cart = engine.resolveReference(v2, "cart");
String text = delta.toWireFormat();On the wire, a snapshot carries its version and a SHA-256 hash of its state; a delta names the version it applies to:
!JDOGO/2 @mode SNAPSHOT @context session-42 @tenant acme @version 1 @time 1795788793538 @hash c76d70… user=ana step=1 @end !JDOGO/2 @mode DELTA @context session-42 @tenant acme @base 1 @version 2 ~step=2 +cart=[sku-1] @end
| Line | Means |
|---|---|
~path=value | Change a value |
+path=value | Add a value |
-path | Remove a value |
- Values keep their types. Each value is one JDogo inline value, so
1and"1", lists, objects and multi-line strings come back exactly. - Any key works. Keys and path parts that are not simple names are quoted:
~nested."k.1".v=2changesvinside the keyk.1. - Nothing silently wrong. Reading a snapshot checks its
@hashand its closing@end, so an altered or cut-off snapshot is rejected. A delta applied to the wrong version or context fails. - Safe IDs. Tenant and context IDs are 1–128 letters, digits or
. _ @ -, so they can't inject header fields.
Signed envelopes
Wrap a snapshot or delta with a digest and an HMAC-SHA256 signature, so a receiver can tell who sent it and that nothing changed on the way.
wire = context.encode_envelope(delta, "billing-svc", key)
env = context.decode_envelope(wire)
if not context.verify_signature(env, key):
raise PermissionError("rejected context")
received = context.ContextDelta.from_wire(env.payload)const wire = context.encodeEnvelope(delta, "billing-svc", key);
const env = context.decodeEnvelope(wire);
if (!context.verifySignature(env, key)) throw new Error("rejected context");
const received = context.deltaFromWire(env.payload);byte[] key = secrets.get("context-hmac-key"); // 32 random bytes, shared by sender and receiver
String wire = ContextEnvelopeCodec.encodeHmac(delta, "billing-svc", key);
ContextEnvelope env = ContextEnvelopeCodec.decode(wire);
if (!ContextEnvelopeCodec.verifySignature(env, key)) {
throw new SecurityException("rejected context from " + env.getIssuerId());
}
ContextDelta received = ContextDelta.fromWireFormat(env.getPayload());verifySignatureis true only for a valid signature under your key. An envelope whose signature line was removed, signed with another key, re-addressed to another context or version, or using an unknown algorithm returns false.verifyDigestalone proves the payload wasn't damaged, not who sent it. Only SHA-256 and SHA-512 digests are accepted.- The issuer name is a label. The key identifies the sender, so give each sender its own key.
Verify before you apply. Keep keys out of code and rotate them like any other secret.
Live updates with server-sent events
In Python context.sse_event(delta) and in TypeScript context.sseEvent(delta) write the same frame as Java.
import com.jdogo.context.transport.*;
var bus = new InMemoryEventTransport();
AutoCloseable sub = bus.subscribe("acme", "session-42",
event -> sseStream.send(SseEventFormatter.format(event)));
bus.publish(ContextEvent.delta("acme", "session-42", v2.getVersion(), delta.toWireFormat()));SseEventFormatter writes a standard text/event-stream frame (event:, id:, data: lines). InMemoryEventTransport works within one process; across processes, publish the same frames through your own broker.
Stores
Every store keeps the latest snapshot and each version, per tenant.
ContextStore store = new InMemoryContextStore(3_600_000); // TTL in ms; tests and single process
ContextStore redis = RedisContextStore.connectOrFallback("redis", 6379, 86_400);
ContextStore sql = SqliteContextStore.open("jdbc:sqlite:context.db"); // or any JDBC DataSource
store.save(v2);
store.load("acme", "session-42"); // latest
store.loadVersion("acme", "session-42", 1); // a pinned version
store.listContexts("acme");
store.delete("acme", "session-42"); // latest and every version| Store | Notes |
|---|---|
InMemoryContextStore | One process; optional TTL |
RedisContextStore | Keys under jdogo:context: with a TTL in seconds. clear() deletes only keys under its prefix, never the rest of the database. For a password, use new SocketRedisAdapter(host, port, timeoutMs, password). connectOrFallback logs a warning and keeps data in memory if Redis is unreachable; in production, construct the adapter yourself so a missing Redis fails at startup |
SqliteContextStore | Plain JDBC with one table, jdogo_context_snapshots. Add the driver yourself, for example org.xerial:sqlite-jdbc. The test suite runs it on H2 |
The Redis store checks tenant and context IDs before it builds keys, so a value such as acme\nevil is rejected. The SQL store passes them as bound parameters.
Metrics and tracing
jdogo-observability has a small recorder and W3C trace context, with no dependencies, to feed your own metrics system.
import com.jdogo.observability.*;
var metrics = new ContextMetricsRecorder.InMemoryMetricsRecorder();
metrics.recordDeltaProcessed();
metrics.recordTokensSaved(jsonTokens - deltaTokens);
var snap = metrics.snapshot(); // totals and average diff and patch times
var trace = ContextTraceContext.parseW3CTraceparent(request.getHeader("traceparent"));
outgoing.setHeader("traceparent", trace.createChildSpan().toW3CTraceparent());