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

14.0 KB
Raw Blame
/**
 * AtomCodeHooksInstaller.ts — AtomCode integration (hooks + MCP).
 *
 * AtomCode (MIT, Rust) reads global hooks from `$ATOMCODE_HOME/hooks.json`
 * (default `~/.atomcode/hooks.json`) and MCP servers from
 * `$ATOMCODE_HOME/mcp.json`, both in the shapes described in its docs/hooks.md
 * and docs/MCP.md. Its hook payload and its accepted `hookSpecificOutput`
 * envelope are Claude Code's, so the worker runs the same handlers through the
 * `atomcode` adapter.
 *
 * Two AtomCode-specific differences shape this installer:
 *
 * - Its `hooks` map is FLAT (`{ name: { event, command, ... } }`), not
 *   event → array. The key is not retained after loading, so our entries are
 *   identified by their command, not by name.
 * - A project-level `.hooks.json` only runs after the user authorizes it, so
 *   everything is written globally. Writing both would run every hook twice.
 *
 * The file holds the user's other hooks: one read, one backup, one atomic
 * write, touching only the entries this installer writes. Absolute paths are
 * baked per Rule B (install-paths.ts).
 */
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';

/** One entry of AtomCode's flat `hooks` map. */
export interface AtomCodeHookEntry {
  event: string;
  command: string;
  matcher?: string;
  timeout_ms?: number;
  [key: string]: unknown;
}

export type AtomCodeHooks = Record<string, AtomCodeHookEntry>;

interface AtomCodeHooksConfig {
  hooks?: AtomCodeHooks;
  [key: string]: unknown;
}

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

const MCP_SERVER_NAME = 'claude-mem';

/** `$ATOMCODE_HOME` or `~/.atomcode`, matching what the CLI itself resolves. */
export function atomcodeHome(): string {
  const configured = process.env.ATOMCODE_HOME?.trim();
  return configured ? configured : path.join(homedir(), '.atomcode');
}

export function atomcodeHooksPath(): string {
  return path.join(atomcodeHome(), 'hooks.json');
}

export function atomcodeMcpPath(): string {
  return path.join(atomcodeHome(), 'mcp.json');
}

/** The AtomCode events claude-mem has a handler for; timeouts are in ms. */
export function buildAtomCodeHooks(bunPath: string, workerPath: string): AtomCodeHooks {
  // AtomCode runs the command through a shell in the project directory, so the
  // paths are quoted the same way the Muse Code installer quotes them.
  const run = (suffix: string) => `"${bunPath}" "${workerPath}" ${suffix}`;
  const entry = (event: string, suffix: string, timeoutMs: number, matcher?: string): AtomCodeHookEntry => ({
    event,
    command: run(suffix),
    timeout_ms: timeoutMs,
    ...(matcher ? { matcher } : {}),
  });
  return {
    'claude-mem-start': entry('SessionStart', 'start', 60000),
    'claude-mem-context': entry('SessionStart', 'hook atomcode context', 60000),
    'claude-mem-session-init': entry('UserPromptSubmit', 'hook atomcode session-init', 15000),
    // Read-only context for file reads. AtomCode's PreToolUse can also deny or
    // rewrite a call, so it is matched to `read_file` alone: the gate's deny
    // text names tools AtomCode may not have, and a deny would strand the model.
    // AtomCode matchers are `|`-separated globs, not regex: a regex such as
    // `^read_file$` is taken literally and never matches (atomcode
    // crates/atomcode-capabilities/src/cc_hooks.rs, matches_all_tools).
    'claude-mem-file-context': entry('PreToolUse', 'hook atomcode file-context', 15000, 'read_file'),
    'claude-mem-observation': entry('PostToolUse', 'hook atomcode observation', 120000),
    'claude-mem-observation-failure': entry('PostToolUseFailure', 'hook atomcode observation', 120000),
    'claude-mem-summarize': entry('Stop', 'hook atomcode summarize', 120000),
    'claude-mem-session-end': entry('SessionEnd', 'hook atomcode session-end', 30000),
  };
}

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

export function isClaudeMemAtomCodeHook(entry: AtomCodeHookEntry): boolean {
  return typeof entry?.command === 'string' && OWN_COMMAND.test(entry.command);
}

/** The subcommand of one of our commands (`start`, `hook atomcode context`, ...). */
function ownSubcommand(command: string): string {
  return OWN_COMMAND.exec(command)?.[1] ?? command;
}

