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, beforeEach, describe, expect, it } from 'bun:test';
import { SessionStore } from '../../src/services/sqlite/SessionStore.js';
import { OBSERVER_SESSIONS_PROJECT } from '../../src/shared/paths.js';
import { MEDIA_PROMPT_PLACEHOLDER } from '../../src/services/sqlite/prompt-storage.js';
import { SESSION_FIRST_PROMPT_MAX_CHARS } from '../../src/shared/session-first-prompt.js';
// The Sessions list titles each row by what the session was about: the trimmed request of the
// session's newest summary that has words (summary_title), or null when there is none.
describe('session catalog summary_title', () => {
let store: SessionStore;
beforeEach(() => {
store = new SessionStore(':memory:');
});
afterEach(() => {
store.close();
});
/** A session started at `startedAt`; registered with a memory session id unless `memoryId` is null. */
function session(contentId: string, project: string, startedAt: number, memoryId: string | null = `mem-${contentId}`, platform = 'claude'): void {
const id = store.createSDKSession(contentId, project, 'first prompt', undefined, platform);
if (memoryId) store.ensureMemorySessionIdRegistered(id, memoryId);
store.db.prepare('UPDATE sdk_sessions SET started_at_epoch = ? WHERE id = ?').run(startedAt, id);
}
function summary(memoryId: string, project: string, request: string | null, createdAt: number): number {
return Number(store.db.prepare(`
INSERT INTO session_summaries (memory_session_id, project, request, created_at, created_at_epoch)
VALUES (?, ?, ?, ?, ?)
`).run(memoryId, project, request, new Date(createdAt).toISOString(), createdAt).lastInsertRowid);
}
const row = (contentId: string) => {
const found = store.getSessionCatalog().sessions.find(entry => entry.content_session_id === contentId);
if (!found) throw new Error(`${contentId} is not in the catalog`);
return found;
};
it('titles a session by its newest summary, trimmed, even when an older one was saved later', () => {
session('a', 'proj', 1);
summary('mem-a', 'proj', 'Older ask', 1000);
summary('mem-a', 'proj', ' Newest ask\n', 2000);
// Saved last (higher id) but older: an import or a synced copy. Time decides, not id.
summary('mem-a', 'proj', 'Late copy of an old ask', 500);
expect(row('a').summary_title).toBe('Newest ask');
});
it('breaks a tie on time with the newer id', () => {
session('tie', 'proj', 1);
summary('mem-tie', 'proj', 'First at 3000', 3000);
summary('mem-tie', 'proj', 'Second at 3000', 3000);
expect(row('tie').summary_title).toBe('Second at 3000');
});
it('skips newer summaries whose request has no words and keeps counting them', () => {
session('blank', 'proj', 1);
summary('mem-blank', 'proj', 'Older ask with words', 1000);
summary('mem-blank', 'proj', '', 4000);
summary('mem-blank', 'proj', null, 5000);
// Every character JavaScript's trim() removes, so the UI and the query agree on "no words".
summary('mem-blank', 'proj', ' \t\n\r\u000b\u000c
', 6000);
const entry = row('blank');
expect(entry.summary_title).toBe('Older ask with words');
expect(entry.item_count).toBe(4);
});
it('is null for a session with no summary, only blank summaries, or no memory session yet', () => {
session('none', 'proj', 1);
session('only-blank', 'proj', 2);
summary('mem-only-blank', 'proj', ' ', 1000);
summary('mem-only-blank', 'proj', null, 2000);
session('unregistered', 'proj', 3, null);
session('titled', 'proj', 4);
summary('mem-titled', 'proj', 'Has a title', 1000);
expect(row('none').summary_title).toBeNull();
expect(row('only-blank').summary_title).toBeNull();
expect(row('unregistered').summary_title).toBeNull();
expect(row('titled').summary_title).toBe('Has a title');
// The field is always present (null, never missing), so the viewer can tell this worker from an older one.
expect(store.getSessionCatalog().sessions.every(entry => 'summary_title' in entry)).toBe(true);
});
it('never takes another session’s summary, even one saved at the same moment', () => {
session('quiet', 'proj', 1);
session('busy', 'proj', 2);
session('elsewhere', 'other-proj', 3);
// Same time on every row: the lookup by time must still stay inside each session.
summary('mem-quiet', 'proj', '', 5000);
summary('mem-busy', 'proj', 'Busy session ask', 5000);
summary('mem-elsewhere', 'other-proj', 'Other project ask', 5000);
session('own', 'proj', 4);
summary('mem-own', 'proj', 'Own ask', 5000);
summary('mem-busy', 'proj', 'Busy session later ask', 5000);
expect(row('quiet').summary_title).toBeNull();
expect(row('busy').summary_title).toBe('Busy session later ask');
expect(row('own').summary_title).toBe('Own ask');
expect(row('elsewhere').summary_title).toBe('Other project ask');
});
describe('first_prompt (how the session opened, the name a session with no summary goes by)', () => {
const promptOf = (contentId: string) => row(contentId).first_prompt;
/** Puts a stored value in place as-is, past createSDKSession's own normalising (older rows, imports, synced copies). */
const storePrompt = (contentId: string, prompt: string | null) =>
store.db.prepare('UPDATE sdk_sessions SET user_prompt = ? WHERE content_session_id = ?').run(prompt, contentId);
it('serves the stored opening prompt, trimmed, beside the summary title', () => {
session('opened', 'proj', 1);
summary('mem-opened', 'proj', 'Summary ask', 1000);
storePrompt('opened', ' \n\t Fix the focus area links \n');
expect(row('opened')).toMatchObject({ summary_title: 'Summary ask', first_prompt: 'Fix the focus area links' });
// Always present (null, never missing), as summary_title is.
session('untouched', 'proj', 2);
storePrompt('untouched', null);
expect(store.getSessionCatalog().sessions.every(entry => 'first_prompt' in entry)).toBe(true);
expect(promptOf('untouched')).toBeNull();
});
it(`cuts a long prompt to ${SESSION_FIRST_PROMPT_MAX_CHARS} characters with an ellipsis and keeps one that fits whole`, () => {
const exact = 'e'.repeat(SESSION_FIRST_PROMPT_MAX_CHARS);
for (const [id, prompt] of [['long', `${'word '.repeat(200)}end`], ['exact', exact], ['one-over', `${exact}x`],
['emoji', '🧠'.repeat(300)], ['padded', ` ${exact} `], ['cut-at-space', `${'a'.repeat(118)} tail of the prompt`]] as const) {
session(id, 'proj', 1);
storePrompt(id, prompt);
}
expect(promptOf('long')).toBe(`${'word '.repeat(200).slice(0, SESSION_FIRST_PROMPT_MAX_CHARS - 1)}…`);
expect(Array.from(promptOf('long')!)).toHaveLength(SESSION_FIRST_PROMPT_MAX_CHARS);
expect(promptOf('exact')).toBe(exact);
expect(promptOf('padded')).toBe(exact);
expect(promptOf('one-over')).toBe(`${exact.slice(0, SESSION_FIRST_PROMPT_MAX_CHARS - 1)}…`);
// A cut that lands on a space does not leave it before the ellipsis.
expect(promptOf('cut-at-space')).toBe(`${'a'.repeat(118)}…`);
// Characters are code points, as SQLite counts them: an emoji is never split into half a surrogate pair.
expect(promptOf('emoji')).toBe(`${'🧠'.repeat(SESSION_FIRST_PROMPT_MAX_CHARS - 1)}…`);
});
it('is null for the [media prompt] stand-in and for a prompt with no words', () => {
// session-init stores the stand-in for an image-only send; createSDKSession stores '' for an all-<private> prompt.
const id = store.createSDKSession('media', 'proj', MEDIA_PROMPT_PLACEHOLDER, undefined, 'claude');
store.createSDKSession('private-only', 'proj', '<private>not for the list</private>', undefined, 'claude');
session('blank', 'proj', 1);
storePrompt('blank', ' \t\n\u000b\u000c ');
session('padded-media', 'proj', 1);
storePrompt('padded-media', ` ${MEDIA_PROMPT_PLACEHOLDER}\n`);
expect(promptOf('media')).toBeNull();
expect(promptOf('private-only')).toBeNull();
expect(promptOf('blank')).toBeNull();
expect(promptOf('padded-media')).toBeNull();
// The first real prompt replaces the stand-in (createSDKSession's repair), and the catalog then serves it.
store.createSDKSession('media', 'proj', 'The real ask after an image', undefined, 'claude');
expect(store.db.prepare('SELECT COUNT(*) AS n FROM sdk_sessions WHERE id = ?').get(id)).toEqual({ n: 1 });
expect(promptOf('media')).toBe('The real ask after an image');
});
it('never serves the words of a <private> block in a stored prompt, even one an older version stored unstripped', () => {
// createSDKSession strips memory tags before storing today; rows stored before that (and imported or synced copies)
// can still hold them, so the catalog strips the whole stored prompt before it cuts it.
for (const [id, prompt] of [['balanced', 'Fix the <private>sk-secret-123</private>links'], ['open', 'Ship it <private>the store cut this block'],
['all-private', '<private>secret</private>'], ['late', `${'a'.repeat(150)} <private>secret</private>`]] as const) {
session(id, 'proj', 1);
storePrompt(id, prompt);
}
expect(promptOf('balanced')).toBe('Fix the links');
expect(promptOf('open')).toBe('Ship it');
expect(promptOf('all-private')).toBeNull();
expect(promptOf('late')).toBe(`${'a'.repeat(SESSION_FIRST_PROMPT_MAX_CHARS - 1)}…`);
expect(JSON.stringify(store.getSessionCatalog().sessions)).not.toContain('secret');
});
});
it('keeps observer sessions out of the catalog', () => {
session('observer', OBSERVER_SESSIONS_PROJECT, 10);
summary('mem-observer', OBSERVER_SESSIONS_PROJECT, 'Observer ask', 1000);
session('visible', 'proj', 1);
expect(store.getSessionCatalog().sessions.map(entry => entry.content_session_id)).toEqual(['visible']);
});
it('pages, orders and filters exactly as before, with each title on its own row', () => {
for (const [id, startedAt, platform] of [['s5', 5000, 'claude'], ['s4', 4000, 'codex'], ['s3', 3000, 'claude'], ['s2', 2000, 'codex'], ['s1', 1000, 'claude']] as const) {
session(id, 'Repo', startedAt, `mem-${id}`, platform);
summary(`mem-${id}`, 'Repo', `Ask of ${id}`, startedAt + 1);
}
session('other', 'Other', 9000);
const first = store.getSessionCatalog({ project: 'repo', limit: 2 });
expect(first.sessions.map(entry => [entry.content_session_id, entry.summary_title])).toEqual([['s5', 'Ask of s5'], ['s4', 'Ask of s4']]);
expect(first.hasMore).toBe(true);
const second = store.getSessionCatalog({ project: 'repo', limit: 2, offset: 2 });
expect(second.sessions.map(entry => [entry.content_session_id, entry.summary_title])).toEqual([['s3', 'Ask of s3'], ['s2', 'Ask of s2']]);
expect(second.hasMore).toBe(true);
const last = store.getSessionCatalog({ project: 'repo', limit: 2, offset: 4 });
expect(last.sessions.map(entry => entry.content_session_id)).toEqual(['s1']);
expect(last.hasMore).toBe(false);
expect(store.getSessionCatalog({ project: 'REPO', platformSource: 'codex' }).sessions
.map(entry => [entry.content_session_id, entry.summary_title])).toEqual([['s4', 'Ask of s4'], ['s2', 'Ask of s2']]);
expect(store.getSessionCatalog({ limit: 1 }).sessions).toEqual([expect.objectContaining({ content_session_id: 'other', summary_title: null, item_count: 0 })]);
});
});