Skip to content

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

20.7 KB
Raw Blame
import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'fs';
import { homedir, tmpdir } from 'os';
import path from 'path';
import * as realInstallPathsModule from '../../src/services/integrations/install-paths.js';
import {
  buildMuseCodeHooks,
  checkMuseCodeStatus,
  handleMuseCodeCommand,
  installMuseCode,
  isClaudeMemMuseCodeCommand,
  mergeMuseCodeHooks,
  MUSE_CODE_STATUS_LABELS,
  museCodeSettingsPath,
  readMuseCodeStatus,
  removeMuseCodeHooks,
  uninstallMuseCode,
  type MuseCodeStatus,
} from '../../src/services/integrations/MuseCodeHooksInstaller.js';

const realInstallPathsSnapshot = { ...realInstallPathsModule };

let scratch: string | undefined;

afterEach(() => {
  if (scratch) rmSync(scratch, { recursive: true, force: true });
  scratch = undefined;
  mock.restore();
});

// Every test writes under a temp dir; the real ~/.config/muse is never touched.
function scratchSettingsPath(dirName = 'muse-install-test'): string {
  scratch = path.join(tmpdir(), `${dirName}-${process.pid}-${Date.now()}`);
  mkdirSync(scratch, { recursive: true });
  return path.join(scratch, '.config', 'muse', 'settings.json');
}

function writeSettings(settingsPath: string, content: unknown): string {
  mkdirSync(path.dirname(settingsPath), { recursive: true });
  const text = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
  writeFileSync(settingsPath, text);
  return text;
}