/** The hooks without claude-mem's entries, leaving every other entry untouched. */
export function removeAtomCodeHooks(hooks: AtomCodeHooks): AtomCodeHooks {
  const next: AtomCodeHooks = {};
  for (const [name, entry] of Object.entries(hooks)) {
    if (isClaudeMemAtomCodeHook(entry)) continue;
    next[name] = entry;
  }
  return next;
}

/** Replace claude-mem's entries with `ours`, leaving every other hook in place. */
export function mergeAtomCodeHooks(hooks: AtomCodeHooks, ours: AtomCodeHooks): AtomCodeHooks {
  return { ...removeAtomCodeHooks(hooks), ...ours };
}

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

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

// AtomCode accepts `//` and `/* */` comments in both files. Rewriting such a
// file would drop the user's comments, so a file that is not plain JSON is
// refused with a message that says why, never rewritten.
function readPlainJson(filePath: string): unknown {
  try {
    return parseJsonWithBom(readFileSync(filePath, 'utf-8'));
  } catch (error) {
    if (!(error instanceof SyntaxError)) throw error;
    throw new Error(
      `${filePath} is not plain JSON (AtomCode allows comments; claude-mem can't edit a file with comments without losing them). Remove the comments or add the entries by hand.`,
    );
  }
}

function readHooksConfig(hooksPath: string): AtomCodeHooksConfig {
  if (!existsSync(hooksPath)) return {};
  const config: unknown = readPlainJson(hooksPath);
  if (!isObject(config)) refuse(hooksPath, 'The root');
  if (config.hooks !== undefined && !isObject(config.hooks)) refuse(hooksPath, '"hooks"');
  return config as AtomCodeHooksConfig;
}

function readMcpConfig(mcpPath: string): AtomCodeMcpConfig {
  if (!existsSync(mcpPath)) return {};
  const config: unknown = readPlainJson(mcpPath);
  if (!isObject(config)) refuse(mcpPath, 'The root');
  if (config.mcpServers !== undefined && !isObject(config.mcpServers)) refuse(mcpPath, '"mcpServers"');
  return config as AtomCodeMcpConfig;
}

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

export function installAtomCode(
  hooksPath: string = atomcodeHooksPath(),
  mcpPath: string = atomcodeMcpPath(),
): 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 hooksConfig = readHooksConfig(hooksPath);
    const mcpConfig = readMcpConfig(mcpPath);

    // Every entry in the map is one hook, so a non-object value is a file we
    // must not rewrite.
    for (const [name, value] of Object.entries(hooksConfig.hooks ?? {})) {
      if (!isObject(value)) refuse(hooksPath, `"hooks.${name}"`);
    }

    mkdirSync(path.dirname(hooksPath), { recursive: true });
    backupOnce(hooksPath);
    const nextHooks: AtomCodeHooksConfig = {
      ...hooksConfig,
      hooks: mergeAtomCodeHooks(hooksConfig.hooks ?? {}, buildAtomCodeHooks(bunPath, workerPath)),
    };
    writeJsonFileAtomic(hooksPath, nextHooks);

    if (existsSync(mcpPath)) backupOnce(mcpPath);
    mkdirSync(path.dirname(mcpPath), { recursive: true });
    writeJsonFileAtomic(mcpPath, {
      ...mcpConfig,
      mcpServers: { ...mcpConfig.mcpServers, [MCP_SERVER_NAME]: buildMcpServerEntry(mcpServerPath) },
    });

    console.log(`  Installed AtomCode hooks into ${hooksPath}`);
    console.log(`  Installed AtomCode MCP server into ${mcpPath}`);
    console.log(`    Bun runtime: ${bunPath}`);
    console.log(`    Worker: ${workerPath}`);
    console.log(`    MCP server: ${mcpServerPath}`);
    console.log('  Start a new AtomCode session to load them.');
    return 0;
  } catch (error) {
    console.error(`Failed to install AtomCode hooks + MCP: ${(error as Error).message}`);
    return 1;
  }
}

