Skip to content

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

Rust

feat: support Kiro v3 lifecycle hooks

AkitaOnRails457b619bd848
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6cc34690..7aba19b9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -85,14 +85,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
without session injection. Kiro remains outside bare automatic selection
until a logged-in current-format acceptance run is available, and v3 managed
sessions remain unsupported (#356).
-- Added verified Kiro CLI v2 lifecycle hooks. CamelCase hooks merge into
- existing agent configs, honor `$KIRO_HOME`, preserve unrelated hooks and
- per-agent project strategies, fail before changing any target when one is
- invalid, infer remote connectivity from the managed Kiro MCP entry, inject
- handoffs through `agentSpawn` stdout, enforce capture exclusions for known
- v2 tool payloads, and uninstall only exact ai-memory entries. Kiro v3 hook
- capture remains unsupported pending sanitized live lifecycle and built-in
- tool payload fixtures, despite its now-documented standalone schema (#355).
+- Added verified Kiro CLI lifecycle hooks for both incompatible engines. The
+ existing `kiro` / `kiro-cli` target keeps v2's camelCase hooks in agent
+ configs; the explicit `kiro-cli-v3` target atomically merges Kiro's
+ standalone `v1` registration under `$KIRO_HOME/hooks`. Both preserve
+ unrelated entries and project strategies, infer remote MCP connectivity,
+ inject startup handoffs, enforce capture exclusions for documented file-tool
+ payloads, and uninstall only proven ai-memory entries (#355).
- Added `[consolidation] max_input_tokens` and `max_output_tokens`
(`AI_MEMORY_CONSOLIDATION__MAX_INPUT_TOKENS` /
`AI_MEMORY_CONSOLIDATION__MAX_OUTPUT_TOKENS`) for provider-specific context
diff --git a/README.md b/README.md
index 71c3a689..ff191d4b 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@
| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no hook handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). |
| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |
| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. |
-| Kiro CLI | Supported (v2) | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges verified v2 hooks into existing agent configs, honors `$KIRO_HOME`, preserves unrelated entries, and injects pending handoffs through `agentSpawn` stdout. Kiro v2 has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` when concurrent sessions share a scope. Explicit `ai-memory run kiro` adds v2 managed resume; it is not in bare automatic selection pending a logged-in current-format acceptance run. Kiro v3 hooks and managed sessions remain unsupported. |
+| Kiro CLI | Supported | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges v2 hooks into existing agent configs; the explicit `--agent kiro-cli-v3` target writes the incompatible standalone v3 registration. Both preserve unrelated entries, honor `$KIRO_HOME`, enforce capture exclusions, and inject pending handoffs at session start. Kiro has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` for concurrent sessions. Managed resume remains v2-only pending v3 workstream support. |
| VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). |
| Zed | MCP-only | Native remote MCP under `context_servers` in Zed's user `settings.json`; no lifecycle hooks or managed-workstream support. |
| Hermes Agent | Community | Core hook ingestion recognizes `agent=hermes` and Hermes' documented shell-hook `tool_name` / `tool_input` payload for concrete session attribution, tool-family titles, and capture exclusions. A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available, but no first-party installer is shipped; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. Hermes ignores session-start hook stdout, so recover handoffs through MCP. |
@@ -474,7 +474,8 @@ ai-memory install-hooks --agent claude-code --apply
# Kiro CLI v2 example (requires an existing Kiro agent config):
# 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.
+# Kiro CLI v3 example (standalone hook registration):
+# ai-memory install-hooks --agent kiro-cli-v3 --apply
# Command Code stable MCP + lifecycle example:
# ai-memory install-mcp --client command-code --apply
# ai-memory install-hooks --agent command-code --apply
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 31318c60..0c43f250 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1015,11 +1015,13 @@ pub enum AgentChoice {
#[value(alias = "kimi")]
KimiCode,
/// Kiro CLI (AWS), v2 agent engine — camelCase lifecycle hooks embedded
- /// in agent configs under `~/.kiro/agents/*.json`. Kiro v3's standalone
- /// schema is documented but lacks accepted live lifecycle and built-in
- /// tool payload fixtures.
+ /// in agent configs under `~/.kiro/agents/*.json`.
#[value(alias = "kiro")]
KiroCli,
+ /// Kiro CLI (AWS), v3 agent engine — PascalCase lifecycle hooks in the
+ /// standalone `$KIRO_HOME/hooks/ai-memory.json` registration file.
+ #[value(alias = "kiro-v3")]
+ KiroCliV3,
/// Command Code CLI — stable JSON-config shell hooks in
/// `~/.commandcode/settings.json`.
#[value(alias = "commandcode", alias = "cmdc", alias = "cmd")]
@@ -1049,7 +1051,7 @@ impl AgentChoice {
Self::Zero => AgentKind::Zero,
Self::Devin => AgentKind::Devin,
Self::KimiCode => AgentKind::KimiCode,
- Self::KiroCli => AgentKind::KiroCli,
+ Self::KiroCli | Self::KiroCliV3 => AgentKind::KiroCli,
Self::CommandCode => AgentKind::CommandCode,
}
}
@@ -2217,7 +2219,7 @@ mod tests {
}
#[test]
- fn kiro_v2_hook_aliases_parse_and_v3_is_not_advertised() {
+ fn kiro_hook_engine_aliases_parse_explicitly() {
for alias in ["kiro-cli", "kiro"] {
let cli = Cli::try_parse_from([
"ai-memory",
@@ -2233,20 +2235,21 @@ mod tests {
};
assert_eq!(args.agent, AgentChoice::KiroCli);
}
- for unsupported in ["kiro-cli-v3", "kiro-v3"] {
- let error = Cli::try_parse_from([
+ for alias in ["kiro-cli-v3", "kiro-v3"] {
+ let cli = Cli::try_parse_from([
"ai-memory",
"install-hooks",
"--agent",
- unsupported,
+ alias,
"--server-url",
"http://127.0.0.1:49374",
])
- .unwrap_err();
- assert!(
- error.to_string().contains("invalid value"),
- "v3 must remain unsupported until its live payload fixtures are verified: {error}"
- );
+ .unwrap_or_else(|error| panic!("failed to parse Kiro v3 alias {alias}: {error}"));
+ let Command::InstallHooks(args) = cli.command else {
+ panic!("expected install-hooks for Kiro v3 alias {alias}");
+ };
+ assert_eq!(args.agent, AgentChoice::KiroCliV3);
+ assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::KiroCli);
}
}
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index dbeee6e1..1cd9b881 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -374,7 +374,7 @@ fn write_success_response<W: std::io::Write>(
) -> std::io::Result<()> {
if agent == AgentKind::KiroCli {
// Kiro adds successful SessionStart/UserPromptSubmit stdout to model
- // context, and v2 Stop parses stdout for a block decision. Capture-only
+ // context, and v2/v3 Stop parse stdout for a block decision. Capture-only
// hooks therefore stay silent unless SessionStart has real context.
Ok(())
} else if agent == AgentKind::AntigravityCli && event == HookEvent::PreToolUse {
@@ -631,7 +631,7 @@ where
get_handoff(&client, &handoff_url, bearer.as_deref(), handoff_timeout()).await
{
if agent_kind == AgentKind::KiroCli {
- // Kiro v2 consumes agentSpawn stdout verbatim and defines
+ // Kiro v2/v3 consume SessionStart stdout verbatim and define
// no wrapper envelope.
writeln!(stdout, "{handoff}")?;
} else {
@@ -922,6 +922,9 @@ mod tests {
),
(AgentKind::KiroCli, HookEvent::PreToolUse, b"".as_slice()),
(AgentKind::KiroCli, HookEvent::SessionStart, b"".as_slice()),
+ (AgentKind::KiroCli, HookEvent::UserPrompt, b"".as_slice()),
+ (AgentKind::KiroCli, HookEvent::PostToolUse, b"".as_slice()),
+ (AgentKind::KiroCli, HookEvent::Stop, b"".as_slice()),
] {
let mut output = Vec::new();
write_success_response(&mut output, agent, event).unwrap();
@@ -929,6 +932,32 @@ mod tests {
}
}
+ #[test]
+ fn kiro_v3_live_lifecycle_fixtures_share_native_context() {
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../tests/fixtures/kiro-v3-hook-payloads.json"
+ ))
+ .unwrap();
+ let events = fixture["events"].as_array().unwrap();
+ assert_eq!(events.len(), 5);
+ for event in events {
+ let payload = &event["payload"];
+ let (cwd, session_id) = hook_context("kiro-cli", payload);
+ assert_eq!(cwd.as_deref(), Some("/workspace/project"));
+ assert_eq!(session_id.as_deref(), Some("kiro-v3-session"));
+ }
+ assert_eq!(events[0]["payload"]["hook_event_name"], "SessionStart");
+ assert_eq!(events[1]["payload"]["hook_event_name"], "UserPromptSubmit");
+ assert_eq!(events[2]["payload"]["hook_event_name"], "PreToolUse");
+ assert_eq!(events[3]["payload"]["hook_event_name"], "PostToolUse");
+ assert_eq!(events[4]["payload"]["hook_event_name"], "Stop");
+ assert_eq!(events[2]["payload"]["tool_name"], "read_file");
+ assert_eq!(
+ events[2]["payload"]["tool_input"]["path"],
+ "/workspace/project/sample.txt"
+ );
+ }
+
#[tokio::test]
async fn antigravity_native_pre_tool_use_allows_and_spools_valid_input() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 585e2fa2..332d0d0b 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -26,12 +26,12 @@ 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, COMMAND_CODE_PROFILE,
- CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS,
+ CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_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,
+ build_kiro_cli_v2_hooks_value, build_kiro_cli_v3_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};
@@ -196,6 +196,14 @@ pub(crate) fn kiro_cli_agents_dir() -> anyhow::Result<std::path::PathBuf> {
kiro_cli_home_join(std::env::var_os("KIRO_HOME"), "agents")
}
+/// `$KIRO_HOME/hooks/ai-memory.json` when set, else
+/// `~/.kiro/hooks/ai-memory.json`. Kiro v3 loads each standalone JSON file in
+/// this directory; using one ai-memory-owned file avoids mutating unrelated
+/// registrations.
+pub(crate) fn kiro_cli_v3_hooks_path() -> anyhow::Result<std::path::PathBuf> {
+ Ok(kiro_cli_home_join(std::env::var_os("KIRO_HOME"), "hooks")?.join("ai-memory.json"))
+}
+
/// The env value comes in as a parameter so tests can exercise both
/// branches without mutating process env (mirrors
/// `kimi_code_config_path_in`).
@@ -346,6 +354,10 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
&args,
)
}
+ AgentChoice::KiroCliV3 => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ apply_to_kiro_cli_v3_hooks(&hooks_dir, &server_url, auth, &config.data_dir, &args)
+ }
};
}
let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);
@@ -445,6 +457,10 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
render_kiro_cli(&hooks_dir, &server_url, auth, &config.data_dir, strategy)
}
+ AgentChoice::KiroCliV3 => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ render_kiro_cli_v3(&hooks_dir, &server_url, auth, &config.data_dir, strategy)
+ }
}
}
@@ -500,6 +516,7 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {
AgentChoice::Devin => devin_hooks_path().ok()?,
AgentChoice::KimiCode => kimi_code_config_path().ok()?,
AgentChoice::KiroCli => return None,
+ AgentChoice::KiroCliV3 => kiro_cli_v3_hooks_path().ok()?,
}
};
std::fs::read_to_string(path).ok()
@@ -544,6 +561,23 @@ fn baked_project_strategy(agent: AgentChoice, existing: &str) -> Option<ProjectS
})
})
}
+ AgentChoice::KiroCliV3 => {
+ let root: serde_json::Value = serde_json::from_str(existing).ok()?;
+ root.get("hooks")
+ .and_then(serde_json::Value::as_array)
+ .and_then(|hooks| {
+ hooks.iter().find_map(|entry| {
+ is_ai_memory_kiro_v3_hook_entry(entry)
+ .then(|| {
+ entry
+ .pointer("/action/command")
+ .and_then(serde_json::Value::as_str)
+ .and_then(project_strategy_from_text)
+ })
+ .flatten()
+ })
+ })
+ }
_ => serde_json::from_str(existing)
.ok()
.as_ref()
@@ -830,7 +864,7 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {
// Pi bridges MCP through its generated extension, not a native
// mcp.json the installer can scrape.
AgentChoice::Pi => None,
- AgentChoice::KiroCli => Some(McpClient::KiroCli),
+ AgentChoice::KiroCli | AgentChoice::KiroCliV3 => Some(McpClient::KiroCli),
}
}
@@ -2009,8 +2043,8 @@ fn apply_to_kiro_cli_agent_configs(
anyhow::ensure!(
p.is_file(),
"{} does not exist. Kiro CLI v2 hooks live inside an existing agent config; \
- create one first (`kiro-cli agent create`) and re-run. Kiro v3 hooks remain \
- unsupported pending fixture-verified lifecycle and built-in tool payloads.",
+ create one first (`kiro-cli agent create`) and re-run. For Kiro v3, select \
+ the explicit `--agent kiro-cli-v3` standalone-hook target instead.",
p.display()
);
vec![p.clone()]
@@ -2022,8 +2056,7 @@ fn apply_to_kiro_cli_agent_configs(
"no Kiro CLI agent configs found in {}. The v2 engine only fires hooks defined in an \
agent config and the built-in default agent has no file on disk, so create an agent \
first (`kiro-cli agent create`, then `kiro-cli agent set-default <name>`) and re-run. \
- Kiro v3 hooks remain unsupported pending fixture-verified lifecycle and built-in tool \
- payloads.",
+ For Kiro v3, select the explicit `--agent kiro-cli-v3` standalone-hook target instead.",
kiro_cli_agents_dir()?.display()
);
let prepared = preflight_kiro_cli_agent_configs(
@@ -2149,6 +2182,176 @@ fn render_kiro_cli_agent_hooks(
})
}
+fn apply_to_kiro_cli_v3_hooks(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let path = match &args.config_file {
+ Some(path) => path.clone(),
+ None => kiro_cli_v3_hooks_path()?,
+ };
+ let existing = match fs::read_to_string(&path) {
+ Ok(existing) => existing,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
+ Err(error) => return Err(error).with_context(|| format!("reading {}", path.display())),
+ };
+ let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);
+
+ // Validate before staging scripts so an incompatible registration file
+ // cannot leave a partial installation behind.
+ render_kiro_cli_v3_hooks(
+ &existing, hooks_dir, server_url, auth_token, data_dir, strategy, &path,
+ )?;
+
+ let staged = stage_hook_scripts(hooks_dir, "kiro-cli")?;
+ let command_dir = staged_command_dir(&staged, "kiro-cli");
+ let outcome = merge_kiro_cli_v3_hooks(
+ &command_dir,
+ server_url,
+ auth_token,
+ data_dir,
+ strategy,
+ &path,
+ )?;
+ 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(())
+}
+
+fn merge_kiro_cli_v3_hooks(
+ command_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ project_strategy: Option<&str>,
+ config_path: &Path,
+) -> Result<ApplyOutcome> {
+ apply_atomic(config_path, |existing| {
+ render_kiro_cli_v3_hooks(
+ existing,
+ command_dir,
+ server_url,
+ auth_token,
+ data_dir,
+ project_strategy,
+ config_path,
+ )
+ })
+}
+
+fn render_kiro_cli_v3_hooks(
+ existing: &str,
+ command_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ project_strategy: Option<&str>,
+ config_path: &Path,
+) -> Result<String> {
+ let desired = build_kiro_cli_v3_hooks_value(
+ command_dir,
+ server_url,
+ auth_token,
+ Some(data_dir),
+ project_strategy,
+ );
+ let desired_hooks = desired
+ .get("hooks")
+ .and_then(serde_json::Value::as_array)
+ .expect("static Kiro v3 hook payload has a hooks array")
+ .clone();
+
+ mutate_json(existing, |root| {
+ match root.get("version") {
+ Some(serde_json::Value::String(version)) if version == "v1" => {}
+ Some(serde_json::Value::String(version)) => anyhow::bail!(
+ "unsupported Kiro hook schema version `{version}` in {}; expected `v1`",
+ config_path.display()
+ ),
+ Some(_) => anyhow::bail!(
+ "`version` in {} is present but not a string",
+ config_path.display()
+ ),
+ None => {
+ root.insert(
+ "version".to_string(),
+ serde_json::Value::String("v1".to_string()),
+ );
+ }
+ }
+
+ let hooks = root
+ .entry("hooks")
+ .or_insert_with(|| serde_json::Value::Array(Vec::new()))
+ .as_array_mut()
+ .with_context(|| {
+ format!(
+ "`hooks` in {} is present but not an array",
+ config_path.display()
+ )
+ })?;
+
+ for entry in hooks.iter() {
+ if let Some(name) = entry.get("name").and_then(serde_json::Value::as_str)
+ && kiro_cli_v3_hook_name_is_reserved(name)
+ && !is_ai_memory_kiro_v3_hook_entry(entry)
+ {
+ anyhow::bail!(
+ "Kiro v3 hook `{name}` in {} uses ai-memory's reserved name but is not an \
+ ai-memory hook; rename it before installing",
+ config_path.display()
+ );
+ }
+ }
+ hooks.retain(|entry| !is_ai_memory_kiro_v3_hook_entry(entry));
+ hooks.extend(desired_hooks);
+ Ok(())
+ })
+}
+
+fn kiro_cli_v3_hook_name_is_reserved(name: &str) -> bool {
+ KIRO_CLI_V3_EVENTS.iter().any(|(_, script)| {
+ script
+ .strip_suffix(".sh")
+ .is_some_and(|stem| name == format!("ai-memory-{stem}"))
+ })
+}
+
+pub(crate) fn is_ai_memory_kiro_v3_hook_entry(entry: &serde_json::Value) -> bool {
+ let Some(name) = entry.get("name").and_then(serde_json::Value::as_str) else {
+ return false;
+ };
+ let Some(trigger) = entry.get("trigger").and_then(serde_json::Value::as_str) else {
+ return false;
+ };
+ let known_pair = KIRO_CLI_V3_EVENTS.iter().any(|(expected_trigger, script)| {
+ *expected_trigger == trigger
+ && script
+ .strip_suffix(".sh")
+ .is_some_and(|stem| name == format!("ai-memory-{stem}"))
+ });
+ known_pair
+ && entry
+ .pointer("/action/type")
+ .and_then(serde_json::Value::as_str)
+ == Some("command")
+ && entry
+ .pointer("/action/command")
+ .and_then(serde_json::Value::as_str)
+ .is_some_and(is_ai_memory_kiro_hook_command)
+}
+
/// Every `*.json` agent config in the Kiro CLI global agents directory,
/// sorted for deterministic apply order. A missing directory is an empty
/// list, not an error — the caller decides how to report it.
@@ -3984,9 +4187,8 @@ fn render_kiro_cli(
println!("// or re-run with --apply to merge into every existing agent config,");
println!("// preserving third-party hook entries. The v2 engine fires hooks");
println!("// only for the active agent config; the built-in default agent has");
- println!("// no file, so create one first (`kiro-cli agent create`). Kiro v3");
- println!("// hooks remain unsupported pending fixture-verified lifecycle and");
- println!("// built-in tool payloads; do not reuse this v2 registration there.");
+ println!("// no file, so create one first (`kiro-cli agent create`). Do not reuse");
+ println!("// this v2 registration for v3; use `--agent kiro-cli-v3` instead.");
println!("// Hook scripts: {}", hooks_dir.display());
println!("// AI-memory server URL: {server_url}");
if auth_token.is_some() {
@@ -4002,6 +4204,48 @@ fn render_kiro_cli(
Ok(())
}
+fn render_kiro_cli_v3(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ project_strategy: Option<&str>,
+) -> Result<()> {
+ for (_, script) in KIRO_CLI_V3_EVENTS {
+ let abs = hooks_dir.join(hook_script_for_current_platform(script).as_ref());
+ if !abs.exists() {
+ eprintln!(
+ "# warning: {} not present on this filesystem. If this command is running \
+ inside docker against a host path, you can ignore this; otherwise extract \
+ the scripts first with `ai-memory setup-agent`.",
+ abs.display()
+ );
+ }
+ }
+ let payload = build_kiro_cli_v3_hooks_value(
+ hooks_dir,
+ server_url,
+ auth_token,
+ Some(data_dir),
+ project_strategy,
+ );
+ println!("// Kiro CLI v3 hooks — write this document to");
+ println!("// $KIRO_HOME/hooks/ai-memory.json (~/.kiro/hooks/ai-memory.json when unset),");
+ println!("// or re-run with --apply for an atomic, idempotent merge.");
+ println!("// Hook scripts: {}", hooks_dir.display());
+ println!("// AI-memory server URL: {server_url}");
+ if auth_token.is_some() {
+ println!("// Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook command below.");
+ println!("// Treat the hook file as sensitive (chmod 600).");
+ }
+ println!();
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&payload).expect("static hook payload serializes")
+ );
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -4033,6 +4277,7 @@ mod tests {
Devin,
KimiCode,
KiroCli,
+ KiroCliV3,
] {
assert!(
!capture_assistant_allowed(agent),
@@ -6691,6 +6936,10 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
};
let agents = kiro_cli_home_join(Some(std::ffi::OsString::from(custom)), "agents").unwrap();
assert_eq!(agents, Path::new(custom).join("agents"));
+ let hooks = kiro_cli_home_join(Some(std::ffi::OsString::from(custom)), "hooks")
+ .unwrap()
+ .join("ai-memory.json");
+ assert_eq!(hooks, Path::new(custom).join("hooks/ai-memory.json"));
// Empty override and unset var both fall back to ~/.kiro.
for env in [None, Some(std::ffi::OsString::new())] {
@@ -6709,6 +6958,126 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
mcp_client_for_agent(AgentChoice::KiroCli),
Some(McpClient::KiroCli)
);
+ assert_eq!(
+ mcp_client_for_agent(AgentChoice::KiroCliV3),
+ Some(McpClient::KiroCli)
+ );
+ }
+
+ #[test]
+ fn kiro_cli_v3_apply_writes_documented_schema_and_is_idempotent() {
+ let hooks_tmp = TempDir::new().unwrap();
+ stub_scripts(hooks_tmp.path(), &KIRO_CLI_STUB_SCRIPTS);
+ let config_tmp = TempDir::new().unwrap();
+ let config_path = config_tmp.path().join("hooks/ai-memory.json");
+
+ let apply = || {
+ merge_kiro_cli_v3_hooks(
+ hooks_tmp.path(),
+ "https://memory.example",
+ Some("test-token"),
+ config_tmp.path(),
+ Some("repo-root"),
+ &config_path,
+ )
+ };
+ assert_eq!(apply().unwrap(), ApplyOutcome::Created);
+
+ let root: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();
+ assert_eq!(root["version"], "v1");
+ let hooks = root["hooks"].as_array().expect("hooks array");
+ assert_eq!(hooks.len(), KIRO_CLI_V3_EVENTS.len());
+ for ((trigger, script), entry) in KIRO_CLI_V3_EVENTS.iter().zip(hooks) {
+ assert_eq!(entry["trigger"], *trigger);
+ assert_eq!(entry["action"]["type"], "command");
+ assert_eq!(
+ entry["timeout"],
+ if *trigger == "SessionStart" { 5 } else { 1 }
+ );
+ assert_eq!(entry["enabled"], true);
+ assert_eq!(
+ entry["name"],
+ format!("ai-memory-{}", script.trim_end_matches(".sh"))
+ );
+ let command = entry["action"]["command"].as_str().unwrap();
+ assert!(is_ai_memory_kiro_hook_command(command), "{command}");
+ assert!(command.contains("test-token"), "{command}");
+ assert!(command.contains("repo-root"), "{command}");
+ assert!(entry.get("matcher").is_none());
+ }
+ assert_eq!(apply().unwrap(), ApplyOutcome::NoOp);
+ }
+
+ #[test]
+ fn kiro_cli_v3_apply_preserves_third_party_hooks_and_replaces_only_ours() {
+ let tmp = TempDir::new().unwrap();
+ let config_path = tmp.path().join("ai-memory.json");
+ fs::write(
+ &config_path,
+ r#"{
+ "version": "v1",
+ "owner": "user",
+ "hooks": [
+ {"name":"audit","trigger":"PreToolUse","action":{"type":"command","command":"audit-tool"}},
+ {"name":"ai-memory-session-start","trigger":"SessionStart","action":{"type":"command","command":"AI_MEMORY_HOOK_URL=http://old /old/hooks/kiro-cli/session-start.sh"}}
+ ]
+}"#,
+ )
+ .unwrap();
+
+ assert_eq!(
+ merge_kiro_cli_v3_hooks(
+ tmp.path(),
+ "https://memory.example",
+ None,
+ tmp.path(),
+ None,
+ &config_path,
+ )
+ .unwrap(),
+ ApplyOutcome::Updated
+ );
+ let root: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();
+ assert_eq!(root["owner"], "user");
+ let hooks = root["hooks"].as_array().unwrap();
+ assert_eq!(hooks.len(), 1 + KIRO_CLI_V3_EVENTS.len());
+ assert_eq!(hooks[0]["name"], "audit");
+ assert!(hooks[1..].iter().all(is_ai_memory_kiro_v3_hook_entry));
+ }
+
+ #[test]
+ fn kiro_cli_v3_apply_rejects_incompatible_schema_and_reserved_collision() {
+ let tmp = TempDir::new().unwrap();
+ let config_path = tmp.path().join("ai-memory.json");
+ fs::write(&config_path, r#"{"version":"v2","hooks":[]}"#).unwrap();
+ let error = merge_kiro_cli_v3_hooks(
+ tmp.path(),
+ "https://memory.example",
+ None,
+ tmp.path(),
+ None,
+ &config_path,
+ )
+ .unwrap_err();
+ assert!(format!("{error:#}").contains("unsupported Kiro hook schema version"));
+
+ fs::write(
+ &config_path,
+ r#"{"version":"v1","hooks":[{"name":"ai-memory-stop","trigger":"Stop","action":{"type":"command","command":"third-party"}}]}"#,
+ )
+ .unwrap();
+ let error = merge_kiro_cli_v3_hooks(
+ tmp.path(),
+ "https://memory.example",
+ None,
+ tmp.path(),
+ None,
+ &config_path,
+ )
+ .unwrap_err();
+ assert!(format!("{error:#}").contains("reserved name"));
}
#[test]
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index fde77162..3b139951 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -1156,10 +1156,9 @@ fn render_kiro_cli(args: &InstallMcpArgs) -> Result<String> {
# Kiro accepts HTTPS remote endpoints and plain HTTP only on\n\
# localhost. `?flavor=bedrock` removes unsupported root-level\n\
# schema combinators while handler validation remains unchanged.\n\
- # Lifecycle capture for the documented v2 engine is installed\n\
- # separately with `install-hooks --agent kiro-cli`. Kiro v3 hook\n\
- # capture remains unsupported pending fixture-verified lifecycle\n\
- # and built-in tool payloads for its standalone schema.\n\
+ # Lifecycle capture is installed separately: use\n\
+ # `install-hooks --agent kiro-cli` for v2 or the explicit\n\
+ # `install-hooks --agent kiro-cli-v3` target for v3.\n\
# Managed workstreams are not installed by this command.\n\
{snippet}\n",
snippet = render_json_mcp_fragment(args)?,
@@ -1868,7 +1867,7 @@ mod tests {
assert!(kiro.contains("http://127.0.0.1:49374/mcp?flavor=bedrock"));
assert!(!kiro.contains("\"transport\""));
assert!(kiro.contains("install-hooks --agent kiro-cli"));
- assert!(kiro.contains("Kiro v3 hook"));
+ assert!(kiro.contains("install-hooks --agent kiro-cli-v3"));
let kiro_with_token = render_with_token(McpClient::KiroCli);
assert!(kiro_with_token.contains("\"Authorization\": \"Bearer test-token-deadbeef\""));
// VS Code Copilot must use the `servers` top-level key — the
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 2e462b8e..51f14a31 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -89,10 +89,6 @@ pub(crate) const KIMI_CODE_EVENTS: [(&str, &str); 10] = [
/// the matching `.sh` and `.ps1` files under `hooks/kiro-cli/`; the
/// install-hooks parity test fails if the bundle drifts.
///
-/// Kiro's v3 engine uses a documented standalone registration format, but its
-/// live lifecycle and built-in tool payloads have not been accepted as
-/// fixtures. Do not advertise or install v3 hooks until those exact contracts
-/// are captured and tested.
pub(crate) const KIRO_CLI_V2_EVENTS: [(&str, &str); 5] = [
("agentSpawn", "session-start.sh"),
("userPromptSubmit", "user-prompt-submit.sh"),
@@ -101,6 +97,16 @@ pub(crate) const KIRO_CLI_V2_EVENTS: [(&str, &str); 5] = [
("stop", "stop.sh"),
];
+/// Kiro CLI v3-engine lifecycle events. V3 uses PascalCase triggers in a
+/// standalone versioned hook file rather than v2's camelCase agent field.
+pub(crate) const KIRO_CLI_V3_EVENTS: [(&str, &str); 5] = [
+ ("SessionStart", "session-start.sh"),
+ ("UserPromptSubmit", "user-prompt-submit.sh"),
+ ("PreToolUse", "pre-tool-use.sh"),
+ ("PostToolUse", "post-tool-use.sh"),
+ ("Stop", "stop.sh"),
+];
+
/// Devin lifecycle events ai-memory hooks. Each pair is
/// `(event-name-in-Devin-settings, POSIX hook-script-filename)`.
///
@@ -907,6 +913,47 @@ fn build_kiro_cli_v2_hooks_value_for_platform(
hooks
}
+/// Build Kiro CLI v3's standalone `{ "version": "v1", "hooks": [...] }`
+/// registration document. Each entry is deliberately named so apply and
+/// uninstall can prove ownership using both the name and command signature.
+pub(crate) fn build_kiro_cli_v3_hooks_value(
+ emit_root: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: Option<&Path>,
+ project_strategy: Option<&str>,
+) -> Value {
+ let platform = HookCommandPlatform::current();
+ let hooks = KIRO_CLI_V3_EVENTS
+ .iter()
+ .map(|(trigger, script)| {
+ let platform_script = script_for_platform(script, platform);
+ let command = hook_command(
+ &emit_root.join(platform_script.as_ref()),
+ server_url,
+ auth_token,
+ HookCommandContext::new(platform, "kiro-cli", data_dir, project_strategy),
+ );
+ let name = script.strip_suffix(".sh").map_or_else(
+ || format!("ai-memory-{script}"),
+ |stem| format!("ai-memory-{stem}"),
+ );
+ let timeout = if *trigger == "SessionStart" { 5 } else { 1 };
+ json!({
+ "name": name,
+ "trigger": trigger,
+ "action": {
+ "type": "command",
+ "command": command,
+ },
+ "timeout": timeout,
+ "enabled": true,
+ })
+ })
+ .collect::<Vec<_>>();
+ json!({"version": "v1", "hooks": hooks})
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum HookCommandPlatform {
Posix,
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 8b189f92..9860d3c3 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -38,7 +38,7 @@ use crate::cli::{AgentChoice, SetupAgentArgs};
use crate::commands::install_mcp;
use crate::commands::render_shared::{
ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, COMMAND_CODE_PROFILE,
- CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS,
+ CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_EVENTS,
build_claude_code_payload, build_devin_payload, build_grok_payload,
hook_script_for_current_platform,
};
@@ -153,12 +153,12 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
// script listing is deduplicated below; apply-mode owns the exact
// `[[hooks]]` TOML merge into the user's config.toml.
AgentChoice::KimiCode => emit_other(&emit_root, agent_sub, &args, &[&KIMI_CODE_EVENTS]),
- // Kiro v2 embeds its lifecycle hooks in agent configs. Kiro v3 is
- // withheld until its live lifecycle and built-in tool payloads are
- // captured in fixtures.
AgentChoice::KiroCli => {
emit_other(&emit_root, agent_sub, &args, &[&KIRO_CLI_V2_EVENTS]);
}
+ AgentChoice::KiroCliV3 => {
+ emit_other(&emit_root, agent_sub, &args, &[&KIRO_CLI_V3_EVENTS]);
+ }
AgentChoice::OpenCode
| AgentChoice::Pi
| AgentChoice::Omp
@@ -714,4 +714,17 @@ mod tests {
assert_eq!(KIRO_CLI_V2_EVENTS.len(), 5);
assert_eq!(v2_paths.len(), 5);
}
+
+ #[test]
+ fn kiro_cli_manual_script_paths_cover_v3_event_set() {
+ let root = Path::new("/hooks/kiro-cli");
+ let paths = event_script_paths(root, &[&KIRO_CLI_V3_EVENTS]);
+ assert_eq!(KIRO_CLI_V3_EVENTS.len(), 5);
+ assert_eq!(paths.len(), 5);
+ assert_eq!(
+ paths,
+ event_script_paths(root, &[&KIRO_CLI_V2_EVENTS]),
+ "v2 and v3 use different trigger names but the same bounded script bundle"
+ );
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 6284b997..6b47dc5c 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -44,6 +44,8 @@ enum RewriteOp {
KimiCodeHooksToml,
/// Kiro CLI v2 agent-config hooks with exact generated command signatures.
KiroCliV2HooksJson,
+ /// Kiro CLI v3 standalone hooks with exact generated names and commands.
+ KiroCliV3HooksJson,
/// MCP JSON config for one client shape.
McpJson(McpClient),
/// Codex TOML MCP config.
@@ -67,6 +69,7 @@ enum DeleteKind {
OpenClawPackageJson,
OpenClawManifest,
OpenClawEntrypoint,
+ KiroCliV3Hooks,
ManagedSkill,
}
@@ -79,6 +82,7 @@ impl DeleteKind {
Self::OpenClawPackageJson => "OpenClaw package manifest",
Self::OpenClawManifest => "OpenClaw plugin manifest",
Self::OpenClawEntrypoint => "OpenClaw plugin entrypoint",
+ Self::KiroCliV3Hooks => "Kiro CLI v3 hook file",
Self::ManagedSkill => "managed Agent Skill",
}
}
@@ -225,6 +229,29 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {
);
}
+ let mut kiro_v3_paths = vec![install_hooks::kiro_cli_v3_hooks_path()?];
+ kiro_v3_paths.push(cwd.join(".kiro/hooks/ai-memory.json"));
+ kiro_v3_paths.sort();
+ kiro_v3_paths.dedup();
+ for path in kiro_v3_paths {
+ if !path.exists() {
+ continue;
+ }
+ if generated_file_is_ours(&path, DeleteKind::KiroCliV3Hooks) {
+ push_generated_delete(&mut plan, path, DeleteKind::KiroCliV3Hooks);
+ continue;
+ }
+ let content = std::fs::read_to_string(&path)
+ .with_context(|| format!("reading {}", path.display()))?;
+ let removal = strip_kiro_cli_v3_hooks(&content)?;
+ push_rewrite(
+ &mut plan,
+ path,
+ removal.removed_events,
+ RewriteOp::KiroCliV3HooksJson,
+ );
+ }
+
let antigravity = install_hooks::antigravity_hooks_path()?;
if antigravity.exists() {
let content = std::fs::read_to_string(&antigravity)
@@ -498,6 +525,7 @@ fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhow
RewriteOp::ZeroHooksJson => strip_zero_hooks(&out)?.new_content,
RewriteOp::KimiCodeHooksToml => strip_kimi_code_hooks(&out)?.new_content,
RewriteOp::KiroCliV2HooksJson => strip_kiro_cli_v2_hooks(&out)?.new_content,
+ RewriteOp::KiroCliV3HooksJson => strip_kiro_cli_v3_hooks(&out)?.new_content,
RewriteOp::McpJson(client) => {
strip_mcp_json_client(&out, client, name, url)?.0
}
@@ -843,6 +871,34 @@ fn strip_kiro_cli_v2_hooks(content: &str) -> Result<HookRemoval> {
})
}
+fn strip_kiro_cli_v3_hooks(content: &str) -> Result<HookRemoval> {
+ let mut removed_events = Vec::new();
+ let new_content = mutate_json(content, |root| {
+ let Some(hooks) = root
+ .get_mut("hooks")
+ .and_then(serde_json::Value::as_array_mut)
+ else {
+ return Ok(());
+ };
+ hooks.retain(|entry| {
+ if !install_hooks::is_ai_memory_kiro_v3_hook_entry(entry) {
+ return true;
+ }
+ let label = entry
+ .get("trigger")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or("unknown");
+ removed_events.push(format!("kiro-cli-v3.{label}"));
+ false
+ });
+ Ok(())
+ })?;
+ Ok(HookRemoval {
+ new_content,
+ removed_events,
+ })
+}
+
/// Remove ai-memory hook entries from Devin's `hooks.v1.json`, whose root
/// object is the hook-event map. This is intentionally separate from
/// `strip_ai_memory_hooks` so we never infer a flat shape for other agents.
@@ -991,6 +1047,22 @@ fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {
.and_then(|additional| additional.as_bool())
== Some(false)
}),
+ DeleteKind::KiroCliV3Hooks => serde_json::from_str::<serde_json::Value>(&content)
+ .ok()
+ .and_then(|value| value.as_object().cloned())
+ .is_some_and(|root| {
+ root.len() == 2
+ && root.get("version").and_then(serde_json::Value::as_str) == Some("v1")
+ && root
+ .get("hooks")
+ .and_then(serde_json::Value::as_array)
+ .is_some_and(|hooks| {
+ !hooks.is_empty()
+ && hooks
+ .iter()
+ .all(install_hooks::is_ai_memory_kiro_v3_hook_entry)
+ })
+ }),
DeleteKind::ManagedSkill => content.contains(MANAGED_MARKER),
}
}
@@ -2127,6 +2199,48 @@ command = "'/usr/local/bin/ai-memory' hook --event stop --agent kimi-code --serv
assert!(value["mcpServers"].get("other").is_some());
}
+ #[test]
+ fn kiro_v3_uninstall_ownership_requires_exact_name_trigger_and_command() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let path = tmp.path().join("ai-memory.json");
+ let command = "'/usr/bin/ai-memory' hook --event session-start --agent kiro-cli --server-url https://memory.example";
+ std::fs::write(
+ &path,
+ serde_json::to_string(&serde_json::json!({
+ "version": "v1",
+ "hooks": [{
+ "name": "ai-memory-session-start",
+ "trigger": "SessionStart",
+ "action": {"type": "command", "command": command}
+ }]
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ assert!(generated_file_is_ours(&path, DeleteKind::KiroCliV3Hooks));
+
+ let shared = serde_json::json!({
+ "version": "v1",
+ "hooks": [
+ {
+ "name": "ai-memory-session-start",
+ "trigger": "SessionStart",
+ "action": {"type": "command", "command": command}
+ },
+ {
+ "name": "audit",
+ "trigger": "PreToolUse",
+ "action": {"type": "command", "command": "audit-tool"}
+ }
+ ]
+ });
+ let removal = strip_kiro_cli_v3_hooks(&serde_json::to_string(&shared).unwrap()).unwrap();
+ assert_eq!(removal.removed_events, ["kiro-cli-v3.SessionStart"]);
+ let after: serde_json::Value = serde_json::from_str(&removal.new_content).unwrap();
+ assert_eq!(after["hooks"].as_array().unwrap().len(), 1);
+ assert_eq!(after["hooks"][0]["name"], "audit");
+ }
+
/// The plan matched the flavored Kimi Code entry but apply dispatched
/// the unflavored stripper — the CLI reported success and left the
/// entry behind. Drive `apply_change` with the exact URL install-mcp
diff --git a/crates/ai-memory-cli/tests/fixtures/kiro-v3-hook-payloads.json b/crates/ai-memory-cli/tests/fixtures/kiro-v3-hook-payloads.json
new file mode 100644
index 00000000..a2ed872b
--- /dev/null
+++ b/crates/ai-memory-cli/tests/fixtures/kiro-v3-hook-payloads.json
@@ -0,0 +1,59 @@
+{
+ "source": "Sanitized payloads captured from an interactive Kiro CLI 2.16.2 --v3 session on 2026-08-07.",
+ "events": [
+ {
+ "event": "session-start",
+ "payload": {
+ "hook_event_name": "SessionStart",
+ "cwd": "/workspace/project",
+ "session_id": "kiro-v3-session"
+ }
+ },
+ {
+ "event": "user-prompt-submit",
+ "payload": {
+ "hook_event_name": "UserPromptSubmit",
+ "cwd": "/workspace/project",
+ "session_id": "kiro-v3-session",
+ "prompt": "Inspect the project"
+ }
+ },
+ {
+ "event": "pre-tool-use",
+ "payload": {
+ "hook_event_name": "PreToolUse",
+ "cwd": "/workspace/project",
+ "session_id": "kiro-v3-session",
+ "tool_name": "read_file",
+ "tool_input": {
+ "path": "/workspace/project/sample.txt",
+ "offset": null,
+ "limit": null
+ }
+ }
+ },
+ {
+ "event": "post-tool-use",
+ "payload": {
+ "hook_event_name": "PostToolUse",
+ "cwd": "/workspace/project",
+ "session_id": "kiro-v3-session",
+ "tool_name": "read_file",
+ "tool_input": {
+ "path": "/workspace/project/sample.txt",
+ "offset": null,
+ "limit": null
+ },
+ "tool_response": "sanitized fixture content"
+ }
+ },
+ {
+ "event": "stop",
+ "payload": {
+ "hook_event_name": "Stop",
+ "cwd": "/workspace/project",
+ "session_id": "kiro-v3-session"
+ }
+ }
+ ]
+}
diff --git a/crates/ai-memory-cli/tests/removal.rs b/crates/ai-memory-cli/tests/removal.rs
index e1e8aace..efa9b57d 100644
--- a/crates/ai-memory-cli/tests/removal.rs
+++ b/crates/ai-memory-cli/tests/removal.rs
@@ -1088,7 +1088,7 @@ command = "'/usr/local/bin/ai-memory' hook --event stop --agent kimi-code --serv
}
#[test]
-fn uninstall_kiro_cli_hooks_preserves_user_and_v3_entries() {
+fn uninstall_kiro_cli_hooks_removes_v2_and_v3_entries_but_preserves_user_hooks() {
let _guard = cli_test_lock();
let project = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
@@ -1123,8 +1123,7 @@ fn uninstall_kiro_cli_hooks_preserves_user_and_v3_entries() {
r#"{"name":"local","hooks":{"stop":[{"command":"/x/hooks/kiro-cli/stop.sh"}]}}"#,
);
- // v3 remains unsupported without accepted live payload fixtures.
- // Uninstall must leave even an ai-memory-looking standalone file untouched.
+ // v3 standalone surface: one ai-memory hook next to a third-party hook.
let hooks_dir = kiro.join("hooks");
std::fs::create_dir_all(&hooks_dir).unwrap();
let v3_file = hooks_dir.join("ai-memory.json");
@@ -1134,7 +1133,7 @@ fn uninstall_kiro_cli_hooks_preserves_user_and_v3_entries() {
"version": "v1",
"hooks": [
{"name": "ai-memory-session-start", "trigger": "SessionStart",
- "action": {"type": "command", "command": "/x/kiro-cli/session-start.sh"}, "timeout": 10},
+ "action": {"type": "command", "command": "/x/hooks/kiro-cli/session-start.sh"}, "timeout": 10},
{"name": "lint-on-save", "trigger": "PostFileSave", "matcher": "\\.rs$",
"action": {"type": "command", "command": "cargo fmt"}}
]
@@ -1171,12 +1170,15 @@ fn uninstall_kiro_cli_hooks_preserves_user_and_v3_entries() {
"project-local ai-memory hooks must also be removed"
);
- assert!(
- std::fs::read_to_string(&v3_file)
- .unwrap()
- .contains("ai-memory-session-start"),
- "unsupported v3 hook files must remain untouched"
+ let v3_after: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&v3_file).unwrap()).unwrap();
+ let v3_hooks = v3_after["hooks"].as_array().unwrap();
+ assert_eq!(
+ v3_hooks.len(),
+ 1,
+ "only the exact ai-memory v3 hook is removed"
);
+ assert_eq!(v3_hooks[0]["name"], "lint-on-save");
assert_eq!(
std::fs::read_to_string(&third_party_file).unwrap(),
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 9709b5fb..5e3a3757 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -138,7 +138,7 @@ pub(crate) fn tool_observation_metadata(
object.get("tool")?.as_str()?,
object.get("callID").and_then(Value::as_str),
),
- // Kiro v2 tool hooks use `tool_name` + `tool_input`. Unknown payload
+ // Kiro v2/v3 tool hooks use `tool_name` + `tool_input`. Unknown payload
// shapes fail safe to metadata-only under an active policy.
AgentKind::KiroCli => (object.get("tool_name")?.as_str()?, None),
AgentKind::AntigravityCli => (object.get("toolCall")?.get("name")?.as_str()?, None),
@@ -656,7 +656,7 @@ fn extract_paths(name: &str, args: &Value) -> Option<Vec<String>> {
paths.extend(paths_in_entry);
}
}
- if name.eq_ignore_ascii_case("fs_read")
+ if matches!(name.to_ascii_lowercase().as_str(), "read" | "fs_read")
&& let Some(operations) = object.get("operations")
{
let entries = operations.as_array()?;
@@ -1118,6 +1118,74 @@ mod tests {
}
}
+ #[test]
+ fn kiro_v3_documented_and_live_tool_shapes_honor_exclusions_and_fail_closed() {
+ let policy = CapturePolicy::resolve(
+ CaptureSource::Parsed(&CaptureConfig {
+ ignore_paths: vec!["secret/**".into()],
+ }),
+ "/repo",
+ None,
+ );
+ let official_read = json!({
+ "session_id": "kiro-session",
+ "cwd": "/repo",
+ "tool_name": "read",
+ "tool_input": {
+ "operations": [
+ {"mode": "Line", "path": "src/lib.rs"},
+ {"mode": "Line", "path": "secret/token.txt"}
+ ]
+ }
+ });
+ let decision = policy.inspect(AgentKind::KiroCli, &official_read, "/repo");
+ assert_eq!(decision.protocol().tool_family(), ToolFamily::File);
+ assert_eq!(decision.protocol().path_count(), 2);
+ assert_eq!(decision.protocol().disposition(), CaptureDisposition::Drop);
+
+ let live_read = json!({
+ "hook_event_name": "PreToolUse",
+ "session_id": "kiro-session",
+ "cwd": "/repo",
+ "tool_name": "read_file",
+ "tool_input": {
+ "path": "secret/token.txt",
+ "offset": null,
+ "limit": null
+ }
+ });
+ let decision = policy.inspect(AgentKind::KiroCli, &live_read, "/repo");
+ assert_eq!(decision.protocol().tool_family(), ToolFamily::File);
+ assert_eq!(decision.protocol().path_count(), 1);
+ assert_eq!(decision.protocol().disposition(), CaptureDisposition::Drop);
+
+ let mut official_post = official_read.clone();
+ official_post.as_object_mut().unwrap().insert(
+ "tool_response".to_string(),
+ json!({"success": true, "result": ["sanitized"]}),
+ );
+ assert_eq!(
+ tool_observation_outcome(AgentKind::KiroCli, &official_post),
+ ToolOutcome::Success
+ );
+
+ let unknown_shape = json!({
+ "session_id": "kiro-session",
+ "cwd": "/repo",
+ "tool_name": "read",
+ "tool_input": {"files": ["secret/token.txt"]}
+ });
+ let decision = policy.inspect(AgentKind::KiroCli, &unknown_shape, "/repo");
+ assert_eq!(
+ decision.protocol().extraction_state(),
+ ExtractionState::MissingOrMalformed
+ );
+ assert_eq!(
+ decision.protocol().disposition(),
+ CaptureDisposition::MetadataOnly
+ );
+ }
+
#[test]
fn antigravity_native_tools_are_no_longer_unknown() {
for (tool, expected) in [
diff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
index 07fd94cf..780b8320 100644
--- a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
@@ -18,8 +18,8 @@
{"agent":"gemini-cli","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},
{"agent":"devin","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},
{"agent":"kiro-cli","payload":{"tool_name":"fs_write","tool_input":{"command":"create","path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},
- {"agent":"kiro-cli","payload":{"tool_name":"fs_read","tool_input":{"operations":[{"mode":"Line","path":"public"},{"mode":"Line","path":"secret/a"}]}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":2},
- {"agent":"kiro-cli","payload":{"tool_name":"fs_read","tool_input":{"operations":[]}},"disposition":"metadata-only","tool_family":"file","extraction_state":"missing-or-malformed","path_count":0},
+ {"agent":"kiro-cli","payload":{"tool_name":"read","tool_input":{"operations":[{"mode":"Line","path":"public"},{"mode":"Line","path":"secret/a"}]}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":2},
+ {"agent":"kiro-cli","payload":{"tool_name":"read","tool_input":{"operations":[]}},"disposition":"metadata-only","tool_family":"file","extraction_state":"missing-or-malformed","path_count":0},
{"agent":"kiro-cli","payload":{"tool_name":"execute_bash","tool_input":{"command":"cat secret/a"}},"disposition":"keep","tool_family":"non-file","extraction_state":"extracted","path_count":0},
{"agent":"grok","payload":{"toolName":"Edit","toolInput":{"filePath":"secret/a"},"callID":"safe-1"},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},
{"agent":"zero","payload":{"toolName":"Edit","input":{"path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},
diff --git a/docs/install.md b/docs/install.md
index 2ba7aab1..50cf952e 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -792,11 +792,10 @@ unchanged.
### Kiro CLI
-Kiro CLI has one MCP surface. ai-memory supports the documented v2 lifecycle
-hook surface. Kiro v3 now documents its incompatible standalone registration
-schema and generic command context, but ai-memory does not install it without
-sanitized live lifecycle and built-in tool payload fixtures. The global MCP
-file is `$KIRO_HOME/settings/mcp.json`, defaulting to
+Kiro CLI has one MCP surface and two incompatible lifecycle-hook formats.
+ai-memory supports both through explicit installer targets: `kiro-cli` remains
+the v2 target, while `kiro-cli-v3` selects the standalone v3 registration. The
+global MCP file is `$KIRO_HOME/settings/mcp.json`, defaulting to
`~/.kiro/settings/mcp.json`; pass `--config-file .kiro/settings/mcp.json` for a
project-scoped entry.
@@ -842,6 +841,30 @@ through successful `agentSpawn` stdout. Verified v2 tool payloads enforce
`[capture] ignore_paths`; an unrecognized payload shape is stored as bounded
metadata rather than exposing file content.
+Install v3 hooks with the explicit `kiro-cli-v3` target. This distinction is
+intentional: `kiro` and `kiro-cli` continue to mean v2 so an upgrade cannot
+silently rewrite an existing installation into an incompatible format. The
+standalone registration was acceptance-tested with an interactive Kiro CLI
+2.16.2 `--v3` session.
+
+```bash
+# Global v3 registration under $KIRO_HOME/hooks (default ~/.kiro/hooks).
+ai-memory install-hooks --agent kiro-cli-v3 --apply
+
+# Project-local v3 registration.
+ai-memory install-hooks --agent kiro-cli-v3 --apply \
+ --config-file .kiro/hooks/ai-memory.json
+```
+
+The v3 installer writes the documented standalone `version: "v1"` schema with
+PascalCase triggers. It preserves third-party entries in a shared file,
+refuses an unsupported schema version or a third-party collision with an
+ai-memory-reserved hook name, and bounds capture-only commands to one second.
+SessionStart gets five seconds so ai-memory's bounded handoff fetch can finish.
+Both engines use the same sanitized hook-ingress boundary: documented and live
+`tool_name`/`tool_input` file operations honor `[capture] ignore_paths`, while
+unknown file-tool payload shapes degrade to metadata-only capture.
+
Kiro v2's `stop` event ends a turn, not the session. After the final turn, close
the matching session explicitly; use the exact id when several Kiro sessions
are open in the same project:
@@ -851,24 +874,17 @@ ai-memory finalize-session --agent kiro-cli
ai-memory finalize-session --agent kiro-cli --session-id <uuid>
```
-Kiro v3 hook capture is intentionally not advertised or installed. Its
-[migration guide](https://kiro.dev/docs/cli/v3/hooks-migration/) documents the
-standalone registration schema, and the
-[shared hook reference](https://kiro.dev/docs/hooks/types/) documents generic
-command context plus `agentSpawn` and MCP tool examples. It does not yet
-establish the exact built-in file and shell tool payloads, and ai-memory has no
-sanitized live fixtures covering the complete v3 lifecycle. Supporting it
-without that evidence would risk silently losing capture and exclusion
-semantics. Add v3 only after real payload fixtures can exercise that boundary.
-
-`ai-memory uninstall --only hooks --apply --yes` removes only exact ai-memory v2
-entries from global agents and the current project's `.kiro/agents` directory;
-it leaves standalone v3 files untouched. Explicit `ai-memory run kiro` (alias
-`kiro-cli`) manages the default v2 engine and honors `$KIRO_HOME`; Kiro stays
+`ai-memory uninstall --only hooks --apply --yes` removes only exact ai-memory
+entries from global v2 agents, the current project's `.kiro/agents` directory,
+and ai-memory's global/current-project v3 registration. A purely generated v3
+file is deleted; third-party entries in a shared file remain. Explicit
+`ai-memory run kiro` (alias `kiro-cli`) still manages the default v2 engine and
+honors `$KIRO_HOME`; Kiro stays
outside no-argument automatic selection until its current event stream is
validated in a logged-in real-harness acceptance run. `--v3`, `--mode`, and
non-v2 `--agent-engine` invocations pass through without managed session
-injection. See [managed workstreams](managed-workstreams.md#native-adapter-behavior).
+injection; issue #356 tracks v3 managed-workstream support. See
+[managed workstreams](managed-workstreams.md#native-adapter-behavior).
### OpenCode
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index a5d1cc57..38f27cbd 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -888,7 +888,8 @@ Kiro permits remote MCP URLs over HTTPS. Plain HTTP is accepted only for
non-loopback HTTP URL before writing the config. See
[HTTPS via reverse proxy](https-via-proxy.md) for a homelab deployment.
-ai-memory supports Kiro's documented v2 hook registration format:
+ai-memory supports both documented Kiro hook registration formats through
+explicit engine targets:
```bash
# v2: update every existing global agent definition.
@@ -897,19 +898,27 @@ ai-memory install-hooks --agent kiro-cli --apply
# v2 project-local agent: target the active definition explicitly.
ai-memory install-hooks --agent kiro-cli --apply \
--config-file .kiro/agents/<agent-name>.json
+
+# v3: standalone global registration.
+ai-memory install-hooks --agent kiro-cli-v3 --apply
+
+# v3 project-local registration.
+ai-memory install-hooks --agent kiro-cli-v3 --apply \
+ --config-file .kiro/hooks/ai-memory.json
```
+The standalone format was acceptance-tested with an interactive Kiro CLI
+2.16.2 `--v3` session.
+
The v2 installer refuses to create a synthetic agent file and parses every
target before changing any of them. Project-local Kiro agents override global
agents, so `--config-file` is required when the active definition lives under
`.kiro/agents/`. The integration remains fail-open, injects pending handoffs
-through `agentSpawn` stdout, and honors `$KIRO_HOME`. Kiro v3 hook capture is
-not installed: its standalone schema and generic command context are now
-documented, but sanitized live lifecycle and built-in tool payload fixtures are
-still needed to validate capture, exclusions, and fail-open behavior. Follow
-[#355](https://github.com/akitaonrails/ai-memory/issues/355) for v3 hook support
-and [#356](https://github.com/akitaonrails/ai-memory/issues/356) for automatic
-selection and broader version-aware managed support. Explicit
+through `agentSpawn` stdout, and honors `$KIRO_HOME`. The v3 installer writes
+the standalone `v1` file with PascalCase triggers, preserves third-party
+entries, and shares the same fail-open sanitizer and capture-exclusion
+boundary. Follow [#356](https://github.com/akitaonrails/ai-memory/issues/356)
+for automatic selection and version-aware managed support. Explicit
`ai-memory run kiro` (alias `kiro-cli`) manages the default v2 engine;
non-v2 engine selections pass through without session injection or import.
diff --git a/docs/usage.md b/docs/usage.md
index ec4d9399..e921ec83 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -306,9 +306,9 @@ Client cleanup hints:
- Kimi Code: check `~/.kimi-code/mcp.json` and the `[[hooks]]` entries in
`~/.kimi-code/config.toml` (both under `$KIMI_CODE_HOME` when set) for stale
MCP or hook entries.
-- Kiro CLI: check the `hooks` objects inside `~/.kiro/agents/*.json` (v2
- engine) and `~/.kiro/settings/mcp.json` (both under `$KIRO_HOME` when set)
- for stale ai-memory entries. ai-memory does not install Kiro v3 hook files.
+- Kiro CLI: check the `hooks` objects inside `~/.kiro/agents/*.json` (v2),
+ `~/.kiro/hooks/ai-memory.json` (v3), and `~/.kiro/settings/mcp.json` (all
+ under `$KIRO_HOME` when set) for stale ai-memory entries.
- OpenCode, OpenClaw, and OMP: check MCP config and plugin/extension directories;
move old memory plugins to a disabled/quarantine directory before deleting.
- VS Code Copilot, Claude Desktop, and Zed: these are MCP-only, so confirm