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

feat(atomcode): add AtomCode hooks + MCP integration (#6749)

TheoCui62fa760a6b24
diff --git a/docs/public/atomcode-integration.mdx b/docs/public/atomcode-integration.mdx
new file mode 100644
index 000000000..98e91247f
--- /dev/null
+++ b/docs/public/atomcode-integration.mdx
@@ -0,0 +1,112 @@
+---
+title: AtomCode Integration
+description: Memory for AtomCode, AtomGit's terminal coding agent — hook-based observation recording, session-start context, MCP memory search and read context
+icon: terminal
+---
+
+## Overview
+
+The AtomCode integration gives your AtomCode agent memory from Claude-Mem. It does four things:
+
+1. **Observation recording**: AtomCode's lifecycle hooks send each tool result to the Claude-Mem worker, and the observer writes observations about it
+2. **Context**: the `SessionStart` hook returns your memory as `hookSpecificOutput.additionalContext`, the Claude Code envelope AtomCode accepts
+3. **MCP search tools**: the Claude-Mem MCP server gives AtomCode the `mcp__claude-mem__*` memory search tools
+4. **Read context**: before a `read_file`, the `PreToolUse` hook adds the file's memory timeline as context and never blocks the read
+
+<Info>
+AtomCode reads global hooks from the `hooks` key in `$ATOMCODE_HOME/hooks.json` and MCP servers from the `mcpServers` key in `$ATOMCODE_HOME/mcp.json`. `$ATOMCODE_HOME` defaults to `~/.atomcode`. The installer adds Claude-Mem's hooks and the `claude-mem` MCP server to those files. It keeps your other hooks and MCP servers.
+</Info>
+
+## Requirements
+
+- AtomCode (the `atomcode` command).
+- Claude-Mem runs on your computer. You do not need CMEM Pro.
+
+## Installation
+
+```bash
+npx claude-mem install --ide atomcode
+```
+
+Or manage the integration directly:
+
+```bash
+npx claude-mem atomcode install
+npx claude-mem atomcode status
+npx claude-mem atomcode uninstall
+```
+
+The installer reads `hooks.json` and `mcp.json`, saves a backup next to each (`hooks.json.bak-YYYYMMDD`, once per day, readable only by you), and writes each new file in one step. If a file does not exist, the installer creates it. If a file is not valid JSON, or `hooks` or `mcpServers` is not an object, the installer stops and changes nothing.
+
+AtomCode allows `//` and `/* */` comments in both files. Claude-Mem can't rewrite a file with comments without losing them, so the installer stops and says the file is not plain JSON. Remove the comments, or add the entries by hand.
+
+Start a new AtomCode session so AtomCode reads the new hooks.
+
+## Verify
+
+1. Run `npx claude-mem atomcode status`. It prints `AtomCode hooks: installed`. It prints `incomplete` when a hook or the `claude-mem` MCP server is missing, `not installed` when neither is there, and `unreadable config` when a file cannot be read. See [Troubleshooting](#troubleshooting).
+2. Run `atomcode hooks list` to see the hooks AtomCode loaded.
+3. Start a new AtomCode session in a project and ask the agent to run a command.
+4. Watch the observation arrive in the viewer.
+
+## What is captured and sent
+
+- **Captured**: your prompts and each tool call's name and result, including failed calls.
+- **Where it goes**: the hooks send this to the Claude-Mem worker on your computer. The worker sends it to the observer you chose with `CLAUDE_MEM_PROVIDER` (by default Claude, through your Claude account) to write observations. Memory is stored in `~/.claude-mem/`.
+- **Opt out**: wrap text in [`<private>` tags](/usage/private-tags) to keep it out of memory, list tools in `CLAUDE_MEM_SKIP_TOOLS` to skip them, or run `npx claude-mem atomcode uninstall`.
+
+## Event mapping
+
+| AtomCode hook event | Claude-Mem event | Notes |
+| --- | --- | --- |
+| `SessionStart` | worker start, then `context` | memory is returned as `hookSpecificOutput.additionalContext` |
+| `UserPromptSubmit` | `session-init` | |
+| `PreToolUse` | `file-context` | only for `read_file` (matcher `read_file`); adds the file's [memory timeline](/file-read-gate) as context and never blocks the read |
+| `PostToolUse` | `observation` | AtomCode tool names are mapped, see below |
+| `PostToolUseFailure` | `observation` | recorded as a failed tool call |
+| `Stop` | `summarize` | no summary is written yet, see [Limits](#limits) |
+| `SessionEnd` | `session-end` | |
+
+Each hook is an entry in AtomCode's flat `hooks` map, named `claude-mem-…`. Its command is the Bun runtime plus the worker script, both quoted. Each has its own `timeout_ms`: 60000 for the worker start and context, 15000 for `session-init` and `file-context`, 120000 for `observation` and `summarize`, and 30000 for `session-end`. AtomCode matchers are `|`-separated globs, not regular expressions, so the `PreToolUse` entry uses the plain name `read_file`.
+
+### Tool names
+
+AtomCode names its tools in snake_case. Claude-Mem maps the ones that have a direct Claude Code counterpart:
+
+| AtomCode tool | Recorded as |
+| --- | --- |
+| `bash` | `Bash` |
+| `read_file` | `Read` |
+| `write_file` | `Write` |
+| `edit_file` | `Edit` |
+| `grep` | `Grep` |
+| `glob` | `Glob` |
+| `web_search` | `WebSearch` |
+| `web_fetch` | `WebFetch` |
+
+Every other tool keeps its AtomCode name. This includes the MCP tools (`mcp__<server>__<tool>`), `task`, `skill`, `ls` and `apply_patch`.
+
+## Limits
+
+- **Results without arguments**: AtomCode's `PostToolUse` and `PostToolUseFailure` hooks send the tool's result and its call id, but not the tool's arguments. Observations from AtomCode therefore don't carry the command that ran or the file path that was edited, only what the tool returned.
+- **No session summaries yet**: AtomCode's `Stop` hook sends no last assistant message, and its `transcript_path` points to AtomCode's own session log, which Claude-Mem can't read yet. The `summarize` hook therefore writes no summary for AtomCode sessions. Observations and context are not affected.
+- **Global hooks only**: the hooks go into `$ATOMCODE_HOME/hooks.json` so they run in every project. Claude-Mem does not write a project `.hooks.json`. AtomCode runs a project file only after you trust the project, and one next to the global hooks would run every hook twice.
+- **Read context only, never blocks**: before a `read_file`, the `PreToolUse` hook adds the file's memory timeline as context. It never blocks or rewrites the read. The [File Read Gate](/file-read-gate) block text names Claude Code's tools, so a block could send the model to tools AtomCode does not have.
+- **Files written at the same moment**: if AtomCode writes `hooks.json` or `mcp.json` while the installer does, the last writer wins.
+
+## Troubleshooting
+
+- **Hooks do not run**: run `npx claude-mem atomcode status` and `atomcode hooks list`, then start a new AtomCode session.
+- **Status says incomplete**: a hook or the `claude-mem` MCP server was removed. The status line names what is missing. Run `npx claude-mem atomcode install` again.
+- **Status says unreadable config, or install says a file is not plain JSON**: `hooks.json` or `mcp.json` has comments or is not valid JSON, or `hooks` or `mcpServers` is not an object. Fix the file, then run `npx claude-mem atomcode install`.
+- **Files are somewhere else**: set `ATOMCODE_HOME` to the folder AtomCode uses before you run the installer.
+- **Bun not found**: the hooks run Bun by its absolute path. If you moved or reinstalled Bun, run `npx claude-mem atomcode install` again.
+- **More detail**: Claude-Mem writes its logs to `~/.claude-mem/logs/`.
+
+## Uninstall
+
+```bash
+npx claude-mem atomcode uninstall
+```
+
+This removes only Claude-Mem's hooks from `hooks.json` and the `claude-mem` MCP server from `mcp.json`. Your other hooks and MCP servers stay. `npx claude-mem uninstall` does the same as part of a full uninstall. Your memory in `~/.claude-mem/` is not deleted.
diff --git a/docs/public/docs.json b/docs/public/docs.json
index b0a20c368..de265bfad 100644
--- a/docs/public/docs.json
+++ b/docs/public/docs.json
@@ -128,6 +128,7 @@
"zcode-integration",
"mcode-integration",
"muse-code-integration",
+ "atomcode-integration",
"kilo",
"kiro",
"qoder-integration",
diff --git a/docs/public/file-read-gate.mdx b/docs/public/file-read-gate.mdx
index 230273e5a..1de1ca99c 100644
--- a/docs/public/file-read-gate.mdx
+++ b/docs/public/file-read-gate.mdx
@@ -50,7 +50,7 @@ Code files the gate covers:
Markdown, YAML, TOML, JSON and every other file type are never blocked. Read is the right tool for them.
-Qwen Code runs the Claude Code hooks, and Codex CLI, Kimi and Muse Code run the same hook, but none of them blocks: the hook adds the file's timeline as context and lets the call through. Other hosts don't run this hook.
+Qwen Code runs the Claude Code hooks, and Codex CLI, Kimi, Muse Code and AtomCode run the same hook, but none of them blocks: the hook adds the file's timeline as context and lets the call through. Other hosts don't run this hook.
---
diff --git a/docs/public/platform-integration.mdx b/docs/public/platform-integration.mdx
index ee9826c5e..a66372ae4 100644
--- a/docs/public/platform-integration.mdx
+++ b/docs/public/platform-integration.mdx
@@ -83,6 +83,7 @@ The worker API is harness-agnostic. claude-mem ships first-party installers and
| ZCode | `zcode` | `~/.zcode/cli/config.json` (`hooks.events`, `mcp.servers`) | `npx claude-mem install --ide zcode` ([ZCode Integration](/zcode-integration)) |
| MiniMax Code | `mcode` | `~/.minimax/hooks.json`, `~/.minimax/mcp.json` | `npx claude-mem install --ide mcode` ([MiniMax Code Integration](/mcode-integration)) |
| Muse Code | `muse-code` | `~/.config/muse/settings.json` (`hooks`, `mcpServers`) | `npx claude-mem install --ide muse-code` ([Muse Code Integration](/muse-code-integration)) |
+| AtomCode | `atomcode` | `$ATOMCODE_HOME/hooks.json` (`hooks`), `$ATOMCODE_HOME/mcp.json` (`mcpServers`), default `~/.atomcode` | `npx claude-mem install --ide atomcode` ([AtomCode Integration](/atomcode-integration)) |
| Hermes Agent | `hermes` | `~/.hermes/plugins/claude-mem/`, `~/.hermes/config.yaml` | `npx claude-mem install --ide hermes` ([Hermes Integration](/hermes-integration)); community Hermes One uses `npx claude-mem hermes install --mcp-only --project-cwd <dir>` ([Desktop MCP setup](/hermes-desktop-integration)) |
The OpenCode plugin needs OpenCode 1.3.4 or later, and supports both OpenCode 1 and OpenCode 2 from one file. OpenCode 2 loads it from its `plugins` directory, so the installer adds a `plugin` entry to `opencode.json` only for OpenCode 1.
diff --git a/docs/public/telemetry.mdx b/docs/public/telemetry.mdx
index a64760377..cb7a319ba 100644
--- a/docs/public/telemetry.mdx
+++ b/docs/public/telemetry.mdx
@@ -391,7 +391,7 @@ the user types it. That did not change. The skills are `agent-cost-report`,
| `telemetry` | the opt-out command itself | unchanged (no usage event) |
| `hook` | `hook_failed` when a hook fails; success is the rollups above | unchanged |
| `start` | `worker_started` when a worker actually starts | unchanged |
-| `stop`, `restart`, `status`, `doctor`, `prune`, `repair`, `search`, `backup`, `restore`, `import`, `sync`, `memory`, `transcript`, `project`, `cleanup`, `adopt`, `mcp`, `worker`, `server`, `teambrain`, `messages`, `imessage`, and the per-IDE helpers (`pi`, `gemini`, `kimi`, `hermes`, `grok`, `aider`, `devin`, `zcode`, `mcode`, `muse-code`, `antigravity-cli`, `t3code`) | none | `cli_command` |
+| `stop`, `restart`, `status`, `doctor`, `prune`, `repair`, `search`, `backup`, `restore`, `import`, `sync`, `memory`, `transcript`, `project`, `cleanup`, `adopt`, `mcp`, `worker`, `server`, `teambrain`, `messages`, `imessage`, and the per-IDE helpers (`pi`, `gemini`, `kimi`, `hermes`, `grok`, `aider`, `devin`, `zcode`, `mcode`, `muse-code`, `atomcode`, `antigravity-cli`, `t3code`) | none | `cli_command` |
### MCP tools
diff --git a/src/cli/adapters/atomcode.ts b/src/cli/adapters/atomcode.ts
new file mode 100644
index 000000000..0461450ba
--- /dev/null
+++ b/src/cli/adapters/atomcode.ts
@@ -0,0 +1,72 @@
+import type { HookResult, NormalizedHookInput, PlatformAdapter } from '../types.js';
+import { claudeCodeAdapter } from './claude-code.js';
+import { AdapterRejectedInput, isValidCwd } from './errors.js';
+
+function stringOrUndefined(value: unknown): string | undefined {
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+}
+
+// AtomCode sends Claude Code field names (session_id, hook_event_name, cwd,
+// tool_name, tool_input, tool_response, transcript_path) but snake_case tool
+// names of its own. Capture keys on the Claude Code names, so only tools with a
+// direct counterpart are mapped; the rest (`task`, `skill`, `ls`, `apply_patch`,
+// `mcp__<server>__<tool>`) pass through unchanged.
+//
+// Two payload differences (atomcode crates/atomcode-capabilities/src/cc_hooks.rs):
+// - The per-call id is `call_id`, not `tool_use_id`. It is passed through as
+// the tool use id so completed-observation dedup has a key.
+// - PostToolUse / PostToolUseFailure carry no `tool_input`, only the result.
+// Observations from AtomCode therefore lack the tool's arguments. Pairing the
+// PreToolUse input by call_id would need a new buffer, which AGENTS.md rules out.
+// AtomCode's own file tools already name their argument `file_path`, so the
+// PreToolUse input the file-context hook reads needs no rename.
+const ATOMCODE_TOOL_NAMES: Record<string, string> = {
+ bash: 'Bash',
+ read_file: 'Read',
+ write_file: 'Write',
+ edit_file: 'Edit',
+ grep: 'Grep',
+ glob: 'Glob',
+ web_search: 'WebSearch',
+ web_fetch: 'WebFetch',
+};
+
+// AtomCode's hook config is its own `hooks.json` shape, but the payload it
+// sends and the `hookSpecificOutput` envelope it accepts are Claude Code's
+// (docs/hooks.md: "the CC shape" is accepted on stdout), so the Claude Code
+// adapter does the rest of the mapping, PostToolUseFailure included.
+export const atomcodeAdapter: PlatformAdapter = {
+ normalizeInput(raw): NormalizedHookInput {
+ const r = (raw ?? {}) as Record<string, unknown>;
+ // A CLAUDE_PROJECT_DIR inherited from the shell that started AtomCode names
+ // another project, so it must not replace this cwd.
+ const cwd = stringOrUndefined(r.cwd) ?? process.cwd();
+ if (!isValidCwd(cwd)) {
+ throw new AdapterRejectedInput('invalid_cwd');
+ }
+ const rawToolName = stringOrUndefined(r.tool_name);
+ const mapped = rawToolName && Object.hasOwn(ATOMCODE_TOOL_NAMES, rawToolName)
+ ? ATOMCODE_TOOL_NAMES[rawToolName]
+ : undefined;
+ const toolName = mapped ?? rawToolName;
+ const input = claudeCodeAdapter.normalizeInput({
+ ...r,
+ cwd,
+ tool_name: toolName,
+ tool_use_id: stringOrUndefined(r.tool_use_id) ?? stringOrUndefined(r.call_id),
+ });
+ if (!stringOrUndefined(input.sessionId)) {
+ throw new AdapterRejectedInput('missing_session_id');
+ }
+ return {
+ ...input,
+ cwd,
+ nativeToolName: mapped ? rawToolName : undefined,
+ };
+ },
+
+ // AtomCode reads `hookSpecificOutput.additionalContext`, the Claude Code envelope.
+ formatOutput(result: HookResult): unknown {
+ return claudeCodeAdapter.formatOutput(result);
+ },
+};
diff --git a/src/cli/adapters/index.ts b/src/cli/adapters/index.ts
index 647633f98..e339e1604 100644
--- a/src/cli/adapters/index.ts
+++ b/src/cli/adapters/index.ts
@@ -1,5 +1,6 @@
import type { PlatformAdapter } from '../types.js';
import { antigravityCliAdapter } from './antigravity-cli.js';
+import { atomcodeAdapter } from './atomcode.js';
import { claudeCodeAdapter } from './claude-code.js';
import { codexAdapter } from './codex.js';
import { cursorAdapter } from './cursor.js';
@@ -26,9 +27,10 @@ export function getPlatformAdapter(platform: string): PlatformAdapter {
case 'windsurf': return windsurfAdapter;
case 'zcode': return zcodeAdapter;
case 'antigravity': case 'antigravity-cli': return antigravityCliAdapter;
+ case 'atomcode': return atomcodeAdapter;
case 'raw': return rawAdapter;
default: return rawAdapter;
}
}
-export { antigravityCliAdapter, claudeCodeAdapter, codexAdapter, cursorAdapter, devinAdapter, kimiAdapter, mcodeAdapter, museCodeAdapter, rawAdapter, windsurfAdapter, zcodeAdapter };
+export { antigravityCliAdapter, atomcodeAdapter, claudeCodeAdapter, codexAdapter, cursorAdapter, devinAdapter, kimiAdapter, mcodeAdapter, museCodeAdapter, rawAdapter, windsurfAdapter, zcodeAdapter };
diff --git a/src/npx-cli/commands/ide-detection.ts b/src/npx-cli/commands/ide-detection.ts
index 819610af1..868733be4 100644
--- a/src/npx-cli/commands/ide-detection.ts
+++ b/src/npx-cli/commands/ide-detection.ts
@@ -126,6 +126,14 @@ export function detectInstalledIDEs(): IDEInfo[] {
detected: existsSync(join(home, '.config', 'muse')),
hint: 'hooks + MCP integration',
},
+ {
+ id: 'atomcode',
+ label: 'AtomCode',
+ detected:
+ existsSync(process.env.ATOMCODE_HOME?.trim() || join(home, '.atomcode')) ||
+ isCommandInPath('atomcode'),
+ hint: 'hooks + MCP integration',
+ },
{
id: 'cursor',
label: 'Cursor',
diff --git a/src/npx-cli/commands/install.ts b/src/npx-cli/commands/install.ts
index faeca4d52..6a39037b8 100644
--- a/src/npx-cli/commands/install.ts
+++ b/src/npx-cli/commands/install.ts
@@ -562,6 +562,23 @@ export function makeIDETask(ideId: string, summary: InstallSummary, dshProfile?:
};
}
+ case 'atomcode': {
+ return {
+ title: 'AtomCode: installing hooks + MCP',
+ task: async (message) => {
+ message('Loading AtomCode installer…');
+ const { installAtomCode } = await import('../../services/integrations/AtomCodeHooksInstaller.js');
+ message('Installing AtomCode hooks + MCP…');
+ const { result, output } = await bufferConsole(async () => installAtomCode());
+ if (result !== 0) {
+ recordFailure('AtomCode: hooks + MCP installation failed', output);
+ return `AtomCode: hooks + MCP installation failed ${styleText('red', 'FAIL')}`;
+ }
+ return `AtomCode: hooks + MCP installed ${styleText('green', 'OK')}`;
+ },
+ };
+ }
+
case 'opencode': {
return {
title: 'OpenCode: installing plugin',
diff --git a/src/npx-cli/commands/uninstall.ts b/src/npx-cli/commands/uninstall.ts
index 05939c25f..d37683bf2 100644
--- a/src/npx-cli/commands/uninstall.ts
+++ b/src/npx-cli/commands/uninstall.ts
@@ -647,6 +647,10 @@ export async function runUninstallCommand(): Promise<void> {
const { uninstallMuseCode } = await import('../../services/integrations/MuseCodeHooksInstaller.js');
return uninstallMuseCode();
}},
+ { label: 'AtomCode hooks + MCP', fn: async () => {
+ const { uninstallAtomCode } = await import('../../services/integrations/AtomCodeHooksInstaller.js');
+ return uninstallAtomCode();
+ }},
{ label: 'OMP hooks', fn: async () => {
const { uninstallOmpHooks } = await import('../../services/integrations/OmpHooksInstaller.js');
return uninstallOmpHooks();
diff --git a/src/npx-cli/index.ts b/src/npx-cli/index.ts
index 7fab852f4..71338a01c 100644
--- a/src/npx-cli/index.ts
+++ b/src/npx-cli/index.ts
@@ -92,6 +92,7 @@ ${styleText('bold', 'Runtime Commands')} (requires Bun, delegates to installed p
${styleText('cyan', 'npx claude-mem zcode install|status|uninstall')} Manage ZCode hooks + MCP
${styleText('cyan', 'npx claude-mem mcode install|status|uninstall')} Manage MiniMax Code hooks + MCP
${styleText('cyan', 'npx claude-mem muse-code install|status|uninstall')} Manage Muse Code hooks + MCP
+ ${styleText('cyan', 'npx claude-mem atomcode install|status|uninstall')} Manage AtomCode hooks + MCP
${styleText('cyan', 'npx claude-mem t3code status|uninstall [--settings <path>]')} Inspect or disable T3 Code provider plugins
${styleText('cyan', 'npx claude-mem pi install|status|uninstall')} Manage the native Pi extension
${styleText('cyan', 'npx claude-mem grok install|status|uninstall')} Load recalled memory into Grok Build sessions (current folder)
@@ -111,7 +112,7 @@ ${styleText('bold', 'Claude Code Hooks')}:
${styleText('bold', 'Agent IDs')} (for --ide):
claude-code, cursor, grok-bot, opencode, openclaw, omp, hermes, pi, dsh,
windsurf, codex-cli, t3code (aliases: t3, t3-code), kimi, devin, copilot-cli, copilot-vscode, antigravity, goose,
- roo-code, warp, zed, zcode, mcode, muse-code
+ roo-code, warp, zed, zcode, mcode, muse-code, atomcode
`);
}
@@ -189,7 +190,7 @@ const HELP_AWARE_COMMANDS = new Set([
'start', 'stop', 'restart', 'status', 'doctor', 'mcp', 'hook',
'adopt', 'cleanup',
'memory', 'import', 'telemetry', 'project', 'backup', 'restore', 'server', 'worker', 'transcript',
- 'gemini', 'kimi', 'hermes', 'imessage', 'aider', 'devin', 'zcode', 'mcode', 'muse-code', 'antigravity-cli', 'pi', 't3code', 't3-code', 't3', 'grok',
+ 'gemini', 'kimi', 'hermes', 'imessage', 'aider', 'devin', 'zcode', 'mcode', 'muse-code', 'atomcode', 'antigravity-cli', 'pi', 't3code', 't3-code', 't3', 'grok',
]);
async function main(): Promise<void> {
@@ -409,6 +410,10 @@ async function runCommand(): Promise<void> {
const { handleMuseCodeCommand } = await import('../services/integrations/MuseCodeHooksInstaller.js');
process.exit(await handleMuseCodeCommand(args[1]?.toLowerCase(), args.slice(2)));
}
+ case 'atomcode': {
+ const { handleAtomCodeCommand } = await import('../services/integrations/AtomCodeHooksInstaller.js');
+ process.exit(await handleAtomCodeCommand(args[1]?.toLowerCase(), args.slice(2)));
+ }
case 'grok': {
const { handleGrokCommand } = await import('../services/integrations/GrokBuildInstaller.js');
diff --git a/src/services/integrations/AtomCodeHooksInstaller.ts b/src/services/integrations/AtomCodeHooksInstaller.ts
new file mode 100644
index 000000000..ecf0cac8c
--- /dev/null
+++ b/src/services/integrations/AtomCodeHooksInstaller.ts
@@ -0,0 +1,348 @@
+/**
+ * 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;
+ }
+}
diff --git a/src/services/telemetry/usage.ts b/src/services/telemetry/usage.ts
index 96df7dc2b..f009629e4 100644
--- a/src/services/telemetry/usage.ts
+++ b/src/services/telemetry/usage.ts
@@ -185,7 +185,7 @@ const CLI_SKIP = new Set([
const CLI_COMMANDS = new Set([
'repair', 'stop', 'restart', 'status', 'doctor', 'prune', 'teambrain', 'server',
'antigravity-cli', 't3code', 'pi', 'gemini', 'kimi', 'hermes', 'imessage', 'aider',
- 'devin', 'zcode', 'mcode', 'muse-code', 'grok', 'worker', 'search', 'mcp', 'adopt',
+ 'devin', 'zcode', 'mcode', 'muse-code', 'atomcode', 'grok', 'worker', 'search', 'mcp', 'adopt',
'project', 'cleanup', 'backup', 'restore', 'transcript', 'memory', 'messages', 'sync', 'import',
]);
diff --git a/src/services/worker-service.ts b/src/services/worker-service.ts
index ea9a5bd4e..bbf973228 100644
--- a/src/services/worker-service.ts
+++ b/src/services/worker-service.ts
@@ -166,6 +166,9 @@ import {
import {
handleMuseCodeCommand
} from './integrations/MuseCodeHooksInstaller.js';
+import {
+ handleAtomCodeCommand
+} from './integrations/AtomCodeHooksInstaller.js';
import {
handleAntigravityCliCommand,
healStaleAntigravityHooksConfig
@@ -1950,7 +1953,7 @@ function rejectUnknownCliFlags(args: string[], usage: string, booleanFlags: stri
function printWorkerServiceUsage(): void {
console.error('Usage: worker-service <command>');
console.error('Commands: start, stop, restart, status, hook <platform> <event>, worker <command>, server <command>,');
- console.error(' adopt, project, transcript, generate, clean, cleanup, cursor, grok, memory, kimi, aider, devin, zcode, mcode, muse-code, antigravity-cli,');
+ console.error(' adopt, project, transcript, generate, clean, cleanup, cursor, grok, memory, kimi, aider, devin, zcode, mcode, muse-code, atomcode, antigravity-cli,');
console.error(' --daemon, --version, --help');
}
@@ -2571,6 +2574,13 @@ export async function main() {
break;
}
+ case 'atomcode': {
+ const atomcodeSubcommand = process.argv[3];
+ const atomcodeResult = await handleAtomCodeCommand(atomcodeSubcommand, process.argv.slice(4));
+ process.exit(atomcodeResult);
+ break;
+ }
+
case 'antigravity-cli': {
const antigravitySubcommand = process.argv[3];
const antigravityResult = await handleAntigravityCliCommand(antigravitySubcommand, process.argv.slice(4));
diff --git a/src/shared/work-state-telemetry.ts b/src/shared/work-state-telemetry.ts
index 023211ae0..92a67c414 100644
--- a/src/shared/work-state-telemetry.ts
+++ b/src/shared/work-state-telemetry.ts
@@ -14,7 +14,7 @@ export interface WorkStateAttribution {
enqueuedAtEpochMs?: number;
}
-const PLATFORMS = new Set(['claude', 'codex', 'cursor', 'devin', 'kimi', 'mcode', 'muse-code', 'antigravity-cli', 'gemini', GROK_BUILD_PLATFORM_SOURCE, 'opencode', 'openclaw', 'omp', 'pi', 'qwen', 'windsurf', 'zcode']);
+const PLATFORMS = new Set(['claude', 'codex', 'cursor', 'devin', 'kimi', 'mcode', 'muse-code', 'atomcode', 'antigravity-cli', 'gemini', GROK_BUILD_PLATFORM_SOURCE, 'opencode', 'openclaw', 'omp', 'pi', 'qwen', 'windsurf', 'zcode']);
/** No default to Claude: missing host attribution really is unknown. */
export function workStatePlatform(value?: string): string {
diff --git a/tests/cli/adapters/atomcode.test.ts b/tests/cli/adapters/atomcode.test.ts
new file mode 100644
index 000000000..a8f17e346
--- /dev/null
+++ b/tests/cli/adapters/atomcode.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, test } from 'bun:test';
+import { atomcodeAdapter, claudeCodeAdapter, getPlatformAdapter } from '../../../src/cli/adapters/index.js';
+import { AdapterRejectedInput } from '../../../src/cli/adapters/errors.js';
+
+// AtomCode hook payloads, in the shapes built by
+// atomcode crates/atomcode-capabilities/src/cc_hooks.rs.
+const BASE = {
+ session_id: 'atomcode-session-0001',
+ cwd: process.cwd(),
+};
+const PRE_READ = {
+ ...BASE,
+ hook_event_name: 'PreToolUse',
+ call_id: 'tc-42',
+ tool_name: 'read_file',
+ tool_input: { file_path: 'notes.txt' },
+};
+// PostToolUse carries the result but no tool_input.
+const POST_BASH = {
+ ...BASE,
+ hook_event_name: 'PostToolUse',
+ call_id: 'tc-43',
+ tool_name: 'bash',
+ tool_response: 'ok\n',
+};
+
+describe('atomcodeAdapter', () => {
+ test('is the adapter for the atomcode platform', () => {
+ expect(getPlatformAdapter('atomcode')).toBe(atomcodeAdapter);
+ });
+
+ test('maps AtomCode tool names and keeps the native name', () => {
+ const mapped: Array<[string, string]> = [
+ ['bash', 'Bash'], ['read_file', 'Read'], ['write_file', 'Write'], ['edit_file', 'Edit'],
+ ['grep', 'Grep'], ['glob', 'Glob'], ['web_search', 'WebSearch'], ['web_fetch', 'WebFetch'],
+ ];
+ for (const [native, recorded] of mapped) {
+ const input = atomcodeAdapter.normalizeInput({ ...POST_BASH, tool_name: native });
+ expect(input.toolName).toBe(recorded);
+ expect(input.nativeToolName).toBe(native);
+ }
+ });
+
+ test('passes unmapped tools through unchanged with no native name', () => {
+ for (const name of ['task', 'mcp__x__y', 'toString']) {
+ const input = atomcodeAdapter.normalizeInput({ ...POST_BASH, tool_name: name });
+ expect(input.toolName).toBe(name);
+ expect(input.nativeToolName).toBeUndefined();
+ }
+ });
+
+ test('uses call_id as the tool use id so repeat tool events dedupe', () => {
+ expect(atomcodeAdapter.normalizeInput(POST_BASH).toolUseId).toBe('tc-43');
+ expect(atomcodeAdapter.normalizeInput(PRE_READ).toolUseId).toBe('tc-42');
+ expect(atomcodeAdapter.normalizeInput({ ...POST_BASH, tool_use_id: 'tu-1' }).toolUseId).toBe('tu-1');
+ });
+
+ test('reads a PostToolUse without tool_input: the result only', () => {
+ const input = atomcodeAdapter.normalizeInput(POST_BASH);
+ expect(input.toolInput).toBeUndefined();
+ expect(input.toolResponse).toBe('ok\n');
+ });
+
+ test('keeps the read_file input the file-context hook reads', () => {
+ expect(atomcodeAdapter.normalizeInput(PRE_READ).toolInput).toEqual({ file_path: 'notes.txt' });
+ });
+
+ test('rejects a payload without a session id', () => {
+ expect(() => atomcodeAdapter.normalizeInput({ ...POST_BASH, session_id: '' })).toThrow(AdapterRejectedInput);
+ expect(() => atomcodeAdapter.normalizeInput({ ...POST_BASH, session_id: undefined })).toThrow('missing_session_id');
+ });
+
+ // A cwd inherited from elsewhere (CLAUDE_PROJECT_DIR) must not replace AtomCode's.
+ test("keeps AtomCode's cwd, and falls back to the process cwd only when it is missing", () => {
+ expect(atomcodeAdapter.normalizeInput({ ...POST_BASH, cwd: '/home/example/project' }).cwd).toBe('/home/example/project');
+ expect(atomcodeAdapter.normalizeInput({ ...POST_BASH, cwd: '' }).cwd).toBe(process.cwd());
+ expect(atomcodeAdapter.normalizeInput({ ...POST_BASH, cwd: 42 }).cwd).toBe(process.cwd());
+ });
+
+ test('returns context in the Claude Code envelope', () => {
+ const result = { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: 'memory' } };
+ expect(atomcodeAdapter.formatOutput(result)).toEqual(claudeCodeAdapter.formatOutput(result));
+ });
+});
diff --git a/tests/integration/atomcode-hooks-installer.test.ts b/tests/integration/atomcode-hooks-installer.test.ts
new file mode 100644
index 000000000..7815231c7
--- /dev/null
+++ b/tests/integration/atomcode-hooks-installer.test.ts
@@ -0,0 +1,431 @@
+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:');
+ });
+});
diff --git a/tests/npx-cli/subcommand-help.test.ts b/tests/npx-cli/subcommand-help.test.ts
index 188b2dacc..977742712 100644
--- a/tests/npx-cli/subcommand-help.test.ts
+++ b/tests/npx-cli/subcommand-help.test.ts
@@ -103,6 +103,8 @@ describe('npx CLI subcommand --help', () => {
['mcode', 'uninstall'],
['muse-code'],
['muse-code', 'uninstall'],
+ ['atomcode'],
+ ['atomcode', 'uninstall'],
['antigravity-cli', 'uninstall'],
['pi', 'uninstall'],
['project', 'merge', 'a', 'b'],
diff --git a/tests/telemetry/work-state.test.ts b/tests/telemetry/work-state.test.ts
index 46627bad7..5a4c9be7b 100644
--- a/tests/telemetry/work-state.test.ts
+++ b/tests/telemetry/work-state.test.ts
@@ -227,6 +227,7 @@ describe('work-state usage telemetry', () => {
expect(workStatePlatform('claude-code')).toBe('claude');
expect(workStatePlatform('omp')).toBe('omp');
expect(workStatePlatform('muse-code')).toBe('muse-code');
+ expect(workStatePlatform('atomcode')).toBe('atomcode');
expect(workStateTool('mcp__mcp_search__work_state_read')).toBe('read');
expect(workStateTool('functions.update_plan')).toBe('native_todo');
expect(workStateTool('Write')).toBeNull();
diff --git a/tests/ui/my-work/setup-step-bar.test.ts b/tests/ui/my-work/setup-step-bar.test.ts
index 603d652e9..815403573 100644
--- a/tests/ui/my-work/setup-step-bar.test.ts
+++ b/tests/ui/my-work/setup-step-bar.test.ts
@@ -433,7 +433,7 @@ describe('setup tool marks', () => {
['openclaw', 'OpenClaw'], ['windsurf', 'Windsurf'], ['t3code', 'T3 Code'], ['kimi', 'Kimi Code'], ['devin', 'Devin CLI / Desktop'],
['cursor', 'Cursor'], ['grok-bot', 'Grok Bot'], ['copilot-cli', 'Copilot CLI'], ['copilot-vscode', 'Copilot in VS Code'], ['omp', 'OMP'], ['hermes', 'Hermes Agent'], ['pi', 'Pi'],
['dsh', 'DeepSeek Harness'], ['goose', 'Goose'], ['roo-code', 'Roo Code'], ['warp', 'Warp'], ['zed', 'Zed'],
- ['zcode', 'ZCode'], ['mcode', 'MiniMax Code'], ['muse-code', 'Muse Code'],
+ ['zcode', 'ZCode'], ['mcode', 'MiniMax Code'], ['muse-code', 'Muse Code'], ['atomcode', 'AtomCode'],
];
const SAME_TOOL = [['codex', 'codex-cli'], ['antigravity', 'antigravity-cli']];
const mark = (id: string, name: string) => app.renderMark(id, name).replace(/data:[^"]+/, (uri: string) => `image:${uri.length}:${uri.slice(-24)}`);