export function uninstallAtomCode(
  hooksPath: string = atomcodeHooksPath(),
  mcpPath: string = atomcodeMcpPath(),
): number {
  if (!existsSync(hooksPath) && !existsSync(mcpPath)) {
    console.log('  No AtomCode hooks.json or mcp.json found; nothing to uninstall');
    return 0;
  }
  try {
    let removedHooks = false;
    if (existsSync(hooksPath)) {
      const hooksConfig = readHooksConfig(hooksPath);
      const ours = hooksConfig.hooks ?? {};
      const next = removeAtomCodeHooks(ours);
      if (Object.keys(next).length !== Object.keys(ours).length) {
        removedHooks = true;
        backupOnce(hooksPath);
        const nextConfig: AtomCodeHooksConfig = { ...hooksConfig };
        if (Object.keys(next).length > 0) nextConfig.hooks = next;
        else delete nextConfig.hooks;
        writeJsonFileAtomic(hooksPath, nextConfig);
      }
    }

    let removedMcp = false;
    if (existsSync(mcpPath)) {
      const mcpConfig = readMcpConfig(mcpPath);
      const servers = mcpConfig.mcpServers;
      if (servers && Object.hasOwn(servers, MCP_SERVER_NAME)) {
        removedMcp = true;
        backupOnce(mcpPath);
        const nextServers = { ...servers };
        delete nextServers[MCP_SERVER_NAME];
        const nextConfig: AtomCodeMcpConfig = { ...mcpConfig };
        if (Object.keys(nextServers).length > 0) nextConfig.mcpServers = nextServers;
        else delete nextConfig.mcpServers;
        writeJsonFileAtomic(mcpPath, nextConfig);
      }
    }

    if (!removedHooks && !removedMcp) {
      console.log('  No claude-mem hooks or MCP server found in AtomCode config');
      return 0;
    }
    console.log('  Removed claude-mem hooks + MCP from AtomCode config');
    return 0;
  } catch (error) {
    console.error(`Failed to uninstall AtomCode hooks + MCP: ${(error as Error).message}`);
    return 1;
  }
}

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

export const ATOMCODE_STATUS_LABELS: Record<AtomCodeStatus, string> = {
  installed: 'installed',
  incomplete: 'incomplete, run npx claude-mem atomcode install',
  'not-installed': 'not installed',
  unreadable: 'unreadable config',
};

export function readAtomCodeStatus(
  hooksPath: string = atomcodeHooksPath(),
  mcpPath: string = atomcodeMcpPath(),
): { status: AtomCodeStatus; detail?: string } {
  let hooksConfig: AtomCodeHooksConfig;
  let mcpConfig: AtomCodeMcpConfig;
  try {
    hooksConfig = readHooksConfig(hooksPath);
    mcpConfig = readMcpConfig(mcpPath);
  } catch (error) {
    return { status: 'unreadable', detail: (error as Error).message };
  }

  // Completeness is judged per hook (event + subcommand), not per event: the two
  // SessionStart entries (`start` and `context`) share an event, and losing
  // either one breaks capture or recall.
  const hookKey = (entry: AtomCodeHookEntry) => `${entry.event} ${ownSubcommand(entry.command)}`;
  const installed = new Set(
    Object.values(hooksConfig.hooks ?? {})
      .filter(isClaudeMemAtomCodeHook)
      .map(hookKey),
  );
  const hasServer = mcpConfig.mcpServers !== undefined && Object.hasOwn(mcpConfig.mcpServers, MCP_SERVER_NAME);

  if (!hasServer && installed.size === 0) return { status: 'not-installed' };

  const expected = buildAtomCodeHooks('bun', '/scripts/worker-service.cjs');
  const missing = Object.values(expected)
    .filter((entry) => !installed.has(hookKey(entry)))
    .map((entry) => `${entry.event} (${ownSubcommand(entry.command)})`);
  if (!hasServer) missing.push(`the ${MCP_SERVER_NAME} MCP server`);
  if (missing.length > 0) return { status: 'incomplete', detail: `missing ${missing.join(', ')}` };
  return { status: 'installed', detail: hooksPath };
}

export function checkAtomCodeStatus(
  hooksPath: string = atomcodeHooksPath(),
  mcpPath: string = atomcodeMcpPath(),
): number {
  const { status, detail } = readAtomCodeStatus(hooksPath, mcpPath);
  const line = `  AtomCode hooks: ${ATOMCODE_STATUS_LABELS[status]}${detail ? ` (${detail})` : ''}`;
  if (status === 'unreadable') console.error(line);
  else console.log(line);
  return status === 'installed' ? 0 : 1;
}

export async function handleAtomCodeCommand(subcommand: string | undefined, _args: string[]): Promise<number> {
  switch (subcommand) {
    case 'install':
      return installAtomCode();
    case 'uninstall':
      return uninstallAtomCode();
    case 'status':
      return checkAtomCodeStatus();
    default:
      console.log('Usage: claude-mem atomcode <install|uninstall|status>');
      return subcommand === undefined || subcommand === 'help' ? 0 : 1;
  }
}