Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(qwen): Added first-party Qwen Code support
Lucas Saavedra Vaz736b98b4931e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f30234a..108330e2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,16 @@ version in [`docs/changelog/`](docs/changelog/):### Added+- Added first-party Qwen Code lifecycle and MCP support. `install-mcp --client+ qwen-code` (aliases `qwen`, `qwencode`) writes a Streamable HTTP `httpUrl`+ entry into `~/.qwen/settings.json`; a token-file install gets a stdio+ `mcp-bridge` instead of embedding the bearer. `install-hooks --agent+ qwen-code` merges ten Claude-shaped events (including `PostToolUseFailure`+ and subagent start/stop) as native `ai-memory hook` commands with no script+ bundle. `SessionStart` injects the prior handoff as+ `hookSpecificOutput.additionalContext`; Qwen's own `SessionEnd` closes the+ session. Capture exclusions cover Qwen's Gemini-like tools. `setup` detects+ `~/.qwen`. There is no `ai-memory run qwen` adapter.- Added zero-LLM substring retrieval for unspaced Han, Kana, and Hangul text.Pages and observations gain transactionally maintained derived unigram/bigramFTS indexes; existing unicode61 search and ranking remain unchanged fordiff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex 7c965bf4..e9dc5df3 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -33,7 +33,7 @@ takes two commands, and neither needs root or administrator rights.`<self>` is one of `claude-code`, `codex`, `opencode`, `opencode2`,`gemini-cli`, `cursor`, `kimi-code`, `kiro-cli`, `grok`, `copilot-cli`,`antigravity-cli`, `command-code`, `devin`, `droid`, `muse`, `omp`, `pi`,- `openclaw`+ `openclaw`, `qwen-code`(`ai-memory setup --help` lists every value). Repeat `--agent` to wireseveral harnesses. Without `--agent`, `setup` wires every harness it findsunder the home directory.diff --git a/README.md b/README.mdindex 2218cd2f..cd90a5b8 100644--- a/README.md+++ b/README.md@@ -159,6 +159,7 @@ caveats is in [`docs/support-matrix.md`](docs/support-matrix.md).| Meta Muse Code | Supported || CodeBuddy Code | Hooks-only || IBM Bob | Supported |+| Qwen Code | Supported || VS Code Copilot | MCP-only || Zed | MCP-only || DeepSeek Harness (DSH) | Hooks + MCP |@@ -392,7 +393,7 @@ docker run -d --name ai-memory \# 3. Wire your agent CLI in two commands. The wrapper takes care of# mounts and each client's config-path detection. Re-run with# `--agent codex`, `--agent command-code`, `--agent devin`, `--agent opencode`, `--agent opencode2`, `--agent gemini-cli`,-# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent copilot-cli`, `--agent droid`, `--agent muse`, `--agent cline`, `--agent omp`,+# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent copilot-cli`, `--agent droid`, `--agent muse`, `--agent cline`, `--agent qwen-code`, `--agent omp`,# `--agent oh-my-pi`, `--client cursor`,# `--client gemini-cli`, `--client grok`, `--client kiro-cli`,# `--client cline`, `--client freebuff`, etc.diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 0e0a92c7..16ee7854 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -2532,6 +2532,14 @@ pub enum AgentChoice {/// handoff injection does not; accept the handoff through MCP instead.#[value(alias = "cline-cli")]Cline,+ /// Qwen Code (`qwen`) — lifecycle hooks merged into the `hooks` key of+ /// `~/.qwen/settings.json`. Qwen sends Claude Code-shaped hook payloads+ /// on stdin, so each entry runs ai-memory's native `hook` command+ /// directly; there is no script bundle. SessionStart stdout+ /// (`hookSpecificOutput.additionalContext`) carries the handoff, and+ /// Qwen's own `SessionEnd` closes the session.+ #[value(name = "qwen-code", alias = "qwen", alias = "qwencode")]+ QwenCode,}impl AgentChoice {@@ -2569,6 +2577,7 @@ impl AgentChoice {Self::IbmBob => AgentKind::IbmBob,Self::Dsh => AgentKind::Dsh,Self::Cline => AgentKind::Cline,+ Self::QwenCode => AgentKind::QwenCode,}}@@ -2592,7 +2601,8 @@ impl AgentChoice {| Self::Muse| Self::CodeBuddy| Self::IbmBob- | Self::Cline => None,+ | Self::Cline+ | Self::QwenCode => None,_ => Some(self.kind().as_str()),}}@@ -2787,6 +2797,13 @@ pub enum McpClient {/// plain-text `SessionStart` handoff delivery.#[value(name = "ibm-bob", alias = "bob")]IbmBob,+ /// Qwen Code — `~/.qwen/settings.json`, servers under the root+ /// `mcpServers` map with `httpUrl` (streamable HTTP; the plain `url`+ /// key is legacy SSE). Qwen expands `$NAME` and `${NAME}` in every+ /// string. Pair with `install-hooks --agent qwen-code` for lifecycle+ /// capture and `SessionStart` handoff delivery.+ #[value(name = "qwen-code", alias = "qwen", alias = "qwencode")]+ QwenCode,/// GitHub Copilot CLI — `$COPILOT_HOME/mcp-config.json` (default/// `~/.copilot/mcp-config.json`), servers under the root `mcpServers` map/// with `type: "http"` + `url` + optional `headers` (#1040). Pair with@@ -4903,6 +4920,27 @@ mod tests {}}+ #[test]+ fn qwen_code_install_hooks_and_mcp_parse_with_both_aliases() {+ for alias in ["qwen-code", "qwen", "qwencode"] {+ let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", alias])+ .unwrap_or_else(|error| panic!("{alias}: {error}"));+ let Command::InstallHooks(args) = hooks.command else {+ panic!("expected install-hooks");+ };+ assert_eq!(args.agent, AgentChoice::QwenCode);+ assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::QwenCode);+ assert_eq!(args.agent.script_hook_subdir(), None);++ let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", alias])+ .unwrap_or_else(|error| panic!("{alias}: {error}"));+ let Command::InstallMcp(args) = mcp.command else {+ panic!("expected install-mcp");+ };+ assert_eq!(args.client, McpClient::QwenCode);+ }+ }+#[test]fn ibm_bob_install_hooks_and_mcp_parse_with_both_aliases() {for alias in ["ibm-bob", "bob"] {diff --git a/crates/ai-memory-cli/src/commands/backup_agents.rs b/crates/ai-memory-cli/src/commands/backup_agents.rsindex 2dda119b..ccb786de 100644--- a/crates/ai-memory-cli/src/commands/backup_agents.rs+++ b/crates/ai-memory-cli/src/commands/backup_agents.rs@@ -442,6 +442,42 @@ pub fn discover_assets(}}+ // 4b. Qwen Code+ if filter_agent(AgentKind::QwenCode) {+ let qwen_dir = home.join(".qwen");+ if want_global {+ push_if_file(+ &mut assets,+ AgentKind::QwenCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ qwen_dir.join("settings.json"),+ ".qwen/settings.json",+ "qwen/settings.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::QwenCode,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &qwen_dir.join("skills"),+ ".qwen/skills",+ "qwen/skills",+ )?;+ }+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::QwenCode,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join("QWEN.md"),+ "QWEN.md",+ "project/QWEN.md",+ );+ }+ }+// 4. Cursorif filter_agent(AgentKind::Cursor) {if want_global {diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 48cb2733..67b3ba4c 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -359,6 +359,14 @@ fn resolve_hook_cwd_with(extract_cwd(raw).or_else(|| env_lookup(CODEBUDDY_PROJECT_DIR_ENV)).filter(|s| !s.trim().is_empty())+ } else if agent_kind == AgentKind::QwenCode {+ // Qwen Code sets `QWEN_PROJECT_DIR` (and Claude/Gemini aliases) on+ // every command hook+ // (<https://qwenlm.github.io/qwen-code-docs/en/users/features/hooks/>).+ let mut env_lookup = env_lookup;+ extract_cwd(raw)+ .or_else(|| env_lookup(QWEN_PROJECT_DIR_ENV))+ .filter(|s| !s.trim().is_empty())} else {extract_cwd(raw).filter(|s| !s.trim().is_empty())}@@ -367,6 +375,9 @@ fn resolve_hook_cwd_with(/// The project directory CodeBuddy Code exports to every hook process.const CODEBUDDY_PROJECT_DIR_ENV: &str = "CODEBUDDY_PROJECT_DIR";+/// The project directory Qwen Code exports to every command hook process.+const QWEN_PROJECT_DIR_ENV: &str = "QWEN_PROJECT_DIR";+fn cwd_query_suffix(agent: &str,raw: &serde_json::Value,@@ -814,13 +825,14 @@ fn write_success_response<W: std::io::Write>(Ok(())} else if matches!(agent,- AgentKind::Muse | AgentKind::CodeBuddy | AgentKind::IbmBob+ AgentKind::Muse | AgentKind::CodeBuddy | AgentKind::IbmBob | AgentKind::QwenCode) && matches!(event, HookEvent::SessionStart | HookEvent::UserPrompt){// Muse and IBM Bob add SessionStart and UserPromptSubmit stdout to the- // turn as context, and CodeBuddy appends exit-0 stdout of both to the- // session, so a capture-only reply stays empty rather than put `{}` in- // front of the model on every prompt.+ // turn as context, CodeBuddy appends exit-0 stdout of both to the+ // session, and Qwen Code injects both as tagged model context, so a+ // capture-only reply stays empty rather than put `{}` in front of the+ // model on every prompt.Ok(())} else if event == HookEvent::UserPrompt && agent.user_prompt_injects_handoff() {// Kimi Code injects any non-empty UserPromptSubmit stdout into the turn@@ -2885,6 +2897,13 @@ mod tests {HookEvent::PostToolUse,b"{}\n".as_slice(),),+ (AgentKind::QwenCode, HookEvent::SessionStart, b"".as_slice()),+ (AgentKind::QwenCode, HookEvent::UserPrompt, b"".as_slice()),+ (+ AgentKind::QwenCode,+ HookEvent::PostToolUse,+ b"{}\n".as_slice(),+ ),] {let mut output = Vec::new();write_success_response(&mut output, agent, event).unwrap();@@ -3230,6 +3249,7 @@ mod tests {let cases = [("codebuddy", "session-start", serde_json::json!({})),("ibm-bob", "session-start", serde_json::json!({})),+ ("qwen-code", "session-start", serde_json::json!({})),("claude-code", "session-start", serde_json::json!({})),("codex", "session-start", serde_json::json!({})),(@@ -3554,6 +3574,31 @@ mod tests {resolve_hook_cwd_with("codebuddy", &with_cwd, project_dir, process).as_deref(),Some("payload-project"));+ }++ /// Qwen Code exports `QWEN_PROJECT_DIR` on every command hook. A missing+ /// payload `cwd` uses that directory; the process cwd is never a fallback.+ #[test]+ fn qwen_code_missing_cwd_uses_qwen_project_dir_only() {+ let bare = serde_json::json!({"hook_event_name": "SessionStart", "source": "startup"});+ let project_dir =+ |name: &str| (name == "QWEN_PROJECT_DIR").then(|| "env-project".to_owned());+ let process = || Some(PathBuf::from("process-project"));++ assert_eq!(+ resolve_hook_cwd_with("qwen-code", &bare, project_dir, process).as_deref(),+ Some("env-project")+ );+ assert_eq!(+ resolve_hook_cwd_with("qwen-code", &bare, |_| None, process),+ None+ );+ let with_cwd =+ serde_json::json!({"hook_event_name": "SessionStart", "cwd": "payload-project"});+ assert_eq!(+ resolve_hook_cwd_with("qwen-code", &with_cwd, project_dir, process).as_deref(),+ Some("payload-project")+ );// Another agent never reads CodeBuddy's variable.assert_eq!(resolve_hook_cwd_with("claude-code", &bare, project_dir, process),diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 29cf803d..5a09de82 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -459,6 +459,15 @@ pub(crate) fn ibm_bob_settings_path() -> anyhow::Result<std::path::PathBuf> {.join("settings.json"))}+/// `~/.qwen/settings.json` — Qwen Code's user settings. MCP servers and+/// lifecycle hooks share this file (`mcpServers` and `hooks`).+pub(crate) fn qwen_code_settings_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(home_dir()+ .context("could not locate $HOME for ~/.qwen/settings.json")?+ .join(".qwen")+ .join("settings.json"))+}+/// `~/.config/zero/hooks.json` — Zero's user-level lifecycle hook config/// (issue #156). Zero resolves it under `$XDG_CONFIG_HOME` falling back to/// `~/.config`; like the OpenCode plugin path below we target the default@@ -1028,6 +1037,13 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(AgentChoice::Cline => {apply_to_cline_hooks(&server_url, auth, &config.data_dir, &args, &capture_mode)}+ AgentChoice::QwenCode => {+ let path = match &args.config_file {+ Some(path) => path.clone(),+ None => qwen_code_settings_path()?,+ };+ apply_to_qwen_code_settings(&path, &server_url, auth, &config.data_dir, &args)+ }};}let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);@@ -1204,6 +1220,7 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(&args,&preview_capture_mode,),+ AgentChoice::QwenCode => render_qwen_code(&server_url, auth, &config.data_dir, strategy),}}@@ -1407,6 +1424,7 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {// Cline hook files are generated independently and carry no// shared settings document from which to recover a strategy.AgentChoice::Cline => return None,+ AgentChoice::QwenCode => qwen_code_settings_path().ok()?,}};std::fs::read_to_string(path).ok()@@ -1691,7 +1709,7 @@ fn infer_installed_mcp_config(&["mcpServers", "ai-memory"],"url",)),- McpClient::GeminiCli => Ok(infer_json_mcp_config(+ McpClient::GeminiCli | McpClient::QwenCode => Ok(infer_json_mcp_config(&content,&["mcpServers", "ai-memory"],"httpUrl",@@ -1848,6 +1866,7 @@ pub(crate) fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {// --server-url / --auth-token instead.AgentChoice::Dsh => None,AgentChoice::Cline => Some(McpClient::Cline),+ AgentChoice::QwenCode => Some(McpClient::QwenCode),}}@@ -7494,6 +7513,91 @@ fn render_ibm_bob(Ok(())}+/// Merge ai-memory's entries into the `hooks` key of Qwen Code's+/// `settings.json`, keeping every other key and every other hook,+/// idempotently.+fn apply_to_qwen_code_settings(+ path: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);+ let payload = super::render_shared::build_qwen_code_hooks_payload(+ server_url,+ auth_token,+ Some(data_dir),+ strategy,+ );+ let our_hooks = payload+ .get("hooks")+ .and_then(serde_json::Value::as_object)+ .context("internal: build_qwen_code_hooks_payload didn't return a hooks object")?;+ let outcome = apply_atomic(path, |existing| {+ mutate_json(existing, |root| {+ let hooks = root+ .entry("hooks")+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))+ .as_object_mut()+ .context("`hooks` is present in the Qwen Code settings.json but not an object")?;+ for (event, value) in our_hooks {+ overlay_event_hooks(hooks, event, value);+ }+ Ok(())+ })+ })?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ print!("{QWEN_CODE_INSTALL_NOTES}");+ Ok(())+}++const QWEN_CODE_INSTALL_NOTES: &str = "\+# NOTE: Qwen Code injects SessionStart stdout (`hookSpecificOutput.additionalContext`)+# into the session, so the prior session's handoff is delivered automatically.+# NOTE: start a new qwen session for it to load the new hooks.+";++/// Print the `hooks` block for `~/.qwen/settings.json` (dry-run counterpart+/// of [`apply_to_qwen_code_settings`]).+fn render_qwen_code(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+) -> Result<()> {+ let payload = super::render_shared::build_qwen_code_hooks_payload(+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ let serialized = serde_json::to_string_pretty(&payload["hooks"])+ .context("serializing qwen-code hook config")?;+ println!("# Qwen Code hook config — merge under the `hooks` key of");+ println!("# ~/.qwen/settings.json, or re-run with --apply to merge it in");+ println!("# place. MCP servers share this file under `mcpServers`.");+ println!("# AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("# Auth: this printed snippet embeds the token in each hook command —");+ println!("# treat settings.json as sensitive (chmod 600). `--apply` stores it");+ println!("# under the data dir instead.");+ }+ print!("{QWEN_CODE_INSTALL_NOTES}");+ println!();+ println!("{serialized}");+ Ok(())+}+/// Merge ai-memory's entries into the `hooks` key of Muse's `settings.json`,/// keeping `schema_version`, every unknown key and every other hook in it,/// idempotently, with a backup next to the file on change. Muse fails every@@ -8942,6 +9046,73 @@ mod tests {assert_eq!(pre[0]["hooks"][0]["command"], "/usr/local/bin/guard.sh");}+ /// `install-hooks --agent qwen-code --apply` merges native `--agent+ /// qwen-code` commands under the `hooks` key of `settings.json`, keeps+ /// sibling keys and third-party hooks, and a re-apply changes nothing.+ #[test]+ fn qwen_code_apply_merges_native_hooks_under_the_settings_hooks_key() {+ let home = TempDir::new().unwrap();+ let data = TempDir::new().unwrap();+ let settings = home.path().join("settings.json");+ fs::write(+ &settings,+ serde_json::json!({+ "model": "qwen3-coder-plus",+ "hooks": {+ "PreToolUse": [{+ "matcher": "write_file",+ "hooks": [{"type": "command", "command": "/usr/local/bin/guard.sh"}]+ }]+ }+ })+ .to_string(),+ )+ .unwrap();+ let args = InstallHooksArgs {+ agent: AgentChoice::QwenCode,+ config_file: Some(settings.clone()),+ ..default_hook_args()+ };++ apply_to_qwen_code_settings(&settings, "http://memory:49374", None, data.path(), &args)+ .unwrap();+ let first = fs::read_to_string(&settings).unwrap();+ apply_to_qwen_code_settings(&settings, "http://memory:49374", None, data.path(), &args)+ .unwrap();+ assert_eq!(+ first,+ fs::read_to_string(&settings).unwrap(),+ "re-apply is a no-op"+ );++ let root: serde_json::Value = serde_json::from_str(&first).unwrap();+ assert_eq!(root["model"], "qwen3-coder-plus");+ for (event, script) in super::super::render_shared::QWEN_CODE_EVENTS {+ let entries = root["hooks"][event].as_array().unwrap();+ let ours: Vec<_> = entries+ .iter()+ .filter(|entry| is_ai_memory_hook_entry(entry))+ .collect();+ assert_eq!(ours.len(), 1, "{event}: exactly one ai-memory entry");+ assert_eq!(ours[0]["matcher"], "", "{event}");+ let command = ours[0]["hooks"][0]["command"].as_str().unwrap();+ let stem = script.trim_end_matches(".sh");+ assert!(+ command.contains(&format!(+ " hook --event {stem} --agent qwen-code --server-url "+ )),+ "{event}: {command}"+ );+ assert!(+ !command.contains(".sh"),+ "{event}: no script bundle: {command}"+ );+ }+ let pre = root["hooks"]["PreToolUse"].as_array().unwrap();+ assert_eq!(pre.len(), 2);+ assert_eq!(pre[0]["hooks"][0]["command"], "/usr/local/bin/guard.sh");+ }+/// IBM Bob shares one global settings file between the IDE and Shell./// Install only their common event vocabulary, preserve unrelated content,/// omit unsupported matchers, and make repeated installation a no-op.diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex b343b3a9..6137c8d8 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -156,6 +156,7 @@ pub(crate) fn run_with_opencode_dialect(McpClient::Cursor => render_cursor(&args)?,McpClient::ClaudeDesktop => render_claude_desktop(&args)?,McpClient::GeminiCli => render_gemini_cli(&args)?,+ McpClient::QwenCode => render_qwen_code(&args)?,McpClient::Openclaw => render_openclaw(&args)?,McpClient::Pi => render_pi(&args)?,McpClient::Omp => render_omp(&args)?,@@ -413,7 +414,7 @@ fn stdio_bridge_entry(args: &InstallMcpArgs) -> Option<serde_json::Value> {| McpClient::Openclaw| McpClient::IbmBob| McpClient::Cline => plain(),- McpClient::GeminiCli | McpClient::AntigravityCli => json!({+ McpClient::GeminiCli | McpClient::AntigravityCli | McpClient::QwenCode => json!({"command": command,"args": bridge,"timeout": GEMINI_MCP_TIMEOUT_MS,@@ -655,6 +656,7 @@ pub(crate) fn mcp_config_path_with(}}McpClient::GeminiCli => home()?.join(".gemini").join("settings.json"),+ McpClient::QwenCode => home()?.join(".qwen").join("settings.json"),McpClient::Openclaw => home()?.join(".openclaw").join("config.json"),McpClient::Pi => bail!("Pi has no native mcp.json; use `ai-memory install-hooks --agent pi --apply` to install the generated MCP bridge extension."@@ -1134,6 +1136,7 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {| McpClient::ClaudeDesktop| McpClient::Cursor| McpClient::GeminiCli+ | McpClient::QwenCode| McpClient::Omp| McpClient::AntigravityCli| McpClient::Devin@@ -1678,7 +1681,10 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {entry.insert("headers".into(), json!({"Authorization": b}));}}- McpClient::GeminiCli => {+ McpClient::GeminiCli | McpClient::QwenCode => {+ // Qwen Code uses the same `httpUrl` field as Gemini CLI for+ // streamable HTTP; the plain `url` key is legacy SSE+ // (<https://qwenlm.github.io/qwen-code-docs/en/users/features/mcp/>).entry.insert("httpUrl".into(), json!(server_url));entry.insert("timeout".into(), json!(GEMINI_MCP_TIMEOUT_MS));if let Some(b) = &bearer {@@ -2317,6 +2323,19 @@ fn render_gemini_cli(args: &InstallMcpArgs) -> Result<String> {))}+fn render_qwen_code(args: &InstallMcpArgs) -> Result<String> {+ Ok(format!(+ "# Qwen Code — merge into ~/.qwen/settings.json:\n\+ #\n\+ # Qwen Code uses `httpUrl` (not `url`) for streamable-HTTP\n\+ # endpoints; `url` is the legacy SSE transport. The `timeout` is\n\+ # in milliseconds. Pair with `ai-memory install-hooks --agent\n\+ # qwen-code --apply` for lifecycle capture.\n\+ {snippet}\n",+ snippet = render_json_mcp_fragment(args)?,+ ))+}+fn render_openclaw(args: &InstallMcpArgs) -> Result<String> {Ok(format!("# OpenClaw — merge into ~/.openclaw/config.json:\n\@@ -2974,6 +2993,69 @@ mod tests {}}+ #[test]+ fn qwen_code_entry_uses_documented_http_url_shape() {+ assert_eq!(+ build_json_mcp_entry(&args_with_token(McpClient::QwenCode)).unwrap(),+ json!({+ "httpUrl": "http://127.0.0.1:49374/mcp",+ "timeout": 5000,+ "headers": {"Authorization": "Bearer test-token-deadbeef"},+ })+ );+ assert_eq!(+ build_json_mcp_entry(&args_for(McpClient::QwenCode)).unwrap(),+ json!({+ "httpUrl": "http://127.0.0.1:49374/mcp",+ "timeout": 5000,+ })+ );+ let path = mcp_config_path_with(McpClient::QwenCode, &|_| None).unwrap();+ assert!(+ path.ends_with(Path::new(".qwen/settings.json")),+ "{}",+ path.display()+ );+ }++ #[test]+ fn qwen_code_apply_preserves_siblings_and_is_idempotent() {+ let tmp = tempfile::tempdir().unwrap();+ let file = tmp.path().join("settings.json");+ fs::write(+ &file,+ json!({+ "mcpServers": {"other": {"command": "other"}},+ "hooks": {"PreToolUse": []},+ "keep": true+ })+ .to_string(),+ )+ .unwrap();+ let mut args = args_for(McpClient::QwenCode);+ args.config_file = Some(file.clone());+ args.server_url = Some("https://memory.example/mcp".into());+ apply_to_config_file(&args).unwrap();+ let first = fs::read_to_string(&file).unwrap();+ apply_to_config_file(&args).unwrap();+ assert_eq!(first, fs::read_to_string(&file).unwrap());+ let root: serde_json::Value = serde_json::from_str(&first).unwrap();+ assert_eq!(root["keep"], true);+ assert_eq!(root["hooks"]["PreToolUse"], json!([]));+ assert_eq!(root["mcpServers"]["other"]["command"], "other");+ assert_eq!(+ root["mcpServers"]["ai-memory"],+ json!({+ "httpUrl": "https://memory.example/mcp",+ "timeout": 5000,+ })+ );+ assert_eq!(+ existing_entry_endpoint(McpClient::QwenCode, &file, "ai-memory").unwrap(),+ Some("https://memory.example/mcp".into())+ );+ }+#[test]fn ibm_bob_entry_uses_documented_legacy_streamable_http_shape() {assert_eq!(@@ -4288,6 +4370,7 @@ mod tests {McpClient::Cursor => render_cursor(&args).unwrap(),McpClient::ClaudeDesktop => render_claude_desktop(&args).unwrap(),McpClient::GeminiCli => render_gemini_cli(&args).unwrap(),+ McpClient::QwenCode => render_qwen_code(&args).unwrap(),McpClient::Openclaw => render_openclaw(&args).unwrap(),McpClient::Pi => render_pi(&args).unwrap(),McpClient::Omp => render_omp(&args).unwrap(),@@ -4330,6 +4413,7 @@ mod tests {McpClient::Cursor,McpClient::ClaudeDesktop,McpClient::GeminiCli,+ McpClient::QwenCode,McpClient::Openclaw,McpClient::Omp,McpClient::AntigravityCli,@@ -4376,6 +4460,7 @@ mod tests {McpClient::Cursor,McpClient::ClaudeDesktop,McpClient::GeminiCli,+ McpClient::QwenCode,McpClient::Openclaw,McpClient::Omp,McpClient::AntigravityCli,@@ -4419,6 +4504,7 @@ mod tests {McpClient::Cursor => render_cursor(&args).unwrap(),McpClient::ClaudeDesktop => render_claude_desktop(&args).unwrap(),McpClient::GeminiCli => render_gemini_cli(&args).unwrap(),+ McpClient::QwenCode => render_qwen_code(&args).unwrap(),McpClient::Openclaw => render_openclaw(&args).unwrap(),McpClient::Pi => render_pi(&args).unwrap(),McpClient::Omp => render_omp(&args).unwrap(),@@ -4756,6 +4842,7 @@ mod tests {fn client_specific_shape_keys() {assert!(render_for_test(McpClient::Cursor).contains("\"url\""));assert!(render_for_test(McpClient::GeminiCli).contains("\"httpUrl\""));+ assert!(render_for_test(McpClient::QwenCode).contains("\"httpUrl\""));assert!(render_for_test(McpClient::ClaudeDesktop).contains("mcp-remote"));assert!(render_for_test(McpClient::Openclaw).contains("\"streamable-http\""));assert!(render_for_test(McpClient::Codex).contains("[mcp_servers.ai-memory]"));diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 750c7188..55c9edb9 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -204,6 +204,31 @@ pub(crate) const DSH_EVENTS: [(&str, &str); 7] = [("SubagentStop", "subagent-stop.sh"),];+/// Qwen Code lifecycle events ai-memory hooks. Each pair is+/// `(event-name-in-~/.qwen/settings.json, native hook-event script stem)`;+/// Qwen has no script bundle, so the `.sh` name only carries the event+/// token the native command is rendered with.+///+/// Qwen Code's hook vocabulary is Claude Code's plus `PostToolUseFailure`+/// (<https://qwenlm.github.io/qwen-code-docs/en/users/features/hooks/>).+/// `PostToolUseFailure` fires instead of `PostToolUse` when a tool throws+/// and is aliased to `post-tool-use`. Subagent events are included: Qwen+/// documents `SubagentStart`/`SubagentStop` for user-spawned agents+/// (`Bash`, `Explorer`, `Plan`). Qwen fires a real `SessionEnd`, so no+/// `finalize-session` step is needed.+pub(crate) const QWEN_CODE_EVENTS: [(&str, &str); 10] = [+ ("SessionStart", "session-start.sh"),+ ("UserPromptSubmit", "user-prompt-submit.sh"),+ ("PreToolUse", "pre-tool-use.sh"),+ ("PostToolUse", "post-tool-use.sh"),+ ("PostToolUseFailure", "post-tool-use.sh"),+ ("PreCompact", "pre-compact.sh"),+ ("Stop", "stop.sh"),+ ("SessionEnd", "session-end.sh"),+ ("SubagentStart", "subagent-start.sh"),+ ("SubagentStop", "subagent-stop.sh"),+];+/// Seconds Muse waits for one ai-memory hook. Muse reads `timeout` in/// seconds, like the Claude Code plugins it loads. The capture POST is/// fire-and-forget; `SessionStart` also fetches a handoff.@@ -1344,6 +1369,35 @@ pub(crate) fn build_ibm_bob_hooks_payload()}+/// `{"hooks": <event map>}` for Qwen Code's `~/.qwen/settings.json`. The+/// `hooks` key holds Claude Code's nested shape (`"Event": [{"matcher": "",+/// "hooks": [{"type": "command", "command": …}]}]`). Qwen runs each+/// `command` with the Claude Code-shaped event JSON on stdin+/// (<https://qwenlm.github.io/qwen-code-docs/en/users/features/hooks/>),+/// so every entry invokes the native `ai-memory hook` command; there is no+/// script bundle. An empty matcher fires on every tool and every+/// SessionStart source.+pub(crate) fn build_qwen_code_hooks_payload(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> Value {+ build_hook_payload_for_platform(+ &QWEN_CODE_EVENTS,+ Path::new(""),+ server_url,+ auth_token,+ HookShape::Nested,+ HookCommandContext::new(+ HookCommandPlatform::native(),+ "qwen-code",+ data_dir,+ project_strategy,+ ),+ )+}+/// Pool (Poolside Agent CLI) `.poolside/settings.yaml` `hooks:` block for/// install-hooks' print path. Pool's hook config is a project-scoped YAML/// file at the repo root — there is no user-global hook file for ai-memory@@ -4519,6 +4573,35 @@ if (inheritOnly) {}}+ #[test]+ fn qwen_code_profile_uses_nested_native_commands() {+ let value = build_qwen_code_hooks_payload(+ "http://memory:49374",+ None,+ Some(Path::new("/data")),+ Some("repo-root"),+ );++ assert_eq!(value["hooks"].as_object().unwrap().len(), 10);+ for (event, script) in QWEN_CODE_EVENTS {+ let definition = &value["hooks"][event][0];+ assert_eq!(definition["matcher"], "", "event: {event}");+ let command = definition["hooks"][0]["command"].as_str().unwrap();+ let event_name = script.trim_end_matches(".sh");+ assert!(+ command.contains(&format!("hook --event {event_name} --agent qwen-code")),+ "{event}: {command}"+ );+ let expected_strategy = if cfg!(windows) {+ r#"--project-strategy "repo-root""#+ } else {+ "--project-strategy repo-root"+ };+ assert!(command.contains(expected_strategy), "{command}");+ assert!(!command.contains(".sh"), "{command}");+ }+ }+#[test]fn ibm_bob_profile_uses_common_events_without_matchers() {let value = build_ibm_bob_hooks_payload(diff --git a/crates/ai-memory-cli/src/commands/restore_agents.rs b/crates/ai-memory-cli/src/commands/restore_agents.rsindex 852aaacd..d4676684 100644--- a/crates/ai-memory-cli/src/commands/restore_agents.rs+++ b/crates/ai-memory-cli/src/commands/restore_agents.rs@@ -616,6 +616,7 @@ fn validate_target_relative(scope: AgentAssetScope, rel_path: &str) -> Result<()".openclaw/",".commandcode/",".kimi/",+ ".qwen/",];let allowed = rel_path == ".claude.json"|| PREFIXES.iter().any(|prefix| rel_path.starts_with(prefix));@@ -631,6 +632,7 @@ fn validate_target_relative(scope: AgentAssetScope, rel_path: &str) -> Result<()"CLAUDE.md","AGENTS.md","GEMINI.md",+ "QWEN.md",".cursorrules","opencode.json","opencode.jsonc",diff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsindex 09891749..6d12254a 100644--- a/crates/ai-memory-cli/src/commands/setup.rs+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -239,6 +239,9 @@ pub async fn run(config: &Config, args: SetupArgs, config_path: Option<&Path>) -if let Some(dir) = ibm_bob_detected(&home) {found.push((AgentChoice::IbmBob, Found::ConfigDir(dir)));}+ if let Some(dir) = qwen_code_detected(&home) {+ found.push((AgentChoice::QwenCode, Found::ConfigDir(dir)));+ }found.into_iter().map(|(agent, found)| (agent, Some(found)))@@ -424,6 +427,13 @@ fn ibm_bob_detected(home: &Path) -> Option<PathBuf> {Some(home.join(".bob")).filter(|dir| dir.is_dir())}+/// Qwen Code's directory, `~/.qwen`, when it exists. Qwen has no+/// native-session adapter, so setup finds it by that directory rather than+/// by [`detect_agents`].+fn qwen_code_detected(home: &Path) -> Option<PathBuf> {+ Some(home.join(".qwen")).filter(|dir| dir.is_dir())+}+/// The binary path the service unit runs. A package manager's versioned/// location (a Homebrew `Cellar/<formula>/<version>` or a `/nix/store` path)/// disappears on the next upgrade or `brew cleanup` / garbage collection, so a@@ -1159,6 +1169,25 @@ mod tests {assert_eq!(AgentPlan::new(AgentChoice::CodeBuddy, None).mcp, None);}+ #[test]+ fn qwen_code_is_detected_and_wires_hooks_mcp_and_shared_skills() {+ let home = tempfile::tempdir().unwrap();+ assert_eq!(qwen_code_detected(home.path()), None);+ std::fs::create_dir_all(home.path().join(".qwen")).unwrap();+ assert_eq!(+ qwen_code_detected(home.path()),+ Some(home.path().join(".qwen"))+ );+ assert_eq!(+ skills_for(AgentChoice::QwenCode),+ InstallSkillsAgent::Agents+ );+ assert_eq!(+ AgentPlan::new(AgentChoice::QwenCode, None).mcp,+ Some(McpClient::QwenCode)+ );+ }+#[test]fn ibm_bob_is_detected_and_wires_hooks_mcp_and_shared_skills() {let home = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 08a163f8..eae3189d 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -141,6 +141,11 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {"Cline discovers generated hook files in the host user's hook directory; run `ai-memory install-hooks --agent cline --apply` on that host");}+ // Qwen Code too: ~/.qwen/settings.json runs the native `hook` command.+ if matches!(args.agent, AgentChoice::QwenCode) {+ emit_qwen_code(&args)?;+ return Ok(());+ }let Some(agent_sub) = args.agent.script_hook_subdir() else {bail!("internal: generated integration should have returned before staging hooks")};@@ -242,7 +247,8 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {| AgentChoice::Muse| AgentChoice::CodeBuddy| AgentChoice::IbmBob- | AgentChoice::Cline => {+ | AgentChoice::Cline+ | AgentChoice::QwenCode => {bail!("internal: generated integration should have returned before emitting staged hooks")@@ -446,6 +452,29 @@ fn emit_ibm_bob(args: &SetupAgentArgs) -> Result<()> {Ok(())}+/// Print the `hooks` block for `~/.qwen/settings.json`. No scripts are+/// staged: each entry runs the native `hook` command.+fn emit_qwen_code(args: &SetupAgentArgs) -> Result<()> {+ let payload = crate::commands::render_shared::build_qwen_code_hooks_payload(+ &args.server_url,+ args.auth_token.as_deref(),+ None,+ None,+ );+ let serialized = serde_json::to_string_pretty(&payload["hooks"])+ .context("serializing Qwen Code hook config")?;+ println!("# Qwen Code — merge under the `hooks` key of");+ println!("# ~/.qwen/settings.json. The `command` must be an ai-memory");+ println!("# binary reachable on the host that runs Qwen Code; prefer");+ println!("# `ai-memory install-hooks --agent qwen-code --apply` from that host.");+ if args.auth_token.is_some() {+ println!("# Treat settings.json as sensitive (chmod 600).");+ }+ println!();+ println!("{serialized}");+ Ok(())+}+fn normalise_hook_server_url(url: &str) -> String {url.trim().trim_end_matches('/').to_string()}diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex b1092b15..498787d2 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -282,6 +282,10 @@ fn build_plan(install_hooks::ibm_bob_settings_path()?,HookConfigShape::NestedHooksKey,),+ (+ install_hooks::qwen_code_settings_path()?,+ HookConfigShape::NestedHooksKey,+ ),]);for (path, shape) in hook_files {if !path.exists() {@@ -461,6 +465,7 @@ fn build_plan(KiroCli,CommandCode,IbmBob,+ QwenCode,CopilotCli,Droid,Swival,@@ -1569,6 +1574,7 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {| McpClient::ClaudeDesktop| McpClient::Cursor| McpClient::GeminiCli+ | McpClient::QwenCode| McpClient::Omp| McpClient::AntigravityCli| McpClient::KimiCodediff --git a/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rsindex 943d6d58..2a09b3a9 100644--- a/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/auth_default_e2e.rs@@ -467,6 +467,7 @@ mod slow {"cursor","claude-desktop","gemini-cli",+ "qwen-code","openclaw","omp","antigravity-cli",diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 80ad27d8..0b980167 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -308,6 +308,12 @@ pub enum AgentKind {/// Cline CLI, whose file hooks use `taskId` plus nested `tool_call` //// `tool_result` payloads. Run-start hooks are detached by default.Cline,+ /// Qwen Code (`qwen`), whose hooks send Claude Code-shaped payloads+ /// (`session_id`, `cwd`, `tool_name`, `tool_input`, `tool_use_id`) and+ /// whose MCP servers use Gemini CLI's `httpUrl` field in+ /// `~/.qwen/settings.json`.+ #[serde(rename = "qwen-code", alias = "qwen")]+ QwenCode,/// Anything else (manual capture, future agents).Other,}@@ -318,7 +324,7 @@ impl AgentKind {/// CHECK constraint accepts every kind (the Zero integration shipped/// with the enum variant but without the V26 migration and only a/// live test caught it). Extend together with the enum.- pub const ALL: [Self; 29] = [+ pub const ALL: [Self; 30] = [Self::ClaudeCode,Self::Codex,Self::OpenCode,@@ -347,6 +353,7 @@ impl AgentKind {Self::IbmBob,Self::Dsh,Self::Cline,+ Self::QwenCode,Self::Other,];@@ -382,6 +389,7 @@ impl AgentKind {Self::IbmBob => "ibm-bob",Self::Dsh => "dsh",Self::Cline => "cline",+ Self::QwenCode => "qwen-code",Self::Other => "other",}}@@ -420,6 +428,7 @@ impl AgentKind {"ibm-bob" | "bob" => Self::IbmBob,"dsh" | "deepseek-harness" | "deepseek_harness" => Self::Dsh,"cline" | "cline-cli" => Self::Cline,+ "qwen-code" | "qwen" | "qwencode" => Self::QwenCode,_ => Self::Other,}}@@ -477,6 +486,10 @@ impl AgentKind {/// against v2.164.0–v2.167.0, #1299), so the native hook fetches the/// handoff for it. The fetch stays the built-in SessionStart path; a/// separate `GET /handoff` client is not part of the installer.+ ///+ /// Qwen Code injects `hookSpecificOutput.additionalContext` from+ /// `SessionStart` stdout into the session (Qwen Code hooks reference:+ /// <https://qwenlm.github.io/qwen-code-docs/en/users/features/hooks/>).#[must_use]pub fn session_start_injects_handoff(self) -> bool {!matches!(@@ -536,13 +549,15 @@ impl AgentKind {/// `hookSpecificOutput.additionalContext` to the turn it belongs to.////// Claude Code places it alongside the submitted prompt and Codex adds it- /// as developer context (both hook references). The compaction recap uses- /// this channel. Grok discards an allowing `UserPromptSubmit`'s output,- /// and Kimi Code injects raw stdout rather than this envelope, so neither- /// is listed.+ /// as developer context (both hook references). Qwen Code sends it as a+ /// tagged text part+ /// (<https://qwenlm.github.io/qwen-code-docs/en/users/features/hooks/>).+ /// The compaction recap uses this channel. Grok discards an allowing+ /// `UserPromptSubmit`'s output, and Kimi Code injects raw stdout rather+ /// than this envelope, so neither is listed.#[must_use]pub fn user_prompt_injects_context(self) -> bool {- matches!(self, Self::ClaudeCode | Self::Codex)+ matches!(self, Self::ClaudeCode | Self::Codex | Self::QwenCode)}/// Whether `PostToolUse` stdout is model-visible context.@@ -883,6 +898,32 @@ mod tests {assert!(!AgentKind::IbmBob.reuses_session_id_after_end());}+ #[test]+ fn agent_kind_qwen_code_round_trips_and_injects_session_start_handoff() {+ assert_eq!(AgentKind::QwenCode.as_str(), "qwen-code");+ for alias in ["qwen-code", "qwen", "qwencode"] {+ assert_eq!(AgentKind::from_wire(alias), AgentKind::QwenCode, "{alias}");+ }+ assert_eq!(+ serde_json::to_string(&AgentKind::QwenCode).unwrap(),+ "\"qwen-code\""+ );+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"qwen-code\"").unwrap(),+ AgentKind::QwenCode+ );+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"qwen\"").unwrap(),+ AgentKind::QwenCode+ );+ assert_eq!(AgentKind::from_wire("qwen-code-2"), AgentKind::Other);+ assert!(AgentKind::QwenCode.session_start_injects_handoff());+ assert!(!AgentKind::QwenCode.user_prompt_injects_handoff());+ assert!(AgentKind::QwenCode.user_prompt_injects_context());+ assert!(!AgentKind::QwenCode.post_tool_injects_handoff());+ assert!(!AgentKind::QwenCode.reuses_session_id_after_end());+ }+#[test]fn agent_kind_grizzybot_round_trips() {assert_eq!(AgentKind::Grizzybot.as_str(), "grizzybot");@@ -986,11 +1027,14 @@ mod tests {}#[test]- fn user_prompt_context_injection_is_claude_code_and_codex() {+ fn user_prompt_context_injection_is_claude_code_codex_and_qwen_code() {for agent in AgentKind::ALL {assert_eq!(agent.user_prompt_injects_context(),- matches!(agent, AgentKind::ClaudeCode | AgentKind::Codex),+ matches!(+ agent,+ AgentKind::ClaudeCode | AgentKind::Codex | AgentKind::QwenCode+ ),"{}",agent.as_str());diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex decd9c14..75893ee4 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -205,7 +205,8 @@ pub(crate) fn tool_payload_fields(agent: AgentKind, raw: &Value) -> Option<(&str| AgentKind::Muse| AgentKind::CodeBuddy| AgentKind::IbmBob- | AgentKind::Dsh => (+ | AgentKind::Dsh+ | AgentKind::QwenCode => (object.get("tool_name")?.as_str()?,object.get("tool_use_id").and_then(Value::as_str),),@@ -295,6 +296,7 @@ pub(crate) fn tool_observation_metadata(| AgentKind::CodeBuddy| AgentKind::IbmBob| AgentKind::Dsh+ | AgentKind::QwenCode) {"tool_input"} else {@@ -351,7 +353,7 @@ pub(crate) fn tool_observation_outcome(agent: AgentKind, raw: &Value) -> ToolOut// Meta Muse Code's `PostToolUseFailure` has the same `error` string// (captured offline on Muse Code 1.4.7); its `PostToolUse` proves no// outcome.- AgentKind::Zcode | AgentKind::Muse+ AgentKind::Zcode | AgentKind::Muse | AgentKind::QwenCodeif raw.get("error").and_then(Value::as_str)@@ -1135,6 +1137,7 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {| AgentKind::Codex| AgentKind::Cursor| AgentKind::GeminiCli+ | AgentKind::QwenCode| AgentKind::Devin| AgentKind::Hermes| AgentKind::KiroCli@@ -4656,6 +4659,7 @@ mod tests {AgentKind::Droid,AgentKind::Muse,AgentKind::CodeBuddy,+ AgentKind::QwenCode,AgentKind::OpenCode,AgentKind::Omp,AgentKind::Pi,@@ -5663,6 +5667,29 @@ mod tests {assert!(tool_observation_metadata(AgentKind::CopilotCli, &no_input, true).is_none());}+ #[test]+ fn qwen_code_tool_metadata_uses_documented_claude_shaped_fields() {+ let pre = json!({+ "tool_name": "write_file",+ "tool_input": {"file_path": "src/lib.rs", "content": "x"},+ "tool_use_id": "toolu_qwen",+ });+ let metadata = tool_observation_metadata(AgentKind::QwenCode, &pre, true).unwrap();+ assert_eq!(metadata.tool_family, ToolFamily::File);+ assert_eq!(metadata.tool_call_id.as_deref(), Some("toolu_qwen"));+ assert_eq!(+ tool_observation_outcome(+ AgentKind::QwenCode,+ &json!({"tool_name": "write_file", "error": "disk full"})+ ),+ ToolOutcome::Error+ );+ assert_eq!(+ tool_observation_outcome(AgentKind::QwenCode, &json!({"tool_name": "write_file"})),+ ToolOutcome::Unknown+ );+ }+#[test]fn command_code_official_tool_shape_is_closed_and_honors_exclusions() {let policy = CapturePolicy::resolve(@@ -6595,6 +6622,10 @@ mod tests {AgentKind::GeminiCli,json!({"tool_name": "read_many_files", "tool_input": {"include": include}}),),+ (+ AgentKind::QwenCode,+ json!({"tool_name": "read_many_files", "tool_input": {"include": include}}),+ ),(AgentKind::OpenCode,json!({"tool": "read_many_files", "args": {"include": include}}),diff --git a/crates/ai-memory-hooks/src/drop_list.rs b/crates/ai-memory-hooks/src/drop_list.rsindex a53b01f6..b5672dd0 100644--- a/crates/ai-memory-hooks/src/drop_list.rs+++ b/crates/ai-memory-hooks/src/drop_list.rs@@ -350,6 +350,19 @@ mod tests {serde_json::json!({ "session_id": "s", "tool_name": "Read", "tool_use_id": "toolu_4" }),);assert!(!list.matches(&codebuddy_kept));+ // Qwen Code sends the same Claude-shaped `tool_name` / `tool_use_id`.+ let qwen = agent_event(+ "qwen-code",+ "post-tool-use",+ serde_json::json!({ "session_id": "s", "tool_name": "write_file", "tool_input": { "file_path": "a" }, "tool_use_id": "plugin-5" }),+ );+ assert!(list.matches(&qwen));+ let qwen_kept = agent_event(+ "qwen-code",+ "post-tool-use",+ serde_json::json!({ "session_id": "s", "tool_name": "write_file", "tool_use_id": "toolu_5" }),+ );+ assert!(!list.matches(&qwen_kept));// Controls: the same agents with ordinary ids and names stay.let kept = agent_event("opencode",diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex db05c389..2881d44e 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -859,6 +859,7 @@ const fn closed_tool_agent(agent: AgentKind) -> bool {// PostToolUse.| AgentKind::Dsh| AgentKind::Cline+ | AgentKind::QwenCode)}@@ -2243,6 +2244,9 @@ mod tests {assert_eq!(parse_agent("poolside"), AgentKind::Pool);assert_eq!(parse_agent("codebuddy"), AgentKind::CodeBuddy);assert_eq!(parse_agent("code-buddy"), AgentKind::CodeBuddy);+ assert_eq!(parse_agent("qwen-code"), AgentKind::QwenCode);+ assert_eq!(parse_agent("qwen"), AgentKind::QwenCode);+ assert_eq!(parse_agent("qwencode"), AgentKind::QwenCode);// Anything else is `Other`. Critical for the hook router:// a typo in the query string must not crash, it just gets// attributed to the catch-all bucket.@@ -2394,6 +2398,49 @@ mod tests {assert!(unknown.body_excerpt.is_none());}+ /// Qwen Code documents Claude Code's snake_case tool fields, including+ /// `tool_use_id`. A recognized Qwen payload becomes a closed tool+ /// observation while an unknown agent carrying identical JSON stays on+ /// the capture-only path.+ #[test]+ fn qwen_code_post_tool_use_uses_the_claude_shaped_parser() {+ let raw = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "session_id": "11111111-2222-3333-4444-555555555555",+ "cwd": "/repo",+ "tool_name": "write_file",+ "tool_use_id": "toolu_qwen",+ "tool_input": {"file_path": "src/lib.rs", "content": "x"},+ "tool_response": "wrote file"+ });+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("qwen-code".into()),+ ..Default::default()+ },+ raw.clone(),+ );+ assert_eq!(env.agent, AgentKind::QwenCode);+ assert_eq!(env.title_hint.as_deref(), Some("tool file"));+ let body = env.body_excerpt.expect("structured tool body");+ assert!(body.starts_with("tool_family: file\n"), "{body}");+ assert!(body.contains("tool_call_id: toolu_qwen"), "{body}");+ assert!(body.contains("\n---\nwrote file"), "{body}");++ let unknown = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("qwen-code-2".into()),+ ..Default::default()+ },+ raw,+ );+ assert_eq!(unknown.agent, AgentKind::Other);+ assert!(unknown.title_hint.is_none());+ assert!(unknown.body_excerpt.is_none());+ }+/// Hermes 3.x puts the tool result inside `extra.result` and mirrors the/// call status in `extra.status` (`ok` | `error`). The extractor must read/// both from the documented `extra` object: output lands in the bodydiff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.jsonindex 69a32e64..896d6192 100644--- a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json@@ -20,6 +20,7 @@{"agent":"codex","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},{"agent":"cursor","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},{"agent":"gemini-cli","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"qwen-code","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},{"agent":"devin","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},{"agent":"kiro-cli","payload":{"tool_name":"fs_write","tool_input":{"command":"create","path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},{"agent":"kiro-cli","payload":{"tool_name":"read","tool_input":{"operations":[{"mode":"Line","path":"public"},{"mode":"Line","path":"secret/a"}]}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":2},@@ -73,6 +74,12 @@{"agent":"gemini-cli","payload":{"tool_name":"run_shell_command","tool_input":{"command":"cat public/a"}},"disposition":"keep","tool_family":"non-file","extraction_state":"extracted","path_count":0},{"agent":"gemini-cli","payload":{"tool_name":"list_directory","tool_input":{"dir_path":"secret"}},"disposition":"drop","tool_family":"search-list","extraction_state":"not-applicable","path_count":0},{"agent":"gemini-cli","payload":{"tool_name":"search_file_content","tool_input":{"pattern":"x"}},"disposition":"drop","tool_family":"search-list","extraction_state":"not-applicable","path_count":0},+ {"agent":"qwen-code","payload":{"tool_name":"write_file","tool_input":{"file_path":"secret/a","content":"x"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"qwen-code","payload":{"tool_name":"read_file","tool_input":{"file_path":"public/a"}},"disposition":"keep","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"qwen-code","payload":{"tool_name":"run_shell_command","tool_input":{"command":"cat secret/a"}},"disposition":"drop","tool_family":"non-file","extraction_state":"extracted","path_count":0},+ {"agent":"qwen-code","payload":{"tool_name":"run_shell_command","tool_input":{"command":"cat public/a"}},"disposition":"keep","tool_family":"non-file","extraction_state":"extracted","path_count":0},+ {"agent":"qwen-code","payload":{"tool_name":"grep_search","tool_input":{"pattern":"x"}},"disposition":"drop","tool_family":"search-list","extraction_state":"not-applicable","path_count":0},+ {"agent":"qwen-code","payload":{"tool_name":"glob","tool_input":{"pattern":"**/*.md"}},"disposition":"drop","tool_family":"search-list","extraction_state":"not-applicable","path_count":0},{"agent":"open-code","payload":{"tool":"read_many_files","args":{"include":["secret/a"]}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},{"agent":"open-code","payload":{"tool":"read_many_files","args":{"include":["public/a","secret/a"]}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":2},{"agent":"open-code","payload":{"tool":"read_many_files","args":{"include":["**/*.md"]}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},diff --git a/crates/ai-memory-store/migrations/V87__sessions_qwen_code_agent_kind.sql b/crates/ai-memory-store/migrations/V87__sessions_qwen_code_agent_kind.sqlnew file mode 100644index 00000000..f6614974--- /dev/null+++ b/crates/ai-memory-store/migrations/V87__sessions_qwen_code_agent_kind.sql@@ -0,0 +1,73 @@+-- Expand sessions.agent_kind CHECK for Qwen Code while preserving V85's+-- schema, indexes, and scope-pairing triggers (V86 only added CJK search+-- indexes and does not rebuild sessions).+--+-- `Store::open` turns foreign keys off around the migration runner (a PRAGMA+-- inside refinery's transaction is ignored). With them on, `DROP TABLE+-- sessions` would delete every observation, ingest key, and other row that+-- references a session through ON DELETE CASCADE.++DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_session_pairing_ai;+DROP TRIGGER IF EXISTS session_consolidation_jobs_session_pairing_ai;++CREATE TABLE sessions_new (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','pi','crush','grok','zero','devin','kimi-code','kiro-cli','command-code','hermes','pool','zcode','grizzybot','copilot-cli','droid','muse','codebuddy','ibm-bob','dsh','cline','qwen-code','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL,+ ended_observation_count INTEGER NOT NULL DEFAULT 0 CHECK (ended_observation_count >= 0),+ actor_user TEXT+);++INSERT INTO sessions_new (+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,+ summary_page_id, ended_observation_count, actor_user+)+SELECT+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,+ summary_page_id, ended_observation_count, actor_user+FROM sessions;++DROP TABLE sessions;++ALTER TABLE sessions_new RENAME TO sessions;++CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);+CREATE INDEX idx_sessions_project ON sessions(project_id);+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);+CREATE INDEX idx_sessions_scope_ended+ ON sessions(workspace_id, project_id, ended_at ASC)+ WHERE ended_at IS NOT NULL;+CREATE INDEX idx_sessions_open_owner+ ON sessions(workspace_id, project_id, agent_kind, actor_user)+ WHERE ended_at IS NULL;++CREATE TRIGGER sessions_ws_proj_pairing_ai+BEFORE INSERT ON sessions+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)+BEGIN+ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');+END;++CREATE TRIGGER auto_improve_scheduler_claims_session_pairing_ai+BEFORE INSERT ON auto_improve_scheduler_claims+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)+BEGIN+ SELECT RAISE(ABORT, 'auto_improve_scheduler_claims scope does not match the session scope');+END;++CREATE TRIGGER session_consolidation_jobs_session_pairing_ai+BEFORE INSERT ON session_consolidation_jobs+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)+BEGIN+ SELECT RAISE(ABORT, 'session_consolidation_jobs scope does not match the session scope');+END;diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rsindex e9d43448..6b080e9c 100644--- a/crates/ai-memory-store/src/api_credentials.rs+++ b/crates/ai-memory-store/src/api_credentials.rs@@ -433,7 +433,7 @@ mod tests {|row| row.get(0),).unwrap();- assert_eq!(version, 86, "update the pin when adding a migration");+ assert_eq!(version, 87, "update the pin when adding a migration");let cols: i64 = conn.query_row("SELECT COUNT(*) FROM pragma_table_info('users') \diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rsindex e56e62c2..403acba3 100644--- a/crates/ai-memory-store/src/migrations.rs+++ b/crates/ai-memory-store/src/migrations.rs@@ -1553,6 +1553,115 @@ mod tests {}}+ /// V87 expands the sessions enum for Qwen Code. Existing sessions and+ /// dependent observations survive the table rebuild, while the old V86+ /// constraint rejects the new value and the migrated schema accepts it.+ #[test]+ fn v86_to_v87_preserves_sessions_and_observations_and_accepts_qwen_code() {+ let mut conn = Connection::open_in_memory().unwrap();+ run_to(&mut conn, 86).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();+ let project_id =+ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();+ let existing = SessionId::new();+ conn.execute(+ "INSERT INTO sessions \+ (id, workspace_id, project_id, agent_kind, cwd, started_at, actor_user) \+ VALUES (?1, ?2, ?3, 'ibm-bob', '/repo', 1, 'user:alice')",+ params![+ existing.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ ],+ )+ .unwrap();+ assert!(+ conn.execute(+ "INSERT INTO sessions \+ (id, workspace_id, project_id, agent_kind, started_at) \+ VALUES (?1, ?2, ?3, 'qwen-code', 1)",+ params![+ SessionId::new().as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ ],+ )+ .is_err(),+ "the V86 CHECK must reject qwen-code"+ );+ conn.execute(+ "INSERT INTO observations \+ (id, session_id, workspace_id, project_id, kind, title, body, created_at) \+ VALUES (?1, ?2, ?3, ?4, 'prompt', 'kept', 'kept body', 1)",+ params![+ uuid::Uuid::new_v4().as_bytes(),+ existing.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ ],+ )+ .unwrap();++ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ run(&mut conn).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++ let preserved: (String, String, Option<String>) = conn+ .query_row(+ "SELECT agent_kind, cwd, actor_user FROM sessions WHERE id = ?1",+ params![existing.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .unwrap();+ assert_eq!(+ preserved,+ ("ibm-bob".into(), "/repo".into(), Some("user:alice".into()))+ );+ let observations: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM observations WHERE session_id = ?1",+ params![existing.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(observations, 1, "the session's observations survive");++ crate::ops::begin_session(+ &mut conn,+ &NewSession {+ occurred_at: None,+ id: SessionId::new(),+ workspace_id,+ project_id,+ agent_kind: AgentKind::QwenCode,+ cwd: Some("/repo".into()),+ actor_user: Some("user:alice".into()),+ },+ )+ .unwrap();+ assert_eq!(+ conn.query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |row| {+ row.get::<_, i64>(0)+ })+ .unwrap(),+ 0+ );+ for name in [+ "idx_sessions_open_owner",+ "sessions_ws_proj_pairing_ai",+ "auto_improve_scheduler_claims_session_pairing_ai",+ "session_consolidation_jobs_session_pairing_ai",+ ] {+ let kind = if name.starts_with("idx_") {+ "index"+ } else {+ "trigger"+ };+ assert_eq!(schema_object_count(&conn, kind, name), 1, "missing {name}");+ }+ }+#[test]fn v81_to_v82_preserves_managed_runs_and_adds_previous_session_identity() {let mut conn = Connection::open_in_memory().unwrap();diff --git a/docs/competitive-parity.md b/docs/competitive-parity.mdindex f71ca7e6..04af326a 100644--- a/docs/competitive-parity.md+++ b/docs/competitive-parity.md@@ -300,7 +300,7 @@ invariants), **ALREADY** (we have it and should say so).| Larger capture caps | Keep ours (2 KB / 16 KiB) | Privacy boundary (invariant 6); the decomposition showed the caps were not the cause (pages holding exactly the captured text scored 0.968) || PaaS deploy templates (Fly, Railway, Render, Coolify) | DECLINE for now (a demand-gated docs recipe at most) | Non-loopback already refuses to run without auth; a hosted path is not our product || Redis or other external store backends | DECLINE | Invariants 2 and 3 (single-writer SQLite; indexes in the same transaction) and markdown as truth |-| Harness long tail (Droid, Warp, Cline, Kilo, Goose, Qwen Code, Aider, …) | SHIPPED as first-class Droid and Cline CLI support plus MCP recipes for Warp, Kilo Code, Goose, Qwen Code and OpenHuman; hooks only where the harness has a lifecycle API | Any MCP client reaches us over HTTP |+| Harness long tail (Droid, Warp, Cline, Kilo, Goose, Qwen Code, Aider, …) | SHIPPED as first-class Droid, Cline CLI, and Qwen Code support plus MCP recipes for Warp, Kilo Code, Goose and OpenHuman; hooks only where the harness has a lifecycle API | Any MCP client reaches us over HTTP || Image / vision memory | DECLINE | Off-mission; the sanitizer boundary is text-only || Bidirectional bridge with a harness's own `MEMORY.md` | DECLINE (bidirectional); one-way import ADOPT | Two sources of truth contradict our routing rule against harness-local stores || Obsidian vault export | ALREADY | The wiki is already markdown in git; open `<data_dir>/wiki/<ws>/<project>` as a vault |diff --git a/docs/design-backup-agent-assets.md b/docs/design-backup-agent-assets.mdindex fa10966e..4a2b4d4d 100644--- a/docs/design-backup-agent-assets.md+++ b/docs/design-backup-agent-assets.md@@ -24,6 +24,7 @@ Before these commands were added:| **Claude Code / Desktop** | `~/.claude.json`<br>`~/.claude/settings.json`<br>`claude_desktop_config.json` | `~/.claude/skills/`<br>`.claude/skills/` | `~/.claude/plugins/`<br>`Claude Extensions/` | `CLAUDE.md` || **OpenAI Codex CLI** | `~/.codex/config.toml`<br>`~/.codex/mcp.json` | `~/.agents/skills/`<br>`.agents/skills/`<br>`~/.codex/skills/` | `~/.codex/plugins/` | `AGENTS.md` || **Antigravity CLI (`agy`) / Gemini** | `~/.gemini/settings.json`<br>`~/.gemini/config/mcp_config.json`<br>`antigravity-cli/mcp_config.json` | Antigravity: `~/.gemini/config/skills/`, `~/.gemini/antigravity-cli/skills/`, `.agents/skills/`<br>Gemini: `~/.gemini/skills/`, `.gemini/skills/` | `antigravity-cli/plugins/`<br>`~/.gemini/plugins/` | `GEMINI.md`<br>`AGENTS.md`<br>`rules/` |+| **Qwen Code** | `~/.qwen/settings.json` | `~/.qwen/skills/`<br>`~/.agents/skills/` | — | `QWEN.md`<br>`AGENTS.md` || **Cursor IDE** | `~/.cursor/mcp.json`<br>`.cursor/mcp.json` | — | VS Code / Cursor extensions | `.cursorrules`<br>`.cursor/rules/` || **OpenCode (v1 / v2)** | `opencode.json`<br>`opencode.jsonc`<br>`~/.config/opencode/opencode.json` | `~/.config/opencode/skills/` | `~/.config/opencode/plugins/` | `AGENTS.md` || **Devin CLI** | `~/.devin/config.json` | `~/.devin/skills/` | — | Devin instructions |diff --git a/docs/install.md b/docs/install.mdindex f2f72b71..22959635 100644--- a/docs/install.md+++ b/docs/install.md@@ -20,7 +20,7 @@ RPM, macOS menu bar app). This page covers everything else:- [macOS menu bar app](#macos-menu-bar-app)(self-contained `.app` + LaunchAgent)- [Configuring other agent CLIs](#configuring-other-agent-clis)- (Codex, Command Code, IBM Bob, Devin CLI, OpenCode, OpenCode 2, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, GitHub Copilot CLI, Factory Droid, Meta Muse Code, CodeBuddy Code, Hermes Agent, Zero, ZCode, Kimi Code, Kiro CLI, Cline CLI, Pool, OpenClaw, FreeBuff, VS Code Copilot, Zed, and MCP-only recipes for Warp, Kilo Code, Goose, Qwen Code and OpenHuman)+ (Codex, Command Code, IBM Bob, Devin CLI, OpenCode, OpenCode 2, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Qwen Code, Antigravity CLI, Grok Build CLI, GitHub Copilot CLI, Factory Droid, Meta Muse Code, CodeBuddy Code, Hermes Agent, Zero, ZCode, Kimi Code, Kiro CLI, Cline CLI, Pool, OpenClaw, FreeBuff, VS Code Copilot, Zed, and MCP-only recipes for Warp, Kilo Code, Goose and OpenHuman)- [Installing hooks without docker](#installing-hooks-without-docker)(curl-based installer)- [Running ai-memory without docker](#running-ai-memory-without-docker)@@ -1603,6 +1603,50 @@ Managed `ai-memory run ibm-bob` resume is not supported because Bob does notdocument a stable native transcript store. See [the IBM Bob MCP and hookdetails](mcp-install.md#ibm-bob).+### Qwen Code++Qwen Code (`qwen`) keeps MCP servers and lifecycle hooks in the same user+file, `~/.qwen/settings.json`. Install both together:++```bash+ai-memory install-mcp --client qwen-code --apply \+ --server-url "https://memory.example/mcp" \+ --auth-token "$TOKEN"+ai-memory install-hooks --agent qwen-code --apply \+ --server-url "https://memory.example" \+ --auth-token "$TOKEN"+```++The `qwen` and `qwencode` aliases are accepted. MCP is merged under+`mcpServers` as Qwen's `httpUrl` streamable-HTTP entry (`timeout` in+milliseconds); the plain `url` key is the legacy SSE transport. A token-file+install writes a stdio `ai-memory mcp-bridge --no-session-id` entry instead of+putting the bearer in `headers`. Hooks are merged into the root `hooks`+object, preserving other settings and handlers. Each entry runs the native+`ai-memory hook --event … --agent qwen-code` command with an empty matcher;+there is no script bundle. Ten events are wired: `SessionStart`,+`UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure` (Qwen+fires it instead of `PostToolUse` when a tool throws), `PreCompact`, `Stop`,+`SessionEnd`, `SubagentStart` and `SubagentStop`. Capture exclusions apply to+Qwen's Gemini-like tools (`write_file`, `read_file`, `run_shell_command`,+`grep_search`, `glob`).++The `SessionStart` hook delivers the prior session's handoff through+`hookSpecificOutput.additionalContext`. With nothing to deliver, `SessionStart`+and `UserPromptSubmit` print nothing, because Qwen injects that stdout into+the session. An interactive `SessionStart` may arrive without `cwd`; the hook+then uses `QWEN_PROJECT_DIR`, which Qwen exports on every command hook. When+neither names a directory, the hook still records the event but fetches no+handoff; the baton stays open for `memory_handoff_accept`. Qwen fires a real+`SessionEnd`, so `finalize-session` is not needed.++`ai-memory setup` wires Qwen Code when `~/.qwen` exists.+`ai-memory uninstall` removes the entries. Qwen reads `AGENTS.md` and+`QWEN.md`. Managed `ai-memory run qwen` resume is not supported because Qwen+does not document a stable native transcript store. Start a new Qwen session+after installing so it reloads `settings.json`. See [the Qwen Code MCP and+hook details](mcp-install.md#qwen-code).+### Kiro CLIKiro CLI has one MCP surface and two incompatible lifecycle-hook formats.@@ -2319,6 +2363,14 @@ docker run --rm akitaonrails/ai-memory:latest \install-hooks --agent gemini-cli --auth-token "$TOKEN" \--server-url "http://homelab:49374"+docker run --rm akitaonrails/ai-memory:latest \+ install-mcp --client qwen-code --auth-token "$TOKEN" \+ --server-url "http://homelab:49374/mcp"++docker run --rm akitaonrails/ai-memory:latest \+ install-hooks --agent qwen-code --auth-token "$TOKEN" \+ --server-url "http://homelab:49374"+docker run --rm akitaonrails/ai-memory:latest \install-mcp --client antigravity-cli --auth-token "$TOKEN" \--server-url "http://homelab:49374/mcp"@@ -2380,7 +2432,7 @@ docker run --rm akitaonrails/ai-memory:latest \--server-url "http://homelab:49374/mcp"```-Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Kiro CLI, Command Code, and OpenClaw support both+Cursor, Gemini CLI, Qwen Code, Antigravity CLI, Grok Build CLI, Kiro CLI, Command Code, and OpenClaw support both`install-mcp` and `install-hooks`. Grok's `install-mcp --client grok` writes`$GROK_HOME/config.toml` (default `~/.grok/config.toml`); its hooks live under`$GROK_HOME/hooks` (default `~/.grok/hooks`). `install-hooks --agent grok`@@ -2556,30 +2608,6 @@ Sources: <https://goose-docs.ai/docs/guides/config-files>,<https://goose-docs.ai/docs/getting-started/using-extensions>,<https://goose-docs.ai/docs/guides/goose-cli-commands>.-##### Qwen Code--Qwen Code reads `mcpServers` from `~/.qwen/settings.json` (user) or-`.qwen/settings.json` (project). A streamable-HTTP server uses `httpUrl`; the-plain `url` key means the legacy SSE transport. Qwen Code expands `$NAME` and-`${NAME}` in every string of `settings.json`:--```json-{- "mcpServers": {- "ai-memory": {- "httpUrl": "http://127.0.0.1:49374/mcp",- "headers": { "Authorization": "Bearer ${AI_MEMORY_AUTH_TOKEN}" }- }- }-}-```--Leave out `headers` when the server has no bearer token; in that case-`qwen mcp add --scope user --transport http ai-memory http://127.0.0.1:49374/mcp`-writes the entry. Documented for Qwen Code 0.25.1.-Sources: <https://qwenlm.github.io/qwen-code-docs/en/users/features/mcp/>,-<https://qwenlm.github.io/qwen-code-docs/en/users/configuration/settings/>.-##### OpenHumanOpenHuman (tinyhumansai/openhuman) adds servers through the **mcp.json** tabdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex aaef8f8e..a78db935 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -3,7 +3,7 @@For a custom tool, start with the [programmatic memory guide](programmatic-memory.md).It shows direct MCP writes, queries and handoffs without a native hook adapter.-Warp, Kilo Code, Goose, Qwen Code and OpenHuman have no+Warp, Kilo Code, Goose and OpenHuman have no`install-mcp` client; their hand-written recipes are in[`install.md`](install.md#clients-without-an-install-mcp-writer).@@ -907,6 +907,57 @@ capture path; `SessionStart` also fetches pending handoffs.---+## Qwen Code++**Status:** MCP and lifecycle hooks are supported. Managed workstreams and+transcript backfill are not claimed.++**Config file:** `~/.qwen/settings.json` (user). Qwen also accepts a+project-level `.qwen/settings.json`; pass that path with `--config-file`+when wanted. MCP servers live under the root `mcpServers` map; hooks live+under the root `hooks` object of the same file.++```bash+ai-memory install-mcp --client qwen-code --apply \+ --server-url "https://memory.example/mcp" --auth-token "$TOKEN"+ai-memory install-hooks --agent qwen-code --apply \+ --server-url "https://memory.example" --auth-token "$TOKEN"+```++The aliases `qwen` and `qwencode` are accepted by both commands. Qwen Code+uses `httpUrl` (not `url`) for streamable-HTTP MCP endpoints, with `timeout`+in milliseconds. The plain `url` key is the legacy SSE transport; do not mix+them in one entry. Qwen expands `$NAME` and `${NAME}` in every string of+`settings.json`. Existing servers, settings and third-party hooks are+preserved, and applying either command again is a no-op. A token-file+install (every fresh `init`) writes a stdio `ai-memory mcp-bridge+--no-session-id` entry instead of embedding the bearer, so Qwen is a static+client: project-scoped calls still need `workspace` and `project`.++The hook installer registers ten events: `SessionStart`, `UserPromptSubmit`,+`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PreCompact`, `Stop`,+`SessionEnd`, `SubagentStart` and `SubagentStop`. Definitions use an empty+`matcher`, which Qwen treats as match-all. Each command receives Qwen's+Claude-shaped JSON on stdin (`session_id`, `cwd`, `tool_name`, `tool_input`,+`tool_use_id`) and enforces capture exclusions over Qwen's Gemini-like+tools. A pending handoff is printed as `hookSpecificOutput.additionalContext`+on `SessionStart`. Capture-only `SessionStart` and `UserPromptSubmit` events+stay silent so `{}` is never injected into the model context. When the payload+has no `cwd`, the hook uses `QWEN_PROJECT_DIR`.++Qwen fires a real `SessionEnd`, so finished sessions close without+`finalize-session`. There is no `ai-memory run qwen` adapter: Qwen does not+document a stable transcript-store schema and path. Qwen reads `AGENTS.md`+and `QWEN.md`, so the normal ai-memory routing snippet and Agent Skills need+no Qwen-specific instruction file. Restart the CLI session after changing+`~/.qwen/settings.json` so both MCP servers and hooks are reloaded.++Sources: [Qwen Code MCP](https://qwenlm.github.io/qwen-code-docs/en/users/features/mcp/),+[Qwen Code hooks](https://qwenlm.github.io/qwen-code-docs/en/users/features/hooks/),+and [Qwen Code settings](https://qwenlm.github.io/qwen-code-docs/en/users/configuration/settings/).++---+## Antigravity CLI (`agy`)**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported viadiff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex 6da0d8db..f9e2c176 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -56,7 +56,7 @@| Warp | MCP-only (documented) | `url` + `headers` entry in `~/.warp/.mcp.json` or **Settings > Agents > MCP servers**; no documented env-var expansion in headers. No `install-mcp` client and no lifecycle hooks. Documented against Warp v0.2026.10.07.08.29, not yet verified end to end. See [`install.md`](install.md#warp). || Kilo Code | MCP-only (documented) | `type: "remote"` entry under `mcp` in `~/.config/kilo/kilo.jsonc` (shared by the VS Code extension and the CLI), with `"oauth": false` and the bearer header from `{env:AI_MEMORY_AUTH_TOKEN}`. No `install-mcp` client and no lifecycle hooks installed. Documented against Kilo Code 7.8.8, not yet verified end to end. See [`install.md`](install.md#kilo-code). || Goose | MCP-only (documented) | `type: streamable_http` extension (URL key `uri`) in `~/.config/goose/config.yaml`, added with `goose configure`; no documented env-var expansion in headers. No `install-mcp` client and no lifecycle hooks installed. Documented against Goose 1.54.0, not yet verified end to end. See [`install.md`](install.md#goose). |-| Qwen Code | MCP-only (documented) | `httpUrl` entry under `mcpServers` in `~/.qwen/settings.json`; the bearer header reads `${AI_MEMORY_AUTH_TOKEN}`, which Qwen Code expands. No `install-mcp` client and no lifecycle hooks installed. Documented against Qwen Code 0.25.1, not yet verified end to end. See [`install.md`](install.md#qwen-code). |+| Qwen Code | Supported | MCP (`install-mcp --client qwen-code`, aliases `qwen`, `qwencode`) plus lifecycle hooks (`install-hooks --agent qwen-code`) in `~/.qwen/settings.json`. Streamable HTTP uses `httpUrl` (plain `url` is legacy SSE); a token-file install gets a stdio `mcp-bridge` entry. Ten Claude-shaped events including `PostToolUseFailure` and subagent start/stop; native `ai-memory hook` commands (no script bundle) enforce capture exclusions over Qwen's Gemini-like tools (`write_file`, `read_file`, `run_shell_command`, `grep_search`, `glob`). `SessionStart` injects the prior handoff as `hookSpecificOutput.additionalContext`. Qwen fires a real `SessionEnd`, so `finalize-session` is not needed. `setup` detects `~/.qwen`. `ai-memory run qwen` and transcript backfill are not claimed because Qwen does not document a stable transcript-store contract. See [`mcp-install.md`](mcp-install.md#qwen-code). || OpenHuman | MCP-only (documented) | `url` + `headers` entry added in the app's **mcp.json** tab (a view over OpenHuman's server store, not a file on disk); header values are stored write-only. No `install-mcp` client and no lifecycle hooks installed. Documented against OpenHuman 0.64.15, not yet verified end to end. See [`install.md`](install.md#openhuman). || LLM/auth providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, OpenCode (Go and Zen), Cursor Agent CLI (`cursor`), OpenAI-compatible endpoints, and generic OIDC device auth for native hooks. || Embedding providers | Supported | OpenAI, Voyage, Google Gemini, and keyless OpenAI-compatible endpoints such as Ollama, LM Studio, and vLLM. |