Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(agents): add version-aware Kiro CLI lifecycle hooks
Samir Hanna Verza24d9a00caf14
diff --git a/AGENTS.md b/AGENTS.mdindex 6785f7ee..19ff5bb3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -37,7 +37,7 @@ install or refresh work.If you're about to write a durable project rule ("always X", "neverY", "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,+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI,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@@ -54,7 +54,7 @@ latest binary's recommended copy:- **From the agent** (no terminal needed): ask "refresh the ai-memoryrouting 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 -> `AGENTS.md`),+ OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI -> `AGENTS.md`),uses its Write / Edit tool to replace or append the returned`markered_block` while preservingnon-ai-memory user content, then writes or updates each returneddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5250259b..32eb9d0e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Version-aware lifecycle hooks for the AWS Kiro CLI (#355). The two agent+ engines of the same binary use incompatible hook surfaces, so each is+ selected explicitly and never guessed: `install-hooks --agent kiro-cli`+ merges five flat camelCase entries (`agentSpawn`, `userPromptSubmit`,+ `preToolUse`, `postToolUse`, `stop`) into every existing v2 agent config+ under `~/.kiro/agents/` (the v2 engine has no global hook surface and the+ built-in default agent has no file on disk), while+ `install-hooks --agent kiro-cli-v3` writes the standalone versioned hooks+ file `~/.kiro/hooks/ai-memory.json` with PascalCase triggers for the+ early-access v3 engine. Both honor `$KIRO_HOME`, share one+ `hooks/kiro-cli/` script bundle, preserve third-party hook entries on+ re-apply and uninstall, and keep capture fail-open (always exit 0; no+ stdout on capture paths, because exit code 2 blocks the tool call and+ session-start/user-prompt stdout is injected into the agent context).+ Handoffs inject through session-start stdout on both engines (v2+ `agentSpawn`, v3 `SessionStart`), raw and unenveloped per the official+ contracts; the native `ai-memory hook` command suppresses its `{}`+ protocol line for `kiro-cli` for the same reason. Tool payloads+ (`tool_name`/`tool_input`, `tool_response.success`) join the capture+ policy with fixture vectors, including Kiro's `fs_read` batched+ `operations` path extraction; the v3 stdin payload shape is not publicly+ documented and stays conservative. Contracts verified against kiro-cli+ 2.16.0 and kiro.dev's v2/v3 hook references; docs cover both engines,+ MCP setup, and the v2/v3 session id-space split.+- `?flavor=bedrock` marker on the MCP URL, an alias of the existing+ Moonshot root-schema flattening: Amazon Bedrock's Converse API (used by+ the Kiro CLI) rejects root-level `anyOf`/`oneOf`/`allOf` in tool+ schemas, so a Kiro `~/.kiro/settings/mcp.json` pointing at+ `…/mcp?flavor=bedrock` gets the same tools with flattened root schemas+ (#351).+## [1.18.0] - 2026-07-23### Addeddiff --git a/README.md b/README.mdindex 7d8275dd..3401352d 100644--- a/README.md+++ b/README.md@@ -38,6 +38,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 handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. 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 | Hooks (engine-aware) | Lifecycle hooks for both agent engines of the AWS Kiro CLI, selected explicitly because their hook surfaces are incompatible: `install-hooks --agent kiro-cli` merges camelCase hook entries into every existing v2 agent config (`~/.kiro/agents/*.json`; the v2 engine has no global hook surface), and `install-hooks --agent kiro-cli-v3` writes the standalone versioned hooks file `~/.kiro/hooks/ai-memory.json` for the early-access v3 engine. Both honor `$KIRO_HOME` and share one script bundle. Handoffs inject via session-start stdout on both engines (v2 `agentSpawn`, v3 `SessionStart`). MCP: configure `~/.kiro/settings/mcp.json` manually (see docs/install.md). || VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). || Hermes Agent | Community | A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available. It is not part of ai-memory's first-party install surface; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. || LLM/auth providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, OpenCode Zen/Go, OpenAI-compatible endpoints, and generic OIDC device auth for native hooks. |@@ -110,7 +111,8 @@ priors are at the [bottom](#influences-and-prior-art).mode. Mounted on the same axum server as MCP.- **Multi-agent + multi-machine ready.** Supported clients: ClaudeCode, Codex, Devin CLI, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),- Gemini CLI, Antigravity CLI, Grok Build CLI, Kimi Code, OpenClaw, Oh My Pi+ Gemini CLI, Antigravity CLI, Grok Build CLI, Kimi Code, Kiro CLI+ (hooks for both agent engines), OpenClaw, Oh My Pi/ OMP (`omp` / `oh-my-pi`), Pi via generated bridge extension, and VS CodeGitHub Copilot agent mode(MCP-only, workspace `.vscode/mcp.json`).@@ -312,7 +314,8 @@ 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 grok`, `--agent kimi-code`, `--agent omp`, `--agent oh-my-pi`, `--client cursor`,+# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli` (or `kiro-cli-v3`),+# `--agent omp`, `--agent oh-my-pi`, `--client cursor`,# `--client gemini-cli`, `--client grok`, etc.# for additional agents; full list in docs/install.md.ai-memory install-mcp --client claude-code --applydiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 10ba9150..8412be02 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -931,6 +931,18 @@ pub enum AgentChoice {/// Kimi Code CLI (Moonshot AI).#[value(alias = "kimi")]KimiCode,+ /// Kiro CLI (AWS), default v2 agent engine — camelCase lifecycle hooks+ /// embedded in agent configs under `~/.kiro/agents/*.json`. The v2 and+ /// v3 engines of the same binary use incompatible hook surfaces, so+ /// each is selected explicitly; use `kiro-cli-v3` for the v3 engine.+ #[value(alias = "kiro")]+ KiroCli,+ /// Kiro CLI (AWS), early-access v3 agent engine (`kiro-cli --v3`) —+ /// PascalCase triggers in a standalone versioned hooks file at+ /// `~/.kiro/hooks/ai-memory.json`. Select explicitly; the v2 engine+ /// ignores this surface and vice versa.+ #[value(name = "kiro-cli-v3", alias = "kiro-v3")]+ KiroCliV3,}impl AgentChoice {@@ -956,6 +968,9 @@ impl AgentChoice {Self::Zero => AgentKind::Zero,Self::Devin => AgentKind::Devin,Self::KimiCode => AgentKind::KimiCode,+ // Both Kiro engine surfaces are the same product and session+ // identity; only the installed hook surface differs.+ Self::KiroCli | Self::KiroCliV3 => AgentKind::KiroCli,}}diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 86e925ec..5b335c9b 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -393,13 +393,24 @@ whereW: std::io::Write,S: FnOnce(&Path) -> std::io::Result<()>,{+ // Kiro CLI adds exit-0 stdout of its session-start and user-prompt+ // hooks to the agent context verbatim (v2 agentSpawn / v3+ // SessionStart + both engines' UserPromptSubmit, per the official+ // hook contracts), and its v2 stop hook parses stdout for a+ // {"decision":"block"} verdict. The Claude-style `{}` protocol+ // output would therefore leak into the conversation as literal+ // text, so for Kiro the hook prints nothing at all except an+ // actually-fetched session-start handoff.+ let inert_stdout = !matches!(AgentKind::from_wire(&args.agent), AgentKind::KiroCli);let (mut payload, mut json) = match parse_hook_payload(payload) {Ok(parsed) => parsed,Err(_) => {eprintln!("ai-memory hook warning: could not parse event payload as JSON; nothing was captured");- writeln!(stdout, "{{}}")?;+ if inert_stdout {+ writeln!(stdout, "{{}}")?;+ }return Ok(());}};@@ -452,7 +463,9 @@ whereif let Some(decision) = decision {match decision.protocol().disposition() {CaptureDisposition::Drop => {- writeln!(stdout, "{{}}")?;+ if inert_stdout {+ writeln!(stdout, "{{}}")?;+ }return Ok(());}CaptureDisposition::MetadataOnly => {@@ -582,13 +595,19 @@ whereif let Some(handoff) =get_handoff(&client, &handoff_url, bearer.as_deref(), handoff_timeout()).await{- let envelope = serde_json::json!({- "hookSpecificOutput": {- "hookEventName": "SessionStart",- "additionalContext": handoff,- }- });- writeln!(stdout, "{envelope}")?;+ if inert_stdout {+ let envelope = serde_json::json!({+ "hookSpecificOutput": {+ "hookEventName": "SessionStart",+ "additionalContext": handoff,+ }+ });+ writeln!(stdout, "{envelope}")?;+ } else {+ // Kiro adds this stdout to the agent context verbatim+ // and documents no envelope, so print the raw handoff.+ writeln!(stdout, "{handoff}")?;+ }return Ok(());}}@@ -681,7 +700,9 @@ where);}- writeln!(stdout, "{{}}")?;+ if inert_stdout {+ writeln!(stdout, "{{}}")?;+ }Ok(())}@@ -1896,6 +1917,129 @@ mod tests {assert!(!second.contains("briefing"), "{second}");}+ fn kiro_hook_args(event: &str, server_url: &str) -> HookArgs {+ HookArgs {+ event: event.into(),+ agent: "kiro-cli".into(),+ server_url: server_url.into(),+ auth_token: None,+ project_strategy: None,+ check_capture: false,+ capture_assistant: false,+ }+ }++ #[tokio::test]+ async fn kiro_session_start_prints_the_raw_handoff_without_an_envelope() {+ // Both Kiro engines add session-start hook stdout to the agent+ // context verbatim (v2 agentSpawn / v3 SessionStart) and document+ // no envelope, so the handoff must be printed raw — a+ // hookSpecificOutput wrapper would inject JSON noise as context.+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let cwd = tmp.path().join("repo");+ std::fs::create_dir(&cwd).unwrap();+ let (base, mut requests) = serve_requests("200 OK", "AMWS-HANDOFF-KIRO").await;++ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir),+ kiro_hook_args("session-start", &base),+ serde_json::json!({+ "hook_event_name": "agentSpawn",+ "session_id": "3f6d1c2a-aaaa-bbbb-cccc-000000000001",+ "cwd": cwd+ })+ .to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();+ assert_eq!(stdout, b"AMWS-HANDOFF-KIRO\n");++ let mut saw_handoff = false;+ while let Some(request) = first_request(&mut requests).await {+ if request.starts_with("GET /handoff") {+ saw_handoff = true;+ assert!(request.contains("agent=kiro-cli"), "{request}");+ assert!(+ request.contains("session_id=3f6d1c2a-aaaa-bbbb-cccc-000000000001"),+ "{request}"+ );+ }+ }+ assert!(saw_handoff, "session-start must fetch the handoff for kiro");+ }++ #[tokio::test]+ async fn kiro_hooks_never_print_the_empty_object() {+ // Kiro injects exit-0 stdout of session-start and user-prompt+ // hooks into the agent context verbatim, and its v2 stop hook+ // parses stdout for a block verdict — so the Claude-style `{}`+ // protocol line must never be emitted for kiro-cli.+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let cwd = tmp.path().join("repo");+ std::fs::create_dir(&cwd).unwrap();+ let (base, mut requests) = serve_requests("404 Not Found", "").await;+ let payload = serde_json::json!({+ "session_id": "3f6d1c2a-aaaa-bbbb-cccc-000000000002",+ "cwd": cwd,+ "prompt": "hi"+ })+ .to_string();++ // No pending handoff on session-start → nothing at all on stdout.+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ kiro_hook_args("session-start", &base),+ payload.clone(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();+ assert_eq!(stdout, b"", "empty handoff must print nothing");+ // Drain the requests recorded so far — session-start legitimately+ // fetched the handoff; the assertions below are about user-prompt.+ while first_request(&mut requests).await.is_some() {}++ // user-prompt: session-start owns the injection for kiro, so no+ // handoff fetch happens here and stdout stays empty.+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ kiro_hook_args("user-prompt-submit", &base),+ payload.clone(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();+ assert_eq!(stdout, b"");+ while let Some(request) = first_request(&mut requests).await {+ assert!(!request.starts_with("GET /handoff"), "{request}");+ }++ // stop and an unparseable payload also stay silent (Claude would+ // print `{}` in both cases).+ for (event, body) in [("stop", payload.as_str()), ("stop", "not-json")] {+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ kiro_hook_args(event, &base),+ body.to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();+ assert_eq!(stdout, b"", "{event} must print nothing");+ }+ }+#[tokio::test]async fn kimi_user_prompt_without_briefing_creates_no_marker() {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.rsindex 350da1b1..46e6a781 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -26,11 +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, CURSOR_PROFILE,- GEMINI_PROFILE, KIMI_CODE_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_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,+ 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_kiro_cli_v3_hooks_file, 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};@@ -177,6 +178,41 @@ fn kimi_code_config_path_in(.join("config.toml"))}+/// `$KIRO_HOME/agents` when set, else `~/.kiro/agents`. The Kiro CLI v2+/// engine embeds hooks inside per-agent config JSONs in this directory;+/// there is no global v2 hook surface, and the built-in default agent+/// has no file on disk. `KIRO_HOME` relocation is honored by the real+/// binary (verified against kiro-cli 2.16.0: settings are written under+/// `$KIRO_HOME` when set).+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`. The Kiro CLI v3 engine discovers+/// every standalone hooks file under `~/.kiro/hooks/` in every+/// workspace (global hooks are a v3-only feature), so ai-memory owns a+/// dedicated file and never touches other tools' hook files.+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`).+fn kiro_cli_home_join(+ env_override: Option<std::ffi::OsString>,+ child: &str,+) -> anyhow::Result<std::path::PathBuf> {+ if let Some(dir) = env_override.filter(|value| !value.is_empty()) {+ return Ok(PathBuf::from(dir).join(child));+ }+ Ok(home_dir()+ .context("could not locate $HOME for ~/.kiro")?+ .join(".kiro")+ .join(child))+}+/// Run the `install-hooks` subcommand.////// # Errors@@ -282,6 +318,20 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;apply_to_kimi_code_config(&hooks_dir, &server_url, auth, &config.data_dir, &args)}+ AgentChoice::KiroCli => {+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ apply_to_kiro_cli_agent_configs(+ &hooks_dir,+ &server_url,+ auth,+ &config.data_dir,+ &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.baked();@@ -366,6 +416,14 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;render_kimi_code(&hooks_dir, &server_url, auth, &config.data_dir, strategy)}+ AgentChoice::KiroCli => {+ 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)+ }}}@@ -576,6 +634,10 @@ 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,+ // Kiro CLI's MCP config (~/.kiro/settings/mcp.json) is documented+ // for manual setup only; the installer does not manage it yet, so+ // there is nothing to infer a server URL from.+ AgentChoice::KiroCli | AgentChoice::KiroCliV3 => None,}}@@ -1515,6 +1577,239 @@ fn is_ai_memory_toml_hook_entry(entry: &toml_edit::Table) -> bool {lower.contains("ai-memory") || lower.contains("ai_memory")}+/// Merge ai-memory's camelCase hook entries into every existing Kiro CLI+/// v2 agent config (`~/.kiro/agents/*.json`, or the single file passed+/// via `--config-file`).+///+/// The v2 engine has no global hook surface: hooks fire only for the+/// agent config that is active, so the installer updates each config the+/// user already has. It never invents one — a fabricated agent config+/// would not be the active agent (the built-in default has no file on+/// disk), so hooks in it would never fire and the install would look+/// successful while capturing nothing.+fn apply_to_kiro_cli_agent_configs(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ // Resolve targets before staging anything so a missing-agent-config+ // bail leaves no half-done install behind.+ let targets: Vec<PathBuf> = match &args.config_file {+ Some(p) => {+ 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, or use \+ `--agent kiro-cli-v3` for the v3 engine's standalone hooks file.",+ p.display()+ );+ vec![p.clone()]+ }+ None => list_kiro_cli_agent_configs(&kiro_cli_agents_dir()?)?,+ };+ anyhow::ensure!(+ !targets.is_empty(),+ "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. \+ For the v3 engine use `--agent kiro-cli-v3`, which installs a standalone hooks file \+ and needs no agent config.",+ kiro_cli_agents_dir()?.display()+ );+ let staged = stage_hook_scripts(hooks_dir, "kiro-cli")?;+ let command_dir = staged_command_dir(&staged, "kiro-cli");+ let strategy = args.project_strategy.baked();+ for path in targets {+ let outcome = merge_kiro_cli_agent_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(())+}++/// Merge ai-memory's v2 hook entries into one Kiro agent config,+/// preserving every third-party entry under the same triggers and every+/// non-hook field of the agent definition.+fn merge_kiro_cli_agent_hooks(+ staged: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+ config_path: &Path,+) -> Result<ApplyOutcome> {+ let our_hooks = build_kiro_cli_v2_hooks_value(+ staged,+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ apply_atomic(config_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()+ .with_context(|| {+ format!(+ "`hooks` in {} is present but not an object",+ config_path.display()+ )+ })?;+ for (event, value) in &our_hooks {+ overlay_event_hooks(hooks, event, value);+ }+ Ok(())+ })+ })+}++/// 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.+pub(crate) fn list_kiro_cli_agent_configs(dir: &Path) -> Result<Vec<PathBuf>> {+ let Ok(entries) = fs::read_dir(dir) else {+ return Ok(Vec::new());+ };+ let mut configs: Vec<PathBuf> = entries+ .filter_map(std::result::Result::ok)+ .map(|e| e.path())+ .filter(|p| p.is_file() && p.extension().and_then(|e| e.to_str()) == Some("json"))+ .collect();+ configs.sort();+ Ok(configs)+}++/// Write/refresh ai-memory's standalone Kiro CLI v3 hooks file+/// (`~/.kiro/hooks/ai-memory.json`). The file is ours by name, but a+/// user may still have added entries to it, so reapply preserves any+/// hook entry that is not ai-memory-owned (see+/// [`is_ai_memory_kiro_v3_hook_entry`]). Other `*.json` files in the+/// hooks directory are never touched.+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(p) => p.clone(),+ None => kiro_cli_v3_hooks_path()?,+ };+ let staged = stage_hook_scripts(hooks_dir, "kiro-cli")?;+ let command_dir = staged_command_dir(&staged, "kiro-cli");+ let strategy = args.project_strategy.baked();+ 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(())+}++/// Merge ai-memory's entries into the standalone Kiro v3 hooks file,+/// preserving any non-ai-memory entries a user added to the same file.+fn merge_kiro_cli_v3_hooks(+ staged: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+ path: &Path,+) -> Result<ApplyOutcome> {+ let payload = build_kiro_cli_v3_hooks_file(+ staged,+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ let our_entries = payload+ .get("hooks")+ .and_then(|v| v.as_array())+ .context("internal: build_kiro_cli_v3_hooks_file didn't return a hooks array")?+ .clone();+ apply_atomic(path, |existing| {+ mutate_json(existing, |root| {+ upsert_kiro_cli_v3_hooks(root, &our_entries)+ })+ })+}++/// Insert or refresh ai-memory's entries in a Kiro v3 hooks file value:+/// pin `version: "v1"` (the schema this installer writes), drop prior+/// ai-memory entries, append the fresh set, keep everything else.+fn upsert_kiro_cli_v3_hooks(+ root: &mut serde_json::Map<String, serde_json::Value>,+ our_entries: &[serde_json::Value],+) -> Result<()> {+ 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()+ .context("`hooks` is present in the Kiro v3 hooks file but not an array")?;+ hooks.retain(|entry| !is_ai_memory_kiro_v3_hook_entry(entry));+ hooks.extend(our_entries.iter().cloned());+ Ok(())+}++/// True if a Kiro v3 hook entry belongs to ai-memory: its `name` carries+/// the `ai-memory-` prefix (what this installer writes) or its command+/// action references ai-memory (legacy/hand-edited installs).+fn is_ai_memory_kiro_v3_hook_entry(entry: &serde_json::Value) -> bool {+ if entry+ .get("name")+ .and_then(|n| n.as_str())+ .is_some_and(|n| n.starts_with("ai-memory-"))+ {+ return true;+ }+ entry+ .get("action")+ .and_then(|a| a.get("command"))+ .and_then(|c| c.as_str())+ .is_some_and(|command| {+ let lower = command.to_ascii_lowercase();+ lower.contains("ai-memory") || lower.contains("ai_memory")+ })+}+/// Generate an OpenCode plugin at `~/.config/opencode/plugins/ai-memory.ts`.////// OpenCode's integration surface is a TypeScript plugin, not a JSON@@ -3241,10 +3536,112 @@ fn render_kimi_code(Ok(())}+fn render_kiro_cli(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+) -> Result<()> {+ // Soft check (same rationale as render_claude_code): warn, don't bail,+ // so the docker host-path flow still works.+ for (_, script) in KIRO_CLI_V2_EVENTS {+ let script = hook_script_for_current_platform(script);+ let abs = hooks_dir.join(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 hooks = build_kiro_cli_v2_hooks_value(+ hooks_dir,+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ println!("// Kiro CLI v2-engine hooks — merge the \"hooks\" object into each");+ println!("// agent config under $KIRO_HOME/agents (~/.kiro/agents when unset),");+ 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`). For the");+ println!("// v3 engine use `--agent kiro-cli-v3` instead — the surfaces are");+ println!("// not compatible.");+ 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 agent configs as sensitive (chmod 600).");+ }+ println!();+ println!(+ "{}",+ serde_json::to_string_pretty(&serde_json::json!({ "hooks": hooks }))+ .expect("static hook payload serializes")+ );+ 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 script = hook_script_for_current_platform(script);+ let abs = hooks_dir.join(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_file(+ hooks_dir,+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ println!("// Kiro CLI v3-engine hooks file — write as");+ println!("// $KIRO_HOME/hooks/ai-memory.json (~/.kiro/hooks/ai-memory.json when");+ println!("// unset), or re-run with --apply to write it in place, preserving");+ println!("// non-ai-memory entries a user may have added to the same file.");+ println!("// Global hooks fire in every workspace on the v3 engine only; the");+ println!("// v2 engine ignores this surface — use `--agent kiro-cli` for it.");+ 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 hooks 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::*;use crate::cli::ProjectStrategyArg;+ use crate::commands::render_shared::{+ KIRO_CLI_V2_SESSION_START_MAX_OUTPUT, KIRO_CLI_V3_HOOK_TIMEOUT_SECONDS,+ };use std::collections::BTreeMap;use std::fs;#[cfg(any(unix, windows))]@@ -5331,6 +5728,284 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio}}+ // ----------------------------------------------------------------+ // Kiro CLI tests (v2 agent-config hooks + v3 standalone hooks file)+ // ----------------------------------------------------------------++ const KIRO_CLI_STUB_SCRIPTS: [&str; 5] = [+ "session-start.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "stop.sh",+ ];++ #[test]+ fn kiro_cli_apply_writes_all_v2_events_into_agent_config() {+ 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("dev.json");+ fs::write(+ &config_path,+ r#"{"name": "dev", "description": "my agent", "tools": ["*"]}"#,+ )+ .unwrap();++ let outcome = merge_kiro_cli_agent_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ )+ .unwrap();+ assert_eq!(outcome, ApplyOutcome::Updated);++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // Non-hook agent fields survive the merge.+ assert_eq!(root["name"], "dev");+ assert_eq!(root["tools"][0], "*");+ let hooks = root["hooks"].as_object().expect("hooks object");+ assert_eq!(hooks.len(), KIRO_CLI_V2_EVENTS.len());+ for (event, script) in KIRO_CLI_V2_EVENTS {+ let entries = hooks[event].as_array().expect("event array");+ assert_eq!(entries.len(), 1, "{event}");+ let entry = entries[0].as_object().expect("entry object");+ let command = entry["command"].as_str().unwrap();+ let stem = script.strip_suffix(".sh").unwrap();+ assert!(+ command.contains(stem),+ "{event}: command must reference the staged script: {command}"+ );+ // The v2 Hook schema has no `type` field, and an empty-string+ // matcher would match no tool at all (absent = every tool), so+ // neither key may be written.+ assert!(!entry.contains_key("type"), "{event}: no type key");+ assert!(!entry.contains_key("matcher"), "{event}: no matcher key");+ if event == "agentSpawn" {+ // The handoff + brief must not be truncated mid-injection.+ assert_eq!(+ entry["max_output_size"],+ serde_json::json!(KIRO_CLI_V2_SESSION_START_MAX_OUTPUT)+ );+ } else {+ assert!(!entry.contains_key("max_output_size"), "{event}");+ }+ }+ }++ #[test]+ fn kiro_cli_apply_preserves_third_party_hooks_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("dev.json");+ fs::write(+ &config_path,+ r#"{+ "name": "dev",+ "hooks": {+ "agentSpawn": [+ {"command": "git status"},+ {"command": "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kiro-cli/session-start.sh"}+ ],+ "preToolUse": [+ {"matcher": "execute_bash", "command": "echo audit >> /tmp/audit.log"}+ ]+ }+}"#,+ )+ .unwrap();++ let apply = || {+ merge_kiro_cli_agent_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ )+ };+ assert_eq!(apply().unwrap(), ApplyOutcome::Updated);++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ let spawn = root["hooks"]["agentSpawn"].as_array().unwrap();+ // Third-party entry first (preserved), our refreshed entry after;+ // the stale ai-memory entry is gone.+ assert_eq!(spawn.len(), 2);+ assert_eq!(spawn[0]["command"], "git status");+ let ours = spawn[1]["command"].as_str().unwrap();+ assert!(ours.contains("session-start"), "{ours}");+ assert!(+ !ours.contains("http://old:1"),+ "stale entry replaced: {ours}"+ );+ // A third-party hook under a trigger we also write survives with+ // its matcher intact.+ let pre = root["hooks"]["preToolUse"].as_array().unwrap();+ assert_eq!(pre.len(), 2);+ assert_eq!(pre[0]["matcher"], "execute_bash");++ // Second apply with identical inputs must be a no-op.+ assert_eq!(apply().unwrap(), ApplyOutcome::NoOp);+ }++ #[test]+ fn kiro_cli_paths_honour_kiro_home() {+ let custom = if cfg!(windows) {+ r"C:\custom\kiro"+ } else {+ "/custom/kiro"+ };+ let agents = kiro_cli_home_join(Some(std::ffi::OsString::from(custom)), "agents").unwrap();+ assert_eq!(agents, Path::new(custom).join("agents"));++ // Empty override and unset var both fall back to ~/.kiro.+ for env in [None, Some(std::ffi::OsString::new())] {+ let agents = kiro_cli_home_join(env.clone(), "agents").unwrap();+ assert!(+ agents.ends_with(Path::new(".kiro").join("agents")),+ "default must be ~/.kiro/agents, got {}",+ agents.display()+ );+ let hooks = kiro_cli_home_join(env, "hooks").unwrap();+ assert!(+ hooks.ends_with(Path::new(".kiro").join("hooks")),+ "default must be ~/.kiro/hooks, got {}",+ hooks.display()+ );+ }+ }++ #[test]+ fn kiro_cli_agent_config_listing_is_sorted_json_only() {+ let tmp = TempDir::new().unwrap();+ fs::write(tmp.path().join("b.json"), "{}").unwrap();+ fs::write(tmp.path().join("a.json"), "{}").unwrap();+ fs::write(tmp.path().join("notes.md"), "not an agent").unwrap();+ fs::create_dir(tmp.path().join("sub.json")).unwrap();++ let listed = list_kiro_cli_agent_configs(tmp.path()).unwrap();+ assert_eq!(+ listed,+ vec![tmp.path().join("a.json"), tmp.path().join("b.json")]+ );++ // A missing directory is an empty list, not an error.+ assert!(+ list_kiro_cli_agent_configs(&tmp.path().join("missing"))+ .unwrap()+ .is_empty()+ );+ }++ #[test]+ fn kiro_cli_v3_apply_writes_versioned_hooks_file() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(hooks_tmp.path(), &KIRO_CLI_STUB_SCRIPTS);++ let config_tmp = TempDir::new().unwrap();+ let path = config_tmp.path().join("ai-memory.json");++ let outcome = merge_kiro_cli_v3_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &path,+ )+ .unwrap();+ assert_eq!(outcome, ApplyOutcome::Created);++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&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 (entry, (trigger, script)) in hooks.iter().zip(KIRO_CLI_V3_EVENTS.iter()) {+ assert_eq!(entry["trigger"], *trigger);+ let stem = script.strip_suffix(".sh").unwrap();+ assert_eq!(+ entry["name"],+ serde_json::json!(format!("ai-memory-{stem}"))+ );+ assert_eq!(entry["action"]["type"], "command");+ let command = entry["action"]["command"].as_str().unwrap();+ assert!(command.contains(stem), "{trigger}: {command}");+ // v3 timeout is seconds (v2 uses timeout_ms) — a mixed-up+ // unit would give hooks a 10 ms budget.+ assert_eq!(+ entry["timeout"],+ serde_json::json!(KIRO_CLI_V3_HOOK_TIMEOUT_SECONDS)+ );+ assert!(+ entry.get("matcher").is_none(),+ "{trigger}: no matcher — omitted always fires"+ );+ }+ }++ #[test]+ fn kiro_cli_v3_apply_preserves_user_entries_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 path = config_tmp.path().join("ai-memory.json");+ fs::write(+ &path,+ r#"{+ "version": "v1",+ "hooks": [+ {"name": "lint-on-save", "trigger": "PostFileSave", "matcher": "\\.rs$",+ "action": {"type": "command", "command": "cargo fmt"}},+ {"name": "ai-memory-session-start", "trigger": "SessionStart",+ "action": {"type": "command", "command": "/old/ai-memory/hooks/kiro-cli/session-start.sh"}}+ ]+}"#,+ )+ .unwrap();++ let apply = || {+ merge_kiro_cli_v3_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &path,+ )+ };+ assert_eq!(apply().unwrap(), ApplyOutcome::Updated);++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();+ let hooks = root["hooks"].as_array().unwrap();+ // The user's hook survives in front; our five refreshed entries+ // replace the single stale ai-memory entry.+ assert_eq!(hooks.len(), 1 + KIRO_CLI_V3_EVENTS.len());+ assert_eq!(hooks[0]["name"], "lint-on-save");+ assert_eq!(hooks[1]["name"], "ai-memory-session-start");+ let refreshed = hooks[1]["action"]["command"].as_str().unwrap();+ // The refreshed command replaces the stale path regardless of the+ // platform's command form (native binary or staged script).+ assert!(refreshed.contains("session-start"), "{refreshed}");+ assert!(+ !refreshed.contains("/old/ai-memory"),+ "stale ai-memory entry must be replaced: {refreshed}"+ );++ assert_eq!(apply().unwrap(), ApplyOutcome::NoOp);+ }+// ----------------------------------------------------------------// Devin tests// ----------------------------------------------------------------diff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rsindex 9ac6f509..0c3350fc 100644--- a/crates/ai-memory-cli/src/commands/install_instructions.rs+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs@@ -121,8 +121,8 @@ fn resolve_targets(explicit: Option<&std::path::PathBuf>) -> Result<Vec<std::pateprintln!("note: neither CLAUDE.md nor AGENTS.md exists in {}; \creating CLAUDE.md. If you use Codex / OpenCode / \- Cursor / Gemini CLI / Antigravity CLI / Kimi Code, \- re-run with `--target AGENTS.md`.",+ Cursor / Gemini CLI / Antigravity CLI / Kimi Code / \+ Kiro CLI, re-run with `--target AGENTS.md`.",cwd.display());Ok(vec![claude_md])diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex a655f917..22635f26 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -77,6 +77,47 @@ pub(crate) const KIMI_CODE_EVENTS: [(&str, &str); 10] = [("SubagentStop", "subagent-stop.sh"),];+/// Kiro CLI v2-engine lifecycle events. Each pair is+/// `(trigger-name-in-agent-config, POSIX hook-script-filename)`.+///+/// The v2 engine embeds hooks in agent configs (`~/.kiro/agents/*.json`)+/// keyed by camelCase triggers, per kiro.dev/docs/cli/hooks and the+/// shipping `HookTrigger` serde in aws/amazon-q-developer-cli+/// (`crates/chat-cli/src/cli/agent/hook.rs`). The vocabulary is exactly+/// these five events — there is no PreCompact/SessionEnd/subagent+/// equivalent. Adding a hook event means updating this list AND adding+/// the matching `.sh` and `.ps1` files under `hooks/kiro-cli/`; the+/// install-hooks parity test fails if the bundle drifts.+///+/// The v3 engine of the same binary uses an incompatible standalone+/// hooks file with PascalCase triggers — see [`KIRO_CLI_V3_EVENTS`].+/// Do not mix the two vocabularies.+pub(crate) const KIRO_CLI_V2_EVENTS: [(&str, &str); 5] = [+ ("agentSpawn", "session-start.sh"),+ ("userPromptSubmit", "user-prompt-submit.sh"),+ ("preToolUse", "pre-tool-use.sh"),+ ("postToolUse", "post-tool-use.sh"),+ ("stop", "stop.sh"),+];++/// Kiro CLI v3-engine lifecycle triggers (early access, `kiro-cli --v3`).+/// Each pair is `(PascalCase trigger, POSIX hook-script-filename)`.+///+/// The v3 engine reads standalone versioned hooks files+/// (`.kiro/hooks/*.json` per workspace, `~/.kiro/hooks/*.json` global)+/// per kiro.dev/docs/cli/v3/hooks. v3 also defines task/file/manual+/// triggers (PreTaskExec, PostFileSave, …) that ai-memory does not+/// subscribe to; capture sticks to the shared five-event vocabulary.+/// The same `hooks/kiro-cli/` script bundle serves both engines — only+/// the registration surface differs.+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)`.///@@ -738,6 +779,139 @@ fn kimi_code_hook_commands_for_platform(.collect()}+/// Build the `hooks` map for a Kiro CLI v2-engine agent config. Entry+/// shape per the shipping `Hook` struct (aws/amazon-q-developer-cli+/// `crates/chat-cli/src/cli/agent/hook.rs`): a flat+/// `{ "command": … }` object per trigger. Two deliberate omissions:+///+/// - no `matcher` key: in Kiro v2 an *absent* matcher applies the hook+/// to every tool, while an empty-string matcher is a tool-name+/// pattern that matches nothing — the opposite of Claude Code's+/// empty-matcher convention, so `HookShape::Flat` must not be reused;+/// - no `type` key: the v2 `Hook` struct has no such field.+///+/// `agentSpawn` sets `max_output_size` above the 10 KiB default so a+/// fetched handoff + compiled project brief is not truncated mid-JSON+/// before Kiro adds it to the agent context.+pub(crate) fn build_kiro_cli_v2_hooks_value(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> serde_json::Map<String, Value> {+ build_kiro_cli_v2_hooks_value_for_platform(+ emit_root,+ server_url,+ auth_token,+ HookCommandPlatform::current(),+ data_dir,+ project_strategy,+ )+}++/// Session-start context injection ceiling for Kiro v2 (`max_output_size`).+/// Kiro truncates hook stdout beyond this; 64 KiB comfortably covers a+/// handoff plus a `[briefing]`-budgeted brief.+pub(crate) const KIRO_CLI_V2_SESSION_START_MAX_OUTPUT: usize = 64 * 1024;++fn build_kiro_cli_v2_hooks_value_for_platform(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ platform: HookCommandPlatform,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> serde_json::Map<String, Value> {+ let mut hooks = serde_json::Map::new();+ for (event, script) in KIRO_CLI_V2_EVENTS {+ let script = script_for_platform(script, platform);+ let abs = emit_root.join(script.as_ref());+ let command = hook_command(+ &abs,+ server_url,+ auth_token,+ HookCommandContext::new(platform, "kiro-cli", data_dir, project_strategy),+ );+ let mut entry = serde_json::Map::new();+ entry.insert("command".to_string(), Value::String(command));+ if event == "agentSpawn" {+ entry.insert(+ "max_output_size".to_string(),+ Value::from(KIRO_CLI_V2_SESSION_START_MAX_OUTPUT),+ );+ }+ hooks.insert(event.to_string(), json!([Value::Object(entry)]));+ }+ hooks+}++/// Build the standalone versioned hooks file for the Kiro CLI v3 engine+/// (`~/.kiro/hooks/ai-memory.json`), per kiro.dev/docs/cli/v3/hooks:+/// `{"version":"v1","hooks":[{name, description, trigger, action, timeout}]}`+/// with PascalCase triggers and `{"type":"command","command":…}` actions.+/// No `matcher` key — an omitted matcher always fires, and v3 matchers+/// are regexes over tool names / prompt text, none of which a capture+/// hook wants to filter. Every entry name carries the `ai-memory-`+/// prefix; reapply and uninstall identify our entries by that prefix or+/// by the command string, so third-party hooks that a user placed in+/// the same file survive.+///+/// `timeout` is in SECONDS on v3 (not v2's `timeout_ms`). The scripts+/// self-bound their network waits well under a second, so 10 s is a+/// generous ceiling that still protects the session UX.+pub(crate) fn build_kiro_cli_v3_hooks_file(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> Value {+ build_kiro_cli_v3_hooks_file_for_platform(+ emit_root,+ server_url,+ auth_token,+ HookCommandPlatform::current(),+ data_dir,+ project_strategy,+ )+}++/// Timeout (seconds) for ai-memory's Kiro v3 hook entries.+pub(crate) const KIRO_CLI_V3_HOOK_TIMEOUT_SECONDS: u64 = 10;++fn build_kiro_cli_v3_hooks_file_for_platform(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ platform: HookCommandPlatform,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> Value {+ let hooks: Vec<Value> = KIRO_CLI_V3_EVENTS+ .iter()+ .map(|(trigger, script)| {+ let stem = script.trim_end_matches(".sh");+ let script = script_for_platform(script, platform);+ let abs = emit_root.join(script.as_ref());+ let command = hook_command(+ &abs,+ server_url,+ auth_token,+ HookCommandContext::new(platform, "kiro-cli", data_dir, project_strategy),+ );+ json!({+ "name": format!("ai-memory-{stem}"),+ "description": "ai-memory lifecycle capture (fire-and-forget)",+ "trigger": trigger,+ "action": { "type": "command", "command": command },+ "timeout": KIRO_CLI_V3_HOOK_TIMEOUT_SECONDS,+ })+ })+ .collect();+ 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.rsindex c05d238b..6f887f9c 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -38,8 +38,9 @@ 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, build_claude_code_payload, build_devin_payload,- build_grok_payload, hook_script_for_current_platform,+ 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,};use crate::config::{Config, DEFAULT_SERVER_URL};@@ -149,6 +150,16 @@ 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]),+ // Both Kiro engine surfaces stage the same `hooks/kiro-cli/`+ // bundle; only the registration config differs (v2 agent-config+ // entries vs the v3 standalone hooks file), and apply-mode owns+ // those exact merges.+ 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@@ -676,4 +687,55 @@ mod tests {assert_eq!(KIMI_CODE_EVENTS.len(), 10);assert_eq!(paths.len(), 9);}++ #[test]+ fn kiro_cli_manual_script_paths_cover_both_engine_event_sets() {+ // Both Kiro engines share one five-script bundle; only the+ // trigger spellings differ (v2 camelCase in agent configs, v3+ // PascalCase in the standalone hooks file). The parity gate+ // keeps the bundle and both event tables from drifting apart.+ let root = Path::new("/hooks/kiro-cli");+ let v2_paths = event_script_paths(root, &[&KIRO_CLI_V2_EVENTS]);+ let v3_paths = event_script_paths(root, &[&KIRO_CLI_V3_EVENTS]);+ assert_eq!(+ v2_paths, v3_paths,+ "both engines must stage the same bundle"+ );+ let rendered = v2_paths+ .iter()+ .map(|path| path.to_string_lossy())+ .collect::<Vec<_>>()+ .join("\n");++ for script in [+ "session-start",+ "user-prompt-submit",+ "pre-tool-use",+ "post-tool-use",+ "stop",+ ] {+ assert!(+ rendered.contains(script),+ "Kiro CLI setup-agent must list {script}; got:\n{rendered}"+ );+ }+ // The v2 vocabulary is exactly five camelCase triggers; the v3+ // vocabulary is the same five in PascalCase. No PreCompact /+ // SessionEnd / subagent equivalents exist on either engine.+ assert_eq!(KIRO_CLI_V2_EVENTS.len(), 5);+ assert_eq!(KIRO_CLI_V3_EVENTS.len(), 5);+ assert_eq!(v2_paths.len(), 5);+ // Positional pairing: entry N of both tables is the same logical+ // event registered under each engine's spelling (v2 `agentSpawn`+ // pairs with v3 `SessionStart`), so the script must match+ // position by position.+ for ((v2_event, v2_script), (v3_event, v3_script)) in+ KIRO_CLI_V2_EVENTS.iter().zip(KIRO_CLI_V3_EVENTS.iter())+ {+ assert_eq!(+ v2_script, v3_script,+ "v2 {v2_event} and v3 {v3_event} must run the same script"+ );+ }+ }}diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 686ff038..3173e905 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -42,6 +42,10 @@ enum RewriteOp {ZeroHooksJson,/// Kimi Code `[[hooks]]` rules inside config.toml.KimiCodeHooksToml,+ /// Kiro CLI v3 standalone hooks file — `hooks` array entries whose+ /// `name` carries the `ai-memory-` prefix (or whose command action+ /// references ai-memory).+ KiroCliV3HooksJson,/// MCP JSON config for one client shape.McpJson(McpClient),/// Codex TOML MCP config.@@ -181,6 +185,15 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {HookConfigShape::NestedHooksKey,),]);+ // Kiro CLI v2-engine agent configs embed hooks under the standard+ // `hooks` key (flat command entries), so the same strip pass+ // removes ours from every config in the agents directory while+ // preserving third-party entries.+ hook_files.extend(+ install_hooks::list_kiro_cli_agent_configs(&install_hooks::kiro_cli_agents_dir()?)?+ .into_iter()+ .map(|path| (path, HookConfigShape::NestedHooksKey)),+ );for (path, shape) in hook_files {if !path.exists() {continue;@@ -238,6 +251,19 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {);}+ let kiro_v3 = install_hooks::kiro_cli_v3_hooks_path()?;+ if kiro_v3.exists() {+ let content = std::fs::read_to_string(&kiro_v3)+ .with_context(|| format!("reading {}", kiro_v3.display()))?;+ let removal = strip_kiro_cli_v3_hooks(&content)?;+ push_rewrite(+ &mut plan,+ kiro_v3,+ removal.removed_events,+ RewriteOp::KiroCliV3HooksJson,+ );+ }+let plugin = install_hooks::opencode_plugin_path()?;push_generated_delete(&mut plan, plugin, DeleteKind::OpenCodePlugin);@@ -468,6 +494,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::KiroCliV3HooksJson => strip_kiro_cli_v3_hooks(&out)?.new_content,RewriteOp::McpJson(client) => {strip_mcp_json_client(&out, client, name, url)?.0}@@ -774,6 +801,43 @@ fn strip_zero_hooks(content: &str) -> Result<HookRemoval> {})}+/// Remove ai-memory's entries from the Kiro CLI v3 standalone hooks file+/// (`~/.kiro/hooks/ai-memory.json`). Install writes every entry with the+/// `ai-memory-` name prefix, so the prefix is the primary ownership+/// signature; a command action referencing ai-memory covers hand-edited+/// entries. Non-ai-memory entries a user added to the same file survive,+/// and the pinned `version` key is left alone (an empty `hooks` array is+/// a valid v3 file).+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(|v| v.as_array_mut()) else {+ return Ok(());+ };+ hooks.retain(|hook| {+ let name = hook.get("name").and_then(|v| v.as_str());+ let ours = name.is_some_and(|name| name.starts_with("ai-memory-"))+ || hook+ .get("action")+ .and_then(|action| action.get("command"))+ .and_then(|command| command.as_str())+ .is_some_and(|command| {+ let lower = command.to_ascii_lowercase();+ lower.contains("ai-memory") || lower.contains("ai_memory")+ });+ if ours {+ removed_events.push(format!("kiro-cli-v3.{}", name.unwrap_or("<unnamed>")));+ }+ !ours+ });+ 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.diff --git a/crates/ai-memory-cli/tests/removal.rs b/crates/ai-memory-cli/tests/removal.rsindex 6af0fe9a..6660d579 100644--- a/crates/ai-memory-cli/tests/removal.rs+++ b/crates/ai-memory-cli/tests/removal.rs@@ -1085,6 +1085,86 @@ command = "'/usr/local/bin/ai-memory' hook --event stop --agent kimi-code --serv);}+#[test]+fn uninstall_kiro_cli_hooks_preserves_user_entries_on_both_engines() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let kiro = home.path().join(".kiro");++ // v2 engine surface: an agent config with a third-party hook next to ours.+ let agents = kiro.join("agents");+ std::fs::create_dir_all(&agents).unwrap();+ let agent_config = agents.join("dev.json");+ std::fs::write(+ &agent_config,+ r#"{+ "name": "dev",+ "tools": ["*"],+ "hooks": {+ "agentSpawn": [+ {"command": "git status"},+ {"command": "AI_MEMORY_HOOK_URL=http://h /x/kiro-cli/session-start.sh", "max_output_size": 65536}+ ],+ "stop": [+ {"command": "'/usr/local/bin/ai-memory' hook --event stop --agent kiro-cli --server-url http://h:49374"}+ ]+ }+}"#,+ )+ .unwrap();++ // v3 engine surface: our standalone hooks file with one user entry inside.+ let hooks_dir = kiro.join("hooks");+ std::fs::create_dir_all(&hooks_dir).unwrap();+ let v3_file = hooks_dir.join("ai-memory.json");+ std::fs::write(+ &v3_file,+ r#"{+ "version": "v1",+ "hooks": [+ {"name": "ai-memory-session-start", "trigger": "SessionStart",+ "action": {"type": "command", "command": "/x/kiro-cli/session-start.sh"}, "timeout": 10},+ {"name": "lint-on-save", "trigger": "PostFileSave", "matcher": "\\.rs$",+ "action": {"type": "command", "command": "cargo fmt"}}+ ]+}"#,+ )+ .unwrap();+ // A neighbouring third-party hooks file must never be touched.+ let third_party_file = hooks_dir.join("team-hooks.json");+ let third_party_body = r#"{"version":"v1","hooks":[{"name":"security-check","trigger":"PreToolUse","action":{"type":"command","command":"/usr/bin/audit"}}]}"#;+ std::fs::write(&third_party_file, third_party_body).unwrap();++ let status = command_with_home(home.path())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let agent_after: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&agent_config).unwrap()).unwrap();+ assert_eq!(agent_after["name"], "dev", "agent definition must survive");+ let spawn = agent_after["hooks"]["agentSpawn"].as_array().unwrap();+ assert_eq!(spawn.len(), 1, "only ai-memory entries removed");+ assert_eq!(spawn[0]["command"], "git status");+ assert!(+ agent_after["hooks"].get("stop").is_none(),+ "an event array left empty is dropped"+ );++ 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, "user entry in our file must survive");+ assert_eq!(v3_hooks[0]["name"], "lint-on-save");++ assert_eq!(+ std::fs::read_to_string(&third_party_file).unwrap(),+ third_party_body,+ "third-party hooks files must stay byte-identical"+ );+}+#[test]fn uninstall_mcp_custom_url_removes_kimi_code_only_by_endpoint() {let _guard = cli_test_lock();diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex cb8dbff7..5fd28b9e 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -208,6 +208,9 @@ pub enum AgentKind {Devin,/// Kimi Code CLI (Moonshot AI).KimiCode,+ /// Kiro CLI (AWS), covering both the default v2 agent engine and the+ /// early-access v3 engine of the same binary.+ KiroCli,/// Anything else (manual capture, future agents).Other,}@@ -218,7 +221,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; 16] = [+ pub const ALL: [Self; 17] = [Self::ClaudeCode,Self::Codex,Self::OpenCode,@@ -234,6 +237,7 @@ impl AgentKind {Self::Zero,Self::Devin,Self::KimiCode,+ Self::KiroCli,Self::Other,];@@ -256,6 +260,7 @@ impl AgentKind {Self::Zero => "zero",Self::Devin => "devin",Self::KimiCode => "kimi-code",+ Self::KiroCli => "kiro-cli",Self::Other => "other",}}@@ -281,6 +286,7 @@ impl AgentKind {"zero" => Self::Zero,"devin" => Self::Devin,"kimi-code" | "kimi" => Self::KimiCode,+ "kiro-cli" | "kiro" | "kiro_cli" => Self::KiroCli,_ => Self::Other,}}@@ -306,6 +312,13 @@ impl AgentKind {/// dispatch return, verified in the v0.28.1 source), so the handoff is/// delivered on `UserPromptSubmit` instead — see/// [`Self::user_prompt_injects_handoff`].+ ///+ /// Kiro CLI injects the session-start hook's stdout on both engines:+ /// the v2 engine adds `agentSpawn` exit-0 stdout to the agent context+ /// and the v3 engine does the same for `SessionStart` stdout (both per+ /// the official hooks contracts at kiro.dev/docs/cli/hooks and+ /// kiro.dev/docs/cli/v3/hooks, cross-checked against the shipping+ /// `HookTrigger` implementation in aws/amazon-q-developer-cli).#[must_use]pub fn session_start_injects_handoff(self) -> bool {!matches!(@@ -416,6 +429,30 @@ mod tests {assert!(AgentKind::KimiCode.user_prompt_injects_handoff());}+ #[test]+ fn agent_kind_kiro_cli_round_trips() {+ assert_eq!(AgentKind::KiroCli.as_str(), "kiro-cli");+ assert_eq!(AgentKind::from_wire("kiro-cli"), AgentKind::KiroCli);+ assert_eq!(AgentKind::from_wire("kiro"), AgentKind::KiroCli);+ assert_eq!(AgentKind::from_wire("kiro_cli"), AgentKind::KiroCli);+ // serde uses rename_all = "kebab-case" → "kiro-cli".+ assert_eq!(+ serde_json::to_string(&AgentKind::KiroCli).unwrap(),+ "\"kiro-cli\""+ );+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"kiro-cli\"").unwrap(),+ AgentKind::KiroCli+ );+ // Unknown tags still degrade to Other.+ assert_eq!(AgentKind::from_wire("kiro-ide"), AgentKind::Other);+ // Both Kiro engines add session-start hook stdout to the agent+ // context (v2 agentSpawn, v3 SessionStart), so the handoff is+ // fetched and injected there — not on UserPromptSubmit.+ assert!(AgentKind::KiroCli.session_start_injects_handoff());+ assert!(!AgentKind::KiroCli.user_prompt_injects_handoff());+ }+#[test]fn user_prompt_handoff_injection_is_kimi_only() {for agent in AgentKind::ALL {diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsindex fa4e6f36..84b2cb1b 100644--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -65,7 +65,7 @@ install or refresh work.If you're about to write a durable project rule ("always X", "neverY", "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,+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI / Kimi Code / Kiro CLI,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@@ -82,7 +82,7 @@ latest binary's recommended copy:- **From the agent** (no terminal needed): ask "refresh the ai-memoryrouting 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 -> `AGENTS.md`),+ OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`; Kimi Code / Kiro CLI -> `AGENTS.md`),uses its Write / Edit tool to replace or append the returned`markered_block` while preservingnon-ai-memory user content, then writes or updates each returneddiff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex 7b0aef8d..2d92e64a 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -130,6 +130,9 @@ pub(crate) fn tool_observation_metadata(object.get("tool_name")?.as_str()?,object.get("tool_use_id").and_then(Value::as_str),),+ // Kiro CLI (fixture-backed, kiro.dev/docs/cli/hooks): tool hooks+ // carry `tool_name` + `tool_input`; no call-id field is documented.+ AgentKind::KiroCli => (object.get("tool_name")?.as_str()?, None),AgentKind::OpenCode => (object.get("tool")?.as_str()?,object.get("callID").and_then(Value::as_str),@@ -147,11 +150,13 @@ pub(crate) fn tool_observation_metadata(|| match agent {AgentKind::AntigravityCli => object.get("toolCall")?.get("args").is_some(),_ => object- .get(if agent == AgentKind::ClaudeCode {- "tool_input"- } else {- "args"- })+ .get(+ if matches!(agent, AgentKind::ClaudeCode | AgentKind::KiroCli) {+ "tool_input"+ } else {+ "args"+ },+ ).is_some(),};has_args.then(|| ToolObservationMetadata {@@ -168,6 +173,17 @@ pub(crate) fn tool_observation_outcome(agent: AgentKind, raw: &Value) -> ToolOutSome(false) => ToolOutcome::Success,None => ToolOutcome::Unknown,},+ // Kiro CLI postToolUse documents `tool_response.success`+ // (kiro.dev/docs/cli/hooks).+ AgentKind::KiroCli => match raw+ .get("tool_response")+ .and_then(|response| response.get("success"))+ .and_then(Value::as_bool)+ {+ Some(true) => ToolOutcome::Success,+ Some(false) => ToolOutcome::Error,+ None => ToolOutcome::Unknown,+ },AgentKind::AntigravityCliif raw.get("error")@@ -507,7 +523,8 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted {| AgentKind::Codex| AgentKind::Cursor| AgentKind::GeminiCli- | AgentKind::Devin => object+ | AgentKind::Devin+ | AgentKind::KiroCli => object.get("tool_name").and_then(Value::as_str).map(|name| (name, object.get("tool_input"))),@@ -556,13 +573,17 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted {fn family(name: &str) -> ToolFamily {match name.to_ascii_lowercase().as_str() {+ // `fs_read`/`fs_write` are Kiro CLI's built-in file tools+ // (kiro.dev/docs/cli/reference/built-in-tools)."read" | "write" | "edit" | "apply_patch" | "notebookedit" | "notebook_edit"| "create_file" | "delete_file" | "rename_file" | "move_file" | "multi_edit"- | "multiedit" | "replace" | "replace_all" => ToolFamily::File,+ | "multiedit" | "replace" | "replace_all" | "fs_read" | "fs_write" => ToolFamily::File,"search" | "grep" | "glob" | "find" | "list" | "ls" | "list_files" | "read_dir" => {ToolFamily::SearchList}- "bash" | "shell" | "execute" | "run_command" | "web_search" => ToolFamily::NonFile,+ // `execute_bash`/`execute_cmd` are Kiro CLI's shell tools.+ "bash" | "shell" | "execute" | "run_command" | "web_search" | "execute_bash"+ | "execute_cmd" => ToolFamily::NonFile,_ => ToolFamily::Unknown,}}@@ -607,6 +628,28 @@ fn extract_paths(name: &str, args: &Value) -> Option<Vec<String>> {paths.extend(paths_in_entry);}}+ // Kiro CLI's `fs_read` batches its targets as+ // `{"operations":[{"mode":…,"path":…},…]}`; every operation must+ // yield a path or the extraction is treated as malformed (which+ // fails safe under an active policy).+ if name.eq_ignore_ascii_case("fs_read")+ && let Some(operations) = object.get("operations")+ {+ let entries = operations.as_array()?;+ if entries.is_empty() {+ return None;+ }+ if entries.len() > MAX_CAPTURE_CANDIDATES {+ return None;+ }+ for entry in entries {+ let paths_in_entry = direct_paths(entry.as_object()?)?;+ if paths.len().checked_add(paths_in_entry.len())? > MAX_CAPTURE_CANDIDATES {+ return None;+ }+ paths.extend(paths_in_entry);+ }+ }(!paths.is_empty()&& paths.iter().all(|path| {!path.trim().is_empty() && path.chars().count() <= MAX_CANDIDATE_PATH_CHARSdiff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.jsonindex 1ece4c14..07fd94cf 100644--- a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json@@ -17,6 +17,10 @@{"agent":"cursor","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},{"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":"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},{"agent":"antigravity-cli","payload":{"toolCall":{"name":"Edit","args":{"path":"secret/a"}}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 2f46e56b..07a885f2 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -2465,6 +2465,7 @@ impl AiMemoryServer {"zero": "AGENTS.md","devin": "AGENTS.md","kimi_code": "AGENTS.md",+ "kiro_cli": "AGENTS.md","grok": "AGENTS.md","default": "AGENTS.md"},@@ -2542,12 +2543,16 @@ impl ServerHandler for AiMemoryServer {// rmcp injects `http::request::Parts` into request extensions in// both stateless and stateful modes, so the flavor marker is// available even without peer clientInfo.- let moonshot = context+ let flat_root_schema = context.extensions.get::<http::request::Parts>().and_then(|parts| parts.uri.query())- .is_some_and(|query| query.split('&').any(|pair| pair == "flavor=moonshot"));- if moonshot {+ .is_some_and(|query| {+ query+ .split('&')+ .any(|pair| pair == "flavor=moonshot" || pair == "flavor=bedrock")+ });+ if flat_root_schema {Ok(ListToolsResult::with_all_items(moonshot_safe_tool_list(tools,)))@@ -2559,10 +2564,13 @@ impl ServerHandler for AiMemoryServer {/// Moonshot ("moonshot flavored json schema") rejects root-level/// `anyOf`/`oneOf`/`allOf` in tool parameter schemas with a 400 at-/// `tools/list` time. Requests marked `?flavor=moonshot` (the URL-/// `install-mcp --client kimi-code` writes) get the tool list with-/// those root keys stripped; nested combinators stay, and the handlers'-/// runtime validation still enforces the arg contracts.+/// `tools/list` time, and Amazon Bedrock's Converse API (used by the+/// AWS Kiro CLI) rejects the same root-level combinators. Requests+/// marked `?flavor=moonshot` (the URL `install-mcp --client kimi-code`+/// writes) or `?flavor=bedrock` (for Kiro CLI's manually configured+/// `~/.kiro/settings/mcp.json`) get the tool list with those root keys+/// stripped; nested combinators stay, and the handlers' runtime+/// validation still enforces the arg contracts.fn moonshot_safe_tool_list(tools: Vec<Tool>) -> Vec<Tool> {const ROOT_COMBINATORS: [&str; 3] = ["anyOf", "oneOf", "allOf"];toolsdiff --git a/crates/ai-memory-mcp/tests/mcp_stateless_http.rs b/crates/ai-memory-mcp/tests/mcp_stateless_http.rsindex d6b42350..75b03571 100644--- a/crates/ai-memory-mcp/tests/mcp_stateless_http.rs+++ b/crates/ai-memory-mcp/tests/mcp_stateless_http.rs@@ -215,6 +215,39 @@ async fn stateless_moonshot_flavor_strips_root_any_of() {);}+/// Kiro CLI's manual MCP config flow: Amazon Bedrock's Converse API+/// rejects the same root-level combinators Moonshot does, so+/// `/mcp?flavor=bedrock` must return the identical flattened tool list.+#[tokio::test]+async fn stateless_bedrock_flavor_strips_root_any_of() {+ let tmp = TempDir::new().unwrap();+ let (router, _store) = make_router(&tmp, false).await;++ let init = router+ .clone()+ .oneshot(post_to("/mcp?flavor=bedrock", INITIALIZE))+ .await+ .unwrap();+ assert_eq!(init.status(), StatusCode::OK);++ let resp = router+ .oneshot(post_to("/mcp?flavor=bedrock", TOOLS_LIST))+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let schema = read_page_input_schema(&body_string(resp).await);+ for key in ["anyOf", "oneOf", "allOf"] {+ assert!(+ schema.get(key).is_none(),+ "bedrock flavor must strip root `{key}`: {schema}"+ );+ }+ assert!(+ schema.get("properties").is_some(),+ "the flat schema must keep describing the args: {schema}"+ );+}+/// Control: without the marker, tools/list keeps the upstream root `anyOf`.#[tokio::test]async fn stateless_tools_list_without_flavor_keeps_root_any_of() {diff --git a/crates/ai-memory-store/migrations/V34__sessions_kiro_cli_agent_kind.sql b/crates/ai-memory-store/migrations/V34__sessions_kiro_cli_agent_kind.sqlnew file mode 100644index 00000000..7cb926a2--- /dev/null+++ b/crates/ai-memory-store/migrations/V34__sessions_kiro_cli_agent_kind.sql@@ -0,0 +1,52 @@+-- Expand sessions.agent_kind CHECK for Kiro CLI (AWS).+--+-- Every sessions-table rebuild must retain the complete AgentKind set and the+-- V18/V22 scope-pairing triggers. Without this rebuild the hook router WARNs+-- and drops kiro-cli sessions at begin_session, silently disabling capture.++PRAGMA foreign_keys = OFF;++DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_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','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL+);++INSERT INTO sessions_new SELECT * 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 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;++PRAGMA foreign_keys = ON;diff --git a/docs/install.md b/docs/install.mdindex 7c9c48a2..8762aa06 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, OpenClaw, VS Code Copilot)+ (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)- [Installing hooks without docker](#installing-hooks-without-docker)(curl-based installer)- [Running ai-memory without docker](#running-ai-memory-without-docker)@@ -681,6 +681,91 @@ 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.+### Kiro CLI++The AWS Kiro CLI ships two agent engines in one binary — the default v2+engine and the early-access v3 engine (`kiro-cli chat --agent-engine v3`,+alias `--v3`) — and their hook surfaces are **not compatible**: v2 embeds+camelCase hook entries inside agent configs, while v3 reads standalone+versioned hooks files with PascalCase triggers. ai-memory never guesses+which engine you use; each surface is installed by its own explicit agent+selection, and installing both is safe (each engine ignores the other's+surface). Both honor `$KIRO_HOME` (default `~/.kiro`) and stage the same+`hooks/kiro-cli/` script bundle. Contracts verified against kiro-cli+2.16.0 and the official hook references+([v2](https://kiro.dev/docs/cli/hooks/), [v3](https://kiro.dev/docs/cli/v3/hooks/)).++**v2 engine (default)** — hooks live inside each agent config+(`~/.kiro/agents/*.json`); there is no global v2 hook surface, and the+built-in default agent has no file on disk. Create an agent config first+if you have none (`kiro-cli agent create`, then+`kiro-cli agent set-default <name>`):++```bash+ai-memory install-hooks --agent kiro-cli --apply \+ --server-url "http://homelab:49374" \+ --auth-token "$TOKEN"+```++This merges five flat entries — `agentSpawn`, `userPromptSubmit`,+`preToolUse`, `postToolUse`, `stop` — into **every** existing agent config+(or only the one passed via `--config-file`), preserving third-party+entries under the same triggers. Entries deliberately carry no `matcher`+key: in Kiro v2 an absent matcher applies the hook to every tool, while an+empty-string matcher matches nothing. The `agentSpawn` entry raises+`max_output_size` to 64 KiB so an injected handoff + project brief is not+truncated. A pending handoff is injected at `agentSpawn` through the+hook's exit-0 stdout, which the v2 engine adds to the agent context.++**v3 engine (early access)** — hooks are standalone files; global ones+under `~/.kiro/hooks/` fire in every workspace:++```bash+ai-memory install-hooks --agent kiro-cli-v3 --apply \+ --server-url "http://homelab:49374" \+ --auth-token "$TOKEN"+```++This writes `~/.kiro/hooks/ai-memory.json` (`{"version":"v1","hooks":[…]}`)+with five command actions — `SessionStart`, `UserPromptSubmit`,+`PreToolUse`, `PostToolUse`, `Stop` — and a 10-second timeout each (v3+timeouts are seconds; v2 uses `timeout_ms`). Other `*.json` files in the+hooks directory are never touched, and non-ai-memory entries inside+`ai-memory.json` survive re-applies and uninstall. A pending handoff is+injected at `SessionStart` through the hook's exit-0 stdout, which the v3+engine adds to the agent context. The v3 stdin payload field names are not+publicly documented yet; capture forwards the raw event JSON, and+tool-payload extraction (for `[capture] ignore_paths` enforcement) is+verified on the v2 payload shape (`tool_name`/`tool_input`).++On both engines the hooks are fail-open by contract: they always exit 0+and print nothing on capture paths (exit code 2 would block the tool call+on `preToolUse`/`PreToolUse`, and stray stdout would leak into the agent+context on session-start/user-prompt events), so a stopped ai-memory+server never breaks a Kiro session.++**MCP** — the installer does not manage Kiro's MCP config yet. Add the+server manually to `~/.kiro/settings/mcp.json`, using the `bedrock`+schema flavor: Kiro talks to Amazon Bedrock's Converse API, which rejects+root-level `anyOf`/`oneOf`/`allOf` in tool schemas, and the flavored URL+serves the same tools with flattened root schemas:++```json+{+ "mcpServers": {+ "ai-memory": {+ "url": "http://homelab:49374/mcp?flavor=bedrock",+ "headers": { "Authorization": "Bearer YOUR_TOKEN" }+ }+ }+}+```++Sessions launched with `--v3` cannot be resumed by the v2 engine (and+vice versa) — the resume hint Kiro prints at session end needs `--v3`+added manually. Managed `ai-memory run kiro` support is tracked+separately (upstream issue #356).+### OpenCode```bashdiff --git a/docs/usage.md b/docs/usage.mdindex 490a48fb..e78823d8 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -211,6 +211,10 @@ 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 staleMCP or hook entries.+- Kiro CLI: check the `hooks` objects inside `~/.kiro/agents/*.json` (v2+ engine), the `~/.kiro/hooks/ai-memory.json` file (v3 engine), and+ `~/.kiro/settings/mcp.json` (all under `$KIRO_HOME` when set) for stale+ 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 and Claude Desktop: these are usually MCP-only, so confirm@@ -304,7 +308,8 @@ docker exec ai-memory git -C /data/wiki log --onelineDurable project rules belong in the agent's rules file, not only in thewiki. For Claude Code that is `CLAUDE.md`; for Codex, Devin CLI, OpenCode,-Cursor, Gemini CLI, Grok Build CLI, and Kimi Code it is usually `AGENTS.md`.+Cursor, Gemini CLI, Grok Build CLI, Kimi Code, and Kiro CLI it is usually+`AGENTS.md`.The consolidator classifies compiled observations as `decision`,`fact`, `rule`, or `gotcha`. Rule-tagged pages are routed todiff --git a/docs/windows.md b/docs/windows.mdindex d65a6e32..7061809a 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -6,8 +6,8 @@ agent CLI actually runs.## Rule Of ThumbRun `install-mcp` and `install-hooks` from the same environment that-launches Claude Code, Codex, Devin CLI, Cursor, Gemini CLI, Kimi Code, or-another agent.+launches Claude Code, Codex, Devin CLI, Cursor, Gemini CLI, Kimi Code,+Kiro CLI, or another agent.- If the agent runs inside WSL2, install ai-memory inside WSL2.- If the agent runs as a native Windows process, install ai-memory from@@ -121,7 +121,8 @@ for each native Windows agent so existing hook entries receive the currentcommand form.Use the matching `--client` / `--agent` values for other clients, for-example `codex`, `devin`, `kimi-code`, `cursor`, or `gemini-cli`.+example `codex`, `devin`, `kimi-code`, `kiro-cli` (or `kiro-cli-v3` for+the v3 engine's hooks file), `cursor`, or `gemini-cli`.For Devin, `install-mcp --client devin --apply` writes MCP config to`%USERPROFILE%\.devin\config.json`. `install-hooks --agent devin --apply`@@ -326,7 +327,7 @@ Windows agent builds.`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, Grok Build CLI, Zero,- Kimi Code, and OpenClaw may each choose different+ Kimi Code, Kiro CLI, and OpenClaw may each choose differentWindows config locations or shell execution behavior. ai-memory usesthe current best-known defaults, but they need validation on realinstallations.diff --git a/hooks/_lib.sh b/hooks/_lib.shindex 6c1d64bc..280d6090 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -2,8 +2,8 @@# Sourced by per-agent lifecycle hook scripts. POSIX shell only —# no bash-isms, no non-standard deps (no jq, no toml crate). Keep changes# byte-trivial because every supported agent (claude-code, codex,-# cursor, gemini-cli, kimi-code, antigravity-cli, opencode, omp) sources-# this same file.+# cursor, gemini-cli, kimi-code, kiro-cli, antigravity-cli, opencode,+# omp) sources this same file.# Walk up from "$1" toward $HOME (or /) looking for `.ai-memory.toml`.# Prints the absolute path of the first marker found, or nothing.diff --git a/hooks/kiro-cli/post-tool-use.ps1 b/hooks/kiro-cli/post-tool-use.ps1new file mode 100644index 00000000..c317ee09--- /dev/null+++ b/hooks/kiro-cli/post-tool-use.ps1@@ -0,0 +1,4 @@+# Kiro CLI post-tool-use hook (v2: postToolUse; v3: PostToolUse).+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "kiro-cli"+exit 0diff --git a/hooks/kiro-cli/post-tool-use.sh b/hooks/kiro-cli/post-tool-use.shnew file mode 100755index 00000000..71037cde--- /dev/null+++ b/hooks/kiro-cli/post-tool-use.sh@@ -0,0 +1,15 @@+#!/bin/sh+# Kiro CLI post-tool-use hook (v2: postToolUse; v3: PostToolUse).+# Forwards the event JSON to the ai-memory server, fire-and-forget.+_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=kiro-cli${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kiro-cli/pre-tool-use.ps1 b/hooks/kiro-cli/pre-tool-use.ps1new file mode 100644index 00000000..54e70068--- /dev/null+++ b/hooks/kiro-cli/pre-tool-use.ps1@@ -0,0 +1,6 @@+# Kiro CLI pre-tool-use hook (v2: preToolUse; v3: PreToolUse).+# Fail-open by contract: exit 0 unconditionally and print nothing —+# exit code 2 would block the tool call on both engines.+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "kiro-cli"+exit 0diff --git a/hooks/kiro-cli/pre-tool-use.sh b/hooks/kiro-cli/pre-tool-use.shnew file mode 100755index 00000000..10f378db--- /dev/null+++ b/hooks/kiro-cli/pre-tool-use.sh@@ -0,0 +1,18 @@+#!/bin/sh+# Kiro CLI pre-tool-use hook (v2: preToolUse; v3: PreToolUse).+# Forwards the event JSON to the ai-memory server, fire-and-forget.+# Fail-open by contract: exit 0 unconditionally and print nothing.+# Exit code 2 would BLOCK the tool call on both engines, so a capture+# hook must never let a server error surface as a non-zero exit.+_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=kiro-cli${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kiro-cli/session-start.ps1 b/hooks/kiro-cli/session-start.ps1new file mode 100644index 00000000..15f70f76--- /dev/null+++ b/hooks/kiro-cli/session-start.ps1@@ -0,0 +1,8 @@+# Kiro CLI session-start hook (v2 engine: agentSpawn; v3: SessionStart).+# Both Kiro engines add this hook's exit-0 stdout to the agent context,+# so the pending handoff is fetched and printed raw here (no envelope —+# Kiro documents none). The compiled project brief rides the same fetch+# once per session.+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "session-start" -Agent "kiro-cli" -FetchHandoff -BriefingOncePerSession+exit 0diff --git a/hooks/kiro-cli/session-start.sh b/hooks/kiro-cli/session-start.shnew file mode 100755index 00000000..e0a31a16--- /dev/null+++ b/hooks/kiro-cli/session-start.sh@@ -0,0 +1,48 @@+#!/bin/sh+# Kiro CLI session-start hook (v2 engine: agentSpawn; v3 engine: SessionStart).+# 1. Forwards the event JSON to the ai-memory server (fire-and-forget).+# 2. Synchronously fetches any pending cross-agent handoff and prints the+# raw body to stdout — both Kiro engines add this hook's exit-0 stdout+# to the agent context (v2 per kiro.dev/docs/cli/hooks, v3 per+# kiro.dev/docs/cli/v3/hooks), so the resuming agent sees prior context+# with no human in the loop. Kiro documents no JSON envelope for hook+# stdout, so print the raw handoff body or nothing at all.+# 3. Delivers the compiled project brief ([briefing]+# inject_on_session_start) once per session, gated by a marker file+# keyed on Kiro's native session id when the payload carries one.+_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")"++# Once-per-session briefing gate. Marker files are created only when the+# repository opted in. Prefer Kiro's native session id when supplied;+# otherwise use a stable hash of agent+cwd.+BRIEF_QS=$(ai_memory_briefing_qs "$CWD")+BRIEF_FILE=""+if [ -n "$BRIEF_QS" ]; then+ BRIEF_KEY="$SESSION_ID"+ if [ -z "$BRIEF_KEY" ]; then+ BRIEF_KEY="kiro-cli-$(printf '%s' "kiro-cli:$CWD" | cksum | awk '{print $1}')"+ fi+ BRIEF_FILE=$(ai_memory_briefed_file "$BRIEF_KEY")+ [ -f "$BRIEF_FILE" ] && BRIEF_QS=""+fi++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=session-start&agent=kiro-cli${QS}" >/dev/null 2>&1 || true++HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=kiro-cli${QS}${SESSION_QS}${BRIEF_QS}" 2>/dev/null || true)+# Mark an opted-in session as briefed only AFTER the GET completed — success+# or error. Fail-open on purpose: with the server down the flagged request+# delivers nothing anyway, and the one lost brief returns next session.+[ -n "$BRIEF_FILE" ] && ai_memory_mark_briefed "$BRIEF_FILE"+[ -n "$HANDOFF" ] && printf '%s\n' "$HANDOFF"+exit 0diff --git a/hooks/kiro-cli/stop.ps1 b/hooks/kiro-cli/stop.ps1new file mode 100644index 00000000..c98626fa--- /dev/null+++ b/hooks/kiro-cli/stop.ps1@@ -0,0 +1,7 @@+# Kiro CLI stop hook (v2: stop; v3: Stop).+# Print nothing: on the v2 engine a stop hook's stdout can carry a+# {"decision":"block"} verdict that would re-prompt the model, so a+# capture-only hook keeps stdout empty and exits 0.+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "stop" -Agent "kiro-cli"+exit 0diff --git a/hooks/kiro-cli/stop.sh b/hooks/kiro-cli/stop.shnew file mode 100755index 00000000..382e9974--- /dev/null+++ b/hooks/kiro-cli/stop.sh@@ -0,0 +1,18 @@+#!/bin/sh+# Kiro CLI stop hook (v2: stop; v3: Stop).+# Forwards the event JSON to the ai-memory server, fire-and-forget.+# Print nothing: on the v2 engine a stop hook's stdout can carry a+# {"decision":"block"} verdict that would re-prompt the model, so a+# capture-only hook must keep stdout empty and exit 0.+_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=kiro-cli${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kiro-cli/user-prompt-submit.ps1 b/hooks/kiro-cli/user-prompt-submit.ps1new file mode 100644index 00000000..b8e1553e--- /dev/null+++ b/hooks/kiro-cli/user-prompt-submit.ps1@@ -0,0 +1,6 @@+# Kiro CLI user-prompt hook (v2: userPromptSubmit; v3: UserPromptSubmit).+# Capture only — the handoff is injected by session-start.ps1. Print+# nothing: exit-0 stdout would be added to the conversation context.+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "user-prompt" -Agent "kiro-cli"+exit 0diff --git a/hooks/kiro-cli/user-prompt-submit.sh b/hooks/kiro-cli/user-prompt-submit.shnew file mode 100755index 00000000..2877d3d9--- /dev/null+++ b/hooks/kiro-cli/user-prompt-submit.sh@@ -0,0 +1,18 @@+#!/bin/sh+# Kiro CLI user-prompt hook (v2: userPromptSubmit; v3: UserPromptSubmit).+# Forwards the event JSON to the ai-memory server, fire-and-forget. The+# handoff is injected by session-start.sh — both Kiro engines add that+# hook's stdout to the agent context, so this hook only captures. Print+# nothing: exit-0 stdout would be added to the conversation context.+_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=user-prompt&agent=kiro-cli${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.shindex 337563f4..e86f9c62 100755--- a/scripts/install-hooks.sh+++ b/scripts/install-hooks.sh@@ -10,7 +10,7 @@# | bash -s -- --agent claude-code## Options:-# --agent <claude-code|codex|cursor|gemini-cli|kimi-code|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi>+# --agent <claude-code|codex|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,9 +46,11 @@ while [[ $# -gt 0 ]]; dodonecase "$AGENT" in- claude-code|codex|cursor|gemini-cli|kimi-code|antigravity-cli|grok|opencode|openclaw|omp|pi|oh-my-pi) ;;+ claude-code|codex|cursor|gemini-cli|kimi-code|kiro-cli|antigravity-cli|grok|opencode|openclaw|omp|pi|oh-my-pi) ;;+ # Both Kiro engine selections stage the same hooks/kiro-cli bundle.+ kiro|kiro-cli-v3|kiro-v3) AGENT="kiro-cli" ;;*)- echo "unsupported agent: $AGENT (expected claude-code | codex | cursor | gemini-cli | kimi-code | antigravity-cli | grok | opencode | openclaw | omp | pi | oh-my-pi)" >&2+ 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)" >&2exit 64 ;;esac@@ -97,6 +99,19 @@ if [[ "$AGENT" == "kimi-code" ]]; thenSCRIPTS+=("subagent-start" "subagent-stop")fi+# kiro-cli's hook vocabulary is exactly five events on both engines —+# no pre-compact/session-end equivalents exist, so fetching them would+# 404 and abort the install.+if [[ "$AGENT" == "kiro-cli" ]]; then+ SCRIPTS=(+ "session-start"+ "user-prompt-submit"+ "pre-tool-use"+ "post-tool-use"+ "stop"+ )+fi+DEST="$TO/$AGENT"mkdir -p "$DEST"