Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(opencode): detect plugin dialect by executable version (#1097)
AkitaOnRailsb8f1e4f80a9e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 20b2a554..d694d682 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0provider. (#1026)### Fixed+- Fixed generic OpenCode commands selecting integration contracts from command+ spelling instead of the executable's major version. `run opencode` now probes+ the exact executable once and carries the resolved V1/V2 dialect through+ session discovery, launch, auto-wire, and transcript import; hook and MCP+ installers use the same strict resolver, while container-oriented+ `setup-agent` requires an explicit V1/V2 artifact dialect. Probe and launch+ share one captured child environment with `--env` overlays, including Windows+ key casing. Automatic launch skips an unresolvable OpenCode candidate without+ hiding other harnesses. Hook/MCP transitions reuse ownership-verified endpoint+ and token settings across both schemas and reject conflicting generated+ entries. Migrations remove only entries proven generated by ai-memory, and plugin+ cleanup never overwrites a concurrent user replacement while restoring an+ unowned quarantined file. (#1097)- Fixed `memory_handoff_list` MCP tool calls being counted under writes in`client_activity`: the read-only inspection tool is now classified as a readin `tool_call_is_write`. (#1088)diff --git a/README.md b/README.mdindex 045616fb..1df813c9 100644--- a/README.md+++ b/README.md@@ -113,8 +113,8 @@ caveats is in [`docs/support-matrix.md`](docs/support-matrix.md).| Codex | Supported || Command Code | Supported || Devin CLI | Supported |-| OpenCode | Supported |-| OpenCode 2 (`opencode2` beta) | Supported |+| OpenCode (V1/V2 auto-detected) | Supported |+| OpenCode V2 compatibility aliases (`opencode2`, `opencode-v2`, `open-code2`) | Supported || Cursor | Supported || Gemini CLI | Supported || Oh My Pi / OMP | Supported |@@ -344,7 +344,11 @@ writable prefix (see [`docs/windows.md`](docs/windows.md) Scenario C).Wiring another agent is the same two commands with a different name —`--client codex`, `--agent codex`, and so on for every row of the support-matrix. The full per-agent guide, including Windows and remote servers, is+matrix. OpenCode is version-detected by host-side commands; when generating its+artifacts inside a container, use `setup-agent --agent opencode+--opencode-dialect v1|v2 --to /tmp/unused` because the container cannot inspect+the host executable. The `opencode2` aliases remain force-V2 compatibility+spellings. The full per-agent guide, including Windows and remote servers, is[`docs/install.md`](docs/install.md).Two agents in the same project at once, or teammates on one server? Thatdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 5ccc5fd3..043f369b 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -373,10 +373,10 @@ pub enum RunHarnessChoice {Claude,/// OpenAI Codex CLI.Codex,- /// OpenCode.+ /// OpenCode; probes the selected executable and uses its V1 or V2 contracts.#[value(name = "opencode", alias = "open-code")]OpenCode,- /// OpenCode 2.0 beta (`opencode2` binary, side-by-side with v1).+ /// OpenCode V2 compatibility alias; forces the V2 contracts.#[value(name = "opencode2", alias = "opencode-v2", alias = "open-code2")]OpenCode2,/// Pi coding agent.@@ -1656,12 +1656,37 @@ pub struct BootstrapArgs {pub resume: bool,}+/// OpenCode artifact dialect for container-only setup where the host executable+/// cannot be probed.+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]+pub enum OpenCodeDialectChoice {+ /// OpenCode V1 function plugin and direct `mcp` entry.+ V1,+ /// OpenCode V2 `{ id, setup }` plugin and nested `mcp.servers` entry.+ V2,+}++impl OpenCodeDialectChoice {+ #[must_use]+ pub const fn dialect(self) -> ai_memory_workstream::OpenCodeDialect {+ match self {+ Self::V1 => ai_memory_workstream::OpenCodeDialect::V1,+ Self::V2 => ai_memory_workstream::OpenCodeDialect::V2,+ }+ }+}+/// Arguments for `setup-agent`.#[derive(Debug, Args)]pub struct SetupAgentArgs {/// Which agent's hook bundle to extract + render.#[arg(long, value_enum, default_value_t = AgentChoice::ClaudeCode)]pub agent: AgentChoice,+ /// OpenCode artifact dialect when `--agent opencode` is used. Required+ /// because setup-agent commonly runs in a container that cannot inspect the+ /// host's executable. The `opencode2` aliases force V2 and reject this flag.+ #[arg(long, value_enum)]+ pub opencode_dialect: Option<OpenCodeDialectChoice>,/// Filesystem directory the hook scripts get copied into. In a/// docker context this is the in-container path; mount a host/// directory there. Example:@@ -1972,22 +1997,14 @@ pub enum AgentChoice {Cursor,/// Google Gemini CLI — JSON-config hooks in `~/.gemini/settings.json`.GeminiCli,- /// OpenCode (open-source coding agent) — TypeScript plugin hooks- /// under `~/.config/opencode/plugins/`. `--apply` writes the plugin- /// file directly; restart OpenCode for it to load.- ///- /// The `opencode` (no hyphen) alias matches both the staged hook- /// dir on disk (`~/.local/share/ai-memory/hooks/opencode/`) and- /// what users commonly type. Without it, `ai-memory upgrade`'s- /// hook-refresh loop iterates the staged dir names and passes- /// them straight to `--agent`, which used to fail on this one.+ /// OpenCode — probes `opencode --version`, then writes the compatible V1+ /// function plugin or V2 `{ id, setup }` plugin under+ /// `~/.config/opencode/plugins/`. Restart OpenCode for it to load.#[value(alias = "opencode")]OpenCode,- /// OpenCode 2.0 beta (`opencode2`, side-by-side with v1) — TypeScript- /// plugin hooks under `~/.config/opencode/plugins/` using the V2- /// `{ id, setup }` plugin shape. `--apply` writes `ai-memory-opencode2.ts`- /// directly; restart OpenCode 2 for it to load. Shares v1's config- /// dir, session store, and agent kind.+ /// OpenCode V2 compatibility alias; forces the V2 plugin contract and+ /// `ai-memory-opencode2.ts` path without probing. Shares V1's config dir,+ /// session store, and agent kind.#[value(name = "opencode2", alias = "opencode-v2", alias = "open-code2")]OpenCode2,/// Real Pi coding agent. The generated TypeScript extension provides@@ -2251,15 +2268,12 @@ pub enum McpClient {ClaudeCode,/// OpenAI Codex CLI — `$CODEX_HOME/config.toml` (default `~/.codex/config.toml`).Codex,- /// OpenCode — `opencode.json`. Accepts `opencode` (no hyphen) as- /// an alias for symmetry with `AgentChoice` and the on-disk- /// hook-staging dir name.+ /// OpenCode — probes `opencode --version`, then writes the compatible V1+ /// direct `mcp` entry or V2 nested `mcp.servers` entry.#[value(alias = "opencode")]OpenCode,- /// OpenCode 2.0 beta (`opencode2`) — `opencode.jsonc`, nested- /// `mcp.servers` map with `type: "remote"` + `url` + `headers`.- /// V2 drops v1's `enabled` field and disables OAuth discovery for- /// header-credentialed servers via `oauth: false`.+ /// OpenCode V2 compatibility alias; forces nested `mcp.servers` with+ /// `type: "remote"`, no V1 `enabled`, and `oauth: false`.#[value(name = "opencode2", alias = "opencode-v2", alias = "open-code2")]OpenCode2,/// Cursor IDE — `~/.cursor/mcp.json` or `.cursor/mcp.json`.@@ -2703,8 +2717,8 @@ pub struct InstallHooksArgs {pub hooks_dir: Option<PathBuf>,/// Server URL the hooks will POST to. Defaults to the configured/// `server_url` / AI_MEMORY_SERVER_URL when set, else loopback. If neither- /// is configured, apply-mode also reuses an existing ai-memory MCP entry- /// for the same agent when one is present.+ /// is configured, apply-mode also reuses an ownership-verified ai-memory MCP+ /// entry from either known OpenCode major-version location when present.// Keep this optional so effective_hook_server_url can distinguish an// omitted flag from an explicit URL that equals the compiled default.#[arg(long)]@@ -3594,6 +3608,30 @@ mod tests {}}+ #[test]+ fn setup_agent_opencode_dialect_parses_for_container_generation() {+ for (value, expected) in [+ ("v1", OpenCodeDialectChoice::V1),+ ("v2", OpenCodeDialectChoice::V2),+ ] {+ let cli = Cli::try_parse_from([+ "ai-memory",+ "setup-agent",+ "--agent",+ "opencode",+ "--opencode-dialect",+ value,+ "--to",+ "/tmp/hooks",+ ])+ .unwrap();+ let Command::SetupAgent(args) = cli.command else {+ panic!("expected setup-agent command");+ };+ assert_eq!(args.opencode_dialect, Some(expected));+ }+ }+#[test]fn opencode2_aliases_parse_to_the_beta_variants() {for alias in ["opencode2", "opencode-v2", "open-code2"] {diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex e280964c..1501c6aa 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -372,9 +372,39 @@ fn kiro_cli_home_join(////// # Errors/// Returns an error if the hook script directory cannot be located.-pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {- let inferred = if args.server_url.is_none() {- infer_installed_mcp_config(args.agent)?+pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {+ run_with_opencode_dialect(config, args, None)+}++pub(crate) fn run_with_opencode_dialect(+ config: &Config,+ args: InstallHooksArgs,+ dialect: Option<ai_memory_workstream::OpenCodeDialect>,+) -> Result<()> {+ run_with_opencode_dialect_and_mcp_path(config, args, dialect, None)+}++pub(crate) fn run_with_opencode_dialect_and_mcp_path(+ config: &Config,+ mut args: InstallHooksArgs,+ dialect: Option<ai_memory_workstream::OpenCodeDialect>,+ mcp_config_path: Option<&Path>,+) -> Result<()> {+ let child_env = super::run::EffectiveChildEnv::from_runtime(&config.runtime_env);+ args.agent = match (args.agent, dialect) {+ (AgentChoice::OpenCode, Some(ai_memory_workstream::OpenCodeDialect::V1)) => {+ AgentChoice::OpenCode+ }+ (AgentChoice::OpenCode, Some(ai_memory_workstream::OpenCodeDialect::V2)) => {+ AgentChoice::OpenCode2+ }+ (agent, None) => super::opencode_dialect::resolve_agent(agent, &child_env)?,+ (agent, Some(_)) => agent,+ };+ let needs_inferred_url = args.server_url.is_none() && !config.server_url_configured();+ let needs_inferred_token = args.auth_token.is_none() && config.auth.bearer_token.is_none();+ let inferred = if needs_inferred_url || needs_inferred_token {+ infer_installed_mcp_config(args.agent, mcp_config_path)?} else {None};@@ -783,7 +813,7 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {}}-#[derive(Debug, Clone, Default)]+#[derive(Debug, Clone, Default, PartialEq, Eq)]struct InferredMcpConfig {hook_server_url: Option<String>,auth_token: Option<String>,@@ -1193,7 +1223,10 @@ fn infer_first_toml_mcp_config(})}-fn infer_installed_mcp_config(agent: AgentChoice) -> Result<Option<InferredMcpConfig>> {+fn infer_installed_mcp_config(+ agent: AgentChoice,+ config_path: Option<&Path>,+) -> Result<Option<InferredMcpConfig>> {if agent == AgentChoice::Grok {let cwd = std::env::current_dir().context("could not resolve current dir for Grok project configuration")?;@@ -1208,7 +1241,10 @@ fn infer_installed_mcp_config(agent: AgentChoice) -> Result<Option<InferredMcpColet Some(client) = mcp_client_for_agent(agent) else {return Ok(None);};- let path = install_mcp::mcp_config_path(client)?;+ let path = match config_path {+ Some(path) => path.to_path_buf(),+ None => install_mcp::mcp_config_path(client)?,+ };if matches!(client, McpClient::Codex) {// An entry written before `install-mcp` honored CODEX_HOME still sits// in ~/.codex/config.toml; keep inferring from it until it is rewritten.@@ -1235,16 +1271,7 @@ fn infer_installed_mcp_config(agent: AgentChoice) -> Result<Option<InferredMcpCo"url",)),McpClient::Grok => infer_grok_mcp_config(&content),- McpClient::OpenCode => Ok(infer_json_mcp_config(- &content,- &["mcp", "ai-memory"],- "url",- )),- McpClient::OpenCode2 => Ok(infer_json_mcp_config(- &content,- &["mcp", "servers", "ai-memory"],- "url",- )),+ McpClient::OpenCode | McpClient::OpenCode2 => infer_opencode_mcp_config(&content, client),McpClient::Cursor => Ok(infer_json_mcp_config(&content,&["mcpServers", "ai-memory"],@@ -1421,16 +1448,36 @@ pub(crate) fn hook_config_target_with(}}+fn infer_opencode_mcp_config(+ content: &str,+ selected: McpClient,+) -> Result<Option<InferredMcpConfig>> {+ Ok(+ install_mcp::infer_owned_opencode_mcp_config(content, selected)?.map(|inferred| {+ InferredMcpConfig {+ hook_server_url: hook_server_url_from_mcp_url(&inferred.mcp_url),+ auth_token: inferred.auth_token,+ }+ }),+ )+}++fn json_value_at_path<'a>(+ root: &'a serde_json::Value,+ entry_path: &[&str],+) -> Option<&'a serde_json::Value> {+ entry_path+ .iter()+ .try_fold(root, |entry, key| entry.get(*key))+}+fn infer_json_mcp_config(content: &str,entry_path: &[&str],url_key: &str,) -> Option<InferredMcpConfig> {let root: serde_json::Value = serde_json::from_str(content).ok()?;- let mut entry = &root;- for key in entry_path {- entry = entry.get(*key)?;- }+ let entry = json_value_at_path(&root, entry_path)?;let hook_server_url = entry.get(url_key).and_then(|v| v.as_str())@@ -3066,6 +3113,7 @@ fn apply_to_opencode_plugin(let body = build_opencode_plugin(server_url, auth_token, strategy, capture_mode);let outcome = apply_atomic(&path, move |_existing| Ok(body.clone()))?;+ remove_incompatible_opencode_plugin(&path, AgentChoice::OpenCode)?;println!("✓ {} {} ({})",outcome.verb(),@@ -3085,6 +3133,142 @@ fn apply_to_opencode_plugin(Ok(())}+fn opencode_plugin_content_is_owned(content: &str, agent: AgentChoice) -> bool {+ match agent {+ AgentChoice::OpenCode => {+ content.starts_with(+ "// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.",+ ) && content.contains("const AGENT = \"open-code\";")+ }+ AgentChoice::OpenCode2 => {+ content.starts_with(+ "// Auto-generated by `ai-memory install-hooks --agent opencode2 --apply`.",+ ) && content.contains("const AGENT = \"opencode2\";")+ }+ _ => false,+ }+}++fn remove_incompatible_opencode_plugin(path: &Path, installed: AgentChoice) -> Result<()> {+ remove_incompatible_opencode_plugin_with(path, installed, |_| Ok(()))+}++fn remove_incompatible_opencode_plugin_with(+ path: &Path,+ installed: AgentChoice,+ after_quarantine: impl FnOnce(&Path) -> Result<()>,+) -> Result<()> {+ let (installed_name, sibling_name) = match installed {+ AgentChoice::OpenCode => ("ai-memory.ts", "ai-memory-opencode2.ts"),+ AgentChoice::OpenCode2 => ("ai-memory-opencode2.ts", "ai-memory.ts"),+ _ => return Ok(()),+ };+ if path.file_name().and_then(|name| name.to_str()) != Some(installed_name) {+ return Ok(());+ }+ let Some(parent) = path.parent() else {+ return Ok(());+ };+ let sibling = parent.join(sibling_name);+ let incompatible = match installed {+ AgentChoice::OpenCode => AgentChoice::OpenCode2,+ AgentChoice::OpenCode2 => AgentChoice::OpenCode,+ _ => return Ok(()),+ };+ if sibling == path || !sibling.exists() {+ return Ok(());+ }+ let quarantine = parent.join(format!(+ ".ai-memory-opencode-quarantine-{}",+ uuid::Uuid::new_v4().simple()+ ));+ fs::rename(&sibling, &quarantine).with_context(|| {+ format!(+ "quarantining incompatible plugin {} before ownership verification",+ sibling.display()+ )+ })?;+ if let Err(error) = after_quarantine(&sibling) {+ restore_quarantined_opencode_plugin(&quarantine, &sibling)?;+ return Err(error);+ }+ let content = fs::read_to_string(&quarantine);+ if content+ .as_deref()+ .is_ok_and(|content| opencode_plugin_content_is_owned(content, incompatible))+ {+ fs::remove_file(&quarantine).with_context(|| {+ format!(+ "removing quarantined generated plugin {}",+ quarantine.display()+ )+ })?;+ println!(+ "✓ removed incompatible generated plugin {}",+ sibling.display()+ );+ return Ok(());+ }+ restore_quarantined_opencode_plugin(&quarantine, &sibling)?;+ Ok(())+}++fn restore_quarantined_opencode_plugin(quarantine: &Path, sibling: &Path) -> Result<()> {+ restore_quarantined_opencode_plugin_with(quarantine, sibling, || Ok(()))+}++fn restore_quarantined_opencode_plugin_with(+ quarantine: &Path,+ sibling: &Path,+ before_restore: impl FnOnce() -> Result<()>,+) -> Result<()> {+ match fs::symlink_metadata(sibling) {+ Ok(_) => {+ warn_opencode_plugin_restore_conflict(quarantine, sibling);+ return Ok(());+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => {+ return Err(error).with_context(|| {+ format!(+ "checking {} before restoring user plugin; original preserved at {}",+ sibling.display(),+ quarantine.display()+ )+ });+ }+ }+ before_restore()?;+ match fs::hard_link(quarantine, sibling) {+ Ok(()) => fs::remove_file(quarantine).with_context(|| {+ format!(+ "restored user plugin {} but could not remove its quarantine {}; both copies were preserved",+ sibling.display(),+ quarantine.display()+ )+ }),+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {+ warn_opencode_plugin_restore_conflict(quarantine, sibling);+ Ok(())+ }+ Err(error) => Err(error).with_context(|| {+ format!(+ "restoring user plugin {} without replacing concurrent content; original preserved at {}",+ sibling.display(),+ quarantine.display()+ )+ }),+ }+}++fn warn_opencode_plugin_restore_conflict(quarantine: &Path, sibling: &Path) {+ eprintln!(+ "[ai-memory] warning: {} changed during cleanup; preserved both it and the quarantined prior file {}",+ sibling.display(),+ quarantine.display()+ );+}+fn render_opencode_plugin(server_url: &str,auth_token: Option<&str>,@@ -3118,13 +3302,11 @@ pub(crate) fn opencode2_plugin_path() -> anyhow::Result<std::path::PathBuf> {/// Generate an OpenCode 2.0 beta plugin at/// `~/.config/opencode/plugins/ai-memory-opencode2.ts`.///-/// The beta's plugin API (`Plugin.define({ id, setup })` with-/// `ctx.session.hook` / `ctx.tool.hook` / `ctx.event.subscribe`) is-/// incompatible with v1's function plugin, so the beta gets its own file.-/// Both files share the one auto-loaded dir while the beta is side-by-side;-/// a host may warn about its sibling's file (API mismatch) — that warning-/// is benign, and `uninstall` removes each file only on its own ownership-/// markers.+/// The V2 plugin API (`{ id, setup }` with `ctx.session.hook` /+/// `ctx.tool.hook` / `ctx.event.subscribe`) is incompatible with V1's function+/// plugin, so V2 gets its own file. After a successful canonical write, an+/// incompatible sibling is removed only when its exact ai-memory ownership+/// markers match.fn apply_to_opencode2_plugin(server_url: &str,auth_token: Option<&str>,@@ -3145,6 +3327,7 @@ fn apply_to_opencode2_plugin()?;let outcome = apply_atomic(&path, move |_existing| Ok(body.clone()))?;+ remove_incompatible_opencode_plugin(&path, AgentChoice::OpenCode2)?;println!("✓ {} {} ({})",outcome.verb(),@@ -7762,19 +7945,20 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/a#[test]fn opencode_mcp_inference_supplies_hook_origin_and_token() {- let inferred = infer_json_mcp_config(+ let inferred = infer_opencode_mcp_config(r#"{"mcp": {"ai-memory": {"type": "remote","url": "http://homelab:49374/mcp",+ "enabled": true,"headers": { "Authorization": "Bearer secret-token" }}}}"#,- &["mcp", "ai-memory"],- "url",+ McpClient::OpenCode,)+ .unwrap().unwrap();assert_eq!(@@ -7784,6 +7968,122 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/aassert_eq!(inferred.auth_token.as_deref(), Some("secret-token"));}+ #[test]+ fn opencode_mcp_inference_follows_owned_entries_across_major_transitions() {+ for (selected, content) in [+ (+ McpClient::OpenCode2,+ r#"{"mcp":{"ai-memory":{"type":"remote","url":"http://v1-host:49374/mcp","enabled":true,"headers":{"Authorization":"Bearer v1-token"}}}}"#,+ ),+ (+ McpClient::OpenCode,+ r#"{"mcp":{"servers":{"ai-memory":{"type":"remote","url":"http://v2-host:49374/mcp","oauth":false,"headers":{"Authorization":"Bearer v2-token"}}}}}"#,+ ),+ ] {+ let inferred = infer_opencode_mcp_config(content, selected)+ .unwrap()+ .unwrap();+ let expected = if selected == McpClient::OpenCode2 {+ ("http://v1-host:49374", "v1-token")+ } else {+ ("http://v2-host:49374", "v2-token")+ };+ assert_eq!(inferred.hook_server_url.as_deref(), Some(expected.0));+ assert_eq!(inferred.auth_token.as_deref(), Some(expected.1));+ }+ }++ #[test]+ fn opencode_hook_install_reuses_owned_mcp_settings_across_major_transitions() {+ for (agent, dialect, mcp_content, plugin_name, expected_server, expected_token) in [+ (+ AgentChoice::OpenCode2,+ ai_memory_workstream::OpenCodeDialect::V2,+ r#"{"mcp":{"ai-memory":{"type":"remote","url":"http://v1-host:49374/mcp","enabled":true,"headers":{"Authorization":"Bearer v1-token"}}}}"#,+ "ai-memory-opencode2.ts",+ "http://v1-host:49374",+ "v1-token",+ ),+ (+ AgentChoice::OpenCode,+ ai_memory_workstream::OpenCodeDialect::V1,+ r#"{"mcp":{"servers":{"ai-memory":{"type":"remote","url":"http://v2-host:49374/mcp","oauth":false,"headers":{"Authorization":"Bearer v2-token"}}}}}"#,+ "ai-memory.ts",+ "http://v2-host:49374",+ "v2-token",+ ),+ ] {+ let temp = tempfile::tempdir().unwrap();+ let mcp = temp.path().join("opencode.json");+ let plugin = temp.path().join(plugin_name);+ fs::write(&mcp, mcp_content).unwrap();+ let config = Config {+ data_dir: temp.path().join("data"),+ ..Config::default()+ };+ let mut args = default_hook_args();+ args.agent = agent;+ args.apply = true;+ args.config_file = Some(plugin.clone());+ args.server_url = None;+ args.auth_token = None;++ run_with_opencode_dialect_and_mcp_path(&config, args, Some(dialect), Some(&mcp))+ .unwrap();++ assert!(+ fs::read_to_string(plugin)+ .unwrap()+ .contains(expected_server)+ );+ assert_eq!(+ crate::config::read_hook_auth_token(&config.data_dir).as_deref(),+ Some(expected_token)+ );+ }+ }++ #[test]+ fn opencode_mcp_inference_accepts_matching_owned_entries() {+ let inferred = infer_opencode_mcp_config(+ r#"{"mcp":{"ai-memory":{"type":"remote","url":"http://same-host:49374/mcp","enabled":true,"headers":{"Authorization":"Bearer same-token"}},"servers":{"ai-memory":{"type":"remote","url":"http://same-host:49374/mcp","oauth":false,"headers":{"Authorization":"Bearer same-token"}}}}}"#,+ McpClient::OpenCode2,+ )+ .unwrap()+ .unwrap();+ assert_eq!(+ inferred,+ InferredMcpConfig {+ hook_server_url: Some("http://same-host:49374".to_string()),+ auth_token: Some("same-token".to_string()),+ }+ );+ }++ #[test]+ fn opencode_mcp_inference_rejects_conflicting_owned_entries() {+ let error = infer_opencode_mcp_config(+ r#"{"mcp":{"ai-memory":{"type":"remote","url":"http://v1-host:49374/mcp","enabled":true},"servers":{"ai-memory":{"type":"remote","url":"http://v2-host:49374/mcp","oauth":false}}}}"#,+ McpClient::OpenCode2,+ )+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("conflicting generated OpenCode MCP entries")+ );+ }++ #[test]+ fn opencode_mcp_inference_ignores_user_owned_entries() {+ let inferred = infer_opencode_mcp_config(+ r#"{"mcp":{"ai-memory":{"type":"remote","url":"http://user-host:49374/mcp","enabled":true,"headers":{"Authorization":"Bearer user-token","X-User":"route"}}}}"#,+ McpClient::OpenCode,+ )+ .unwrap();+ assert_eq!(inferred, None);+ }+/// Inferring the hook URL from Kimi Code's flavored mcp.json entry/// must yield the bare origin — hooks POST to `<origin>/hook`.#[test]@@ -8854,6 +9154,169 @@ model = "gpt-5");}+ #[test]+ fn opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling() {+ let temp = tempfile::tempdir().unwrap();+ let v1 = temp.path().join("ai-memory.ts");+ let v2 = temp.path().join("ai-memory-opencode2.ts");+ fs::write(+ &v1,+ "// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.\nconst AGENT = \"open-code\";\n",+ )+ .unwrap();+ fs::write(+ &v2,+ "// Auto-generated by `ai-memory install-hooks --agent opencode2 --apply`.\nconst AGENT = \"opencode2\";\n",+ )+ .unwrap();++ remove_incompatible_opencode_plugin(&v2, AgentChoice::OpenCode2).unwrap();+ assert!(!v1.exists());+ assert!(v2.exists());++ fs::write(&v1, "export default function userPlugin() {}\n").unwrap();+ remove_incompatible_opencode_plugin(&v2, AgentChoice::OpenCode2).unwrap();+ assert_eq!(+ fs::read_to_string(&v1).unwrap(),+ "export default function userPlugin() {}\n"+ );++ fs::write(+ &v2,+ "// Auto-generated by `ai-memory install-hooks --agent opencode2 --apply`.\nconst AGENT = \"opencode2\";\n",+ )+ .unwrap();+ remove_incompatible_opencode_plugin(&v1, AgentChoice::OpenCode).unwrap();+ assert!(!v2.exists());+ }++ #[test]+ fn opencode_plugin_cleanup_preserves_a_concurrent_user_replacement() {+ let temp = tempfile::tempdir().unwrap();+ let v1 = temp.path().join("ai-memory.ts");+ let v2 = temp.path().join("ai-memory-opencode2.ts");+ fs::write(+ &v1,+ "// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.\nconst AGENT = \"open-code\";\n",+ )+ .unwrap();++ remove_incompatible_opencode_plugin_with(&v2, AgentChoice::OpenCode2, |sibling| {+ fs::write(sibling, "export default function userReplacement() {}\n")?;+ Ok(())+ })+ .unwrap();++ assert_eq!(+ fs::read_to_string(&v1).unwrap(),+ "export default function userReplacement() {}\n"+ );+ assert_eq!(+ fs::read_dir(temp.path())+ .unwrap()+ .filter_map(Result::ok)+ .filter(|entry| entry.file_name().to_string_lossy().contains("quarantine"))+ .count(),+ 0,+ "the quarantined generated file is deleted, never the replacement"+ );+ }++ #[test]+ fn opencode_plugin_restore_moves_quarantine_when_destination_is_free() {+ let temp = tempfile::tempdir().unwrap();+ let sibling = temp.path().join("ai-memory.ts");+ let quarantine = temp.path().join(".ai-memory-opencode-quarantine-test");+ fs::write(&quarantine, "export default function original() {}\n").unwrap();++ restore_quarantined_opencode_plugin_with(&quarantine, &sibling, || Ok(())).unwrap();++ assert_eq!(+ fs::read_to_string(&sibling).unwrap(),+ "export default function original() {}\n"+ );+ assert!(!quarantine.exists());+ }++ #[test]+ fn opencode_plugin_restore_preserves_an_existing_replacement() {+ let temp = tempfile::tempdir().unwrap();+ let sibling = temp.path().join("ai-memory.ts");+ let quarantine = temp.path().join(".ai-memory-opencode-quarantine-test");+ fs::write(&quarantine, "export default function original() {}\n").unwrap();+ fs::write(&sibling, "export default function replacement() {}\n").unwrap();++ restore_quarantined_opencode_plugin_with(&quarantine, &sibling, || Ok(())).unwrap();++ assert_eq!(+ fs::read_to_string(&sibling).unwrap(),+ "export default function replacement() {}\n"+ );+ assert_eq!(+ fs::read_to_string(&quarantine).unwrap(),+ "export default function original() {}\n"+ );+ }++ #[test]+ fn opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window() {+ let temp = tempfile::tempdir().unwrap();+ let sibling = temp.path().join("ai-memory.ts");+ let quarantine = temp.path().join(".ai-memory-opencode-quarantine-test");+ fs::write(&quarantine, "export default function original() {}\n").unwrap();++ restore_quarantined_opencode_plugin_with(&quarantine, &sibling, || {+ fs::write(&sibling, "export default function concurrent() {}\n")?;+ Ok(())+ })+ .unwrap();++ assert_eq!(+ fs::read_to_string(&sibling).unwrap(),+ "export default function concurrent() {}\n"+ );+ assert_eq!(+ fs::read_to_string(&quarantine).unwrap(),+ "export default function original() {}\n"+ );+ }++ #[test]+ fn opencode_plugin_apply_is_byte_idempotent_after_cleanup() {+ let temp = tempfile::tempdir().unwrap();+ let plugin = temp.path().join("ai-memory-opencode2.ts");+ let sibling = temp.path().join("ai-memory.ts");+ fs::write(+ &sibling,+ "// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.\nconst AGENT = \"open-code\";\n",+ )+ .unwrap();+ let mut args = default_hook_args();+ args.agent = AgentChoice::OpenCode2;+ args.config_file = Some(plugin.clone());++ apply_to_opencode2_plugin("http://127.0.0.1:49374", None, &args, "denylist").unwrap();+ let first = fs::read(&plugin).unwrap();+ apply_to_opencode2_plugin("http://127.0.0.1:49374", None, &args, "denylist").unwrap();+ assert_eq!(fs::read(&plugin).unwrap(), first);+ assert!(!sibling.exists());+ }++ #[test]+ fn opencode_plugin_cleanup_does_not_escape_custom_target_directory() {+ let temp = tempfile::tempdir().unwrap();+ let custom = temp.path().join("custom.ts");+ let sibling = temp.path().join("ai-memory.ts");+ fs::write(+ &sibling,+ "// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.\nconst AGENT = \"open-code\";\n",+ )+ .unwrap();++ remove_incompatible_opencode_plugin(&custom, AgentChoice::OpenCode2).unwrap();+ assert!(sibling.exists());+ }+#[test]fn opencode_plugin_uses_real_plugin_hooks() {let plugin = build_opencode_plugin("http://127.0.0.1:49374", Some("tok"), None, "denylist");diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 328d19c9..9c471d01 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -15,6 +15,7 @@//! profile's `~/.omp/profiles/<name>/agent`, or `$PI_CODING_AGENT_DIR`) with//! the same `mcpServers` root as several other clients.+use std::fs;use std::path::{Path, PathBuf};use anyhow::{Context, Result, bail};@@ -56,10 +57,54 @@ enum JsonMcpLocation {/// Returns an error if JSON serialisation fails (should never happen/// for our handcrafted values).pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {- let server_url = effective_mcp_server_url(config, &args);+ run_with_opencode_dialect(config, args, None)+}++pub(crate) fn run_with_opencode_dialect(+ config: &Config,+ mut args: InstallMcpArgs,+ dialect: Option<ai_memory_workstream::OpenCodeDialect>,+) -> Result<()> {+ let child_env = super::run::EffectiveChildEnv::from_runtime(&config.runtime_env);+ args.client = match (args.client, dialect) {+ (McpClient::OpenCode, Some(ai_memory_workstream::OpenCodeDialect::V1)) => {+ McpClient::OpenCode+ }+ (McpClient::OpenCode, Some(ai_memory_workstream::OpenCodeDialect::V2)) => {+ McpClient::OpenCode2+ }+ (client, None) => super::opencode_dialect::resolve_client(client, &child_env)?,+ (client, Some(_)) => client,+ };+ let needs_inferred_url = args.server_url.is_none() && !config.server_url_configured();+ let needs_inferred_token = args.auth_token.is_none() && config.auth.bearer_token.is_none();+ let inferred = if args.name == "ai-memory"+ && matches!(args.client, McpClient::OpenCode | McpClient::OpenCode2)+ && (needs_inferred_url || needs_inferred_token)+ {+ let path = resolve_config_file(&args)?;+ fs::read_to_string(path)+ .ok()+ .map(|content| infer_owned_opencode_mcp_config(&content, args.client))+ .transpose()?+ .flatten()+ } else {+ None+ };+ let server_url = if config.server_url_configured() || args.server_url.is_some() {+ effective_mcp_server_url(config, &args)+ } else {+ inferred.as_ref().map_or_else(+ || DEFAULT_MCP_URL.to_string(),+ |entry| entry.mcp_url.clone(),+ )+ };let args = InstallMcpArgs {server_url: Some(server_url),- auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),+ auth_token: args+ .auth_token+ .or_else(|| config.auth.bearer_token.clone())+ .or_else(|| inferred.and_then(|entry| entry.auth_token)),..args};validate_args(&args)?;@@ -186,11 +231,10 @@ pub(crate) fn mcp_config_path_with(.join(".config").join("opencode").join("opencode.json"),- // V2 reads the same global config file (`opencode.json(c)`); its- // `mcp.servers` key coexists with v1's `mcp` key in one strict-JSON- // file, so both binaries stay wired side by side. Users who keep- // comments in `opencode.jsonc` should pass it via `--config-file`- // (`mutate_json` refuses to rewrite non-strict JSON).+ // V2 reads the same global config file (`opencode.json(c)`) but uses+ // `mcp.servers`. Users who keep comments in `opencode.jsonc` should+ // pass it via `--config-file` (`mutate_json` refuses to rewrite+ // non-strict JSON).McpClient::OpenCode2 => home()?.join(".config").join("opencode")@@ -628,11 +672,239 @@ fn build_json_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {}}+fn migrate_opencode_mcp_entry(+ root: &mut serde_json::Map<String, serde_json::Value>,+ args: &InstallMcpArgs,+) -> Result<()> {+ if matches!(args.client, McpClient::OpenCode | McpClient::OpenCode2)+ && opencode_selected_entry(root, args.client, &args.name)+ .is_some_and(|entry| !opencode_mcp_entry_has_generated_shape(entry, args.client))+ {+ bail!(+ "refusing to replace user-owned OpenCode MCP entry '{}' in the selected major-version location",+ args.name+ );+ }+ let alternate = match args.client {+ McpClient::OpenCode => root+ .get("mcp")+ .and_then(serde_json::Value::as_object)+ .and_then(|mcp| mcp.get("servers"))+ .and_then(serde_json::Value::as_object)+ .and_then(|servers| servers.get(&args.name))+ .cloned(),+ McpClient::OpenCode2 => root+ .get("mcp")+ .and_then(serde_json::Value::as_object)+ .and_then(|mcp| mcp.get(&args.name))+ .cloned(),+ _ => None,+ };+ let Some(alternate) = alternate else {+ return Ok(());+ };+ if opencode_mcp_entry_has_generated_shape(+ &alternate,+ match args.client {+ McpClient::OpenCode => McpClient::OpenCode2,+ McpClient::OpenCode2 => McpClient::OpenCode,+ other => other,+ },+ ) && opencode_selected_entry(root, args.client, &args.name)+ .is_some_and(|entry| !opencode_mcp_entry_has_generated_shape(entry, args.client))+ {+ bail!(+ "refusing to replace a user-owned OpenCode MCP entry '{}' in the selected major-version location while migrating the generated alternate entry",+ args.name+ );+ }+ if !opencode_mcp_entry_is_owned(&alternate, args) {+ eprintln!(+ "[ai-memory] warning: preserving ambiguous OpenCode MCP entry '{}' in the alternate major-version location",+ args.name+ );+ return Ok(());+ }+ let mcp = root+ .get_mut("mcp")+ .and_then(serde_json::Value::as_object_mut)+ .context("`mcp` is present but not an object")?;+ match args.client {+ McpClient::OpenCode => {+ if let Some(servers) = mcp+ .get_mut("servers")+ .and_then(serde_json::Value::as_object_mut)+ {+ servers.remove(&args.name);+ if servers.is_empty() {+ mcp.remove("servers");+ }+ }+ }+ McpClient::OpenCode2 => {+ mcp.remove(&args.name);+ }+ _ => {}+ }+ Ok(())+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct InferredOpenCodeMcpConfig {+ pub(crate) mcp_url: String,+ pub(crate) auth_token: Option<String>,+}++pub(crate) fn infer_owned_opencode_mcp_config(+ content: &str,+ selected: McpClient,+) -> Result<Option<InferredOpenCodeMcpConfig>> {+ let root: serde_json::Value = match serde_json::from_str(content) {+ Ok(root) => root,+ Err(_) => return Ok(None),+ };+ let v1_entry = root.pointer("/mcp/ai-memory");+ let v2_entry = root.pointer("/mcp/servers/ai-memory");+ let v1 = v1_entry.and_then(|entry| inferred_owned_opencode_entry(entry, McpClient::OpenCode));+ let v2 = v2_entry.and_then(|entry| inferred_owned_opencode_entry(entry, McpClient::OpenCode2));+ let selected_is_user_owned = match selected {+ McpClient::OpenCode => v1_entry.is_some() && v1.is_none(),+ McpClient::OpenCode2 => v2_entry.is_some() && v2.is_none(),+ _ => false,+ };+ let alternate_is_generated = match selected {+ McpClient::OpenCode => v2.is_some(),+ McpClient::OpenCode2 => v1.is_some(),+ _ => false,+ };+ if selected_is_user_owned && alternate_is_generated {+ bail!(+ "a user-owned OpenCode MCP entry occupies the selected major-version location while a generated entry remains in the alternate location; preserved both, pass explicit --server-url and --auth-token after resolving the conflict"+ );+ }+ match (v1, v2) {+ (Some(v1), Some(v2)) if v1 != v2 => bail!(+ "conflicting generated OpenCode MCP entries exist in the V1 and V2 locations; pass explicit --server-url and --auth-token before installing"+ ),+ (Some(v1), Some(_)) | (Some(v1), None) => Ok(Some(v1)),+ (None, Some(v2)) => Ok(Some(v2)),+ (None, None) => {+ let selected_entry = match selected {+ McpClient::OpenCode => root.pointer("/mcp/ai-memory"),+ McpClient::OpenCode2 => root.pointer("/mcp/servers/ai-memory"),+ _ => None,+ };+ if selected_entry.is_some() {+ eprintln!(+ "[ai-memory] warning: preserving user-owned OpenCode MCP entry in the selected major-version location; pass explicit --server-url and --auth-token rather than inferring from it"+ );+ }+ Ok(None)+ }+ }+}++fn inferred_owned_opencode_entry(+ entry: &serde_json::Value,+ location: McpClient,+) -> Option<InferredOpenCodeMcpConfig> {+ if !opencode_mcp_entry_has_generated_shape(entry, location) {+ return None;+ }+ let object = entry.as_object()?;+ Some(InferredOpenCodeMcpConfig {+ mcp_url: object+ .get("url")+ .and_then(serde_json::Value::as_str)?+ .to_string(),+ auth_token: object+ .get("headers")+ .and_then(|headers| headers.get("Authorization"))+ .and_then(serde_json::Value::as_str)+ .and_then(|value| value.trim().strip_prefix("Bearer "))+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(ToOwned::to_owned),+ })+}++fn opencode_selected_entry<'a>(+ root: &'a serde_json::Map<String, serde_json::Value>,+ client: McpClient,+ name: &str,+) -> Option<&'a serde_json::Value> {+ let mcp = root.get("mcp")?.as_object()?;+ match client {+ McpClient::OpenCode => mcp.get(name),+ McpClient::OpenCode2 => mcp.get("servers")?.as_object()?.get(name),+ _ => None,+ }+}++fn opencode_generated_headers(headers: Option<&serde_json::Value>) -> bool {+ let Some(headers) = headers else {+ return true;+ };+ let Some(headers) = headers.as_object() else {+ return false;+ };+ headers.len() == 1+ && headers+ .get("Authorization")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|value| value.starts_with("Bearer ") && value.len() > "Bearer ".len())+}++fn opencode_mcp_entry_has_generated_shape(entry: &serde_json::Value, location: McpClient) -> bool {+ let Some(entry) = entry.as_object() else {+ return false;+ };+ if entry.get("type").and_then(serde_json::Value::as_str) != Some("remote")+ || entry+ .get("url")+ .and_then(serde_json::Value::as_str)+ .is_none()+ {+ return false;+ }+ let allowed = ["type", "url", "enabled", "oauth", "headers"];+ if entry.keys().any(|key| !allowed.contains(&key.as_str()))+ || !opencode_generated_headers(entry.get("headers"))+ {+ return false;+ }+ match location {+ McpClient::OpenCode => {+ entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(true)+ && !entry.contains_key("oauth")+ }+ McpClient::OpenCode2 => {+ entry.get("oauth").and_then(serde_json::Value::as_bool) == Some(false)+ && !entry.contains_key("enabled")+ }+ _ => false,+ }+}++fn opencode_mcp_entry_is_owned(entry: &serde_json::Value, args: &InstallMcpArgs) -> bool {+ let expected_url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL);+ entry.get("url").and_then(serde_json::Value::as_str) == Some(expected_url)+ && opencode_mcp_entry_has_generated_shape(+ entry,+ match args.client {+ McpClient::OpenCode => McpClient::OpenCode2,+ McpClient::OpenCode2 => McpClient::OpenCode,+ other => other,+ },+ )+}+fn upsert_json_mcp_entry(root: &mut serde_json::Map<String, serde_json::Value>,args: &InstallMcpArgs,) -> Result<()> {let entry = build_json_mcp_entry(args)?;+ migrate_opencode_mcp_entry(root, args)?;match json_mcp_location(args.client).context("internal: unsupported JSON MCP client")? {JsonMcpLocation::RootMcpServers => {let servers = root@@ -1267,10 +1539,10 @@ fn render_opencode2(args: &InstallMcpArgs) -> Result<String> {"# OpenCode 2.0 beta (`opencode2`) — merge into\n\# ~/.config/opencode/opencode.json(c) under \"mcp\" → \"servers\":\n\#\n\- # V2 nests servers under `mcp.servers` (v1 used top-level `mcp`)\n\- # and has no `enabled` field. Both keys coexist in the one file,\n\- # so v1 and the beta stay wired side by side. If your config is\n\- # `opencode.jsonc` with comments, re-run with\n\+ # V2 nests servers under `mcp.servers` (V1 used direct `mcp`)\n\+ # and has no `enabled` field. Apply mode migrates an alternate V1\n\+ # entry only when its endpoint and generated shape prove ownership.\n\+ # If your config is `opencode.jsonc` with comments, re-run with\n\# `--config-file ~/.config/opencode/opencode.jsonc`.\n\{snippet}\n",snippet = render_json_mcp_fragment(args)?,@@ -1641,6 +1913,302 @@ mod tests {assert!(!rendered.contains("\"mcpServers\""), "{rendered}");}+ #[test]+ fn opencode_mcp_migration_moves_only_owned_alternate_shape() {+ let args = args_with_token(McpClient::OpenCode2);+ let mut root = json!({+ "mcp": {+ "ai-memory": {+ "type": "remote",+ "url": "http://127.0.0.1:49374/mcp",+ "enabled": true,+ "headers": {"Authorization": "Bearer old"}+ },+ "other": {"type": "remote", "url": "https://example.invalid/mcp"}+ }+ })+ .as_object()+ .unwrap()+ .clone();++ upsert_json_mcp_entry(&mut root, &args).unwrap();+ assert!(root["mcp"].get("ai-memory").is_none());+ assert_eq!(root["mcp"]["other"]["url"], "https://example.invalid/mcp");+ assert_eq!(root["mcp"]["servers"]["ai-memory"]["oauth"], json!(false));+ let once = serde_json::to_string_pretty(&root).unwrap();+ upsert_json_mcp_entry(&mut root, &args).unwrap();+ assert_eq!(serde_json::to_string_pretty(&root).unwrap(), once);+ }++ #[test]+ fn opencode_mcp_migration_works_in_both_major_directions() {+ let mut root = json!({+ "mcp": {+ "servers": {+ "ai-memory": {+ "type": "remote",+ "url": "http://127.0.0.1:49374/mcp",+ "oauth": false+ }+ }+ }+ })+ .as_object()+ .unwrap()+ .clone();++ upsert_json_mcp_entry(&mut root, &args_for(McpClient::OpenCode)).unwrap();+ assert!(root["mcp"].get("servers").is_none());+ assert_eq!(root["mcp"]["ai-memory"]["enabled"], json!(true));+ }++ #[test]+ fn opencode_mcp_migration_preserves_custom_headers() {+ let args = args_for(McpClient::OpenCode2);+ let user_entry = json!({+ "type": "remote",+ "url": "http://127.0.0.1:49374/mcp",+ "enabled": true,+ "headers": {+ "Authorization": "Bearer user-token",+ "X-User-Route": "custom"+ }+ });+ let mut root = json!({"mcp": {"ai-memory": user_entry.clone()}})+ .as_object()+ .unwrap()+ .clone();++ upsert_json_mcp_entry(&mut root, &args).unwrap();+ assert_eq!(root["mcp"]["ai-memory"], user_entry);+ assert!(root["mcp"]["servers"]["ai-memory"].is_object());+ }++ #[test]+ fn opencode_mcp_migration_accepts_only_historical_generated_headers() {+ for headers in [+ None,+ Some(json!({"Authorization": "Bearer historical-token"})),+ ] {+ let mut entry = serde_json::Map::from_iter([+ ("type".to_string(), json!("remote")),+ ("url".to_string(), json!("http://127.0.0.1:49374/mcp")),+ ("enabled".to_string(), json!(true)),+ ]);+ if let Some(headers) = headers {+ entry.insert("headers".to_string(), headers);+ }+ assert!(opencode_mcp_entry_is_owned(+ &serde_json::Value::Object(entry),+ &args_for(McpClient::OpenCode2),+ ));+ }+ }++ #[test]+ fn opencode_install_reuses_owned_endpoint_and_token_across_major_transitions() {+ for (client, initial, selected_path, removed_path, expected_url) in [+ (+ McpClient::OpenCode2,+ json!({"mcp":{"ai-memory":{"type":"remote","url":"http://v1-host:49374/mcp","enabled":true,"headers":{"Authorization":"Bearer v1-token"}}}}),+ "/mcp/servers/ai-memory",+ "/mcp/ai-memory",+ "http://v1-host:49374/mcp",+ ),+ (+ McpClient::OpenCode,+ json!({"mcp":{"servers":{"ai-memory":{"type":"remote","url":"http://v2-host:49374/mcp","oauth":false,"headers":{"Authorization":"Bearer v2-token"}}}}}),+ "/mcp/ai-memory",+ "/mcp/servers/ai-memory",+ "http://v2-host:49374/mcp",+ ),+ ] {+ let tmp = tempfile::tempdir().unwrap();+ let config_path = tmp.path().join("opencode.json");+ fs::write(+ &config_path,+ serde_json::to_string_pretty(&initial).unwrap(),+ )+ .unwrap();+ let config = Config::default();+ let mut args = args_for(client);+ args.server_url = None;+ args.config_file = Some(config_path.clone());+ args.apply = true;++ run_with_opencode_dialect(+ &config,+ args,+ Some(match client {+ McpClient::OpenCode => ai_memory_workstream::OpenCodeDialect::V1,+ McpClient::OpenCode2 => ai_memory_workstream::OpenCodeDialect::V2,+ _ => unreachable!(),+ }),+ )+ .unwrap();++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(config_path).unwrap()).unwrap();+ let entry = root.pointer(selected_path).unwrap();+ assert_eq!(entry["url"], expected_url);+ let expected_token = if client == McpClient::OpenCode2 {+ "Bearer v1-token"+ } else {+ "Bearer v2-token"+ };+ assert_eq!(entry["headers"]["Authorization"], expected_token);+ assert!(root.pointer(removed_path).is_none());+ }+ }++ #[test]+ fn opencode_install_refuses_conflicting_owned_transition_entries() {+ let tmp = tempfile::tempdir().unwrap();+ let config_path = tmp.path().join("opencode.json");+ let initial = json!({"mcp":{+ "ai-memory":{"type":"remote","url":"http://v1-host:49374/mcp","enabled":true},+ "servers":{"ai-memory":{"type":"remote","url":"http://v2-host:49374/mcp","oauth":false}}+ }});+ fs::write(+ &config_path,+ serde_json::to_string_pretty(&initial).unwrap(),+ )+ .unwrap();+ let mut args = args_for(McpClient::OpenCode2);+ args.server_url = None;+ args.config_file = Some(config_path.clone());+ args.apply = true;++ let error = run_with_opencode_dialect(+ &Config::default(),+ args,+ Some(ai_memory_workstream::OpenCodeDialect::V2),+ )+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("conflicting generated OpenCode MCP entries")+ );+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&fs::read_to_string(config_path).unwrap())+ .unwrap(),+ initial+ );+ }++ #[test]+ fn opencode_install_refuses_generated_transition_over_a_user_owned_selected_entry() {+ let tmp = tempfile::tempdir().unwrap();+ let config_path = tmp.path().join("opencode.json");+ let initial = json!({"mcp":{+ "ai-memory":{"type":"remote","url":"http://user-host:49374/mcp","enabled":true,"command":"user-owned"},+ "servers":{"ai-memory":{"type":"remote","url":"http://generated-host:49374/mcp","oauth":false}}+ }});+ fs::write(+ &config_path,+ serde_json::to_string_pretty(&initial).unwrap(),+ )+ .unwrap();+ let mut args = args_for(McpClient::OpenCode);+ args.server_url = None;+ args.config_file = Some(config_path.clone());+ args.apply = true;++ let error = run_with_opencode_dialect(+ &Config::default(),+ args,+ Some(ai_memory_workstream::OpenCodeDialect::V1),+ )+ .unwrap_err();+ assert!(error.to_string().contains("user-owned OpenCode MCP entry"));+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&fs::read_to_string(config_path).unwrap())+ .unwrap(),+ initial+ );+ }++ #[test]+ fn opencode_install_does_not_infer_from_a_user_owned_transition_entry() {+ let tmp = tempfile::tempdir().unwrap();+ let config_path = tmp.path().join("opencode.json");+ let user = json!({+ "type":"remote",+ "url":"http://user-host:49374/mcp",+ "enabled":true,+ "headers":{"Authorization":"Bearer user-token","X-User":"route"}+ });+ fs::write(+ &config_path,+ serde_json::to_string_pretty(&json!({"mcp":{"ai-memory":user.clone()}})).unwrap(),+ )+ .unwrap();+ let mut args = args_for(McpClient::OpenCode2);+ args.server_url = None;+ args.config_file = Some(config_path.clone());+ args.apply = true;++ run_with_opencode_dialect(+ &Config::default(),+ args,+ Some(ai_memory_workstream::OpenCodeDialect::V2),+ )+ .unwrap();++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(config_path).unwrap()).unwrap();+ assert_eq!(root["mcp"]["ai-memory"], user);+ assert_eq!(root["mcp"]["servers"]["ai-memory"]["url"], DEFAULT_MCP_URL);+ }++ #[test]+ fn opencode_mcp_apply_is_byte_idempotent_after_migration() {+ let tmp = tempfile::tempdir().unwrap();+ let config = tmp.path().join("opencode.json");+ fs::write(+ &config,+ serde_json::to_string_pretty(&json!({+ "mcp": {+ "ai-memory": {+ "type": "remote",+ "url": "http://127.0.0.1:49374/mcp",+ "enabled": true+ }+ }+ }))+ .unwrap(),+ )+ .unwrap();+ let mut args = args_for(McpClient::OpenCode2);+ args.config_file = Some(config.clone());+ args.apply = true;++ apply_to_config_file(&args).unwrap();+ let first = fs::read(&config).unwrap();+ apply_to_config_file(&args).unwrap();+ assert_eq!(fs::read(&config).unwrap(), first);+ }++ #[test]+ fn opencode_mcp_migration_preserves_ambiguous_user_entry() {+ let args = args_for(McpClient::OpenCode2);+ let user_entry = json!({+ "type": "remote",+ "url": "http://127.0.0.1:49374/mcp",+ "enabled": true,+ "command": "user-owned"+ });+ let mut root = json!({"mcp": {"ai-memory": user_entry.clone()}})+ .as_object()+ .unwrap()+ .clone();++ upsert_json_mcp_entry(&mut root, &args).unwrap();+ assert_eq!(root["mcp"]["ai-memory"], user_entry);+ assert!(root["mcp"]["servers"]["ai-memory"].is_object());+ }+#[test]fn opencode2_entry_uses_v2_servers_shape() {// V2 nests under `mcp.servers`, drops v1's `enabled`, and disablesdiff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex fd53a4d0..792fbc5d 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -58,6 +58,7 @@ pub mod message;pub mod move_project;pub mod move_session;pub mod openclaw_plugin;+pub mod opencode_dialect;pub mod path_util;pub mod pending_writes;pub mod project;diff --git a/crates/ai-memory-cli/src/commands/opencode_dialect.rs b/crates/ai-memory-cli/src/commands/opencode_dialect.rsnew file mode 100644index 00000000..eb7af36b--- /dev/null+++ b/crates/ai-memory-cli/src/commands/opencode_dialect.rs@@ -0,0 +1,308 @@+//! OpenCode major-version resolution shared by launch and installers.++use std::ffi::OsStr;+use std::io::Read;+use std::process::{Command, Stdio};+use std::sync::mpsc;+use std::thread;+use std::time::{Duration, Instant};++use ai_memory_workstream::OpenCodeDialect;+use anyhow::{Context as _, Result, anyhow, bail};++use crate::cli::{AgentChoice, McpClient};+use crate::commands::run::EffectiveChildEnv;++const PROBE_TIMEOUT: Duration = Duration::from_secs(2);+const MAX_VERSION_OUTPUT: u64 = 64 * 1024;++#[derive(Debug)]+pub(crate) struct ResolvedOpenCode {+ pub(crate) dialect: OpenCodeDialect,+ pub(crate) executable: std::path::PathBuf,+}++pub(crate) fn resolve_agent(agent: AgentChoice, env: &EffectiveChildEnv) -> Result<AgentChoice> {+ if agent != AgentChoice::OpenCode {+ return Ok(agent);+ }+ match resolve_generic(None, env)?.dialect {+ OpenCodeDialect::V1 => Ok(AgentChoice::OpenCode),+ OpenCodeDialect::V2 => Ok(AgentChoice::OpenCode2),+ }+}++pub(crate) fn resolve_client(client: McpClient, env: &EffectiveChildEnv) -> Result<McpClient> {+ if client != McpClient::OpenCode {+ return Ok(client);+ }+ match resolve_generic(None, env)?.dialect {+ OpenCodeDialect::V1 => Ok(McpClient::OpenCode),+ OpenCodeDialect::V2 => Ok(McpClient::OpenCode2),+ }+}++pub(crate) fn resolve_generic(+ executable: Option<&OsStr>,+ env: &EffectiveChildEnv,+) -> Result<ResolvedOpenCode> {+ let program = executable.unwrap_or_else(|| OsStr::new("opencode"));+ let resolved = super::run::resolve_program(program, env.executable_search()).ok_or_else(|| {+ anyhow!(+ "OpenCode executable `{}` was not found; install it or select an explicit opencode2 compatibility alias",+ program.to_string_lossy()+ )+ })?;+ let mut command = Command::new(&resolved);+ env.apply_to_std(&mut command);+ let mut child = command+ .arg("--version")+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .with_context(|| format!("probing OpenCode executable {}", resolved.display()))?;+ let stdout = read_bounded(child.stdout.take());+ let stderr = read_bounded(child.stderr.take());+ let started = Instant::now();+ let status = loop {+ if let Some(status) = child+ .try_wait()+ .with_context(|| format!("waiting for OpenCode version probe {}", resolved.display()))?+ {+ break status;+ }+ if started.elapsed() >= PROBE_TIMEOUT {+ let _ = child.kill();+ let _ = child.wait();+ return Err(timeout_error(&resolved));+ }+ thread::sleep(Duration::from_millis(10));+ };+ let remaining = PROBE_TIMEOUT.saturating_sub(started.elapsed());+ let stdout = stdout+ .recv_timeout(remaining)+ .map_err(|_| timeout_error(&resolved))??;+ let remaining = PROBE_TIMEOUT.saturating_sub(started.elapsed());+ let stderr = stderr+ .recv_timeout(remaining)+ .map_err(|_| timeout_error(&resolved))??;+ if stdout.len() > MAX_VERSION_OUTPUT as usize || stderr.len() > MAX_VERSION_OUTPUT as usize {+ bail!("OpenCode version probe returned more than {MAX_VERSION_OUTPUT} bytes");+ }+ if !status.success() {+ bail!(+ "OpenCode version probe `{}` --version failed with {status}: {}",+ resolved.display(),+ String::from_utf8_lossy(&stderr).trim()+ );+ }+ let stdout = std::str::from_utf8(&stdout).context("OpenCode version output was not UTF-8")?;+ let stderr =+ std::str::from_utf8(&stderr).context("OpenCode version error output was not UTF-8")?;+ let output = match (stdout.trim(), stderr.trim()) {+ ("", "") => bail!("OpenCode version probe returned no output"),+ (stdout, "") => stdout.to_string(),+ ("", stderr) => stderr.to_string(),+ (stdout, stderr) => format!("{stdout}\n{stderr}"),+ };+ let dialect = OpenCodeDialect::parse_version_output(&output).with_context(|| {+ format!(+ "could not determine the OpenCode major from `{}` --version output {:?}; expected a semantic version with major 1 or 2",+ resolved.display(),+ output.trim()+ )+ })?;+ Ok(ResolvedOpenCode {+ dialect,+ executable: resolved,+ })+}++fn timeout_error(program: &std::path::Path) -> anyhow::Error {+ anyhow!(+ "OpenCode version probe timed out after {} seconds for {}; run `{} --version` and verify it exits promptly",+ PROBE_TIMEOUT.as_secs(),+ program.display(),+ program.display()+ )+}++fn read_bounded(+ pipe: Option<impl Read + Send + 'static>,+) -> mpsc::Receiver<std::io::Result<Vec<u8>>> {+ let (sender, receiver) = mpsc::channel();+ thread::spawn(move || {+ let result = (|| {+ let mut bytes = Vec::new();+ if let Some(pipe) = pipe {+ pipe.take(MAX_VERSION_OUTPUT + 1).read_to_end(&mut bytes)?;+ }+ Ok(bytes)+ })();+ let _ = sender.send(result);+ });+ receiver+}++#[cfg(test)]+mod tests {+ use ai_memory_workstream::ManagedHarness;++ use super::*;++ #[test]+ fn explicit_v2_alias_choices_force_v2_without_probing() {+ assert_eq!(+ resolve_agent(+ AgentChoice::OpenCode2,+ &EffectiveChildEnv::from_runtime(&crate::config::RuntimeEnv::default()),+ )+ .unwrap(),+ AgentChoice::OpenCode2+ );+ assert_eq!(+ resolve_client(+ McpClient::OpenCode2,+ &EffectiveChildEnv::from_runtime(&crate::config::RuntimeEnv::default()),+ )+ .unwrap(),+ McpClient::OpenCode2+ );+ }++ #[test]+ fn version_reader_caps_captured_output() {+ let output = read_bounded(Some(std::io::Cursor::new(vec![+ b'x';+ MAX_VERSION_OUTPUT as usize+ + 128+ ])))+ .recv_timeout(Duration::from_secs(1))+ .unwrap()+ .unwrap();+ assert_eq!(output.len(), MAX_VERSION_OUTPUT as usize + 1);+ }++ #[cfg(unix)]+ fn fake_version(version: &str) -> tempfile::TempDir {+ use std::os::unix::fs::PermissionsExt as _;++ let temp = tempfile::tempdir().unwrap();+ let executable = temp.path().join("opencode");+ std::fs::write(+ &executable,+ format!("#!/bin/sh\nprintf '%s\\n' '{version}'\n"),+ )+ .unwrap();+ let mut permissions = std::fs::metadata(&executable).unwrap().permissions();+ permissions.set_mode(0o755);+ std::fs::set_permissions(executable, permissions).unwrap();+ temp+ }++ #[cfg(unix)]+ #[test]+ fn exact_fake_executable_selects_each_dialect() {+ for (version, expected) in [+ ("1.18.34", ManagedHarness::OpenCode),+ ("opencode v2.0.23 (build abc)", ManagedHarness::OpenCode2),+ ] {+ let temp = fake_version(version);+ assert_eq!(+ resolve_generic(+ Some(temp.path().join("opencode").as_os_str()),+ &EffectiveChildEnv::from_runtime(&crate::config::RuntimeEnv::default()),+ )+ .unwrap()+ .dialect+ .harness(),+ expected+ );+ }+ }++ #[cfg(unix)]+ #[test]+ fn version_probe_uses_the_effective_child_environment() {+ use std::os::unix::fs::PermissionsExt as _;++ let temp = tempfile::tempdir().unwrap();+ let executable = temp.path().join("opencode");+ std::fs::write(+ &executable,+ "#!/bin/sh\n[ -z \"${HOME+x}\" ] || { printf 'ambient leak\\n'; exit 1; }\nprintf '%s.%s.0\\n' \"$OPENCODE_MAJOR\" \"$OPENCODE_MINOR\"\n",+ )+ .unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();+ let env = EffectiveChildEnv::for_tests([+ ("PATH", temp.path().as_os_str()),+ ("OPENCODE_MAJOR", OsStr::new("2")),+ ("OPENCODE_MINOR", OsStr::new("7")),+ ]);++ let resolved = resolve_generic(None, &env).unwrap();+ assert_eq!(resolved.dialect, OpenCodeDialect::V2);+ assert_eq!(resolved.executable, executable);+ }++ #[cfg(unix)]+ #[test]+ fn version_probe_timeout_fails_actionably() {+ use std::os::unix::fs::PermissionsExt as _;++ let temp = tempfile::tempdir().unwrap();+ let executable = temp.path().join("opencode");+ std::fs::write(&executable, "#!/bin/sh\nexec sleep 5\n").unwrap();+ let mut permissions = std::fs::metadata(&executable).unwrap().permissions();+ permissions.set_mode(0o755);+ std::fs::set_permissions(&executable, permissions).unwrap();++ let error = resolve_generic(+ Some(executable.as_os_str()),+ &EffectiveChildEnv::from_runtime(&crate::config::RuntimeEnv::default()),+ )+ .unwrap_err()+ .to_string();+ assert!(error.contains("version probe timed out"), "{error}");+ }++ #[cfg(windows)]+ #[test]+ fn windows_explicit_extensionless_path_resolves_the_cmd_launcher() {+ let temp = tempfile::tempdir().unwrap();+ let base = temp.path().join("opencode-custom");+ std::fs::write(+ base.with_extension("cmd"),+ "@echo off\r\necho opencode v2.0.23\r\n",+ )+ .unwrap();+ let resolved = resolve_generic(+ Some(base.as_os_str()),+ &EffectiveChildEnv::from_runtime(&crate::config::RuntimeEnv::default()),+ )+ .unwrap();+ assert_eq!(resolved.dialect, OpenCodeDialect::V2);+ assert_eq!(resolved.executable, base.with_extension("cmd"));+ }++ #[cfg(unix)]+ #[test]+ fn malformed_and_future_fake_versions_fail_actionably() {+ for version in ["OpenCode latest", "3.0.0"] {+ let temp = fake_version(version);+ let error = format!(+ "{:#}",+ resolve_generic(+ Some(temp.path().join("opencode").as_os_str()),+ &EffectiveChildEnv::from_runtime(&crate::config::RuntimeEnv::default()),+ )+ .unwrap_err()+ );+ assert!(+ error.contains("could not determine the OpenCode major"),+ "{error}"+ );+ }+ }+}diff --git a/crates/ai-memory-cli/src/commands/resume.rs b/crates/ai-memory-cli/src/commands/resume.rsindex e5825df4..67b80166 100644--- a/crates/ai-memory-cli/src/commands/resume.rs+++ b/crates/ai-memory-cli/src/commands/resume.rs@@ -122,7 +122,7 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {);}- let harnesses = available_harnesses();+ let harnesses = available_harnesses(config);let mut harness_indices = vec![0usize; candidates.len()];let mut choices = candidates.iter()diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 2ce1574b..cf7a1f04 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -16,7 +16,7 @@ use ai_memory_workstream::{JailHostFacts, JailSupport, JailToggleChoice, JailToggleKind, LaunchMode, LaunchPlan,LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_support,allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_ai_jail_invocation,- build_launch_plan, build_launch_plan_with_env, claude_attached_background_session,+ build_launch_plan, build_launch_plan_with_env_lookup, claude_attached_background_session,claude_live_background_attach_id, claude_session_ran_in_background, clean_path,crush_global_config_path, discover_native_session, export_transcript,has_native_session_selector, inside_ai_jail_here, inspect_repository, jail_checklist,@@ -53,6 +53,114 @@ const IMPORT_BATCH_BYTES: usize = 1024 * 1024;const ADOPTION_CANDIDATE_LIMIT: usize = 8;/// Bound on `claude agents --json`, which only reads the daemon's session list.const CLAUDE_AGENTS_TIMEOUT: Duration = Duration::from_secs(10);++#[derive(Clone, Default)]+pub(crate) struct EffectiveChildEnv {+ entries: Vec<(OsString, OsString)>,+}++impl EffectiveChildEnv {+ pub(super) fn from_runtime(env: &crate::config::RuntimeEnv) -> Self {+ Self {+ entries: env.process_env().to_vec(),+ }+ }++ pub(crate) fn with_overrides(+ env: &crate::config::RuntimeEnv,+ overrides: &[(String, String)],+ ) -> Self {+ Self::with_overrides_for_platform(env.process_env(), overrides, cfg!(windows))+ }++ pub(crate) fn with_overrides_for_platform(+ base: &[(OsString, OsString)],+ overrides: &[(String, String)],+ windows: bool,+ ) -> Self {+ let mut effective = Self {+ entries: base.to_vec(),+ };+ for (key, value) in overrides {+ effective.upsert(OsString::from(key), OsString::from(value), windows);+ }+ effective+ }++ fn upsert(&mut self, key: OsString, value: OsString, windows: bool) {+ self.entries+ .retain(|(existing, _)| !environment_keys_equal(existing, &key, windows));+ self.entries.push((key, value));+ }++ pub(crate) fn get(&self, name: &str) -> Option<&OsStr> {+ self.get_for_platform(name, cfg!(windows))+ }++ fn get_for_platform(&self, name: &str, windows: bool) -> Option<&OsStr> {+ self.entries+ .iter()+ .rev()+ .find(|(key, _)| environment_keys_equal(key, OsStr::new(name), windows))+ .map(|(_, value)| value.as_os_str())+ }++ pub(crate) fn with_additional_overrides(&self, overrides: &[(String, String)]) -> Self {+ Self::with_overrides_for_platform(&self.entries, overrides, cfg!(windows))+ }++ pub(crate) fn executable_search(&self) -> ExecutableSearch<'_> {+ ExecutableSearch {+ path: self.get("PATH"),+ extensions: self.get("PATHEXT"),+ }+ }++ pub(crate) fn apply_to_std(&self, command: &mut std::process::Command) {+ command+ .env_clear()+ .envs(self.entries.iter().map(|(key, value)| (key, value)));+ }++ fn apply_to_tokio(&self, command: &mut Command) {+ command+ .env_clear()+ .envs(self.entries.iter().map(|(key, value)| (key, value)));+ }++ #[cfg(test)]+ pub(crate) fn for_tests(+ entries: impl IntoIterator<Item = (impl Into<OsString>, impl Into<OsString>)>,+ ) -> Self {+ Self {+ entries: entries+ .into_iter()+ .map(|(key, value)| (key.into(), value.into()))+ .collect(),+ }+ }++ #[cfg(test)]+ pub(crate) fn entries(&self) -> &[(OsString, OsString)] {+ &self.entries+ }+}++pub(crate) fn environment_keys_equal(left: &OsStr, right: &OsStr, windows: bool) -> bool {+ if windows {+ left.to_string_lossy()+ .eq_ignore_ascii_case(&right.to_string_lossy())+ } else {+ left == right+ }+}++#[derive(Clone, Copy)]+pub(crate) struct ExecutableSearch<'a> {+ path: Option<&'a OsStr>,+ extensions: Option<&'a OsStr>,+}+const AUTO_HARNESSES: [ManagedHarness; 9] = [ManagedHarness::Claude,ManagedHarness::Codex,@@ -90,6 +198,28 @@ impl HeartbeatHealth {}}+fn resolve_opencode_for_launch(+ requested: Option<RunHarnessChoice>,+ executable: Option<&OsStr>,+ env: &EffectiveChildEnv,+) -> Result<Option<super::opencode_dialect::ResolvedOpenCode>> {+ let search = env.executable_search();+ let automatic = requested.is_none();+ if !(matches!(requested, Some(RunHarnessChoice::OpenCode))+ || automatic && executable_available(OsStr::new("opencode"), search))+ {+ return Ok(None);+ }+ match super::opencode_dialect::resolve_generic(executable, env) {+ Ok(resolved) => Ok(Some(resolved)),+ Err(error) if automatic => {+ eprintln!("ai-memory: automatic OpenCode scan skipped: {error:#}");+ Ok(None)+ }+ Err(error) => Err(error),+ }+}+/// Run one native harness and return its exact process exit code.pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {let cwd = std::env::current_dir().context("getting managed run working directory")?;@@ -125,6 +255,8 @@ pub(super) async fn run_from_with_wiring(let repository = inspect_repository(cwd)?;let home = native_home(config).context("locating native harness session storage")?;let automatic_harness = args.harness.is_none();+ let requested_harness = args.harness;+ let mut executable = args.executable.map(PathBuf::into_os_string);let mut native_args = args.native_args;let trailing_yolo = remove_wrapper_yolo(&mut native_args);let trailing_true_yolo = remove_wrapper_true_yolo(&mut native_args);@@ -144,33 +276,72 @@ pub(super) async fn run_from_with_wiring(let no_autowire = args.no_autowire || trailing_no_autowire;let run_env = resolve_run_env(args.env_file.as_deref(), &args.env).context("resolving --env/--env-file for the managed run")?;+ let child_env = EffectiveChildEnv::with_overrides(&config.runtime_env, &run_env);+ let executable_search = child_env.executable_search();if automatic_harness && !native_args.is_empty() {return Err(anyhow!("native harness arguments require an explicit harness; try `ai-memory run codex ...`"));}- if automatic_harness && args.executable.is_some() {+ if automatic_harness && executable.is_some() {return Err(anyhow!("--executable requires an explicit harness; try `ai-memory run --executable <path> codex`"));}+ let resolved_opencode =+ resolve_opencode_for_launch(requested_harness, executable.as_deref(), &child_env)?;+ if matches!(requested_harness, Some(RunHarnessChoice::OpenCode))+ && let Some(resolved) = &resolved_opencode+ {+ executable = Some(resolved.executable.clone().into_os_string());+ }let auto_candidates = if automatic_harness {filter_usable_auto_sessions(- list_auto_sessions(&home, &repository.cwd, &run_env).await?,- |harness| executable_available(OsStr::new(harness.executable())),+ list_auto_sessions(+ &home,+ &repository.cwd,+ &child_env,+ resolved_opencode+ .as_ref()+ .map(|resolved| resolved.dialect.harness()),+ )+ .await?,+ |harness| {+ matches!(+ harness,+ ManagedHarness::OpenCode | ManagedHarness::OpenCode2+ ) && resolved_opencode.is_some()+ || executable_available(OsStr::new(harness.executable()), executable_search)+ },)?} else {Vec::new()};- let provisional_harness = match args.harness {+ let provisional_harness = match requested_harness {+ Some(RunHarnessChoice::OpenCode) => resolved_opencode+ .as_ref()+ .map(|resolved| resolved.dialect.harness())+ .context("OpenCode dialect was not resolved")?,Some(choice) => managed_harness_for_args(choice, &native_args),None => auto_candidates.first().map(|candidate| candidate.harness).ok_or_else(no_auto_session_error)?,};- let executable = args.executable.map(PathBuf::into_os_string);- ensure_executable_available(provisional_harness, executable.as_deref())?;+ if automatic_harness+ && matches!(+ provisional_harness,+ ManagedHarness::OpenCode | ManagedHarness::OpenCode2+ )+ && let Some(resolved) = &resolved_opencode+ {+ executable = Some(resolved.executable.clone().into_os_string());+ }+ ensure_executable_available(+ provisional_harness,+ executable.as_deref(),+ executable_search,+ )?;// Resolve BOTH halves here. `--workspace` used to default to a literal// `default`, so a checkout whose marker declared another workspace put its// managed workstream in one scope while its hook-captured sessions went to@@ -292,6 +463,9 @@ pub(super) async fn run_from_with_wiring(selected,provisional_harness,prepared.native_session_id.as_deref(),+ resolved_opencode+ .as_ref()+ .map(|resolved| resolved.dialect.harness()),)} else {provisional_harness@@ -308,7 +482,20 @@ pub(super) async fn run_from_with_wiring(} else {resolved_harness};- acquired_try!(ensure_executable_available(harness, executable.as_deref()));+ if automatic_harness+ && matches!(+ harness,+ ManagedHarness::OpenCode | ManagedHarness::OpenCode2+ )+ && let Some(resolved) = &resolved_opencode+ {+ executable = Some(resolved.executable.clone().into_os_string());+ }+ acquired_try!(ensure_executable_available(+ harness,+ executable.as_deref(),+ executable_search,+ ));// Warn, and offer ai-jail, before any further native-session work — a// yolo re-exec under ai-jail must forward the original argv, not the// resolved launch plan, and restarting cleanly under ai-jail before@@ -334,7 +521,7 @@ pub(super) async fn run_from_with_wiring(force_fresh,&home,&repository.cwd,- &run_env,+ &child_env,));let resumes_linked_session = !force_fresh&& orphaned_session.is_none()@@ -382,12 +569,12 @@ pub(super) async fn run_from_with_wiring(.find(|candidate| candidate.harness == harness).context("the selected automatic harness no longer has a checkout-local session"));- plan = acquired_try!(build_launch_plan_with_env(+ plan = acquired_try!(build_launch_plan_with_env_lookup(harness,executable.clone(),native_args.clone(),Some(&candidate.session.native_session_id),- &run_env,+ |name| child_env.get(name).map(OsStr::to_os_string),Some(LaunchRoots {home: &home,cwd: &repository.cwd,@@ -429,12 +616,12 @@ pub(super) async fn run_from_with_wiring();match selection {Ok(Some(native_session_id)) => {- plan = acquired_try!(build_launch_plan_with_env(+ plan = acquired_try!(build_launch_plan_with_env_lookup(harness,executable,native_args,Some(&native_session_id),- &run_env,+ |name| child_env.get(name).map(OsStr::to_os_string),Some(LaunchRoots {home: &home,cwd: &repository.cwd,@@ -502,13 +689,7 @@ pub(super) async fn run_from_with_wiring(// home the child will read, and before the child spawns so the harness// picks up the fresh hooks.// The environment the child runs with: `--env` over ai-memory's own.- let launch_env = |name: &str| {- run_env- .iter()- .find(|(key, _)| key == name)- .map(|(_, value)| OsString::from(value))- .or_else(|| std::env::var_os(name))- };+ let launch_env = |name: &str| child_env.get(name).map(OsStr::to_os_string);if config.run_autowire && !no_autowire {// A Kiro v3 resume from the default store drops `KIRO_HOME` from the// child, so its hooks and MCP belong under the default home.@@ -520,7 +701,14 @@ pub(super) async fn run_from_with_wiring(home.join(".kiro").display().to_string(),);}- super::run_autowire::ensure_wired_with(config, harness, wire_overrides, &wire_env);+ let wire_child_env = child_env.with_additional_overrides(&wire_env);+ super::run_autowire::ensure_wired_with_env(+ config,+ harness,+ wire_overrides,+ &wire_env,+ &wire_child_env,+ );}// A Kiro v3 resume that dropped `KIRO_HOME` runs against the default store.let linked_store = effective_store(@@ -558,8 +746,15 @@ pub(super) async fn run_from_with_wiring(&& resumes_linked_session&& let Some(native_session_id) = plan.expected_session_id.as_deref(){- claude_background_attach_id(&plan, &home, &repository.cwd, &run_env, native_session_id)- .await+ claude_background_attach_id(+ &plan,+ &home,+ &repository.cwd,+ &child_env,+ native_session_id,+ executable_search,+ )+ .await} else {None};@@ -610,14 +805,11 @@ pub(super) async fn run_from_with_wiring(// alone can match an unlaunchable extension-less shim (see// `resolve_program`). Falling back to the plan's own value keeps an// unresolvable program reaching the spawn error below, which explains it.- let program = resolve_program(&plan.program).unwrap_or_else(|| plan.program.clone().into());+ let program = resolve_program(&plan.program, executable_search)+ .unwrap_or_else(|| plan.program.clone().into());let mut command = Command::new(&program);+ child_env.apply_to_tokio(&mut command);command.args(&plan.args).current_dir(&repository.cwd);- // Caller-supplied `--env`/`--env-file` entries go first so the fixed- // AI_MEMORY_* plumbing below always wins on a key collision.- for (key, value) in &run_env {- command.env(key, value);- }command.env("AI_MEMORY_RUN_ID", prepared.run_id.to_string()).env(@@ -1549,16 +1741,23 @@ async fn resolve_native_session_after_run(async fn list_auto_sessions(home: &Path,cwd: &Path,- env_overrides: &[(String, String)],+ env: &EffectiveChildEnv,+ opencode_harness: Option<ManagedHarness>,) -> Result<Vec<AutoSessionCandidate>> {let mut found = Vec::new();let mut failures = Vec::new();- for harness in AUTO_HARNESSES {+ for mut harness in AUTO_HARNESSES {+ if harness == ManagedHarness::OpenCode {+ let Some(resolved) = opencode_harness else {+ continue;+ };+ harness = resolved;+ }// Scan the store the launch would resume from. With a custom// `CLAUDE_CONFIG_DIR` (or another store override) the default store// holds none of this checkout's sessions, so scanning it either finds// nothing or picks a session the launched harness cannot see.- let session_dir = match auto_session_dir(harness, home, cwd, env_overrides) {+ let session_dir = match auto_session_dir(harness, home, cwd, env) {Ok(session_dir) => session_dir,Err(error) => {failures.push(format!("{}: {error}", harness.as_str()));@@ -1599,14 +1798,14 @@ fn auto_session_dir(harness: ManagedHarness,home: &Path,cwd: &Path,- env_overrides: &[(String, String)],+ env: &EffectiveChildEnv,) -> Result<Option<PathBuf>> {- Ok(build_launch_plan_with_env(+ Ok(build_launch_plan_with_env_lookup(harness,None,Vec::new(),None,- env_overrides,+ |name| env.get(name).map(OsStr::to_os_string),Some(LaunchRoots { home, cwd }),)?.session_dir)@@ -1627,12 +1826,15 @@ fn automatic_harness_flavor(selected: ManagedHarness,provisional: ManagedHarness,linked_session_id: Option<&str>,+ opencode_harness: Option<ManagedHarness>,) -> ManagedHarness {if selected == ManagedHarness::Kiro&& provisional.agent_kind() == AgentKind::KiroCli&& linked_session_id.is_none(){provisional+ } else if selected == ManagedHarness::OpenCode {+ opencode_harness.unwrap_or(selected)} else {selected}@@ -1810,10 +2012,19 @@ fn resolve_run_env(/// Insert or replace one entry in an ordered env list, keeping the position/// of an existing key so `--env-file` order stays stable across overrides.fn upsert_env(entries: &mut Vec<(String, String)>, key: String, value: String) {- if let Some(existing) = entries- .iter_mut()- .find(|(existing_key, _)| *existing_key == key)- {+ upsert_env_for_platform(entries, key, value, cfg!(windows));+}++fn upsert_env_for_platform(+ entries: &mut Vec<(String, String)>,+ key: String,+ value: String,+ windows: bool,+) {+ if let Some(existing) = entries.iter_mut().find(|(existing_key, _)| {+ environment_keys_equal(OsStr::new(existing_key), OsStr::new(&key), windows)+ }) {+ existing.0 = key;existing.1 = value;} else {entries.push((key, value));@@ -1877,7 +2088,7 @@ fn build_preflighted_launch_plan(force_fresh: bool,home: &Path,cwd: &Path,- env_overrides: &[(String, String)],+ env: &EffectiveChildEnv,) -> Result<(LaunchPlan, Option<String>)> {let explicit_selector = has_native_session_selector(harness, &native_args);if force_fresh && explicit_selector {@@ -1886,12 +2097,12 @@ fn build_preflighted_launch_plan());}let linked_session_id = if force_fresh { None } else { linked_session_id };- let plan = build_launch_plan_with_env(+ let plan = build_launch_plan_with_env_lookup(harness,executable.clone(),native_args.clone(),linked_session_id,- env_overrides,+ |name| env.get(name).map(OsStr::to_os_string),Some(LaunchRoots { home, cwd }),)?;let Some(linked_session_id) = linked_session_id else {@@ -1909,12 +2120,12 @@ fn build_preflighted_launch_plan() {Ok(true) => Ok((plan, None)),Ok(false) => Ok((- build_launch_plan_with_env(+ build_launch_plan_with_env_lookup(harness,executable,native_args,None,- env_overrides,+ |name| env.get(name).map(OsStr::to_os_string),Some(LaunchRoots { home, cwd }),)?,Some(linked_session_id.to_string()),@@ -2027,9 +2238,13 @@ fn store_mismatch_error())}-fn ensure_executable_available(harness: ManagedHarness, executable: Option<&OsStr>) -> Result<()> {+fn ensure_executable_available(+ harness: ManagedHarness,+ executable: Option<&OsStr>,+ search: ExecutableSearch<'_>,+) -> Result<()> {let program = executable.unwrap_or_else(|| OsStr::new(harness.executable()));- if executable_available(program) {+ if executable_available(program, search) {return Ok(());}Err(anyhow!(@@ -2045,12 +2260,12 @@ fn ensure_executable_available(harness: ManagedHarness, executable: Option<&OsSt/// [`ensure_executable_available`] would accept a moment later. Harnesses/// reached only through `--executable` are not covered: the picker has no way/// to ask for that path.-pub(super) fn harness_available(choice: RunHarnessChoice) -> bool {- executable_available(OsStr::new(managed_harness(choice).executable()))+pub(super) fn harness_available(choice: RunHarnessChoice, search: ExecutableSearch<'_>) -> bool {+ executable_available(OsStr::new(managed_harness(choice).executable()), search)}-fn executable_available(program: &OsStr) -> bool {- resolve_program(program).is_some()+fn executable_available(program: &OsStr, search: ExecutableSearch<'_>) -> bool {+ resolve_program(program, search).is_some()}/// The `claude attach` id for a linked Claude session that is still running in@@ -2062,8 +2277,9 @@ async fn claude_background_attach_id(plan: &LaunchPlan,home: &Path,cwd: &Path,- env: &[(String, String)],+ env: &EffectiveChildEnv,native_session_id: &str,+ search: ExecutableSearch<'_>,) -> Option<String> {let background =claude_session_ran_in_background(home, cwd, plan.session_dir.as_deref(), native_session_id)@@ -2071,13 +2287,14 @@ async fn claude_background_attach_id(if !background {return None;}- let program = resolve_program(&plan.program).unwrap_or_else(|| plan.program.clone().into());+ let program =+ resolve_program(&plan.program, search).unwrap_or_else(|| plan.program.clone().into());let mut command = Command::new(&program);+ env.apply_to_tokio(&mut command);command.args(["agents", "--json", "--cwd"]).arg(cwd).current_dir(cwd)- .envs(env.iter().map(|(key, value)| (key, value))).stdin(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true);@@ -2102,18 +2319,27 @@ async fn claude_background_attach_id(/// to spawn with "program not found". Resolving to the concrete file keeps the/// availability check and the launch agreeing on one answer, and lets the/// launch use a path that works.-pub(super) fn resolve_program(program: &OsStr) -> Option<std::path::PathBuf> {+pub(super) fn resolve_program(+ program: &OsStr,+ search: ExecutableSearch<'_>,+) -> Option<std::path::PathBuf> {let path = Path::new(program);if path.components().count() > 1 {- return resolve_candidate(path);+ return resolve_candidate(path, search.extensions);}- std::env::var_os("PATH").and_then(|path_value| {- std::env::split_paths(&path_value).find_map(|dir| resolve_candidate(&dir.join(path)))+ search.path.and_then(|path_value| {+ std::env::split_paths(path_value)+ .find_map(|dir| resolve_candidate(&dir.join(path), search.extensions))})}/// Concrete launchable file for one candidate location.-fn resolve_candidate(path: &Path) -> Option<std::path::PathBuf> {+fn resolve_candidate(+ path: &Path,+ executable_extensions: Option<&OsStr>,+) -> Option<std::path::PathBuf> {+ #[cfg(not(windows))]+ let _ = executable_extensions;#[cfg(windows)]{// An explicit extension is taken at face value; otherwise only a@@ -2121,8 +2347,9 @@ fn resolve_candidate(path: &Path) -> Option<std::path::PathBuf> {if path.extension().is_some() && executable_file(path) {return Some(path.to_path_buf());}- let extensions =- std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());+ let extensions = executable_extensions+ .and_then(OsStr::to_str)+ .unwrap_or(".COM;.EXE;.BAT;.CMD");extensions.split(';').filter(|extension| !extension.is_empty())@@ -3374,9 +3601,11 @@ mod tests {/// offer an agent that cannot start.#[test]fn executable_available_rejects_a_program_that_is_not_installed() {- assert!(!executable_available(OsStr::new(- "ai-memory-no-such-harness-binary"- )));+ let env = EffectiveChildEnv::from_runtime(&crate::config::RuntimeEnv::default());+ assert!(!executable_available(+ OsStr::new("ai-memory-no-such-harness-binary"),+ env.executable_search(),+ ));}/// An absolute path that exists resolves without consulting `PATH`, which@@ -3384,13 +3613,83 @@ mod tests {#[test]fn executable_available_accepts_an_existing_absolute_path() {let current = std::env::current_exe().unwrap();- assert!(executable_available(current.as_os_str()));+ let runtime = crate::config::RuntimeEnv::default();+ let env = EffectiveChildEnv::from_runtime(&runtime);+ let search = env.executable_search();+ assert!(executable_available(current.as_os_str(), search));assert_eq!(- resolve_program(current.as_os_str()).as_deref(),+ resolve_program(current.as_os_str(), search).as_deref(),Some(current.as_path()));}+ #[test]+ fn resolved_run_env_overlays_windows_keys_case_insensitively() {+ let mut entries = vec![("Path".to_string(), "C:\\base".to_string())];+ upsert_env_for_platform(+ &mut entries,+ "PATH".to_string(),+ "C:\\override".to_string(),+ true,+ );++ assert_eq!(+ entries,+ vec![("PATH".to_string(), "C:\\override".to_string())]+ );+ }++ #[test]+ fn effective_child_env_keeps_unix_path_keys_case_sensitive() {+ let base = [(OsString::from("PATH"), OsString::from("/base"))];+ let overrides = [("Path".to_string(), "/override".to_string())];+ let env = EffectiveChildEnv::with_overrides_for_platform(&base, &overrides, false);++ assert_eq!(+ env.get_for_platform("PATH", false),+ Some(OsStr::new("/base"))+ );+ assert_eq!(+ env.get_for_platform("Path", false),+ Some(OsStr::new("/override"))+ );+ assert_eq!(env.entries().len(), 2);+ }++ #[test]+ fn effective_child_env_overlays_windows_path_keys_case_insensitively() {+ for override_key in ["PATH", "Path", "path"] {+ let base = [+ (OsString::from("Path"), OsString::from("C:\\base")),+ (OsString::from("PATHEXT"), OsString::from(".EXE;.CMD")),+ ];+ let overrides = [+ (override_key.to_string(), "C:\\override".to_string()),+ ("pathext".to_string(), ".BAT;.CMD".to_string()),+ ];+ let env = EffectiveChildEnv::with_overrides_for_platform(&base, &overrides, true);++ assert_eq!(+ env.get_for_platform("PATH", true),+ Some(OsStr::new("C:\\override")),+ "{override_key}"+ );+ assert_eq!(+ env.get_for_platform("PATHEXT", true),+ Some(OsStr::new(".BAT;.CMD")),+ "{override_key}"+ );+ assert_eq!(+ env.entries()+ .iter()+ .filter(|(key, _)| environment_keys_equal(key, OsStr::new("PATH"), true))+ .count(),+ 1,+ "{override_key}"+ );+ }+ }+/// npm-style installs drop an extension-less shell script beside the/// `.cmd` wrapper. On Windows only the wrapper is launchable, so probing/// for mere existence reported the harness as available and the launch@@ -3402,7 +3701,7 @@ mod tests {std::fs::write(tmp.path().join("faux-harness"), "#!/bin/sh\n").unwrap();assert_eq!(- resolve_candidate(&tmp.path().join("faux-harness")),+ resolve_candidate(&tmp.path().join("faux-harness"), None),None,"an extension-less script is not launchable by CreateProcess");@@ -3412,8 +3711,11 @@ mod tests {"@echo off\r\nexit /b 0\r\n",).unwrap();- let resolved =- resolve_candidate(&tmp.path().join("faux-harness")).expect("the wrapper resolves");+ let resolved = resolve_candidate(+ &tmp.path().join("faux-harness"),+ Some(OsStr::new(".COM;.EXE;.BAT;.CMD")),+ )+ .expect("the wrapper resolves");// PATHEXT is upper-case, and Windows paths are case-insensitive, so the// resolved name carries whichever casing the probe used.assert_eq!(@@ -3437,7 +3739,7 @@ mod tests {#[test]fn unix_resolution_returns_the_file_itself() {let current = std::env::current_exe().unwrap();- assert_eq!(resolve_candidate(¤t), Some(current));+ assert_eq!(resolve_candidate(¤t, None), Some(current));}fn candidates() -> Vec<NativeSessionCandidate> {@@ -3839,6 +4141,46 @@ mod tests {}}+ #[cfg(unix)]+ #[test]+ fn automatic_opencode_probe_failure_keeps_another_harness_available() {+ use std::os::unix::fs::PermissionsExt as _;++ let temp = tempfile::tempdir().unwrap();+ let bin = temp.path().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ for (name, body) in [+ ("opencode", "#!/bin/sh\nprintf 'OpenCode latest\\n'\n"),+ ("codex", "#!/bin/sh\nexit 0\n"),+ ] {+ let path = bin.join(name);+ std::fs::write(&path, body).unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let env = EffectiveChildEnv::for_tests([("PATH", bin.as_os_str())]);+ let search = env.executable_search();++ assert!(+ resolve_opencode_for_launch(None, None, &env)+ .unwrap()+ .is_none()+ );+ let usable = filter_usable_auto_sessions(+ vec![auto_candidate(ManagedHarness::Codex, 100)],+ |harness| executable_available(OsStr::new(harness.executable()), search),+ )+ .unwrap();+ assert_eq!(usable.len(), 1);+ assert_eq!(usable[0].harness, ManagedHarness::Codex);++ let explicit =+ resolve_opencode_for_launch(Some(RunHarnessChoice::OpenCode), None, &env).unwrap_err();+ assert!(+ format!("{explicit:#}").contains("could not determine the OpenCode major"),+ "{explicit:#}"+ );+ }+#[test]fn automatic_selection_skips_newer_sessions_for_unavailable_harnesses() {let candidates = vec![@@ -4124,21 +4466,40 @@ mod tests {assert_eq!(unique_auto_agents(&candidates), [AgentKind::KiroCli]);assert_eq!(- automatic_harness_flavor(ManagedHarness::Kiro, ManagedHarness::KiroV3, None),+ automatic_harness_flavor(ManagedHarness::Kiro, ManagedHarness::KiroV3, None, None,),ManagedHarness::KiroV3);assert_eq!(- automatic_harness_flavor(ManagedHarness::Kiro, ManagedHarness::KiroV3, Some("linked"),),+ automatic_harness_flavor(+ ManagedHarness::Kiro,+ ManagedHarness::KiroV3,+ Some("linked"),+ None,+ ),ManagedHarness::Kiro);}+ #[test]+ fn automatic_opencode_selection_keeps_the_resolved_major() {+ assert_eq!(+ automatic_harness_flavor(+ ManagedHarness::OpenCode,+ ManagedHarness::OpenCode2,+ Some("linked"),+ Some(ManagedHarness::OpenCode2),+ ),+ ManagedHarness::OpenCode2+ );+ }+#[test]fn incompatible_link_starts_fresh_in_the_explicit_kiro_engine() {let temp = tempfile::tempdir().unwrap();let cwd = temp.path().join("repo");std::fs::create_dir_all(&cwd).unwrap();+ let env = EffectiveChildEnv::default();let (fresh, orphaned) = build_preflighted_launch_plan(ManagedHarness::KiroV3,None,@@ -4147,7 +4508,7 @@ mod tests {false,temp.path(),&cwd,- &[],+ &env,).unwrap();assert_eq!(@@ -4382,7 +4743,7 @@ mod tests {"CLAUDE_CONFIG_DIR".to_string(),"/accounts/work".to_string(),)];- let plan = build_launch_plan_with_env(+ let plan = ai_memory_workstream::build_launch_plan_with_env(ManagedHarness::Claude,None,Vec::new(),@@ -4420,7 +4781,7 @@ mod tests {).unwrap();std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();- let env = vec![+ let env = [("FAKE_CALLS".to_string(), calls.display().to_string()),("FAKE_AGENTS".to_string(), listing.display().to_string()),];@@ -4441,7 +4802,13 @@ mod tests {).unwrap();plan.session_dir = None;- let attach = || claude_background_attach_id(&plan, temp.path(), &cwd, &env, full);+ let child_env = EffectiveChildEnv::for_tests(+ env.iter()+ .map(|(key, value)| (OsString::from(key), OsString::from(value))),+ );+ let search = child_env.executable_search();+ let attach =+ || claude_background_attach_id(&plan, temp.path(), &cwd, &child_env, full, search);let transcript = |kind: Option<&str>| {let mut record = serde_json::json!({"type": "user", "sessionId": full, "cwd": cwd});if let Some(kind) = kind {@@ -4724,6 +5091,7 @@ mod tests {session_root.as_os_str().to_os_string(),].to_vec();+ let env = EffectiveChildEnv::default();let (resumed, orphaned) = build_preflighted_launch_plan(ManagedHarness::Pi,@@ -4733,7 +5101,7 @@ mod tests {false,temp.path(),&cwd,- &[],+ &env,).unwrap();assert!(orphaned.is_none());@@ -4749,7 +5117,7 @@ mod tests {false,temp.path(),&cwd,- &[],+ &env,).unwrap();assert_eq!(orphaned.as_deref(), Some("linked"));@@ -4768,7 +5136,7 @@ mod tests {false,temp.path(),&cwd,- &[],+ &env,).unwrap();assert!(orphaned.is_none());@@ -4904,8 +5272,15 @@ mod tests {"CLAUDE_CONFIG_DIR".to_string(),custom.to_string_lossy().into_owned(),)];+ let env = EffectiveChildEnv::for_tests(+ overrides+ .iter()+ .map(|(key, value)| (OsString::from(key), OsString::from(value))),+ );- let found = list_auto_sessions(&home, &cwd, &overrides).await.unwrap();+ let found = list_auto_sessions(&home, &cwd, &env, Some(ManagedHarness::OpenCode))+ .await+ .unwrap();let claude: Vec<&str> = found.iter().filter(|candidate| candidate.harness == ManagedHarness::Claude)@@ -4919,6 +5294,7 @@ mod tests {let temp = tempfile::tempdir().unwrap();let cwd = temp.path().join("repo");std::fs::create_dir_all(&cwd).unwrap();+ let env = EffectiveChildEnv::default();let (fresh, orphaned) = build_preflighted_launch_plan(ManagedHarness::Claude,None,@@ -4927,7 +5303,7 @@ mod tests {true,temp.path(),&cwd,- &[],+ &env,).unwrap();assert!(orphaned.is_none());@@ -4942,7 +5318,7 @@ mod tests {true,temp.path(),&cwd,- &[],+ &env,).unwrap_err();assert!(error.to_string().contains("--fresh cannot be combined"));@@ -5267,6 +5643,122 @@ mod tests {assert_eq!(std::fs::read_to_string(packet).unwrap(), "managed packet");}+ #[cfg(unix)]+ #[tokio::test]+ async fn opencode_executable_probe_selects_v2_for_launch_and_autowire() {+ use std::os::unix::fs::PermissionsExt as _;++ use crate::commands::run_autowire::WireOverrides;+ use crate::config::Config;++ let app = Router::new()+ .route(+ "/workstream/runs",+ post(|| async {+ axum::Json(PrepareManagedRunResponse {+ workstream_id: WorkstreamId::new(),+ workstream_name: "default".into(),+ run_id: ManagedRunId::new(),+ resolved_agent: None,+ native_session_id: None,+ source_cursor: None,+ sync_after: 0,+ sync_through: 0,+ may_adopt_existing_session: false,+ })+ }),+ )+ .route(+ "/workstream/runs/{run_id}/finish",+ post(|| async {+ axum::Json(FinishManagedRunResponse {+ imported_events: 0,+ latest_sequence: 0,+ })+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });++ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let launched = repo.path().join("launched");+ let executable_dir = repo.path().join("child-bin");+ std::fs::create_dir_all(&executable_dir).unwrap();+ let executable = executable_dir.join("opencode");+ std::fs::write(+ &executable,+ format!(+ "#!/bin/sh\nif [ \"$1\" = --version ]; then printf 'opencode v%s.0.23\\n' \"$OPENCODE_MAJOR\"; exit 0; fi\nprintf '%s|%s\\n' \"$*\" \"$OPENCODE_MAJOR\" > {}\n",+ launched.display()+ ),+ )+ .unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();++ let plugins = data.path().join("plugins");+ std::fs::create_dir_all(&plugins).unwrap();+ let plugin = plugins.join("ai-memory-opencode2.ts");+ let mcp = data.path().join("opencode.json");+ let mut config = Config::load(None, Some(home.path().to_path_buf())).unwrap();+ config.data_dir = data.path().to_path_buf();+ config.home_dir = Some(home.path().to_string_lossy().into_owned());+ config.server_url = format!("http://{address}");+ config.run_autowire = true;+ let overrides = WireOverrides {+ hooks_config_file: Some(plugin.clone()),+ mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()+ };+ let args = RunArgs {+ workspace: Some("ws".into()),+ project: Some("proj".into()),+ workstream: None,+ new_workstream: None,+ executable: None,+ yolo: false,+ true_yolo: false,+ jail: None,+ no_jail: false,+ fresh: false,+ force_unlock: false,+ no_autowire: false,+ env: vec![+ ("PATH".into(), executable_dir.display().to_string()),+ ("OPENCODE_MAJOR".into(), "2".into()),+ ],+ env_file: None,+ harness: Some(RunHarnessChoice::OpenCode),+ native_args: vec![OsString::from("--help")],+ };++ let exit = run_from_with_wiring(&config, args, repo.path(), &overrides)+ .await+ .unwrap();+ assert_eq!(exit, 0);+ assert_eq!(+ std::fs::read_to_string(launched).unwrap().trim(),+ "--help|2"+ );+ assert!(+ std::fs::read_to_string(plugin)+ .unwrap()+ .contains("const AiMemoryOpencode2: Plugin.Plugin")+ );+ let mcp: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(mcp).unwrap()).unwrap();+ assert!(mcp["mcp"]["servers"]["ai-memory"].is_object());+ let sentinels = std::fs::read_dir(crate::commands::run_autowire::autowire_state_dir(+ data.path(),+ ))+ .unwrap()+ .count();+ assert_eq!(sentinels, 1);+ server.abort();+ }+/// The `ai-memory run` -> autowire -> child-spawn seam: driving the launcher/// entry point (`run_from_with_wiring`) must run auto-wire *before* the child/// starts, so the harness's ai-memory hooks + MCP are installed and thediff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex d9a482ec..d2bf0cc3 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -19,10 +19,10 @@//! with `run --no-autowire` or `AI_MEMORY_RUN_AUTOWIRE=false`.use std::cell::Cell;-use std::ffi::OsString;+use std::ffi::{OsStr, OsString};use std::path::{Component, Path, PathBuf};-use ai_memory_workstream::ManagedHarness;+use ai_memory_workstream::{ManagedHarness, OpenCodeDialect};use sha2::{Digest as _, Sha256};use crate::cli::{AgentChoice, InstallHooksArgs, InstallMcpArgs, McpClient};@@ -134,30 +134,34 @@ fn resolve_through_links(path: &Path) -> Option<PathBuf> {/// transcript import agree on one config home. It also records whether any/// value it handed out came from `--env`.struct LaunchEnv<'a> {+ effective: &'a super::run::EffectiveChildEnv,run_env: &'a [(String, String)],from_run_env: Cell<bool>,}impl<'a> LaunchEnv<'a> {- fn new(run_env: &'a [(String, String)]) -> Self {+ fn new(effective: &'a super::run::EffectiveChildEnv, run_env: &'a [(String, String)]) -> Self {Self {+ effective,run_env,from_run_env: Cell::new(false),}}fn var_os(&self, name: &str) -> Option<OsString> {- if let Some((_, value)) = self.run_env.iter().find(|(key, _)| key == name) {+ if self.run_env.iter().any(|(key, _)| {+ super::run::environment_keys_equal(OsStr::new(key), OsStr::new(name), cfg!(windows))+ }) {self.from_run_env.set(true);- return Some(OsString::from(value));}- std::env::var_os(name)+ self.effective.get(name).map(OsStr::to_os_string)}}/// Where this launch's auto-wire installs, resolved without touching the disk.struct WireTargets {agent: AgentChoice,+ opencode_dialect: Option<OpenCodeDialect>,sentinel: PathBuf,hook_target: anyhow::Result<PathBuf>,/// Whether any relocation variable behind the hook target came from `--env`.@@ -171,31 +175,53 @@ struct WireTargets {shared_extensions_dir: Option<PathBuf>,}+#[cfg(test)]fn wire_targets(config: &Config,harness: ManagedHarness,overrides: &WireOverrides,run_env: &[(String, String)],+) -> Option<WireTargets> {+ let effective_env = super::run::EffectiveChildEnv::with_overrides(&config.runtime_env, run_env);+ wire_targets_with_env(config, harness, overrides, run_env, &effective_env)+}++fn wire_targets_with_env(+ config: &Config,+ harness: ManagedHarness,+ overrides: &WireOverrides,+ run_env: &[(String, String)],+ effective_env: &super::run::EffectiveChildEnv,) -> Option<WireTargets> {let agent = agent_choice_for_harness(harness)?;- let hook_env = LaunchEnv::new(run_env);+ let opencode_dialect = match harness {+ ManagedHarness::OpenCode => Some(OpenCodeDialect::V1),+ ManagedHarness::OpenCode2 => Some(OpenCodeDialect::V2),+ _ => None,+ };+ let hook_env = LaunchEnv::new(effective_env, run_env);let hook_target = install_hooks::hook_config_target_with(agent, &|name| hook_env.var_os(name));let mcp_client = install_hooks::mcp_client_for_agent(agent);- let mcp_env = LaunchEnv::new(run_env);+ let mcp_env = LaunchEnv::new(effective_env, run_env);let mcp_target = mcp_client.map(|client| install_mcp::mcp_config_path_with(client, &|name| mcp_env.var_os(name)));let sentinel = sentinel_path(&config.data_dir,agent,&[+ opencode_dialect.map_or_else(+ || "dialect:default".to_string(),+ |dialect| format!("opencode-major:{}", dialect.major()),+ ),target_key(overrides.hooks_config_file.as_deref(), Some(&hook_target)),target_key(overrides.mcp_config_file.as_deref(), mcp_target.as_ref()),],);let shared_extensions_dir = match (&overrides.hooks_config_file, &hook_target) {(None, Ok(target)) => {- let launch = LaunchEnv::new(run_env);- let process = LaunchEnv::new(&[]);+ let launch = LaunchEnv::new(effective_env, run_env);+ let process_env = super::run::EffectiveChildEnv::from_runtime(&config.runtime_env);+ let process = LaunchEnv::new(&process_env, &[]);install_hooks::shared_extensions_dir(agent, target, &|name| launch.var_os(name)).filter(|_| {install_hooks::shared_extensions_dir(agent, target, &|name| {@@ -209,6 +235,7 @@ fn wire_targets(};Some(WireTargets {agent,+ opencode_dialect,sentinel,hook_target,hook_relocated: hook_env.from_run_env.get(),@@ -241,6 +268,7 @@ fn target_key(injected: Option<&Path>, resolved: Option<&anyhow::Result<PathBuf>/// otherwise a target is pinned only when `--env` moved it, so a launch without/// `--env` installs exactly where the installers pick on their own.struct WireInstalls {+ opencode_dialect: Option<OpenCodeDialect>,/// One hook install, or one per agent config for a Kiro CLI v2 home that/// `--env` relocated.hooks: Vec<InstallHooksArgs>,@@ -255,6 +283,7 @@ struct WireInstalls {fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverrides) -> WireInstalls {let WireTargets {agent,+ opencode_dialect,hook_target,hook_relocated,mcp_client,@@ -263,7 +292,8 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverrideshared_extensions_dir,..} = targets;- let server_url = Some(config.server_url.clone());+ let infer_opencode_transition = opencode_dialect.is_some() && !config.server_url_configured();+ let server_url = (!infer_opencode_transition).then(|| config.server_url.clone());let auth_token = config.auth.bearer_token.clone();let hook_install = |config_file: Option<PathBuf>| InstallHooksArgs {agent,@@ -358,6 +388,7 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverrideflavor: None,});WireInstalls {+ opencode_dialect,hooks,hooks_skipped,mcp,@@ -375,13 +406,26 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverride/// Production launches pass [`WireOverrides::default()`] (via/// [`run_from`](super::run::run_from)); the overrides exist only so the seam can/// be exercised without writing to the developer's real `$HOME`.+#[cfg(test)]pub(crate) fn ensure_wired_with(config: &Config,harness: ManagedHarness,overrides: &WireOverrides,run_env: &[(String, String)],) {- let Some(targets) = wire_targets(config, harness, overrides, run_env) else {+ let effective_env = super::run::EffectiveChildEnv::with_overrides(&config.runtime_env, run_env);+ ensure_wired_with_env(config, harness, overrides, run_env, &effective_env);+}++pub(crate) fn ensure_wired_with_env(+ config: &Config,+ harness: ManagedHarness,+ overrides: &WireOverrides,+ run_env: &[(String, String)],+ effective_env: &super::run::EffectiveChildEnv,+) {+ let Some(targets) = wire_targets_with_env(config, harness, overrides, run_env, effective_env)+ else {return;};if targets.sentinel.exists() {@@ -396,7 +440,7 @@ pub(crate) fn ensure_wired_with(harness.as_str());- let installs = wire_installs(config, targets, overrides);+ let mut installs = wire_installs(config, targets, overrides);let warn_hooks = |reason: &str| {eprintln!("ai-memory: could not auto-install {} hooks ({reason}); continuing launch. \@@ -405,23 +449,15 @@ pub(crate) fn ensure_wired_with(agent.kind().as_str());};- for args in installs.hooks {- match install_hooks::run(config, args) {- Ok(()) => {- if let Some(dir) = &installs.shared_extensions_dir {- install_hooks::warn_agents_share_extensions_dir(dir);- }- }- Err(error) => warn_hooks(&format!("{error:#}")),- }- }- if let Some(reason) = &installs.hooks_skipped {- warn_hooks(reason);- }-+ // Install MCP first so a major-version migration has one canonical selected+ // entry before the hook installer infers its endpoint and credential.// Not every hook-capable harness has an MCP client the installer can write// (e.g. Pi bridges MCP through its generated extension); skip those quietly.- let mcp_failure = match installs.mcp {+ let mcp_config_path = installs+ .mcp+ .as_ref()+ .and_then(|args| args.config_file.clone());+ let mcp_failure = match installs.mcp.take() {// The sentinel is version-keyed, so this whole step re-runs on every// upgrade. install-mcp replaces the `ai-memory` entry wholesale, so a// plain re-run would overwrite a session-aware Claude Code bridge the@@ -442,12 +478,14 @@ pub(crate) fn ensure_wired_with();None}- Some(args) => install_mcp::run(config, args)- .err()- .map(|error| format!("{error:#}")),+ Some(args) => {+ install_mcp::run_with_opencode_dialect(config, args, installs.opencode_dialect)+ .err()+ .map(|error| format!("{error:#}"))+ }None => installs.mcp_skipped,};- if let Some(reason) = mcp_failure {+ if let Some(reason) = &mcp_failure {eprintln!("ai-memory: could not auto-install the {} MCP server ({reason}); continuing \launch. Wire it manually with `ai-memory install-mcp --client {} --apply`.",@@ -456,6 +494,29 @@ pub(crate) fn ensure_wired_with();}+ if installs.opencode_dialect.is_some() && mcp_failure.is_some() {+ warn_hooks("the OpenCode MCP transition failed before hook endpoint/token inference");+ } else {+ for args in installs.hooks {+ match install_hooks::run_with_opencode_dialect_and_mcp_path(+ config,+ args,+ installs.opencode_dialect,+ mcp_config_path.as_deref(),+ ) {+ Ok(()) => {+ if let Some(dir) = &installs.shared_extensions_dir {+ install_hooks::warn_agents_share_extensions_dir(dir);+ }+ }+ Err(error) => warn_hooks(&format!("{error:#}")),+ }+ }+ if let Some(reason) = &installs.hooks_skipped {+ warn_hooks(reason);+ }+ }+// Record the attempt even on partial failure: re-applying an idempotent// install on every launch would nag and churn config. A user who wants a// retry can re-run install-hooks manually or delete this sentinel under@@ -512,6 +573,83 @@ mod tests {);}+ #[test]+ fn opencode_major_transition_changes_the_autowire_sentinel() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let overrides = WireOverrides::default();+ let v1 = wire_targets(&config, ManagedHarness::OpenCode, &overrides, &[]).unwrap();+ let v2 = wire_targets(&config, ManagedHarness::OpenCode2, &overrides, &[]).unwrap();+ assert_ne!(v1.sentinel, v2.sentinel);+ }++ #[test]+ fn opencode_autowire_migrates_mcp_before_hooks_infer_transition_settings() {+ let data = tempfile::tempdir().unwrap();+ let plugin = data.path().join("plugins/ai-memory-opencode2.ts");+ let mcp = data.path().join("opencode.json");+ std::fs::write(+ &mcp,+ r#"{"mcp":{"ai-memory":{"type":"remote","url":"http://transition-host:49374/mcp","enabled":true,"headers":{"Authorization":"Bearer transition-token"}}}}"#,+ )+ .unwrap();+ let config = Config {+ data_dir: data.path().join("data"),+ run_autowire: true,+ ..Config::default()+ };+ let overrides = WireOverrides {+ hooks_config_file: Some(plugin.clone()),+ mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()+ };++ ensure_wired_with(&config, ManagedHarness::OpenCode2, &overrides, &[]);++ let mcp: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(mcp).unwrap()).unwrap();+ assert!(mcp.pointer("/mcp/ai-memory").is_none());+ assert_eq!(+ mcp.pointer("/mcp/servers/ai-memory/url"),+ Some(&serde_json::json!("http://transition-host:49374/mcp"))+ );+ assert!(+ std::fs::read_to_string(plugin)+ .unwrap()+ .contains("http://transition-host:49374")+ );+ assert_eq!(+ crate::config::read_hook_auth_token(&config.data_dir).as_deref(),+ Some("transition-token")+ );+ }++ #[test]+ fn opencode_autowire_does_not_write_hooks_when_mcp_transition_conflicts() {+ let data = tempfile::tempdir().unwrap();+ let plugin = data.path().join("plugins/ai-memory-opencode2.ts");+ let mcp = data.path().join("opencode.json");+ let initial = r#"{"mcp":{"ai-memory":{"type":"remote","url":"http://v1-host:49374/mcp","enabled":true},"servers":{"ai-memory":{"type":"remote","url":"http://v2-host:49374/mcp","oauth":false}}}}"#;+ std::fs::write(&mcp, initial).unwrap();+ let config = Config {+ data_dir: data.path().join("data"),+ run_autowire: true,+ ..Config::default()+ };+ let overrides = WireOverrides {+ hooks_config_file: Some(plugin.clone()),+ mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()+ };++ ensure_wired_with(&config, ManagedHarness::OpenCode2, &overrides, &[]);++ assert!(!plugin.exists());+ assert_eq!(std::fs::read_to_string(mcp).unwrap(), initial);+ assert!(crate::config::read_hook_auth_token(&config.data_dir).is_none());+ }+#[test]fn sentinel_keys_on_agent_version_and_install_targets() {let dir = Path::new("/data");@@ -637,12 +775,21 @@ mod tests {/// masks the process one, the same layering native-session resolution uses.#[test]fn launch_env_prefers_run_env_and_records_it() {- let process_only = LaunchEnv::new(&[]);- assert_eq!(process_only.var_os("PATH"), std::env::var_os("PATH"));+ let process = crate::commands::run::EffectiveChildEnv::for_tests([("PATH", "/process")]);+ let process_only = LaunchEnv::new(&process, &[]);+ assert_eq!(+ process_only.var_os("PATH"),+ Some(OsString::from("/process"))+ );assert!(!process_only.from_run_env.get());let run_env = [("PATH".to_string(), "/from-run-env".to_string())];- let layered = LaunchEnv::new(&run_env);+ let effective = crate::commands::run::EffectiveChildEnv::with_overrides_for_platform(+ process.entries(),+ &run_env,+ false,+ );+ let layered = LaunchEnv::new(&effective, &run_env);assert_eq!(layered.var_os("PATH"),Some(OsString::from("/from-run-env"))@@ -650,7 +797,15 @@ mod tests {assert!(layered.from_run_env.get());let empty = [("PATH".to_string(), String::new())];- assert_eq!(LaunchEnv::new(&empty).var_os("PATH"), Some(OsString::new()));+ let effective = crate::commands::run::EffectiveChildEnv::with_overrides_for_platform(+ process.entries(),+ &empty,+ false,+ );+ assert_eq!(+ LaunchEnv::new(&effective, &empty).var_os("PATH"),+ Some(OsString::new())+ );}/// A named OMP profile owns its agent dir and ignoresdiff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex d2ee4b55..b1ad0fc6 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -36,14 +36,14 @@ use std::path::{Path, PathBuf};use anyhow::{Context, Result, bail};-use crate::cli::{AgentChoice, SetupAgentArgs};-use crate::commands::install_mcp;+use crate::cli::{AgentChoice, InstallHooksArgs, InstallMcpArgs, McpClient, SetupAgentArgs};use crate::commands::render_shared::{ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, COMMAND_CODE_PROFILE,CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_EVENTS,build_claude_code_payload, build_devin_payload, build_grok_payload, build_pool_settings_yaml,hook_script_for_current_platform,};+use crate::commands::{install_hooks, install_mcp};use crate::config::{Config, DEFAULT_SERVER_URL};/// Run the `setup-agent` subcommand.@@ -52,7 +52,25 @@ use crate::config::{Config, DEFAULT_SERVER_URL};/// Returns an error if the source bundle can't be located, the/// destination directory can't be created, any script copy fails,/// or the JSON config can't be serialised.-pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {+pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {+ args.agent = match (args.agent, args.opencode_dialect) {+ (AgentChoice::OpenCode, Some(choice)) => match choice.dialect() {+ ai_memory_workstream::OpenCodeDialect::V1 => AgentChoice::OpenCode,+ ai_memory_workstream::OpenCodeDialect::V2 => AgentChoice::OpenCode2,+ },+ (AgentChoice::OpenCode, None) => bail!(+ "setup-agent --agent opencode requires --opencode-dialect v1|v2 because a container cannot inspect the host executable"+ ),+ (AgentChoice::OpenCode2, None) => AgentChoice::OpenCode2,+ (AgentChoice::OpenCode2, Some(_)) => bail!(+ "--opencode-dialect cannot be combined with the force-V2 opencode2 compatibility alias"+ ),+ (agent, None) => agent,+ (agent, Some(_)) => bail!(+ "--opencode-dialect is valid only with --agent opencode, not {}",+ agent.kind().as_str()+ ),+ };let server_url = if args.server_url == DEFAULT_SERVER_URL && config.server_url_configured() {normalise_hook_server_url(&config.server_url)} else {@@ -71,7 +89,7 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {| AgentChoice::Omp| AgentChoice::Openclaw) {- emit_extension_setup_hint(&args)?;+ emit_extension_setup_hint(config, &args)?;return Ok(());}// Zero and ZCode run ai-memory's native `hook` command directly (exec@@ -285,7 +303,7 @@ fn normalise_hook_server_url(url: &str) -> String {url.trim().trim_end_matches('/').to_string()}-fn emit_extension_setup_hint(args: &SetupAgentArgs) -> Result<()> {+fn emit_extension_setup_hint(config: &Config, args: &SetupAgentArgs) -> Result<()> {let (label, agent, restart_note, mcp_client) = match args.agent {AgentChoice::OpenCode => ("OpenCode",@@ -327,6 +345,49 @@ fn emit_extension_setup_hint(args: &SetupAgentArgs) -> Result<()> {"# Legacy shell/PowerShell and remote-only paths are unsupported compatibility modes.");println!("# Install it directly instead:");+ if matches!(args.agent, AgentChoice::OpenCode | AgentChoice::OpenCode2) {+ let dialect = if args.agent == AgentChoice::OpenCode {+ ai_memory_workstream::OpenCodeDialect::V1+ } else {+ ai_memory_workstream::OpenCodeDialect::V2+ };+ install_hooks::run_with_opencode_dialect(+ config,+ InstallHooksArgs {+ agent: AgentChoice::OpenCode,+ hooks_dir: None,+ server_url: Some(args.server_url.clone()),+ auth_token: args.auth_token.clone(),+ as_user: None,+ apply: false,+ config_file: None,+ project_strategy: None,+ capture_assistant: false,+ capture_mode: None,+ no_capture_prompts: false,+ capture_prompts: false,+ profile: None,+ },+ Some(dialect),+ )?;+ install_mcp::run_with_opencode_dialect(+ config,+ InstallMcpArgs {+ client: McpClient::OpenCode,+ server_url: Some(args.server_url.clone()),+ name: "ai-memory".to_string(),+ auth_token: args.auth_token.clone(),+ apply: false,+ config_file: None,+ session_aware: false,+ flavor: None,+ },+ Some(dialect),+ )?;+ println!();+ println!("{restart_note}");+ return Ok(());+ }println!("ai-memory install-hooks --agent {agent} --apply \\");if args.auth_token.is_some() {println!(" --server-url {} \\", args.server_url);@@ -642,6 +703,7 @@ mod tests {let tmp = tempfile::TempDir::new().unwrap();let args = SetupAgentArgs {agent: AgentChoice::Pi,+ opencode_dialect: None,to: tmp.path().join("hooks"),host_prefix: None,server_url: "http://127.0.0.1:49374".into(),@@ -658,6 +720,7 @@ mod tests {fn devin_setup_emits_script_hook_config() {let args = SetupAgentArgs {agent: AgentChoice::Devin,+ opencode_dialect: None,to: PathBuf::from("/container/hooks"),host_prefix: Some(PathBuf::from("/host/hooks")),server_url: "http://127.0.0.1:49374".into(),@@ -720,6 +783,7 @@ mod tests {let dest = tmp.path().join("dest");let args = SetupAgentArgs {agent: AgentChoice::Devin,+ opencode_dialect: None,to: dest.clone(),host_prefix: None,server_url: "http://127.0.0.1:49374".into(),diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rsindex b0a48076..7329587d 100644--- a/crates/ai-memory-cli/src/commands/show.rs+++ b/crates/ai-memory-cli/src/commands/show.rs@@ -143,7 +143,7 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {!args.no_scan,).await;- let harnesses = available_harnesses();+ let harnesses = available_harnesses(config);if args.json {print_json(&endpoint, &candidates, &harnesses)?;@@ -421,11 +421,13 @@ fn print_json(Ok(())}-pub(super) fn available_harnesses() -> Vec<RunHarnessChoice> {+pub(super) fn available_harnesses(config: &Config) -> Vec<RunHarnessChoice> {+ let child_env = crate::commands::run::EffectiveChildEnv::from_runtime(&config.runtime_env);+ let search = child_env.executable_search();RunHarnessChoice::value_variants().iter().copied()- .filter(|choice| crate::commands::run::harness_available(*choice))+ .filter(|choice| crate::commands::run::harness_available(*choice, search)).collect()}diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex fe6aec4a..e734ada0 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -6,6 +6,7 @@//! guard read `process.env` while the rest of the codebase used//! `getMergedEnv()`, masking the bug for weeks).+use std::ffi::OsString;use std::path::{Path, PathBuf};use std::sync::Arc;@@ -618,6 +619,18 @@ pub struct Config {pub runtime_env: RuntimeEnv,}+#[derive(Clone, Default)]+struct CapturedProcessEnv(Vec<(OsString, OsString)>);++impl std::fmt::Debug for CapturedProcessEnv {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("CapturedProcessEnv")+ .field("entries", &self.0.len())+ .finish()+ }+}+/// Environment-only values captured once by [`Config::load`].#[derive(Debug, Clone, Default)]pub struct RuntimeEnv {@@ -632,6 +645,7 @@ pub struct RuntimeEnv {scope_cwd: Option<String>,ignore_marker: bool,project_strategy: Option<String>,+ process_env: CapturedProcessEnv,claude_code_session_id: Option<String>,anthropic_api_key: Option<SecretString>,anthropic_oauth_token: Option<SecretString>,@@ -651,6 +665,7 @@ pub struct RuntimeEnv {impl RuntimeEnv {fn from_process() -> Self {let platform_home = dirs::home_dir();+ let process_env = CapturedProcessEnv(std::env::vars_os().collect());Self {data_dir: env_path("AI_MEMORY_DATA_DIR"),home_dir: resolve_operator_home(@@ -674,6 +689,7 @@ impl RuntimeEnv {// --project-strategy` bakes into the generated hook commands.// Consulted only when a marker does not pin one.project_strategy: env_string("AI_MEMORY_PROJECT_STRATEGY"),+ process_env,claude_code_session_id: env_string("CLAUDE_CODE_SESSION_ID"),anthropic_api_key: env_secret("ANTHROPIC_API_KEY"),// CLAUDE_CODE_OAUTH_TOKEN is what `claude setup-token` writes;@@ -732,6 +748,12 @@ impl RuntimeEnv {self.project_strategy.as_deref()}+ /// Complete process environment captured by the single config-read path.+ #[must_use]+ pub fn process_env(&self) -> &[(OsString, OsString)] {+ &self.process_env.0+ }+/// Claude Code lifecycle session id inherited by an stdio MCP subprocess.#[must_use]pub fn claude_code_session_id(&self) -> Option<&str> {diff --git a/crates/ai-memory-cli/tests/suite/external_capture_ts.rs b/crates/ai-memory-cli/tests/suite/external_capture_ts.rsindex ee7174fe..52781482 100644--- a/crates/ai-memory-cli/tests/suite/external_capture_ts.rs+++ b/crates/ai-memory-cli/tests/suite/external_capture_ts.rs@@ -54,12 +54,26 @@ mod slow_generated_runtime {/// The plugin exactly as `install-hooks` would write it, minus the three/// human-facing comment lines the non-`--apply` render prints first.fn render_opencode_plugin(home: &Path, server_url: &str) -> String {+ let bin = home.join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ let opencode = bin.join("opencode");+ std::fs::write(&opencode, "#!/bin/sh\nprintf '1.18.34\\n'\n").unwrap();+ let mut permissions = std::fs::metadata(&opencode).unwrap().permissions();+ permissions.set_mode(0o755);+ std::fs::set_permissions(&opencode, permissions).unwrap();+ }+ #[cfg(windows)]+ std::fs::write(bin.join("opencode.cmd"), "@echo off\r\necho 1.18.34\r\n").unwrap();let output = hermetic(BIN).args(["install-hooks", "--agent", "opencode", "--server-url"]).arg(server_url).env("HOME", home).env("USERPROFILE", home).env("AI_MEMORY_HOME", home)+ .env("PATH", bin).current_dir(home).output().expect("render opencode plugin");diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex 7ee7dfd7..e79f56a0 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -21,6 +21,7 @@ mod hook_payload;mod jail_toggles_e2e;mod marker_scope;mod message_e2e;+mod opencode_dialect;mod packaging;mod removal;mod repo_layout;diff --git a/crates/ai-memory-cli/tests/suite/opencode_dialect.rs b/crates/ai-memory-cli/tests/suite/opencode_dialect.rsnew file mode 100644index 00000000..18badd77--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/opencode_dialect.rs@@ -0,0 +1,213 @@+#![cfg(unix)]++use std::os::unix::fs::PermissionsExt as _;+use std::path::Path;+use std::process::Output;++use crate::e2e_support::hermetic;++const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++fn fake_opencode(home: &Path, version: &str) -> std::path::PathBuf {+ let bin = home.join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ let executable = bin.join("opencode");+ std::fs::write(+ &executable,+ format!("#!/bin/sh\nprintf '%s\\n' '{version}'\n"),+ )+ .unwrap();+ let mut permissions = std::fs::metadata(&executable).unwrap().permissions();+ permissions.set_mode(0o755);+ std::fs::set_permissions(executable, permissions).unwrap();+ bin+}++fn run(home: &Path, path: &Path, args: &[&str]) -> Output {+ hermetic(BIN)+ .args(args)+ .env("HOME", home)+ .env("USERPROFILE", home)+ .env("PATH", path)+ .output()+ .unwrap()+}++#[test]+fn generic_install_commands_select_the_probed_major() {+ for (version, dialect, plugin_marker, mcp_marker, setup_marker) in [+ (+ "1.18.34",+ "v1",+ "export default AiMemoryHooks",+ "\"enabled\": true",+ "plugins/ai-memory.ts",+ ),+ (+ "opencode v2.0.23 (build abc)",+ "v2",+ "const AiMemoryOpencode2: Plugin.Plugin",+ "\"servers\"",+ "plugins/ai-memory-opencode2.ts",+ ),+ ] {+ let home = tempfile::tempdir().unwrap();+ let path = fake_opencode(home.path(), version);+ let hooks = run(+ home.path(),+ &path,+ &[+ "install-hooks",+ "--agent",+ "opencode",+ "--server-url",+ "http://127.0.0.1:49374",+ ],+ );+ assert!(+ hooks.status.success(),+ "{}",+ String::from_utf8_lossy(&hooks.stderr)+ );+ assert!(String::from_utf8_lossy(&hooks.stdout).contains(plugin_marker));++ let mcp = run(+ home.path(),+ &path,+ &[+ "install-mcp",+ "--client",+ "opencode",+ "--server-url",+ "http://127.0.0.1:49374",+ ],+ );+ assert!(+ mcp.status.success(),+ "{}",+ String::from_utf8_lossy(&mcp.stderr)+ );+ assert!(String::from_utf8_lossy(&mcp.stdout).contains(mcp_marker));++ let setup = run(+ home.path(),+ Path::new(""),+ &[+ "setup-agent",+ "--agent",+ "opencode",+ "--opencode-dialect",+ dialect,+ "--to",+ "unused",+ ],+ );+ assert!(+ setup.status.success(),+ "{}",+ String::from_utf8_lossy(&setup.stderr)+ );+ assert!(String::from_utf8_lossy(&setup.stdout).contains(setup_marker));+ }+}++#[test]+fn explicit_v2_aliases_do_not_require_an_executable_probe() {+ let home = tempfile::tempdir().unwrap();+ for alias in ["opencode2", "opencode-v2", "open-code2"] {+ let output = run(+ home.path(),+ Path::new(""),+ &[+ "install-mcp",+ "--client",+ alias,+ "--server-url",+ "http://127.0.0.1:49374",+ ],+ );+ assert!(+ output.status.success(),+ "{alias}: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(String::from_utf8_lossy(&output.stdout).contains("\"servers\""));+ }+}++#[test]+fn setup_agent_alias_forces_v2_without_a_host_executable() {+ let home = tempfile::tempdir().unwrap();+ let output = run(+ home.path(),+ Path::new(""),+ &["setup-agent", "--agent", "opencode2", "--to", "unused"],+ );+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(stdout.contains("const AiMemoryOpencode2: Plugin.Plugin"));+ assert!(stdout.contains("\"servers\""));+}++#[test]+fn setup_agent_alias_rejects_a_conflicting_dialect_override() {+ let home = tempfile::tempdir().unwrap();+ let output = run(+ home.path(),+ Path::new(""),+ &[+ "setup-agent",+ "--agent",+ "opencode2",+ "--opencode-dialect",+ "v1",+ "--to",+ "unused",+ ],+ );+ assert!(!output.status.success());+ assert!(+ String::from_utf8_lossy(&output.stderr)+ .contains("cannot be combined with the force-V2 opencode2 compatibility alias")+ );+}++#[test]+fn setup_agent_generic_requires_an_explicit_dialect_without_probing() {+ let home = tempfile::tempdir().unwrap();+ let output = run(+ home.path(),+ Path::new(""),+ &["setup-agent", "--agent", "opencode", "--to", "unused"],+ );+ assert!(!output.status.success());+ assert!(String::from_utf8_lossy(&output.stderr).contains("requires --opencode-dialect v1|v2"));+}++#[test]+fn malformed_generic_version_fails_without_writing_config() {+ let home = tempfile::tempdir().unwrap();+ let path = fake_opencode(home.path(), "OpenCode latest");+ let config = home.path().join("opencode.json");+ let output = run(+ home.path(),+ &path,+ &[+ "install-mcp",+ "--client",+ "opencode",+ "--apply",+ "--config-file",+ config.to_str().unwrap(),+ ],+ );+ assert!(!output.status.success());+ assert!(!config.exists());+ assert!(+ String::from_utf8_lossy(&output.stderr).contains("could not determine the OpenCode major")+ );+}diff --git a/crates/ai-memory-cli/tests/suite/packaging.rs b/crates/ai-memory-cli/tests/suite/packaging.rsindex b5d44ac2..84d246cb 100644--- a/crates/ai-memory-cli/tests/suite/packaging.rs+++ b/crates/ai-memory-cli/tests/suite/packaging.rs@@ -817,6 +817,29 @@ fn dev_loop_is_wired_consistently() {}}+#[cfg(unix)]+#[test]+fn hook_installer_normalizes_the_open_code_alias() {+ let tmp = tempfile::tempdir().unwrap();+ let output = shell_script_command(&repo_root().join("scripts/install-hooks.sh"))+ .args(["--agent", "open-code", "--to"])+ .arg(tmp.path().join("hooks"))+ .env("HOME", tmp.path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "installer failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout.contains("install-hooks --agent opencode --apply"),+ "{stdout}"+ );+ assert!(!stdout.contains("unsupported agent"), "{stdout}");+}+#[cfg(unix)]fn installed_hook_names(agent_arg: &str, canonical_agent: &str, hooks: &[&str]) -> Vec<String> {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rsindex be5ba727..55b69c3a 100644--- a/crates/ai-memory-workstream/src/harness.rs+++ b/crates/ai-memory-workstream/src/harness.rs@@ -7,6 +7,112 @@ use ai_memory_core::AgentKind;use anyhow::{Result, anyhow, bail};use uuid::Uuid;+/// OpenCode's incompatible major-version contracts.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OpenCodeDialect {+ /// OpenCode 1 plugin, MCP, and transcript contracts.+ V1,+ /// OpenCode 2 plugin, MCP, and transcript contracts.+ V2,+}++impl OpenCodeDialect {+ /// Parse an OpenCode `--version` response without guessing an unknown major.+ pub fn parse_version_output(output: &str) -> Result<Self> {+ let mut versions = output+ .split_ascii_whitespace()+ .filter_map(parse_semver_major);+ let major = versions+ .next()+ .ok_or_else(|| anyhow!("OpenCode returned no strict semantic version"))?;+ if versions.next().is_some() {+ bail!("OpenCode returned multiple semantic versions");+ }+ match major {+ 1 => Ok(Self::V1),+ 2 => Ok(Self::V2),+ other => bail!(+ "OpenCode major {other} is not supported; upgrade ai-memory before using this OpenCode version"+ ),+ }+ }++ /// Numeric major used in persisted compatibility keys.+ #[must_use]+ pub const fn major(self) -> u8 {+ match self {+ Self::V1 => 1,+ Self::V2 => 2,+ }+ }++ /// Managed harness carrying this dialect through launch and transcript IO.+ #[must_use]+ pub const fn harness(self) -> ManagedHarness {+ match self {+ Self::V1 => ManagedHarness::OpenCode,+ Self::V2 => ManagedHarness::OpenCode2,+ }+ }+}++fn parse_semver_major(raw: &str) -> Option<u64> {+ let trimmed =+ raw.trim_matches(|character: char| matches!(character, '(' | ')' | '[' | ']' | ',' | ';'));+ let token = trimmed+ .strip_prefix('v')+ .or_else(|| trimmed.strip_prefix('V'))+ .unwrap_or(trimmed);+ let (without_build, build) = token+ .split_once('+')+ .map_or((token, None), |(core, build)| (core, Some(build)));+ if without_build.contains('+')+ || build.is_some_and(|value| !valid_semver_identifiers(value, false))+ {+ return None;+ }+ let (core, prerelease) = without_build+ .split_once('-')+ .map_or((without_build, None), |(core, prerelease)| {+ (core, Some(prerelease))+ });+ if prerelease.is_some_and(|value| !valid_semver_identifiers(value, true)) {+ return None;+ }+ let mut parts = core.split('.');+ let major = parts.next()?;+ let minor = parts.next()?;+ let patch = parts.next()?;+ if parts.next().is_some()+ || !valid_semver_number(major)+ || !valid_semver_number(minor)+ || !valid_semver_number(patch)+ {+ return None;+ }+ major.parse().ok()+}++fn valid_semver_number(value: &str) -> bool {+ !value.is_empty()+ && value.bytes().all(|byte| byte.is_ascii_digit())+ && (value == "0" || !value.starts_with('0'))+}++fn valid_semver_identifiers(value: &str, reject_leading_zero_numeric: bool) -> bool {+ !value.is_empty()+ && value.split('.').all(|identifier| {+ !identifier.is_empty()+ && identifier+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')+ && (!reject_leading_zero_numeric+ || !identifier.bytes().all(|byte| byte.is_ascii_digit())+ || identifier.len() == 1+ || !identifier.starts_with('0'))+ })+}+/// Harnesses with native-session and transcript adapters.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ManagedHarness {@@ -255,8 +361,6 @@ pub fn build_launch_plan_with_env(env_overrides: &[(String, String)],roots: Option<LaunchRoots<'_>>,) -> Result<LaunchPlan> {- let program = executable.unwrap_or_else(|| OsString::from(harness.executable()));- let mut args = native_args;let get = |name: &str| {env_overrides.iter()@@ -264,6 +368,27 @@ pub fn build_launch_plan_with_env(.map(|(_, value)| OsString::from(value)).or_else(|| std::env::var_os(name))};+ build_launch_plan_with_env_lookup(+ harness,+ executable,+ native_args,+ linked_session_id,+ get,+ roots,+ )+}++/// Build a launch plan from one caller-owned environment snapshot.+pub fn build_launch_plan_with_env_lookup(+ harness: ManagedHarness,+ executable: Option<OsString>,+ native_args: Vec<OsString>,+ linked_session_id: Option<&str>,+ get: impl Fn(&str) -> Option<OsString> + Copy,+ roots: Option<LaunchRoots<'_>>,+) -> Result<LaunchPlan> {+ let program = executable.unwrap_or_else(|| OsString::from(harness.executable()));+ let mut args = native_args;let session_dir = match harness {ManagedHarness::Pi | ManagedHarness::Omp => flag_path(&args, &["--session-dir"]),ManagedHarness::Crush => flag_path(&args, &["--data-dir", "-D"]),@@ -1717,6 +1842,35 @@ mod tests {));}+ #[test]+ fn opencode_version_parser_accepts_strict_and_decorated_versions() {+ for (output, expected) in [+ ("1.18.34", OpenCodeDialect::V1),+ ("v2.0.23", OpenCodeDialect::V2),+ ("OpenCode v2.0.23 (build abc)", OpenCodeDialect::V2),+ ("opencode 1.18.34-beta.1", OpenCodeDialect::V1),+ ] {+ assert_eq!(+ OpenCodeDialect::parse_version_output(output).unwrap(),+ expected+ );+ }+ }++ #[test]+ fn opencode_version_parser_rejects_malformed_and_unsupported_versions() {+ for output in ["2", "2.0", "latest", "version 2.x", "1.2.3 2.0.0"] {+ assert!(+ OpenCodeDialect::parse_version_output(output).is_err(),+ "{output}"+ );+ }+ let error = OpenCodeDialect::parse_version_output("3.0.0")+ .unwrap_err()+ .to_string();+ assert!(error.contains("major 3 is not supported"), "{error}");+ }+#[test]fn opencode2_shares_v1_session_contract_with_its_own_binary() {for name in ["opencode2", "opencode-v2", "open-code2"] {diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rsindex 1efb1373..fa2f2318 100644--- a/crates/ai-memory-workstream/src/lib.rs+++ b/crates/ai-memory-workstream/src/lib.rs@@ -6,9 +6,10 @@ mod repository;mod transcript;pub use harness::{- LaunchMode, LaunchPlan, LaunchRoots, ManagedHarness, allows_native_session_adoption,- apply_claude_true_yolo, apply_yolo, build_launch_plan, build_launch_plan_with_env, clean_path,- crush_data_dir, crush_global_config_path, env_dir_override, has_native_session_selector,+ LaunchMode, LaunchPlan, LaunchRoots, ManagedHarness, OpenCodeDialect,+ allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_launch_plan,+ build_launch_plan_with_env, build_launch_plan_with_env_lookup, clean_path, crush_data_dir,+ crush_global_config_path, env_dir_override, has_native_session_selector,kiro_explicit_session_id, kiro_selects_non_default_engine, kiro_selects_v2_engine,kiro_selects_v3_engine, omp_agent_dir, omp_profile_flag, omp_profile_flag_env,store_override_vars,diff --git a/docs/install.md b/docs/install.mdindex eabe4231..4d16cac3 100644--- a/docs/install.md+++ b/docs/install.md@@ -1239,26 +1239,28 @@ No first-party `install-mcp` client and no managed workstream### OpenCode```bash-docker run --rm akitaonrails/ai-memory:latest \- install-mcp --client opencode \+# Host-side commands probe the installed executable and select V1/V2.+ai-memory install-mcp --client opencode --apply \--server-url "http://homelab:49374/mcp" \--auth-token "$TOKEN"--# Plugin — write to ~/.config/opencode/plugins/ai-memory.ts.-# If you have the local wrapper installed, prefer `--apply`:ai-memory install-hooks --agent opencode --apply \--server-url "http://homelab:49374" \--auth-token "$TOKEN"-# Docker-only preview path; redirect only if you want to write the file yourself:+# Docker cannot inspect the host executable. Generate V1 artifacts explicitly:docker run --rm akitaonrails/ai-memory:latest \- install-hooks --agent opencode \+ setup-agent --agent opencode --opencode-dialect v1 --to /tmp/unused \--server-url "http://homelab:49374" \--auth-token "$TOKEN"```Restart OpenCode after installing or changing the plugin; plugins are-loaded at startup.+loaded at startup. The generic `opencode` client/agent spelling runs the installed+`opencode --version` directly, accepts only major 1 or 2, and selects the matching+plugin and MCP schema. Under `ai-memory run`, executable lookup, the version probe,+and launch share the same captured environment plus `--env` / `--env-file`+overrides. Malformed output, a timeout, or an unsupported future major fails with+an actionable error instead of guessing.### OpenCode 2 (beta)@@ -1278,7 +1280,8 @@ it or publish a baton.Assistant text stays opt-in, as for Claude Code and Codex: set`capture_assistant = true` on the server and install with-`ai-memory install-hooks --agent opencode2 --capture-assistant --apply`. The+`ai-memory install-hooks --agent opencode --capture-assistant --apply`; the+generic spelling verifies that the installed executable is V2 first. Theplugin hands the last completed text to the native hook, which sanitizes andcaps it before it reaches the spool or the wire; the excerpt then rides in thenext session's automatic handoff. A bare re-apply preserves the opt-in.@@ -1287,34 +1290,32 @@ For a commented `opencode.jsonc`, preview `install-mcp --client opencode2` andmerge the entry into the existing `mcp.servers` object by hand: the apply pathwrites strict JSON.-The 2.0 beta installs side by side as `opencode2` and shares v1's config-dir and session store, but its MCP schema and plugin API changed. Wire it-with the `opencode2` client/agent names:+The `opencode2`, `opencode-v2`, and `open-code2` spellings remain compatibility+aliases that force the V2 contracts without probing. They share V1's config dir+and session store. Prefer the generic `opencode` spelling for normal installs:```bash-docker run --rm akitaonrails/ai-memory:latest \- install-mcp --client opencode2 \- --server-url "http://homelab:49374/mcp" \+# Host-side generic commands auto-detect V2; compatibility aliases force it.+ai-memory install-hooks --agent opencode2 --apply \+ --server-url "http://homelab:49374" \--auth-token "$TOKEN"-# Plugin — write to ~/.config/opencode/plugins/ai-memory-opencode2.ts.-# If you have the local wrapper installed, prefer `--apply`:-ai-memory install-hooks --agent opencode2 --apply \+# Docker cannot inspect the host executable. Generate V2 artifacts explicitly:+docker run --rm akitaonrails/ai-memory:latest \+ setup-agent --agent opencode --opencode-dialect v2 --to /tmp/unused \--server-url "http://homelab:49374" \--auth-token "$TOKEN"```-V2 nests servers under `mcp.servers` (no `enabled` field), so the v1-(`mcp`) and v2 (`mcp.servers`) entries coexist in the one-`~/.config/opencode/opencode.json(c)` file — the beta explicitly supports-this mixed nesting, so keep both entries and do not "convert" the file by-removing the v1 one-(see [Migrate from V1](https://opencode.ai/v2/docs/migrate-v1)). `ai-memory run opencode2`-resumes the same native sessions as `ai-memory run opencode` through the-`opencode2` binary. Both plugins share the one auto-loaded dir while the-beta is side-by-side; a host may warn about its sibling's file (the two-plugin APIs are incompatible) — that warning is benign, and `uninstall`-removes each file only on its own ownership markers.+V2 nests servers under `mcp.servers` and uses a different plugin API. A+successful `--apply` removes the incompatible sibling plugin only when its+exact ai-memory ownership markers match. It likewise migrates an alternate MCP+entry only when its endpoint and shape prove ai-memory ownership. Hook and MCP+installation reuse its endpoint and bearer across a major transition; conflicting+owned V1/V2 entries fail for explicit resolution, while user-authored entries are+preserved. Repeating either install is+byte-idempotent, and `uninstall` continues to recognize both historical files+and MCP locations.> **Back up `~/.local/share/opencode` before running the beta against> your real data.** The two binaries share the one `opencode.db` file anddiff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 1f91230d..e6464e5e 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -252,16 +252,22 @@ checkout themselves.With no harness name, `ai-memory run` inspects checkout-local sessions forClaude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, and both Kiro-CLI engines. For an empty workstream it resumes+CLI engines. Before scanning OpenCode sessions, it probes the exact `opencode`+executable once and uses that resolved major for discovery, launch, auto-wire,+and transcript import. Executable lookup, the version probe, and the child launch+share one captured environment with `--env` / `--env-file` overlays, including+case-insensitive `PATH`/`Path` replacement on Windows. A missing, malformed,+timed-out, or unsupported OpenCode+probe skips only OpenCode; discovery continues with every other available+harness. For an empty workstream 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 fromanother harness merely because that file has a later timestamp. Kiro's v2 andv3 candidates share one server agent identity, but the selected native engineflavor remains exact. OMP, Grok, and Antigravity remain available explicitly-but are not in the automatic pool. OpenCode 2 is likewise explicit-only-(`ai-memory run opencode2`): it shares v1's session store, so listing both-would duplicate every candidate.+but are not in the automatic pool. OpenCode's resolved major contributes one+adapter to the pool, so shared V1/V2 storage never duplicates a candidate.OpenCode 2 sessions run inside a shared background service, so its plugincannot see a managed run's environment the way in-process plugins do. Managed@@ -381,8 +387,8 @@ is labelled completed evidence and must never be replayed as a pending call.|---|---|---|---|| Claude Code | generated `--session-id` | `--resume <id>` | `~/.claude/projects/**/*.jsonl` || Codex | native default creation | `resume <id>` | `~/.codex/sessions/**/rollout-*.jsonl` |-| OpenCode | native default creation | `--session <id>` | `~/.local/share/opencode/opencode.db` opened read-only |-| OpenCode 2 beta | native default creation | `--session <id>` | same `opencode.db` as v1 (the beta channel keeps v1's filename; the beta adds `session_v2`/`session_message` tables beside v1's); launched via the `opencode2` binary |+| OpenCode V1 | native default creation | `--session <id>` | `~/.local/share/opencode/opencode.db` opened read-only; selected when the exact launch executable reports major 1 |+| OpenCode V2 | native default creation | `--session <id>` | same `opencode.db` filename, using the `session_v2`/`session_message` tables; selected when the exact launch executable reports major 2 || Pi | generated `--session-id` | `--session <id>` | `~/.pi/agent/sessions/**/*.jsonl` || Crush | native default creation | `--session <id>` | `<data dir>/crush.db` opened read-only: `options.data_directory` from Crush's JSON configs, else the closest `.crush` up to the git worktree root, else `<cwd>/.crush` || Kimi Code | native default creation | `--session <id>` | `$KIMI_CODE_HOME/sessions/*/*/agents/main/wire.jsonl` |diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 371667ac..704aa10b 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -17,7 +17,17 @@> --http-stateful` to restore rmcp's session mode.This page documents how to register ai-memory as an MCP server with-agent CLIs beyond the README quick start.+agent CLIs beyond the README quick start. For OpenCode, the generic+`install-mcp --client opencode` command probes `opencode --version` and writes+the matching V1 direct `mcp` or V2 nested `mcp.servers` entry. Strict semantic+major 1 and 2 outputs are accepted; malformed, timed-out, and future-major+probes fail rather than guessing. During a V1/V2 transition, hook and MCP+installers reuse an ownership-verified endpoint and bearer from either known+schema; conflicting generated entries fail for explicit resolution, and custom+entries are preserved. The `opencode2`, `opencode-v2`, and `open-code2`+spellings remain force-V2 compatibility aliases. A Docker+container cannot inspect the host executable; use `setup-agent --agent opencode+--opencode-dialect v1|v2` there to print the selected plugin and MCP artifacts.The hook-capable clients in the [README Support Matrix](../README.md#support-matrix)have automatic capture integrations (host-native commands for supported localdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 2218ad9f..f469e729 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -61,6 +61,7 @@ boundary not yet built.| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` || 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG || 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI |+| 11g | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label || 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG || 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_attached_background_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050); `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_attached_background_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous || 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet |diff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex bbd71ae9..b7987eaa 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -14,8 +14,8 @@| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. `SessionEnd` is wired since Codex CLI 0.145.0 (openai/codex#33895), so finished sessions get an automatic end-of-session summary/handoff; on older Codex the event is inert and `ai-memory finalize-session --agent codex` is the fallback. Managed runs (`ai-memory run codex`) recover when Codex's shared daemon reports a stale run id, provided exactly one live run matches the authorized project, checkout, and operator; ambiguous matches fail closed. `--no-daemon` remains available as an isolation and diagnostic option (see [`docs/managed-workstreams.md`](managed-workstreams.md)). 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's `Stop` payload carries `last_assistant_message`, same as Claude Code. || 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; an interactive session launched with `ai-memory run command-code` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `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. |-| OpenCode 2 (`opencode2` beta) | Supported | V2 `mcp.servers` remote MCP config + generated TypeScript plugin (`ai-memory-opencode2.ts`) for the OpenCode 2.0.10+ event API, checked against 2.0.14; shares v1's config dir, session store, and agent kind. Completed root turns checkpoint the session page and baton without ending the shared service's session; MCP calls route by the native `_meta` session id, so concurrent sessions in different projects stay isolated. `--capture-assistant` is supported (double opt-in). Managed runs launch, resume, and import; ledger-delta acknowledgement is limited by the shared background service (see managed-workstreams notes). |+| OpenCode (V1/V2 auto-detected) | Supported | Host-side generic `opencode` commands probe the exact executable and select the V1 direct MCP/function-plugin/transcript contracts or V2 nested `mcp.servers`/`{ id, setup }` plugin/`session_v2` contracts. The result is reused through managed discovery, launch, auto-wire, and transcript import; an automatic run skips OpenCode when probing fails but continues other harness discovery. Container-oriented `setup-agent` requires `--opencode-dialect v1|v2`. Generated sibling plugins and alternate MCP entries are migrated only when ai-memory ownership is proven. |+| OpenCode V2 compatibility aliases | Supported | `opencode2`, `opencode-v2`, and `open-code2` force V2 compatibility without probing. V2 completed root turns checkpoint the session page and baton without ending the shared service's session; MCP calls route by the native `_meta` session id, and `--capture-assistant` is supported (double opt-in). || Cursor | Supported | MCP config + lifecycle hooks. || Gemini CLI | Supported | MCP config + lifecycle hooks. || 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. |diff --git a/docs/usage.md b/docs/usage.mdindex bc517da7..48cdc8ea 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -356,8 +356,10 @@ Client cleanup hints:under `$KIRO_HOME` when set) for stale ai-memory entries.- OpenCode, OpenClaw, and OMP: check MCP config and plugin/extension directories;move old memory plugins to a disabled/quarantine directory before deleting.- For the OpenCode 2 beta the plugin file is `ai-memory-opencode2.ts` and the- MCP entry lives under `mcp.servers` in the same `opencode.json(c)`.+ OpenCode uses `ai-memory.ts` with direct `mcp` on V1 and+ `ai-memory-opencode2.ts` with `mcp.servers` on V2; the generic installer+ detects the installed major and removes only an incompatible sibling proven+ to be generated by ai-memory.- VS Code Copilot, Claude Desktop, and Zed: these are MCP-only, so confirmwhether the old tool was providing capture hooks elsewhere. Zed's MCPentries live under `context_servers` in its user `settings.json`.diff --git a/docs/windows.md b/docs/windows.mdindex 30dd74ff..4e49d98d 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -677,9 +677,10 @@ Windows agent builds.- MCP over HTTP should be less path-sensitive than hooks, but`install-mcp --apply` still writes to a client-specific config file;confirm the agent actually loads it.-- OpenClaw, OpenCode (v1 `ai-memory.ts` plus the 2 beta's- `ai-memory-opencode2.ts`), OMP / Oh My Pi, and Pi use generated TypeScript- integrations rather than the shell hook bundle, so their Windows+- OpenClaw, OpenCode (V1 `ai-memory.ts` or V2+ `ai-memory-opencode2.ts`, selected from the resolved executable major), OMP /+ Oh My Pi, and Pi use generated TypeScript integrations rather than the shell+ hook bundle, so their Windowsbehavior depends on the host runtime loading those files correctly.Pi's generated extension also bridges MCP tools because Pi has no native`mcp.json` install surface.diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.shindex cd3d6f14..994edc89 100755--- a/scripts/install-hooks.sh+++ b/scripts/install-hooks.sh@@ -49,6 +49,7 @@ case "$AGENT" inclaude-code|codex|command-code|cursor|gemini-cli|kimi-code|kiro-cli|antigravity-cli|grok|opencode|opencode2|openclaw|omp|pi|oh-my-pi) ;;commandcode|cmdc|cmd) AGENT="command-code" ;;kiro) AGENT="kiro-cli" ;;+ open-code) AGENT="opencode" ;;opencode-v2|open-code2) AGENT="opencode2" ;;*)echo "unsupported agent: $AGENT (expected claude-code | codex | command-code | cursor | gemini-cli | kimi-code | kiro-cli | antigravity-cli | grok | opencode | opencode2 | openclaw | omp | pi | oh-my-pi)" >&2@@ -67,7 +68,7 @@ fiif [[ "$AGENT" == "opencode" ]]; thenecho "OpenCode uses a generated TypeScript plugin, not shell hook scripts."echo "Run: ai-memory install-hooks --agent opencode --apply"- echo "Then restart OpenCode so it loads ~/.config/opencode/plugins/ai-memory.ts."+ echo "Then restart OpenCode; ai-memory detects V1/V2 and prints the installed plugin path."exit 0fi