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

11.9 KB
Raw Blame
/**
 * MuseCodeHooksInstaller.ts — Muse Code (Meta's `muse` CLI) integration (hooks + MCP).
 *
 * Muse reads hooks in the Claude Code shape from the `hooks` key and MCP
 * servers from `mcpServers` in ~/.config/muse/settings.json. Its hooks send
 * Claude Code field names, so the worker runs the same handlers through the
 * `muse-code` adapter. The file holds the user's other Muse settings: one
 * read, one backup, one atomic write, touching only the hook entries and the
 * `claude-mem` server this installer writes. Absolute paths are baked per
 * Rule B (install-paths.ts).
 *
 * User level only: these hooks run in every folder, trusted or not. A project
 * `.muse/hooks.json` or a Muse plugin bundle next to them would run every
 * hook twice. The PreToolUse rule gives read context only and never denies:
 * the gate's deny text names Claude Code's MCP tools, and Muse loads MCP only
 * in a trusted folder, so a deny could send the model to tools it lacks.
 * Muse may write the file at the same moment; the atomic write means the
 * last writer wins, as with ZCode.
 */
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { homedir } from 'os';
import path from 'path';
import { parseJsonWithBom, writeJsonFileAtomic } from '../../shared/atomic-json.js';
import { getBunAbsolutePath, getMcpServerAbsolutePath, getWorkerServiceAbsolutePath } from './install-paths.js';
import { buildMcpServerEntry } from './McpIntegrations.js';

export interface MuseCodeHookCommand {
  type: string;
  command?: string;
  timeout?: number;
  [key: string]: unknown;
}

export interface MuseCodeHookRule {
  matcher?: string;
  hooks: MuseCodeHookCommand[];
  [key: string]: unknown;
}

export type MuseCodeHooks = Record<string, MuseCodeHookRule[]>;

interface MuseCodeSettings {
  hooks?: MuseCodeHooks;
  mcpServers?: Record<string, unknown>;
  [key: string]: unknown;
}

const MCP_SERVER_NAME = 'claude-mem';

export function museCodeSettingsPath(): string {
  return path.join(homedir(), '.config', 'muse', 'settings.json');
}

/** The Muse events claude-mem has a handler for; timeouts are in seconds. */
export function buildMuseCodeHooks(bunPath: string, workerPath: string): MuseCodeHooks {
  const run = (suffix: string) => `"${bunPath}" "${workerPath}" ${suffix}`;
  const rule = (suffix: string, timeout: number, matcher = '*'): MuseCodeHookRule => ({
    matcher,
    hooks: [{ type: 'command', command: run(suffix), timeout }],
  });
  return {
    SessionStart: [rule('start', 60), rule('hook muse-code context', 60)],
    UserPromptSubmit: [rule('hook muse-code session-init', 15)],
    PreToolUse: [rule('hook muse-code file-context', 15, '^read_file$')],
    PostToolUse: [rule('hook muse-code observation', 120)],
    PostToolUseFailure: [rule('hook muse-code observation', 120)],
    Stop: [rule('hook muse-code summarize', 120)],
    SubagentStart: [rule('hook muse-code subagent-context', 20)],
    SubagentStop: [rule('hook muse-code subagent-stop', 30)],
    SessionEnd: [rule('hook muse-code session-end', 30)],
  };
}

