Skip to content

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

Rust

feat(workstream): support Command Code sessions (#373)

AkitaOnRails813b51aed104
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e10432e0..d61b73c1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,15 +19,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
writing v3 sessions to default `~/.kiro` despite custom `KIRO_HOME`: only a
resume proven to live in that fallback drops the override for its child
process. The optional deterministic acceptance runner now covers fresh,
- resume, and import round trips for both engines (#356).
+ resume, and import round trips for both engines. The server automatic-harness
+ validator now accepts the Kiro candidate pool advertised by the client,
+ preventing bare `ai-memory run` from rejecting a discovered Kiro session
+ before launch (#356).
- Added first-party Command Code MCP and stable lifecycle-hook support.
`install-mcp --client command-code` merges the documented user-scope HTTP
entry; `install-hooks --agent command-code` preserves existing settings and
registers only `SessionStart`, `PreToolUse`, `PostToolUse`, and `Stop` with
native session attribution, capture exclusions, and startup handoff
- injection. Experimental Mods and managed resume remain acceptance-gated,
- and the turn-only Stop boundary is documented with the manual finalizer
- workflow (#373).
+ injection. `ai-memory run command-code` now adds v3 checkout-scoped
+ transcript discovery, exact `--session <uuid>` resume, automatic harness
+ selection, native `--yolo` translation, and a visible-event allowlist that
+ retains branch parent ids and summaries while excluding hidden reasoning,
+ images, custom/Mod records, and provider metadata. Deterministic acceptance
+ covers fresh, resume, and incremental-import round trips. Experimental unsandboxed Mods remain
+ excluded, and the turn-only Stop boundary is documented with the manual
+ finalizer workflow (#373).
- `ai-memory finalize-session --session-id <uuid>` targets exactly one open
session instead of "the latest open one for this agent+scope". Agents with
no true SessionEnd hook (Kiro CLI, Codex, Antigravity CLI) rely on
diff --git a/README.md b/README.md
index e2a9cec0..ded7c015 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@
| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Local supported profiles default to host-native hook commands; Claude Code may use its Windows exec form, while other agents use native single command strings matching their hook schema. PowerShell/Git Bash scripts are compatibility fallbacks. See [`docs/windows.md`](docs/windows.md). |
| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. `install-mcp --session-aware` optionally enables per-session auto-scope isolation through a local stdio bridge. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). |
| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. No automatic true session-end hook, so run `ai-memory finalize-session` when you need a final summary/handoff. |
-| Command Code | Supported | MCP config (`~/.commandcode/mcp.json`) + its four stable lifecycle-hook events (`~/.commandcode/settings.json`); native commands enforce capture exclusions and `SessionStart` injects handoffs. `Stop` is only a turn boundary, so use `ai-memory finalize-session --agent command-code` after the final turn. Experimental Mods and managed workstreams remain acceptance-gated. |
+| Command Code | Supported | MCP config (`~/.commandcode/mcp.json`) + its four stable lifecycle-hook events (`~/.commandcode/settings.json`); native commands enforce capture exclusions and `SessionStart` injects handoffs. `Stop` is only a turn boundary, so use `ai-memory finalize-session --agent command-code` after the final turn. `ai-memory run command-code` adds exact v3 native-session resume and visible-event import; experimental unsandboxed Mods remain excluded. |
| Devin CLI | Supported | MCP config + lifecycle hooks. Hooks use Devin's `PostCompaction` event, inject handoffs via `hookSpecificOutput.additionalContext`, and omit subagent events because Devin does not expose them. |
| OpenCode | Supported | Remote MCP config + generated TypeScript plugin; generated plugin enforces capture exclusions. |
| Cursor | Supported | MCP config + lifecycle hooks. |
@@ -32,7 +32,7 @@
| 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, both incompatible Kiro CLI engines, 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, Command Code, both incompatible Kiro CLI engines, 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. |
@@ -70,21 +70,23 @@ priors are at the [bottom](#influences-and-prior-art).
notifications and tool excerpts retain up to 2 KB, with a 16 KiB durable
backstop for every observation body.
- **Opt-in managed workstreams.** `ai-memory run claude`, then `ai-memory run
- codex --yolo`, then `ai-memory run kimi`, transparently resumes one logical
- workstream with native per-harness sessions, a portable visible-event ledger,
- and full-ledger search. Delivered packets are origin-marked; Claude transcript
- import rejects a packet that Claude persisted and read back through a tool.
+ codex --yolo`, then `ai-memory run command-code`, transparently resumes one
+ logical workstream with native per-harness sessions, a portable visible-event
+ ledger, 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 v2/v3 session for this
- checkout.
+ Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, or Kiro CLI v2/v3
+ 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` and
`--fresh`; direct
commands are unaffected. `kimi-code` and `kimi-cli` are accepted aliases for
- the installed `kimi` command, and `kiro-cli` for the installed `kiro-cli`
- command. Kiro defaults to v2; `ai-memory run kiro --v3` selects v3, while a
+ the installed `kimi` command; `commandcode`, `cmdc`, and `cmd` select the
+ cross-platform `command-code` executable (`cmdc` on native Windows); and
+ `kiro-cli` selects the installed `kiro-cli` command. Kiro defaults to v2;
+ `ai-memory run kiro --v3` selects v3, while a
returning linked v3 workstream selects its engine transparently.
- **Per-repository capture exclusions.** A nearest-marker `[capture]`
`ignore_paths` policy drops matching recognized file-tool events before they
@@ -200,6 +202,9 @@ priors are at the [bottom](#influences-and-prior-art).
# Quit Claude Code, then continue the same workstream in Codex.
ai-memory run codex --yolo
+ # Continue in Command Code, preserving its own exact native session.
+ ai-memory run command-code
+
# Later, omit the name to resume the newest usable managed session here.
ai-memory run
@@ -252,8 +257,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, Kiro CLI v2/v3, OMP, Grok Build CLI,
- and Antigravity CLI; direct harness launches remain unchanged. See
+ Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, Kiro CLI v2/v3, 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:
@@ -996,7 +1001,7 @@ diagram, crate breakdown, schema notes, and invariants.
|---|---|
| [`docs/install.md`](docs/install.md) | **Installation cookbook.** Every agent CLI, every alternative (curl, source build, no-docker, no-auth), and the server-on-a-different-machine (homelab/LAN) walkthrough. Read after the Quick start if your setup doesn't match the happy path. |
| [`docs/usage.md`](docs/usage.md) | Handoffs, proactive memory queries, slim routing snippet + managed Agent Skills, migration from other memory tools, web UI, raw-wiki inspection, and rules-vs-facts workflow. |
-| [`docs/managed-workstreams.md`](docs/managed-workstreams.md) | Optional `ai-memory run` continuity across Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI v2/v3, OMP, Grok Build CLI, and Antigravity CLI: automatic harness selection, native resume, argument forwarding, ledger search, privacy, and recovery. |
+| [`docs/managed-workstreams.md`](docs/managed-workstreams.md) | Optional `ai-memory run` continuity across Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, Kiro CLI v2/v3, OMP, Grok Build CLI, and Antigravity CLI: automatic harness selection, native resume, argument forwarding, ledger search, privacy, and recovery. |
| [`docs/managed-harness-contributions.md`](docs/managed-harness-contributions.md) | Protocol and acceptance bar for contributors adding managed resume, read-only transcript import, and startup context delivery to another harness. |
| [`docs/marker-file.md`](docs/marker-file.md) | `.ai-memory.toml` workspace/project routing for multi-client trees, mono-repos, worktrees, and work/personal separation. |
| [`docs/auto-scope.md`](docs/auto-scope.md) | `[auto_scope]` modes for shared servers: default single-slot routing, session-aware isolation, and multi-user `per_actor` behavior. |
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 0c43f250..e80ce805 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -234,6 +234,14 @@ pub enum RunHarnessChoice {
/// Moonshot AI Kimi Code.
#[value(name = "kimi", alias = "kimi-code", alias = "kimi-cli")]
Kimi,
+ /// Command Code CLI.
+ #[value(
+ name = "command-code",
+ alias = "commandcode",
+ alias = "cmdc",
+ alias = "cmd"
+ )]
+ CommandCode,
/// Amazon Kiro CLI (v2 engine).
#[value(name = "kiro", alias = "kiro-cli")]
Kiro,
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 50bdcbf6..372fd23a 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -38,13 +38,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; 8] = [
+const AUTO_HARNESSES: [ManagedHarness; 9] = [
ManagedHarness::Claude,
ManagedHarness::Codex,
ManagedHarness::OpenCode,
ManagedHarness::Pi,
ManagedHarness::Crush,
ManagedHarness::Kimi,
+ ManagedHarness::CommandCode,
ManagedHarness::Kiro,
ManagedHarness::KiroV3,
];
@@ -707,7 +708,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, Kimi Code, Command 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`, `ai-memory run command-code`, or `ai-memory run kiro`"
)
}
@@ -1350,6 +1351,7 @@ const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {
RunHarnessChoice::Crush => ManagedHarness::Crush,
RunHarnessChoice::Omp => ManagedHarness::Omp,
RunHarnessChoice::Kimi => ManagedHarness::Kimi,
+ RunHarnessChoice::CommandCode => ManagedHarness::CommandCode,
RunHarnessChoice::Kiro => ManagedHarness::Kiro,
RunHarnessChoice::Grok => ManagedHarness::Grok,
RunHarnessChoice::Antigravity => ManagedHarness::Antigravity,
@@ -1373,6 +1375,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::CommandCode => Some(ManagedHarness::CommandCode),
AgentKind::KiroCli => Some(ManagedHarness::Kiro),
AgentKind::Grok => Some(ManagedHarness::Grok),
AgentKind::AntigravityCli => Some(ManagedHarness::Antigravity),
@@ -1788,6 +1791,34 @@ mod tests {
);
}
+ #[test]
+ fn command_code_aliases_select_the_managed_adapter() {
+ for name in ["command-code", "commandcode", "cmdc", "cmd"] {
+ let cli = Cli::try_parse_from([
+ OsStr::new("ai-memory"),
+ OsStr::new("run"),
+ OsStr::new(name),
+ OsStr::new("--print"),
+ OsStr::new("continue here"),
+ ])
+ .unwrap();
+ let CliCommand::Run(args) = cli.command else {
+ panic!("expected run command");
+ };
+ assert!(
+ matches!(
+ args.harness,
+ Some(crate::cli::RunHarnessChoice::CommandCode)
+ ),
+ "{name}"
+ );
+ assert_eq!(
+ args.native_args,
+ ["--print", "continue here"].map(OsString::from).to_vec()
+ );
+ }
+ }
+
#[test]
fn kiro_cli_alias_selects_the_kiro_adapter() {
for name in ["kiro", "kiro-cli"] {
diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rs
index a61de986..afbbdfc1 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::CommandCode
| AgentKind::KiroCli
| AgentKind::Grok
| AgentKind::AntigravityCli
@@ -145,13 +146,15 @@ async fn prepare_run(
"managed run requires a supported command-line harness",
);
}
- const AUTO_AGENTS: [AgentKind; 6] = [
+ const AUTO_AGENTS: [AgentKind; 8] = [
AgentKind::ClaudeCode,
AgentKind::Codex,
AgentKind::OpenCode,
AgentKind::Pi,
AgentKind::Crush,
AgentKind::KimiCode,
+ AgentKind::CommandCode,
+ AgentKind::KiroCli,
];
if request.automatic_harness
&& (!AUTO_AGENTS.contains(&request.agent)
@@ -898,7 +901,7 @@ mod tests {
}
#[tokio::test]
- async fn kiro_is_accepted_explicitly_but_not_in_the_automatic_pool() {
+ async fn kiro_is_accepted_as_an_explicit_and_automatic_harness() {
let temp = TempDir::new().unwrap();
let store = Store::open(temp.path()).unwrap();
let state = test_state(&store, temp.path());
@@ -925,6 +928,19 @@ mod tests {
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));
+ store
+ .writer
+ .finish_workstream_run(FinishWorkstreamRun {
+ run_id: prepared.run_id,
+ native_session_id: Some("7c1d5698-204a-4c0f-ae9c-43db7fc4e41d".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ })
+ .await
+ .unwrap();
let automatic = prepare_run(
State(state),
@@ -944,7 +960,70 @@ mod tests {
}),
)
.await;
- assert_eq!(automatic.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(automatic.status(), StatusCode::OK);
+ }
+
+ #[tokio::test]
+ async fn command_code_is_accepted_as_an_explicit_and_automatic_harness() {
+ 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::CommandCode,
+ 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::CommandCode));
+ store
+ .writer
+ .finish_workstream_run(FinishWorkstreamRun {
+ run_id: prepared.run_id,
+ native_session_id: Some("2cce5126-f57d-4ddd-8f66-e5bb409f60db".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ })
+ .await
+ .unwrap();
+
+ 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::CommandCode,
+ automatic_harness: true,
+ available_agents: vec![AgentKind::CommandCode, AgentKind::ClaudeCode],
+ workstream: None,
+ new_workstream: None,
+ lease_owner: "automatic".into(),
+ }),
+ )
+ .await;
+ assert_eq!(automatic.status(), StatusCode::OK);
}
#[tokio::test]
diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rs
index 10a3b7ca..35c5dace 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,
+ /// Command Code CLI.
+ CommandCode,
/// Amazon Kiro CLI (v2 engine).
Kiro,
/// Amazon Kiro CLI (v3 engine).
@@ -46,6 +48,7 @@ impl ManagedHarness {
"crush" => Some(Self::Crush),
"omp" | "oh-my-pi" => Some(Self::Omp),
"kimi" | "kimi-code" | "kimi-cli" => Some(Self::Kimi),
+ "command-code" | "commandcode" | "cmdc" | "cmd" => Some(Self::CommandCode),
"kiro" | "kiro-cli" => Some(Self::Kiro),
"grok" | "grok-build" => Some(Self::Grok),
"antigravity" | "antigravity-cli" | "agy" => Some(Self::Antigravity),
@@ -64,6 +67,7 @@ impl ManagedHarness {
Self::Crush => AgentKind::Crush,
Self::Omp => AgentKind::Omp,
Self::Kimi => AgentKind::KimiCode,
+ Self::CommandCode => AgentKind::CommandCode,
Self::Kiro | Self::KiroV3 => AgentKind::KiroCli,
Self::Grok => AgentKind::Grok,
Self::Antigravity => AgentKind::AntigravityCli,
@@ -81,6 +85,13 @@ impl ManagedHarness {
Self::Crush => "crush",
Self::Omp => "omp",
Self::Kimi => "kimi",
+ Self::CommandCode => {
+ if cfg!(windows) {
+ "cmdc"
+ } else {
+ "command-code"
+ }
+ }
Self::Kiro | Self::KiroV3 => "kiro-cli",
Self::Grok => "grok",
Self::Antigravity => "agy",
@@ -98,6 +109,7 @@ impl ManagedHarness {
Self::Crush => "crush",
Self::Omp => "omp",
Self::Kimi => "kimi",
+ Self::CommandCode => "command-code",
Self::Kiro => "kiro",
Self::KiroV3 => "kiro-v3",
Self::Grok => "grok",
@@ -278,6 +290,15 @@ pub fn build_launch_plan(
expected = Some(id.to_string());
}
}
+ ManagedHarness::CommandCode => {
+ // Command Code assigns UUIDs to fresh sessions. Use its exact
+ // session selector for a linked resume; a fresh session is
+ // discovered from the versioned transcript header after exit.
+ if let Some(id) = linked_session_id {
+ args.extend([OsString::from("--session"), OsString::from(id)]);
+ expected = Some(id.to_string());
+ }
+ }
ManagedHarness::Kiro | ManagedHarness::KiroV3 => {
// Both engines assign ids to fresh sessions. A linked session
// can be selected exactly after its engine-specific store has
@@ -333,6 +354,7 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {
ManagedHarness::Crush => Some("--yolo"),
ManagedHarness::Omp => None,
ManagedHarness::Kimi => Some("--yolo"),
+ ManagedHarness::CommandCode => Some("--yolo"),
ManagedHarness::Kiro => {
if kiro_selects_non_default_engine(args) {
None
@@ -352,6 +374,7 @@ 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"],
+ ManagedHarness::CommandCode => &["--yolo", "--dangerously-skip-permissions"],
// 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"],
@@ -381,6 +404,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::CommandCode => has_flag(args, &["--print", "-p"]),
ManagedHarness::Kiro | ManagedHarness::KiroV3 => has_flag(args, &["--no-interactive"]),
ManagedHarness::Grok => {
has_flag(args, &["--single", "-p", "--prompt-file", "--prompt-json"])
@@ -407,6 +431,9 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {
{
return LaunchMode::Passthrough;
}
+ if harness == ManagedHarness::CommandCode && has_flag(args, &["--list-models", "--ide-setup"]) {
+ return LaunchMode::Passthrough;
+ }
if matches!(harness, ManagedHarness::Kiro | ManagedHarness::KiroV3) {
// An unknown non-v2 engine remains passthrough rather than being
// assigned to either incompatible adapter. Headless runs and one-shot
@@ -554,6 +581,22 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {
"__plugin_run_node",
]
.as_slice(),
+ ManagedHarness::CommandCode => [
+ "info",
+ "status",
+ "help",
+ "whoami",
+ "update",
+ "feedback",
+ "taste",
+ "learn-taste",
+ "mcp",
+ "skills",
+ "mods",
+ "login",
+ "logout",
+ ]
+ .as_slice(),
// Every root command except `chat` in kiro-cli 2.16.2. Bare and
// flags-only invocations open chat and remain session-bearing.
ManagedHarness::Kiro | ManagedHarness::KiroV3 => [
@@ -683,6 +726,18 @@ pub fn has_native_session_selector(harness: ManagedHarness, args: &[OsString]) -
"-C",
],
),
+ ManagedHarness::CommandCode => has_flag(
+ args,
+ &[
+ "--session",
+ "--resume",
+ "--sessions",
+ "-r",
+ "--continue",
+ "-c",
+ "--fork-session",
+ ],
+ ),
ManagedHarness::Kiro | ManagedHarness::KiroV3 => has_flag(
args,
&["--resume", "-r", "--resume-id", "--resume-picker", "--list"],
@@ -731,6 +786,8 @@ 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::CommandCode => flag_value(args, &["--session", "--resume", "-r"])
+ .filter(|value| Uuid::parse_str(value).is_ok()),
ManagedHarness::Kiro | ManagedHarness::KiroV3 => 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
@@ -838,6 +895,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")),
+ // Command Code documents no session-root override. Its user store is
+ // rooted below HOME and remains isolated when the wrapper runs with a
+ // configured host home.
+ ManagedHarness::CommandCode => None,
ManagedHarness::Kiro => value("KIRO_HOME").map(|dir| dir.join("sessions/cli")),
ManagedHarness::KiroV3 => value("KIRO_HOME").map(|dir| dir.join("sessions")),
// Sessions live under `<GROK_HOME>/sessions/<encoded-cwd>/<id>/`.
@@ -993,6 +1054,10 @@ mod tests {
ManagedHarness::OpenCode,
&[OsString::from("run"), OsString::from("continue here")]
));
+ assert!(!allows_native_session_adoption(
+ ManagedHarness::CommandCode,
+ &[OsString::from("--print"), OsString::from("continue here")]
+ ));
}
#[test]
@@ -1078,6 +1143,7 @@ mod tests {
(ManagedHarness::Crush, Some("--yolo")),
(ManagedHarness::Omp, None),
(ManagedHarness::Kimi, Some("--yolo")),
+ (ManagedHarness::CommandCode, Some("--yolo")),
(ManagedHarness::Grok, Some("--yolo")),
(
ManagedHarness::Antigravity,
@@ -1096,6 +1162,79 @@ mod tests {
}
}
+ #[test]
+ fn command_code_resumes_exactly_and_preserves_native_arguments() {
+ let fresh = build_launch_plan(
+ ManagedHarness::CommandCode,
+ None,
+ vec![OsString::from("--model"), OsString::from("model-id")],
+ None,
+ )
+ .unwrap();
+ assert_eq!(strings(&fresh.args), ["--model", "model-id"]);
+ assert_eq!(fresh.expected_session_id, None);
+
+ let id = "7c1d5698-204a-4c0f-ae9c-43db7fc4e41d";
+ let resumed = build_launch_plan(
+ ManagedHarness::CommandCode,
+ None,
+ vec![OsString::from("--model"), OsString::from("model-id")],
+ Some(id),
+ )
+ .unwrap();
+ assert_eq!(
+ strings(&resumed.args),
+ ["--model", "model-id", "--session", id]
+ );
+ assert_eq!(resumed.expected_session_id.as_deref(), Some(id));
+ }
+
+ #[test]
+ fn command_code_explicit_selectors_and_utilities_are_not_overridden() {
+ let id = "2cce5126-f57d-4ddd-8f66-e5bb409f60db";
+ let exact = build_launch_plan(
+ ManagedHarness::CommandCode,
+ None,
+ vec![OsString::from("--session"), OsString::from(id)],
+ Some("7c1d5698-204a-4c0f-ae9c-43db7fc4e41d"),
+ )
+ .unwrap();
+ assert_eq!(strings(&exact.args), ["--session", id]);
+ assert_eq!(exact.expected_session_id.as_deref(), Some(id));
+
+ let named = build_launch_plan(
+ ManagedHarness::CommandCode,
+ None,
+ vec![OsString::from("--resume=auth refactor")],
+ Some("7c1d5698-204a-4c0f-ae9c-43db7fc4e41d"),
+ )
+ .unwrap();
+ assert_eq!(strings(&named.args), ["--resume=auth refactor"]);
+ assert_eq!(named.expected_session_id, None);
+
+ for args in [
+ vec![OsString::from("mcp"), OsString::from("list")],
+ vec![OsString::from("--no-session")],
+ vec![OsString::from("--list-models")],
+ ] {
+ let plan = build_launch_plan(ManagedHarness::CommandCode, None, args.clone(), Some(id))
+ .unwrap();
+ assert_eq!(plan.args, args);
+ assert_eq!(plan.mode, LaunchMode::Passthrough);
+ }
+ }
+
+ #[test]
+ fn command_code_yolo_recognizes_only_equivalent_dangerous_modes() {
+ let mut alias = vec![OsString::from("--dangerously-skip-permissions")];
+ apply_yolo(ManagedHarness::CommandCode, &mut alias);
+ assert_eq!(strings(&alias), ["--dangerously-skip-permissions"]);
+
+ let mut narrower = vec![OsString::from("--auto-accept")];
+ apply_yolo(ManagedHarness::CommandCode, &mut narrower);
+ assert_eq!(strings(&narrower), ["--auto-accept", "--yolo"]);
+ }
+
#[test]
fn omp_resume_uses_equals_form_without_reordering_native_args() {
let plan = build_launch_plan(
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index 8dfaf5e6..7ec2732b 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -412,6 +412,13 @@ fn export_jsonl(
&mut events,
&mut losses,
),
+ ManagedHarness::CommandCode => parse_command_code(
+ &value,
+ native_session_id,
+ &record_id,
+ &mut events,
+ &mut losses,
+ ),
ManagedHarness::Kiro => parse_kiro(
&value,
native_session_id,
@@ -949,6 +956,234 @@ fn parse_kimi(
}
}
+/// Command Code v3 session record. The stable documentation guarantees an
+/// append-only tree; the record-level allowlist was checked against the
+/// integrity-matched published 1.14.1 bundle and a sanitized live fixture.
+/// Parent ids are retained so a consumer can distinguish branch changes
+/// without importing hidden reasoning or provider metadata.
+fn parse_command_code(
+ value: &Value,
+ session: &str,
+ record_id: &str,
+ events: &mut Vec<NewWorkstreamEvent>,
+ losses: &mut Vec<String>,
+) {
+ let record_type = value.get("type").and_then(Value::as_str);
+ let parent_id = match value.get("parentId") {
+ Some(Value::String(parent)) => Some(parent.as_str()),
+ Some(Value::Null) | None => None,
+ Some(_) => {
+ losses.push("Command Code malformed parent ids were intentionally excluded".into());
+ return;
+ }
+ };
+ if matches!(record_type, Some("compaction") | Some("branch_summary")) {
+ let Some(summary) = value.get("summary").and_then(Value::as_str) else {
+ losses.push("Command Code malformed summaries were intentionally excluded".into());
+ return;
+ };
+ let (kind, summary_type) = if record_type == Some("compaction") {
+ (WorkstreamEventKind::Compaction, "compaction")
+ } else {
+ (WorkstreamEventKind::Message, "branch-summary")
+ };
+ push_event(
+ events,
+ AgentKind::CommandCode,
+ session,
+ record_id,
+ 0,
+ kind,
+ Some("assistant"),
+ summary,
+ timestamp(value),
+ json!({"parent_id": parent_id, "summary_type": summary_type}),
+ );
+ return;
+ }
+ if record_type != Some("message") {
+ return;
+ }
+ let Some(message) = value.get("message").and_then(Value::as_object) else {
+ losses.push("Command Code malformed message records were intentionally excluded".into());
+ return;
+ };
+ let Some(role) = message.get("role").and_then(Value::as_str) else {
+ losses.push("Command Code messages without a role were intentionally excluded".into());
+ return;
+ };
+ let source = message
+ .get("meta")
+ .and_then(|meta| meta.get("source"))
+ .and_then(Value::as_str);
+ if message
+ .get("meta")
+ .and_then(|meta| meta.get("isMeta"))
+ .and_then(Value::as_bool)
+ == Some(true)
+ {
+ losses.push("Command Code synthetic/meta messages were intentionally excluded".into());
+ return;
+ }
+ if !matches!(
+ (role, source),
+ ("user", Some("user")) | ("assistant", Some("model"))
+ ) {
+ losses
+ .push("Command Code non-user/model message records were intentionally excluded".into());
+ return;
+ }
+ let Some(parts) = message.get("content").and_then(Value::as_array) else {
+ losses.push(
+ "Command Code messages without content blocks were intentionally excluded".into(),
+ );
+ return;
+ };
+ let occurred_at = timestamp(value);
+ for (index, part) in parts.iter().enumerate() {
+ match (role, part.get("type").and_then(Value::as_str)) {
+ ("user", Some("text")) => {
+ let Some(text) = part.get("text").and_then(Value::as_str) else {
+ losses.push(
+ "Command Code malformed text blocks were intentionally excluded".into(),
+ );
+ continue;
+ };
+ push_event(
+ events,
+ AgentKind::CommandCode,
+ session,
+ record_id,
+ index,
+ WorkstreamEventKind::Message,
+ Some("user"),
+ text,
+ occurred_at.clone(),
+ json!({"parent_id": parent_id}),
+ );
+ }
+ ("assistant", Some("text")) => {
+ let Some(text) = part.get("text").and_then(Value::as_str) else {
+ losses.push(
+ "Command Code malformed text blocks were intentionally excluded".into(),
+ );
+ continue;
+ };
+ push_event(
+ events,
+ AgentKind::CommandCode,
+ session,
+ record_id,
+ index,
+ WorkstreamEventKind::Message,
+ Some("assistant"),
+ text,
+ occurred_at.clone(),
+ json!({"parent_id": parent_id}),
+ );
+ }
+ ("assistant", Some("thinking")) => {
+ losses.push("Command Code hidden reasoning was intentionally excluded".into());
+ }
+ ("assistant", Some("tool_use")) => {
+ let (Some(tool_id), Some(name), Some(input)) = (
+ part.get("id").and_then(Value::as_str),
+ part.get("name").and_then(Value::as_str),
+ part.get("input").filter(|value| value.is_object()),
+ ) else {
+ losses.push(
+ "Command Code malformed tool calls were intentionally excluded".into(),
+ );
+ continue;
+ };
+ push_event(
+ events,
+ AgentKind::CommandCode,
+ session,
+ record_id,
+ index,
+ WorkstreamEventKind::ToolCall,
+ Some("assistant"),
+ &format!("{name}: {}", compact_json(input)),
+ occurred_at.clone(),
+ json!({"tool": name, "tool_use_id": tool_id, "parent_id": parent_id}),
+ );
+ }
+ ("user", Some("tool_result")) => {
+ parse_command_code_tool_result(
+ part,
+ session,
+ record_id,
+ index,
+ parent_id,
+ occurred_at.clone(),
+ events,
+ losses,
+ );
+ }
+ (_, Some(_)) | (_, None) => losses
+ .push("Command Code unsupported content blocks were intentionally excluded".into()),
+ }
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+fn parse_command_code_tool_result(
+ part: &Value,
+ session: &str,
+ record_id: &str,
+ block: usize,
+ parent_id: Option<&str>,
+ occurred_at: Option<String>,
+ events: &mut Vec<NewWorkstreamEvent>,
+ losses: &mut Vec<String>,
+) {
+ let Some(tool_use_id) = part.get("tool_use_id").and_then(Value::as_str) else {
+ losses.push("Command Code malformed tool results were intentionally excluded".into());
+ return;
+ };
+ let Some(parts) = part.get("content").and_then(Value::as_array) else {
+ losses.push("Command Code malformed tool results were intentionally excluded".into());
+ return;
+ };
+ let mut texts = Vec::new();
+ for item in parts {
+ match item.get("type").and_then(Value::as_str) {
+ Some("text") => {
+ if let Some(text) = item.get("text").and_then(Value::as_str) {
+ texts.push(text);
+ } else {
+ losses.push(
+ "Command Code malformed tool-result text was intentionally excluded".into(),
+ );
+ }
+ }
+ Some("image") => {
+ losses.push("Command Code image tool results were intentionally excluded".into());
+ }
+ _ => losses.push(
+ "Command Code unsupported tool-result content was intentionally excluded".into(),
+ ),
+ }
+ }
+ push_event(
+ events,
+ AgentKind::CommandCode,
+ session,
+ record_id,
+ block,
+ WorkstreamEventKind::ToolResult,
+ Some("tool"),
+ &texts.join("\n"),
+ occurred_at,
+ json!({
+ "tool_use_id": tool_use_id,
+ "parent_id": parent_id,
+ "is_error": part.get("is_error").and_then(Value::as_bool).unwrap_or(false),
+ }),
+ );
+}
+
/// One event per text part of a kimi message; `think` reasoning and media
/// parts become loss annotations. Returns the number of content parts seen so
/// callers can index sibling events (tool calls) without collisions.
@@ -1987,6 +2222,27 @@ fn locate_session_file(
}
}
}
+ if harness == ManagedHarness::CommandCode {
+ // The project bucket is a one-way cwd slug. Enumerate only that level,
+ // then probe the exact UUID filename and validate its self-describing
+ // header before returning it.
+ if Uuid::parse_str(id).is_err() {
+ return Ok(None);
+ }
+ if let Ok(buckets) = fs::read_dir(root) {
+ for bucket in buckets.take(MAX_SCAN_FILES) {
+ let bucket = bucket?;
+ if !bucket.file_type()?.is_dir() {
+ continue;
+ }
+ let candidate = bucket.path().join(format!("{id}.jsonl"));
+ if session_path_matches(harness, &candidate, id, cwd)? {
+ return Ok(Some(candidate));
+ }
+ }
+ }
+ return Ok(None);
+ }
if harness == ManagedHarness::Kiro {
// The store is flat and shared by every checkout. Require both the
// UUID file name and its sibling metadata to identify this checkout;
@@ -2072,6 +2328,15 @@ fn transcript_file(harness: ManagedHarness, path: &Path) -> bool {
.and_then(|stem| stem.to_str())
.is_some_and(|stem| Uuid::parse_str(stem).is_ok());
}
+ if harness == ManagedHarness::CommandCode {
+ // Sidecars such as `<id>.checkpoints.jsonl` do not have a UUID file
+ // stem and are excluded from discovery and import.
+ 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::KiroV3 {
return path.file_name().and_then(|name| name.to_str()) == Some("messages.jsonl")
&& path
@@ -2101,6 +2366,9 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(String
if harness == ManagedHarness::Kimi {
return kimi_session_header(path);
}
+ if harness == ManagedHarness::CommandCode {
+ return command_code_session_header(path);
+ }
if harness == ManagedHarness::Kiro {
return kiro_session_header(path);
}
@@ -2139,6 +2407,7 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(String
ManagedHarness::OpenCode
| ManagedHarness::Crush
| ManagedHarness::Kimi
+ | ManagedHarness::CommandCode
| ManagedHarness::Kiro
| ManagedHarness::KiroV3
| ManagedHarness::Grok
@@ -2151,6 +2420,49 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(String
Ok(None)
}
+/// Command Code v3 transcripts are self-describing on their first line. Fail
+/// closed on an unknown version, malformed UUID/timestamp/path, or a header id
+/// that disagrees with the transcript filename.
+fn command_code_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 mut reader = BufReader::new(File::open(path)?);
+ let mut line = String::new();
+ let read =
+ std::io::Read::take(&mut reader, (MAX_EVENT_BYTES + 1) as u64).read_line(&mut line)?;
+ if read == 0 || read > MAX_EVENT_BYTES {
+ return Ok(None);
+ }
+ let Ok(header) = serde_json::from_str::<Value>(&line) else {
+ return Ok(None);
+ };
+ if header.get("type").and_then(Value::as_str) != Some("session")
+ || header.get("version").and_then(Value::as_u64) != Some(3)
+ {
+ return Ok(None);
+ }
+ let (Some(id), Some(timestamp), Some(cwd)) = (
+ header.get("id").and_then(Value::as_str),
+ header.get("timestamp").and_then(Value::as_str),
+ header.get("cwd").and_then(Value::as_str),
+ ) else {
+ return Ok(None);
+ };
+ let cwd = PathBuf::from(cwd);
+ if id != stem
+ || Uuid::parse_str(id).is_err()
+ || timestamp.parse::<jiff::Timestamp>().is_err()
+ || !cwd.is_absolute()
+ {
+ return Ok(None);
+ }
+ Ok(Some((id.to_string(), cwd)))
+}
+
fn session_header_for_cwd(
harness: ManagedHarness,
path: &Path,
@@ -2616,6 +2928,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::CommandCode => home.join(".commandcode/projects"),
ManagedHarness::Kiro => home.join(".kiro/sessions/cli"),
ManagedHarness::KiroV3 => home.join(".kiro/sessions"),
ManagedHarness::Grok => home.join(".grok/sessions"),
@@ -2840,6 +3153,7 @@ mod tests {
ManagedHarness::OpenCode
| ManagedHarness::Crush
| ManagedHarness::Kimi
+ | ManagedHarness::CommandCode
| ManagedHarness::Kiro
| ManagedHarness::KiroV3
| ManagedHarness::Grok
@@ -2870,6 +3184,203 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn command_code_v3_discovery_requires_exact_uuid_header_and_checkout() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let other = temp.path().join("other");
+ let root = temp.path().join("command-code-projects");
+ let bucket = root.join("opaque-project-slug");
+ fs::create_dir_all(&cwd).unwrap();
+ fs::create_dir_all(&other).unwrap();
+ fs::create_dir_all(&bucket).unwrap();
+
+ let matching = "7c1d5698-204a-4c0f-ae9c-43db7fc4e41d";
+ let wrong_checkout = "2cce5126-f57d-4ddd-8f66-e5bb409f60db";
+ let future_schema = "bb40bd9b-d60a-4a87-91c6-57d12c3d3002";
+ fs::write(
+ bucket.join(format!("{matching}.jsonl")),
+ format!(
+ "{}\n",
+ json!({"type":"session","version":3,"id":matching,"timestamp":"2026-08-07T17:00:00Z","cwd":cwd})
+ ),
+ )
+ .unwrap();
+ fs::write(
+ bucket.join(format!("{wrong_checkout}.jsonl")),
+ format!(
+ "{}\n",
+ json!({"type":"session","version":3,"id":wrong_checkout,"timestamp":"2026-08-07T17:00:00Z","cwd":other})
+ ),
+ )
+ .unwrap();
+ fs::write(
+ bucket.join(format!("{future_schema}.jsonl")),
+ format!(
+ "{}\n",
+ json!({"type":"session","version":4,"id":future_schema,"timestamp":"2026-08-07T17:00:00Z","cwd":cwd})
+ ),
+ )
+ .unwrap();
+ fs::write(
+ bucket.join(format!("{matching}.checkpoints.jsonl")),
+ "{\"prompt\":\"private checkpoint\"}\n",
+ )
+ .unwrap();
+
+ let sessions = list_native_sessions(
+ ManagedHarness::CommandCode,
+ temp.path(),
+ &cwd,
+ Some(&root),
+ 8,
+ )
+ .await
+ .unwrap();
+ assert_eq!(sessions.len(), 1);
+ assert_eq!(sessions[0].native_session_id, matching);
+ assert!(
+ native_session_exists(
+ ManagedHarness::CommandCode,
+ temp.path(),
+ &cwd,
+ Some(&root),
+ matching,
+ )
+ .unwrap()
+ );
+ assert!(
+ !native_session_exists(
+ ManagedHarness::CommandCode,
+ temp.path(),
+ &cwd,
+ Some(&root),
+ wrong_checkout,
+ )
+ .unwrap()
+ );
+ assert!(
+ !native_session_exists(
+ ManagedHarness::CommandCode,
+ temp.path(),
+ &cwd,
+ Some(&root),
+ future_schema,
+ )
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn command_code_v3_exports_only_visible_allowlisted_blocks_incrementally() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ fs::create_dir_all(&cwd).unwrap();
+ let session = "7c1d5698-204a-4c0f-ae9c-43db7fc4e41d";
+ let path = temp.path().join(format!("{session}.jsonl"));
+ let records = [
+ json!({"type":"session","version":3,"id":session,"timestamp":"2026-08-07T17:00:00Z","cwd":cwd}),
+ json!({"type":"message","id":"u1","parentId":null,"timestamp":"2026-08-07T17:00:01Z","message":{"role":"user","content":[{"type":"text","text":"visible user"}],"meta":{"source":"user"}}}),
+ json!({"type":"message","id":"a1","parentId":"u1","timestamp":"2026-08-07T17:00:02Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"private reasoning","signature":"private signature"},{"type":"text","text":"visible assistant"},{"type":"tool_use","id":"tool-1","name":"read_directory","input":{"path":"src"}}],"meta":{"source":"model"}},"model":"private model","usage":{"costUsd":99}}),
+ json!({"type":"message","id":"t1","parentId":"a1","timestamp":"2026-08-07T17:00:03Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-1","is_error":true,"content":[{"type":"text","text":"visible result"},{"type":"image","source":{"type":"base64","data":"private image"}}]}],"meta":{"source":"user"}}}),
+ json!({"type":"compaction","id":"c1","parentId":"t1","timestamp":"2026-08-07T17:00:04Z","summary":"visible compacted context","firstKeptEntryId":"u1","tokensBefore":1000,"details":"private details"}),
+ json!({"type":"branch_summary","id":"b1","parentId":"u1","timestamp":"2026-08-07T17:00:05Z","fromId":"c1","summary":"visible abandoned-branch summary","details":"private details"}),
+ json!({"type":"message","id":"injected","parentId":"b1","timestamp":"2026-08-07T17:00:06Z","message":{"role":"user","content":[{"type":"text","text":"harness context"}],"meta":{"source":"hook"}}}),
+ ];
+ fs::write(
+ &path,
+ records
+ .iter()
+ .map(|record| format!("{record}\n"))
+ .collect::<String>(),
+ )
+ .unwrap();
+
+ let first = export_jsonl(ManagedHarness::CommandCode, &path, session, None).unwrap();
+ assert_eq!(first.events.len(), 6);
+ assert_eq!(
+ first
+ .events
+ .iter()
+ .map(|event| (event.kind, event.role.as_deref(), event.content.as_str()))
+ .collect::<Vec<_>>(),
+ [
+ (WorkstreamEventKind::Message, Some("user"), "visible user"),
+ (
+ WorkstreamEventKind::Message,
+ Some("assistant"),
+ "visible assistant",
+ ),
+ (
+ WorkstreamEventKind::ToolCall,
+ Some("assistant"),
+ "read_directory: {\"path\":\"src\"}",
+ ),
+ (
+ WorkstreamEventKind::ToolResult,
+ Some("tool"),
+ "visible result",
+ ),
+ (
+ WorkstreamEventKind::Compaction,
+ Some("assistant"),
+ "visible compacted context",
+ ),
+ (
+ WorkstreamEventKind::Message,
+ Some("assistant"),
+ "visible abandoned-branch summary",
+ ),
+ ]
+ );
+ assert_eq!(first.events[1].metadata["parent_id"], "u1");
+ assert_eq!(first.events[2].metadata["tool_use_id"], "tool-1");
+ assert_eq!(first.events[3].metadata["parent_id"], "a1");
+ assert_eq!(first.events[3].metadata["is_error"], true);
+ assert_eq!(first.events[4].metadata["summary_type"], "compaction");
+ assert_eq!(first.events[5].metadata["summary_type"], "branch-summary");
+ assert!(
+ first
+ .losses
+ .iter()
+ .any(|loss| loss.contains("hidden reasoning"))
+ );
+ assert!(
+ first
+ .losses
+ .iter()
+ .any(|loss| loss.contains("image tool results"))
+ );
+ assert!(
+ first
+ .losses
+ .iter()
+ .any(|loss| loss.contains("non-user/model"))
+ );
+ assert!(first.events.iter().all(|event| {
+ !event.content.contains("private") && !event.content.contains("harness context")
+ }));
+
+ let mut file = fs::OpenOptions::new().append(true).open(&path).unwrap();
+ use std::io::Write as _;
+ writeln!(
+ file,
+ "{}",
+ json!({"type":"message","id":"a2","parentId":"u1","timestamp":"2026-08-07T17:00:07Z","message":{"role":"assistant","content":[{"type":"text","text":"visible alternate branch"}],"meta":{"source":"model"}}})
+ )
+ .unwrap();
+ let second = export_jsonl(
+ ManagedHarness::CommandCode,
+ &path,
+ session,
+ first.source_cursor.as_deref(),
+ )
+ .unwrap();
+ assert_eq!(second.events.len(), 1);
+ assert_eq!(second.events[0].content, "visible alternate branch");
+ assert_eq!(second.events[0].metadata["parent_id"], "u1");
+ }
+
#[tokio::test]
async fn opencode_candidate_discovery_is_newest_first_and_checkout_scoped() {
let temp = tempfile::tempdir().unwrap();
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index e5be8886..b7dd342a 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, Kiro CLI, 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, Command 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 bdbef71f..188dd24f 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -777,18 +777,25 @@ ai-memory finalize-session --agent command-code
ai-memory finalize-session --agent command-code --session-id <uuid>
```
-ai-memory does not install Command Code Mods. Mods are currently documented
-as experimental, run unsandboxed, and do not provide the same stable native
-session identity at every callback. Managed `ai-memory run command-code`
-support is also withheld. Command Code documents append-only JSONL transcripts
-under `~/.commandcode/projects/<project-slug>/`, native `--continue`,
-`--resume`, and `--session` selectors, `--yolo`, and the Windows `cmdc` alias.
-It does not document the JSONL record schema needed for bounded visible-event
-import. A logged-in acceptance run must still supply sanitized structural
-fixtures and validate checkout matching, incremental import, resume identity,
-normal-exit finalization, and native Windows behavior before ai-memory manages
-those sessions. Direct `cmd`, `cmdc`, or `command-code` launches remain
-unchanged.
+ai-memory does not install Command Code Mods. Mods run arbitrary unsandboxed
+code and are not needed for the stable hook or managed-session paths.
+
+Managed sessions are opt-in:
+
+```bash
+ai-memory run command-code
+ai-memory run command-code --yolo --model <model-id>
+```
+
+The aliases `commandcode`, `cmdc`, and `cmd` select the same adapter. The
+default executable is `command-code` on Unix and `cmdc` on native Windows.
+Fresh sessions keep Command Code's native UUID; returning sessions use exact
+`--session <uuid>`. The read-only adapter accepts only the observed v3 header,
+requires its UUID filename and canonical `cwd` to match the checkout, excludes
+checkpoint/prompt sidecars, hidden reasoning, images, and provider metadata,
+and preserves `parentId` on visible events for branch provenance. An unknown
+future transcript version fails closed until its schema is audited. Direct
+`cmd`, `cmdc`, or `command-code` launches remain unchanged.
### Kiro CLI
@@ -1459,7 +1466,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| Subcommand | Pattern | What it does |
|---|---|---|
| `serve` | `docker compose up -d` (already done) | Run the HTTP MCP server |
-| `run [harness] [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; omit the harness to resume the newest usable local session, or name Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Kiro CLI v2/v3, OMP, Grok Build CLI, or Antigravity CLI explicitly; exact `--yolo` and `--fresh` flags are wrapper-owned and other native arguments pass through |
+| `run [harness] [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; omit the harness to resume the newest usable local session, or name Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, Kiro CLI v2/v3, OMP, Grok Build CLI, or Antigravity CLI explicitly; exact `--yolo` and `--fresh` flags are wrapper-owned and other native arguments pass through |
| `show [--json]` | host wrapper or native binary | Choose a client-local checkout and installed managed harness, or return structured discovery data without launching; remote servers never provide checkout paths |
| `continue [--workspace NAME]` | host wrapper or native binary | From any directory, revalidate and resume the newest client-local managed checkout; accepts `--yolo` and `--fresh` but no harness-native arguments |
| `workstream-search [query]` | managed child or thin HTTP client | Search the complete visible managed-workstream ledger; the managed child receives its workstream id automatically |
diff --git a/docs/managed-harness-contributions.md b/docs/managed-harness-contributions.md
index 467b34a7..c8c74c91 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, Kiro CLI
-v2/v3, 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, Command
+Code, Kiro CLI v2/v3, 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 503755b4..9c442d5b 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, Kiro CLI v2/v3,
-OMP, Grok Build CLI, and Antigravity CLI. Direct agent launches
+between Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, Kiro
+CLI v2/v3, 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
+# Command Code uses `command-code` on Unix and `cmdc` on native Windows
+ai-memory run command-code
# Kiro defaults to v2; select its incompatible v3 engine explicitly once
ai-memory run kiro
ai-memory run kiro --v3
@@ -40,7 +42,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|kiro|grok|antigravity]
+ [claude|codex|opencode|pi|crush|omp|kimi|command-code|kiro|grok|antigravity]
[native arguments...]
```
@@ -121,8 +123,8 @@ 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 both Kiro CLI engines.
-For an empty workstream it resumes
+Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, and both Kiro
+CLI engines. 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
@@ -230,23 +232,25 @@ 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` |
+| Command Code | native default creation | `--session <uuid>` | `~/.commandcode/projects/*/<uuid>.jsonl` |
| Kiro CLI v2 | native default creation | `--resume-id <uuid>` | `$KIRO_HOME/sessions/cli/<uuid>.jsonl` (+ sibling `<uuid>.json` metadata) |
| Kiro CLI v3 | native default creation with `--v3` | `--v3 --resume-id <sess_uuid>` | `$KIRO_HOME/sessions/<checkout-bucket>/<sess_uuid>/messages.jsonl` (+ sibling `session.json` metadata) |
| OMP | native default creation | `--resume=<id>` | `~/.omp/agent/sessions/**/*.jsonl` |
| Grok Build CLI | generated `--session-id` | `--resume <id>` | `$GROK_HOME/sessions/*/*/chat_history.jsonl` |
| Antigravity CLI | native default creation | `--conversation <id>` | `~/.gemini/antigravity-cli/conversations/<id>.db` metadata plus lifecycle-hook capture |
-Command Code is intentionally absent from this table. Its first-party MCP and
-stable lifecycle-hook integration does not imply managed resume support.
-The official session contract establishes append-only JSONL transcripts at
-`~/.commandcode/projects/<project-slug>/<session-id>.jsonl`, native
-`--continue`, `--resume`, and `--session` selectors, `--yolo`, and `cmdc` as
-the native Windows alias. The record-level JSONL schema is not documented.
-Before adding a managed adapter, a logged-in current release must therefore
-supply sanitized structural fixtures and validate project-slug ownership,
-branch-aware visible-event extraction, incremental append behavior, resume
-identity, normal-exit finalization, and native Windows execution. Experimental
-Mod APIs are not a substitute for those native-session acceptance artifacts.
+Command Code v3 transcripts are self-describing and append-only. The adapter
+requires the UUID filename, header id, and canonical header `cwd` to agree
+before discovery or resume. Its 1.14.1 allowlist was checked against both the
+integrity-matched published package and a sanitized live fixture. It imports
+visible messages, compactions, and branch summaries, retains `parentId` as
+branch provenance, and excludes hidden thinking, images, harness-injected
+messages, provider/model metadata, custom/Mod records, and every sidecar. An
+unknown transcript version fails closed until audited.
+The default executable is `command-code` on Unix and `cmdc` on native Windows;
+`commandcode`, `cmdc`, and `cmd` are accepted launcher aliases. Exact user
+`--session`, `--resume`, `--continue`, and fork choices remain authoritative.
+The experimental unsandboxed Mod API is not used.
An explicit native selector such as Claude's `--resume`, OpenCode's `--session`,
Codex's `resume`, or Antigravity's `--conversation` / `--continue` wins.
@@ -270,8 +274,9 @@ 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`, Kiro CLI v2 `--trust-all-tools`, Grok Build
-CLI `--yolo` (equivalent to its `--always-approve` option), and Antigravity CLI
+Crush `--yolo`, Kimi Code `--yolo`, Command Code `--yolo`, Kiro CLI v2
+`--trust-all-tools`, Grok Build CLI `--yolo` (equivalent to its
+`--always-approve` option), and Antigravity CLI
`--dangerously-skip-permissions`. Kiro v3 replaced the trust-all flag with
`permissions.yaml`, so ai-memory prints a notice and adds no unverified flag.
OMP currently needs no added flag. ai-memory does not add a duplicate when the
@@ -453,8 +458,8 @@ 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, Kiro, OMP, Grok, or Antigravity private stores. The launched harness
-retains normal ownership of its own session writes. Adapters read only
+Kimi Code, Command 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
server sanitizer runs before both the SQLite FTS ledger and immutable files under
@@ -470,7 +475,8 @@ 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 `cwd` or legacy `workDir`), Kiro v2
+Pi, Kimi Code (`state.json`'s `cwd` or legacy `workDir`), Command Code (v3
+header `cwd`), Kiro v2
(`<uuid>.json`'s `cwd`), Kiro v3 (`session.json`'s `workspacePaths`), OMP, and
Antigravity may still reference the old path; Crush's project-local `.crush`
database moves with the checkout.
@@ -488,8 +494,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, Grok, and
-Antigravity CLIs through one real workstream:
+the locally installed Claude, Codex, OpenCode, Pi, Crush, OMP, Kimi, Command
+Code, Grok, and Antigravity CLIs through one real workstream:
```bash
scripts/managed-workstream-acceptance.sh
@@ -502,12 +508,14 @@ OpenCode receive only copied authentication material; OMP receives a temporary
agent directory with read-consistent credential/model database backups and
copied settings. Crush uses its existing global provider configuration and an
isolated project database. Kimi Code runs with an isolated `$KIMI_CODE_HOME`
-seeded with the operator's provider configuration. Antigravity runs with an
-isolated `HOME` seeded only with the operator's OAuth and settings files. The
+seeded with the operator's provider configuration. Command Code runs with an
+isolated `HOME` seeded only with `auth.json` and `config.json`. Antigravity runs
+with an 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, a fake-mode Kiro v2 store/resume/import round trip,
+cleanup, fake-mode Kimi and Command Code store/resume/import round trips, an
+Antigravity hook/link/resume round trip, a fake-mode Kiro v2
+store/resume/import round trip,
the equivalent Kiro v3 nested-store round trip with transparent engine recovery,
private-trajectory exclusion, and the
established-workstream guard against obsolete sessions. The fake Kimi round
@@ -545,6 +553,8 @@ Grok and Antigravity cross-harness fixtures exercise the same assertion helper
without credentials or model calls.
Set
+`AI_MEMORY_ACCEPTANCE_HARNESSES="command-code codex"` to select a
+Command-Code-to-Codex-to-Command-Code round trip, or
`AI_MEMORY_ACCEPTANCE_HARNESSES="antigravity codex"` to select an
Antigravity-to-Codex-to-Antigravity round trip (`agy` and `antigravity-cli` are
accepted aliases), `AI_MEMORY_ACCEPTANCE_DETERMINISTIC_ONLY=1` to skip model
diff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.sh
index 50bdeb4d..701b8417 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 kiro grok antigravity"}
+HARNESS_WORDS=${AI_MEMORY_ACCEPTANCE_HARNESSES:-"claude codex opencode pi crush omp kimi command-code kiro grok antigravity"}
TMP=$(mktemp -d "${TMPDIR:-/tmp}/ai-memory-workstream-acceptance.XXXXXX")
DATA="$TMP/data"
REPO="$TMP/repo"
@@ -322,6 +322,40 @@ case "${AI_MEMORY_ACCEPTANCE_FAKE_MODE:-argv}" in
printf '{"type":"context.append_message","time":%s,"message":{"role":"assistant","content":[{"type":"text","text":"%s reply"}],"toolCalls":[]}}\n' \
"$(date +%s)000" "$sentinel" >>"$wire"
;;
+ command-code)
+ printf '%s\n' "$@" >"$AI_MEMORY_ACCEPTANCE_ARGV_LOG"
+ session_id=""
+ previous_arg=""
+ for arg in "$@"; do
+ if [ "$previous_arg" = --session ]; then
+ session_id=$arg
+ fi
+ previous_arg=$arg
+ done
+ if [ -z "$session_id" ]; then
+ 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 'command-code fake mode needs uuidgen or /proc/sys/kernel/random/uuid\n' >&2
+ exit 1
+ fi
+ fi
+ store="$HOME/.commandcode/projects/opaque_fixture_slug"
+ mkdir -p "$store"
+ stream="$store/$session_id.jsonl"
+ if [ ! -f "$stream" ]; then
+ printf '{"type":"session","version":3,"id":"%s","timestamp":"2026-08-07T17:00:00Z","cwd":"%s"}\n' \
+ "$session_id" "$PWD" >"$stream"
+ fi
+ sentinel=${AI_MEMORY_ACCEPTANCE_SENTINEL:-AMWS-FAKE-COMMAND-CODE}
+ now=$(date +%s)
+ printf '{"type":"message","id":"u-%s","parentId":null,"timestamp":"2026-08-07T17:00:01Z","message":{"role":"user","content":[{"type":"text","text":"%s"}],"meta":{"source":"user"}}}\n' \
+ "$now" "$sentinel" >>"$stream"
+ printf '{"type":"message","id":"a-%s","parentId":"u-%s","timestamp":"2026-08-07T17:00:02Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"private reasoning","signature":"private signature"},{"type":"text","text":"%s reply"}],"meta":{"source":"model"}}}\n' \
+ "$now" "$now" "$sentinel" >>"$stream"
+ ;;
grok)
printf '%s\n' "$@" >"$AI_MEMORY_ACCEPTANCE_ARGV_LOG"
# Honor the wrapper-owned `--session-id <id>` (fresh) and `--resume <id>`
@@ -493,16 +527,24 @@ grep -q 'session was found for this directory' \
AUTO_HOME="$CONFIG/auto-home"
AUTO_CODEX_HOME="$AUTO_HOME/.codex"
AUTO_CLAUDE_HOME="$AUTO_HOME/.claude"
+AUTO_COMMAND_CODE_HOME="$AUTO_HOME/.commandcode"
AUTO_BIN="$AUTO_HOME/bin"
mkdir -p "$AUTO_CODEX_HOME/sessions/2026/01/01" \
- "$AUTO_CLAUDE_HOME/projects/fixture" "$AUTO_BIN"
+ "$AUTO_CLAUDE_HOME/projects/fixture" \
+ "$AUTO_COMMAND_CODE_HOME/projects/opaque_fixture_slug" "$AUTO_BIN"
ln -s "$FAKE" "$AUTO_BIN/codex"
ln -s "$FAKE" "$AUTO_BIN/claude"
+ln -s "$FAKE" "$AUTO_BIN/command-code"
printf '{"sessionId":"auto-claude-old","cwd":"%s"}\n' "$REPO" \
>"$AUTO_CLAUDE_HOME/projects/fixture/auto-claude-old.jsonl"
sleep 1
printf '{"type":"session_meta","payload":{"id":"auto-codex-new","cwd":"%s"}}\n' \
"$REPO" >"$AUTO_CODEX_HOME/sessions/2026/01/01/rollout-auto.jsonl"
+sleep 1
+AUTO_COMMAND_CODE_ID="7c1d5698-204a-4c0f-ae9c-43db7fc4e41d"
+printf '{"type":"session","version":3,"id":"%s","timestamp":"2026-08-07T17:00:00Z","cwd":"%s"}\n' \
+ "$AUTO_COMMAND_CODE_ID" "$REPO" \
+ >"$AUTO_COMMAND_CODE_HOME/projects/opaque_fixture_slug/$AUTO_COMMAND_CODE_ID.jsonl"
(
cd "$REPO"
HOME="$AUTO_HOME" CODEX_HOME="$AUTO_CODEX_HOME" \
@@ -513,11 +555,11 @@ printf '{"type":"session_meta","payload":{"id":"auto-codex-new","cwd":"%s"}}\n'
>"$LOGS/edge-auto-newest.log" 2>&1
)
diff -u \
- <(printf '%s\n' resume auto-codex-new --dangerously-bypass-approvals-and-sandbox) \
+ <(printf '%s\n' --session "$AUTO_COMMAND_CODE_ID" --yolo) \
"$TMP/auto-newest-argv.log"
-# Establish Claude after Codex, then verify bare run follows the managed
-# workstream's current Claude link instead of the newer but obsolete Codex file.
+# Establish Claude after Command Code, then verify bare run follows the managed
+# workstream's current Claude link instead of newer but obsolete native files.
(
cd "$REPO"
HOME="$AUTO_HOME" CLAUDE_CONFIG_DIR="$AUTO_CLAUDE_HOME" \
@@ -693,6 +735,66 @@ kimi_current_id=$(sqlite3 "$DATA/db/memory.sqlite" \
exit 1
}
+# Command Code v3 fixture: the fake creates an exact UUID transcript under an
+# opaque project slug, then accepts the same `--session <uuid>` selector on the
+# returning leg. HOME isolates the documented user store from real sessions.
+COMMAND_CODE_FAKE_HOME="$CONFIG/command-code-fake"
+mkdir -p "$COMMAND_CODE_FAKE_HOME"
+(
+ cd "$REPO"
+ HOME="$COMMAND_CODE_FAKE_HOME" \
+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=command-code \
+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/command-code-first-argv.log" \
+ AI_MEMORY_ACCEPTANCE_SENTINEL="AMWS-FAKE-COMMAND-CODE-ONE" \
+ "$BIN" --data-dir "$DATA" run --new edge-command-code --executable "$FAKE" \
+ --yolo command-code >"$LOGS/edge-command-code-first.log" 2>&1
+)
+diff -u <(printf '%s\n' --yolo) "$TMP/command-code-first-argv.log"
+command_code_session_file=$(find "$COMMAND_CODE_FAKE_HOME/.commandcode/projects" \
+ -mindepth 2 -maxdepth 2 -name '*.jsonl' ! -name '*.checkpoints.jsonl' -print -quit)
+[ -n "$command_code_session_file" ] || {
+ printf 'fake command-code did not create a native session transcript\n' >&2
+ exit 1
+}
+command_code_session_id=$(basename "$command_code_session_file" .jsonl)
+command_code_ws_hex=$(sqlite3 "$DATA/db/memory.sqlite" \
+ "SELECT lower(hex(id)) FROM workstreams WHERE name = 'edge-command-code' ORDER BY selected_at DESC LIMIT 1;")
+[ "${#command_code_ws_hex}" -eq 32 ] || {
+ printf 'could not resolve the edge-command-code workstream id\n' >&2
+ exit 1
+}
+command_code_ws_id="${command_code_ws_hex:0:8}-${command_code_ws_hex:8:4}-${command_code_ws_hex:12:4}-${command_code_ws_hex:16:4}-${command_code_ws_hex:20:12}"
+command_code_first_hits=$("$BIN" --data-dir "$DATA" workstream-search \
+ --workstream-id "$command_code_ws_id" --limit 100 --json "AMWS-FAKE-COMMAND-CODE-ONE")
+jq -e --arg id "$command_code_session_id" \
+ '[.[] | select(.agent == "command-code" and .role == "assistant" and (.content | contains("AMWS-FAKE-COMMAND-CODE-ONE")) and .native_session_id == $id)] | length == 1' \
+ <<<"$command_code_first_hits" >/dev/null || {
+ printf 'command-code transcript sentinel was not imported\n' >&2
+ tail -80 "$LOGS/edge-command-code-first.log" >&2
+ exit 1
+}
+(
+ cd "$REPO"
+ HOME="$COMMAND_CODE_FAKE_HOME" \
+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=command-code \
+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/command-code-second-argv.log" \
+ AI_MEMORY_ACCEPTANCE_SENTINEL="AMWS-FAKE-COMMAND-CODE-TWO" \
+ "$BIN" --data-dir "$DATA" run --workstream edge-command-code --executable "$FAKE" \
+ cmdc >"$LOGS/edge-command-code-second.log" 2>&1
+)
+diff -u <(printf '%s\n' --session "$command_code_session_id") \
+ "$TMP/command-code-second-argv.log"
+command_code_second_hits=$("$BIN" --data-dir "$DATA" workstream-search \
+ --workstream-id "$command_code_ws_id" --limit 100 --json "AMWS-FAKE-COMMAND-CODE")
+jq -e \
+ '([.[] | select(.role == "assistant" and (.content | contains("AMWS-FAKE-COMMAND-CODE-ONE")))] | length == 1)
+ and ([.[] | select(.role == "assistant" and (.content | contains("AMWS-FAKE-COMMAND-CODE-TWO")))] | length == 1)' \
+ <<<"$command_code_second_hits" >/dev/null || {
+ printf 'command-code incremental import duplicated or missed a sentinel\n' >&2
+ tail -80 "$LOGS/edge-command-code-second.log" >&2
+ exit 1
+}
+
# Kiro fake-mode fixtures cover both incompatible native stores. The fake owns
# each fresh id, writes the sanitized schema observed in live acceptance, and
# honors the exact engine-specific resume selected by the wrapper.
@@ -1085,6 +1187,7 @@ harnesses=()
for requested_harness in "${requested_harnesses[@]}"; do
case "$requested_harness" in
kimi-code | kimi-cli) harness=kimi ;;
+ commandcode | cmdc | cmd) harness=command-code ;;
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
@@ -1118,6 +1221,8 @@ OMP_EXTENSION="$CONFIG/omp/ai-memory.ts"
OMP_AGENT_DIR="$CONFIG/omp/agent"
CRUSH_DATA_DIR="$CONFIG/crush/data"
KIMI_ACCEPTANCE_HOME="$CONFIG/kimi-home"
+COMMAND_CODE_ACCEPTANCE_HOME="$CONFIG/command-code-home"
+COMMAND_CODE_SETTINGS="$COMMAND_CODE_ACCEPTANCE_HOME/.commandcode/settings.json"
GROK_ACCEPTANCE_HOME="$CONFIG/grok-home"
ANTIGRAVITY_ACCEPTANCE_HOME="$CONFIG/antigravity-home"
ANTIGRAVITY_HOOKS="$ANTIGRAVITY_ACCEPTANCE_HOME/.gemini/config/hooks.json"
@@ -1125,6 +1230,7 @@ mkdir -p "$(dirname "$CLAUDE_SETTINGS")" "$(dirname "$CODEX_HOOKS")" \
"$(dirname "$OPENCODE_PLUGIN")" "$(dirname "$PI_EXTENSION")" \
"$(dirname "$OMP_EXTENSION")" "$OMP_AGENT_DIR" "$OPENCODE_DATA_HOME/opencode" \
"$CRUSH_DATA_DIR" "$KIMI_ACCEPTANCE_HOME" "$GROK_ACCEPTANCE_HOME" \
+ "$(dirname "$COMMAND_CODE_SETTINGS")" \
"$(dirname "$ANTIGRAVITY_HOOKS")" \
"$ANTIGRAVITY_ACCEPTANCE_HOME/.gemini/antigravity-cli"
@@ -1181,6 +1287,16 @@ for relative in credentials/kimi-code.json oauth/kimi-code device_id; do
fi
done
+# Command Code resolves its documented user config, credentials, hooks, and
+# session catalog through HOME/USERPROFILE. Copy only login/model preferences;
+# the acceptance HOME receives a fresh session store and hook file.
+for relative in auth.json config.json; do
+ if [ -f "$HOME/.commandcode/$relative" ]; then
+ cp "$HOME/.commandcode/$relative" \
+ "$COMMAND_CODE_ACCEPTANCE_HOME/.commandcode/$relative"
+ fi
+done
+
# Grok resolves everything below $GROK_HOME. Seed the isolated home with the
# operator's login state and settings only; native sessions, logs, and caches
# remain isolated.
@@ -1233,6 +1349,7 @@ install_hook opencode "$OPENCODE_PLUGIN"
install_hook pi "$PI_EXTENSION"
install_hook omp "$OMP_EXTENSION"
install_hook kimi-code "$KIMI_ACCEPTANCE_HOME/config.toml"
+install_hook command-code "$COMMAND_CODE_SETTINGS"
install_hook antigravity-cli "$ANTIGRAVITY_HOOKS"
agent_wire_name() {
@@ -1240,6 +1357,7 @@ agent_wire_name() {
claude) printf 'claude-code\n' ;;
opencode) printf 'open-code\n' ;;
kimi) printf 'kimi-code\n' ;;
+ command-code) printf 'command-code\n' ;;
antigravity) printf 'antigravity-cli\n' ;;
*) printf '%s\n' "$1" ;;
esac
@@ -1305,6 +1423,10 @@ run_harness() {
native_args=(-p "$prompt")
[ -z "${AI_MEMORY_ACCEPTANCE_KIMI_MODEL:-}" ] || native_args=(-p -m "$AI_MEMORY_ACCEPTANCE_KIMI_MODEL" "$prompt")
;;
+ command-code)
+ native_args=(-p --no-auto-update "$prompt")
+ [ -z "${AI_MEMORY_ACCEPTANCE_COMMAND_CODE_MODEL:-}" ] || native_args=(-p --no-auto-update -m "$AI_MEMORY_ACCEPTANCE_COMMAND_CODE_MODEL" "$prompt")
+ ;;
grok)
native_args=(-p "$prompt")
[ -z "${AI_MEMORY_ACCEPTANCE_GROK_MODEL:-}" ] || native_args=(-p -m "$AI_MEMORY_ACCEPTANCE_GROK_MODEL" "$prompt")
@@ -1342,6 +1464,10 @@ run_harness() {
(cd "$REPO" && KIMI_CODE_HOME="$KIMI_ACCEPTANCE_HOME" \
"$BIN" --data-dir "$DATA" run "${wrapper_args[@]}" "$harness" "${native_args[@]}") \
>"$log" 2>&1
+ elif [ "$harness" = command-code ]; then
+ (cd "$REPO" && HOME="$COMMAND_CODE_ACCEPTANCE_HOME" \
+ "$BIN" --data-dir "$DATA" run "${wrapper_args[@]}" "$harness" "${native_args[@]}") \
+ >"$log" 2>&1
elif [ "$harness" = grok ]; then
(cd "$REPO" && GROK_HOME="$GROK_ACCEPTANCE_HOME" \
"$BIN" --data-dir "$DATA" run "${wrapper_args[@]}" "$harness" "${native_args[@]}") \