Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

5.0 KB
Raw Blame
import type { AuthDependencies } from "../src/auth";
import { loadEnv, type SyncApiEnv } from "../src/env";
import { DEFAULT_SYNC_API_TIMEOUTS, startSyncApi, type SyncApiApp, type SyncApiTimeouts } from "../src/index";
import {
	canonicalJson,
	sha256Base64Url,
	stableDocumentId,
	wrapCanonicalBody,
	type CanonicalContentBody,
	type CanonicalWireOp,
} from "../src/canonical-content";

export const PROJECTOR_SECRET = "test-projector-secret";
export const DEFAULT_DATABASE_URL =
	process.env.DATABASE_URL
	?? "postgres://postgres:[email protected]:5432/sync_api_test";

export interface ProjectionRequest {
	protocol_version: number;
	user_id: string;
	epoch: string;
	from_seq_exclusive: string;
	through_seq: string;
	ops: Array<{ seq: string; body: string; operation_sha256: string }>;
}

export interface SidecarState {
	projectionCalls: ProjectionRequest[];
}

interface TestApp {
	app: SyncApiApp;
	sidecar: { server: ReturnType<typeof Bun.serve>; state: SidecarState; baseUrl: string };
	env: SyncApiEnv;
}

const apps: TestApp[] = [];

export async function trackedApp(
	timeouts: SyncApiTimeouts = DEFAULT_SYNC_API_TIMEOUTS,
	authDependencies?: AuthDependencies,
): Promise<TestApp> {
	const state: SidecarState = { projectionCalls: [] };
	const server = Bun.serve({
		hostname: "127.0.0.1",
		port: 0,
		async fetch(request): Promise<Response> {
			const url = new URL(request.url);
			if (url.pathname === "/verify") {
				const token = (request.headers.get("Authorization") ?? "").replace(/^Bearer\s+/i, "");
				if (token === "denied") {
					return Response.json({ error: "denied" }, { status: 401 });
				}
				if (token === "wrong-user") {
					return Response.json({ userId: "someone-else" });
				}
				if (token.startsWith("valid-for:")) {
					return Response.json({ userId: token.slice("valid-for:".length) });
				}
				return Response.json({ error: "denied" }, { status: 401 });
			}
			if (url.pathname === "/project") {
				if (request.headers.get("Authorization") !== `Bearer ${PROJECTOR_SECRET}`) {
					return Response.json({ error: "denied" }, { status: 401 });
				}
				const payload = await request.json() as ProjectionRequest;
				state.projectionCalls.push(payload);
				return Response.json({
					protocol_version: 1,
					epoch: payload.epoch,
					projected_through_seq: payload.through_seq,
				});
			}
			return Response.json({ error: "not found" }, { status: 404 });
		},
	});
	const sidecar = { server, state, baseUrl: `http://127.0.0.1:${server.port}` };
	const env = loadEnv({
		DATABASE_URL: DEFAULT_DATABASE_URL,
		TOKEN_VERIFY_URL: `${sidecar.baseUrl}/verify`,
		INTERNAL_PROJECTOR_URL: `${sidecar.baseUrl}/project`,
		CMEM_INTERNAL_PROJECTOR_SECRET: PROJECTOR_SECRET,
		AUTH_CACHE_TTL_SECONDS: "900",
		PORT: "0",
		HOST: "127.0.0.1",
	});
	const app = await startSyncApi(env, timeouts, authDependencies);
	const started = { app, sidecar, env };
	apps.push(started);
	return started;
}

export function pushRequest(
	app: SyncApiApp,
	userId: string,
	deviceId: string,
	ops: CanonicalWireOp[],
	init: RequestInit = {},
): Promise<Response> {
	return fetch(`${app.url}/v1/sync/ops`, {
		...init,
		method: "POST",
		headers: { ...authHeaders(userId, deviceId), "Content-Type": "application/json" },
		body: JSON.stringify({ protocol_version: 2, ops }),
	});
}

/** Poll until `condition` holds; fails the test after `timeoutMs`. */
export async function waitUntil(condition: () => Promise<boolean>, label: string, timeoutMs = 5_000): Promise<void> {
	const deadline = Date.now() + timeoutMs;
	while (Date.now() < deadline) {
		if (await condition()) return;
		await Bun.sleep(25);
	}
	throw new Error(`timed out waiting for ${label}`);
}

export function authHeaders(userId: string, deviceId?: string, token?: string): Record<string, string> {
	return {
		Authorization: `Bearer ${token ?? `valid-for:${userId}`}`,
		"X-User-Id": userId,
		...(deviceId ? { "X-Device-Id": deviceId } : {}),
	};
}

export async function observationOp(
	originLocalId: string,
	entityRev = "1",
	originDeviceId = "dev-a",
	overrides: Record<string, unknown> = {},
): Promise<CanonicalWireOp> {
	const payload: Record<string, unknown> = {
		created_at: "2026-07-20T12:34:56.789Z",
		created_at_epoch: "1784550896789",
		memory_session_id: "memory-test",
		project: "/test/project",
		type: "discovery",
		text: `observation ${originLocalId}`,
		...overrides,
	};
	const body: CanonicalContentBody = {
		body_schema_version: 1,
		deleted: false,
		deleted_at: null,
		entity_rev: entityRev,
		id: await stableDocumentId("observation", originDeviceId, originLocalId),
		kind: "observation",
		mutation: null,
		origin_device_id: originDeviceId,
		origin_local_id: originLocalId,
		payload,
		payload_schema_version: 2,
		payload_sha256: await sha256Base64Url(canonicalJson(payload)),
	};
	return wrapCanonicalBody(body);
}

export function uniqueUser(): string {
	return `user-${crypto.randomUUID()}`;
}

export async function stopTrackedApps(): Promise<void> {
	for (const started of apps.splice(0)) {
		await started.app.stop();
		started.sidecar.server.stop(true);
	}
}