Skip to content

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

Rust

feat(workstream): add a v2-engine Kiro CLI managed-workstream adapter

Samir Hanna Verza991fbaf7c067
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 32eb9d0e..50cc7ca5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Managed workstreams support the AWS Kiro CLI through `ai-memory run kiro`
+ (`kiro-cli` accepted as an alias), scoped deliberately to the default v2
+ agent engine (#356). Fresh launches inject nothing (Kiro session ids are
+ server-assigned); returning sessions resume with `--resume-id <id>`
+ appended after user arguments; discovery and import read the interactive
+ session store (`$KIRO_HOME/sessions/cli/<uuid>.json` metadata +
+ `<uuid>.jsonl` event stream) with exact-checkout matching on the metadata
+ `cwd`. Cross-engine resume is prevented by construction: any `--v3`,
+ `--mode`, or non-`v2` `--agent-engine` selection passes the invocation
+ through unmanaged, because v3 sessions occupy a separate id space the v2
+ engine cannot resume and the v3 store format is not publicly documented.
+ Headless `--no-interactive` runs (which persist to Kiro's v1 SQLite store
+ rather than the session files) and one-shot list/delete flags also pass
+ through. The wrapper `--yolo` maps to the official v2 flag
+ `--trust-all-tools`, never widens an explicit `--trust-tools=<set>`, and
+ maps nothing on non-v2 engines (v3 replaced the flag with
+ permissions.yaml) with a stderr notice. The event stream is treated as
+ rewrite-tolerant like Kimi's journal (prefix-hash cursor, stable
+ line-hash record ids). Kiro joins the automatic bare-`run` pool and the
+ deterministic phase of the acceptance script; the CLI argument surface
+ was verified against kiro-cli 2.16.0, while session-file shapes derive
+ from public 1.29.x references and are documented as pending revalidation
+ on a live logged-in install.
- 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`
diff --git a/README.md b/README.md
index 3401352d..e46f7ffb 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, and OMP. 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 engine), and OMP. 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). |
| 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). |
+| Kiro CLI | Supported (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`). `ai-memory run kiro` adds managed workstream resume on the default v2 engine (`--v3`/non-v2 engine selections pass through unmanaged — separate session id spaces). MCP: configure `~/.kiro/settings/mcp.json` manually with `?flavor=bedrock` (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. |
@@ -69,12 +69,14 @@ priors are at the [bottom](#influences-and-prior-art).
workstream with native per-harness sessions, a portable visible-event ledger,
and full-ledger search.
`ai-memory run` with no harness continues the newest usable Claude Code,
- Codex, OpenCode, Pi, Crush, or Kimi Code session for this checkout. On first
+ Codex, OpenCode, Pi, Crush, Kimi Code, or Kiro CLI 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
arguments pass through unchanged except the wrapper-owned `--yolo`; direct
commands are unaffected. `kimi-code` and `kimi-cli` are accepted aliases for
- the installed `kimi` command.
+ the installed `kimi` command, and `kiro-cli` for the installed `kiro-cli`
+ command (`ai-memory run kiro`, default v2 engine only).
- **Per-repository capture exclusions.** A nearest-marker `[capture]`
`ignore_paths` policy drops matching recognized file-tool events before they
reach the local spool or server. See [the capture policy reference](docs/marker-file.md#capture-exclusions).
@@ -157,7 +159,8 @@ priors are at the [bottom](#influences-and-prior-art).
newer cross-harness history. After a normal quit, the next launch waits
briefly if the previous launcher is still finalizing; handled failures release
the workstream immediately. Managed mode currently covers Claude Code, Codex,
- OpenCode, Pi, Crush, Kimi Code, and OMP; direct harness launches remain
+ OpenCode, Pi, Crush, Kimi Code, Kiro CLI (v2 engine), and OMP; direct harness
+ launches remain
unchanged. See [Managed cross-harness workstreams](docs/managed-workstreams.md).
- **"Quit at 4 PM, pick up at 9 AM in a different agent."** The
classic. SessionStart hook in the next supported hook client prepends a
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 8412be02..3a67ec0d 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -219,6 +219,11 @@ pub enum RunHarnessChoice {
/// Moonshot AI Kimi Code.
#[value(name = "kimi", alias = "kimi-code", alias = "kimi-cli")]
Kimi,
+ /// AWS Kiro CLI (default v2 agent engine; a `--v3`/`--agent-engine`
+ /// selection passes through unmanaged — v3 sessions live in a
+ /// separate id space the v2 engine cannot resume).
+ #[value(name = "kiro", alias = "kiro-cli")]
+ Kiro,
}
/// Arguments for `workstream-search`.
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 731d152d..604ea10c 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -16,7 +16,8 @@ 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, inspect_repository, list_native_sessions, wait_for_transcript_flush,
+ export_transcript, inspect_repository, kiro_selects_non_default_engine, list_native_sessions,
+ wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
@@ -34,13 +35,14 @@ 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; 6] = [
+const AUTO_HARNESSES: [ManagedHarness; 7] = [
ManagedHarness::Claude,
ManagedHarness::Codex,
ManagedHarness::OpenCode,
ManagedHarness::Pi,
ManagedHarness::Crush,
ManagedHarness::Kimi,
+ ManagedHarness::Kiro,
];
#[derive(Debug, Clone)]
@@ -230,6 +232,16 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {
}
}
if args.yolo || trailing_yolo {
+ // Kiro's official dangerous mode exists on the v2 engine only
+ // (`--trust-all-tools`); the v3 engine replaced it with
+ // permissions.yaml and documents no CLI equivalent, so the wrapper
+ // maps nothing there and says so instead of failing silently.
+ if harness == ManagedHarness::Kiro && kiro_selects_non_default_engine(&plan.args) {
+ eprintln!(
+ "ai-memory: --yolo maps to no verified flag on the selected Kiro engine \
+ (v3 replaced --trust-all-tools with permissions.yaml); launching without it"
+ );
+ }
apply_yolo(harness, &mut plan.args);
}
if plan.mode == LaunchMode::Session
@@ -501,7 +513,7 @@ fn filter_usable_auto_sessions(
fn no_auto_session_error() -> anyhow::Error {
anyhow!(
- "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`"
+ "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`"
)
}
@@ -982,6 +994,7 @@ const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {
RunHarnessChoice::Crush => ManagedHarness::Crush,
RunHarnessChoice::Omp => ManagedHarness::Omp,
RunHarnessChoice::Kimi => ManagedHarness::Kimi,
+ RunHarnessChoice::Kiro => ManagedHarness::Kiro,
}
}
@@ -993,6 +1006,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),
_ => None,
}
}
@@ -1259,6 +1273,32 @@ mod tests {
);
}
+ #[test]
+ fn kiro_cli_alias_selects_the_kiro_adapter() {
+ for name in ["kiro", "kiro-cli"] {
+ let cli = Cli::try_parse_from([
+ OsStr::new("ai-memory"),
+ OsStr::new("run"),
+ OsStr::new(name),
+ OsStr::new("--model"),
+ OsStr::new("sonnet"),
+ ])
+ .unwrap();
+ let CliCommand::Run(args) = cli.command else {
+ panic!("expected run command");
+ };
+ assert!(
+ matches!(args.harness, Some(crate::cli::RunHarnessChoice::Kiro)),
+ "{name}"
+ );
+ assert_eq!(
+ args.native_args,
+ ["--model", "sonnet"].map(OsString::from).to_vec()
+ );
+ assert_eq!(managed_harness(args.harness.unwrap()), ManagedHarness::Kiro);
+ }
+ }
+
#[test]
fn bare_run_and_wrapper_yolo_parse_without_a_harness() {
let cli = Cli::try_parse_from(["ai-memory", "run", "--yolo"]).unwrap();
diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rs
index c0a7cf85..31efcb7f 100644
--- a/crates/ai-memory-hooks/src/workstream.rs
+++ b/crates/ai-memory-hooks/src/workstream.rs
@@ -136,19 +136,21 @@ async fn prepare_run(
| AgentKind::Crush
| AgentKind::Omp
| AgentKind::KimiCode
+ | AgentKind::KiroCli
) {
return error(
StatusCode::BAD_REQUEST,
"managed run requires a supported command-line harness",
);
}
- const AUTO_AGENTS: [AgentKind; 6] = [
+ const AUTO_AGENTS: [AgentKind; 7] = [
AgentKind::ClaudeCode,
AgentKind::Codex,
AgentKind::OpenCode,
AgentKind::Pi,
AgentKind::Crush,
AgentKind::KimiCode,
+ AgentKind::KiroCli,
];
if request.automatic_harness
&& (!AUTO_AGENTS.contains(&request.agent)
diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rs
index 642c9d5d..54495822 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,
+ /// AWS Kiro CLI (v2 agent engine only — see [`kiro_selects_non_default_engine`]).
+ Kiro,
}
impl ManagedHarness {
@@ -38,6 +40,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),
_ => None,
}
}
@@ -53,6 +56,7 @@ impl ManagedHarness {
Self::Crush => AgentKind::Crush,
Self::Omp => AgentKind::Omp,
Self::Kimi => AgentKind::KimiCode,
+ Self::Kiro => AgentKind::KiroCli,
}
}
@@ -67,6 +71,7 @@ impl ManagedHarness {
Self::Crush => "crush",
Self::Omp => "omp",
Self::Kimi => "kimi",
+ Self::Kiro => "kiro-cli",
}
}
@@ -81,10 +86,33 @@ impl ManagedHarness {
Self::Crush => "crush",
Self::Omp => "omp",
Self::Kimi => "kimi",
+ Self::Kiro => "kiro",
}
}
}
+/// Whether a Kiro CLI invocation targets an agent engine other than the
+/// default v2 engine — `--v3`, `--mode` (a v3-only option), or an
+/// `--agent-engine` value that is not `v2` (the `chat` subcommand's
+/// engine selector, verified on kiro-cli 2.16.0).
+///
+/// Kiro v3 sessions live in a separate id space and cannot be resumed by
+/// the v2 engine (nor vice versa), and the v3 persisted-session format is
+/// not publicly documented, so managed continuity covers the v2 engine
+/// only. Any non-v2 engine selection makes the whole invocation pass
+/// through — no session injection, no adoption, no import — which keeps
+/// incompatible v2/v3 sessions from being cross-resumed by construction.
+#[must_use]
+pub fn kiro_selects_non_default_engine(args: &[OsString]) -> bool {
+ if has_flag(args, &["--v3", "--mode"]) {
+ return true;
+ }
+ if !has_flag(args, &["--agent-engine"]) {
+ return false;
+ }
+ flag_value(args, &["--agent-engine"]).as_deref() != Some("v2")
+}
+
/// Whether the planned native invocation participates in session continuity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LaunchMode {
@@ -209,6 +237,19 @@ pub fn build_launch_plan(
expected = Some(id.to_string());
}
}
+ ManagedHarness::Kiro => {
+ // Kiro accepts no caller-chosen id for a fresh session
+ // (session ids are server-assigned UUIDs), so only a
+ // linked resume injects `--resume-id <id>` — a clap option
+ // accepted at the root and on the `chat` subcommand
+ // (verified on kiro-cli 2.16.0), appended at the end so
+ // user arguments are never reordered. The fresh session is
+ // linked by the session-start hook or discovered post-exit.
+ if let Some(id) = linked_session_id {
+ args.extend([OsString::from("--resume-id"), OsString::from(id)]);
+ expected = Some(id.to_string());
+ }
+ }
}
}
@@ -233,13 +274,28 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {
ManagedHarness::Crush => Some("--yolo"),
ManagedHarness::Omp => None,
ManagedHarness::Kimi => Some("--yolo"),
+ // `--trust-all-tools` (alias `-a`) is the official v2-engine
+ // dangerous mode (verified on kiro-cli 2.16.0). The v3 engine
+ // replaced it with permissions.yaml and documents no CLI
+ // equivalent, so a non-v2 engine selection maps nothing — the
+ // caller surfaces that to the user.
+ ManagedHarness::Kiro => {
+ if kiro_selects_non_default_engine(args) {
+ None
+ } else {
+ Some("--trust-all-tools")
+ }
+ }
};
if let Some(flag) = flag {
// Kimi's `--yolo` has hidden aliases (`--yes`, `--auto-approve`) and
// conflicts with the distinct `--auto` mode, so any of those native
// spellings already satisfies the wrapper's dangerous-mode request.
+ // Kiro's `--trust-tools=<set>` is an explicit narrower trust choice
+ // that the wrapper must not widen.
let present: &[&str] = match harness {
ManagedHarness::Kimi => &["--yolo", "-y", "--yes", "--auto-approve", "--auto"],
+ ManagedHarness::Kiro => &["--trust-all-tools", "-a", "--trust-tools"],
_ => &[flag],
};
if !has_flag(args, present) {
@@ -265,15 +321,47 @@ 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"]),
}
}
fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {
- if has_flag(args, &["--help", "-h", "--version", "-v"])
+ // Kiro's `-v` is verbose (its version short flag is `-V`), so the
+ // generic version-flag check must not send `kiro-cli -v` through
+ // unmanaged.
+ let version_flags: &[&str] = if harness == ManagedHarness::Kiro {
+ &["--help", "-h", "--version", "-V", "--help-all"]
+ } else {
+ &["--help", "-h", "--version", "-v"]
+ };
+ if has_flag(args, version_flags)
|| has_flag(args, &["--no-session", "--no-session-persistence"])
{
return LaunchMode::Passthrough;
}
+ if harness == ManagedHarness::Kiro {
+ // Managed continuity is verified for the default v2 engine only;
+ // any other engine selection passes straight through (see
+ // `kiro_selects_non_default_engine`). Headless `--no-interactive`
+ // runs persist to the v1 SQLite store rather than the v2 session
+ // files this adapter reads, and the one-shot list/delete flags
+ // never open a session, so none of them is session-bearing.
+ if kiro_selects_non_default_engine(args)
+ || has_flag(
+ args,
+ &[
+ "--no-interactive",
+ "--list-sessions",
+ "-l",
+ "--list-models",
+ "--delete-session",
+ "-d",
+ ],
+ )
+ {
+ return LaunchMode::Passthrough;
+ }
+ }
if harness == ManagedHarness::Codex
&& first_arg_is(args, "exec")
&& args
@@ -401,6 +489,37 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {
"__plugin_run_node",
]
.as_slice(),
+ // Every root subcommand except `chat` (kiro-cli 2.16.0
+ // --help-all). A bare `kiro-cli` and root chat flags both open
+ // the chat, so flags-only invocations stay 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(),
};
let first = args.first().and_then(|arg| arg.to_str());
if first.is_some_and(|value| utility.contains(&value)) {
@@ -454,6 +573,13 @@ fn has_explicit_session_selector(harness: ManagedHarness, args: &[OsString]) ->
"-C",
],
),
+ // `-r/--resume` resumes the newest conversation of this directory,
+ // `--resume-id <id>` a specific one, and `--resume-picker` (alias
+ // `--list`) opens the native picker — each an explicit user choice.
+ ManagedHarness::Kiro => has_flag(
+ args,
+ &["--resume", "-r", "--resume-id", "--resume-picker", "--list"],
+ ),
}
}
@@ -479,6 +605,9 @@ 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"]),
+ // Only `--resume-id` names a session; bare `--resume` means
+ // "newest in this directory" and the picker flags carry no id.
+ ManagedHarness::Kiro => flag_value(args, &["--resume-id"]),
}
}
@@ -560,6 +689,10 @@ 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")),
+ // Interactive v2-engine sessions live under
+ // `<KIRO_HOME>/sessions/cli/<uuid>.{json,jsonl}` (default ~/.kiro);
+ // KIRO_HOME relocation is honored by the binary.
+ ManagedHarness::Kiro => value("KIRO_HOME").map(|dir| dir.join("sessions").join("cli")),
}
}
@@ -794,6 +927,7 @@ mod tests {
(ManagedHarness::Crush, Some("--yolo")),
(ManagedHarness::Omp, None),
(ManagedHarness::Kimi, Some("--yolo")),
+ (ManagedHarness::Kiro, Some("--trust-all-tools")),
] {
let mut args = Vec::new();
apply_yolo(harness, &mut args);
@@ -1018,4 +1152,220 @@ mod tests {
Some(std::path::Path::new("/stores/kimi-code/sessions"))
);
}
+
+ #[test]
+ fn kiro_cli_name_is_an_alias_for_kiro() {
+ for name in ["kiro", "kiro-cli"] {
+ assert_eq!(ManagedHarness::from_name(name), Some(ManagedHarness::Kiro));
+ }
+ assert_eq!(ManagedHarness::Kiro.executable(), "kiro-cli");
+ assert_eq!(ManagedHarness::Kiro.agent_kind(), AgentKind::KiroCli);
+ }
+
+ #[test]
+ fn kiro_fresh_launch_injects_no_session_selector() {
+ // Kiro session ids are server-assigned; a fresh launch must leave
+ // argv untouched even though the harness is managed. Both the bare
+ // form and the explicit `chat` subcommand are session-bearing.
+ for native in [
+ vec![OsString::from("continue here")],
+ vec![OsString::from("chat"), OsString::from("continue here")],
+ ] {
+ let plan = build_launch_plan(ManagedHarness::Kiro, None, native.clone(), None).unwrap();
+ assert_eq!(plan.args, native);
+ assert_eq!(plan.expected_session_id, None);
+ assert_eq!(plan.mode, LaunchMode::Session, "{native:?}");
+ }
+ }
+
+ #[test]
+ fn kiro_resume_appends_resume_id_after_user_arguments() {
+ let plan = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ vec![OsString::from("--model"), OsString::from("sonnet")],
+ Some("3f6d1c2a-aaaa-bbbb-cccc-000000000001"),
+ )
+ .unwrap();
+ assert_eq!(
+ strings(&plan.args),
+ [
+ "--model",
+ "sonnet",
+ "--resume-id",
+ "3f6d1c2a-aaaa-bbbb-cccc-000000000001"
+ ]
+ );
+ assert_eq!(
+ plan.expected_session_id.as_deref(),
+ Some("3f6d1c2a-aaaa-bbbb-cccc-000000000001")
+ );
+ }
+
+ #[test]
+ fn kiro_explicit_selector_always_wins_including_pickers() {
+ for native in [
+ vec![OsString::from("--resume-id"), OsString::from("id_chosen")],
+ vec![OsString::from("--resume-id=id_chosen")],
+ // `-r/--resume` (newest in this directory) and the pickers
+ // (`--resume-picker`, alias `--list`) are explicit choices that
+ // carry no id up front.
+ vec![OsString::from("--resume")],
+ vec![OsString::from("-r")],
+ vec![OsString::from("--resume-picker")],
+ vec![OsString::from("--list")],
+ ] {
+ let plan = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ native.clone(),
+ Some("id_linked"),
+ )
+ .unwrap();
+ assert_eq!(plan.args, native, "{native:?} must stay byte-identical");
+ assert_ne!(plan.expected_session_id.as_deref(), Some("id_linked"));
+ }
+ let chosen = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ vec![OsString::from("--resume-id"), OsString::from("id_chosen")],
+ Some("id_linked"),
+ )
+ .unwrap();
+ assert_eq!(chosen.expected_session_id.as_deref(), Some("id_chosen"));
+ }
+
+ #[test]
+ fn kiro_utility_subcommands_are_passed_through() {
+ for utility in [
+ "login",
+ "settings",
+ "agent",
+ "mcp",
+ "doctor",
+ "translate",
+ "update",
+ "dashboard",
+ "acp",
+ "help",
+ ] {
+ let plan = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ vec![OsString::from(utility)],
+ Some("id_linked"),
+ )
+ .unwrap();
+ assert_eq!(plan.mode, LaunchMode::Passthrough, "{utility}");
+ assert_eq!(strings(&plan.args), [utility]);
+ }
+ }
+
+ #[test]
+ fn kiro_non_default_engine_always_passes_through() {
+ // v3 sessions live in a separate id space the v2 engine cannot
+ // resume, and the v3 store format is unverified — every non-v2
+ // engine selection must pass through with argv untouched so
+ // cross-engine resume cannot happen by construction.
+ for native in [
+ vec![OsString::from("--v3")],
+ vec![OsString::from("chat"), OsString::from("--v3")],
+ vec![OsString::from("--agent-engine"), OsString::from("v3")],
+ vec![OsString::from("--agent-engine=v1")],
+ vec![OsString::from("--mode"), OsString::from("spec")],
+ ] {
+ let plan = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ native.clone(),
+ Some("id_linked"),
+ )
+ .unwrap();
+ assert_eq!(plan.mode, LaunchMode::Passthrough, "{native:?}");
+ assert_eq!(plan.args, native, "{native:?} must stay byte-identical");
+ assert!(!allows_native_session_adoption(
+ ManagedHarness::Kiro,
+ &native
+ ));
+ }
+ // The explicit default engine stays managed.
+ let v2 = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ vec![OsString::from("--agent-engine"), OsString::from("v2")],
+ None,
+ )
+ .unwrap();
+ assert_eq!(v2.mode, LaunchMode::Session);
+ }
+
+ #[test]
+ fn kiro_one_shot_and_headless_invocations_pass_through() {
+ // `--no-interactive` persists to the v1 SQLite store rather than
+ // the v2 session files this adapter reads, and the list/delete
+ // flags never open a session.
+ for native in [
+ vec![OsString::from("--no-interactive"), OsString::from("hi")],
+ vec![OsString::from("--list-sessions")],
+ vec![OsString::from("-l")],
+ vec![OsString::from("--list-models")],
+ vec![OsString::from("--delete-session"), OsString::from("id")],
+ vec![OsString::from("-d"), OsString::from("id")],
+ ] {
+ let plan = build_launch_plan(
+ ManagedHarness::Kiro,
+ None,
+ native.clone(),
+ Some("id_linked"),
+ )
+ .unwrap();
+ assert_eq!(plan.mode, LaunchMode::Passthrough, "{native:?}");
+ assert_eq!(plan.args, native);
+ }
+ }
+
+ #[test]
+ fn kiro_verbose_short_flag_is_not_the_version_flag() {
+ // Kiro's `-v` increases verbosity (`-V` prints the version), so a
+ // verbose chat must stay managed while `-V` passes through.
+ let verbose =
+ build_launch_plan(ManagedHarness::Kiro, None, vec![OsString::from("-v")], None)
+ .unwrap();
+ assert_eq!(verbose.mode, LaunchMode::Session);
+ let version =
+ build_launch_plan(ManagedHarness::Kiro, None, vec![OsString::from("-V")], None)
+ .unwrap();
+ assert_eq!(version.mode, LaunchMode::Passthrough);
+ }
+
+ #[test]
+ fn kiro_yolo_maps_to_trust_all_tools_on_the_v2_engine_only() {
+ // Fresh args: the official v2 dangerous-mode flag is appended.
+ let mut args = Vec::new();
+ apply_yolo(ManagedHarness::Kiro, &mut args);
+ assert_eq!(strings(&args), ["--trust-all-tools"]);
+
+ // Native spellings that already grant (or explicitly narrow) trust
+ // are respected — `--trust-tools=<set>` must not be widened.
+ 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], "{already} must not duplicate");
+ }
+
+ // The v3 engine has no verified CLI equivalent (permissions.yaml
+ // replaced --trust-all-tools), so nothing is mapped.
+ let mut v3 = vec![OsString::from("--v3")];
+ apply_yolo(ManagedHarness::Kiro, &mut v3);
+ assert_eq!(strings(&v3), ["--v3"]);
+ }
+
+ #[test]
+ fn kiro_home_environment_override_points_at_cli_sessions_root() {
+ 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"))
+ );
+ }
}
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index 4a544e67..9d6bcb2e 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,
+ build_launch_plan, 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 923afbc3..838419a9 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -12,6 +12,7 @@ use rusqlite::{Connection, OpenFlags, params};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest as _, Sha256};
+use uuid::Uuid;
use crate::ManagedHarness;
@@ -204,7 +205,7 @@ fn export_jsonl(
let mut file = File::open(path)
.with_context(|| format!("opening native transcript {}", path.display()))?;
let len = file.metadata()?.len();
- let (start, mut kimi_prefix_hasher) = if harness == ManagedHarness::Kimi {
+ let (start, mut prefix_hasher) = if rewrite_tolerant_journal(harness) {
let validated = if let Some(cursor) = cursor.as_ref().filter(|cursor| cursor.offset <= len)
&& let Some(expected) = cursor.prefix_sha256.as_deref()
&& let Some(hasher) = hash_file_prefix(&mut file, cursor.offset)?
@@ -238,8 +239,8 @@ fn export_jsonl(
if !line.ends_with(b"\n") {
break;
}
- if harness == ManagedHarness::Kimi {
- kimi_prefix_hasher.update(&line);
+ if rewrite_tolerant_journal(harness) {
+ prefix_hasher.update(&line);
}
committed_offset = offset;
let value: Value = match serde_json::from_slice(&line) {
@@ -252,12 +253,14 @@ fn export_jsonl(
continue;
}
};
- let record_id = if harness == ManagedHarness::Kimi {
+ let record_id = if rewrite_tolerant_journal(harness) {
// Kimi wire records carry no envelope id, and the journal is
// rewritten wholesale on fork/compaction/resume — a byte-offset
// id would silently change meaning. Hashing the raw line keeps
// record ids (and therefore server-side event dedup) stable
- // across rewrites.
+ // across rewrites. Kiro records reuse one message_id across an
+ // exchange's Prompt/AssistantMessage/ToolResults records, so
+ // the line hash is its unique record id as well.
let raw = line.strip_suffix(b"\n").unwrap_or(&line);
format!("{:x}", Sha256::digest(raw))
} else {
@@ -293,6 +296,13 @@ fn export_jsonl(
&mut events,
&mut losses,
),
+ ManagedHarness::Kiro => parse_kiro(
+ &value,
+ native_session_id,
+ &record_id,
+ &mut events,
+ &mut losses,
+ ),
ManagedHarness::OpenCode | ManagedHarness::Crush => {
return Err(anyhow!(
"{} transcripts must use their SQLite adapter",
@@ -309,14 +319,25 @@ fn export_jsonl(
source_cursor: Some(serde_json::to_string(&FileCursor {
path: path.to_string_lossy().into_owned(),
offset: committed_offset,
- prefix_sha256: (harness == ManagedHarness::Kimi)
- .then(|| format!("{:x}", kimi_prefix_hasher.finalize())),
+ prefix_sha256: rewrite_tolerant_journal(harness)
+ .then(|| format!("{:x}", prefix_hasher.finalize())),
})?),
events,
losses: deduplicate_losses(losses),
})
}
+/// 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();
@@ -894,6 +915,185 @@ fn kimi_timestamp(value: &Value) -> Option<String> {
.map(|timestamp| timestamp.to_string())
}
+/// Import one Kiro v2-engine session event: a versioned envelope
+/// `{"version":"v1","kind":…,"data":{"message_id":…,"content":[…],"meta":…}}`
+/// whose `content` parts carry their own `kind`/`data`. Visible kinds:
+/// `Prompt` (user), `AssistantMessage` (assistant text + `toolUse` parts),
+/// `ToolResults` (`toolResult` parts). Unknown record kinds within the
+/// `v1` envelope are ignored so newer Kiro versions stay
+/// forward-compatible; a non-`v1` envelope version is annotated instead —
+/// that axis signals a schema break, not an additive record type.
+fn parse_kiro(
+ value: &Value,
+ session: &str,
+ record_id: &str,
+ events: &mut Vec<NewWorkstreamEvent>,
+ losses: &mut Vec<String>,
+) {
+ match value.get("version").and_then(Value::as_str) {
+ Some("v1") => {}
+ Some(other) => {
+ losses.push(format!(
+ "Kiro records with unsupported envelope version {other} were skipped"
+ ));
+ return;
+ }
+ None => {
+ losses.push("Kiro records without an envelope version were skipped".into());
+ return;
+ }
+ }
+ let data = value.get("data").unwrap_or(&Value::Null);
+ let occurred_at = kiro_timestamp(data);
+ let parts = data
+ .get("content")
+ .and_then(Value::as_array)
+ .map_or(&[][..], Vec::as_slice);
+ match value
+ .get("kind")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ {
+ "Prompt" => {
+ for (index, part) in parts.iter().enumerate() {
+ match part.get("kind").and_then(Value::as_str).unwrap_or_default() {
+ "text" => {
+ if let Some(text) = part.get("data").and_then(Value::as_str) {
+ push_event(
+ events,
+ AgentKind::KiroCli,
+ session,
+ record_id,
+ index,
+ WorkstreamEventKind::Message,
+ Some("user"),
+ text,
+ occurred_at.clone(),
+ json!({}),
+ );
+ }
+ }
+ _ => {
+ losses
+ .push("Kiro non-text content parts were intentionally excluded".into());
+ }
+ }
+ }
+ }
+ "AssistantMessage" => {
+ for (index, part) in parts.iter().enumerate() {
+ match part.get("kind").and_then(Value::as_str).unwrap_or_default() {
+ "text" => {
+ if let Some(text) = part.get("data").and_then(Value::as_str) {
+ push_event(
+ events,
+ AgentKind::KiroCli,
+ session,
+ record_id,
+ index,
+ WorkstreamEventKind::Message,
+ Some("assistant"),
+ text,
+ occurred_at.clone(),
+ json!({}),
+ );
+ }
+ }
+ "toolUse" => {
+ let tool = part.get("data").unwrap_or(&Value::Null);
+ let name = first_string(tool, &["name", "toolName", "tool_name"])
+ .unwrap_or("tool");
+ let arguments = tool
+ .get("input")
+ .or_else(|| tool.get("args"))
+ .or_else(|| tool.get("arguments"))
+ .map(compact_json)
+ .unwrap_or_else(|| compact_json(tool));
+ push_event(
+ events,
+ AgentKind::KiroCli,
+ session,
+ record_id,
+ index,
+ WorkstreamEventKind::ToolCall,
+ Some("assistant"),
+ &format!("{name}: {arguments}"),
+ occurred_at.clone(),
+ json!({
+ "tool": name,
+ "tool_call_id": first_string(tool, &["tool_use_id", "toolUseId", "id"])
+ }),
+ );
+ }
+ _ => {
+ losses
+ .push("Kiro non-text content parts were intentionally excluded".into());
+ }
+ }
+ }
+ }
+ "ToolResults" => {
+ for (index, part) in parts.iter().enumerate() {
+ if part.get("kind").and_then(Value::as_str) != Some("toolResult") {
+ continue;
+ }
+ let result = part.get("data").unwrap_or(&Value::Null);
+ let body = kiro_result_text(result)
+ .filter(|text| !text.trim().is_empty())
+ .unwrap_or_else(|| compact_json(result));
+ push_event(
+ events,
+ AgentKind::KiroCli,
+ session,
+ record_id,
+ index,
+ WorkstreamEventKind::ToolResult,
+ Some("tool"),
+ &body,
+ occurred_at.clone(),
+ json!({
+ "tool_call_id": first_string(result, &["tool_use_id", "toolUseId", "id"]),
+ "is_error": result
+ .get("is_error")
+ .or_else(|| result.get("isError"))
+ .and_then(Value::as_bool)
+ }),
+ );
+ }
+ }
+ _ => {}
+ }
+}
+
+/// Kiro event timestamps ride `data.meta.timestamp` as a unix epoch in
+/// milliseconds.
+fn kiro_timestamp(data: &Value) -> Option<String> {
+ let millis = data.get("meta")?.get("timestamp").and_then(Value::as_i64)?;
+ jiff::Timestamp::from_millisecond(millis)
+ .ok()
+ .map(|timestamp| timestamp.to_string())
+}
+
+/// Text of a Kiro tool result: its `content` is an array of the same
+/// `{kind, data}` parts the message records use (text parts join), with
+/// plain-string `content`/`output`/`text` fields tolerated as fallbacks.
+fn kiro_result_text(result: &Value) -> Option<String> {
+ if let Some(parts) = result.get("content").and_then(Value::as_array) {
+ let texts: Vec<&str> = parts
+ .iter()
+ .filter(|part| part.get("kind").and_then(Value::as_str) == Some("text"))
+ .filter_map(|part| part.get("data").and_then(Value::as_str))
+ .collect();
+ if !texts.is_empty() {
+ return Some(texts.join("\n"));
+ }
+ }
+ ["content", "output", "text"]
+ .iter()
+ .find_map(|key| result.get(*key).and_then(Value::as_str))
+ .map(str::to_owned)
+}
+
/// Subagent journals (`agents/<id != main>/wire.jsonl`) are not imported in
/// v1; annotate the gap once so the omission is visible in the ledger.
fn annotate_kimi_subagents(path: &Path, losses: &mut Vec<String>) {
@@ -1396,6 +1596,13 @@ fn locate_session_file(
}
}
}
+ if harness == ManagedHarness::Kiro {
+ // The store is flat: `<root>/<session-id>.jsonl`.
+ let exact = root.join(format!("{id}.jsonl"));
+ if exact.is_file() {
+ return Ok(Some(exact));
+ }
+ }
let mut files = collect_files(&root, |path| transcript_file(harness, path))?;
files.sort_by_key(|path| temporary_transcript(path));
for path in &files {
@@ -1422,6 +1629,17 @@ fn transcript_file(harness: ManagedHarness, path: &Path) -> bool {
.and_then(|name| name.to_str())
== Some("main");
}
+ if harness == ManagedHarness::Kiro {
+ // Only `<uuid>.jsonl` event streams directly in the store; session
+ // ids are UUIDs, so the stem filter excludes stray JSONL files a
+ // session subdirectory (e.g. `<id>/tasks/`) might hold. The
+ // sibling `<uuid>.json` metadata is not a transcript.
+ 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());
+ }
path.extension().is_some_and(|ext| ext == "jsonl")
|| matches!(harness, ManagedHarness::Pi | ManagedHarness::Omp) && temporary_transcript(path)
}
@@ -1438,6 +1656,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);
+ }
let mut reader = BufReader::new(File::open(path)?);
let mut line = String::new();
for _ in 0..64 {
@@ -1464,7 +1685,10 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(String
value.get("id").and_then(Value::as_str),
value.get("cwd").and_then(Value::as_str),
),
- ManagedHarness::OpenCode | ManagedHarness::Crush | ManagedHarness::Kimi => (None, None),
+ ManagedHarness::OpenCode
+ | ManagedHarness::Crush
+ | ManagedHarness::Kimi
+ | ManagedHarness::Kiro => (None, None),
};
if let (Some(id), Some(cwd)) = (id, cwd) {
return Ok(Some((id.to_string(), PathBuf::from(cwd))));
@@ -1498,6 +1722,36 @@ fn kimi_session_header(path: &Path) -> Result<Option<(String, PathBuf)>> {
Ok(Some((id.to_string(), PathBuf::from(cwd))))
}
+/// Kiro v2-engine sessions are self-describing in the sibling metadata
+/// file: `<root>/<id>.jsonl` (event stream) pairs with `<root>/<id>.json`
+/// (`{"session_id": …, "cwd": …, …}`). The event stream itself carries no
+/// session id or cwd. A missing or invalid metadata file means the
+/// session is unusable for checkout matching, not an error; a metadata
+/// `session_id` that disagrees with the file stem is treated the same
+/// way rather than trusting either side.
+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);
+ };
+ let metadata_path = path.with_extension("json");
+ let Ok(raw) = fs::read_to_string(&metadata_path) 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))))
+}
+
fn discover_opencode(
home: &Path,
session_dir: Option<&Path>,
@@ -1685,6 +1939,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"),
}
}
@@ -1842,9 +2097,13 @@ mod tests {
"{}\n",
json!({"type":"session","id":"other-id","cwd":other})
),
- // Kimi's header lives in state.json, not the journal;
- // covered by kimi_discovery_matches_checkout_via_state_json.
- ManagedHarness::OpenCode | ManagedHarness::Crush | ManagedHarness::Kimi => {
+ // Kimi's header lives in state.json and Kiro's in the
+ // sibling metadata JSON, not the journal; covered by
+ // their dedicated discovery tests.
+ ManagedHarness::OpenCode
+ | ManagedHarness::Crush
+ | ManagedHarness::Kimi
+ | ManagedHarness::Kiro => {
unreachable!()
}
},
@@ -2535,4 +2794,239 @@ mod tests {
assert!(events.is_empty());
assert_eq!(losses, ["Kimi system messages were intentionally excluded"]);
}
+
+ const KIRO_ID_A: &str = "3f6d1c2a-0000-4000-8000-000000000aaa";
+ const KIRO_ID_B: &str = "3f6d1c2a-0000-4000-8000-000000000bbb";
+
+ /// The canonical Kiro v2-engine store shape: flat
+ /// `<root>/<uuid>.json` metadata + `<root>/<uuid>.jsonl` event stream,
+ /// one pair per session. Returns the root and the matching session's
+ /// stream path.
+ fn kiro_store_fixture(cwd: &Path, other: &Path) -> (tempfile::TempDir, PathBuf) {
+ let root = tempfile::tempdir().unwrap();
+ for (id, dir) in [(KIRO_ID_A, cwd), (KIRO_ID_B, other)] {
+ fs::write(
+ root.path().join(format!("{id}.json")),
+ json!({
+ "session_id": id,
+ "cwd": dir,
+ "created_at": "2026-08-01T10:00:00Z",
+ "updated_at": "2026-08-01T10:05:00Z",
+ "title": "fixture session",
+ "session_state": {"version": "v1", "conversation_metadata": {}}
+ })
+ .to_string(),
+ )
+ .unwrap();
+ fs::write(root.path().join(format!("{id}.jsonl")), "").unwrap();
+ }
+ (root, PathBuf::from(format!("{KIRO_ID_A}.jsonl")))
+ }
+
+ #[tokio::test]
+ async fn kiro_discovery_matches_checkout_via_sibling_metadata() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let other = temp.path().join("other");
+ fs::create_dir_all(&cwd).unwrap();
+ fs::create_dir_all(&other).unwrap();
+ let (root, stream_a) = kiro_store_fixture(&cwd, &other);
+ let stream_a = root.path().join(stream_a);
+ fs::write(
+ &stream_a,
+ format!(
+ "{}\n",
+ json!({"version":"v1","kind":"Prompt","data":{"message_id":"m1","content":[{"kind":"text","data":"hi"}]}})
+ ),
+ )
+ .unwrap();
+ // Distractors that must never surface: a non-UUID stream, a stray
+ // JSONL inside a session's tasks directory, and a metadata file
+ // whose session_id disagrees with its stem.
+ fs::write(root.path().join("notes.jsonl"), "{}\n").unwrap();
+ let tasks = root.path().join(KIRO_ID_A).join("tasks");
+ fs::create_dir_all(&tasks).unwrap();
+ fs::write(tasks.join("todo.jsonl"), "{}\n").unwrap();
+ let mismatched = "3f6d1c2a-0000-4000-8000-000000000ccc";
+ fs::write(
+ root.path().join(format!("{mismatched}.json")),
+ json!({"session_id": KIRO_ID_A, "cwd": cwd}).to_string(),
+ )
+ .unwrap();
+ fs::write(root.path().join(format!("{mismatched}.jsonl")), "{}\n").unwrap();
+
+ let sessions = list_native_sessions(
+ ManagedHarness::Kiro,
+ temp.path(),
+ &cwd,
+ Some(root.path()),
+ 8,
+ )
+ .await
+ .unwrap();
+ assert_eq!(sessions.len(), 1);
+ assert_eq!(sessions[0].native_session_id, KIRO_ID_A);
+
+ let other_sessions = list_native_sessions(
+ ManagedHarness::Kiro,
+ temp.path(),
+ &other,
+ Some(root.path()),
+ 8,
+ )
+ .await
+ .unwrap();
+ assert_eq!(other_sessions.len(), 1);
+ assert_eq!(other_sessions[0].native_session_id, KIRO_ID_B);
+
+ let found = locate_session_file(
+ ManagedHarness::Kiro,
+ temp.path(),
+ &cwd,
+ Some(root.path()),
+ KIRO_ID_B,
+ )
+ .unwrap();
+ assert_eq!(
+ found.as_deref(),
+ Some(root.path().join(format!("{KIRO_ID_B}.jsonl")).as_path())
+ );
+ }
+
+ #[test]
+ fn kiro_export_maps_visible_records_and_excludes_private_ones() {
+ let temp = tempfile::tempdir().unwrap();
+ let stream = temp.path().join(format!("{KIRO_ID_A}.jsonl"));
+ let lines = [
+ 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":"Prompt","data":{"message_id":"m2","content":[{"kind":"image","data":{"format":"png"}}]}}),
+ json!({"version":"v1","kind":"AssistantMessage","data":{"message_id":"m3","content":[
+ {"kind":"text","data":"visible answer"},
+ {"kind":"toolUse","data":{"name":"fs_read","tool_use_id":"call_1","input":{"operations":[{"mode":"Line","path":"README.md"}]}}}
+ ]}}),
+ json!({"version":"v1","kind":"ToolResults","data":{"message_id":"m4","content":[
+ {"kind":"toolResult","data":{"tool_use_id":"call_1","content":[{"kind":"text","data":"result ok"}],"is_error":false}}
+ ]}}),
+ // Unknown record kinds inside the v1 envelope are additive and
+ // ignored; foreign envelope versions are annotated and skipped.
+ json!({"version":"v1","kind":"Checkpoint","data":{"message_id":"m5"}}),
+ json!({"version":"v2","kind":"Prompt","data":{"message_id":"m6","content":[{"kind":"text","data":"future schema"}]}}),
+ json!({"kind":"Prompt","data":{"message_id":"m7","content":[{"kind":"text","data":"unversioned"}]}}),
+ ];
+ let raw: String = lines
+ .iter()
+ .map(|line| format!("{line}\n"))
+ .collect::<Vec<_>>()
+ .concat();
+ fs::write(&stream, &raw).unwrap();
+
+ let export = export_jsonl(ManagedHarness::Kiro, &stream, KIRO_ID_A, None).unwrap();
+ let kinds: Vec<_> = export.events.iter().map(|event| event.kind).collect();
+ assert_eq!(
+ kinds,
+ [
+ WorkstreamEventKind::Message,
+ WorkstreamEventKind::Message,
+ WorkstreamEventKind::ToolCall,
+ WorkstreamEventKind::ToolResult,
+ ]
+ );
+ 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[1].role.as_deref(), Some("assistant"));
+ assert!(
+ export.events[2].content.starts_with("fs_read: "),
+ "{}",
+ export.events[2].content
+ );
+ assert_eq!(export.events[2].metadata["tool"], "fs_read");
+ assert_eq!(export.events[2].metadata["tool_call_id"], "call_1");
+ assert_eq!(export.events[3].content, "result ok");
+ assert_eq!(export.events[3].metadata["is_error"], false);
+ // Every event id is stable and the record ids are line hashes.
+ assert!(
+ export
+ .events
+ .iter()
+ .all(|event| event.event_id.starts_with("native:"))
+ );
+ assert_eq!(
+ export.losses,
+ [
+ "Kiro non-text content parts were intentionally excluded".to_string(),
+ "Kiro records with unsupported envelope version v2 were skipped".to_string(),
+ "Kiro records without an envelope version were skipped".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn kiro_export_is_incremental_and_tolerates_an_unfinished_tail() {
+ let temp = tempfile::tempdir().unwrap();
+ let stream = temp.path().join(format!("{KIRO_ID_A}.jsonl"));
+ let first = format!(
+ "{}\n",
+ json!({"version":"v1","kind":"Prompt","data":{"message_id":"m1","content":[{"kind":"text","data":"first"}]}})
+ );
+ fs::write(&stream, &first).unwrap();
+ let export = export_jsonl(ManagedHarness::Kiro, &stream, KIRO_ID_A, None).unwrap();
+ assert_eq!(export.events.len(), 1);
+ let cursor = export.source_cursor.clone().unwrap();
+
+ // Append one complete record plus an unfinished tail: only the
+ // complete record is imported and the cursor never advances past it.
+ let second = format!(
+ "{}\n",
+ json!({"version":"v1","kind":"AssistantMessage","data":{"message_id":"m2","content":[{"kind":"text","data":"second"}]}})
+ );
+ let mut appended = fs::read_to_string(&stream).unwrap();
+ appended.push_str(&second);
+ appended.push_str("{\"version\":\"v1\",\"kind\":\"Assist");
+ fs::write(&stream, &appended).unwrap();
+
+ let export = export_jsonl(ManagedHarness::Kiro, &stream, KIRO_ID_A, Some(&cursor)).unwrap();
+ assert_eq!(export.events.len(), 1);
+ assert_eq!(export.events[0].content, "second");
+ let cursor: FileCursor =
+ serde_json::from_str(export.source_cursor.as_deref().unwrap()).unwrap();
+ assert_eq!(cursor.offset as usize, first.len() + second.len());
+ }
+
+ #[test]
+ fn kiro_export_resets_cursor_after_an_in_place_rewrite() {
+ let temp = tempfile::tempdir().unwrap();
+ let stream = temp.path().join(format!("{KIRO_ID_A}.jsonl"));
+ let original = format!(
+ "{}\n{}\n",
+ json!({"version":"v1","kind":"Prompt","data":{"message_id":"m1","content":[{"kind":"text","data":"first"}]}}),
+ json!({"version":"v1","kind":"AssistantMessage","data":{"message_id":"m2","content":[{"kind":"text","data":"second"}]}}),
+ );
+ fs::write(&stream, &original).unwrap();
+ let export = export_jsonl(ManagedHarness::Kiro, &stream, KIRO_ID_A, None).unwrap();
+ assert_eq!(export.events.len(), 2);
+ let cursor = export.source_cursor.clone().unwrap();
+
+ // Simulate a compaction-style rewrite: the file is replaced with
+ // different content of a similar length. The stale byte offset must
+ // not be trusted — the adapter replays from the start and the
+ // stable line-hash record ids dedupe server-side.
+ let rewritten = format!(
+ "{}\n",
+ json!({"version":"v1","kind":"Prompt","data":{"message_id":"m9","content":[{"kind":"text","data":"rewritten history"}]}})
+ );
+ fs::write(&stream, &rewritten).unwrap();
+ let export = export_jsonl(ManagedHarness::Kiro, &stream, KIRO_ID_A, Some(&cursor)).unwrap();
+ assert_eq!(export.events.len(), 1);
+ assert_eq!(export.events[0].content, "rewritten history");
+
+ // An untouched file with a valid cursor stays a no-op.
+ let cursor = export.source_cursor.clone().unwrap();
+ let export = export_jsonl(ManagedHarness::Kiro, &stream, KIRO_ID_A, Some(&cursor)).unwrap();
+ assert!(export.events.is_empty());
+ }
}
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 04994691..b29a164a 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -283,7 +283,8 @@ 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, and OMP launches
+Direct Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI, and OMP
+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
diff --git a/docs/install.md b/docs/install.md
index 8762aa06..10a39e36 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -763,8 +763,10 @@ serves the same tools with flattened root schemas:
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).
+added manually. `ai-memory run kiro` adds managed workstream resume for
+the default v2 engine; non-v2 engine selections pass through unmanaged.
+See [managed workstreams](managed-workstreams.md) for the adapter's
+verified scope and limitations.
### OpenCode
diff --git a/docs/managed-harness-contributions.md b/docs/managed-harness-contributions.md
index b9edf574..cf062fa8 100644
--- a/docs/managed-harness-contributions.md
+++ b/docs/managed-harness-contributions.md
@@ -1,7 +1,8 @@
# 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, and OMP.
+release can manage Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI
+(v2 engine only), and OMP.
Gemini CLI, Devin CLI, Cursor, Grok Build CLI, and the other integrations in
the README support matrix do not become managed merely because ai-memory can
capture their hooks.
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index e17b91a0..f93d086d 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, and OMP. Direct
-agent launches
+between Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI, and OMP.
+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.
@@ -28,7 +28,7 @@ second copy of each harness's option schema. Other wrapper options come first:
```text
ai-memory run [--workspace NAME] [--project NAME]
[--workstream NAME | --new NAME] [--executable PATH] [--yolo]
- [claude|codex|opencode|pi|crush|omp|kimi] [native arguments...]
+ [claude|codex|opencode|pi|crush|omp|kimi|kiro] [native arguments...]
```
The default is the most recently selected workstream for the current repository
@@ -39,8 +39,8 @@ branching controls, not harness-switch controls.
## Automatic harness selection
With no harness name, `ai-memory run` inspects checkout-local sessions for
-Claude Code, Codex, OpenCode, Pi, Crush, and Kimi Code. For an empty workstream
-it resumes
+Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, and Kiro CLI. 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
@@ -129,6 +129,7 @@ is labelled completed evidence and must never be replayed as a pending call.
| Pi | generated `--session-id` | `--session <id>` | `~/.pi/agent/sessions/**/*.jsonl` |
| Crush | native default creation | `--session <id>` | `<project>/.crush/crush.db` opened read-only |
| Kimi Code | native default creation | `--session <id>` | `$KIMI_CODE_HOME/sessions/*/*/agents/main/wire.jsonl` |
+| Kiro CLI | native default creation | `--resume-id <id>` | `$KIRO_HOME/sessions/cli/<uuid>.jsonl` (+ sibling `<uuid>.json` metadata) |
| OMP | native default creation | `--resume=<id>` | `~/.omp/agent/sessions/**/*.jsonl` |
An explicit native selector such as Claude's `--resume`, OpenCode's `--session`,
@@ -138,7 +139,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`, and `KIMI_CODE_HOME`.
+`PI_CODING_AGENT_SESSION_DIR`, `PI_CODING_AGENT_DIR`, `KIMI_CODE_HOME`, and
+`KIRO_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
@@ -151,7 +153,11 @@ 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`, and Kimi Code `--yolo`. OMP currently needs no added flag.
+Crush `--yolo`, Kimi Code `--yolo`, and Kiro CLI `--trust-all-tools` (the
+official v2-engine flag; a `--trust-tools=<set>` the user passed is an
+explicit narrower choice and is never widened, and a non-v2 engine selection
+maps nothing because Kiro v3 replaced the flag with `permissions.yaml` — the
+wrapper says so on stderr). OMP currently needs no added flag.
ai-memory does not add a duplicate when the translated native flag is already
present.
@@ -175,6 +181,7 @@ ai-memory install-hooks --agent opencode --apply
ai-memory install-hooks --agent pi --apply
ai-memory install-hooks --agent omp --apply
ai-memory install-hooks --agent kimi-code --apply
+ai-memory install-hooks --agent kiro-cli --apply
```
Kimi Code hooks installed as native `ai-memory hook` commands automatically
@@ -203,6 +210,29 @@ 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.
+Known Kiro CLI adapter limitations: managed continuity covers the **default
+v2 agent engine only**. Any `--v3`, `--mode`, or non-`v2` `--agent-engine`
+selection passes the whole invocation through unmanaged — v3 sessions live
+in a separate id space that the v2 engine cannot resume (the resume hint
+Kiro prints after a v3 session silently starts a fresh v2 session unless
+`--v3` is added), and the v3 persisted-session format is not publicly
+documented, so cross-engine resume is prevented by construction rather than
+detection. Headless `--no-interactive` runs persist to Kiro's v1 SQLite
+store (`~/.local/share/kiro-cli/data.sqlite3`) rather than the v2 session
+files, so they also pass through; only interactive chat sessions
+(`~/.kiro/sessions/cli/<uuid>.json` + `<uuid>.jsonl`) are discovered and
+imported. `/chat save`/`load` exports and Kiro's one-shot list/delete flags
+are passthrough utility invocations. The event stream is not verified
+append-only, so the adapter keeps a prefix-hash cursor like Kimi's: an
+in-place rewrite resets to the beginning and replays with stable line-hash
+event ids. The CLI argument surface (`--resume-id`, `--trust-all-tools`,
+`--agent-engine`, subcommand list) was verified against kiro-cli 2.16.0;
+the session-file shapes derive from the public references for kiro-cli
+1.29.x and MUST be revalidated against a logged-in current install before
+this adapter is relied on — the deterministic acceptance fixtures encode
+exactly that documented shape. The managed launcher accepts `kiro` and
+`kiro-cli`; both resolve the installed `kiro-cli` executable.
+
Crush needs no ai-memory hook installation for managed mode. The launcher reads
its one-time context from the server, copies the existing global Crush JSON into
a private temporary directory, appends an ephemeral context path, and points the
diff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.sh
index 5a68a8d3..54631f0c 100755
--- a/scripts/managed-workstream-acceptance.sh
+++ b/scripts/managed-workstream-acceptance.sh
@@ -107,6 +107,37 @@ case "${AI_MEMORY_ACCEPTANCE_FAKE_MODE:-argv}" in
packet=$(jq -r '.options.global_context_paths[-1]' "$CRUSH_GLOBAL_CONFIG/crush.json")
cp "$packet" "$AI_MEMORY_ACCEPTANCE_CRUSH_PACKET_LOG"
;;
+ kiro)
+ printf '%s\n' "$@" >"$AI_MEMORY_ACCEPTANCE_ARGV_LOG"
+ # Honor `--resume-id <id>` (resume); a fresh launch mints its own id
+ # because Kiro CLI session ids are server-assigned UUIDs.
+ session_id=""
+ previous_arg=""
+ for arg in "$@"; do
+ if [ "$previous_arg" = --resume-id ]; then
+ session_id=$arg
+ fi
+ previous_arg=$arg
+ done
+ if [ -z "$session_id" ]; then
+ session_id=$(cat /proc/sys/kernel/random/uuid)
+ fi
+ # Real layout: flat store, one `<uuid>.json` metadata + `<uuid>.jsonl`
+ # event-stream pair per session; discovery must read the metadata cwd.
+ store="${KIRO_HOME:?kiro fake mode requires KIRO_HOME}/sessions/cli"
+ mkdir -p "$store"
+ stream="$store/$session_id.jsonl"
+ if [ ! -f "$store/$session_id.json" ]; then
+ printf '{"session_id":"%s","cwd":"%s","created_at":"2026-08-01T10:00:00Z","updated_at":"2026-08-01T10:00:00Z","title":"acceptance","session_state":{"version":"v1","conversation_metadata":{}}}\n' \
+ "$session_id" "$PWD" >"$store/$session_id.json"
+ : >"$stream"
+ fi
+ sentinel=${AI_MEMORY_ACCEPTANCE_SENTINEL:-AMWS-FAKE-KIRO}
+ printf '{"version":"v1","kind":"Prompt","data":{"message_id":"m-%s-u","content":[{"kind":"text","data":"%s"}],"meta":{"timestamp":%s}}}\n' \
+ "$(date +%s)" "$sentinel" "$(date +%s)000" >>"$stream"
+ printf '{"version":"v1","kind":"AssistantMessage","data":{"message_id":"m-%s-a","content":[{"kind":"text","data":"%s reply"}],"meta":{"timestamp":%s}}}\n' \
+ "$(date +%s)" "$sentinel" "$(date +%s)000" >>"$stream"
+ ;;
kimi)
printf '%s\n' "$@" >"$AI_MEMORY_ACCEPTANCE_ARGV_LOG"
# Honor `--session <id>` (resume); a fresh launch mints its own id
@@ -410,6 +441,86 @@ jq -e \
exit 1
}
+# Kiro fake-mode fixture: the fake kiro honors `--resume-id <id>`, writes the
+# native flat store ($KIRO_HOME/sessions/cli/<uuid>.json + <uuid>.jsonl), and
+# appends the round sentinel as versioned v1 Prompt/AssistantMessage records.
+# A fresh launch injects no selector because Kiro session ids are
+# server-assigned; the wrapper links the session post-exit by exact-checkout
+# discovery through the sibling metadata JSON.
+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" \
+ kiro >"$LOGS/edge-kiro-first.log" 2>&1
+)
+if grep -q . "$TMP/kiro-first-argv.log"; then
+ printf 'fresh kiro launch unexpectedly received a session selector\n' >&2
+ cat "$TMP/kiro-first-argv.log" >&2
+ exit 1
+fi
+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
+}
+# An engine-selector invocation must pass through byte-identical: v3
+# sessions live in a separate id space the v2 engine cannot resume, so the
+# wrapper must never inject a selector next to `--v3`.
+(
+ 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" || {
+ printf 'kiro --v3 invocation was not passed through byte-identical\n' >&2
+ exit 1
+}
+
# A blank first launch remains eligible for one-time native-session adoption.
# Use a pseudo-terminal because redirected/scripted launches deliberately skip
# the chooser.
@@ -484,6 +595,16 @@ harnesses=()
for requested_harness in "${requested_harnesses[@]}"; do
case "$requested_harness" in
kimi-code | kimi-cli) harness=kimi ;;
+ # The real-harness round trip drives every harness through a scripted
+ # noninteractive turn, but headless Kiro (`--no-interactive`) persists
+ # to its v1 SQLite store rather than the v2 session files the managed
+ # adapter reads — so a scripted kiro turn is passthrough by design and
+ # cannot exchange sentinels. Kiro's wrapper mechanics are fully covered
+ # by the deterministic fake-harness phase above.
+ kiro | kiro-cli)
+ printf 'skipping kiro in the real-harness phase: headless runs use the v1 SQLite store (deterministic phase covers the adapter)\n' >&2
+ continue
+ ;;
*) harness=$requested_harness ;;
esac
if command -v "$harness" >/dev/null 2>&1; then