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, mock, spyOn, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import path from 'path';
import * as realInstallPathsModule from '../../src/services/integrations/install-paths.js';
import {
ATOMCODE_STATUS_LABELS,
atomcodeHooksPath,
atomcodeMcpPath,
buildAtomCodeHooks,
checkAtomCodeStatus,
handleAtomCodeCommand,
installAtomCode,
isClaudeMemAtomCodeHook,
mergeAtomCodeHooks,
readAtomCodeStatus,
removeAtomCodeHooks,
uninstallAtomCode,
} from '../../src/services/integrations/AtomCodeHooksInstaller.js';
const INSTALL_PATHS = '../../src/services/integrations/install-paths.js';
const realInstallPathsSnapshot = { ...realInstallPathsModule };
let scratch: string | undefined;
const priorAtomcodeHome = process.env.ATOMCODE_HOME;
afterEach(() => {
if (scratch) rmSync(scratch, { recursive: true, force: true });
scratch = undefined;
if (priorAtomcodeHome === undefined) delete process.env.ATOMCODE_HOME;
else process.env.ATOMCODE_HOME = priorAtomcodeHome;
mock.module(INSTALL_PATHS, () => realInstallPathsSnapshot);
mock.restore();
});
// Every test writes under a temp dir; the real ~/.atomcode is never touched.
function scratchPaths(dirName = 'atomcode-install-test'): { hooks: string; mcp: string } {
scratch = path.join(tmpdir(), `${dirName}-${process.pid}-${Date.now()}`);
mkdirSync(scratch, { recursive: true });
return { hooks: path.join(scratch, 'hooks.json'), mcp: path.join(scratch, 'mcp.json') };
}
function writeJson(filePath: string, content: unknown): string {
mkdirSync(path.dirname(filePath), { recursive: true });
const text = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
writeFileSync(filePath, text, 'utf-8');
return text;
}
function readJson(filePath: string): any {
return JSON.parse(readFileSync(filePath, 'utf-8'));
}
const backups = (filePath: string) =>
readdirSync(path.dirname(filePath)).filter((name) => name.startsWith(`${path.basename(filePath)}.bak-`));
const quiet = () => {
const log = spyOn(console, 'log').mockImplementation(() => {});
const error = spyOn(console, 'error').mockImplementation(() => {});
const stdout = () => (log as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().join('\n');
return Object.assign(error, { stdout });
};
const BUN = '/usr/local/bin/bun';
const WORKER = '/plugin/scripts/worker-service.cjs';
const withInstallPaths = (overrides: Record<string, unknown>, run: () => void) => {
mock.module(INSTALL_PATHS, () => ({ ...realInstallPathsSnapshot, ...overrides }));
try {
run();
} finally {
mock.module(INSTALL_PATHS, () => realInstallPathsSnapshot);
}
};
const stubInstallPaths = (overrides: Record<string, unknown> = {}) => {
mock.module(INSTALL_PATHS, () => ({
...realInstallPathsSnapshot,
getBunAbsolutePath: () => BUN,
getWorkerServiceAbsolutePath: () => WORKER,
getMcpServerAbsolutePath: () => '/plugin/scripts/mcp-server.cjs',
...overrides,
}));
};
describe('AtomCode paths', () => {
test('$ATOMCODE_HOME relocates both files', () => {
process.env.ATOMCODE_HOME = '/tmp/custom-atomcode-home';
expect(atomcodeHooksPath()).toBe(path.join('/tmp/custom-atomcode-home', 'hooks.json'));
expect(atomcodeMcpPath()).toBe(path.join('/tmp/custom-atomcode-home', 'mcp.json'));
});
test('an unset $ATOMCODE_HOME falls back to ~/.atomcode', () => {
delete process.env.ATOMCODE_HOME;
expect(atomcodeHooksPath().endsWith(path.join('.atomcode', 'hooks.json'))).toBe(true);
expect(atomcodeMcpPath().endsWith(path.join('.atomcode', 'mcp.json'))).toBe(true);
});
});
describe('AtomCode hook building', () => {
const ours = buildAtomCodeHooks(BUN, WORKER);
// AtomCode's `hooks` is a flat map, not event -> array like Claude Code. A
// nested shape would parse as zero hooks, so the flatness is the contract.
test('is a flat map whose every value names one event', () => {
for (const [name, entry] of Object.entries(ours)) {
expect(typeof name).toBe('string');
expect(typeof entry.event).toBe('string');
expect(typeof entry.command).toBe('string');
expect(typeof entry.timeout_ms).toBe('number');
}
expect(new Set(Object.values(ours).map((entry) => entry.event))).toEqual(
new Set(['SessionStart', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'Stop', 'SessionEnd']),
);
});
test('quotes both absolute paths so a spaced install dir still runs', () => {
const spaced = buildAtomCodeHooks('/opt/my bun/bun', '/opt/claude mem/scripts/worker-service.cjs');
expect(spaced['claude-mem-start'].command).toBe(
`"/opt/my bun/bun" "/opt/claude mem/scripts/worker-service.cjs" start`,
);
});
// AtomCode's PreToolUse can deny or rewrite a call, so the read-context rule
// is matched to read_file alone rather than every tool.
test('matches the file-context rule to read_file only', () => {
expect(ours['claude-mem-file-context'].matcher).toBe('read_file');
expect(ours['claude-mem-observation'].matcher).toBeUndefined();
expect(ours['claude-mem-start'].matcher).toBeUndefined();
});
// AtomCode matchers are `|`-separated globs: `.`, `^`, `$`, `[]` and `()` are
// taken literally, so a regex-shaped matcher silently never fires.
test('writes only glob matchers, never regex syntax', () => {
for (const entry of Object.values(ours)) {
if (entry.matcher === undefined) continue;
expect(entry.matcher).not.toMatch(/[\^$.\[\]()+?{}\\]/);
}
});
test('two SessionStart entries: capture and context injection', () => {
const starts = Object.values(ours).filter((entry) => entry.event === 'SessionStart');
expect(starts).toHaveLength(2);
expect(starts.map((entry) => entry.command.split(' ').slice(2).join(' ')).sort()).toEqual([
'hook atomcode context',
'start',
]);
});
});
describe('owning only our own hooks', () => {
const ours = buildAtomCodeHooks(BUN, WORKER);
test('recognises our commands and nothing else', () => {
for (const entry of Object.values(ours)) {
expect(isClaudeMemAtomCodeHook(entry)).toBe(true);
}
expect(isClaudeMemAtomCodeHook({ event: 'Stop', command: `echo "${WORKER}" start` })).toBe(false);
expect(isClaudeMemAtomCodeHook({ event: 'Stop', command: `${BUN} ${WORKER} start` })).toBe(false);
expect(isClaudeMemAtomCodeHook({ event: 'Stop', command: 'notify-send done' })).toBe(false);
expect(isClaudeMemAtomCodeHook({ event: 'Stop', command: `${BUN} ${WORKER} hook atomcode start` })).toBe(false);
});
test('remove keeps every other entry under its own name', () => {
const userHook = { event: 'PreToolUse', command: '/usr/local/bin/audit.sh', matcher: 'bash' };
const merged = mergeAtomCodeHooks({ 'user-audit': userHook }, ours);
expect(Object.keys(merged)).toContain('user-audit');
expect(removeAtomCodeHooks(merged)).toEqual({ 'user-audit': userHook });
});
test('merge is idempotent: installing twice leaves one set', () => {
const once = mergeAtomCodeHooks({}, ours);
const twice = mergeAtomCodeHooks(once, ours);
expect(Object.keys(twice).sort()).toEqual(Object.keys(once).sort());
expect(twice).toEqual(once);
});
});
describe('install', () => {
test('writes hooks and the MCP server, preserving other entries in both files', () => {
quiet();
withInstallPaths({}, () => {
const paths = scratchPaths();
stubInstallPaths();
writeJson(paths.hooks, { hooks: { 'user-audit': { event: 'PreToolUse', command: '/usr/local/bin/audit.sh' } } });
writeJson(paths.mcp, { mcpServers: { playwright: { command: 'npx', args: ['@playwright/mcp@latest'] } } });
expect(installAtomCode(paths.hooks, paths.mcp)).toBe(0);
const hooks = readJson(paths.hooks);
expect(Object.keys(hooks.hooks)).toContain('user-audit');
expect(Object.values(hooks.hooks).filter((entry: any) => isClaudeMemAtomCodeHook(entry))).toHaveLength(
Object.keys(buildAtomCodeHooks(BUN, WORKER)).length,
);
const mcp = readJson(paths.mcp);
expect(mcp.mcpServers.playwright).toEqual({ command: 'npx', args: ['@playwright/mcp@latest'] });
expect(mcp.mcpServers['claude-mem'].args[0]).toBe('/plugin/scripts/mcp-server.cjs');
});
});
test('creates both files when the host has none', () => {
quiet();
const paths = scratchPaths();
stubInstallPaths();
expect(installAtomCode(paths.hooks, paths.mcp)).toBe(0);
expect(existsSync(paths.hooks)).toBe(true);
expect(existsSync(paths.mcp)).toBe(true);
});
test('backs each file up once, owner-only', () => {
quiet();
const paths = scratchPaths();
stubInstallPaths();
writeJson(paths.hooks, { hooks: {} });
installAtomCode(paths.hooks, paths.mcp);
installAtomCode(paths.hooks, paths.mcp);
expect(backups(paths.hooks)).toHaveLength(1);
expect(backups(paths.mcp)).toHaveLength(1);
});
// AtomCode accepts comments in hooks.json and mcp.json; rewriting would drop them.
test('refuses a file with comments, saying why, and leaves it untouched', () => {
const paths = scratchPaths();
stubInstallPaths();
const before = writeJson(paths.mcp, '{\n // my servers\n "mcpServers": {}\n}\n');
const error = quiet();
expect(installAtomCode(paths.hooks, paths.mcp)).toBe(1);
expect(readFileSync(paths.mcp, 'utf-8')).toBe(before);
const message = (error as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().join('\n');
expect(message).toContain(`${paths.mcp} is not plain JSON`);
expect(message).toContain('Remove the comments or add the entries by hand');
});
test('refuses malformed JSON instead of overwriting it', () => {
const paths = scratchPaths();
stubInstallPaths();
const before = writeJson(paths.hooks, '{ not json');
const error = quiet();
expect(installAtomCode(paths.hooks, paths.mcp)).toBe(1);
expect(readFileSync(paths.hooks, 'utf-8')).toBe(before);
expect(error).toHaveBeenCalled();
});
test('refuses a hooks entry that is not an object', () => {
const paths = scratchPaths();
stubInstallPaths();
const before = writeJson(paths.hooks, { hooks: { broken: 'echo hi' } });
quiet();
expect(installAtomCode(paths.hooks, paths.mcp)).toBe(1);
expect(readFileSync(paths.hooks, 'utf-8')).toBe(before);
});
test('refuses an mcpServers value that is not an object', () => {
const paths = scratchPaths();
stubInstallPaths();
const before = writeJson(paths.mcp, { mcpServers: 'nope' });
quiet();
expect(installAtomCode(paths.hooks, paths.mcp)).toBe(1);
expect(readFileSync(paths.mcp, 'utf-8')).toBe(before);
});
test('fails without writing when the plugin payload cannot be located', () => {
const paths = scratchPaths();
const error = quiet();
stubInstallPaths({ getWorkerServiceAbsolutePath: () => null });
expect(installAtomCode(paths.hooks, paths.mcp)).toBe(1);
expect(error).toHaveBeenCalled();
expect(existsSync(paths.hooks)).toBe(false);
expect(existsSync(paths.mcp)).toBe(false);
});
});
describe('uninstall', () => {
test('removes ours and leaves the user hooks and MCP servers', () => {
quiet();
const paths = scratchPaths();
stubInstallPaths();
writeJson(paths.hooks, { hooks: { 'user-audit': { event: 'PreToolUse', command: '/usr/local/bin/audit.sh' } } });
writeJson(paths.mcp, { mcpServers: { playwright: { command: 'npx', args: ['x'] } } });
installAtomCode(paths.hooks, paths.mcp);
expect(uninstallAtomCode(paths.hooks, paths.mcp)).toBe(0);
expect(readJson(paths.hooks).hooks).toEqual({
'user-audit': { event: 'PreToolUse', command: '/usr/local/bin/audit.sh' },
});
expect(readJson(paths.mcp).mcpServers).toEqual({ playwright: { command: 'npx', args: ['x'] } });
});
test('drops the keys it emptied rather than leaving an empty object', () => {
quiet();
const paths = scratchPaths();
stubInstallPaths();
installAtomCode(paths.hooks, paths.mcp);
uninstallAtomCode(paths.hooks, paths.mcp);
expect(Object.hasOwn(readJson(paths.hooks), 'hooks')).toBe(false);
expect(Object.hasOwn(readJson(paths.mcp), 'mcpServers')).toBe(false);
});
test('is a no-op when nothing of ours is installed', () => {
const log = quiet();
// Explicit scratch paths: the default would be the real ~/.atomcode.
const paths = scratchPaths();
expect(uninstallAtomCode(paths.hooks, paths.mcp)).toBe(0);
expect(log.stdout()).toContain('nothing to uninstall');
});
});
describe('status', () => {
test('reports not-installed, installed and incomplete', () => {
quiet();
const paths = scratchPaths();
stubInstallPaths();
expect(readAtomCodeStatus(paths.hooks, paths.mcp).status).toBe('not-installed');
installAtomCode(paths.hooks, paths.mcp);
expect(readAtomCodeStatus(paths.hooks, paths.mcp).status).toBe('installed');
// One missing event is enough to call the install incomplete.
const hooks = readJson(paths.hooks);
delete hooks.hooks['claude-mem-observation'];
writeJson(paths.hooks, hooks);
const status = readAtomCodeStatus(paths.hooks, paths.mcp);
expect(status.status).toBe('incomplete');
expect(status.detail).toContain('PostToolUse');
});
// Both SessionStart entries share an event; losing either breaks capture or recall.
test('a missing SessionStart entry is incomplete even though the event is still there', () => {
quiet();
const paths = scratchPaths();
stubInstallPaths();
installAtomCode(paths.hooks, paths.mcp);
for (const name of ['claude-mem-start', 'claude-mem-context']) {
installAtomCode(paths.hooks, paths.mcp);
const hooks = readJson(paths.hooks);
delete hooks.hooks[name];
writeJson(paths.hooks, hooks);
const status = readAtomCodeStatus(paths.hooks, paths.mcp);
expect(status.status).toBe('incomplete');
expect(status.detail).toContain('SessionStart');
}
});
test('a missing MCP server alone is incomplete', () => {
quiet();
const paths = scratchPaths();
stubInstallPaths();
installAtomCode(paths.hooks, paths.mcp);
rmSync(paths.mcp);
const status = readAtomCodeStatus(paths.hooks, paths.mcp);
expect(status.status).toBe('incomplete');
expect(status.detail).toContain('MCP server');
});
test('reports unreadable rather than throwing on broken JSON', () => {
const paths = scratchPaths();
writeJson(paths.hooks, '{ nope');
expect(readAtomCodeStatus(paths.hooks, paths.mcp).status).toBe('unreadable');
});
test('labels cover every state', () => {
expect(Object.keys(ATOMCODE_STATUS_LABELS).sort()).toEqual([
'incomplete',
'installed',
'not-installed',
'unreadable',
]);
});
test('check exits non-zero unless installed', () => {
quiet();
const paths = scratchPaths();
stubInstallPaths();
expect(checkAtomCodeStatus(paths.hooks, paths.mcp)).toBe(1);
installAtomCode(paths.hooks, paths.mcp);
expect(checkAtomCodeStatus(paths.hooks, paths.mcp)).toBe(0);
});
test('check reports an unreadable config on stderr', () => {
const error = quiet();
const paths = scratchPaths();
writeJson(paths.hooks, '{ nope');
expect(checkAtomCodeStatus(paths.hooks, paths.mcp)).toBe(1);
expect(error).toHaveBeenCalled();
});
});
describe('CLI subcommands', () => {
test('install, status and uninstall each answer, and an unknown one reports usage', async () => {
const log = quiet();
stubInstallPaths();
process.env.ATOMCODE_HOME = path.join(tmpdir(), `atomcode-cli-${process.pid}-${Date.now()}`);
const home = process.env.ATOMCODE_HOME;
try {
expect(await handleAtomCodeCommand('install', [])).toBe(0);
expect(await handleAtomCodeCommand('status', [])).toBe(0);
expect(await handleAtomCodeCommand('uninstall', [])).toBe(0);
expect(await handleAtomCodeCommand('bogus', [])).toBe(1);
expect(log.stdout()).toContain('Usage:');
} finally {
rmSync(home, { recursive: true, force: true });
}
});
test('no subcommand prints usage and succeeds', async () => {
const log = quiet();
expect(await handleAtomCodeCommand(undefined, [])).toBe(0);
expect(log.stdout()).toContain('Usage:');
});
});