Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(setup): probe the OpenCode major instead of always wiring V1
4nrry821d3a9d82f4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 59954396..e443f212 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,16 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Fixed+- Fixed `ai-memory setup` wiring OpenCode 2 with OpenCode 1 artifacts. A+ named `--agent opencode` (or `open-code`), or an OpenCode found by the+ session store both majors share, always got the V1 function plugin+ `plugins/ai-memory.ts` and a direct `mcp.ai-memory` entry, which OpenCode+ 2 does not load. `setup` now runs `opencode --version` once, as+ `install-mcp` and `install-hooks` already did for the generic spelling, and+ wires the V2 `{ id, setup }` plugin and nested `mcp.servers` entry when it+ reports major 2. A failed probe writes no OpenCode wiring and is reported+ as a setup problem; `--agent opencode2` still forces V2 without probing.## [3.1.0] - 2026-10-16### Addeddiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex e2eac8e2..eebfe292 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1972,8 +1972,9 @@ pub struct SetupArgs {pub yes: bool,/// Wire this agent instead of the detected ones. Repeat for several./// Detection looks for each harness's session store or MCP config under- /// your home; OpenCode 2 and the Kiro CLI v3 engine are only wired when- /// named here.+ /// your home. A detected or named `opencode` is wired for the major+ /// `opencode --version` reports (`opencode2` forces V2 without probing);+ /// the Kiro CLI v3 engine is only wired when named here.#[arg(long = "agent", value_enum)]pub agents: Vec<AgentChoice>,/// Do not install or start a user service; use this when the serverdiff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsindex 4db7a48c..58fe9141 100644--- a/crates/ai-memory-cli/src/commands/setup.rs+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -68,7 +68,8 @@ const PLAN_FORMAT: u32 = 1;/// cannot tell them apart: OpenCode 2 shares OpenCode's, and the Kiro CLI v3/// engine's store contains the v2 engine's. Wiring both would write two/// dialects into one config, so only the stable one is detected; the other is-/// wired when named with `--agent`.+/// wired when named with `--agent`. A detected OpenCode still gets the major+/// its version probe reports ([`opencode_dialect`]).const EXPLICIT_ONLY: &[ManagedHarness] = &[ManagedHarness::OpenCode2, ManagedHarness::KiroV3];/// What `setup` will do.@@ -185,13 +186,21 @@ fn skills_for(agent: AgentChoice) -> InstallSkillsAgent {}}-/// The OpenCode major version an agent names outright, so neither installer-/// probes `opencode --version` and picks one dialect for both.-fn opencode_dialect(agent: AgentChoice) -> Option<OpenCodeDialect> {+/// The OpenCode major version to wire, resolved once so both installers use+/// the same dialect. The `opencode2` alias names V2 outright; the generic+/// `opencode` (named, or detected by the session store both majors share)+/// probes `opencode --version` the way `install-mcp` and `install-hooks` do+/// by hand, and a failed probe is an error rather than a guess.+fn opencode_dialect(+ agent: AgentChoice,+ env: &super::run::EffectiveChildEnv,+) -> Result<Option<OpenCodeDialect>> {match agent {- AgentChoice::OpenCode => Some(OpenCodeDialect::V1),- AgentChoice::OpenCode2 => Some(OpenCodeDialect::V2),- _ => None,+ AgentChoice::OpenCode => {+ super::opencode_dialect::resolve_generic(None, env).map(|found| Some(found.dialect))+ }+ AgentChoice::OpenCode2 => Ok(Some(OpenCodeDialect::V2)),+ _ => Ok(None),}}@@ -956,7 +965,36 @@ fn wire_agent();return problems;}- let dialect = opencode_dialect(plan.agent);+ let child_env = super::run::EffectiveChildEnv::from_runtime(&config.runtime_env);+ match opencode_dialect(plan.agent, &child_env) {+ Ok(dialect) => wire_mcp_and_hooks(config, plan, dialect, &mut problems),+ // A guessed major writes a plugin and MCP shape the installed OpenCode+ // ignores without an error, so nothing is written instead.+ Err(error) => problems.push(format!("skipped install-mcp and install-hooks: {error:#}")),+ }+ let skills_key = format!("{:?}", plan.skills);+ if skills_done.insert(skills_key) {+ let args = InstallSkillsArgs {+ scope: InstallSkillsScope::Global,+ agent: plan.skills,+ target_dir: None,+ print: false,+ force: false,+ };+ if let Err(error) = install_skills::run(config, args) {+ problems.push(format!("install-skills: {error:#}"));+ }+ }+ problems+}++/// `install-mcp` then `install-hooks` for one agent, in one OpenCode dialect.+fn wire_mcp_and_hooks(+ config: &Config,+ plan: &AgentPlan,+ dialect: Option<OpenCodeDialect>,+ problems: &mut Vec<String>,+) {if let Some(client) = plan.mcp {if install_mcp::existing_entry_is_session_aware(client, None, ENTRY_NAME) {println!("mcp: keeping the existing session-aware entry");@@ -1000,20 +1038,6 @@ fn wire_agent({problems.push(format!("install-hooks: {error:#}"));}- let skills_key = format!("{:?}", plan.skills);- if skills_done.insert(skills_key) {- let args = InstallSkillsArgs {- scope: InstallSkillsScope::Global,- agent: plan.skills,- target_dir: None,- print: false,- force: false,- };- if let Err(error) = install_skills::run(config, args) {- problems.push(format!("install-skills: {error:#}"));- }- }- problems}/// `/healthz`, `memory_status` over MCP, and `doctor`; none of them writes a@@ -1553,6 +1577,42 @@ mod tests {);}+ /// Generic `opencode` takes the probed major; the `opencode2` alias and+ /// other agents never run a probe, so an empty `PATH` cannot fail them.+ #[cfg(unix)]+ #[test]+ fn opencode_dialect_probes_only_the_generic_spelling() {+ use std::os::unix::fs::PermissionsExt as _;++ let empty = super::super::run::EffectiveChildEnv::for_tests([("PATH", "")]);+ assert_eq!(+ opencode_dialect(AgentChoice::OpenCode2, &empty).unwrap(),+ Some(OpenCodeDialect::V2)+ );+ assert_eq!(opencode_dialect(AgentChoice::Codex, &empty).unwrap(), None);+ let error = format!(+ "{:#}",+ opencode_dialect(AgentChoice::OpenCode, &empty).unwrap_err()+ );+ assert!(error.contains("was not found"), "{error}");++ for (version, expected) in [+ ("2.0.31", OpenCodeDialect::V2),+ ("1.18.34", OpenCodeDialect::V1),+ ] {+ let bin = tempfile::tempdir().unwrap();+ let opencode = bin.path().join("opencode");+ std::fs::write(&opencode, format!("#!/bin/sh\necho '{version}'\n")).unwrap();+ std::fs::set_permissions(&opencode, std::fs::Permissions::from_mode(0o755)).unwrap();+ let env = super::super::run::EffectiveChildEnv::for_tests([("PATH", bin.path())]);+ assert_eq!(+ opencode_dialect(AgentChoice::OpenCode, &env).unwrap(),+ Some(expected),+ "{version}"+ );+ }+ }+#[test]fn named_agents_are_deduplicated_in_order() {assert_eq!(diff --git a/crates/ai-memory-cli/tests/suite/setup_e2e.rs b/crates/ai-memory-cli/tests/suite/setup_e2e.rsindex 712906fa..81a243a0 100644--- a/crates/ai-memory-cli/tests/suite/setup_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/setup_e2e.rs@@ -17,8 +17,6 @@ const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");/// A temp root holding the operator's home and a directory of fake tools.struct Sandbox {_tmp: tempfile::TempDir,- // Only the Linux service test reads it.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]root: PathBuf,home: PathBuf,}@@ -173,6 +171,104 @@ fn setup_plan_json_prints_the_plan_and_changes_nothing() {assert_eq!(sandbox.snapshot(), before, "a refused setup wrote");}+/// The generic `opencode` agent, named or found by the session store both+/// majors share, is wired in the major `opencode --version` reports: OpenCode+/// 2 gets the `{ id, setup }` plugin and the nested `mcp.servers` entry, not+/// the V1 function plugin and direct `mcp` entry. No server answers here, so+/// each run still exits non-zero on its self-check.+#[test]+fn setup_wires_the_opencode_major_the_version_probe_reports() {+ use std::os::unix::fs::PermissionsExt as _;++ for (version, named, plugin, stale, v2) in [+ (+ "2.0.31",+ true,+ "ai-memory-opencode2.ts",+ "ai-memory.ts",+ true,+ ),+ (+ "2.0.31",+ false,+ "ai-memory-opencode2.ts",+ "ai-memory.ts",+ true,+ ),+ (+ "1.18.34",+ true,+ "ai-memory.ts",+ "ai-memory-opencode2.ts",+ false,+ ),+ ] {+ let sandbox = Sandbox::new();+ let bin = sandbox.root.join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ let opencode = bin.join("opencode");+ std::fs::write(&opencode, format!("#!/bin/sh\necho '{version}'\n")).unwrap();+ std::fs::set_permissions(&opencode, std::fs::Permissions::from_mode(0o755)).unwrap();+ std::fs::create_dir_all(sandbox.home.join(".local/share/opencode")).unwrap();+ let mut cmd = sandbox.cmd(Some(crate::e2e_support::free_port()));+ cmd.env("PATH", &bin)+ .args(["setup", "--yes", "--no-service"]);+ if named {+ cmd.args(["--agent", "opencode"]);+ }+ let out = cmd.output().unwrap();+ let case = format!("{version} named={named}\n{}", text(&out));+ assert!(+ String::from_utf8_lossy(&out.stdout).contains("== open-code"),+ "{case}"+ );+ assert!(+ !String::from_utf8_lossy(&out.stderr).contains("problem: open-code"),+ "{case}"+ );++ let config = sandbox.home.join(".config/opencode");+ assert!(config.join("plugins").join(plugin).is_file(), "{case}");+ assert!(!config.join("plugins").join(stale).exists(), "{case}");+ let mcp: serde_json::Value =+ serde_json::from_slice(&std::fs::read(config.join("opencode.json")).unwrap()).unwrap();+ assert_eq!(+ mcp["mcp"]["servers"]["ai-memory"].is_object(),+ v2,+ "{case}\n{mcp}"+ );+ assert_eq!(mcp["mcp"]["ai-memory"].is_object(), !v2, "{case}\n{mcp}");+ }+}++/// With no `opencode` to probe, setup does not guess a major: it writes no+/// OpenCode plugin or MCP entry and names the problem.+#[test]+fn setup_without_an_opencode_to_probe_writes_no_opencode_wiring() {+ let sandbox = Sandbox::new();+ let empty = sandbox.root.join("empty-path");+ std::fs::create_dir_all(&empty).unwrap();+ let out = sandbox+ .cmd(Some(crate::e2e_support::free_port()))+ .env("PATH", &empty)+ .args(["setup", "--yes", "--no-service", "--agent", "opencode"])+ .output()+ .unwrap();+ assert!(!out.status.success(), "{}", text(&out));+ let stderr = String::from_utf8_lossy(&out.stderr);+ assert!(+ stderr.contains("problem: open-code: skipped install-mcp and install-hooks")+ && stderr.contains("was not found"),+ "{}",+ text(&out)+ );+ assert!(+ !sandbox.home.join(".config/opencode").exists(),+ "{}",+ text(&out)+ );+}+/// `setup --web` through the binary: the printed address serves the page and/// plan, a foreign Host is refused, Apply runs `setup --yes --agent/// claude-code` (which writes Claude Code's hooks), and Finish stops thediff --git a/docs/install.md b/docs/install.mdindex 3140f873..b9671264 100644--- a/docs/install.md+++ b/docs/install.md@@ -158,9 +158,14 @@ runs, in order, the commands a native install otherwise needs one by one:says what it was found by (its session store, its MCP config, or for Museits directory), then lists the other agents `--agent` accepts. Cursor,Gemini CLI, Droid and the other agents with no store to look for are- wired by naming them. OpenCode 2 and the Kiro CLI v3 engine share a store- with OpenCode and Kiro CLI, so they are wired only when named, for example- `--agent opencode2`.+ wired by naming them. OpenCode 1 and 2 share one session store, so a+ detected or named `opencode` runs `opencode --version` once and wires the+ plugin and MCP entry for the major it reports, as `install-mcp --client+ opencode` and `install-hooks --agent opencode` do by hand. When that probe+ fails (no `opencode` on `PATH`, a timeout, or unreadable output), `setup`+ writes no OpenCode plugin or MCP entry and reports the problem; `--agent+ opencode2` forces V2 without probing. The Kiro CLI v3 engine shares a+ store with Kiro CLI, so it is wired only when named.4. A self-check that writes nothing: `GET /healthz`, a `memory_status` callover MCP with the install's credential, and `doctor`. When Codex was wired,`setup` also asks Codex whether it will run the ai-memory hooks. If Codex