const readSettings = (settingsPath: string) => JSON.parse(readFileSync(settingsPath, 'utf-8'));
const backups = (settingsPath: string) => readdirSync(path.dirname(settingsPath)).filter((name) => name.startsWith('settings.json.bak-'));
const quiet = () => {
  spyOn(console, 'log').mockImplementation(() => {});
  return spyOn(console, 'error').mockImplementation(() => {});
};
const logged = () => (console.log as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().join('\n');

const withInstallPaths = (overrides: Record<string, unknown>, run: () => void) => {
  mock.module('../../src/services/integrations/install-paths.js', () => ({ ...realInstallPathsSnapshot, ...overrides }));
  try {
    run();
  } finally {
    mock.module('../../src/services/integrations/install-paths.js', () => realInstallPathsSnapshot);
  }
};

const BUN = '/usr/local/bin/bun';
const WORKER = '/plugin/scripts/worker-service.cjs';
const EVENTS = ['SessionStart', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'Stop', 'SubagentStart', 'SubagentStop', 'SessionEnd'];
const USER_HOOK = { matcher: 'bash', hooks: [{ type: 'command', command: '/usr/bin/audit --log', timeout: 5 }] };
const USER_WORKER_HOOK = { matcher: '*', hooks: [{ type: 'command', command: `echo "${WORKER}" start` }] };

describe('museCodeSettingsPath', () => {
  test('is ~/.config/muse/settings.json', () => {
    expect(museCodeSettingsPath()).toBe(path.join(homedir(), '.config', 'muse', 'settings.json'));
  });
});

describe('Muse Code hook building and merge', () => {
  const ours = buildMuseCodeHooks(BUN, WORKER);

  test('registers quoted command hooks with their matcher and timeouts in seconds', () => {
    expect(Object.keys(ours)).toEqual(EVENTS);
    const hooks = Object.values(ours).flatMap((rules) => rules.map((rule) => ({ matcher: rule.matcher, ...rule.hooks[0] })));
    const run = (suffix: string) => `"${BUN}" "${WORKER}" ${suffix}`;
    expect(hooks).toEqual([
      { matcher: '*', type: 'command', command: run('start'), timeout: 60 },
      { matcher: '*', type: 'command', command: run('hook muse-code context'), timeout: 60 },
      { matcher: '*', type: 'command', command: run('hook muse-code session-init'), timeout: 15 },
      { matcher: '^read_file$', type: 'command', command: run('hook muse-code file-context'), timeout: 15 },
      { matcher: '*', type: 'command', command: run('hook muse-code observation'), timeout: 120 },
      { matcher: '*', type: 'command', command: run('hook muse-code observation'), timeout: 120 },
      { matcher: '*', type: 'command', command: run('hook muse-code summarize'), timeout: 120 },
      { matcher: '*', type: 'command', command: run('hook muse-code subagent-context'), timeout: 20 },
      { matcher: '*', type: 'command', command: run('hook muse-code subagent-stop'), timeout: 30 },
      { matcher: '*', type: 'command', command: run('hook muse-code session-end'), timeout: 30 },
    ]);
  });

  test('keeps a user hook on the same event and appends ours after it, once', () => {
    const once = mergeMuseCodeHooks({ PostToolUse: [USER_HOOK] }, ours);
    const twice = mergeMuseCodeHooks(once, ours);
    expect(twice).toEqual(once);
    expect(twice.PostToolUse).toEqual([USER_HOOK, ...ours.PostToolUse]);
  });

  test('replaces stale hooks from an older worker path without duplicates', () => {
    const stale = buildMuseCodeHooks(BUN, '/old/plugin/scripts/worker-service.cjs');
    expect(mergeMuseCodeHooks(mergeMuseCodeHooks({}, stale), ours)).toEqual(ours);
  });

  test('does not claim a user command that mentions worker-service.cjs in another shape', () => {
    for (const command of [
      `echo "${WORKER}" start`,
      `"${BUN}" "${WORKER}" hook muse-code observation --extra`,
      `"${BUN}" "${WORKER}" hook zcode observation`,
      `"${BUN}" "${WORKER}" hook muse-code file-context-x`,
      `"${BUN}" "${WORKER}" hook kimi file-context`,
      `echo "${WORKER}" hook muse-code file-context`,
      `"${BUN}" "${WORKER}" stop`,
      `"/usr/bin/node" "${WORKER}" start`,
      `"${BUN}" "/tmp/worker-service.cjs" start`,
      `${BUN} ${WORKER} start`,
    ]) {
      expect(isClaudeMemMuseCodeCommand({ type: 'command', command })).toBe(false);
    }
    expect(removeMuseCodeHooks({ SessionStart: [USER_WORKER_HOOK] })).toEqual({ SessionStart: [USER_WORKER_HOOK] });
  });

  test('quotes paths with spaces and claims every hook it writes', () => {
    for (const [bun, worker] of [
      ['bun', WORKER],
      ['/Users/a b/.bun/bin/bun', '/Users/a b/plugin dir/scripts/worker-service.cjs'],
      ['C:\\Users\\a b\\.bun\\bin\\bun.exe', 'C:\\Users\\a b\\plugin\\scripts\\worker-service.cjs'],
    ]) {
      const built = buildMuseCodeHooks(bun, worker);
      const hooks = Object.values(built).flatMap((rules) => rules.flatMap((rule) => rule.hooks));
      expect(hooks.every((hook) => hook.command!.startsWith(`"${bun}" "${worker}" `))).toBe(true);
      expect(hooks.every(isClaudeMemMuseCodeCommand)).toBe(true);
      expect(removeMuseCodeHooks(built)).toEqual({});
    }
  });
});

describe('installMuseCode', () => {
  test('creates settings.json with schema_version 1, every hook and the claude-mem MCP server, and no backup', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    expect(installMuseCode(settingsPath)).toBe(0);
    const settings = readSettings(settingsPath);
    expect(settings.schema_version).toBe(1);
    expect(Object.keys(settings.hooks)).toEqual(EVENTS);
    expect(Object.keys(settings.mcpServers)).toEqual(['claude-mem']);
    expect(settings.mcpServers['claude-mem'].command).toBe(process.execPath);
    expect(String(settings.mcpServers['claude-mem'].args[0])).toEndWith('mcp-server.cjs');
    expect(backups(settingsPath)).toEqual([]);
  });

  test('keeps other keys, user hooks and MCP servers; backs up once with mode 0o600; second install is identical', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    const original = {
      schema_version: 1,
      model: 'muse-ember-1.0',
      tui: { theme: 'dark' },
      provider: { name: 'meta' },
      hooks: { PostToolUse: [USER_HOOK], SessionStart: [USER_WORKER_HOOK] },
      mcpServers: { other: { command: 'y', args: [] } },
    };
    writeSettings(settingsPath, original);
    expect(installMuseCode(settingsPath)).toBe(0);
    const settings = readSettings(settingsPath);
    expect(settings.schema_version).toBe(1);
    expect(settings.model).toBe(original.model);
    expect(settings.tui).toEqual(original.tui);
    expect(settings.provider).toEqual(original.provider);
    expect(settings.hooks.PostToolUse[0]).toEqual(USER_HOOK);
    expect(settings.hooks.PostToolUse).toHaveLength(2);
    expect(settings.hooks.SessionStart[0]).toEqual(USER_WORKER_HOOK);
    expect(settings.hooks.SessionStart).toHaveLength(3);
    expect(settings.mcpServers.other).toEqual(original.mcpServers.other);
    expect(backups(settingsPath)).toHaveLength(1);
    const backupPath = path.join(path.dirname(settingsPath), backups(settingsPath)[0]);
    if (process.platform !== 'win32') expect(statSync(backupPath).mode & 0o777).toBe(0o600);
    expect(readSettings(backupPath)).toEqual(original);

    const firstText = readFileSync(settingsPath, 'utf-8');
    expect(installMuseCode(settingsPath)).toBe(0);
    expect(readFileSync(settingsPath, 'utf-8')).toBe(firstText);
    expect(backups(settingsPath)).toHaveLength(1);
  });

  test('replaces an existing claude-mem MCP entry and keeps other servers', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    writeSettings(settingsPath, { mcpServers: { 'claude-mem': { command: 'old', args: ['/old/mcp-server.cjs'] }, other: { command: 'y' } } });
    expect(installMuseCode(settingsPath)).toBe(0);
    const servers = readSettings(settingsPath).mcpServers;
    expect(servers.other).toEqual({ command: 'y' });
    expect(servers['claude-mem'].command).toBe(process.execPath);
    expect(String(servers['claude-mem'].args[0])).toEndWith('mcp-server.cjs');
  });

  test('replaces stale claude-mem hooks in the file without duplicates', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    writeSettings(settingsPath, { hooks: buildMuseCodeHooks(BUN, '/old/plugin/scripts/worker-service.cjs') });
    expect(installMuseCode(settingsPath)).toBe(0);
    const hooks = readSettings(settingsPath).hooks;
    expect(hooks.SessionStart).toHaveLength(2);
    expect(hooks.Stop).toHaveLength(1);
    expect(JSON.stringify(hooks)).not.toContain('/old/plugin');
  });

  test('keeps a user PreToolUse hook first and writes ours after it; uninstall drops only ours', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    writeSettings(settingsPath, { hooks: { PreToolUse: [USER_HOOK] } });
    expect(installMuseCode(settingsPath)).toBe(0);
    const pre = readSettings(settingsPath).hooks.PreToolUse;
    expect(pre).toHaveLength(2);
    expect(pre[0]).toEqual(USER_HOOK);
    expect(pre[1].matcher).toBe('^read_file$');
    expect(pre[1].hooks[0].command).toEndWith('hook muse-code file-context');
    expect(pre[1].hooks[0].timeout).toBe(15);
    expect(readSettings(settingsPath).hooks.SubagentStart[0].hooks[0].command).toEndWith('hook muse-code subagent-context');
    expect(uninstallMuseCode(settingsPath)).toBe(0);
    expect(readSettings(settingsPath).hooks).toEqual({ PreToolUse: [USER_HOOK] });
  });

  test('upgrades a Phase 1 install in place: incomplete, then installed without duplicates', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    const phase1 = buildMuseCodeHooks(BUN, WORKER);
    delete phase1.PreToolUse;
    delete phase1.SubagentStart;
    writeSettings(settingsPath, { hooks: phase1, mcpServers: { 'claude-mem': { command: 'node' } } });
    expect(readMuseCodeStatus(settingsPath)).toEqual({ status: 'incomplete', detail: 'missing PreToolUse, SubagentStart' });
    expect(installMuseCode(settingsPath)).toBe(0);
    expect(readMuseCodeStatus(settingsPath).status).toBe('installed');
    const hooks = readSettings(settingsPath).hooks;
    expect(hooks.PreToolUse).toHaveLength(1);
    expect(hooks.SubagentStart).toHaveLength(1);
    expect(hooks.SessionStart).toHaveLength(2);
  });

  test('refuses settings that are not usable JSON objects and leaves the file byte-equal with no backup', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    for (const content of ['{ not json', '[]', 'null', '"x"', { hooks: [] }, { hooks: null }, { mcpServers: 'x' }, { mcpServers: [] }]) {
      const text = writeSettings(settingsPath, content);
      expect(installMuseCode(settingsPath)).toBe(1);
      expect(readFileSync(settingsPath, 'utf-8')).toBe(text);
    }
    expect(backups(settingsPath)).toEqual([]);
  });

  test('keeps the user\'s empty hook entries', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    const emptyRule = { matcher: '*', hooks: [] };
    writeSettings(settingsPath, { hooks: { PreCompact: [], PostToolUse: [emptyRule] } });
    expect(installMuseCode(settingsPath)).toBe(0);
    const hooks = readSettings(settingsPath).hooks;
    expect(hooks.PreCompact).toEqual([]);
    expect(hooks.PostToolUse[0]).toEqual(emptyRule);
    expect(hooks.PostToolUse).toHaveLength(2);
    const text = readFileSync(settingsPath, 'utf-8');
    expect(installMuseCode(settingsPath)).toBe(0);
    expect(readFileSync(settingsPath, 'utf-8')).toBe(text);
  });

  test('refuses a non-array value on an event it writes, before any backup or write', () => {
    const errors = quiet();
    const settingsPath = scratchSettingsPath();
    for (const stop of ['abc', { a: 1 }, null]) {
      const text = writeSettings(settingsPath, { hooks: { Stop: stop } });
      expect(installMuseCode(settingsPath)).toBe(1);
      expect(readFileSync(settingsPath, 'utf-8')).toBe(text);
    }
    expect(backups(settingsPath)).toEqual([]);
    expect(errors.mock.calls.flat().join('\n')).toContain('"hooks.Stop"');
  });

  test('leaves a non-array value on an event it does not write untouched', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    writeSettings(settingsPath, { hooks: { PreCompact: 'abc' } });
    expect(installMuseCode(settingsPath)).toBe(0);
    expect(readSettings(settingsPath).hooks.PreCompact).toBe('abc');
  });

  test('quotes a worker path with spaces and recognises it on status and uninstall', () => {
    quiet();
    const settingsPath = scratchSettingsPath('muse install test with spaces');
    const spacedWorker = path.join(scratch!, 'plugin dir', 'scripts', 'worker-service.cjs');
    withInstallPaths({ getWorkerServiceAbsolutePath: () => spacedWorker }, () => {
      expect(installMuseCode(settingsPath)).toBe(0);
    });
    expect(readSettings(settingsPath).hooks.Stop[0].hooks[0].command).toContain(`"${spacedWorker}" hook muse-code summarize`);
    expect(checkMuseCodeStatus(settingsPath)).toBe(0);
    expect(uninstallMuseCode(settingsPath)).toBe(0);
    expect(readSettings(settingsPath).hooks).toBeUndefined();
  });

  test.each([
    ['worker-service.cjs', { getWorkerServiceAbsolutePath: () => null }],
    ['mcp-server.cjs', { getMcpServerAbsolutePath: () => null }],
  ])('exits 1 without writing when %s is not found', (name, overrides) => {
    const errors = quiet();
    const settingsPath = scratchSettingsPath();
    withInstallPaths(overrides, () => {
      expect(installMuseCode(settingsPath)).toBe(1);
    });
    expect(existsSync(settingsPath)).toBe(false);
    expect(errors.mock.calls.flat().join('\n')).toContain(name);
  });
});

