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
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
import { afterEach, describe, expect, it, spyOn } from 'bun:test';
import {
OpenAICompatProvider,
resetRefusedHostModelsForTesting,
resetServedModelsForTesting,
} from '../../src/services/worker/OpenAICompatProvider.js';
import { SessionStore } from '../../src/services/sqlite/SessionStore.js';
import { SessionManager } from '../../src/services/worker/SessionManager.js';
import { ModeManager } from '../../src/services/domain/ModeManager.js';
import { SettingsDefaultsManager } from '../../src/shared/SettingsDefaultsManager.js';
import type { DatabaseManager } from '../../src/services/worker/DatabaseManager.js';
/**
* End-to-end attribution guard for the per-session observer endpoint map.
*
* Observations stored from two mapped sessions must carry the model that
* actually served each one. generated_by_model is written
* by the storage path from the model on the wire, so this drives the real
* SessionManager (queue -> iterator -> provider -> ResponseProcessor ->
* SessionStore) against two loopback endpoints and reads the column back.
*
* Isolation: a private SessionStore(':memory:') per test, ephemeral loopback
* ports, a stubbed settings load, and no real .env credential or network.
*/
const GLOBAL_MODEL = 'global-model';
const MODEL_A = 'model-a';
const ENDPOINT_MODEL_B = 'endpoint-model-b';
const OBSERVATION_XML = '<observation><type>change</type><title>Updated the file</title></observation>';
const servers: Array<ReturnType<typeof Bun.serve>> = [];
const stores: SessionStore[] = [];
const originalLoad = SettingsDefaultsManager.loadFromFile;
afterEach(() => {
SettingsDefaultsManager.loadFromFile = originalLoad;
resetRefusedHostModelsForTesting();
resetServedModelsForTesting();
for (const server of servers.splice(0)) server.stop(true);
for (const store of stores.splice(0)) store.close();
});
describe('OpenAI-compatible served-model attribution', () => {
it('stores observations from two mapped sessions with their own generated_by_model', async () => {
const wireModels: Array<{ endpoint: 'a' | 'b'; model: string }> = [];
const answer = (endpoint: 'a' | 'b', model: string) => {
wireModels.push({ endpoint, model });
return Response.json({
model,
choices: [{ message: { role: 'assistant', content: OBSERVATION_XML }, finish_reason: 'stop' }],
usage: { prompt_tokens: 100, completion_tokens: 10, total_tokens: 110 },
});
};
const serverA = Bun.serve({
hostname: '127.0.0.1',
port: 0,
async fetch(request) {
const body = (await request.json()) as { model: string };
return answer('a', body.model);
},
});
const serverB = Bun.serve({
hostname: '127.0.0.1',
port: 0,
async fetch(request) {
const body = (await request.json()) as { model: string };
return answer('b', body.model);
},
});
servers.push(serverA, serverB);
const settings = spyOn(SettingsDefaultsManager, 'loadFromFile').mockImplementation(() => ({
...SettingsDefaultsManager.getAllDefaults(),
CLAUDE_MEM_PROVIDER: 'openai-compatible',
CLAUDE_MEM_OPENAI_COMPAT_PRESET: 'custom',
CLAUDE_MEM_OPENAI_COMPAT_BASE_URL: `http://127.0.0.1:${serverA.port}/v1`,
CLAUDE_MEM_OPENAI_COMPAT_MODEL: GLOBAL_MODEL,
CLAUDE_MEM_OPENAI_COMPAT_API_KEY: 'fixture-key',
CLAUDE_MEM_OPENAI_COMPAT_API_KEYS: 'cm_pro_fixture,fixture-key-2',
CLAUDE_MEM_OPENAI_COMPAT_MODEL_FROM_SESSION: 'true',
CLAUDE_MEM_OPENAI_COMPAT_SESSION_ENDPOINTS: JSON.stringify({
'provider-b': {
baseUrl: `http://127.0.0.1:${serverB.port}/v1`,
modelMap: { 'host-model-b': ENDPOINT_MODEL_B },
// Pool: [fixture-key, cm_pro_fixture, fixture-key-2]; B takes the last.
keyIndexes: [2],
},
}),
CLAUDE_MEM_OBSERVE_BARE_PROMPTS: 'false',
CLAUDE_MEM_OBSERVER_ENABLED: 'true',
CLAUDE_MEM_TIER_ROUTING_ENABLED: 'false',
CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED: 'false',
CLAUDE_MEM_AUTO_UPDATE: 'false',
}));
try {
ModeManager.getInstance().loadMode('code');
const store = new SessionStore(':memory:');
stores.push(store);
const dbManager = {
getSessionById: (id: number) => store.getSessionById(id),
getSessionStore: () => store,
getChromaSync: () => null,
getCloudSync: () => null,
} as unknown as DatabaseManager;
const manager = new SessionManager(dbManager);
const provider = new OpenAICompatProvider(dbManager, manager);
/** Queue one Write, then run the real generation until its queue drains. */
const observeOnce = async (
contentSessionId: string,
observerProvider: string,
observerModel: string,
): Promise<void> => {
const sid = store.createSDKSession(contentSessionId, 'served-model-project', 'Record the edit');
const session = manager.initializeSession(sid, 'Record the edit', 1);
session.observerProvider = observerProvider;
session.observerModel = observerModel;
manager.queueObservation(sid, {
tool_name: 'Write',
tool_input: { file_path: `src/${contentSessionId}.ts` },
tool_response: 'Written',
prompt_number: 1,
});
try {
await provider.startSession(session, {
broadcastProcessingStatus() {
if (manager.getTotalQueueDepth() === 0) session.abortController.abort();
},
});
} finally {
session.abortController.abort();
manager.removeSessionImmediate(sid);
}
};
await observeOnce('served-model-a', 'provider-a', MODEL_A);
await observeOnce('served-model-b', 'provider-b', 'host-model-b');
// Each session reached its own endpoint with its own (translated) model.
expect(wireModels).toEqual([
{ endpoint: 'a', model: MODEL_A },
{ endpoint: 'b', model: ENDPOINT_MODEL_B },
]);
// The row records the model that actually served it, not the global one
// and not the host's untranslated display id.
const rows = store.db.query('SELECT generated_by_model FROM observations ORDER BY id').all() as Array<{
generated_by_model: string;
}>;
expect(rows).toEqual([
{ generated_by_model: MODEL_A },
{ generated_by_model: ENDPOINT_MODEL_B },
]);
expect(manager.getTotalQueueDepth()).toBe(0);
} finally {
settings.mockRestore();
}
});
});