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, test } from 'bun:test';
import { readFileSync } from 'fs';
import path from 'path';
import { claudeCodeAdapter, getPlatformAdapter, museCodeAdapter } from '../../../src/cli/adapters/index.js';
import { AdapterRejectedInput } from '../../../src/cli/adapters/errors.js';
import { isRecursiveMemoryTool } from '../../../src/shared/memory-retrieval-tools.js';
const ENV_KEYS = ['MUSE_SESSION_ID', 'MUSE_THREAD_ID', 'CLAUDE_PROJECT_DIR'] as const;
const originalEnv = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]]));
beforeEach(() => {
// A test run inside Claude Code inherits CLAUDE_PROJECT_DIR; a run inside Muse inherits MUSE_*.
for (const key of ENV_KEYS) delete process.env[key];
});
afterEach(() => {
for (const key of ENV_KEYS) {
if (originalEnv[key] === undefined) delete process.env[key];
else process.env[key] = originalEnv[key];
}
});
// Real Muse Code 1.4.25 payloads and env, sanitized (tests/fixtures/hosts/muse-code-hooks.json).
type Entry = { env: Record<string, string>; payload: Record<string, any> };
const fixture = JSON.parse(
readFileSync(path.join(import.meta.dir, '..', '..', 'fixtures', 'hosts', 'muse-code-hooks.json'), 'utf-8'),
);
const entries: Record<string, Entry> = fixture.payloads;
const SESSION_ID = '00000000-0000-4000-8000-000000000001';
const CHILD_THREAD_ID = '00000000-0000-4000-8000-000000000002';
const PROJECT = '/Users/example/projects/muse-test-project';
function normalize(name: string, payloadPatch: Record<string, unknown> = {}) {
const { env, payload } = entries[name];
Object.assign(process.env, env);
return museCodeAdapter.normalizeInput({ ...payload, ...payloadPatch });
}
function rejection(run: () => unknown): string | undefined {
try {
run();
} catch (error) {
expect(error).toBeInstanceOf(AdapterRejectedInput);
return (error as AdapterRejectedInput).reason;
}
return undefined;
}
describe('museCodeAdapter session and subagent ids', () => {
test('is the adapter for the muse-code platform', () => {
expect(getPlatformAdapter('muse-code')).toBe(museCodeAdapter);
});
test('main thread (MUSE_SESSION_ID == MUSE_THREAD_ID) has no agentId/agentType', () => {
const input = normalize('PostToolUseReadRelative');
expect(input.sessionId).toBe(SESSION_ID);
expect(input.agentId).toBeUndefined();
expect(input.agentType).toBeUndefined();
});
test('subagent tool event uses the parent session and the child thread as agentId', () => {
const input = normalize('PostToolUseSubagentRead');
expect(entries.PostToolUseSubagentRead.payload.session_id).toBe(CHILD_THREAD_ID);
expect(input.sessionId).toBe(SESSION_ID);
expect(input.agentId).toBe(CHILD_THREAD_ID);
expect(input.agentType).toBe('subagent');
});
test('user SubagentStop has the parent session and the same agentId as its tool events', () => {
const input = normalize('SubagentStopUser');
expect(input.sessionId).toBe(SESSION_ID);
expect(input.agentId).toBe(normalize('PostToolUseSubagentRead').agentId);
expect(input.agentId).toBe(entries.SubagentStopUser.payload.child_session_id);
});
test('without MUSE_SESSION_ID uses the payload session_id and no agentId', () => {
process.env.MUSE_THREAD_ID = CHILD_THREAD_ID;
const input = museCodeAdapter.normalizeInput(entries.PostToolUseSubagentRead.payload);
expect(input.sessionId).toBe(CHILD_THREAD_ID);
expect(input.agentId).toBeUndefined();
expect(input.agentType).toBeUndefined();
});
test('an empty MUSE_SESSION_ID is treated as unset', () => {
process.env.MUSE_SESSION_ID = '';
process.env.MUSE_THREAD_ID = CHILD_THREAD_ID;
const input = museCodeAdapter.normalizeInput(entries.PostToolUseSubagentRead.payload);
expect(input.sessionId).toBe(CHILD_THREAD_ID);
expect(input.agentId).toBeUndefined();
});
test('only MUSE_SESSION_ID set gives the parent id and no agentId', () => {
process.env.MUSE_SESSION_ID = SESSION_ID;
const input = museCodeAdapter.normalizeInput(entries.PostToolUseSubagentRead.payload);
expect(input.sessionId).toBe(SESSION_ID);
expect(input.agentId).toBeUndefined();
expect(input.agentType).toBeUndefined();
});
test.each([
['missing', (({ session_id: _s, ...rest }) => rest)(entries.PostToolUseReadRelative.payload)],
['empty', { ...entries.PostToolUseReadRelative.payload, session_id: '' }],
])('rejects a %s session_id with no MUSE_SESSION_ID', (_label, payload) => {
expect(rejection(() => museCodeAdapter.normalizeInput(payload))).toBe('missing_session_id');
});
});
describe('museCodeAdapter cwd', () => {
const { cwd: _cwd, ...withoutCwd } = entries.PostToolUseReadRelative.payload;
test('falls back to process.cwd() without a payload cwd', () => {
process.env.MUSE_SESSION_ID = SESSION_ID;
expect(museCodeAdapter.normalizeInput(withoutCwd).cwd).toBe(process.cwd());
});
test('CLAUDE_PROJECT_DIR never wins over the payload cwd or process.cwd()', () => {
process.env.CLAUDE_PROJECT_DIR = '/Users/example/projects/some-claude-project';
expect(normalize('PostToolUseReadRelative').cwd).toBe(PROJECT);
expect(museCodeAdapter.normalizeInput(withoutCwd).cwd).toBe(process.cwd());
});
test.each([
['empty', ''],
['not a string', 42],
])('rejects an %s cwd', (_label, cwd) => {
expect(rejection(() => normalize('PostToolUseReadRelative', { cwd }))).toBe('invalid_cwd');
});
});
describe('museCodeAdapter drops the internal goal-reminder run', () => {
test.each(['SubagentStartReminder', 'SubagentStopReminder', 'PreToolUseReminder', 'PostToolUseReminder'])(
'%s is rejected as muse_internal_agent',
(name) => {
expect(rejection(() => normalize(name))).toBe('muse_internal_agent');
},
);
test('a user SubagentStart is not rejected', () => {
expect(rejection(() => normalize('SubagentStartUser'))).toBeUndefined();
const input = normalize('SubagentStartUser');
expect(input.sessionId).toBe(SESSION_ID);
expect(input.agentId).toBe(CHILD_THREAD_ID);
expect(input.agentType).toBe('subagent');
});
});
describe('museCodeAdapter tool names and inputs', () => {
test('read_file with a relative path maps to Read with a file_path under cwd', () => {
const input = normalize('PostToolUseReadRelative');
expect(input.toolName).toBe('Read');
expect(input.nativeToolName).toBe('read_file');
expect(input.toolInput).toEqual({ path: 'notes.txt', file_path: `${PROJECT}/notes.txt` });
});
test('a PreToolUse read_file maps to Read with a file_path under cwd', () => {
const input = normalize('PreToolUseReadRelative');
expect(input.toolName).toBe('Read');
expect(input.nativeToolName).toBe('read_file');
expect(input.toolInput).toEqual({ path: 'src/big.ts', file_path: `${PROJECT}/src/big.ts` });
});
test('apply_patch is not mapped and passes unchanged', () => {
const input = normalize('PostToolUseEdit', { tool_name: 'apply_patch' });
expect(input.toolName).toBe('apply_patch');
expect(input.nativeToolName).toBeUndefined();
expect((input.toolInput as any).file_path).toBeUndefined();
});
test('read_file with an absolute path keeps it as file_path', () => {
expect((normalize('PostToolUseReadAbsolute').toolInput as any).file_path).toBe('/Users/example/projects/outside/other.txt');
});
test('read_file with ~ is not expanded (Muse reads <cwd>/~/x)', () => {
expect((normalize('PreToolUseReadTilde').toolInput as any).file_path).toBe(`${PROJECT}/~/.zshrc`);
});
test('read_file keeps offset and limit', () => {
expect(normalize('PostToolUseReadRange').toolInput).toEqual({
path: 'notes.txt', offset: 2, limit: 1, file_path: `${PROJECT}/notes.txt`,
});
});
test.each([
['no path', {}],
['an empty path', { path: '' }],
['a non-string path', { path: 7 }],
])('read_file with %s maps to Read without file_path and does not throw', (_label, toolInput) => {
const input = normalize('PostToolUseReadRelative', { tool_input: toolInput });
expect(input.toolName).toBe('Read');
expect(input.toolInput).toEqual(toolInput);
});
test('an input that already has file_path is not overwritten', () => {
const toolInput = { path: 'notes.txt', file_path: '/elsewhere/notes.txt' };
expect(normalize('PostToolUseReadRelative', { tool_input: toolInput }).toolInput).toEqual(toolInput);
});
test('write_file maps to Write with file_path and content kept', () => {
const input = normalize('PostToolUseWrite');
expect(input.toolName).toBe('Write');
expect(input.toolInput).toEqual({ path: 'a.txt', content: 'one', file_path: `${PROJECT}/a.txt` });
});
test('edit_file maps to Edit with file_path and find/replace kept', () => {
const input = normalize('PostToolUseEdit');
expect(input.toolName).toBe('Edit');
expect(input.toolInput).toEqual({ path: 'a.txt', find: 'one', replace: 'two', file_path: `${PROJECT}/a.txt` });
});
test('bash maps to Bash with the input kept', () => {
const input = normalize('PostToolUseBash');
expect(input.toolName).toBe('Bash');
expect(input.toolInput).toEqual(entries.PostToolUseBash.payload.tool_input);
});
test('search maps to Grep with glob/output_mode kept and no file_path', () => {
const input = normalize('PostToolUseSearch');
expect(input.toolName).toBe('Grep');
expect(input.toolInput).toEqual(entries.PostToolUseSearch.payload.tool_input);
expect(normalize('PostToolUseSearch', { tool_input: { pattern: 'x', path: 'src' } }).toolInput).toEqual({ pattern: 'x', path: 'src' });
});
test('web_fetch maps to WebFetch', () => {
expect(normalize('PostToolUseWebFetch').toolName).toBe('WebFetch');
});
test.each([
['bash', 'Bash'],
['read_file', 'Read'],
['write_file', 'Write'],
['edit_file', 'Edit'],
['search', 'Grep'],
['web_fetch', 'WebFetch'],
])('mapped tool %s sets nativeToolName', (raw, mapped) => {
const input = normalize('PostToolUseBash', { tool_name: raw });
expect(input.toolName).toBe(mapped);
expect(input.nativeToolName).toBe(raw);
});
test('the claude-mem MCP search passes unchanged and counts as its own recall', () => {
const input = normalize('PostToolUseMcpSearch');
expect(input.toolName).toBe('mcp__claude_mem__search');
expect(input.nativeToolName).toBeUndefined();
expect(isRecursiveMemoryTool(input.toolName!)).toBe(true);
});
test.each(['todo_write', 'subagent_spawn', 'subagent_wait', 'Read', 'constructor', '__proto__'])(
'unmapped tool %s passes unchanged without nativeToolName',
(name) => {
const input = normalize('PostToolUseSubagentSpawn', { tool_name: name });
expect(input.toolName).toBe(name);
expect(input.nativeToolName).toBeUndefined();
},
);
test('subagent_spawn and subagent_wait from the fixture pass unchanged', () => {
expect(normalize('PostToolUseSubagentSpawn').toolName).toBe('subagent_spawn');
expect(normalize('PostToolUseSubagentWait').toolName).toBe('subagent_wait');
});
});
describe('museCodeAdapter fields from the Claude Code adapter', () => {
test('PostToolUseFailure becomes an error response', () => {
const input = normalize('PostToolUseFailureRead');
expect(input.toolResponse).toEqual({ is_error: true, error: entries.PostToolUseFailureRead.payload.error, is_interrupt: false });
expect(input.toolUseId).toBe(entries.PostToolUseFailureRead.payload.tool_use_id);
});
test('a tool_response string with newlines and N| prefixes is kept byte-equal', () => {
expect(normalize('PostToolUseReadRelative').toolResponse).toBe(entries.PostToolUseReadRelative.payload.tool_response);
});
test('reads the prompt from UserPromptSubmit', () => {
expect(normalize('UserPromptSubmit').prompt).toBe('Read notes.txt and tell me the marker.');
});
test.each([null, '/tmp/muse/transcript.jsonl'])('transcript_path %p gives no transcriptPath', (transcriptPath) => {
expect(normalize('Stop', { transcript_path: transcriptPath }).transcriptPath).toBeUndefined();
});
test('Stop keeps last_assistant_message; null or empty is undefined', () => {
expect(normalize('Stop').lastAssistantMessage).toBe(entries.Stop.payload.last_assistant_message);
expect(normalize('Stop', { last_assistant_message: null }).lastAssistantMessage).toBeUndefined();
expect(normalize('Stop', { last_assistant_message: '' }).lastAssistantMessage).toBeUndefined();
});
test('stop_hook_active true is not mapped', () => {
expect(normalize('Stop', { stop_hook_active: true }).stopHookActive).toBeUndefined();
});
test('SessionStart source compact maps to compact; unknown source is undefined', () => {
expect(normalize('SessionStartStartup').sessionSource).toBe('startup');
expect(normalize('SessionStartCompact').sessionSource).toBe('compact');
expect(normalize('SessionStartStartup', { source: 'other' }).sessionSource).toBeUndefined();
});
test('SessionEnd keeps the reason', () => {
expect(normalize('SessionEnd').reason).toBe('other');
});
});
describe('museCodeAdapter.formatOutput', () => {
test('equals the Claude Code envelope', () => {
const result = { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: 'memory' } };
expect(museCodeAdapter.formatOutput(result)).toEqual(claudeCodeAdapter.formatOutput(result));
expect(museCodeAdapter.formatOutput({})).toEqual({});
});
test.each(['PreToolUse', 'SubagentStart'])('passes a %s additionalContext through byte-equal, with no permissionDecision', (hookEventName) => {
const additionalContext = 'line one\r\nline two\n| table |\n';
const output = museCodeAdapter.formatOutput({ hookSpecificOutput: { hookEventName, additionalContext } } as any);
expect(output).toEqual({ hookSpecificOutput: { hookEventName, additionalContext } });
expect(JSON.stringify(output)).not.toContain('permissionDecision');
});
});