Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(workstream): add Grok Build CLI managed harness
iagogfe9c6a2ab38498
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3183aca0..62930bb7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0the local SQLite index directly, so every CLI command is a thin HTTPclient of the running server; the command now requires a reachableserver and no longer works against an offline data directory.+- Managed workstream support for Grok Build CLI: `ai-memory run grok` (alias+ `grok-build`) creates fresh sessions with a wrapper-generated `--session-id`,+ resumes linked sessions with `--resume`, maps wrapper `--yolo` onto Grok's+ native `--yolo`/`--always-approve`, and delivers the bounded workstream+ context packet through Grok's native `--rules` flag (system-prompt append,+ acknowledged only after the child spawns). Transcript import reads+ `$GROK_HOME/sessions/*/*/chat_history.jsonl` read-only with a+ prefix-validated cursor and content-hash event ids so rewind-driven journal+ rewrites cannot duplicate history; system prompts, encrypted reasoning, and+ the injected `<user_info>` block are excluded as loss annotations. Discovery+ matches checkouts through `summary.json`'s recorded `info.cwd` and honors+ `GROK_HOME`. Grok stays out of the bare-mode automatic pool. Verified+ against Grok Build CLI v0.2.111 ([#237]).## [1.18.0] - 2026-07-23diff --git a/README.md b/README.mdindex 583aa94c..945131f4 100644--- a/README.md+++ b/README.md@@ -31,11 +31,11 @@| 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, OMP, and Grok Build 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). |-| 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`). |+| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no hook handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). || Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. || Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. || VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). |diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 10ba9150..e58f0d32 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -219,6 +219,9 @@ pub enum RunHarnessChoice {/// Moonshot AI Kimi Code.#[value(name = "kimi", alias = "kimi-code", alias = "kimi-cli")]Kimi,+ /// Grok Build CLI (xAI).+ #[value(alias = "grok-build")]+ Grok,}/// Arguments for `workstream-search`.diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 731d152d..d2e0cb44 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -150,6 +150,7 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {provisional_harness};acquired_try!(ensure_executable_available(harness, executable.as_deref()));+ let native_grok_rules = user_supplied_grok_rules(&native_args);let mut plan = acquired_try!(build_launch_plan(harness,executable.clone(),@@ -253,6 +254,25 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {} else {None};+ let grok_context = if harness == ManagedHarness::Grok && plan.mode == LaunchMode::Session {+ // `--rules` is single-use in Grok's argument parser, so a user-supplied+ // rules flag wins and the packet stays undelivered (it is redelivered+ // on the next managed run that can accept it).+ if native_grok_rules {+ eprintln!(+ "ai-memory: --rules was supplied natively; the workstream context packet will be delivered on a later run"+ );+ None+ } else {+ acquired_try!(fetch_grok_context(&endpoint, &run_path).await)+ }+ } else {+ None+ };+ if let Some(context) = &grok_context {+ plan.args+ .extend([OsString::from("--rules"), OsString::from(context)]);+ }if interrupted_before_spawn.load(Ordering::SeqCst) {acquired_try!(Err(anyhow!("managed run interrupted before the agent started"@@ -307,15 +327,18 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {));}};- if harness == ManagedHarness::Crush+ if (harness == ManagedHarness::Crush || grok_context.is_some())&& let Err(error) = post_empty_with_retry(&endpoint,&format!("{run_path}/context/accept"),- "acknowledging Crush managed context",+ "acknowledging managed context",).await{- eprintln!("ai-memory: {error}; the context may be delivered again on the next Crush run");+ eprintln!(+ "ai-memory: {error}; the context may be delivered again on the next {} run",+ harness.as_str()+ );}let mut heartbeat = tokio::time::interval(HEARTBEAT_INTERVAL);@@ -570,6 +593,30 @@ fn executable_file(path: &Path) -> bool {}}+fn user_supplied_grok_rules(native_args: &[OsString]) -> bool {+ native_args.iter().any(|arg| {+ arg.to_str().is_some_and(|value| {+ ["--rules", "--append-system-prompt"]+ .iter()+ .any(|name| value == *name || value.starts_with(&format!("{name}=")))+ })+ })+}++/// Grok appends `--rules` text to its session system prompt, so the packet is+/// delivered as an argument instead of a file. Acceptance happens only after+/// the child spawns, matching the Crush contract.+async fn fetch_grok_context(endpoint: &ServerEndpoint, run_path: &str) -> Result<Option<String>> {+ let response: ManagedRunContextResponse = post_json(+ endpoint,+ &format!("{run_path}/context"),+ &serde_json::json!({}),+ )+ .await+ .context("loading the managed context for Grok; the agent was not started")?;+ Ok(response.context)+}+async fn prepare_crush_context(endpoint: &ServerEndpoint,run_path: &str,@@ -982,6 +1029,7 @@ const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {RunHarnessChoice::Crush => ManagedHarness::Crush,RunHarnessChoice::Omp => ManagedHarness::Omp,RunHarnessChoice::Kimi => ManagedHarness::Kimi,+ RunHarnessChoice::Grok => ManagedHarness::Grok,}}@@ -993,6 +1041,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::Grok => Some(ManagedHarness::Grok),_ => None,}}@@ -1026,6 +1075,24 @@ mod tests {]}+ #[test]+ fn native_grok_rules_flags_suppress_context_injection() {+ for args in [+ vec![OsString::from("--rules"), OsString::from("be terse")],+ vec![OsString::from("--rules=be terse")],+ vec![+ OsString::from("--append-system-prompt"),+ OsString::from("x"),+ ],+ ] {+ assert!(user_supplied_grok_rules(&args), "{args:?}");+ }+ assert!(!user_supplied_grok_rules(&[+ OsString::from("--model"),+ OsString::from("grok-4.5")+ ]));+ }+#[test]fn lease_owner_uses_the_resolved_host_and_process() {assert_eq!(lease_owner_label(Some("workstation"), 42), "workstation:42");diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex c0a7cf85..54672a29 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::Grok) {return error(StatusCode::BAD_REQUEST,@@ -311,10 +312,10 @@ async fn run_context(Ok(None) => return error(StatusCode::NOT_FOUND, "active managed run not found"),Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),};- if context.agent != AgentKind::Crush {+ if !matches!(context.agent, AgentKind::Crush | AgentKind::Grok) {return error(StatusCode::BAD_REQUEST,- "direct managed context is only supported for Crush",+ "direct managed context is only supported for Crush and Grok",);}if context.context_delivered {@@ -346,10 +347,10 @@ async fn accept_run_context(Ok(None) => return error(StatusCode::NOT_FOUND, "managed run not found"),Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),};- if status.agent != AgentKind::Crush {+ if !matches!(status.agent, AgentKind::Crush | AgentKind::Grok) {return error(StatusCode::BAD_REQUEST,- "direct managed context is only supported for Crush",+ "direct managed context is only supported for Crush and Grok",);}match state.writer.accept_managed_run_context(run_id).await {@@ -894,6 +895,104 @@ mod tests {assert_eq!(automatic.status(), StatusCode::OK);}+ #[tokio::test]+ async fn grok_is_accepted_explicitly_but_not_in_the_automatic_pool() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());++ let explicit = prepare_run(+ State(state.clone()),+ None,+ Json(PrepareManagedRunRequest {+ workspace: "default".into(),+ project: "managed".into(),+ cwd: "/repo".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ agent: AgentKind::Grok,+ 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::Grok));+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: prepared.run_id,+ native_session_id: Some("019f-session".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::Grok,+ automatic_harness: true,+ available_agents: vec![AgentKind::Grok],+ workstream: None,+ new_workstream: None,+ lease_owner: "automatic".into(),+ }),+ )+ .await;+ assert_eq!(automatic.status(), StatusCode::BAD_REQUEST);+ }++ #[tokio::test]+ async fn grok_run_context_uses_the_direct_delivery_gate() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let (workspace_id, project_id) = seed_scope(&store).await;+ let input = prepare_input(workspace_id, project_id, AgentKind::Grok, "launcher");+ let prepared = store.writer.prepare_workstream_run(input).await.unwrap();++ let context = run_context(+ State(state.clone()),+ None,+ AxumPath(prepared.run_id.to_string()),+ )+ .await;+ assert_eq!(context.status(), StatusCode::OK);++ let accept = accept_run_context(+ State(state.clone()),+ None,+ AxumPath(prepared.run_id.to_string()),+ )+ .await;+ assert_eq!(accept.status(), StatusCode::NO_CONTENT);++ // Delivered context is not re-rendered.+ let redelivered = run_context(State(state), None, AxumPath(prepared.run_id.to_string()))+ .await+ .into_body();+ let body = to_bytes(redelivered, 64 * 1024).await.unwrap();+ let response: ai_memory_core::ManagedRunContextResponse =+ serde_json::from_slice(&body).unwrap();+ assert!(response.context.is_none());+ }+#[tokio::test]async fn cancel_endpoint_is_idempotent_and_releases_the_workstream() {let temp = TempDir::new().unwrap();diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rsindex 642c9d5d..b3228f55 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,+ /// Grok Build CLI (xAI).+ Grok,}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),+ "grok" | "grok-build" => Some(Self::Grok),_ => None,}}@@ -53,6 +56,7 @@ impl ManagedHarness {Self::Crush => AgentKind::Crush,Self::Omp => AgentKind::Omp,Self::Kimi => AgentKind::KimiCode,+ Self::Grok => AgentKind::Grok,}}@@ -67,6 +71,7 @@ impl ManagedHarness {Self::Crush => "crush",Self::Omp => "omp",Self::Kimi => "kimi",+ Self::Grok => "grok",}}@@ -81,6 +86,7 @@ impl ManagedHarness {Self::Crush => "crush",Self::Omp => "omp",Self::Kimi => "kimi",+ Self::Grok => "grok",}}}@@ -209,6 +215,18 @@ pub fn build_launch_plan(expected = Some(id.to_string());}}+ ManagedHarness::Grok => {+ let id = linked_session_id+ .map(str::to_owned)+ .unwrap_or_else(|| Uuid::new_v4().to_string());+ let selector = if linked_session_id.is_some() {+ "--resume"+ } else {+ "--session-id"+ };+ args.extend([OsString::from(selector), OsString::from(&id)]);+ expected = Some(id);+ }}}@@ -233,13 +251,17 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {ManagedHarness::Crush => Some("--yolo"),ManagedHarness::Omp => None,ManagedHarness::Kimi => Some("--yolo"),+ ManagedHarness::Grok => Some("--yolo"),};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.+ // Grok's `--yolo` is a hidden alias of the documented+ // `--always-approve`; either spelling satisfies the request.let present: &[&str] = match harness {ManagedHarness::Kimi => &["--yolo", "-y", "--yes", "--auto-approve", "--auto"],+ ManagedHarness::Grok => &["--yolo", "--always-approve"],_ => &[flag],};if !has_flag(args, present) {@@ -265,6 +287,9 @@ fn noninteractive_invocation(harness: ManagedHarness, args: &[OsString]) -> boolManagedHarness::Crush => first_arg_is(args, "run"),ManagedHarness::Pi | ManagedHarness::Omp => has_flag(args, &["--print", "-p"]),ManagedHarness::Kimi => has_flag(args, &["--prompt", "-p"]),+ ManagedHarness::Grok => {+ has_flag(args, &["--single", "-p", "--prompt-file", "--prompt-json"])+ }}}@@ -401,6 +426,33 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {"__plugin_run_node",].as_slice(),+ // `agent` covers the stdio/headless/serve/leader runners, which manage+ // their own session lifecycles and must not receive selectors.+ ManagedHarness::Grok => [+ "agent",+ "completions",+ "dashboard",+ "doctor",+ "export",+ "help",+ "inspect",+ "leader",+ "login",+ "logout",+ "mcp",+ "memory",+ "models",+ "plugin",+ "sessions",+ "setup",+ "trace",+ "update",+ "version",+ "v",+ "worktree",+ "wrap",+ ]+ .as_slice(),};let first = args.first().and_then(|arg| arg.to_str());if first.is_some_and(|value| utility.contains(&value)) {@@ -454,6 +506,21 @@ fn has_explicit_session_selector(harness: ManagedHarness, args: &[OsString]) ->"-C",],),+ // A bare `--resume` opens Grok's native session picker; that is still+ // an explicit user choice. `--fork-session` modifies how the explicit+ // resume/continue selector behaves and never appears alone.+ ManagedHarness::Grok => has_flag(+ args,+ &[+ "--resume",+ "-r",+ "--continue",+ "-c",+ "--session-id",+ "-s",+ "--fork-session",+ ],+ ),}}@@ -479,6 +546,7 @@ fn explicit_session_id(harness: ManagedHarness, args: &[OsString]) -> Option<Str// A bare `--session`/`--resume` opens the picker: `flag_value`// returns `None` when no value follows, as intended.ManagedHarness::Kimi => flag_value(args, &["--session", "-S", "--resume", "-r"]),+ ManagedHarness::Grok => flag_value(args, &["--resume", "-r", "--session-id", "-s"]),}}@@ -560,6 +628,8 @@ 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")),+ // Sessions live under `<GROK_HOME>/sessions/<encoded-cwd>/<id>/`.+ ManagedHarness::Grok => value("GROK_HOME").map(|dir| dir.join("sessions")),}}@@ -794,6 +864,7 @@ mod tests {(ManagedHarness::Crush, Some("--yolo")),(ManagedHarness::Omp, None),(ManagedHarness::Kimi, Some("--yolo")),+ (ManagedHarness::Grok, Some("--yolo")),] {let mut args = Vec::new();apply_yolo(harness, &mut args);@@ -1009,6 +1080,99 @@ mod tests {}}+ #[test]+ fn grok_generates_then_resumes_native_session() {+ let fresh = build_launch_plan(ManagedHarness::Grok, None, vec![], None).unwrap();+ let id = fresh.expected_session_id.clone().unwrap();+ assert_eq!(strings(&fresh.args), ["--session-id", id.as_str()]);++ let resumed = build_launch_plan(+ ManagedHarness::Grok,+ None,+ vec![OsString::from("--model"), OsString::from("grok-4.5")],+ Some(&id),+ )+ .unwrap();+ assert_eq!(+ strings(&resumed.args),+ ["--model", "grok-4.5", "--resume", id.as_str()]+ );+ }++ #[test]+ fn grok_explicit_selector_always_wins_including_bare_picker_and_fork() {+ for native in [+ vec![OsString::from("--resume"), OsString::from("chosen")],+ vec![OsString::from("--session-id=chosen")],+ vec![OsString::from("-c")],+ vec![OsString::from("--fork-session")],+ // Bare `--resume` opens the native picker; still an explicit+ // choice, so nothing may be injected.+ vec![OsString::from("--resume")],+ ] {+ let plan =+ build_launch_plan(ManagedHarness::Grok, None, native.clone(), Some("linked"))+ .unwrap();+ assert_eq!(plan.args, native, "{native:?} must stay byte-identical");+ assert_ne!(plan.expected_session_id.as_deref(), Some("linked"));+ }+ }++ #[test]+ fn grok_utility_subcommands_are_passed_through() {+ for utility in ["agent", "sessions", "login", "export", "doctor", "wrap"] {+ let plan = build_launch_plan(+ ManagedHarness::Grok,+ None,+ vec![OsString::from(utility)],+ Some("linked"),+ )+ .unwrap();+ assert_eq!(plan.mode, LaunchMode::Passthrough, "{utility}");+ assert_eq!(strings(&plan.args), [utility]);+ }+ }++ #[test]+ fn grok_noninteractive_prompt_blocks_adoption() {+ for args in [+ vec![OsString::from("-p"), OsString::from("summarize")],+ vec![OsString::from("--single"), OsString::from("summarize")],+ vec![OsString::from("--prompt-file"), OsString::from("p.md")],+ ] {+ assert!(!allows_native_session_adoption(ManagedHarness::Grok, &args));+ }+ assert!(allows_native_session_adoption(+ ManagedHarness::Grok,+ &[OsString::from("--model"), OsString::from("grok-4.5")]+ ));+ }++ #[test]+ fn grok_yolo_respects_the_always_approve_alias() {+ for already in ["--yolo", "--always-approve"] {+ let mut args = vec![OsString::from(already)];+ apply_yolo(ManagedHarness::Grok, &mut args);+ assert_eq!(strings(&args), [already], "{already} must not duplicate");+ }+ }++ #[test]+ fn grok_build_name_is_an_alias_for_grok() {+ for name in ["grok", "grok-build"] {+ assert_eq!(ManagedHarness::from_name(name), Some(ManagedHarness::Grok));+ }+ }++ #[test]+ fn grok_home_environment_override_points_at_sessions_root() {+ let get = |name: &str| (name == "GROK_HOME").then(|| OsString::from("/stores/grok"));+ assert_eq!(+ environment_session_dir_with(ManagedHarness::Grok, get).as_deref(),+ Some(std::path::Path::new("/stores/grok/sessions"))+ );+ }+#[test]fn kimi_home_environment_override_points_at_sessions_root() {let get =diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsindex 923afbc3..49b7fef9 100644--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -45,13 +45,20 @@ pub struct ExportedTranscript {struct FileCursor {path: String,offset: u64,- /// Hash of every committed byte through `offset`. Kimi Code can rewrite- /// its journal in place, so its adapter validates this prefix before- /// trusting the byte offset. Other JSONL adapters remain offset-only.+ /// Hash of every committed byte through `offset`. Kimi Code and Grok can+ /// rewrite their journals in place (Kimi on fork/compaction/resume, Grok+ /// on rewind), so those adapters validate this prefix before trusting the+ /// byte offset. Other JSONL adapters remain offset-only.#[serde(default, skip_serializing_if = "Option::is_none")]prefix_sha256: Option<String>,}+/// Harnesses whose JSONL journal can be rewritten in place, requiring+/// prefix-validated cursors and content-hash record ids.+const fn journal_rewrites_in_place(harness: ManagedHarness) -> bool {+ matches!(harness, ManagedHarness::Kimi | ManagedHarness::Grok)+}+#[derive(Debug, Clone, Serialize, Deserialize, Default)]struct SqlCursor {updated: i64,@@ -204,7 +211,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 journal_rewrites_in_place(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 +245,8 @@ fn export_jsonl(if !line.ends_with(b"\n") {break;}- if harness == ManagedHarness::Kimi {- kimi_prefix_hasher.update(&line);+ if journal_rewrites_in_place(harness) {+ prefix_hasher.update(&line);}committed_offset = offset;let value: Value = match serde_json::from_slice(&line) {@@ -252,10 +259,11 @@ fn export_jsonl(continue;}};- let record_id = if harness == ManagedHarness::Kimi {- // 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+ let record_id = if journal_rewrites_in_place(harness) {+ // Kimi wire records and Grok chat-history records carry no+ // envelope id, and both journals can be rewritten wholesale (Kimi+ // on fork/compaction/resume, Grok on rewind) — a byte-offset id+ // would silently change meaning. Hashing the raw line keeps// record ids (and therefore server-side event dedup) stable// across rewrites.let raw = line.strip_suffix(b"\n").unwrap_or(&line);@@ -293,6 +301,13 @@ fn export_jsonl(&mut events,&mut losses,),+ ManagedHarness::Grok => parse_grok(+ &value,+ native_session_id,+ &record_id,+ &mut events,+ &mut losses,+ ),ManagedHarness::OpenCode | ManagedHarness::Crush => {return Err(anyhow!("{} transcripts must use their SQLite adapter",@@ -309,8 +324,8 @@ 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: journal_rewrites_in_place(harness)+ .then(|| format!("{:x}", prefix_hasher.finalize())),})?),events,losses: deduplicate_losses(losses),@@ -911,6 +926,127 @@ fn annotate_kimi_subagents(path: &Path, losses: &mut Vec<String>) {}}+/// Grok chat history (`<session-dir>/chat_history.jsonl`): flat records+/// `{type, ...}`. `system` carries the private system prompt and `reasoning`+/// carries encrypted hidden reasoning — neither may reach the ledger. Tool+/// calls ride on the `assistant` record's `tool_calls` array and pair with+/// separate `tool_result` records; `backend_tool_call` records server-side+/// tools such as web search. Unknown record types are ignored so newer Grok+/// versions stay forward-compatible.+fn parse_grok(+ 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)+ .unwrap_or_default();+ match record_type {+ "system" => {+ losses.push("Grok system prompt records were intentionally excluded".into());+ }+ "reasoning" => {+ losses.push("Grok hidden reasoning was intentionally excluded".into());+ }+ "user" => {+ parse_content_blocks(+ AgentKind::Grok,+ session,+ record_id,+ "user",+ value.get("content"),+ timestamp(value),+ events,+ losses,+ );+ }+ "assistant" => {+ let block_count = if let Some(text) = value.get("content").and_then(Value::as_str) {+ push_event(+ events,+ AgentKind::Grok,+ session,+ record_id,+ 0,+ WorkstreamEventKind::Message,+ Some("assistant"),+ text,+ timestamp(value),+ json!({}),+ );+ 1+ } else {+ 0+ };+ let tool_calls = value+ .get("tool_calls")+ .and_then(Value::as_array)+ .map_or(&[][..], Vec::as_slice);+ for (index, call) in tool_calls.iter().enumerate() {+ let name = first_string(call, &["name"]).unwrap_or("tool");+ // `arguments` is a JSON string; re-serialize it compact when+ // it parses, mirroring parse_codex's tool-call shape.+ let arguments = call+ .get("arguments")+ .and_then(Value::as_str)+ .map(|raw| match serde_json::from_str::<Value>(raw) {+ Ok(parsed) => compact_json(&parsed),+ Err(_) => raw.to_string(),+ })+ .unwrap_or_default();+ push_event(+ events,+ AgentKind::Grok,+ session,+ record_id,+ block_count + index,+ WorkstreamEventKind::ToolCall,+ Some("assistant"),+ &format!("{name}: {arguments}"),+ timestamp(value),+ json!({"tool": name}),+ );+ }+ }+ "tool_result" => {+ let body = value.get("content").map(value_text).unwrap_or_default();+ push_event(+ events,+ AgentKind::Grok,+ session,+ record_id,+ 0,+ WorkstreamEventKind::ToolResult,+ Some("tool"),+ &body,+ timestamp(value),+ json!({}),+ );+ }+ "backend_tool_call" => {+ let kind = value.get("kind").unwrap_or(&Value::Null);+ let tool = first_string(kind, &["tool_type"]).unwrap_or("backend_tool");+ let action = kind.get("action").map(compact_json).unwrap_or_default();+ push_event(+ events,+ AgentKind::Grok,+ session,+ record_id,+ 0,+ WorkstreamEventKind::ToolCall,+ Some("assistant"),+ &format!("{tool}: {action}"),+ timestamp(value),+ json!({"tool": tool}),+ );+ }+ _ => {}+ }+}+#[allow(clippy::too_many_arguments)]fn parse_content_blocks(agent: AgentKind,@@ -1028,6 +1164,8 @@ fn codex_synthetic_context(agent: AgentKind, role: &str, text: &str) -> bool {|| trimmed.starts_with("<INSTRUCTIONS>")}AgentKind::ClaudeCode => trimmed.starts_with("<system-reminder>"),+ // Grok injects an environment block into the first user message.+ AgentKind::Grok => trimmed.starts_with("<user_info>"),_ => false,}}@@ -1412,6 +1550,12 @@ fn locate_session_file(}fn transcript_file(harness: ManagedHarness, path: &Path) -> bool {+ if harness == ManagedHarness::Grok {+ // Only the conversation journal. `events.jsonl`, `updates.jsonl`, and+ // `rewind_points.jsonl` in the same session directory carry harness+ // internals and are excluded.+ return path.file_name().and_then(|name| name.to_str()) == Some("chat_history.jsonl");+ }if harness == ManagedHarness::Kimi {// Only the main agent's journal: `agents/main/wire.jsonl`. Subagent// wire journals and any other *.jsonl in the store are excluded.@@ -1438,6 +1582,9 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(Stringif harness == ManagedHarness::Kimi {return kimi_session_header(path);}+ if harness == ManagedHarness::Grok {+ return grok_session_header(path);+ }let mut reader = BufReader::new(File::open(path)?);let mut line = String::new();for _ in 0..64 {@@ -1464,7 +1611,10 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(Stringvalue.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::Grok => (None, None),};if let (Some(id), Some(cwd)) = (id, cwd) {return Ok(Some((id.to_string(), PathBuf::from(cwd))));@@ -1498,6 +1648,32 @@ fn kimi_session_header(path: &Path) -> Result<Option<(String, PathBuf)>> {Ok(Some((id.to_string(), PathBuf::from(cwd))))}+/// Grok sessions are self-describing in `<session-dir>/summary.json`+/// (`info.id` + `info.cwd`). The chat-history journal carries no session id or+/// cwd, and the bucket directory name is a URL-encoded cwd that is never+/// parsed — recorded metadata is the only accepted checkout identifier.+/// Missing/invalid metadata means the session is unusable for checkout+/// matching, not an error.+fn grok_session_header(path: &Path) -> Result<Option<(String, PathBuf)>> {+ let Some(session_dir) = path.parent() else {+ return Ok(None);+ };+ let Ok(raw) = fs::read_to_string(session_dir.join("summary.json")) else {+ return Ok(None);+ };+ let Ok(summary) = serde_json::from_str::<Value>(&raw) else {+ return Ok(None);+ };+ let info = summary.get("info").unwrap_or(&Value::Null);+ let (Some(id), Some(cwd)) = (+ info.get("id").and_then(Value::as_str),+ info.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 +1861,7 @@ fn session_root(harness: ManagedHarness, home: &Path, override_dir: Option<&PathManagedHarness::Crush => home.join(".crush"),ManagedHarness::Omp => home.join(".omp/agent/sessions"),ManagedHarness::Kimi => home.join(".kimi-code/sessions"),+ ManagedHarness::Grok => home.join(".grok/sessions"),}}@@ -1842,9 +2019,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 Grok's in+ // summary.json, not the journal; covered by their own+ // discovery tests.+ ManagedHarness::OpenCode+ | ManagedHarness::Crush+ | ManagedHarness::Kimi+ | ManagedHarness::Grok => {unreachable!()}},@@ -2535,4 +2716,173 @@ mod tests {assert!(events.is_empty());assert_eq!(losses, ["Kimi system messages were intentionally excluded"]);}++ /// Build a two-bucket grok store: `session_a` checked out at `cwd`,+ /// `session_b` at `other`. Returns `(root, chat_a)`.+ fn grok_store_fixture(cwd: &Path, other: &Path) -> (tempfile::TempDir, PathBuf) {+ let root = tempfile::tempdir().unwrap();+ for (bucket, id, work_dir) in [+ ("%2Fother%2Fencoded", "019f-session-aaa", cwd),+ ("%2Frepo%2Fencoded", "019f-session-bbb", other),+ ] {+ let session_dir = root.path().join(bucket).join(id);+ fs::create_dir_all(&session_dir).unwrap();+ fs::write(+ session_dir.join("summary.json"),+ json!({"info": {"id": id, "cwd": work_dir}}).to_string(),+ )+ .unwrap();+ }+ let chat_a = root+ .path()+ .join("%2Fother%2Fencoded/019f-session-aaa/chat_history.jsonl");+ (root, chat_a)+ }++ #[tokio::test]+ async fn grok_discovery_matches_checkout_via_summary_json_not_bucket_name() {+ 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();+ // Bucket names deliberately contradict the recorded cwd, so only+ // summary.json metadata can produce a correct match.+ let (root, chat_a) = grok_store_fixture(&cwd, &other);+ fs::write(&chat_a, "{\"type\":\"user\",\"content\":\"hi\"}\n").unwrap();+ let chat_b = root+ .path()+ .join("%2Frepo%2Fencoded/019f-session-bbb/chat_history.jsonl");+ std::thread::sleep(Duration::from_millis(20));+ fs::write(&chat_b, "{\"type\":\"user\",\"content\":\"hello\"}\n").unwrap();+ // Sibling harness internals must never count as transcripts.+ fs::write(chat_a.parent().unwrap().join("events.jsonl"), "{}\n").unwrap();++ let sessions = list_native_sessions(+ ManagedHarness::Grok,+ temp.path(),+ &cwd,+ Some(root.path()),+ 8,+ )+ .await+ .unwrap();+ assert_eq!(sessions.len(), 1);+ assert_eq!(sessions[0].native_session_id, "019f-session-aaa");++ let found = locate_session_file(+ ManagedHarness::Grok,+ temp.path(),+ &cwd,+ Some(root.path()),+ "019f-session-aaa",+ )+ .unwrap();+ assert_eq!(found.as_deref(), Some(chat_a.as_path()));+ assert!(!transcript_file(+ ManagedHarness::Grok,+ &chat_a.parent().unwrap().join("events.jsonl")+ ));+ }++ #[test]+ fn grok_adapter_excludes_private_records_and_keeps_visible_history() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("chat_history.jsonl");+ let records = [+ json!({"type":"system","content":"private system prompt"}),+ json!({"type":"user","content":[{"type":"text","text":"<user_info>\nOS: linux\n</user_info>"}]}),+ json!({"type":"user","content":[{"type":"text","text":"fix the bug"}]}),+ json!({"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"opaque","status":"done"}),+ json!({"type":"assistant","content":"reading the file","model_id":"grok-4.5",+ "tool_calls":[{"id":"call-1","name":"read_file","arguments":"{\"target_file\":\"a.rs\"}"}]}),+ json!({"type":"tool_result","tool_call_id":"call-1","content":"fn main() {}"}),+ json!({"type":"backend_tool_call","kind":{"tool_type":"web_search","action":{"type":"search","query":"rust"}}}),+ ];+ let body = records+ .iter()+ .map(|record| format!("{record}\n"))+ .collect::<String>();+ fs::write(&path, body).unwrap();++ let export = export_jsonl(ManagedHarness::Grok, &path, "019f-session", None).unwrap();+ let contents: Vec<_> = export+ .events+ .iter()+ .map(|event| (event.kind, event.content.as_str()))+ .collect();+ assert_eq!(+ contents,+ [+ (WorkstreamEventKind::Message, "fix the bug"),+ (WorkstreamEventKind::Message, "reading the file"),+ (+ WorkstreamEventKind::ToolCall,+ "read_file: {\"target_file\":\"a.rs\"}"+ ),+ (WorkstreamEventKind::ToolResult, "fn main() {}"),+ (+ WorkstreamEventKind::ToolCall,+ "web_search: {\"type\":\"search\",\"query\":\"rust\"}"+ ),+ ]+ );+ assert!(+ export+ .losses+ .iter()+ .any(|loss| loss.contains("system prompt records"))+ );+ assert!(+ export+ .losses+ .iter()+ .any(|loss| loss.contains("hidden reasoning"))+ );+ let cursor: FileCursor = serde_json::from_str(&export.source_cursor.unwrap()).unwrap();+ assert!(cursor.prefix_sha256.is_some());+ }++ #[test]+ fn grok_export_resets_cursor_after_an_in_place_journal_rewrite() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("chat_history.jsonl");+ fs::write(&path, "{\"type\":\"user\",\"content\":\"one\"}\n").unwrap();+ let first = export_jsonl(ManagedHarness::Grok, &path, "019f-session", None).unwrap();+ assert_eq!(first.events.len(), 1);++ // Appending keeps the validated prefix and resumes incrementally.+ let mut appended = fs::read(&path).unwrap();+ appended.extend(b"{\"type\":\"user\",\"content\":\"two\"}\n");+ fs::write(&path, appended).unwrap();+ let second = export_jsonl(+ ManagedHarness::Grok,+ &path,+ "019f-session",+ first.source_cursor.as_deref(),+ )+ .unwrap();+ assert_eq!(second.events.len(), 1);+ assert_eq!(second.events[0].content, "two");++ // A rewind rewrites the journal in place: the stored prefix no longer+ // matches, so the export replays from the start with stable event ids.+ fs::write(+ &path,+ "{\"type\":\"user\",\"content\":\"one\"}\n{\"type\":\"assistant\",\"content\":\"rewound\"}\n",+ )+ .unwrap();+ let third = export_jsonl(+ ManagedHarness::Grok,+ &path,+ "019f-session",+ second.source_cursor.as_deref(),+ )+ .unwrap();+ assert_eq!(third.events.len(), 2);+ assert_eq!(+ third.events[0].event_id, first.events[0].event_id,+ "identical lines must keep identical event ids across rewrites"+ );+ }}diff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex 04994691..a2d94e73 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -283,11 +283,11 @@ Top-line rules carved into the codebase:## 15. Managed workstreams use a portable ledger, not native format conversionManaged cross-harness continuity is explicitly opt-in through `ai-memory run`.-Direct Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, 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-create/resume syntax.+Direct Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, and Grok Build+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.One logical workstream owns one native session per harness plus an append-onlyportable event ledger. We rejected converting a Claude transcript into a fakediff --git a/docs/install.md b/docs/install.mdindex 7c9c48a2..738c34fe 100644--- a/docs/install.md+++ b/docs/install.md@@ -1177,7 +1177,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, or OMP explicitly; exact `--yolo` is 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, OMP, or Grok Build CLI explicitly; exact `--yolo` is wrapper-owned and other native arguments pass through || `workstream-search [query]` | managed child or thin HTTP client | Search the complete visible managed-workstream ledger; the managed child receives its workstream id automatically || `status` | `docker exec` | Counts, paths, derived-index diagnostics, and passive LLM/embedding provider health || `search "<query>"` | `docker exec` | Wiki search with FTS5 + graph/vector RRF |diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex e17b91a0..24991cde 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, OMP, and Grok+Build CLI. Direct agent launcheskeep their existing ai-memory behavior. There is no global mode toggle and no`switch` command: using `run` selects the current workstream and transparentlycreates 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:```textai-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|grok] [native arguments...]```The default is the most recently selected workstream for the current repository@@ -44,8 +44,8 @@ it resumesthe newest session automatically. For an established workstream, server statetakes precedence: ai-memory resumes the most recently linked harness that stillhas a usable local session. It never chooses a newer but obsolete session from-another harness merely because that file has a later timestamp. OMP remains-available explicitly but is not in the automatic pool.+another harness merely because that file has a later timestamp. OMP and Grok+remain available explicitly but are not in the automatic pool.Bare mode accepts wrapper options but not harness-native arguments or`--executable`, because their meaning depends on the selected harness. In a new@@ -130,6 +130,7 @@ is labelled completed evidence and must never be replayed as a pending call.| 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` || OMP | native default creation | `--resume=<id>` | `~/.omp/agent/sessions/**/*.jsonl` |+| Grok Build CLI | generated `--session-id` | `--resume <id>` | `$GROK_HOME/sessions/*/*/chat_history.jsonl` |An explicit native selector such as Claude's `--resume`, OpenCode's `--session`,or Codex's `resume` wins. ai-memory links the selected native session and resets@@ -138,7 +139,8 @@ Pi and OMP `--session-dir` values and Crush `--data-dir` values are passedthrough unchanged and used as the read-only import root. Native storeenvironment 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+`GROK_HOME`.The Pi-family adapteralso recognizes a complete `.jsonl.<nonce>.tmp` atomic-write file when a nativeprocess exits before renaming it; incomplete final JSONL records are never@@ -156,7 +158,7 @@ ai-memory does not add a duplicate when the translated native flag is alreadypresent.Managed support is intentionally narrower than the general integration matrix.-Gemini CLI, Devin CLI, Cursor, Grok Build CLI, and other agents may+Gemini CLI, Devin CLI, Cursor, and other agents mayhave MCP or lifecycle-hook support without native managed resume. Contributorsadding another managed harness must follow the [managed-harness contributionprotocol](managed-harness-contributions.md), including read-only extraction,@@ -203,6 +205,23 @@ 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.+Grok needs no ai-memory hook installation for managed delivery either. Grok+ignores `SessionStart` stdout and its `UserPromptSubmit` hook is passive, so+the launcher fetches the bounded context packet from the server and passes it+through Grok's native `--rules` flag, which appends the text to that session's+system prompt. Delivery is acknowledged only after the child spawns. Because+`--rules` is single-use in Grok's argument parser, a natively supplied+`--rules`/`--append-system-prompt` wins and the packet stays undelivered until+a later managed run can accept it. Grok can rewrite `chat_history.jsonl` in+place on rewind, so the import cursor stores a prefix hash and replays from+the beginning when it no longer matches, with content-hash event ids+deduplicating records already in the workstream. Sibling session files+(`events.jsonl`, `updates.jsonl`, `rewind_points.jsonl`) carry harness+internals and are never read as transcripts; discovery reads+`summary.json`'s `info.cwd` and never parses the URL-encoded bucket name. The+managed launcher accepts `grok` and `grok-build`. The native contract was+verified against Grok Build CLI v0.2.111.+Crush needs no ai-memory hook installation for managed mode. The launcher readsits one-time context from the server, copies the existing global Crush JSON intoa private temporary directory, appends an ephemeral context path, and points thediff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.shindex 5a68a8d3..1209020b 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"}+HARNESS_WORDS=${AI_MEMORY_ACCEPTANCE_HARNESSES:-"claude codex opencode pi crush omp kimi grok"}TMP=$(mktemp -d "${TMPDIR:-/tmp}/ai-memory-workstream-acceptance.XXXXXX")DATA="$TMP/data"REPO="$TMP/repo"@@ -139,6 +139,32 @@ case "${AI_MEMORY_ACCEPTANCE_FAKE_MODE:-argv}" inprintf '{"type":"context.append_message","time":%s,"message":{"role":"assistant","content":[{"type":"text","text":"%s reply"}],"toolCalls":[]}}\n' \"$(date +%s)000" "$sentinel" >>"$wire";;+ grok)+ printf '%s\n' "$@" >"$AI_MEMORY_ACCEPTANCE_ARGV_LOG"+ # Honor the wrapper-owned `--session-id <id>` (fresh) and `--resume <id>`+ # (returning) selectors the way the real CLI does.+ session_id=""+ previous_arg=""+ for arg in "$@"; do+ case "$previous_arg" in+ --session-id | --resume) session_id=$arg ;;+ esac+ previous_arg=$arg+ done+ [ -n "$session_id" ] || session_id="019f-fake-$(date +%s)-$$"+ # The bucket directory name is a URL-encoded cwd in the real layout, but+ # discovery must read summary.json's info.cwd instead of parsing it.+ session_dir="${GROK_HOME:?grok fake mode requires GROK_HOME}/sessions/%2Ffixture%2Fbucket/$session_id"+ mkdir -p "$session_dir"+ chat="$session_dir/chat_history.jsonl"+ if [ ! -f "$session_dir/summary.json" ]; then+ printf '{"info":{"id":"%s","cwd":"%s"}}\n' "$session_id" "$PWD" >"$session_dir/summary.json"+ printf '{"type":"system","content":"fake grok system prompt"}\n' >"$chat"+ fi+ sentinel=${AI_MEMORY_ACCEPTANCE_SENTINEL:-AMWS-FAKE-GROK}+ printf '{"type":"user","content":[{"type":"text","text":"%s"}]}\n' "$sentinel" >>"$chat"+ printf '{"type":"assistant","content":"%s reply"}\n' "$sentinel" >>"$chat"+ ;;esacEOFchmod +x "$FAKE"@@ -410,6 +436,111 @@ jq -e \exit 1}+# Grok fake-mode fixture: the fake grok honors the wrapper's `--session-id`+# (fresh) and `--resume <id>` (returning) selectors, writes the native store+# layout ($GROK_HOME/sessions/<bucket>/<id>/summary.json plus+# chat_history.jsonl), and appends the round sentinel. The returning launch+# must also receive the undelivered workstream packet through `--rules`.+GROK_FAKE_HOME="$CONFIG/grok-fake"+mkdir -p "$GROK_FAKE_HOME"+(+ cd "$REPO"+ GROK_HOME="$GROK_FAKE_HOME" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=grok \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/grok-first-argv.log" \+ AI_MEMORY_ACCEPTANCE_SENTINEL="AMWS-FAKE-GROK-ONE" \+ "$BIN" --data-dir "$DATA" run --new edge-grok --executable "$FAKE" \+ grok >"$LOGS/edge-grok-first.log" 2>&1+)+grep -qx -- '--session-id' "$TMP/grok-first-argv.log" || {+ printf 'fresh grok launch did not receive a wrapper session id\n' >&2+ cat "$TMP/grok-first-argv.log" >&2+ exit 1+}+if grep -qx -- '--rules' "$TMP/grok-first-argv.log"; then+ printf 'fresh grok launch on an empty workstream unexpectedly received --rules\n' >&2+ exit 1+fi+grok_session_id=$(basename "$(find "$GROK_FAKE_HOME/sessions" -mindepth 2 -maxdepth 2 -type d -print -quit)")+[ -n "$grok_session_id" ] || {+ printf 'fake grok did not create a native session store\n' >&2+ exit 1+}+grok_ws_hex=$(sqlite3 "$DATA/db/memory.sqlite" \+ "SELECT lower(hex(id)) FROM workstreams WHERE name = 'edge-grok' ORDER BY selected_at DESC LIMIT 1;")+[ "${#grok_ws_hex}" -eq 32 ] || {+ printf 'could not resolve the edge-grok workstream id\n' >&2+ exit 1+}+grok_ws_id="${grok_ws_hex:0:8}-${grok_ws_hex:8:4}-${grok_ws_hex:12:4}-${grok_ws_hex:16:4}-${grok_ws_hex:20:12}"+grok_first_hits=$("$BIN" --data-dir "$DATA" workstream-search \+ --workstream-id "$grok_ws_id" --limit 100 --json "AMWS-FAKE-GROK-ONE")+jq -e --arg id "$grok_session_id" \+ '[.[] | select(.agent == "grok" and .role == "assistant" and (.content | contains("AMWS-FAKE-GROK-ONE")) and .native_session_id == $id)] | length == 1' \+ <<<"$grok_first_hits" >/dev/null || {+ printf 'grok chat_history.jsonl sentinel was not imported\n' >&2+ tail -80 "$LOGS/edge-grok-first.log" >&2+ exit 1+}+# Returning to the same grok session must resume it (`--resume <id>`) and,+# because that session already produced every workstream event, receive no+# context packet.+(+ cd "$REPO"+ GROK_HOME="$GROK_FAKE_HOME" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=grok \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/grok-second-argv.log" \+ AI_MEMORY_ACCEPTANCE_SENTINEL="AMWS-FAKE-GROK-TWO" \+ "$BIN" --data-dir "$DATA" run --workstream edge-grok --executable "$FAKE" \+ grok-build >"$LOGS/edge-grok-second.log" 2>&1+)+grep -A1 -x -- '--resume' "$TMP/grok-second-argv.log" | grep -qx "$grok_session_id" || {+ printf 'returning grok launch did not resume the linked session\n' >&2+ cat "$TMP/grok-second-argv.log" >&2+ exit 1+}+if grep -qx -- '--rules' "$TMP/grok-second-argv.log"; then+ printf 'same-session grok resume unexpectedly received a context packet\n' >&2+ exit 1+fi+grok_second_hits=$("$BIN" --data-dir "$DATA" workstream-search \+ --workstream-id "$grok_ws_id" --limit 100 --json "AMWS-FAKE-GROK")+jq -e \+ '([.[] | select(.role == "assistant" and (.content | contains("AMWS-FAKE-GROK-ONE")))] | length == 1)+ and ([.[] | select(.role == "assistant" and (.content | contains("AMWS-FAKE-GROK-TWO")))] | length == 1)' \+ <<<"$grok_second_hits" >/dev/null || {+ printf 'grok incremental import duplicated or missed a round sentinel\n' >&2+ tail -80 "$LOGS/edge-grok-second.log" >&2+ exit 1+}++# A fresh grok session joining the established edge-kimi workstream must+# receive that workstream's history through `--rules`, with historical tool+# activity labelled as completed evidence.+(+ cd "$REPO"+ GROK_HOME="$GROK_FAKE_HOME" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=grok \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/grok-cross-argv.log" \+ AI_MEMORY_ACCEPTANCE_SENTINEL="AMWS-FAKE-GROK-CROSS" \+ "$BIN" --data-dir "$DATA" run --workstream edge-kimi --executable "$FAKE" \+ grok >"$LOGS/edge-grok-cross.log" 2>&1+)+grep -qx -- '--session-id' "$TMP/grok-cross-argv.log" || {+ printf 'grok joining an established workstream did not start a fresh session\n' >&2+ cat "$TMP/grok-cross-argv.log" >&2+ exit 1+}+grep -qx -- '--rules' "$TMP/grok-cross-argv.log" || {+ printf 'grok joining an established workstream did not receive --rules context\n' >&2+ cat "$TMP/grok-cross-argv.log" >&2+ exit 1+}+grep -q 'AMWS-FAKE-KIMI' "$TMP/grok-cross-argv.log" || {+ printf 'the grok --rules packet did not carry the prior harness history\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 +615,7 @@ harnesses=()for requested_harness in "${requested_harnesses[@]}"; docase "$requested_harness" inkimi-code | kimi-cli) harness=kimi ;;+ grok-build) harness=grok ;;*) harness=$requested_harness ;;esacif command -v "$harness" >/dev/null 2>&1; then@@ -509,10 +641,11 @@ 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"+GROK_ACCEPTANCE_HOME="$CONFIG/grok-home"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"+ "$CRUSH_DATA_DIR" "$KIMI_ACCEPTANCE_HOME" "$GROK_ACCEPTANCE_HOME"# Redirect native transcript stores into the fixture while reusing only the# minimum authentication material required for real model calls.@@ -567,6 +700,15 @@ for relative in credentials/kimi-code.json oauth/kimi-code device_id; dofidone+# 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.+for relative in auth.json config.toml; do+ if [ -f "$HOME/.grok/$relative" ]; then+ cp "$HOME/.grok/$relative" "$GROK_ACCEPTANCE_HOME/$relative"+ fi+done+install_hook() {local agent=$1local target=$2@@ -669,6 +811,10 @@ run_harness() {native_args=(-p "$prompt")[ -z "${AI_MEMORY_ACCEPTANCE_KIMI_MODEL:-}" ] || native_args=(-p -m "$AI_MEMORY_ACCEPTANCE_KIMI_MODEL" "$prompt");;+ grok)+ native_args=(-p "$prompt")+ [ -z "${AI_MEMORY_ACCEPTANCE_GROK_MODEL:-}" ] || native_args=(-p -m "$AI_MEMORY_ACCEPTANCE_GROK_MODEL" "$prompt")+ ;;*)printf 'unsupported acceptance harness: %s\n' "$harness" >&2return 1@@ -698,6 +844,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" = grok ]; then+ (cd "$REPO" && GROK_HOME="$GROK_ACCEPTANCE_HOME" \+ "$BIN" --data-dir "$DATA" run "${wrapper_args[@]}" "$harness" "${native_args[@]}") \+ >"$log" 2>&1else(cd "$REPO" && "$BIN" --data-dir "$DATA" run \"${wrapper_args[@]}" "$harness" "${native_args[@]}") >"$log" 2>&1