describe('uninstallMuseCode', () => {
  test('removes only our hooks and MCP server; keeps every user key, user hook and server', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    const original = {
      schema_version: 1,
      model: 'muse-ember-1.0',
      hooks: { PostToolUse: [USER_HOOK], SessionStart: [USER_WORKER_HOOK] },
      mcpServers: { other: { command: 'y' } },
    };
    writeSettings(settingsPath, original);
    expect(installMuseCode(settingsPath)).toBe(0);
    expect(uninstallMuseCode(settingsPath)).toBe(0);
    expect(readSettings(settingsPath)).toEqual(original);
  });

  test('after a fresh install, drops the emptied hooks and mcpServers objects', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    expect(installMuseCode(settingsPath)).toBe(0);
    expect(uninstallMuseCode(settingsPath)).toBe(0);
    expect(readSettings(settingsPath)).toEqual({ schema_version: 1 });
  });

  test('with no settings.json exits 0 and creates nothing', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    expect(uninstallMuseCode(settingsPath)).toBe(0);
    expect(existsSync(settingsPath)).toBe(false);
  });

  test('does not rewrite the file when none of ours is present', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    const text = writeSettings(settingsPath, { schema_version: 1, hooks: { PostToolUse: [USER_HOOK] } });
    expect(uninstallMuseCode(settingsPath)).toBe(0);
    expect(readFileSync(settingsPath, 'utf-8')).toBe(text);
    expect(backups(settingsPath)).toEqual([]);
  });

  test('does not rewrite the file when the only empty hook entries are the user\'s', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    for (const hooks of [{ PreToolUse: [] }, { PostToolUse: [{ matcher: '*', hooks: [] }] }]) {
      const text = writeSettings(settingsPath, { hooks });
      expect(uninstallMuseCode(settingsPath)).toBe(0);
      expect(readFileSync(settingsPath, 'utf-8')).toBe(text);
    }
    expect(backups(settingsPath)).toEqual([]);
  });

  test('leaves a non-array event value as is while removing ours', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    writeSettings(settingsPath, { hooks: { Stop: 'abc', SessionEnd: buildMuseCodeHooks(BUN, WORKER).SessionEnd } });
    expect(uninstallMuseCode(settingsPath)).toBe(0);
    expect(readSettings(settingsPath).hooks).toEqual({ Stop: 'abc' });
  });

  test('exits 1 on corrupt settings and leaves them unchanged', () => {
    quiet();
    const settingsPath = scratchSettingsPath();
    const text = writeSettings(settingsPath, '{ not json');
    expect(uninstallMuseCode(settingsPath)).toBe(1);
    expect(readFileSync(settingsPath, 'utf-8')).toBe(text);
  });
});

