Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(command-code): add verified MCP and hook support

AkitaOnRailsfe2bd57d1367
diff --git a/AGENTS.md b/AGENTS.md
index 7f8ea5a0..732ae268 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -60,7 +60,7 @@ install or refresh work.
If you're about to write a durable project rule ("always X", "never
Y", "all PRs must ..."), write it in the project's canonical agent instruction file.
Many projects use CLAUDE.md for Claude Code and
-AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI,
+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI / Command Code,
but if the project says one file is canonical, use that file.
If the rule is a standing *user/team* preference that should apply to
@@ -77,7 +77,7 @@ latest binary's recommended copy:
- **From the agent** (no terminal needed): ask "refresh the ai-memory
routing in this project". The agent calls `memory_install_self_routing`,
picks the right filename for itself (Claude Code -> `CLAUDE.md`; Codex /
- OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI -> `AGENTS.md`),
+ OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI / Command Code -> `AGENTS.md`),
uses its Write / Edit tool to replace or append the returned
`markered_block` while preserving
non-ai-memory user content, then writes or updates each returned
@@ -95,7 +95,7 @@ start/end HTML-comment markers, without disturbing the rest of the file.
This file is the single canonical instruction file for AI coding agents
working in this repository (Claude Code, Codex, OpenCode, Cursor, Gemini
-CLI, Kimi Code, and other AGENTS-aware harnesses). `CLAUDE.md` is only a
+CLI, Kimi Code, Command Code, and other AGENTS-aware harnesses). `CLAUDE.md` is only a
short pointer here — do not duplicate rules into it.
## Project overview
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d31c814d..a140f379 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added first-party Command Code MCP and stable lifecycle-hook support.
+ `install-mcp --client command-code` merges the documented user-scope HTTP
+ entry; `install-hooks --agent command-code` preserves existing settings and
+ registers only `SessionStart`, `PreToolUse`, `PostToolUse`, and `Stop` with
+ native session attribution, capture exclusions, and startup handoff
+ injection. Experimental Mods and managed resume remain acceptance-gated,
+ and the turn-only Stop boundary is documented with the manual finalizer
+ workflow (#373).
- `ai-memory finalize-session --session-id <uuid>` targets exactly one open
session instead of "the latest open one for this agent+scope". Agents with
no true SessionEnd hook (Kiro CLI, Codex, Antigravity CLI) rely on
diff --git a/README.md b/README.md
index 997f1d23..6084795f 100644
--- a/README.md
+++ b/README.md
@@ -24,6 +24,7 @@
| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Local supported profiles default to host-native hook commands; Claude Code may use its Windows exec form, while other agents use native single command strings matching their hook schema. PowerShell/Git Bash scripts are compatibility fallbacks. See [`docs/windows.md`](docs/windows.md). |
| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. `install-mcp --session-aware` optionally enables per-session auto-scope isolation through a local stdio bridge. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). |
| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. No automatic true session-end hook, so run `ai-memory finalize-session` when you need a final summary/handoff. |
+| Command Code | Supported | MCP config (`~/.commandcode/mcp.json`) + its four stable lifecycle-hook events (`~/.commandcode/settings.json`); native commands enforce capture exclusions and `SessionStart` injects handoffs. `Stop` is only a turn boundary, so use `ai-memory finalize-session --agent command-code` after the final turn. Experimental Mods and managed workstreams remain acceptance-gated. |
| Devin CLI | Supported | MCP config + lifecycle hooks. Hooks use Devin's `PostCompaction` event, inject handoffs via `hookSpecificOutput.additionalContext`, and omit subagent events because Devin does not expose them. |
| OpenCode | Supported | Remote MCP config + generated TypeScript plugin; generated plugin enforces capture exclusions. |
| Cursor | Supported | MCP config + lifecycle hooks. |
@@ -154,7 +155,7 @@ priors are at the [bottom](#influences-and-prior-art).
volume; shared deployments keep the endpoint root-only. See
[MCP client activity](docs/users.md#mcp-client-activity).
- **Multi-agent + multi-machine ready.** Supported clients: Claude
- Code, Codex, Devin CLI, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),
+ Code, Codex, Command Code, Devin CLI, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),
Gemini CLI, Antigravity CLI, Grok Build CLI, Kimi Code, OpenClaw, Oh My Pi
/ OMP (`omp` / `oh-my-pi`), Pi via generated bridge extension, VS Code
GitHub Copilot agent mode (MCP-only, workspace `.vscode/mcp.json`), Kiro CLI
@@ -460,7 +461,7 @@ docker run -d --name ai-memory \
# 3. Wire your agent CLI in two commands. The wrapper takes care of
# mounts and each client's config-path detection. Re-run with
-# `--agent codex`, `--agent devin`, `--agent opencode`, `--agent gemini-cli`,
+# `--agent codex`, `--agent command-code`, `--agent devin`, `--agent opencode`, `--agent gemini-cli`,
# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent omp`,
# `--agent oh-my-pi`, `--client cursor`,
# `--client gemini-cli`, `--client grok`, `--client kiro-cli`, etc.
@@ -474,6 +475,9 @@ ai-memory install-hooks --agent claude-code --apply
# ai-memory install-mcp --client kiro-cli --apply
# ai-memory install-hooks --agent kiro-cli --apply
# Kiro CLI v3 hook capture is not yet supported; see docs/install.md.
+# Command Code stable MCP + lifecycle example:
+# ai-memory install-mcp --client command-code --apply
+# ai-memory install-hooks --agent command-code --apply
```
On Linux/macOS, that's it. Start a Claude Code session as usual - every
@@ -976,7 +980,7 @@ diagram, crate breakdown, schema notes, and invariants.
|---|---|
| [`docs/install.md`](docs/install.md) | **Installation cookbook.** Every agent CLI, every alternative (curl, source build, no-docker, no-auth), and the server-on-a-different-machine (homelab/LAN) walkthrough. Read after the Quick start if your setup doesn't match the happy path. |
| [`docs/usage.md`](docs/usage.md) | Handoffs, proactive memory queries, slim routing snippet + managed Agent Skills, migration from other memory tools, web UI, raw-wiki inspection, and rules-vs-facts workflow. |
-| [`docs/managed-workstreams.md`](docs/managed-workstreams.md) | Optional `ai-memory run` continuity across Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok Build CLI, and Antigravity CLI: automatic harness selection, native resume, argument forwarding, ledger search, privacy, and recovery. |
+| [`docs/managed-workstreams.md`](docs/managed-workstreams.md) | Optional `ai-memory run` continuity across Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI v2, OMP, Grok Build CLI, and Antigravity CLI: automatic harness selection, native resume, argument forwarding, ledger search, privacy, and recovery. |
| [`docs/managed-harness-contributions.md`](docs/managed-harness-contributions.md) | Protocol and acceptance bar for contributors adding managed resume, read-only transcript import, and startup context delivery to another harness. |
| [`docs/marker-file.md`](docs/marker-file.md) | `.ai-memory.toml` workspace/project routing for multi-client trees, mono-repos, worktrees, and work/personal separation. |
| [`docs/auto-scope.md`](docs/auto-scope.md) | `[auto_scope]` modes for shared servers: default single-slot routing, session-aware isolation, and multi-user `per_actor` behavior. |
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 09f036a6..31318c60 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1020,6 +1020,10 @@ pub enum AgentChoice {
/// tool payload fixtures.
#[value(alias = "kiro")]
KiroCli,
+ /// Command Code CLI — stable JSON-config shell hooks in
+ /// `~/.commandcode/settings.json`.
+ #[value(alias = "commandcode", alias = "cmdc", alias = "cmd")]
+ CommandCode,
}
impl AgentChoice {
@@ -1046,6 +1050,7 @@ impl AgentChoice {
Self::Devin => AgentKind::Devin,
Self::KimiCode => AgentKind::KimiCode,
Self::KiroCli => AgentKind::KiroCli,
+ Self::CommandCode => AgentKind::CommandCode,
}
}
@@ -1153,6 +1158,9 @@ pub enum McpClient {
/// `install-hooks --agent kiro-cli` for verified v2 lifecycle capture.
#[value(alias = "kiro")]
KiroCli,
+ /// Command Code CLI — `~/.commandcode/mcp.json`.
+ #[value(alias = "commandcode", alias = "cmdc", alias = "cmd")]
+ CommandCode,
/// VS Code GitHub Copilot (agent mode) — per-workspace
/// `.vscode/mcp.json`. Copilot's agent mode reads MCP servers
/// from VS Code's own MCP framework (top-level `servers` key),
@@ -2242,6 +2250,39 @@ mod tests {
}
}
+ #[test]
+ fn command_code_mcp_and_hook_aliases_parse() {
+ for alias in ["command-code", "commandcode", "cmdc", "cmd"] {
+ let mcp = Cli::try_parse_from([
+ "ai-memory",
+ "install-mcp",
+ "--client",
+ alias,
+ "--server-url",
+ "http://memory.example:49374",
+ ])
+ .unwrap_or_else(|error| panic!("failed to parse MCP alias {alias}: {error}"));
+ let Command::InstallMcp(args) = mcp.command else {
+ panic!("expected install-mcp for {alias}");
+ };
+ assert_eq!(args.client, McpClient::CommandCode);
+
+ let hooks = Cli::try_parse_from([
+ "ai-memory",
+ "install-hooks",
+ "--agent",
+ alias,
+ "--server-url",
+ "http://memory.example:49374",
+ ])
+ .unwrap_or_else(|error| panic!("failed to parse hook alias {alias}: {error}"));
+ let Command::InstallHooks(args) = hooks.command else {
+ panic!("expected install-hooks for {alias}");
+ };
+ assert_eq!(args.agent, AgentChoice::CommandCode);
+ }
+ }
+
#[test]
fn install_hooks_project_strategy_repo_root_parses() {
let cli = Cli::try_parse_from([
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index ba625fb3..585e2fa2 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -25,13 +25,13 @@ use crate::commands::install_mcp;
use crate::commands::openclaw_plugin;
use crate::commands::path_util::home_dir;
use crate::commands::render_shared::{
- ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,
- GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, build_antigravity_payload_with_data_dir,
- build_claude_code_payload_with_data_dir, build_devin_payload_with_data_dir,
- build_grok_payload_with_data_dir, build_kiro_cli_v2_hooks_value,
- build_profile_payload_for_agent, hook_script_for_claude_code, hook_script_for_current_platform,
- kimi_code_hook_commands, local_hook_policy_v1_supported, ts_capture_policy_v1,
- ts_string_literal,
+ ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, COMMAND_CODE_PROFILE,
+ CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS,
+ build_antigravity_payload_with_data_dir, build_claude_code_payload_with_data_dir,
+ build_devin_payload_with_data_dir, build_grok_payload_with_data_dir,
+ build_kiro_cli_v2_hooks_value, build_profile_payload_for_agent, hook_script_for_claude_code,
+ hook_script_for_current_platform, kimi_code_hook_commands, local_hook_policy_v1_supported,
+ ts_capture_policy_v1, ts_string_literal,
};
use crate::config::{Config, DEFAULT_SERVER_URL};
@@ -65,6 +65,14 @@ pub(crate) fn codex_hooks_path() -> anyhow::Result<std::path::PathBuf> {
.join("hooks.json"))
}
+/// `~/.commandcode/settings.json`.
+pub(crate) fn command_code_settings_path() -> anyhow::Result<std::path::PathBuf> {
+ Ok(home_dir()
+ .context("could not locate $HOME for ~/.commandcode/settings.json")?
+ .join(".commandcode")
+ .join("settings.json"))
+}
+
/// `~/.cursor/hooks.json`.
pub(crate) fn cursor_hooks_path() -> anyhow::Result<std::path::PathBuf> {
Ok(home_dir()
@@ -286,6 +294,16 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
apply_to_codex_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)
}
+ AgentChoice::CommandCode => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ apply_to_command_code_settings(
+ &hooks_dir,
+ &server_url,
+ auth,
+ &config.data_dir,
+ &args,
+ )
+ }
AgentChoice::Cursor => {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
apply_to_cursor_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)
@@ -362,6 +380,17 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
&[CODEX_PROFILE.events],
)
}
+ AgentChoice::CommandCode => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ render_agent(
+ "command-code",
+ &hooks_dir,
+ &server_url,
+ auth,
+ strategy,
+ &[COMMAND_CODE_PROFILE.events],
+ )
+ }
AgentChoice::Cursor => {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
render_agent(
@@ -456,6 +485,7 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {
match args.agent {
AgentChoice::ClaudeCode => claude_settings_path().ok()?,
AgentChoice::Codex => codex_hooks_path().ok()?,
+ AgentChoice::CommandCode => command_code_settings_path().ok()?,
AgentChoice::Cursor => cursor_hooks_path().ok()?,
AgentChoice::GeminiCli => gemini_settings_path().ok()?,
AgentChoice::OpenCode => opencode_plugin_path().ok()?,
@@ -681,6 +711,11 @@ fn infer_installed_mcp_config(agent: AgentChoice) -> Result<Option<InferredMcpCo
// Codex uses `http_headers`; Grok uses `headers`. The shared TOML
// inferencer accepts both.
McpClient::Codex => Ok(infer_toml_mcp_config(&content)),
+ McpClient::CommandCode => Ok(infer_json_mcp_config(
+ &content,
+ &["mcpServers", "ai-memory"],
+ "url",
+ )),
McpClient::Grok => infer_grok_mcp_config(&content),
McpClient::OpenCode => Ok(infer_json_mcp_config(
&content,
@@ -781,6 +816,7 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {
match agent {
AgentChoice::ClaudeCode => Some(McpClient::ClaudeCode),
AgentChoice::Codex => Some(McpClient::Codex),
+ AgentChoice::CommandCode => Some(McpClient::CommandCode),
AgentChoice::Cursor => Some(McpClient::Cursor),
AgentChoice::GeminiCli => Some(McpClient::GeminiCli),
AgentChoice::OpenCode => Some(McpClient::OpenCode),
@@ -1302,6 +1338,103 @@ fn apply_to_devin_settings_with_staged(
Ok(())
}
+/// Mutate `~/.commandcode/settings.json` so Command Code fires the stable
+/// four-event lifecycle integration. Command Code's schema requires the outer
+/// `matcher` to be omitted for SessionStart and Stop, so its profile must not
+/// reuse the otherwise similar Claude/Codex payload byte-for-byte.
+fn apply_to_command_code_settings(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let staged = stage_hook_scripts(hooks_dir, "command-code")?;
+ apply_to_command_code_settings_with_staged(&staged, server_url, auth_token, data_dir, args)
+}
+
+#[cfg(test)]
+fn apply_to_command_code_settings_in(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ staging_data_local: &Path,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let staged = stage_hook_scripts_in(hooks_dir, "command-code", staging_data_local)?;
+ let command_dir = staged_command_dir(&staged, "command-code");
+ let payload = crate::commands::render_shared::build_profile_script_payload_for_test(
+ &COMMAND_CODE_PROFILE,
+ &command_dir,
+ server_url,
+ auth_token,
+ "command-code",
+ Some(data_dir),
+ args.project_strategy.and_then(ProjectStrategyArg::baked),
+ );
+ apply_to_command_code_settings_with_payload(payload, args)
+}
+
+fn apply_to_command_code_settings_with_staged(
+ staged: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let command_dir = staged_command_dir(staged, "command-code");
+ let payload = build_profile_payload_for_agent(
+ &COMMAND_CODE_PROFILE,
+ &command_dir,
+ server_url,
+ auth_token,
+ "command-code",
+ Some(data_dir),
+ args.project_strategy.and_then(ProjectStrategyArg::baked),
+ );
+ apply_to_command_code_settings_with_payload(payload, args)
+}
+
+fn apply_to_command_code_settings_with_payload(
+ payload: serde_json::Value,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let path = match &args.config_file {
+ Some(path) => path.clone(),
+ None => command_code_settings_path()?,
+ };
+ let our_hooks = payload
+ .get("hooks")
+ .and_then(serde_json::Value::as_object)
+ .context("internal: Command Code payload did not return a hooks object")?
+ .clone();
+ let outcome = apply_atomic(&path, |existing| {
+ mutate_json(existing, |root| {
+ let hooks = root
+ .entry("hooks")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`hooks` is present in settings.json but not an object")?;
+ for (event, value) in &our_hooks {
+ overlay_event_hooks(hooks, event, value);
+ }
+ Ok(())
+ })
+ })?;
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ path.display(),
+ match outcome {
+ ApplyOutcome::Created => "new file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ Ok(())
+}
+
/// Mutate `~/.codex/hooks.json` (creating it if absent) so Codex's
/// lifecycle hook runner fires the ai-memory scripts on every
/// session/prompt/tool event.
@@ -3887,6 +4020,7 @@ mod tests {
// opt-in cannot take effect for them, so the installer must bail.
for agent in [
Codex,
+ CommandCode,
Cursor,
GeminiCli,
OpenCode,
@@ -3898,6 +4032,7 @@ mod tests {
Zero,
Devin,
KimiCode,
+ KiroCli,
] {
assert!(
!capture_assistant_allowed(agent),
@@ -3980,6 +4115,88 @@ mod tests {
);
}
+ #[test]
+ fn command_code_apply_uses_only_stable_events_and_preserves_user_settings() {
+ let source = TempDir::new().unwrap();
+ stub_scripts(
+ source.path(),
+ &[
+ "session-start.sh",
+ "pre-tool-use.sh",
+ "post-tool-use.sh",
+ "stop.sh",
+ ],
+ );
+ let staging = TempDir::new().unwrap();
+ let config_dir = TempDir::new().unwrap();
+ let config_path = config_dir.path().join("settings.json");
+ fs::write(
+ &config_path,
+ serde_json::json!({
+ "theme": "dark",
+ "hooks": {
+ "SessionStart": [{
+ "hooks": [{"type": "command", "command": "third-party"}]
+ }]
+ }
+ })
+ .to_string(),
+ )
+ .unwrap();
+ let args = InstallHooksArgs {
+ agent: AgentChoice::CommandCode,
+ config_file: Some(config_path.clone()),
+ ..default_hook_args()
+ };
+
+ apply_to_command_code_settings_in(
+ source.path(),
+ "http://memory:49374",
+ Some("token"),
+ config_dir.path(),
+ staging.path(),
+ &args,
+ )
+ .unwrap();
+ let first = fs::read_to_string(&config_path).unwrap();
+ apply_to_command_code_settings_in(
+ source.path(),
+ "http://memory:49374",
+ Some("token"),
+ config_dir.path(),
+ staging.path(),
+ &args,
+ )
+ .unwrap();
+ let second = fs::read_to_string(&config_path).unwrap();
+ assert_eq!(first, second, "re-apply must be idempotent");
+
+ let value: serde_json::Value = serde_json::from_str(&second).unwrap();
+ assert_eq!(value["theme"], "dark");
+ let hooks = value["hooks"].as_object().unwrap();
+ for event in ["SessionStart", "PreToolUse", "PostToolUse", "Stop"] {
+ let entries = hooks[event].as_array().unwrap();
+ let ours = entries
+ .iter()
+ .find(|entry| serde_json::to_string(entry).unwrap().contains("ai-memory"))
+ .unwrap_or_else(|| panic!("missing ai-memory entry for {event}"));
+ assert!(ours.get("matcher").is_none(), "event: {event}");
+ }
+ assert_eq!(
+ hooks["SessionStart"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|entry| serde_json::to_string(entry)
+ .unwrap()
+ .contains("third-party"))
+ .count(),
+ 1,
+ "third-party hook must survive"
+ );
+ assert_eq!(hooks.len(), COMMAND_CODE_PROFILE.events.len());
+ }
+
#[test]
fn overlay_event_hooks_inserts_when_event_absent() {
let mut hooks = serde_json::Map::new();
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index 063c9af7..fde77162 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -76,6 +76,7 @@ pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {
McpClient::Devin => render_devin(&args)?,
McpClient::KimiCode => render_kimi_code(&args)?,
McpClient::KiroCli => render_kiro_cli(&args)?,
+ McpClient::CommandCode => render_command_code(&args)?,
McpClient::VsCodeCopilot => render_vscode_copilot(&args)?,
McpClient::Zed => render_zed(&args)?,
};
@@ -210,6 +211,7 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>
McpClient::KiroCli => kiro_home(std::env::var_os("KIRO_HOME"))?
.join("settings")
.join("mcp.json"),
+ McpClient::CommandCode => home()?.join(".commandcode").join("mcp.json"),
// VS Code MCP is workspace-scoped by default: `.vscode/mcp.json`
// at the current workspace root. The user-profile alternative
// lives under VS Code's profile-specific data dir; use VS
@@ -461,7 +463,8 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {
| McpClient::AntigravityCli
| McpClient::Devin
| McpClient::KimiCode
- | McpClient::KiroCli => Some(JsonMcpLocation::RootMcpServers),
+ | McpClient::KiroCli
+ | McpClient::CommandCode => Some(JsonMcpLocation::RootMcpServers),
McpClient::OpenCode => Some(JsonMcpLocation::RootMcp),
// Zero's config.json nests servers under `mcp.servers`, the same
// shape OpenClaw uses.
@@ -680,6 +683,14 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {
entry.insert("headers".into(), json!({"Authorization": b}));
}
}
+ McpClient::CommandCode => {
+ entry.insert("transport".into(), json!("http"));
+ entry.insert("enabled".into(), json!(true));
+ entry.insert("url".into(), json!(server_url));
+ if let Some(b) = &bearer {
+ entry.insert("headers".into(), json!({"Authorization": b}));
+ }
+ }
McpClient::VsCodeCopilot => {
// VS Code MCP framework schema: `type: "http"` + `url`,
// headers map for auth. Verified against
@@ -1155,6 +1166,20 @@ fn render_kiro_cli(args: &InstallMcpArgs) -> Result<String> {
))
}
+fn render_command_code(args: &InstallMcpArgs) -> Result<String> {
+ Ok(format!(
+ "# Command Code — merge into ~/.commandcode/mcp.json:\n\
+ #\n\
+ # The equivalent CLI registration is:\n\
+ # cmd mcp add --transport http --scope user {name} {url}\n\
+ # (`cmdc` is the native Windows executable name.)\n\
+ {snippet}\n",
+ name = args.name,
+ url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),
+ snippet = render_json_mcp_fragment(args)?,
+ ))
+}
+
fn render_vscode_copilot(args: &InstallMcpArgs) -> Result<String> {
Ok(format!(
"# VS Code GitHub Copilot (agent mode) — write to one of:\n\
@@ -1311,6 +1336,32 @@ mod tests {
);
}
+ #[test]
+ fn command_code_renderer_uses_documented_user_scope_http_schema() {
+ let fragment = render_json_mcp_fragment(&args_with_token(McpClient::CommandCode)).unwrap();
+ let value: serde_json::Value = serde_json::from_str(&fragment).unwrap();
+
+ assert_eq!(
+ value,
+ json!({
+ "mcpServers": {
+ "ai-memory": {
+ "transport": "http",
+ "enabled": true,
+ "url": "http://127.0.0.1:49374/mcp",
+ "headers": {
+ "Authorization": "Bearer test-token-deadbeef"
+ }
+ }
+ }
+ })
+ );
+ let rendered = render_command_code(&args_for(McpClient::CommandCode)).unwrap();
+ assert!(rendered.contains("~/.commandcode/mcp.json"));
+ assert!(rendered.contains("cmd mcp add --transport http --scope user"));
+ assert!(rendered.contains("`cmdc` is the native Windows executable"));
+ }
+
#[test]
fn zed_apply_preserves_settings_and_siblings_and_is_idempotent() {
let tmp = tempfile::TempDir::new().unwrap();
@@ -1561,6 +1612,7 @@ mod tests {
McpClient::Devin => render_devin(&args).unwrap(),
McpClient::KimiCode => render_kimi_code(&args).unwrap(),
McpClient::KiroCli => render_kiro_cli(&args).unwrap(),
+ McpClient::CommandCode => render_command_code(&args).unwrap(),
McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),
McpClient::Zed => render_zed(&args).unwrap(),
}
@@ -1585,6 +1637,7 @@ mod tests {
McpClient::Devin,
McpClient::KimiCode,
McpClient::KiroCli,
+ McpClient::CommandCode,
McpClient::VsCodeCopilot,
McpClient::Zed,
] {
@@ -1623,6 +1676,7 @@ mod tests {
McpClient::Devin,
McpClient::KimiCode,
McpClient::KiroCli,
+ McpClient::CommandCode,
McpClient::VsCodeCopilot,
McpClient::Zed,
] {
@@ -1654,6 +1708,7 @@ mod tests {
McpClient::Devin => render_devin(&args).unwrap(),
McpClient::KimiCode => render_kimi_code(&args).unwrap(),
McpClient::KiroCli => render_kiro_cli(&args).unwrap(),
+ McpClient::CommandCode => render_command_code(&args).unwrap(),
McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),
McpClient::Zed => render_zed(&args).unwrap(),
}
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 8b609a63..2e462b8e 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -518,6 +518,10 @@ pub(crate) enum HookShape {
/// Gemini CLI tolerates (but doesn't require) a sibling
/// `sequential` key at the outer level — we don't set it.
Nested,
+ /// Command Code's nested handler shape without an outer matcher. Its
+ /// stable hook schema treats omission as "all tools" and does not fire
+ /// SessionStart/Stop when a matcher is present.
+ NestedWithoutMatcher,
/// Cursor: `"e": [ { "type":"command", "command":"...",
/// "matcher":"" } ]` (no inner `hooks` array). Cursor's
/// `hooks.json` also requires a sibling `version: 1` key at
@@ -554,6 +558,16 @@ pub(crate) const CODEX_EVENTS: [(&str, &str); 6] = [
("Stop", "stop.sh"),
];
+/// Command Code's stable shell-hook vocabulary. Mods expose more lifecycle
+/// events but remain experimental, so the first-party integration uses only
+/// these documented stable boundaries.
+pub(crate) const COMMAND_CODE_EVENTS: [(&str, &str); 4] = [
+ ("SessionStart", "session-start.sh"),
+ ("PreToolUse", "pre-tool-use.sh"),
+ ("PostToolUse", "post-tool-use.sh"),
+ ("Stop", "stop.sh"),
+];
+
/// Cursor's hook-event vocabulary (per
/// <https://cursor.com/docs/agent/hooks>). camelCase event names
/// and a FLAT JSON shape (no inner `hooks: [...]` wrapper).
@@ -592,6 +606,10 @@ pub(crate) const CODEX_PROFILE: HookProfile = HookProfile {
events: &CODEX_EVENTS,
shape: HookShape::Nested,
};
+pub(crate) const COMMAND_CODE_PROFILE: HookProfile = HookProfile {
+ events: &COMMAND_CODE_EVENTS,
+ shape: HookShape::NestedWithoutMatcher,
+};
pub(crate) const CURSOR_PROFILE: HookProfile = HookProfile {
events: &CURSOR_EVENTS,
shape: HookShape::Flat,
@@ -1078,6 +1096,9 @@ fn build_hook_payload_for_platform(
"matcher": "",
"hooks": [handler],
}]),
+ HookShape::NestedWithoutMatcher => json!([{
+ "hooks": [handler],
+ }]),
HookShape::Flat => Value::Array(vec![hook_handler_with_matcher(handler)]),
};
hooks_block.insert((*event).to_string(), entry);
@@ -2142,7 +2163,9 @@ check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 &&
HookCommandContext::new(platform, agent, None, None).allow_claude_windows_exec(),
);
match shape {
- HookShape::Nested => v.pointer("/hooks/SessionStart/0/hooks/0").unwrap().clone(),
+ HookShape::Nested | HookShape::NestedWithoutMatcher => {
+ v.pointer("/hooks/SessionStart/0/hooks/0").unwrap().clone()
+ }
HookShape::Flat => v.pointer("/hooks/SessionStart/0").unwrap().clone(),
}
}
@@ -2240,6 +2263,25 @@ check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 &&
);
}
+ #[test]
+ fn command_code_profile_omits_matchers_and_uses_native_agent_identity() {
+ let value = build_hook_payload_for_platform(
+ &COMMAND_CODE_EVENTS,
+ Path::new("/hooks"),
+ "http://memory:49374",
+ None,
+ HookShape::NestedWithoutMatcher,
+ HookCommandContext::new(HookCommandPlatform::PosixNative, "command-code", None, None),
+ );
+
+ for event in ["SessionStart", "PreToolUse", "PostToolUse", "Stop"] {
+ let definition = &value["hooks"][event][0];
+ assert!(definition.get("matcher").is_none(), "event: {event}");
+ let command = definition["hooks"][0]["command"].as_str().unwrap();
+ assert!(command.contains("--agent command-code"), "{command}");
+ }
+ }
+
#[test]
fn claude_code_payload_emits_absolute_paths() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 50524071..8b189f92 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -37,9 +37,10 @@ use anyhow::{Context, Result, bail};
use crate::cli::{AgentChoice, SetupAgentArgs};
use crate::commands::install_mcp;
use crate::commands::render_shared::{
- ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,
- GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, build_claude_code_payload,
- build_devin_payload, build_grok_payload, hook_script_for_current_platform,
+ ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, COMMAND_CODE_PROFILE,
+ CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS,
+ build_claude_code_payload, build_devin_payload, build_grok_payload,
+ hook_script_for_current_platform,
};
use crate::config::{Config, DEFAULT_SERVER_URL};
@@ -135,6 +136,9 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
AgentChoice::Grok => emit_grok(&emit_root, &args)?,
AgentChoice::Devin => emit_devin(&emit_root, &args)?,
AgentChoice::Codex => emit_other(&emit_root, agent_sub, &args, &[CODEX_PROFILE.events]),
+ AgentChoice::CommandCode => {
+ emit_other(&emit_root, agent_sub, &args, &[COMMAND_CODE_PROFILE.events])
+ }
AgentChoice::Cursor => emit_other(&emit_root, agent_sub, &args, &[CURSOR_PROFILE.events]),
AgentChoice::GeminiCli => {
emit_other(&emit_root, agent_sub, &args, &[GEMINI_PROFILE.events]);
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index b3a8736b..6284b997 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -165,6 +165,10 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {
install_hooks::gemini_settings_path()?,
HookConfigShape::NestedHooksKey,
),
+ (
+ install_hooks::command_code_settings_path()?,
+ HookConfigShape::NestedHooksKey,
+ ),
// Grok's ~/.grok/hooks/ai-memory.json shares Claude Code's
// JSON shape, so the same strip pass removes our entries.
(
@@ -307,6 +311,7 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {
Devin,
KimiCode,
KiroCli,
+ CommandCode,
] {
let paths = if matches!(client, ClaudeCode) {
claude_config_paths(
@@ -1002,6 +1007,7 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {
| McpClient::AntigravityCli
| McpClient::KimiCode
| McpClient::KiroCli
+ | McpClient::CommandCode
| McpClient::Devin => Some(&["mcpServers"]),
McpClient::OpenCode => Some(&["mcp"]),
McpClient::Openclaw | McpClient::Zero => Some(&["mcp", "servers"]),
diff --git a/crates/ai-memory-cli/tests/packaging.rs b/crates/ai-memory-cli/tests/packaging.rs
index 4e07b1c5..ac38f15a 100644
--- a/crates/ai-memory-cli/tests/packaging.rs
+++ b/crates/ai-memory-cli/tests/packaging.rs
@@ -671,22 +671,11 @@ fn hook_installer_rejects_a_checksum_mismatch_before_writing_scripts() {
}
#[cfg(unix)]
-#[test]
-fn hook_installer_writes_only_expected_files_from_a_verified_archive() {
- const HOOKS: &[&str] = &[
- "post-tool-use",
- "pre-compact",
- "pre-tool-use",
- "session-end",
- "session-start",
- "stop",
- "user-prompt-submit",
- ];
-
+fn installed_hook_names(agent_arg: &str, canonical_agent: &str, hooks: &[&str]) -> Vec<String> {
let tmp = tempfile::tempdir().unwrap();
- let bundle = tmp.path().join("bundle/hooks/claude-code");
+ let bundle = tmp.path().join("bundle/hooks").join(canonical_agent);
std::fs::create_dir_all(&bundle).unwrap();
- for hook in HOOKS {
+ for hook in hooks {
std::fs::write(
bundle.join(format!("{hook}.sh")),
format!("#!/usr/bin/env bash\nprintf '{hook}\\n'\n"),
@@ -737,7 +726,7 @@ fn hook_installer_writes_only_expected_files_from_a_verified_archive() {
);
let destination = tmp.path().join("installed-hooks");
let output = shell_script_command(&repo_root().join("scripts/install-hooks.sh"))
- .args(["--agent", "claude-code", "--to"])
+ .args(["--agent", agent_arg, "--to"])
.arg(&destination)
.env("PATH", path)
.env("HOME", tmp.path())
@@ -751,20 +740,14 @@ fn hook_installer_writes_only_expected_files_from_a_verified_archive() {
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
- let installed = destination.join("claude-code");
+ let installed = destination.join(canonical_agent);
let mut names = std::fs::read_dir(&installed)
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.collect::<Vec<_>>();
names.sort();
- let mut expected = HOOKS
- .iter()
- .map(|hook| format!("{hook}.sh"))
- .collect::<Vec<_>>();
- expected.sort();
- assert_eq!(names, expected);
use std::os::unix::fs::PermissionsExt as _;
- for name in names {
+ for name in &names {
assert_ne!(
std::fs::metadata(installed.join(name))
.unwrap()
@@ -774,6 +757,41 @@ fn hook_installer_writes_only_expected_files_from_a_verified_archive() {
0
);
}
+ names
+}
+
+#[cfg(unix)]
+#[test]
+fn hook_installer_writes_only_expected_files_from_a_verified_archive() {
+ const HOOKS: &[&str] = &[
+ "post-tool-use",
+ "pre-compact",
+ "pre-tool-use",
+ "session-end",
+ "session-start",
+ "stop",
+ "user-prompt-submit",
+ ];
+
+ let names = installed_hook_names("claude-code", "claude-code", HOOKS);
+ let expected = HOOKS
+ .iter()
+ .map(|hook| format!("{hook}.sh"))
+ .collect::<Vec<_>>();
+ assert_eq!(names, expected);
+}
+
+#[cfg(unix)]
+#[test]
+fn hook_installer_writes_only_command_code_stable_events() {
+ const HOOKS: &[&str] = &["post-tool-use", "pre-tool-use", "session-start", "stop"];
+
+ let names = installed_hook_names("cmdc", "command-code", HOOKS);
+ let expected = HOOKS
+ .iter()
+ .map(|hook| format!("{hook}.sh"))
+ .collect::<Vec<_>>();
+ assert_eq!(names, expected);
}
#[cfg(unix)]
diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rs
index 351bd784..a977c02a 100644
--- a/crates/ai-memory-core/src/ids.rs
+++ b/crates/ai-memory-core/src/ids.rs
@@ -212,6 +212,8 @@ pub enum AgentKind {
KimiCode,
/// AWS Kiro CLI (verified v2 lifecycle protocol).
KiroCli,
+ /// Command Code CLI.
+ CommandCode,
/// Hermes Agent (Nous Research).
Hermes,
/// Anything else (manual capture, future agents).
@@ -224,7 +226,7 @@ impl AgentKind {
/// CHECK constraint accepts every kind (the Zero integration shipped
/// with the enum variant but without the V26 migration and only a
/// live test caught it). Extend together with the enum.
- pub const ALL: [Self; 18] = [
+ pub const ALL: [Self; 19] = [
Self::ClaudeCode,
Self::Codex,
Self::OpenCode,
@@ -241,6 +243,7 @@ impl AgentKind {
Self::Devin,
Self::KimiCode,
Self::KiroCli,
+ Self::CommandCode,
Self::Hermes,
Self::Other,
];
@@ -265,6 +268,7 @@ impl AgentKind {
Self::Devin => "devin",
Self::KimiCode => "kimi-code",
Self::KiroCli => "kiro-cli",
+ Self::CommandCode => "command-code",
Self::Hermes => "hermes",
Self::Other => "other",
}
@@ -292,6 +296,7 @@ impl AgentKind {
"devin" => Self::Devin,
"kimi-code" | "kimi" => Self::KimiCode,
"kiro-cli" | "kiro" => Self::KiroCli,
+ "command-code" | "commandcode" | "cmdc" | "cmd" => Self::CommandCode,
"hermes" | "hermes-agent" => Self::Hermes,
_ => Self::Other,
}
@@ -445,6 +450,24 @@ mod tests {
assert!(!AgentKind::Hermes.user_prompt_injects_handoff());
}
+ #[test]
+ fn agent_kind_command_code_round_trips_and_injects_session_start_handoff() {
+ assert_eq!(AgentKind::CommandCode.as_str(), "command-code");
+ for alias in ["command-code", "commandcode", "cmdc", "cmd"] {
+ assert_eq!(AgentKind::from_wire(alias), AgentKind::CommandCode);
+ }
+ assert_eq!(
+ serde_json::to_string(&AgentKind::CommandCode).unwrap(),
+ "\"command-code\""
+ );
+ assert_eq!(
+ serde_json::from_str::<AgentKind>("\"command-code\"").unwrap(),
+ AgentKind::CommandCode
+ );
+ assert!(AgentKind::CommandCode.session_start_injects_handoff());
+ assert!(!AgentKind::CommandCode.user_prompt_injects_handoff());
+ }
+
#[test]
fn agent_kind_kiro_cli_round_trips_and_injects_at_session_start() {
assert_eq!(AgentKind::KiroCli.as_str(), "kiro-cli");
diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rs
index d2d172b7..cdecabc4 100644
--- a/crates/ai-memory-core/src/routing_snippet.rs
+++ b/crates/ai-memory-core/src/routing_snippet.rs
@@ -88,7 +88,7 @@ install or refresh work.
If you're about to write a durable project rule ("always X", "never
Y", "all PRs must ..."), write it in the project's canonical agent instruction file.
Many projects use CLAUDE.md for Claude Code and
-AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI,
+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI / Command Code,
but if the project says one file is canonical, use that file.
If the rule is a standing *user/team* preference that should apply to
@@ -105,7 +105,7 @@ latest binary's recommended copy:
- **From the agent** (no terminal needed): ask "refresh the ai-memory
routing in this project". The agent calls `memory_install_self_routing`,
picks the right filename for itself (Claude Code -> `CLAUDE.md`; Codex /
- OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI -> `AGENTS.md`),
+ OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI / Command Code -> `AGENTS.md`),
uses its Write / Edit tool to replace or append the returned
`markered_block` while preserving
non-ai-memory user content, then writes or updates each returned
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 5aace4fa..9709b5fb 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -126,7 +126,7 @@ pub(crate) fn tool_observation_metadata(
) -> Option<ToolObservationMetadata> {
let object = raw.as_object()?;
let (name, id) = match agent {
- AgentKind::ClaudeCode => (
+ AgentKind::ClaudeCode | AgentKind::CommandCode => (
object.get("tool_name")?.as_str()?,
object.get("tool_use_id").and_then(Value::as_str),
),
@@ -161,7 +161,10 @@ pub(crate) fn tool_observation_metadata(
.get(
if matches!(
agent,
- AgentKind::ClaudeCode | AgentKind::Hermes | AgentKind::KiroCli
+ AgentKind::ClaudeCode
+ | AgentKind::CommandCode
+ | AgentKind::Hermes
+ | AgentKind::KiroCli
) {
"tool_input"
} else {
@@ -529,6 +532,7 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted {
.and_then(Value::as_str)
.map(|name| (name, object.get("input"))),
AgentKind::ClaudeCode
+ | AgentKind::CommandCode
| AgentKind::Codex
| AgentKind::Cursor
| AgentKind::GeminiCli
@@ -603,11 +607,11 @@ fn family(name: &str) -> ToolFamily {
| "write_to_file"
| "fs_read"
| "fs_write" => ToolFamily::File,
- "read_file" | "write_file" | "patch" => ToolFamily::File,
+ "read_file" | "write_file" | "edit_file" | "patch" => ToolFamily::File,
"search" | "grep" | "glob" | "find" | "list" | "ls" | "list_files" | "read_dir"
| "list_dir" | "grep_search" | "search_files" => ToolFamily::SearchList,
- "bash" | "shell" | "execute" | "run_command" | "web_search" | "terminal"
- | "execute_bash" | "execute_cmd" => ToolFamily::NonFile,
+ "bash" | "shell" | "shell_command" | "execute" | "run_command" | "web_search"
+ | "terminal" | "execute_bash" | "execute_cmd" => ToolFamily::NonFile,
_ => ToolFamily::Unknown,
}
}
@@ -1077,6 +1081,43 @@ mod tests {
}
}
+ #[test]
+ fn command_code_official_tool_shape_is_closed_and_honors_exclusions() {
+ let policy = CapturePolicy::resolve(
+ CaptureSource::Parsed(&CaptureConfig {
+ ignore_paths: vec!["secret/**".into()],
+ }),
+ "/repo",
+ None,
+ );
+ let ignored = json!({
+ "session_id": "command-session",
+ "cwd": "/repo",
+ "tool_use_id": "tool-42",
+ "tool_name": "edit_file",
+ "tool_input": {
+ "file_path": "secret/token.txt",
+ "old_value": "old",
+ "new_value": "new"
+ }
+ });
+
+ let metadata = tool_observation_metadata(AgentKind::CommandCode, &ignored, true).unwrap();
+ assert_eq!(metadata.tool_family, ToolFamily::File);
+ assert_eq!(metadata.tool_call_id.as_deref(), Some("tool-42"));
+ let decision = policy.inspect(AgentKind::CommandCode, &ignored, "/repo");
+ assert_eq!(decision.protocol().disposition(), CaptureDisposition::Drop);
+
+ for (tool, expected) in [
+ ("read_file", ToolFamily::File),
+ ("write_file", ToolFamily::File),
+ ("edit_file", ToolFamily::File),
+ ("shell_command", ToolFamily::NonFile),
+ ] {
+ assert_eq!(family(tool), expected, "tool: {tool}");
+ }
+ }
+
#[test]
fn antigravity_native_tools_are_no_longer_unknown() {
for (tool, expected) in [
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 3eb05a53..0899ed0b 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -512,6 +512,7 @@ const fn closed_tool_agent(agent: AgentKind) -> bool {
matches!(
agent,
AgentKind::ClaudeCode
+ | AgentKind::CommandCode
| AgentKind::OpenCode
| AgentKind::Pi
| AgentKind::AntigravityCli
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 2174879a..87eb8b13 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -3536,6 +3536,7 @@ impl AiMemoryServer {
"zero": "AGENTS.md",
"devin": "AGENTS.md",
"kimi_code": "AGENTS.md",
+ "command_code": "AGENTS.md",
"grok": "AGENTS.md",
"default": "AGENTS.md"
},
@@ -5065,6 +5066,12 @@ mod tests {
response["agent_filenames"]["kimi_code"].as_str().unwrap(),
"AGENTS.md"
);
+ assert_eq!(
+ response["agent_filenames"]["command_code"]
+ .as_str()
+ .unwrap(),
+ "AGENTS.md"
+ );
// Proposed symmetrically alongside the devin assertion above:
// upstream added "zero" to this same payload (issue #156) without a
// matching assertion. Not validated against a live Zero agent in
diff --git a/crates/ai-memory-store/migrations/V47__sessions_command_code_agent_kind.sql b/crates/ai-memory-store/migrations/V47__sessions_command_code_agent_kind.sql
new file mode 100644
index 00000000..9730b5f5
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V47__sessions_command_code_agent_kind.sql
@@ -0,0 +1,73 @@
+-- Expand sessions.agent_kind CHECK for Command Code CLI.
+--
+-- Keep the complete V45 schema, indexes, and scope-pairing triggers while
+-- adding the `command-code` wire value.
+
+PRAGMA foreign_keys = OFF;
+
+DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_session_pairing_ai;
+DROP TRIGGER IF EXISTS session_consolidation_jobs_session_pairing_ai;
+
+CREATE TABLE sessions_new (
+ id BLOB PRIMARY KEY NOT NULL,
+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','pi','crush','grok','zero','devin','kimi-code','kiro-cli','command-code','hermes','other')),
+ cwd TEXT,
+ started_at INTEGER NOT NULL,
+ ended_at INTEGER,
+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL,
+ ended_observation_count INTEGER NOT NULL DEFAULT 0 CHECK (ended_observation_count >= 0),
+ actor_user TEXT
+);
+
+INSERT INTO sessions_new (
+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,
+ summary_page_id, ended_observation_count, actor_user
+)
+SELECT
+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,
+ summary_page_id, ended_observation_count, actor_user
+FROM sessions;
+
+DROP TABLE sessions;
+
+ALTER TABLE sessions_new RENAME TO sessions;
+
+CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);
+CREATE INDEX idx_sessions_project ON sessions(project_id);
+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);
+CREATE INDEX idx_sessions_scope_ended
+ ON sessions(workspace_id, project_id, ended_at ASC)
+ WHERE ended_at IS NOT NULL;
+CREATE INDEX idx_sessions_open_owner
+ ON sessions(workspace_id, project_id, agent_kind, actor_user)
+ WHERE ended_at IS NULL;
+
+CREATE TRIGGER sessions_ws_proj_pairing_ai
+BEFORE INSERT ON sessions
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)
+BEGIN
+ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');
+END;
+
+CREATE TRIGGER auto_improve_scheduler_claims_session_pairing_ai
+BEFORE INSERT ON auto_improve_scheduler_claims
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)
+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)
+BEGIN
+ SELECT RAISE(ABORT, 'auto_improve_scheduler_claims scope does not match the session scope');
+END;
+
+CREATE TRIGGER session_consolidation_jobs_session_pairing_ai
+BEFORE INSERT ON session_consolidation_jobs
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)
+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)
+BEGIN
+ SELECT RAISE(ABORT, 'session_consolidation_jobs scope does not match the session scope');
+END;
+
+PRAGMA foreign_keys = ON;
diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rs
index 8e919ab2..be2a9ac0 100644
--- a/crates/ai-memory-store/src/migrations.rs
+++ b/crates/ai-memory-store/src/migrations.rs
@@ -660,4 +660,76 @@ mod tests {
assert_eq!(schema_object_count(&conn, kind, name), 1, "missing {name}");
}
}
+
+ #[test]
+ fn v46_to_v47_preserves_session_state_and_accepts_command_code() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ run_to(&mut conn, 46).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();
+ let project_id =
+ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();
+ let existing = SessionId::new();
+ conn.execute(
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at, \
+ ended_observation_count, actor_user) \
+ VALUES (?1, ?2, ?3, 'kiro-cli', '/repo', 1, 2, 7, 'user:alice')",
+ params![
+ existing.as_bytes(),
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ ],
+ )
+ .unwrap();
+
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ run(&mut conn).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+
+ let preserved: (String, String, i64, Option<String>) = conn
+ .query_row(
+ "SELECT agent_kind, cwd, ended_observation_count, actor_user \
+ FROM sessions WHERE id = ?1",
+ params![existing.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
+ )
+ .unwrap();
+ assert_eq!(
+ preserved,
+ (
+ "kiro-cli".into(),
+ "/repo".into(),
+ 7,
+ Some("user:alice".into())
+ )
+ );
+
+ crate::ops::begin_session(
+ &mut conn,
+ &NewSession {
+ id: SessionId::new(),
+ workspace_id,
+ project_id,
+ agent_kind: AgentKind::CommandCode,
+ cwd: Some("/repo".into()),
+ actor_user: Some("user:alice".into()),
+ },
+ )
+ .unwrap();
+
+ for name in [
+ "idx_sessions_open_owner",
+ "sessions_ws_proj_pairing_ai",
+ "auto_improve_scheduler_claims_session_pairing_ai",
+ "session_consolidation_jobs_session_pairing_ai",
+ ] {
+ let kind = if name.starts_with("idx_") {
+ "index"
+ } else {
+ "trigger"
+ };
+ assert_eq!(schema_object_count(&conn, kind, name), 1, "missing {name}");
+ }
+ }
}
diff --git a/docs/install.md b/docs/install.md
index fc91e27f..9a18d71f 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -9,7 +9,7 @@ path (docker + Claude Code). This page covers everything else:
- [Arch Linux native packages (AUR)](#arch-linux-native-packages-aur)
(systemd system service or user service)
- [Configuring other agent CLIs](#configuring-other-agent-clis)
- (Codex, Devin CLI, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, Kimi Code, Kiro CLI, OpenClaw, VS Code Copilot, Zed)
+ (Codex, Command Code, Devin CLI, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, Kimi Code, Kiro CLI, OpenClaw, VS Code Copilot, Zed)
- [Installing hooks without docker](#installing-hooks-without-docker)
(curl-based installer)
- [Running ai-memory without docker](#running-ai-memory-without-docker)
@@ -738,6 +738,53 @@ Kimi Code hook entries accept only `event`, `matcher`, `command`, and
`timeout`; extra fields make the whole `config.toml` fail to load, so prefer
`install-hooks --apply` over hand edits.
+### Command Code
+
+Command Code keeps user-scope MCP and hook configuration in separate JSON
+files under `~/.commandcode/`. Install both integrations with:
+
+```bash
+ai-memory install-mcp --client command-code --apply \
+ --server-url "http://homelab:49374/mcp" \
+ --auth-token "$TOKEN"
+
+ai-memory install-hooks --agent command-code --apply \
+ --server-url "http://homelab:49374" \
+ --auth-token "$TOKEN"
+```
+
+The aliases `commandcode`, `cmdc`, and `cmd` are accepted. `install-mcp`
+merges a native HTTP entry into `~/.commandcode/mcp.json`; `install-hooks`
+merges only Command Code's four stable events (`SessionStart`, `PreToolUse`,
+`PostToolUse`, and `Stop`) into `~/.commandcode/settings.json`, preserving
+other settings and hook handlers. The hook definitions deliberately omit
+`matcher`: Command Code documents omission as "all tools", while any matcher
+on `SessionStart` or `Stop` prevents that lifecycle hook from firing.
+
+Local installs use the native `ai-memory hook` command, so Command Code's
+native `session_id` and `cwd` are attributed directly;
+recognized `shell_command`, `read_file`, `write_file`, and `edit_file`
+payloads pass through the same bounded capture-exclusion policy as other
+native integrations. A pending handoff is injected through
+`hookSpecificOutput.additionalContext` at `SessionStart`.
+
+Command Code's stable `Stop` event ends a turn, not a session. Finalize the
+open session after the last turn when you need immediate consolidation and a
+handoff:
+
+```bash
+ai-memory finalize-session --agent command-code
+ai-memory finalize-session --agent command-code --session-id <uuid>
+```
+
+ai-memory does not install Command Code Mods. Mods are currently documented
+as experimental, run unsandboxed, and do not provide the same stable native
+session identity at every callback. Managed `ai-memory run command-code`
+support is also withheld until a logged-in acceptance run proves the current
+session-store layout, exact resume selector, checkout ownership, read-only
+transcript import, `--yolo` translation, and Windows executable behavior.
+Direct `cmd`, `cmdc`, or `command-code` launches remain unchanged.
+
### Kiro CLI
Kiro CLI has one MCP surface. ai-memory supports the documented v2 lifecycle
@@ -964,6 +1011,14 @@ docker run --rm akitaonrails/ai-memory:latest \
install-hooks --agent kiro-cli --auth-token "$TOKEN" \
--server-url "https://memory.example"
+docker run --rm akitaonrails/ai-memory:latest \
+ install-mcp --client command-code --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374/mcp"
+
+docker run --rm akitaonrails/ai-memory:latest \
+ install-hooks --agent command-code --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374"
+
docker run --rm akitaonrails/ai-memory:latest \
install-mcp --client vscode-copilot --auth-token "$TOKEN" \
--server-url "http://homelab:49374/mcp"
@@ -973,7 +1028,7 @@ docker run --rm akitaonrails/ai-memory:latest \
--server-url "http://homelab:49374/mcp"
```
-Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Kiro CLI, and OpenClaw support both
+Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Kiro CLI, Command Code, and OpenClaw support both
`install-mcp` and `install-hooks`. Grok's `install-mcp --client grok` writes
`$GROK_HOME/config.toml` (default `~/.grok/config.toml`); its hooks live under
`$GROK_HOME/hooks` (default `~/.grok/hooks`). `install-hooks --agent grok`
@@ -1373,7 +1428,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| Subcommand | Pattern | What it does |
|---|---|---|
| `serve` | `docker compose up -d` (already done) | Run the HTTP MCP server |
-| `run [harness] [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; omit the harness to resume the newest usable local session, or name Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok Build CLI, or Antigravity CLI explicitly; exact `--yolo` and `--fresh` flags are wrapper-owned and other native arguments pass through |
+| `run [harness] [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; omit the harness to resume the newest usable local session, or name Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI v2, OMP, Grok Build CLI, or Antigravity CLI explicitly; exact `--yolo` and `--fresh` flags are wrapper-owned and other native arguments pass through |
| `show [--json]` | host wrapper or native binary | Choose a client-local checkout and installed managed harness, or return structured discovery data without launching; remote servers never provide checkout paths |
| `continue [--workspace NAME]` | host wrapper or native binary | From any directory, revalidate and resume the newest client-local managed checkout; accepts `--yolo` and `--fresh` but no harness-native arguments |
| `workstream-search [query]` | managed child or thin HTTP client | Search the complete visible managed-workstream ledger; the managed child receives its workstream id automatically |
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 51767f49..cd697ce1 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -234,6 +234,14 @@ is labelled completed evidence and must never be replayed as a pending call.
| Grok Build CLI | generated `--session-id` | `--resume <id>` | `$GROK_HOME/sessions/*/*/chat_history.jsonl` |
| Antigravity CLI | native default creation | `--conversation <id>` | `~/.gemini/antigravity-cli/conversations/<id>.db` metadata plus lifecycle-hook capture |
+Command Code is intentionally absent from this table. Its first-party MCP and
+stable lifecycle-hook integration does not imply managed resume support.
+Before adding a managed adapter, a logged-in current release must prove the
+session-store layout, exact resume selector, checkout validation, read-only
+visible-event extraction, dangerous-mode translation, normal-exit finalization,
+and the `cmdc` executable path on native Windows. Experimental Mod APIs are not
+a substitute for those native-session acceptance artifacts.
+
An explicit native selector such as Claude's `--resume`, OpenCode's `--session`,
Codex's `resume`, or Antigravity's `--conversation` / `--continue` wins.
ai-memory links the selected native session and resets an unrelated adapter
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index e596e1f3..175fa6e7 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -120,7 +120,7 @@ metadata.
> **One-shot tip:** every snippet below is also reachable from the
> CLI:
> ```bash
-> ai-memory install-mcp --client gemini-cli # or cursor / claude-desktop / openclaw / omp / pi / antigravity-cli / grok / kimi-code / kiro-cli / devin / zero / vscode-copilot / zed
+> ai-memory install-mcp --client gemini-cli # or cursor / claude-desktop / openclaw / omp / pi / antigravity-cli / grok / kimi-code / kiro-cli / command-code / devin / zero / vscode-copilot / zed
> ```
---
@@ -774,9 +774,9 @@ script bundle /
native `ai-memory hook --event … --agent kimi-code` commands (native is the
default for local installs; the staged scripts under
`~/.local/share/ai-memory/hooks/kimi-code/` are the compatibility fallback).
-Capture is fire-and-forget; a pending handoff is injected at `SessionStart`
-via the hook's stdout (Kimi Code appends stdout to context on exit 0), the
-same pattern as Gemini CLI.
+Capture is fire-and-forget; a pending handoff is injected at
+`UserPromptSubmit` via the hook's stdout (Kimi Code discards `SessionStart`
+stdout but prepends successful user-prompt hook output to the turn).
**Gotchas:**
- Do not add a `transport` field for HTTP servers: `url` alone means
@@ -793,6 +793,56 @@ same pattern as Gemini CLI.
but are mutually exclusive event triggers, so successful and failed calls
are both captured once.
+## Command Code
+
+**Status:** MCP and the four stable shell-hook events are supported. Managed
+workstreams and experimental Mods are not installed.
+
+**Config files:** `~/.commandcode/mcp.json` for MCP and
+`~/.commandcode/settings.json` for lifecycle hooks.
+
+```bash
+ai-memory install-mcp --client command-code --apply \
+ --server-url "http://homelab:49374/mcp" --auth-token "$TOKEN"
+ai-memory install-hooks --agent command-code --apply \
+ --server-url "http://homelab:49374" --auth-token "$TOKEN"
+```
+
+The MCP installer writes the documented user-scope remote shape:
+
+```json
+{
+ "mcpServers": {
+ "ai-memory": {
+ "transport": "http",
+ "enabled": true,
+ "url": "http://homelab:49374/mcp",
+ "headers": { "Authorization": "Bearer <token>" }
+ }
+ }
+}
+```
+
+The hook installer registers `SessionStart`, `PreToolUse`, `PostToolUse`, and
+`Stop`. It omits the outer `matcher` from every definition because Command
+Code documents omission as matching every tool and says a matcher prevents
+the non-tool `SessionStart` and `Stop` events from firing. Native installs
+spool events locally, enforce capture exclusions for the documented tool
+envelope, and inject pending handoffs with
+`hookSpecificOutput.additionalContext` at `SessionStart`.
+
+`Stop` is only a turn boundary. Run `ai-memory finalize-session --agent
+command-code` after the final turn (or add `--session-id <uuid>` when several
+sessions share the project). ai-memory does not generate a Mod: that API is
+experimental and unsandboxed. A managed adapter remains deferred until a real
+logged-in client acceptance test supplies safe fixtures for exact resume,
+checkout ownership, transcript import, dangerous mode, and native Windows.
+
+Sources: <https://commandcode.ai/docs/mcp>,
+<https://commandcode.ai/docs/hooks>,
+<https://commandcode.ai/docs/mods>, and
+<https://commandcode.ai/docs/reference/cli>.
+
## Kiro CLI
**Status:** MCP, v2 lifecycle hooks, and explicit v2 managed workstreams are
@@ -1027,8 +1077,8 @@ that *starts* the next one - to play nicely with ai-memory:
| Side | What's needed | Covered by |
|---|---|---|
-| **Ending side** | The agent must create a handoff through a true session-end hook, the manual finalizer, or `memory_handoff_begin`. | Built-in automatically for Claude Code, Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, and OMP. Codex and Antigravity CLI have no reliable true session-end event: run `ai-memory finalize-session` for Codex or `ai-memory finalize-session --agent antigravity-cli` for Antigravity after the final turn. |
-| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Kimi Code / OpenClaw / OpenCode / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok and Zero are explicitly excluded because they discard SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |
+| **Ending side** | The agent must create a handoff through a true session-end hook, the manual finalizer, or `memory_handoff_begin`. | Built-in automatically for Claude Code, Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, and OMP. Codex, Antigravity CLI, Kiro CLI v2, and Command Code have no reliable true session-end event; run `ai-memory finalize-session` with the corresponding `--agent` after the final turn. |
+| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Kimi Code / Kiro CLI v2 / Command Code / OpenClaw / OpenCode / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok and Zero are explicitly excluded because they discard SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |
OpenCode uses its official `session.deleted` plugin event for true session-end
delivery. Its generated plugin also sends a deduped best-effort close for any
diff --git a/docs/usage.md b/docs/usage.md
index f3d45fa3..ec4d9399 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -297,6 +297,8 @@ Client cleanup hints:
- Claude Code: check plugins, hooks, old SessionStart injection, and MCP servers.
- Codex: check MCP config plus session/user-prompt/tool/compaction/stop hooks.
+- Command Code: check `~/.commandcode/mcp.json` and the four stable lifecycle
+ events in `~/.commandcode/settings.json`.
- Devin CLI: check `.devin/config.json`, `.devin/hooks.v1.json`, and
`.devin/skills` for stale MCP, hook, or routing-skill entries.
- Gemini CLI and Antigravity CLI: check `settings.json` or equivalent hook/MCP
@@ -418,7 +420,7 @@ page and no argument, ai-memory appends no preference block.
Durable project rules belong in the agent's rules file, not only in the
wiki. For Claude Code that is `CLAUDE.md`; for Codex, Devin CLI, OpenCode,
-Cursor, Gemini CLI, Grok Build CLI, Kimi Code, and Kiro CLI it is usually
+Cursor, Gemini CLI, Grok Build CLI, Kimi Code, Kiro CLI, and Command Code it is usually
`AGENTS.md`.
The consolidator classifies compiled observations as `decision`,
diff --git a/docs/windows.md b/docs/windows.md
index 1bbfed36..93764e81 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -6,7 +6,7 @@ agent CLI actually runs.
## Rule Of Thumb
Run `install-mcp` and `install-hooks` from the same environment that
-launches Claude Code, Codex, Devin CLI, Cursor, Gemini CLI, Kimi Code, Kiro CLI,
+launches Claude Code, Codex, Command Code, Devin CLI, Cursor, Gemini CLI, Kimi Code, Kiro CLI,
Antigravity CLI, or another agent.
- If the agent runs inside WSL2, install ai-memory inside WSL2.
@@ -143,7 +143,7 @@ for each native Windows agent so existing hook entries receive the current
command form.
Use the matching `--client` / `--agent` values for other clients, for
-example `codex`, `devin`, `kimi-code`, `kiro-cli`, `cursor`, or `gemini-cli`.
+example `codex`, `command-code`, `devin`, `kimi-code`, `kiro-cli`, `cursor`, or `gemini-cli`.
For Devin, `install-mcp --client devin --apply` writes MCP config to
`%USERPROFILE%\.devin\config.json`. `install-hooks --agent devin --apply`
@@ -356,8 +356,8 @@ Windows agent builds.
Claude Code invokes hooks as a direct binary call (no shell) by default;
`AI_MEMORY_HOOK_PLATFORM=windows-bash` restores the Git Bash `bash -c`
path. WSL2 Claude Code uses normal WSL `.sh` paths.
-- Codex, Devin CLI, OpenCode, Cursor, Gemini CLI, Antigravity CLI, Grok Build
- CLI, Zero, Kimi Code, and OpenClaw may each choose different
+- Codex, Command Code, Devin CLI, OpenCode, Cursor, Gemini CLI, Antigravity
+ CLI, Grok Build CLI, Zero, Kimi Code, and OpenClaw may each choose different
Windows config locations or shell execution behavior. ai-memory uses
the current best-known defaults, but they need validation on real
installations.
diff --git a/hooks/command-code/post-tool-use.ps1 b/hooks/command-code/post-tool-use.ps1
new file mode 100644
index 00000000..60b141ef
--- /dev/null
+++ b/hooks/command-code/post-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "command-code"
+exit 0
diff --git a/hooks/command-code/post-tool-use.sh b/hooks/command-code/post-tool-use.sh
new file mode 100755
index 00000000..b5cd08f6
--- /dev/null
+++ b/hooks/command-code/post-tool-use.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+# Command Code PostToolUse hook. Capture-only: it never asks for a retry.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+PAYLOAD=$(cat)
+CWD=$(ai_memory_extract_cwd "$PAYLOAD")
+QS=$(ai_memory_marker_qs "$CWD")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=post-tool-use&agent=command-code${QS}" >/dev/null 2>&1 || true
+printf '{}\n'
+exit 0
diff --git a/hooks/command-code/pre-tool-use.ps1 b/hooks/command-code/pre-tool-use.ps1
new file mode 100644
index 00000000..7e447b3e
--- /dev/null
+++ b/hooks/command-code/pre-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "command-code"
+exit 0
diff --git a/hooks/command-code/pre-tool-use.sh b/hooks/command-code/pre-tool-use.sh
new file mode 100755
index 00000000..0ae5bbaa
--- /dev/null
+++ b/hooks/command-code/pre-tool-use.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+# Command Code PreToolUse hook. Capture-only: it never blocks a tool.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+PAYLOAD=$(cat)
+CWD=$(ai_memory_extract_cwd "$PAYLOAD")
+QS=$(ai_memory_marker_qs "$CWD")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=pre-tool-use&agent=command-code${QS}" >/dev/null 2>&1 || true
+printf '{}\n'
+exit 0
diff --git a/hooks/command-code/session-start.ps1 b/hooks/command-code/session-start.ps1
new file mode 100644
index 00000000..acb47f1d
--- /dev/null
+++ b/hooks/command-code/session-start.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-start" -Agent "command-code" -FetchHandoff
+exit 0
diff --git a/hooks/command-code/session-start.sh b/hooks/command-code/session-start.sh
new file mode 100755
index 00000000..08a6b215
--- /dev/null
+++ b/hooks/command-code/session-start.sh
@@ -0,0 +1,26 @@
+#!/bin/sh
+# Command Code SessionStart hook: capture the boundary, then inject a pending
+# cross-agent handoff through hookSpecificOutput.additionalContext.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+PAYLOAD=$(cat)
+CWD=$(ai_memory_extract_cwd "$PAYLOAD")
+QS=$(ai_memory_marker_qs "$CWD")
+SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")
+SESSION_QS=""
+[ -n "$SESSION_ID" ] && SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=session-start&agent=command-code${QS}" >/dev/null 2>&1 || true
+
+HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=command-code${QS}${SESSION_QS}" 2>/dev/null || true)
+if [ -n "$HANDOFF" ]; then
+ printf '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":%s}}\n' \
+ "$(printf '%s' "$HANDOFF" | ai_memory_json_string)"
+else
+ printf '{}\n'
+fi
+exit 0
diff --git a/hooks/command-code/stop.ps1 b/hooks/command-code/stop.ps1
new file mode 100644
index 00000000..00f34acd
--- /dev/null
+++ b/hooks/command-code/stop.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "stop" -Agent "command-code"
+exit 0
diff --git a/hooks/command-code/stop.sh b/hooks/command-code/stop.sh
new file mode 100755
index 00000000..a182d883
--- /dev/null
+++ b/hooks/command-code/stop.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+# Command Code Stop hook. Stop is a turn boundary, not a true session end.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+PAYLOAD=$(cat)
+CWD=$(ai_memory_extract_cwd "$PAYLOAD")
+QS=$(ai_memory_marker_qs "$CWD")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=stop&agent=command-code${QS}" >/dev/null 2>&1 || true
+printf '{}\n'
+exit 0
diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh
index 69e2ddee..5aab1dfb 100755
--- a/scripts/install-hooks.sh
+++ b/scripts/install-hooks.sh
@@ -9,7 +9,7 @@
# ai-memory-install-hooks --agent claude-code
#
# Options:
-# --agent <claude-code|codex|cursor|gemini-cli|kimi-code|kiro-cli|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi>
+# --agent <claude-code|codex|command-code|cursor|gemini-cli|kimi-code|kiro-cli|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi>
# which agent (default: claude-code;
# generated-plugin agents print hints)
# --to <dir> install root (default: $HOME/.ai-memory/hooks)
@@ -46,10 +46,11 @@ while [[ $# -gt 0 ]]; do
done
case "$AGENT" in
- claude-code|codex|cursor|gemini-cli|kimi-code|kiro-cli|antigravity-cli|grok|opencode|openclaw|omp|pi|oh-my-pi) ;;
+ claude-code|codex|command-code|cursor|gemini-cli|kimi-code|kiro-cli|antigravity-cli|grok|opencode|openclaw|omp|pi|oh-my-pi) ;;
+ commandcode|cmdc|cmd) AGENT="command-code" ;;
kiro) AGENT="kiro-cli" ;;
*)
- echo "unsupported agent: $AGENT (expected claude-code | codex | cursor | gemini-cli | kimi-code | kiro-cli | antigravity-cli | grok | opencode | openclaw | omp | pi | oh-my-pi)" >&2
+ echo "unsupported agent: $AGENT (expected claude-code | codex | command-code | cursor | gemini-cli | kimi-code | kiro-cli | antigravity-cli | grok | opencode | openclaw | omp | pi | oh-my-pi)" >&2
exit 64 ;;
esac
@@ -120,6 +121,17 @@ if [[ "$AGENT" == "kiro-cli" ]]; then
)
fi
+# Command Code's stable hook API exposes exactly these four events. Additional
+# lifecycle boundaries belong to its experimental Mod API and are not shipped.
+if [[ "$AGENT" == "command-code" ]]; then
+ SCRIPTS=(
+ "session-start"
+ "pre-tool-use"
+ "post-tool-use"
+ "stop"
+ )
+fi
+
DEST="$TO/$AGENT"
mkdir -p "$DEST"