Skip to content

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

Rust

fix(workstream): harden explicit Kiro v2 support

AkitaOnRailseb05a773c77f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 76fdcfe5..ce568cfa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added explicit Kiro CLI v2 managed-workstream launches through `ai-memory run
+ kiro` / `kiro-cli`, including native `--resume-id` reuse, `$KIRO_HOME`
+ discovery, v2 `--yolo` translation, read-only visible-event import, and
+ checkout-scoped UUID/metadata validation. Non-v2 engines pass through
+ without session injection. Kiro remains outside bare automatic selection
+ until a logged-in current-format acceptance run is available, and v3 managed
+ sessions remain unsupported (#356).
- Added verified Kiro CLI v2 lifecycle hooks. CamelCase hooks merge into
existing agent configs, honor `$KIRO_HOME`, preserve unrelated hooks and
per-agent project strategies, fail before changing any target when one is
diff --git a/README.md b/README.md
index 8ec8d9d2..9a703e8e 100644
--- a/README.md
+++ b/README.md
@@ -31,14 +31,14 @@
| Oh My Pi / OMP | Supported | Use `--client omp` / `--agent omp` (or `oh-my-pi`) for native `.omp` MCP config + TypeScript extension; generated extension enforces capture exclusions. |
| Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory.ts` extension provides lifecycle capture and an HTTP MCP bridge; generated extension enforces capture exclusions. |
| Crush | Managed-only | `ai-memory run crush` resumes its project-local session database and supplies portable context through a temporary supported global-context file; no lifecycle-hook installer is provided. |
-| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok Build CLI, and Antigravity CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). |
+| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI v2, OMP, Grok Build CLI, and Antigravity CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). |
| Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. |
| OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. |
| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation. `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; conversation text is not decoded, so the ledger for this harness comes from hook capture. |
| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no hook handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). |
| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |
| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. |
-| Kiro CLI | Supported (v2) | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges verified v2 hooks into existing agent configs, honors `$KIRO_HOME`, preserves unrelated entries, and injects pending handoffs through `agentSpawn` stdout. Kiro v3 hook capture is not yet supported because its command-input payload is undocumented. Managed workstreams are tracked separately. |
+| Kiro CLI | Supported (v2) | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges verified v2 hooks into existing agent configs, honors `$KIRO_HOME`, preserves unrelated entries, and injects pending handoffs through `agentSpawn` stdout. Explicit `ai-memory run kiro` adds v2 managed resume; it is not in bare automatic selection pending a logged-in current-format acceptance run. Kiro v3 hooks and managed sessions remain unsupported. |
| VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). |
| Zed | MCP-only | Native remote MCP under `context_servers` in Zed's user `settings.json`; no lifecycle hooks or managed-workstream support. |
| Hermes Agent | Community | Core hook ingestion recognizes `agent=hermes` and Hermes' documented shell-hook `tool_name` / `tool_input` payload for concrete session attribution, tool-family titles, and capture exclusions. A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available, but no first-party installer is shipped; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. Hermes ignores session-start hook stdout, so recover handoffs through MCP. |
@@ -74,7 +74,7 @@ priors are at the [bottom](#influences-and-prior-art).
and full-ledger search. Delivered packets are origin-marked; Claude transcript
import rejects a packet that Claude persisted and read back through a tool.
`ai-memory run` with no harness continues the newest usable Claude Code,
- Codex, OpenCode, Pi, Crush, Kimi Code, or Kiro CLI session for this checkout.
+ Codex, OpenCode, Pi, Crush, or Kimi Code session for this checkout.
On first
explicit use, an interactive launcher can adopt a previous session from the
same checkout; later switches cannot select unrelated native history. Native
@@ -238,8 +238,8 @@ priors are at the [bottom](#influences-and-prior-art).
the workstream immediately. If a linked native transcript was deleted,
ai-memory detects the orphan before launch and starts fresh; `--fresh` forces
that recovery for one harness. Managed mode currently covers Claude Code,
- Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok Build CLI, and Antigravity
- CLI; direct harness launches remain unchanged. See
+ Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI v2, OMP, Grok Build CLI, and
+ Antigravity CLI; direct harness launches remain unchanged. See
[Managed cross-harness workstreams](docs/managed-workstreams.md).
- **"Just put me back where I was."** From any directory, with no name to
type and no list to read:
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 542ac38d..0b7fed99 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -234,6 +234,9 @@ pub enum RunHarnessChoice {
/// Moonshot AI Kimi Code.
#[value(name = "kimi", alias = "kimi-code", alias = "kimi-cli")]
Kimi,
+ /// Amazon Kiro CLI (v2 engine).
+ #[value(name = "kiro", alias = "kiro-cli")]
+ Kiro,
/// Grok Build CLI (xAI).
#[value(alias = "grok-build")]
Grok,
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 203cf3ab..10633de3 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -16,8 +16,9 @@ use ai_memory_core::{
use ai_memory_workstream::{
ExportedTranscript, LaunchMode, LaunchPlan, ManagedHarness, NativeSessionCandidate,
allows_native_session_adoption, apply_yolo, build_launch_plan, discover_native_session,
- export_transcript, has_native_session_selector, inspect_repository, list_native_sessions,
- native_session_exists, wait_for_transcript_flush,
+ export_transcript, has_native_session_selector, inspect_repository,
+ kiro_selects_non_default_engine, list_native_sessions, native_session_exists,
+ wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
@@ -36,14 +37,13 @@ const PREPARE_BUSY_RETRY_INTERVAL: Duration = Duration::from_millis(250);
const IMPORT_BATCH_EVENTS: usize = 400;
const IMPORT_BATCH_BYTES: usize = 1024 * 1024;
const ADOPTION_CANDIDATE_LIMIT: usize = 8;
-const AUTO_HARNESSES: [ManagedHarness; 7] = [
+const AUTO_HARNESSES: [ManagedHarness; 6] = [
ManagedHarness::Claude,
ManagedHarness::Codex,
ManagedHarness::OpenCode,
ManagedHarness::Pi,
ManagedHarness::Crush,
ManagedHarness::Kimi,
- ManagedHarness::Kiro,
];
#[derive(Debug, Clone)]
@@ -642,7 +642,7 @@ fn filter_usable_auto_sessions(
fn no_auto_session_error() -> anyhow::Error {
anyhow!(
- "no Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, or Kiro CLI session was found for this directory; start one explicitly with `ai-memory run claude`, `ai-memory run codex`, `ai-memory run opencode`, `ai-memory run pi`, `ai-memory run crush`, `ai-memory run kimi`, or `ai-memory run kiro`"
+ "no Claude Code, Codex, OpenCode, Pi, Crush, or Kimi Code session was found for this directory; start one explicitly with `ai-memory run claude`, `ai-memory run codex`, `ai-memory run opencode`, `ai-memory run pi`, `ai-memory run crush`, or `ai-memory run kimi`"
)
}
@@ -1232,6 +1232,7 @@ const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {
RunHarnessChoice::Crush => ManagedHarness::Crush,
RunHarnessChoice::Omp => ManagedHarness::Omp,
RunHarnessChoice::Kimi => ManagedHarness::Kimi,
+ RunHarnessChoice::Kiro => ManagedHarness::Kiro,
RunHarnessChoice::Grok => ManagedHarness::Grok,
RunHarnessChoice::Antigravity => ManagedHarness::Antigravity,
}
@@ -1245,6 +1246,7 @@ const fn managed_harness_from_agent(agent: AgentKind) -> Option<ManagedHarness>
AgentKind::Pi => Some(ManagedHarness::Pi),
AgentKind::Crush => Some(ManagedHarness::Crush),
AgentKind::KimiCode => Some(ManagedHarness::Kimi),
+ AgentKind::KiroCli => Some(ManagedHarness::Kiro),
AgentKind::Grok => Some(ManagedHarness::Grok),
AgentKind::AntigravityCli => Some(ManagedHarness::Antigravity),
_ => None,
diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rs
index 290ce0e8..a61de986 100644
--- a/crates/ai-memory-hooks/src/workstream.rs
+++ b/crates/ai-memory-hooks/src/workstream.rs
@@ -136,6 +136,7 @@ async fn prepare_run(
| AgentKind::Crush
| AgentKind::Omp
| AgentKind::KimiCode
+ | AgentKind::KiroCli
| AgentKind::Grok
| AgentKind::AntigravityCli
) {
@@ -144,14 +145,13 @@ async fn prepare_run(
"managed run requires a supported command-line harness",
);
}
- const AUTO_AGENTS: [AgentKind; 7] = [
+ const AUTO_AGENTS: [AgentKind; 6] = [
AgentKind::ClaudeCode,
AgentKind::Codex,
AgentKind::OpenCode,
AgentKind::Pi,
AgentKind::Crush,
AgentKind::KimiCode,
- AgentKind::KiroCli,
];
if request.automatic_harness
&& (!AUTO_AGENTS.contains(&request.agent)
@@ -897,6 +897,56 @@ mod tests {
assert_eq!(automatic.status(), StatusCode::OK);
}
+ #[tokio::test]
+ async fn kiro_is_accepted_explicitly_but_not_in_the_automatic_pool() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+
+ let explicit = prepare_run(
+ State(state.clone()),
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "managed".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::KiroCli,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ workstream: None,
+ new_workstream: None,
+ lease_owner: "explicit".into(),
+ }),
+ )
+ .await;
+ assert_eq!(explicit.status(), StatusCode::OK);
+ let body = to_bytes(explicit.into_body(), 64 * 1024).await.unwrap();
+ let prepared: PrepareManagedRunResponse = serde_json::from_slice(&body).unwrap();
+ assert_eq!(prepared.resolved_agent, Some(AgentKind::KiroCli));
+
+ let automatic = prepare_run(
+ State(state),
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "managed".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::KiroCli,
+ automatic_harness: true,
+ available_agents: vec![AgentKind::KiroCli],
+ workstream: None,
+ new_workstream: None,
+ lease_owner: "automatic".into(),
+ }),
+ )
+ .await;
+ assert_eq!(automatic.status(), StatusCode::BAD_REQUEST);
+ }
+
#[tokio::test]
async fn grok_is_accepted_explicitly_but_not_in_the_automatic_pool() {
let temp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rs
index aeb75d1e..2e9a1800 100644
--- a/crates/ai-memory-workstream/src/harness.rs
+++ b/crates/ai-memory-workstream/src/harness.rs
@@ -24,6 +24,8 @@ pub enum ManagedHarness {
Omp,
/// Moonshot AI Kimi Code.
Kimi,
+ /// Amazon Kiro CLI (v2 engine).
+ Kiro,
/// Grok Build CLI (xAI).
Grok,
/// Google Antigravity CLI (`agy`).
@@ -42,6 +44,7 @@ impl ManagedHarness {
"crush" => Some(Self::Crush),
"omp" | "oh-my-pi" => Some(Self::Omp),
"kimi" | "kimi-code" | "kimi-cli" => Some(Self::Kimi),
+ "kiro" | "kiro-cli" => Some(Self::Kiro),
"grok" | "grok-build" => Some(Self::Grok),
"antigravity" | "antigravity-cli" | "agy" => Some(Self::Antigravity),
_ => None,
@@ -59,6 +62,7 @@ impl ManagedHarness {
Self::Crush => AgentKind::Crush,
Self::Omp => AgentKind::Omp,
Self::Kimi => AgentKind::KimiCode,
+ Self::Kiro => AgentKind::KiroCli,
Self::Grok => AgentKind::Grok,
Self::Antigravity => AgentKind::AntigravityCli,
}
@@ -75,6 +79,7 @@ impl ManagedHarness {
Self::Crush => "crush",
Self::Omp => "omp",
Self::Kimi => "kimi",
+ Self::Kiro => "kiro-cli",
Self::Grok => "grok",
Self::Antigravity => "agy",
}
@@ -91,6 +96,7 @@ impl ManagedHarness {
Self::Crush => "crush",
Self::Omp => "omp",
Self::Kimi => "kimi",
+ Self::Kiro => "kiro",
Self::Grok => "grok",
Self::Antigravity => "antigravity",
}
@@ -243,6 +249,15 @@ pub fn build_launch_plan(
expected = Some(id.to_string());
}
}
+ ManagedHarness::Kiro => {
+ // Kiro assigns UUIDs to fresh sessions. A linked v2 session
+ // can be selected exactly; a fresh one is discovered after
+ // the native process exits.
+ if let Some(id) = linked_session_id {
+ args.extend([OsString::from("--resume-id"), OsString::from(id)]);
+ expected = Some(id.to_string());
+ }
+ }
ManagedHarness::Grok => {
let id = linked_session_id
.map(str::to_owned)
@@ -289,6 +304,13 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {
ManagedHarness::Crush => Some("--yolo"),
ManagedHarness::Omp => None,
ManagedHarness::Kimi => Some("--yolo"),
+ ManagedHarness::Kiro => {
+ if kiro_selects_non_default_engine(args) {
+ None
+ } else {
+ Some("--trust-all-tools")
+ }
+ }
ManagedHarness::Grok => Some("--yolo"),
ManagedHarness::Antigravity => Some("--dangerously-skip-permissions"),
};
@@ -300,6 +322,9 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {
// `--always-approve`; either spelling satisfies the request.
let present: &[&str] = match harness {
ManagedHarness::Kimi => &["--yolo", "-y", "--yes", "--auto-approve", "--auto"],
+ // A narrower native trust set is an explicit user choice and must
+ // never be widened by the wrapper.
+ ManagedHarness::Kiro => &["--trust-all-tools", "-a", "--trust-tools"],
ManagedHarness::Grok => &["--yolo", "--always-approve"],
_ => &[flag],
};
@@ -326,6 +351,7 @@ fn noninteractive_invocation(harness: ManagedHarness, args: &[OsString]) -> bool
ManagedHarness::Crush => first_arg_is(args, "run"),
ManagedHarness::Pi | ManagedHarness::Omp => has_flag(args, &["--print", "-p"]),
ManagedHarness::Kimi => has_flag(args, &["--prompt", "-p"]),
+ ManagedHarness::Kiro => has_flag(args, &["--no-interactive"]),
ManagedHarness::Grok => {
has_flag(args, &["--single", "-p", "--prompt-file", "--prompt-json"])
}
@@ -500,6 +526,36 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {
"__plugin_run_node",
]
.as_slice(),
+ // Every root command except `chat` in kiro-cli 2.16.0. Bare and
+ // flags-only invocations open chat and remain session-bearing.
+ ManagedHarness::Kiro => [
+ "debug",
+ "settings",
+ "setup",
+ "update",
+ "diagnostic",
+ "init",
+ "theme",
+ "issue",
+ "login",
+ "logout",
+ "whoami",
+ "profile",
+ "user",
+ "doctor",
+ "launch",
+ "quit",
+ "restart",
+ "integrations",
+ "translate",
+ "dashboard",
+ "mcp",
+ "inline",
+ "agent",
+ "acp",
+ "help",
+ ]
+ .as_slice(),
// `agent` covers the stdio/headless/serve/leader runners, which manage
// their own session lifecycles and must not receive selectors.
ManagedHarness::Grok => [
@@ -540,7 +596,11 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {
]
.as_slice(),
};
- let first = args.first().and_then(|arg| arg.to_str());
+ let first = if harness == ManagedHarness::Kiro {
+ kiro_root_subcommand(args)
+ } else {
+ args.first().and_then(|arg| arg.to_str())
+ };
if first.is_some_and(|value| utility.contains(&value)) {
LaunchMode::Passthrough
} else {
@@ -595,6 +655,10 @@ pub fn has_native_session_selector(harness: ManagedHarness, args: &[OsString]) -
"-C",
],
),
+ ManagedHarness::Kiro => has_flag(
+ args,
+ &["--resume", "-r", "--resume-id", "--resume-picker", "--list"],
+ ),
// A bare `--resume` opens Grok's native session picker; that is still
// an explicit user choice. `--fork-session` modifies how the explicit
// resume/continue selector behaves and never appears alone.
@@ -639,6 +703,7 @@ fn explicit_session_id(harness: ManagedHarness, args: &[OsString]) -> Option<Str
// A bare `--session`/`--resume` opens the picker: `flag_value`
// returns `None` when no value follows, as intended.
ManagedHarness::Kimi => flag_value(args, &["--session", "-S", "--resume", "-r"]),
+ ManagedHarness::Kiro => flag_value(args, &["--resume-id"]),
ManagedHarness::Grok => flag_value(args, &["--resume", "-r", "--session-id", "-s"]),
// A bare `--continue` names no conversation: the id is only known
// after the fact, from the conversation store.
@@ -650,6 +715,27 @@ fn first_arg_is(args: &[OsString], expected: &str) -> bool {
args.first().and_then(|value| value.to_str()) == Some(expected)
}
+fn kiro_root_subcommand(args: &[OsString]) -> Option<&str> {
+ let mut index = 0;
+ while index < args.len() {
+ let value = args.get(index)?.to_str()?;
+ if matches!(value, "--agent" | "--resume-id") {
+ index += 2;
+ continue;
+ }
+ if value.starts_with("--agent=") || value.starts_with("--resume-id=") {
+ index += 1;
+ continue;
+ }
+ if value.starts_with('-') {
+ index += 1;
+ continue;
+ }
+ return Some(value);
+ }
+ None
+}
+
fn has_flag(args: &[OsString], names: &[&str]) -> bool {
args.iter().any(|arg| {
let Some(value) = arg.to_str() else {
@@ -724,6 +810,7 @@ fn environment_session_dir_with(
ManagedHarness::Omp => value("PI_CODING_AGENT_DIR").map(|dir| dir.join("sessions")),
// Sessions live under `<KIMI_CODE_HOME>/sessions/<bucket>/<id>/`.
ManagedHarness::Kimi => value("KIMI_CODE_HOME").map(|dir| dir.join("sessions")),
+ ManagedHarness::Kiro => value("KIRO_HOME").map(|dir| dir.join("sessions/cli")),
// Sessions live under `<GROK_HOME>/sessions/<encoded-cwd>/<id>/`.
ManagedHarness::Grok => value("GROK_HOME").map(|dir| dir.join("sessions")),
// `agy` exposes no environment override for its conversation store.
@@ -1285,6 +1372,147 @@ mod tests {
);
}
+ #[test]
+ fn kiro_names_parse_to_the_v2_adapter() {
+ for name in ["kiro", "kiro-cli"] {
+ assert_eq!(ManagedHarness::from_name(name), Some(ManagedHarness::Kiro));
+ }
+ assert_eq!(ManagedHarness::Kiro.executable(), "kiro-cli");
+ }
+
+ #[test]
+ fn kiro_fresh_and_linked_launches_preserve_native_arguments() {
+ let fresh = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ vec![OsString::from("--model"), OsString::from("sonnet")],
+ None,
+ )
+ .unwrap();
+ assert_eq!(strings(&fresh.args), ["--model", "sonnet"]);
+ assert_eq!(fresh.expected_session_id, None);
+
+ let linked = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ vec![OsString::from("--model"), OsString::from("sonnet")],
+ Some("3f6d1c2a-0000-4000-8000-000000000aaa"),
+ )
+ .unwrap();
+ assert_eq!(
+ strings(&linked.args),
+ [
+ "--model",
+ "sonnet",
+ "--resume-id",
+ "3f6d1c2a-0000-4000-8000-000000000aaa"
+ ]
+ );
+ }
+
+ #[test]
+ fn kiro_explicit_selectors_and_non_v2_engines_are_never_overridden() {
+ for native in [
+ vec![OsString::from("--resume")],
+ vec![
+ OsString::from("--resume-id"),
+ OsString::from("3f6d1c2a-0000-4000-8000-000000000aaa"),
+ ],
+ vec![OsString::from("--resume-picker")],
+ vec![OsString::from("--v3")],
+ vec![OsString::from("--agent-engine"), OsString::from("v1")],
+ ] {
+ let plan = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ native.clone(),
+ Some("3f6d1c2a-0000-4000-8000-000000000bbb"),
+ )
+ .unwrap();
+ assert_eq!(plan.args, native, "{native:?} must stay byte-identical");
+ }
+ }
+
+ #[test]
+ fn kiro_utilities_are_passthrough_even_after_global_flags() {
+ for native in [
+ vec![OsString::from("login")],
+ vec![OsString::from("-vv"), OsString::from("doctor")],
+ vec![
+ OsString::from("--agent"),
+ OsString::from("reviewer"),
+ OsString::from("mcp"),
+ ],
+ ] {
+ let plan = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ native.clone(),
+ Some("3f6d1c2a-0000-4000-8000-000000000aaa"),
+ )
+ .unwrap();
+ assert_eq!(plan.mode, LaunchMode::Passthrough, "{native:?}");
+ assert_eq!(plan.args, native);
+ }
+ assert_eq!(
+ build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ vec![OsString::from("chat")],
+ None,
+ )
+ .unwrap()
+ .mode,
+ LaunchMode::Session
+ );
+ }
+
+ #[test]
+ fn kiro_yolo_maps_only_to_the_v2_permission_flag() {
+ let mut args = Vec::new();
+ apply_yolo(ManagedHarness::Kiro, &mut args);
+ assert_eq!(strings(&args), ["--trust-all-tools"]);
+
+ for already in ["--trust-all-tools", "-a", "--trust-tools=fs_read"] {
+ let mut args = vec![OsString::from(already)];
+ apply_yolo(ManagedHarness::Kiro, &mut args);
+ assert_eq!(strings(&args), [already]);
+ }
+
+ let mut v3 = vec![OsString::from("--v3")];
+ apply_yolo(ManagedHarness::Kiro, &mut v3);
+ assert_eq!(strings(&v3), ["--v3"]);
+ }
+
+ #[test]
+ fn kiro_noninteractive_and_one_shot_modes_are_passthrough() {
+ for native in [
+ vec![OsString::from("--no-interactive"), OsString::from("hi")],
+ vec![OsString::from("--list-sessions")],
+ vec![OsString::from("--list-models")],
+ vec![
+ OsString::from("--delete-session"),
+ OsString::from("3f6d1c2a-0000-4000-8000-000000000aaa"),
+ ],
+ ] {
+ assert_eq!(
+ build_launch_plan(ManagedHarness::Kiro, None, native, None)
+ .unwrap()
+ .mode,
+ LaunchMode::Passthrough
+ );
+ }
+ }
+
+ #[test]
+ fn kiro_home_override_points_at_the_cli_session_store() {
+ let get = |name: &str| (name == "KIRO_HOME").then(|| OsString::from("/stores/kiro"));
+ assert_eq!(
+ environment_session_dir_with(ManagedHarness::Kiro, get).as_deref(),
+ Some(std::path::Path::new("/stores/kiro/sessions/cli"))
+ );
+ }
+
#[test]
fn antigravity_names_parse_to_one_variant() {
for name in ["antigravity", "antigravity-cli", "agy"] {
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index 80df779d..ca2f8fd6 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -6,7 +6,7 @@ mod transcript;
pub use harness::{
LaunchMode, LaunchPlan, ManagedHarness, allows_native_session_adoption, apply_yolo,
- build_launch_plan, has_native_session_selector,
+ build_launch_plan, has_native_session_selector, kiro_selects_non_default_engine,
};
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index bb33ecc7..0ff9f787 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -51,8 +51,9 @@ struct FileCursor {
offset: u64,
/// Hash of every committed byte through `offset`. Kimi Code and Grok can
/// rewrite their journals in place (Kimi on fork/compaction/resume, Grok
- /// on rewind), so those adapters validate this prefix before trusting the
- /// byte offset. Other JSONL adapters remain offset-only.
+ /// on rewind); Kiro's append-only behavior is not documented. Those
+ /// adapters validate this prefix before trusting the byte offset. Other
+ /// JSONL adapters remain offset-only.
#[serde(default, skip_serializing_if = "Option::is_none")]
prefix_sha256: Option<String>,
}
@@ -60,7 +61,10 @@ struct FileCursor {
/// Harnesses whose JSONL journal can be rewritten in place, requiring
/// prefix-validated cursors and content-hash record ids.
const fn journal_rewrites_in_place(harness: ManagedHarness) -> bool {
- matches!(harness, ManagedHarness::Kimi | ManagedHarness::Grok)
+ matches!(
+ harness,
+ ManagedHarness::Kimi | ManagedHarness::Kiro | ManagedHarness::Grok
+ )
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -338,6 +342,13 @@ fn export_jsonl(
&mut events,
&mut losses,
),
+ ManagedHarness::Kiro => parse_kiro(
+ &value,
+ native_session_id,
+ &record_id,
+ &mut events,
+ &mut losses,
+ ),
ManagedHarness::Grok => parse_grok(
&value,
native_session_id,
@@ -369,17 +380,6 @@ fn export_jsonl(
})
}
-/// Journals the harness may rewrite in place (fork/compaction/resume),
-/// where a byte-offset cursor would silently change meaning: the adapter
-/// validates a prefix hash before trusting the offset and derives record
-/// ids from the raw line bytes. Kimi is a confirmed rewriter; Kiro's
-/// event stream is not verified append-only, so it gets the same
-/// tolerance defensively (a rewrite resets the cursor and the stable
-/// line-hash record ids dedupe the replay server-side).
-const fn rewrite_tolerant_journal(harness: ManagedHarness) -> bool {
- matches!(harness, ManagedHarness::Kimi | ManagedHarness::Kiro)
-}
-
fn hash_file_prefix(file: &mut File, len: u64) -> Result<Option<Sha256>> {
file.seek(SeekFrom::Start(0))?;
let mut hasher = Sha256::new();
@@ -1766,13 +1766,16 @@ fn locate_session_file(
id: &str,
) -> Result<Option<PathBuf>> {
let root = session_root(harness, home, session_dir);
+ if !valid_native_session_id(id) {
+ return Ok(None);
+ }
if harness == ManagedHarness::Antigravity {
// The conversation id is the file name, so no scan is ever needed.
if Uuid::parse_str(id).is_err() {
return Ok(None);
}
let exact = root.join(format!("{id}.db"));
- return Ok(exact.is_file().then_some(exact));
+ return Ok(session_path_matches(harness, &exact, id, cwd)?.then_some(exact));
}
if harness == ManagedHarness::Claude {
let encoded = cwd.to_string_lossy().replace('/', "-");
@@ -1788,34 +1791,49 @@ fn locate_session_file(
if let Ok(buckets) = fs::read_dir(&root) {
for bucket in buckets.flatten() {
let candidate = bucket.path().join(id).join("agents/main/wire.jsonl");
- if candidate.is_file() {
+ if session_path_matches(harness, &candidate, id, cwd)? {
return Ok(Some(candidate));
}
}
}
}
if harness == ManagedHarness::Kiro {
- // The store is flat: `<root>/<session-id>.jsonl`.
+ // The store is flat and shared by every checkout. Require both the
+ // UUID file name and its sibling metadata to identify this checkout;
+ // a server-linked id is untrusted input and must not select another
+ // project's transcript.
+ if Uuid::parse_str(id).is_err() {
+ return Ok(None);
+ }
let exact = root.join(format!("{id}.jsonl"));
- if exact.is_file() {
+ if session_path_matches(harness, &exact, id, cwd)? {
return Ok(Some(exact));
}
+ return Ok(None);
}
let mut files = collect_files(&root, |path| transcript_file(harness, path))?;
files.sort_by_key(|path| temporary_transcript(path));
- for path in &files {
- if path.to_string_lossy().contains(id) {
- return Ok(Some(path.clone()));
- }
- }
for path in files.into_iter().take(2_000) {
- if session_header(harness, &path)?.is_some_and(|(found, _)| found == id) {
+ if session_path_matches(harness, &path, id, cwd)? {
return Ok(Some(path));
}
}
Ok(None)
}
+fn session_path_matches(
+ harness: ManagedHarness,
+ path: &Path,
+ id: &str,
+ cwd: &Path,
+) -> Result<bool> {
+ if !path.is_file() {
+ return Ok(false);
+ }
+ Ok(session_header(harness, path)?
+ .is_some_and(|(found, recorded_cwd)| found == id && same_path(&recorded_cwd, cwd)))
+}
+
fn transcript_file(harness: ManagedHarness, path: &Path) -> bool {
if harness == ManagedHarness::Grok {
// Only the conversation journal. `events.jsonl`, `updates.jsonl`, and
@@ -1833,6 +1851,13 @@ fn transcript_file(harness: ManagedHarness, path: &Path) -> bool {
.and_then(|name| name.to_str())
== Some("main");
}
+ if harness == ManagedHarness::Kiro {
+ return path.extension().is_some_and(|ext| ext == "jsonl")
+ && path
+ .file_stem()
+ .and_then(|stem| stem.to_str())
+ .is_some_and(|stem| Uuid::parse_str(stem).is_ok());
+ }
if harness == ManagedHarness::Antigravity {
// One SQLite database per conversation, named by its id.
return path.extension().is_some_and(|ext| ext == "db");
@@ -1853,6 +1878,9 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(String
if harness == ManagedHarness::Kimi {
return kimi_session_header(path);
}
+ if harness == ManagedHarness::Kiro {
+ return kiro_session_header(path);
+ }
if harness == ManagedHarness::Grok {
return grok_session_header(path);
}
@@ -1888,6 +1916,7 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(String
ManagedHarness::OpenCode
| ManagedHarness::Crush
| ManagedHarness::Kimi
+ | ManagedHarness::Kiro
| ManagedHarness::Grok
| ManagedHarness::Antigravity => (None, None),
};
@@ -1923,6 +1952,34 @@ fn kimi_session_header(path: &Path) -> Result<Option<(String, PathBuf)>> {
Ok(Some((id.to_string(), PathBuf::from(cwd))))
}
+/// Kiro v2 sessions pair a flat `<uuid>.jsonl` event stream with
+/// `<uuid>.json` metadata. Missing, malformed, or mismatched metadata makes
+/// the transcript ineligible for discovery or resume.
+fn kiro_session_header(path: &Path) -> Result<Option<(String, PathBuf)>> {
+ let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
+ return Ok(None);
+ };
+ if Uuid::parse_str(stem).is_err() {
+ return Ok(None);
+ }
+ let Ok(raw) = fs::read_to_string(path.with_extension("json")) else {
+ return Ok(None);
+ };
+ let Ok(metadata) = serde_json::from_str::<Value>(&raw) else {
+ return Ok(None);
+ };
+ let Some(id) = metadata.get("session_id").and_then(Value::as_str) else {
+ return Ok(None);
+ };
+ if id != stem {
+ return Ok(None);
+ }
+ let Some(cwd) = metadata.get("cwd").and_then(Value::as_str) else {
+ return Ok(None);
+ };
+ Ok(Some((id.to_string(), PathBuf::from(cwd))))
+}
+
/// Grok sessions are self-describing in `<session-dir>/summary.json`
/// (`info.id` + `info.cwd`). The chat-history journal carries no session id or
/// cwd, and the bucket directory name is a URL-encoded cwd that is never
@@ -2258,6 +2315,7 @@ fn session_root(harness: ManagedHarness, home: &Path, override_dir: Option<&Path
ManagedHarness::Crush => home.join(".crush"),
ManagedHarness::Omp => home.join(".omp/agent/sessions"),
ManagedHarness::Kimi => home.join(".kimi-code/sessions"),
+ ManagedHarness::Kiro => home.join(".kiro/sessions/cli"),
ManagedHarness::Grok => home.join(".grok/sessions"),
ManagedHarness::Antigravity => home.join(".gemini/antigravity-cli/conversations"),
}
@@ -2353,6 +2411,9 @@ fn valid_native_session_id(value: &str) -> bool {
!value.trim().is_empty()
&& value.len() <= MAX_NATIVE_SESSION_ID_BYTES
&& !value.starts_with('-')
+ && value != "."
+ && value != ".."
+ && !value.contains(['/', '\\'])
&& !value.chars().any(char::is_control)
}
@@ -2423,6 +2484,7 @@ mod tests {
ManagedHarness::OpenCode
| ManagedHarness::Crush
| ManagedHarness::Kimi
+ | ManagedHarness::Kiro
| ManagedHarness::Grok
| ManagedHarness::Antigravity => {
unreachable!()
@@ -2952,7 +3014,16 @@ mod tests {
"session_bbb",
)
.unwrap();
- assert_eq!(found.as_deref(), Some(wire_b.as_path()));
+ assert!(found.is_none());
+ let found_for_other = locate_session_file(
+ ManagedHarness::Kimi,
+ temp.path(),
+ &other,
+ Some(root.path()),
+ "session_bbb",
+ )
+ .unwrap();
+ assert_eq!(found_for_other.as_deref(), Some(wire_b.as_path()));
assert!(
native_session_exists(
ManagedHarness::Kimi,
@@ -3599,6 +3670,200 @@ mod tests {
assert!(error.contains("hook capture"), "{error}");
}
+ const KIRO_SESSION_A: &str = "3f6d1c2a-0000-4000-8000-000000000aaa";
+ const KIRO_SESSION_B: &str = "3f6d1c2a-0000-4000-8000-000000000bbb";
+
+ fn write_kiro_session(root: &Path, id: &str, cwd: &Path, lines: &[Value]) {
+ fs::write(
+ root.join(format!("{id}.json")),
+ json!({
+ "session_id": id,
+ "cwd": cwd,
+ "created_at": "2026-08-01T10:00:00Z",
+ "updated_at": "2026-08-01T10:05:00Z",
+ "title": "sanitized structural fixture",
+ "session_state": {"version": "v1", "conversation_metadata": {}}
+ })
+ .to_string(),
+ )
+ .unwrap();
+ let transcript = lines
+ .iter()
+ .map(|line| format!("{line}\n"))
+ .collect::<String>();
+ fs::write(root.join(format!("{id}.jsonl")), transcript).unwrap();
+ }
+
+ #[tokio::test]
+ async fn kiro_discovery_and_exact_lookup_are_checkout_scoped() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let other = temp.path().join("other");
+ let root = temp.path().join("kiro-sessions");
+ fs::create_dir_all(&cwd).unwrap();
+ fs::create_dir_all(&other).unwrap();
+ fs::create_dir_all(&root).unwrap();
+ write_kiro_session(&root, KIRO_SESSION_A, &cwd, &[]);
+ write_kiro_session(&root, KIRO_SESSION_B, &other, &[]);
+
+ let sessions =
+ list_native_sessions(ManagedHarness::Kiro, temp.path(), &cwd, Some(&root), 8)
+ .await
+ .unwrap();
+ assert_eq!(sessions.len(), 1);
+ assert_eq!(sessions[0].native_session_id, KIRO_SESSION_A);
+
+ assert_eq!(
+ locate_session_file(
+ ManagedHarness::Kiro,
+ temp.path(),
+ &cwd,
+ Some(&root),
+ KIRO_SESSION_A,
+ )
+ .unwrap()
+ .as_deref(),
+ Some(root.join(format!("{KIRO_SESSION_A}.jsonl")).as_path())
+ );
+ assert!(
+ locate_session_file(
+ ManagedHarness::Kiro,
+ temp.path(),
+ &cwd,
+ Some(&root),
+ KIRO_SESSION_B,
+ )
+ .unwrap()
+ .is_none()
+ );
+ assert!(
+ locate_session_file(
+ ManagedHarness::Kiro,
+ temp.path(),
+ &cwd,
+ Some(&root),
+ "../../outside",
+ )
+ .unwrap()
+ .is_none()
+ );
+ }
+
+ #[tokio::test]
+ async fn kiro_mismatched_metadata_never_becomes_resumable() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let root = temp.path().join("kiro-sessions");
+ fs::create_dir_all(&cwd).unwrap();
+ fs::create_dir_all(&root).unwrap();
+ fs::write(
+ root.join(format!("{KIRO_SESSION_A}.json")),
+ json!({"session_id": KIRO_SESSION_B, "cwd": cwd}).to_string(),
+ )
+ .unwrap();
+ fs::write(root.join(format!("{KIRO_SESSION_A}.jsonl")), "{}\n").unwrap();
+
+ assert!(
+ list_native_sessions(ManagedHarness::Kiro, temp.path(), &cwd, Some(&root), 8,)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ !native_session_exists(
+ ManagedHarness::Kiro,
+ temp.path(),
+ &cwd,
+ Some(&root),
+ KIRO_SESSION_A,
+ )
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn kiro_export_maps_only_visible_v1_records() {
+ let temp = tempfile::tempdir().unwrap();
+ let stream = temp.path().join(format!("{KIRO_SESSION_A}.jsonl"));
+ let records = [
+ json!({"version":"v1","kind":"Prompt","data":{"message_id":"m1","content":[{"kind":"text","data":"hello kiro"}],"meta":{"timestamp":1_700_000_000_000_i64}}}),
+ json!({"version":"v1","kind":"AssistantMessage","data":{"message_id":"m2","content":[
+ {"kind":"text","data":"visible answer"},
+ {"kind":"toolUse","data":{"name":"fs_read","tool_use_id":"call_1","input":{"path":"README.md"}}}
+ ]}}),
+ json!({"version":"v1","kind":"ToolResults","data":{"message_id":"m3","content":[
+ {"kind":"toolResult","data":{"tool_use_id":"call_1","content":[{"kind":"text","data":"result ok"}],"is_error":false}}
+ ]}}),
+ json!({"version":"v1","kind":"Prompt","data":{"message_id":"m4","content":[{"kind":"image","data":{"format":"png"}}]}}),
+ json!({"version":"v2","kind":"Prompt","data":{"message_id":"m5","content":[{"kind":"text","data":"future"}]}}),
+ ];
+ fs::write(
+ &stream,
+ records
+ .iter()
+ .map(|record| format!("{record}\n"))
+ .collect::<String>(),
+ )
+ .unwrap();
+
+ let export = export_jsonl(ManagedHarness::Kiro, &stream, KIRO_SESSION_A, None).unwrap();
+ assert_eq!(export.events.len(), 4);
+ assert_eq!(export.events[0].content, "hello kiro");
+ assert_eq!(export.events[0].role.as_deref(), Some("user"));
+ assert_eq!(
+ export.events[0].occurred_at.as_deref(),
+ Some("2023-11-14T22:13:20Z")
+ );
+ assert_eq!(export.events[1].content, "visible answer");
+ assert_eq!(export.events[2].kind, WorkstreamEventKind::ToolCall);
+ assert_eq!(export.events[3].content, "result ok");
+ assert!(
+ export
+ .losses
+ .iter()
+ .any(|loss| loss.contains("non-text content"))
+ );
+ assert!(
+ export
+ .losses
+ .iter()
+ .any(|loss| loss.contains("unsupported envelope version v2"))
+ );
+ }
+
+ #[test]
+ fn kiro_cursor_restarts_after_an_in_place_rewrite() {
+ let temp = tempfile::tempdir().unwrap();
+ let stream = temp.path().join(format!("{KIRO_SESSION_A}.jsonl"));
+ fs::write(
+ &stream,
+ format!(
+ "{}\n",
+ json!({"version":"v1","kind":"Prompt","data":{"message_id":"m1","content":[{"kind":"text","data":"first"}]}})
+ ),
+ )
+ .unwrap();
+ let first = export_jsonl(ManagedHarness::Kiro, &stream, KIRO_SESSION_A, None).unwrap();
+
+ fs::write(
+ &stream,
+ format!(
+ "{}\n",
+ json!({"version":"v1","kind":"Prompt","data":{"message_id":"m2","content":[{"kind":"text","data":"rewritten"}]}})
+ ),
+ )
+ .unwrap();
+ let rewritten = export_jsonl(
+ ManagedHarness::Kiro,
+ &stream,
+ KIRO_SESSION_A,
+ first.source_cursor.as_deref(),
+ )
+ .unwrap();
+ assert_eq!(rewritten.events.len(), 1);
+ assert_eq!(rewritten.events[0].content, "rewritten");
+ }
+
#[test]
fn file_uris_decode_on_both_platform_shapes() {
assert_eq!(
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 37756c6f..e5be8886 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -300,9 +300,9 @@ Top-line rules carved into the codebase:
## 15. Managed workstreams use a portable ledger, not native format conversion
Managed cross-harness continuity is explicitly opt-in through `ai-memory run`.
-Direct Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok Build CLI,
-and Antigravity CLI launches retain the existing hook and single-use handoff
-behavior. There is
+Direct Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI, OMP, Grok
+Build CLI, and Antigravity CLI launches retain the existing hook and single-use
+handoff behavior. There is
no process-global mode or manual harness switch: the wrapper selects the
current repository/worktree workstream and each adapter applies that harness's
native create/resume syntax.
diff --git a/docs/install.md b/docs/install.md
index ac4e5483..035f52e3 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -794,8 +794,12 @@ semantics. Add v3 only after real payload fixtures can exercise that boundary.
`ai-memory uninstall --only hooks --apply --yes` removes only exact ai-memory v2
entries from global agents and the current project's `.kiro/agents` directory;
-it leaves standalone v3 files untouched. Managed `ai-memory run kiro` support
-is tracked separately in [#356](https://github.com/akitaonrails/ai-memory/issues/356).
+it leaves standalone v3 files untouched. Explicit `ai-memory run kiro` (alias
+`kiro-cli`) manages the default v2 engine and honors `$KIRO_HOME`; Kiro stays
+outside no-argument automatic selection until its current event stream is
+validated in a logged-in real-harness acceptance run. `--v3`, `--mode`, and
+non-v2 `--agent-engine` invocations pass through without managed session
+injection. See [managed workstreams](managed-workstreams.md#native-adapter-behavior).
### OpenCode
diff --git a/docs/managed-harness-contributions.md b/docs/managed-harness-contributions.md
index c236e0bb..8646baaa 100644
--- a/docs/managed-harness-contributions.md
+++ b/docs/managed-harness-contributions.md
@@ -1,10 +1,10 @@
# Adding a managed harness
Managed-workstream support is narrower than MCP or lifecycle-hook support. This
-release can manage Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP,
-Grok Build CLI, and Antigravity CLI. Gemini CLI, Devin CLI, Cursor, and the
-other integrations in the README support matrix do not become managed merely
-because ai-memory can capture their hooks.
+release can manage Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI
+v2, OMP, Grok Build CLI, and Antigravity CLI. Gemini CLI, Devin CLI, Cursor, and
+the other integrations in the README support matrix do not become managed
+merely because ai-memory can capture their hooks.
A managed adapter must preserve a harness's real native session, deliver the
portable workstream delta exactly once, and import only visible history without
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 7f97e809..47ecad33 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -1,8 +1,8 @@
# Managed cross-harness workstreams
`ai-memory run` is an opt-in launcher that lets one logical coding session move
-between Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok
-Build CLI, and Antigravity CLI. Direct agent launches
+between Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI v2, OMP,
+Grok Build CLI, and Antigravity CLI. Direct agent launches
keep their existing ai-memory behavior. There is no global mode toggle and no
`switch` command: using `run` selects the current workstream and transparently
creates or resumes the correct native session for the requested harness.
@@ -17,6 +17,8 @@ ai-memory run codex --yolo
ai-memory run claude --model opus
# Kimi Code installs `kimi`; `kimi-cli` is accepted as a launcher alias
ai-memory run kimi-cli
+# Kiro's explicit managed adapter covers its default v2 engine
+ai-memory run kiro
# or omit the harness and continue the newest usable session automatically
ai-memory run
```
@@ -37,7 +39,7 @@ file, and the current checkout remain authoritative.
ai-memory run [--workspace NAME] [--project NAME]
[--workstream NAME | --new NAME] [--executable PATH]
[--yolo] [--fresh]
- [claude|codex|opencode|pi|crush|omp|kimi|grok|antigravity]
+ [claude|codex|opencode|pi|crush|omp|kimi|kiro|grok|antigravity]
[native arguments...]
```
@@ -118,13 +120,15 @@ directory, including automatic harness selection. `continue` therefore accepts
## Automatic harness selection
With no harness name, `ai-memory run` inspects checkout-local sessions for
-Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, and Kiro CLI. For an empty
-workstream it resumes
+Claude Code, Codex, OpenCode, Pi, Crush, and Kimi Code. For an empty workstream
+it resumes
the newest session automatically. For an established workstream, server state
takes precedence: ai-memory resumes the most recently linked harness that still
has a usable local session. It never chooses a newer but obsolete session from
-another harness merely because that file has a later timestamp. OMP, Grok, and
-Antigravity remain available explicitly but are not in the automatic pool.
+another harness merely because that file has a later timestamp. Kiro, OMP,
+Grok, and Antigravity remain available explicitly but are not in the automatic
+pool. Kiro joins only after a logged-in current-format acceptance run validates
+its checkout-local discovery and import behavior.
Bare mode accepts wrapper options but not harness-native arguments or
`--executable`, because their meaning depends on the selected harness. In a new
@@ -238,8 +242,8 @@ Pi and OMP `--session-dir` values and Crush `--data-dir` values are passed
through unchanged and used as the read-only import root. Native store
environment overrides are also honored:
`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `XDG_DATA_HOME`,
-`PI_CODING_AGENT_SESSION_DIR`, `PI_CODING_AGENT_DIR`, `KIMI_CODE_HOME`, and
-`GROK_HOME`.
+`PI_CODING_AGENT_SESSION_DIR`, `PI_CODING_AGENT_DIR`, `KIMI_CODE_HOME`,
+`KIRO_HOME`, and `GROK_HOME`.
The Pi-family adapter
also recognizes a complete `.jsonl.<nonce>.tmp` atomic-write file when a native
process exits before renaming it; incomplete final JSONL records are never
@@ -252,8 +256,8 @@ chooser.
the harness's native dangerous mode. The translation is Claude Code
`--dangerously-skip-permissions`, Codex
`--dangerously-bypass-approvals-and-sandbox`, OpenCode `--auto`, Pi `--approve`,
-Crush `--yolo`, Kimi Code `--yolo`, Grok Build CLI `--yolo` (equivalent to its
-`--always-approve` option), and Antigravity CLI
+Crush `--yolo`, Kimi Code `--yolo`, Kiro CLI v2 `--trust-all-tools`, Grok Build
+CLI `--yolo` (equivalent to its `--always-approve` option), and Antigravity CLI
`--dangerously-skip-permissions`. OMP currently needs no added flag. ai-memory
does not add a duplicate when the translated native flag is already present.
@@ -306,6 +310,21 @@ contract was verified against Kimi Code v0.29.0. The managed launcher accepts
`kimi`, `kimi-code`, and `kimi-cli`; all three resolve the installed `kimi`
executable.
+Kiro's explicit adapter covers only the default v2 engine. Official Kiro docs
+define UUID session IDs, checkout scoping, `--resume-id`, `$KIRO_HOME`, and the
+flat `$KIRO_HOME/sessions/cli/<uuid>.json` plus `<uuid>.jsonl` store. The current
+2.16.0 binary also exposes the v1 `Prompt`, `AssistantMessage`, and `ToolResults`
+event variants, but authentication prevented producing a new isolated live
+transcript during this audit. The parser therefore accepts only the known v1
+envelope, records unsupported versions as extraction loss, imports visible text
+and completed tool records only, and stays outside automatic selection until a
+logged-in current-format acceptance run is recorded. Exact lookups require a
+UUID, matching sibling `session_id`, and an exact canonical `cwd`; a linked ID
+cannot select another checkout's flat-store transcript. `--v3`, `--mode`, and a
+non-v2 `--agent-engine` select incompatible engines and pass through unchanged.
+The v2 `--yolo` translation is `--trust-all-tools`; an explicit narrower
+`--trust-tools` choice is never widened.
+
Grok needs no ai-memory hook installation for managed delivery either. Grok
ignores `SessionStart` stdout and its `UserPromptSubmit` hook is passive, so
the launcher fetches the bounded context packet from the server and passes it
@@ -398,7 +417,7 @@ process launch is fatal; ai-memory does not silently start an unmanaged agent.
## Privacy and storage boundaries
ai-memory's managed adapters do not write to Claude, Codex, OpenCode, Pi, Crush,
-Kimi Code, OMP, Grok, or Antigravity private stores. The launched harness
+Kimi Code, Kiro, OMP, Grok, or Antigravity private stores. The launched harness
retains normal ownership of its own session writes. Adapters read only
documented or observed local session formats. Provider credentials, encrypted
content, system/developer prompt records, and hidden reasoning are not copied. The
@@ -415,9 +434,9 @@ belong in wiki pages through consolidation or explicit durable writes.
project name. Wiki paths are UUID-keyed, so it moves no server directory, source
checkout, or native harness session. If the source checkout path itself is
renamed, absolute-path session locators used by Claude Code, Codex, OpenCode,
-Pi, Kimi Code (`state.json`'s `workDir`), OMP, and Antigravity may still
-reference the old path; Crush's project-local `.crush` database moves with the
-checkout.
+Pi, Kimi Code (`state.json`'s `workDir`), Kiro (`<uuid>.json`'s `cwd`), OMP, and
+Antigravity may still reference the old path; Crush's project-local `.crush`
+database moves with the checkout.
There is no portable, supported API that rewrites every harness's private
project locator. ai-memory therefore does not mutate those stores or silently
@@ -432,8 +451,8 @@ checkout to match exactly.
## Manual acceptance
The opt-in acceptance runner exercises launcher edge cases and then orchestrates
-the locally installed Claude, Codex, OpenCode, Pi, Crush, OMP, Kimi, and Grok
-CLIs through one real workstream:
+the locally installed Claude, Codex, OpenCode, Pi, Crush, OMP, Kimi, Grok, and
+Antigravity CLIs through one real workstream:
```bash
scripts/managed-workstream-acceptance.sh
@@ -451,7 +470,8 @@ isolated `HOME` seeded only with the operator's OAuth and settings files. The
deterministic phase also covers first-run adoption, bare-mode selection and
empty-directory failure, wrapper `--yolo`, lease exclusion, Crush context
cleanup, a fake-mode Kimi store/resume/import round trip, an Antigravity
-hook/link/resume round trip, private-trajectory exclusion, and the
+hook/link/resume round trip, a fake-mode Kiro v2 store/resume/import round trip,
+Kiro v3 passthrough, private-trajectory exclusion, and the
established-workstream guard against obsolete sessions. The fake Kimi round
trip also deletes the linked native session and verifies automatic
fresh-session recovery and repointing.
@@ -460,6 +480,16 @@ returning resume paths are all exercised. Docker wrapper host execution and
remote URL preservation are covered separately by the `ai-memory-cli`
packaging tests.
+Kiro is intentionally skipped in the scripted real-harness phase. Its
+`--no-interactive` mode writes a different v1 SQLite store, while the managed v2
+adapter reads the interactive flat JSON/JSONL store. A logged-in Kiro acceptance
+therefore remains interactive: run `ai-memory run --new kiro-accept kiro`, enter
+a unique prompt, quit normally, then run `ai-memory run --workstream
+kiro-accept kiro-cli` and verify that Kiro resumes the same native conversation.
+Repeat with `--v3` and confirm ai-memory prints no managed resume selector or
+import result for that invocation. Record the Kiro version and sanitize the
+paired metadata/event files before converting any new shape into a fixture.
+
The real-harness phase treats the model as the system under transport, not as
the test oracle. For each leg it records the prior ledger sequence, then
requires a newly imported assistant event from harnesses with readable native
diff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.sh
index 39768363..f51a7cb8 100755
--- a/scripts/managed-workstream-acceptance.sh
+++ b/scripts/managed-workstream-acceptance.sh
@@ -8,7 +8,7 @@ ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
BIN=${AI_MEMORY_ACCEPTANCE_BIN:-"$ROOT/target/debug/ai-memory"}
KEEP=${AI_MEMORY_ACCEPTANCE_KEEP:-0}
DETERMINISTIC_ONLY=${AI_MEMORY_ACCEPTANCE_DETERMINISTIC_ONLY:-0}
-HARNESS_WORDS=${AI_MEMORY_ACCEPTANCE_HARNESSES:-"claude codex opencode pi crush omp kimi grok antigravity"}
+HARNESS_WORDS=${AI_MEMORY_ACCEPTANCE_HARNESSES:-"claude codex opencode pi crush omp kimi kiro grok antigravity"}
TMP=$(mktemp -d "${TMPDIR:-/tmp}/ai-memory-workstream-acceptance.XXXXXX")
DATA="$TMP/data"
REPO="$TMP/repo"
@@ -230,7 +230,14 @@ case "${AI_MEMORY_ACCEPTANCE_FAKE_MODE:-argv}" in
previous_arg=$arg
done
if [ -z "$session_id" ]; then
- session_id=$(cat /proc/sys/kernel/random/uuid)
+ if command -v uuidgen >/dev/null 2>&1; then
+ session_id=$(uuidgen | tr '[:upper:]' '[:lower:]')
+ elif [ -r /proc/sys/kernel/random/uuid ]; then
+ session_id=$(cat /proc/sys/kernel/random/uuid)
+ else
+ printf 'kiro fake mode needs uuidgen or /proc/sys/kernel/random/uuid\n' >&2
+ exit 1
+ fi
fi
# Real layout: flat store, one `<uuid>.json` metadata + `<uuid>.jsonl`
# event-stream pair per session; discovery must read the metadata cwd.
@@ -651,6 +658,74 @@ kimi_current_id=$(sqlite3 "$DATA/db/memory.sqlite" \
exit 1
}
+# Kiro fake-mode fixture: the fake owns the fresh UUID, writes the documented
+# flat metadata/event pair, and honors `--resume-id` on the second launch.
+# These deterministic checks cover wrapper mechanics only; the current Kiro
+# event schema still requires a separate logged-in interactive acceptance pass.
+KIRO_FAKE_HOME="$CONFIG/kiro-fake"
+mkdir -p "$KIRO_FAKE_HOME"
+(
+ cd "$REPO"
+ KIRO_HOME="$KIRO_FAKE_HOME" \
+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=kiro \
+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/kiro-first-argv.log" \
+ AI_MEMORY_ACCEPTANCE_SENTINEL="AMWS-FAKE-KIRO-ONE" \
+ "$BIN" --data-dir "$DATA" run --new edge-kiro --executable "$FAKE" \
+ --yolo kiro >"$LOGS/edge-kiro-first.log" 2>&1
+)
+diff -u <(printf '%s\n' --trust-all-tools) "$TMP/kiro-first-argv.log"
+kiro_session_file=$(find "$KIRO_FAKE_HOME/sessions/cli" -maxdepth 1 -name '*.jsonl' -print -quit)
+[ -n "$kiro_session_file" ] || {
+ printf 'fake kiro did not create a native session store\n' >&2
+ exit 1
+}
+kiro_session_id=$(basename "$kiro_session_file" .jsonl)
+kiro_ws_hex=$(sqlite3 "$DATA/db/memory.sqlite" \
+ "SELECT lower(hex(id)) FROM workstreams WHERE name = 'edge-kiro' ORDER BY selected_at DESC LIMIT 1;")
+[ "${#kiro_ws_hex}" -eq 32 ] || {
+ printf 'could not resolve the edge-kiro workstream id\n' >&2
+ exit 1
+}
+kiro_ws_id="${kiro_ws_hex:0:8}-${kiro_ws_hex:8:4}-${kiro_ws_hex:12:4}-${kiro_ws_hex:16:4}-${kiro_ws_hex:20:12}"
+kiro_first_hits=$("$BIN" --data-dir "$DATA" workstream-search \
+ --workstream-id "$kiro_ws_id" --limit 100 --json "AMWS-FAKE-KIRO-ONE")
+jq -e --arg id "$kiro_session_id" \
+ '[.[] | select(.agent == "kiro-cli" and .role == "assistant" and (.content | contains("AMWS-FAKE-KIRO-ONE")) and .native_session_id == $id)] | length == 1' \
+ <<<"$kiro_first_hits" >/dev/null || {
+ printf 'kiro event-stream sentinel was not imported from the discovered session\n' >&2
+ tail -80 "$LOGS/edge-kiro-first.log" >&2
+ exit 1
+}
+(
+ cd "$REPO"
+ KIRO_HOME="$KIRO_FAKE_HOME" \
+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=kiro \
+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/kiro-second-argv.log" \
+ AI_MEMORY_ACCEPTANCE_SENTINEL="AMWS-FAKE-KIRO-TWO" \
+ "$BIN" --data-dir "$DATA" run --workstream edge-kiro --executable "$FAKE" \
+ kiro-cli >"$LOGS/edge-kiro-second.log" 2>&1
+)
+diff -u <(printf '%s\n' --resume-id "$kiro_session_id") "$TMP/kiro-second-argv.log"
+kiro_second_hits=$("$BIN" --data-dir "$DATA" workstream-search \
+ --workstream-id "$kiro_ws_id" --limit 100 --json "AMWS-FAKE-KIRO")
+jq -e \
+ '([.[] | select(.role == "assistant" and (.content | contains("AMWS-FAKE-KIRO-ONE")))] | length == 1)
+ and ([.[] | select(.role == "assistant" and (.content | contains("AMWS-FAKE-KIRO-TWO")))] | length == 1)' \
+ <<<"$kiro_second_hits" >/dev/null || {
+ printf 'kiro incremental import duplicated or missed a round sentinel\n' >&2
+ tail -80 "$LOGS/edge-kiro-second.log" >&2
+ exit 1
+}
+(
+ cd "$REPO"
+ KIRO_HOME="$KIRO_FAKE_HOME" \
+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \
+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/kiro-v3-argv.log" \
+ "$BIN" --data-dir "$DATA" run --workstream edge-kiro --executable "$FAKE" \
+ kiro --v3 >"$LOGS/edge-kiro-v3.log" 2>&1
+)
+diff -u <(printf '%s\n' --v3) "$TMP/kiro-v3-argv.log"
+
# Antigravity fake-mode fixture: `agy` owns the conversation id and SQLite
# database, while its real PreInvocation hook links that id and accepts any
# pending workstream context. The private trajectory table is never decoded or
@@ -935,6 +1010,10 @@ harnesses=()
for requested_harness in "${requested_harnesses[@]}"; do
case "$requested_harness" in
kimi-code | kimi-cli) harness=kimi ;;
+ kiro | kiro-cli)
+ printf 'skipping kiro in the scripted real-harness phase: noninteractive Kiro uses a different session store; run the documented interactive Kiro acceptance separately\n' >&2
+ continue
+ ;;
grok-build) harness=grok ;;
antigravity-cli | agy) harness=antigravity ;;
*) harness=$requested_harness ;;