describe('readMuseCodeStatus and checkMuseCodeStatus', () => {
  const fullSettings = () => ({
    schema_version: 1,
    hooks: buildMuseCodeHooks(BUN, WORKER),
    mcpServers: { 'claude-mem': { command: 'node' }, other: { command: 'y' } },
  });
  const statusOf = (content: unknown) => {
    const settingsPath = scratchSettingsPath();
    writeSettings(settingsPath, content);
    return readMuseCodeStatus(settingsPath);
  };

  test('installed: every hook and the MCP entry, also with a user hook on the same event', () => {
    expect(statusOf(fullSettings()).status).toBe('installed');
    const settings = fullSettings();
    settings.hooks.PostToolUse.unshift(USER_HOOK);
    expect(statusOf(settings).status).toBe('installed');
  });

  test('incomplete names the missing events and the MCP server', () => {
    const settings = fullSettings();
    delete (settings.hooks as Record<string, unknown>).SubagentStop;
    settings.hooks.SessionStart = settings.hooks.SessionStart.slice(0, 1);
    delete (settings.mcpServers as Record<string, unknown>)['claude-mem'];
    expect(statusOf(settings)).toEqual({ status: 'incomplete', detail: 'missing SessionStart, SubagentStop, the claude-mem MCP server' });
  });

  test('not installed with no file, or with only user hooks and servers', () => {
    expect(readMuseCodeStatus(path.join(scratchSettingsPath(), 'none.json')).status).toBe('not-installed');
    expect(statusOf({ hooks: { PostToolUse: [USER_HOOK], SessionStart: [USER_WORKER_HOOK] }, mcpServers: { other: {} } }).status)
      .toBe('not-installed');
  });

  test('unreadable on invalid JSON or a wrong shape', () => {
    expect(statusOf('{ not json').status).toBe('unreadable');
    expect(statusOf({ mcpServers: [] }).status).toBe('unreadable');
  });

  test('prints the label for each state, exits 0 only when installed, and prints unreadable to stderr', () => {
    const errors = quiet();
    const cases: Array<[MuseCodeStatus, unknown]> = [
      ['installed', fullSettings()],
      ['incomplete', { hooks: fullSettings().hooks }],
      ['not-installed', {}],
      ['unreadable', '[]'],
    ];
    for (const [status, content] of cases) {
      const settingsPath = scratchSettingsPath();
      writeSettings(settingsPath, content);
      (console.log as unknown as { mockClear: () => void }).mockClear();
      errors.mockClear();
      expect(checkMuseCodeStatus(settingsPath)).toBe(status === 'installed' ? 0 : 1);
      const stream = status === 'unreadable' ? errors.mock.calls.flat().join('\n') : logged();
      expect(stream).toContain(`Muse Code hooks: ${MUSE_CODE_STATUS_LABELS[status]}`);
      if (status === 'incomplete') expect(stream).toContain('missing the claude-mem MCP server');
      rmSync(scratch!, { recursive: true, force: true });
    }
  });
});

describe('handleMuseCodeCommand', () => {
  test('an unknown subcommand prints usage and exits 1; help exits 0', async () => {
    quiet();
    expect(await handleMuseCodeCommand('bogus', [])).toBe(1);
    expect(logged()).toContain('Usage: claude-mem muse-code <install|uninstall|status>');
    expect(await handleMuseCodeCommand(undefined, [])).toBe(0);
    expect(await handleMuseCodeCommand('help', [])).toBe(0);
  });
});