// Ours only in the exact shape buildMuseCodeHooks writes: a quoted Bun runtime,
// the quoted plugin worker, then one of our subcommands. A command that merely
// mentions the worker (`echo "/tmp/worker-service.cjs" start`) is the user's.
const OWN_COMMAND = /^"(?:[^"]*[\\/])?bun(?:\.exe)?" "[^"]*[\\/]scripts[\\/]worker-service\.cjs" (start|hook muse-code (?:context|session-init|file-context|observation|summarize|subagent-context|subagent-stop|session-end))$/;

export function isClaudeMemMuseCodeCommand(hook: MuseCodeHookCommand): boolean {
  return hook?.type === 'command' && typeof hook.command === 'string' && OWN_COMMAND.test(hook.command);
}

/** The hooks without claude-mem's entries; only rules and events that ours emptied are dropped. */
export function removeMuseCodeHooks(hooks: MuseCodeHooks): MuseCodeHooks {
  const next: MuseCodeHooks = {};
  for (const [event, rules] of Object.entries(hooks)) {
    if (!Array.isArray(rules)) {
      next[event] = rules;
      continue;
    }
    let dropped = false;
    const kept = rules.flatMap((rule) => {
      if (!Array.isArray(rule?.hooks)) return [rule];
      const left = rule.hooks.filter((hook) => !isClaudeMemMuseCodeCommand(hook));
      if (left.length === rule.hooks.length) return [rule];
      if (left.length > 0) return [{ ...rule, hooks: left }];
      dropped = true;
      return [];
    });
    if (kept.length > 0 || !dropped) next[event] = kept;
  }
  return next;
}

/** Replace claude-mem's entries with `ours`, leaving every other hook in place. */
export function mergeMuseCodeHooks(hooks: MuseCodeHooks, ours: MuseCodeHooks): MuseCodeHooks {
  const next = removeMuseCodeHooks(hooks);
  for (const [event, rules] of Object.entries(ours)) {
    next[event] = [...(next[event] ?? []), ...rules];
  }
  return next;
}

const isObject = (value: unknown): value is Record<string, unknown> =>
  value !== null && typeof value === 'object' && !Array.isArray(value);

function refuse(settingsPath: string, key: string, kind = 'object'): never {
  throw new Error(`${key} in ${settingsPath} is not a JSON ${kind}; refusing to overwrite it`);
}

function readMuseCodeSettings(settingsPath: string): MuseCodeSettings {
  if (!existsSync(settingsPath)) return {};
  const settings: unknown = parseJsonWithBom(readFileSync(settingsPath, 'utf-8'));
  if (!isObject(settings)) refuse(settingsPath, 'The root');
  if (settings.hooks !== undefined && !isObject(settings.hooks)) refuse(settingsPath, '"hooks"');
  if (settings.mcpServers !== undefined && !isObject(settings.mcpServers)) refuse(settingsPath, '"mcpServers"');
  return settings as MuseCodeSettings;
}

function backupOnce(settingsPath: string): void {
  const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, '');
  const backupPath = `${settingsPath}.bak-${stamp}`;
  if (existsSync(settingsPath) && !existsSync(backupPath)) {
    // Owner-only: the backup holds every Muse setting.
    writeFileSync(backupPath, readFileSync(settingsPath, 'utf-8'), { mode: 0o600 });
  }
}

export function installMuseCode(settingsPath: string = museCodeSettingsPath()): number {
  const workerPath = getWorkerServiceAbsolutePath();
  if (!workerPath) {
    console.error('Could not find worker-service.cjs (expected under the installed plugin scripts/ directory)');
    return 1;
  }
  const mcpServerPath = getMcpServerAbsolutePath();
  if (!mcpServerPath) {
    console.error('Could not find mcp-server.cjs (expected under the installed plugin scripts/ directory)');
    return 1;
  }
  const bunPath = getBunAbsolutePath();
  try {
    const existed = existsSync(settingsPath);
    const settings = readMuseCodeSettings(settingsPath);
    const ourHooks = buildMuseCodeHooks(bunPath, workerPath);
    for (const event of Object.keys(ourHooks)) {
      const value = settings.hooks?.[event];
      if (value !== undefined && !Array.isArray(value)) refuse(settingsPath, `"hooks.${event}"`, 'array');
    }
    mkdirSync(path.dirname(settingsPath), { recursive: true });
    backupOnce(settingsPath);
    // Muse's minimal settings object carries schema_version.
    const next: MuseCodeSettings = existed ? settings : { schema_version: 1 };
    next.hooks = mergeMuseCodeHooks(settings.hooks ?? {}, ourHooks);
    next.mcpServers = { ...settings.mcpServers, [MCP_SERVER_NAME]: buildMcpServerEntry(mcpServerPath) };
    writeJsonFileAtomic(settingsPath, next);
    console.log(`  Installed Muse Code hooks + MCP into ${settingsPath}`);
    console.log(`    Bun runtime: ${bunPath}`);
    console.log(`    Worker: ${workerPath}`);
    console.log(`    MCP server: ${mcpServerPath}`);
    console.log('  Start a new Muse Code session to load them.');
    return 0;
  } catch (error) {
    console.error(`Failed to install Muse Code hooks + MCP: ${(error as Error).message}`);
    return 1;
  }
}

