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 { afterAll, afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import type { TranscriptSchema, WatchTarget } from '../../src/services/transcripts/types.js';
import * as realIngest from '../../src/services/worker/http/shared.js';
const realIngestSnapshot = { ...realIngest };
const observations: Array<Record<string, unknown>> = [];
const summaries: Array<Record<string, unknown>> = [];
mock.module('../../src/services/worker/http/shared.js', () => ({
...realIngestSnapshot,
ingestSummarize: async (payload: Record<string, unknown>) => {
summaries.push(payload);
return { status: 'accepted' };
},
ingestObservation: async (payload: Record<string, unknown>) => {
observations.push(payload);
return { ok: true };
},
}));
afterAll(() => {
mock.module('../../src/services/worker/http/shared.js', () => realIngestSnapshot);
});
import { logger } from '../../src/utils/logger.js';
import { evictIdleSessions, TranscriptEventProcessor } from '../../src/services/transcripts/processor.js';
describe('evictIdleSessions', () => {
it('evicts the oldest idle sessions once over the cap', () => {
const sessions = new Map<string, { pendingTools?: Map<string, unknown> }>();
for (let i = 0; i < 5; i++) sessions.set(`s${i}`, { pendingTools: new Map() });
expect(evictIdleSessions(sessions, 3)).toBe(2);
expect([...sessions.keys()]).toEqual(['s2', 's3', 's4']);
});
it('keeps sessions with outstanding tools while trimming idle ones', () => {
const sessions = new Map<string, { pendingTools?: Map<string, unknown> }>();
sessions.set('busy', { pendingTools: new Map([['tool-1', {}]]) });
for (let i = 0; i < 4; i++) sessions.set(`idle${i}`, { pendingTools: new Map() });
evictIdleSessions(sessions, 2);
expect(sessions.has('busy')).toBe(true);
expect(sessions.size).toBe(2);
});
it('never drops a busy session just to meet the cap', () => {
const sessions = new Map<string, { pendingTools?: Map<string, unknown> }>();
sessions.set('a', { pendingTools: new Map([['tool-1', {}]]) });
sessions.set('b', { pendingTools: new Map([['tool-2', {}]]) });
expect(evictIdleSessions(sessions, 1)).toBe(0);
expect(sessions.size).toBe(2);
});
it('never drops the session it was told to keep', () => {
const sessions = new Map<string, { pendingTools?: Map<string, unknown> }>();
sessions.set('busy', { pendingTools: new Map([['tool-1', {}]]) });
sessions.set('new', {});
expect(evictIdleSessions(sessions, 1, 'new')).toBe(0);
expect([...sessions.keys()]).toEqual(['busy', 'new']);
});
});
const schema: TranscriptSchema = {
name: 'eviction-test',
sessionIdPath: 'session',
events: [
{ name: 'meta', match: { path: 'type', equals: 'meta' }, action: 'session_context', fields: { cwd: 'cwd' } },
{ name: 'assistant', match: { path: 'type', equals: 'assistant' }, action: 'assistant_message', fields: { message: 'text' } },
{ name: 'call', match: { path: 'type', equals: 'call' }, action: 'tool_use', fields: { toolId: 'id', toolName: 'name', toolInput: 'input' } },
{ name: 'result', match: { path: 'type', equals: 'result' }, action: 'tool_result', fields: { toolId: 'id', toolResponse: 'output' } },
{ name: 'end', match: { path: 'type', equals: 'end' }, action: 'session_end' },
],
};
const watch: WatchTarget = { name: 'eviction', path: '/nonexistent/*.jsonl', schema };
const meta = (session: string) => ({ type: 'meta', session, cwd: '/work/project' });
describe('TranscriptEventProcessor session cap', () => {
let loggerSpies: ReturnType<typeof spyOn>[] = [];
let debugSpy: ReturnType<typeof spyOn>;
let warnSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
observations.length = 0;
summaries.length = 0;
debugSpy = spyOn(logger, 'debug').mockImplementation(() => {});
warnSpy = spyOn(logger, 'warn').mockImplementation(() => {});
loggerSpies = [
debugSpy,
warnSpy,
spyOn(logger, 'info').mockImplementation(() => {}),
spyOn(logger, 'error').mockImplementation(() => {}),
];
});
afterEach(() => {
loggerSpies.forEach(spy => spy.mockRestore());
});
it('keeps a new session when every older session is busy, and reports the cap once', async () => {
const processor = new TranscriptEventProcessor('in-process', 1);
await processor.processEntry(meta('busy'), watch, schema);
await processor.processEntry({ type: 'call', session: 'busy', id: 'busy-tool', name: 'Bash', input: { command: 'sleep' } }, watch, schema);
await processor.processEntry(meta('fresh'), watch, schema);
await processor.processEntry({ type: 'call', session: 'fresh', id: 'fresh-tool', name: 'Read', input: { path: 'a.ts' } }, watch, schema);
await processor.processEntry({ type: 'result', session: 'fresh', id: 'fresh-tool', output: 'contents' }, watch, schema);
expect(observations.map(o => [o.contentSessionId, o.toolName, o.toolInput, o.cwd])).toEqual([
['fresh', 'Read', { path: 'a.ts' }, '/work/project'],
]);
const capWarnings = warnSpy.mock.calls.filter(call => String(call[1]).includes('over cap'));
expect(capWarnings).toHaveLength(1);
});
it('evicts the least recently used idle session, not the oldest created', async () => {
const processor = new TranscriptEventProcessor('in-process', 2);
await processor.processEntry(meta('first'), watch, schema);
await processor.processEntry(meta('second'), watch, schema);
await processor.processEntry({ type: 'assistant', session: 'first', text: 'first answer' }, watch, schema);
await processor.processEntry(meta('third'), watch, schema);
await processor.processEntry({ type: 'end', session: 'first' }, watch, schema);
expect(summaries.map(s => [s.contentSessionId, s.lastAssistantMessage])).toEqual([['first', 'first answer']]);
const evictions = debugSpy.mock.calls.filter(call => call[1] === 'Evicted idle transcript sessions over cap');
expect(evictions).toHaveLength(1);
expect(evictions[0][2]).toEqual({ evicted: 1, cap: 2, remaining: 2 });
});
});