export function uninstallMuseCode(settingsPath: string = museCodeSettingsPath()): number {
  if (!existsSync(settingsPath)) {
    console.log('  No Muse Code settings.json found; nothing to uninstall');
    return 0;
  }
  try {
    const settings = readMuseCodeSettings(settingsPath);
    const hooks = settings.hooks;
    const nextHooks = hooks ? removeMuseCodeHooks(hooks) : undefined;
    const hooksChanged = JSON.stringify(nextHooks) !== JSON.stringify(hooks);
    const servers = settings.mcpServers;
    const serverPresent = servers !== undefined && Object.hasOwn(servers, MCP_SERVER_NAME);
    if (!hooksChanged && !serverPresent) {
      console.log('  No claude-mem hooks or MCP server found in Muse Code settings.json');
      return 0;
    }
    backupOnce(settingsPath);
    if (hooksChanged) {
      if (nextHooks && Object.keys(nextHooks).length > 0) settings.hooks = nextHooks;
      else delete settings.hooks;
    }
    if (servers && serverPresent) {
      delete servers[MCP_SERVER_NAME];
      if (Object.keys(servers).length === 0) delete settings.mcpServers;
    }
    writeJsonFileAtomic(settingsPath, settings);
    console.log(`  Removed claude-mem hooks + MCP from ${settingsPath}`);
    return 0;
  } catch (error) {
    console.error(`Failed to uninstall Muse Code hooks + MCP: ${(error as Error).message}`);
    return 1;
  }
}

/**
 * What `claude-mem muse-code status` reports; readMuseCodeStatus is its one
 * writer. Only `installed` means capture and recall can work. Muse has no
 * hooks on/off switch, so there is no `disabled` state.
 */
export type MuseCodeStatus = 'installed' | 'incomplete' | 'not-installed' | 'unreadable';

export const MUSE_CODE_STATUS_LABELS: Record<MuseCodeStatus, string> = {
  installed: 'installed',
  incomplete: 'incomplete, run npx claude-mem muse-code install',
  'not-installed': 'not installed',
  unreadable: 'unreadable settings',
};

const ownHooks = (rules: unknown): MuseCodeHookCommand[] => Array.isArray(rules)
  ? rules.flatMap((rule) => Array.isArray(rule?.hooks) ? rule.hooks.filter(isClaudeMemMuseCodeCommand) : [])
  : [];
// The subcommand after the worker path, e.g. "hook muse-code context".
const hookTail = (hook: MuseCodeHookCommand) => OWN_COMMAND.exec(hook.command ?? '')?.[1];

export function readMuseCodeStatus(settingsPath: string = museCodeSettingsPath()): { status: MuseCodeStatus; detail?: string } {
  let settings: MuseCodeSettings;
  try {
    settings = readMuseCodeSettings(settingsPath);
  } catch (error) {
    return { status: 'unreadable', detail: (error as Error).message };
  }
  const hooks = settings.hooks ?? {};
  const servers = settings.mcpServers;
  const hasServer = servers !== undefined && Object.hasOwn(servers, MCP_SERVER_NAME);
  const missing = Object.entries(buildMuseCodeHooks('bun', '/scripts/worker-service.cjs')).flatMap(([event, rules]) => {
    const present = new Set(ownHooks(Object.hasOwn(hooks, event) ? hooks[event] : undefined).map(hookTail));
    return rules.every((rule) => present.has(hookTail(rule.hooks[0]))) ? [] : [event];
  });
  if (!hasServer) missing.push(`the ${MCP_SERVER_NAME} MCP server`);
  if (!hasServer && !Object.values(hooks).some((rules) => ownHooks(rules).length > 0)) return { status: 'not-installed' };
  if (missing.length > 0) return { status: 'incomplete', detail: `missing ${missing.join(', ')}` };
  return { status: 'installed', detail: settingsPath };
}

export function checkMuseCodeStatus(settingsPath: string = museCodeSettingsPath()): number {
  const { status, detail } = readMuseCodeStatus(settingsPath);
  const line = `  Muse Code hooks: ${MUSE_CODE_STATUS_LABELS[status]}${detail ? ` (${detail})` : ''}`;
  if (status === 'unreadable') console.error(line);
  else console.log(line);
  return status === 'installed' ? 0 : 1;
}

export async function handleMuseCodeCommand(subcommand: string | undefined, _args: string[]): Promise<number> {
  switch (subcommand) {
    case 'install':
      return installMuseCode();
    case 'uninstall':
      return uninstallMuseCode();
    case 'status':
      return checkMuseCodeStatus();
    default:
      console.log('Usage: claude-mem muse-code <install|uninstall|status>');
      return subcommand === undefined || subcommand === 'help' ? 0 : 1;
  }
}