Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(qwen): trust only submitted prompt provenance
AkitaOnRails377b1b6307c9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dce0459e..1cfad4f0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,8 +21,11 @@ version in [`docs/changelog/`](docs/changelog/):and subagent start/stop) as native `ai-memory hook` commands with no scriptbundle. `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.+ session. User-prompt capture uses Qwen's provenance-bearing+ `submitted_prompt`, never an automated continuation in `prompt`. Capture+ exclusions cover Qwen's Gemini-like tools. Qwen-only agent backups include+ its settings, both documented global skill roots, `QWEN.md`, and `AGENTS.md`.+ `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/crates/ai-memory-cli/src/commands/backup_agents.rs b/crates/ai-memory-cli/src/commands/backup_agents.rsindex ccb786de..49ae0fd6 100644--- a/crates/ai-memory-cli/src/commands/backup_agents.rs+++ b/crates/ai-memory-cli/src/commands/backup_agents.rs@@ -464,6 +464,20 @@ pub fn discover_assets(".qwen/skills","qwen/skills",)?;+ // `~/.agents/skills` is shared with Codex. Attribute it to Codex+ // when both are selected; a Qwen-only backup must still preserve+ // the shared skills Qwen documents and loads.+ if !filter_agent(AgentKind::Codex) {+ collect_dir_assets(+ &mut assets,+ AgentKind::QwenCode,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &home.join(".agents").join("skills"),+ ".agents/skills",+ "qwen/skills/agents",+ )?;+ }}if want_project {push_if_file(@@ -475,6 +489,19 @@ pub fn discover_assets("QWEN.md","project/QWEN.md",);+ // Qwen also reads AGENTS.md. Codex owns the shared file in a+ // combined backup so the archive remains one-to-one.+ if !filter_agent(AgentKind::Codex) {+ push_if_file(+ &mut assets,+ AgentKind::QwenCode,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join("AGENTS.md"),+ "AGENTS.md",+ "project/qwen/AGENTS.md",+ );+ }}}diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 67b3ba4c..9b8c3410 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -1191,7 +1191,7 @@ where}// Read before any capture rewrite can drop the prompt text.let reload_requested = hook_event == HookEvent::UserPrompt- && ai_memory_hooks::user_prompt_text(&json)+ && ai_memory_hooks::user_prompt_text_for_agent(agent_kind, &json).is_some_and(|prompt| ai_memory_core::compaction_recap::is_reload_request(&prompt));// Antigravity's PreInvocation fires before every model call; only// invocation zero, the start of a user turn, is a boundary.@@ -9345,6 +9345,54 @@ mod tests {assert!(recap_requests(&seen).is_empty(), "{seen:?}");}+ #[tokio::test]+ async fn qwen_ignores_unsubmitted_prompt_for_reload_detection() {+ let tmp = tempfile::tempdir().unwrap();+ let (base, mut requests) = serve_requests("200 OK", "RECAP-BODY").await;+ let mut args = claude_args("user-prompt-submit", &base);+ args.agent = "qwen-code".into();+ let stdout = run_hook(+ &tmp.path().join("data"),+ args,+ serde_json::json!({+ "session_id": "qwen-session",+ "cwd": tmp.path(),+ "prompt": "reload context",+ "submitted_prompt": "keep working"+ }),+ )+ .await;+ assert!(stdout.is_empty());+ let seen = all_requests(&mut requests).await;+ assert!(recap_requests(&seen).is_empty(), "{seen:?}");+ }++ #[tokio::test]+ async fn qwen_submitted_reload_prompt_fetches_a_recap() {+ let tmp = tempfile::tempdir().unwrap();+ let (base, mut requests) = serve_requests("200 OK", "RECAP-BODY").await;+ let mut args = claude_args("user-prompt-submit", &base);+ args.agent = "qwen-code".into();+ let stdout = run_hook(+ &tmp.path().join("data"),+ args,+ serde_json::json!({+ "session_id": "qwen-session",+ "cwd": tmp.path(),+ "prompt": "automated continuation",+ "submitted_prompt": "reload context"+ }),+ )+ .await;+ let envelope: serde_json::Value = serde_json::from_slice(stdout.trim_ascii()).unwrap();+ assert_eq!(+ envelope["hookSpecificOutput"]["additionalContext"],+ "RECAP-BODY"+ );+ let seen = all_requests(&mut requests).await;+ assert_eq!(recap_requests(&seen).len(), 1, "{seen:?}");+ }+#[tokio::test]async fn cursor_running_claude_settings_does_not_fetch_a_recap() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/tests/suite/backup_agents.rs b/crates/ai-memory-cli/tests/suite/backup_agents.rsindex 29b6d7fa..06239bc7 100644--- a/crates/ai-memory-cli/tests/suite/backup_agents.rs+++ b/crates/ai-memory-cli/tests/suite/backup_agents.rs@@ -370,6 +370,89 @@ fn antigravity_backup_round_trips_every_documented_skill_root() {);}+#[test]+fn qwen_backup_round_trips_every_documented_asset() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ let fixtures = [+ (+ home.path().join(".qwen/settings.json"),+ r#"{"mcpServers":{"ai-memory":{"httpUrl":"http://localhost"}}}"#,+ ),+ (+ home.path().join(".qwen/skills/qwen/SKILL.md"),+ "# Qwen skill",+ ),+ (+ home.path().join(".agents/skills/shared/SKILL.md"),+ "# Shared skill",+ ),+ (project.path().join("QWEN.md"), "# Qwen instructions"),+ (project.path().join("AGENTS.md"), "# Shared instructions"),+ ];+ for (path, body) in &fixtures {+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(path, body).unwrap();+ }++ let archive = project.path().join("qwen.tar.gz");+ let backup = command_with_env(home.path(), project.path())+ .args([+ "backup-agents",+ "-o",+ archive.to_str().unwrap(),+ "--agents",+ "qwen-code",+ "--include-secrets",+ ])+ .output()+ .unwrap();+ assert!(+ backup.status.success(),+ "backup failed: {}",+ String::from_utf8_lossy(&backup.stderr)+ );++ let restored_home = tempfile::tempdir().unwrap();+ let restored_project = tempfile::tempdir().unwrap();+ let restore = command_with_env(restored_home.path(), restored_project.path())+ .args([+ "restore-agents",+ "-i",+ archive.to_str().unwrap(),+ "--agents",+ "qwen-code",+ "--apply",+ ])+ .output()+ .unwrap();+ assert!(+ restore.status.success(),+ "restore failed: {}",+ String::from_utf8_lossy(&restore.stderr)+ );++ for (path, body) in [+ (+ restored_home.path().join(".qwen/settings.json"),+ fixtures[0].1,+ ),+ (+ restored_home.path().join(".qwen/skills/qwen/SKILL.md"),+ fixtures[1].1,+ ),+ (+ restored_home.path().join(".agents/skills/shared/SKILL.md"),+ fixtures[2].1,+ ),+ (restored_project.path().join("QWEN.md"), fixtures[3].1),+ (restored_project.path().join("AGENTS.md"), fixtures[4].1),+ ] {+ assert_eq!(fs::read_to_string(path).unwrap(), body);+ }+}+#[test]fn backup_agents_sanitizes_secrets_by_default() {let _guard = cli_test_lock();diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 9c27e51a..84cd8b45 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -67,7 +67,7 @@ pub use json_repair::replace_lone_surrogate_escapes;pub use payload::{HookEnvelope, HookEvent, NOTIFICATION_EXCERPT_MAX_BYTES, POST_COMPACTION_EXCERPT_MAX_BYTES,USER_PROMPT_EXCERPT_MAX_BYTES, agent_from_payload, cap_lifecycle_body_for_client,- hook_payload_context, user_prompt_text,+ hook_payload_context, user_prompt_text, user_prompt_text_for_agent,};pub use recap::RECAP_BUDGET_MIN;pub use router::{diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 2881d44e..65b1ef01 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -515,6 +515,21 @@ pub fn user_prompt_text(raw: &serde_json::Value) -> Option<String> {extract_content(raw, &["prompt", "message", "text"])}+/// The submitted user prompt for a specific harness.+///+/// Qwen's `prompt` field can also contain a continuation or hook-generated+/// prompt. Its optional `submitted_prompt` field is the provenance-bearing+/// value for an actual user submission, so Qwen must never fall back to the+/// generic field.+#[must_use]+pub fn user_prompt_text_for_agent(agent: AgentKind, raw: &serde_json::Value) -> Option<String> {+ if agent == AgentKind::QwenCode {+ extract_content(raw, &["submitted_prompt"])+ } else {+ user_prompt_text(raw)+ }+}+/// Identify the harness from the payload itself when it carries an/// unambiguous vendor marker, overriding the `?agent=` the hook command/// declared.@@ -684,7 +699,7 @@ impl HookEnvelope {} else if matches!(event, HookEvent::PreToolUse | HookEvent::PostToolUse) {legacy_tool_title(event, agent, &raw)} else {- best_title_hint(event, &raw).or_else(|| {+ best_title_hint(event, agent, &raw).or_else(|| {source_event.as_deref().map(|source| extension_title_hint(&raw, source))@@ -699,7 +714,7 @@ impl HookEnvelope {} else if matches!(event, HookEvent::PreToolUse | HookEvent::PostToolUse) {legacy_tool_body(event, agent, &raw)} else {- best_body_excerpt(event, &raw).or_else(|| {+ best_body_excerpt(event, agent, &raw).or_else(|| {source_event.as_deref().and_then(|_| extension_body_excerpt(&raw))@@ -1100,17 +1115,21 @@ fn push_candidates<'a>(out: &mut Vec<&'a serde_json::Value>, value: &'a serde_js}}-fn best_title_hint(event: HookEvent, raw: &serde_json::Value) -> Option<String> {+fn best_title_hint(event: HookEvent, agent: AgentKind, raw: &serde_json::Value) -> Option<String> {match event {HookEvent::SessionStart => extract_string(raw, &["model", "title"]).and_then(first_line),HookEvent::UserPrompt => {// Kimi Code sends `prompt` as content blocks// (`[{"type":"text","text":...}]`); `extract_content` flattens// them and returns identical values for plain-string agents.- extract_content(raw, &["prompt", "message", "text"])+ user_prompt_text_for_agent(agent, raw).or_else(|| {- raw.pointer("/userPromptSubmit/prompt")- .and_then(value_to_text)+ (agent != AgentKind::QwenCode)+ .then(|| {+ raw.pointer("/userPromptSubmit/prompt")+ .and_then(value_to_text)+ })+ .flatten()}).and_then(first_line)}@@ -1197,14 +1216,20 @@ fn value_to_text(value: &serde_json::Value) -> Option<String> {}}-fn best_body_excerpt(event: HookEvent, raw: &serde_json::Value) -> Option<String> {+fn best_body_excerpt(+ event: HookEvent,+ agent: AgentKind,+ raw: &serde_json::Value,+) -> Option<String> {match event {- HookEvent::UserPrompt => {- extract_content(raw, &["prompt", "message", "text"]).or_else(|| {- raw.pointer("/userPromptSubmit/prompt")- .and_then(value_to_text)- })- }+ HookEvent::UserPrompt => user_prompt_text_for_agent(agent, raw).or_else(|| {+ (agent != AgentKind::QwenCode)+ .then(|| {+ raw.pointer("/userPromptSubmit/prompt")+ .and_then(value_to_text)+ })+ .flatten()+ }),HookEvent::PostToolUse => {let tool = extract_string(raw, &["tool", "tool_name", "name"]).or_else(|| extract_string_path(raw, &[&["toolCall", "name"]]))@@ -3370,6 +3395,41 @@ mod tests {assert_eq!(env.body_excerpt.as_deref(), Some("MARKER_PROMPT_789"));}+ #[test]+ fn qwen_user_prompt_uses_only_submission_provenance() {+ let query = HookQuery {+ event: "user-prompt-submit".into(),+ agent: Some("qwen-code".into()),+ ..Default::default()+ };+ let envelope = HookEnvelope::from_query_and_body(+ query.clone(),+ serde_json::json!({+ "session_id": "qwen-session",+ "prompt": "AUTOMATED_CONTINUATION_MUST_NOT_BE_CAPTURED",+ "submitted_prompt": "MARKER_QWEN_USER_PROMPT"+ }),+ );+ assert_eq!(+ envelope.title_hint.as_deref(),+ Some("MARKER_QWEN_USER_PROMPT")+ );+ assert_eq!(+ envelope.body_excerpt.as_deref(),+ Some("MARKER_QWEN_USER_PROMPT")+ );++ let automated = HookEnvelope::from_query_and_body(+ query,+ serde_json::json!({+ "session_id": "qwen-session",+ "prompt": "AUTOMATED_CONTINUATION_MUST_NOT_BE_CAPTURED"+ }),+ );+ assert!(automated.title_hint.is_none());+ assert!(automated.body_excerpt.is_none());+ }+// Native fields and canonical tool names follow Codex rust-v0.154.0's// pre/post-tool-use schemas. `tool_response` accepts any JSON value.#[test]diff --git a/docs/install.md b/docs/install.mdindex 22959635..0df32457 100644--- a/docs/install.md+++ b/docs/install.md@@ -1629,7 +1629,9 @@ there is no script bundle. Ten events are wired: `SessionStart`,fires it instead of `PostToolUse` when a tool throws), `PreCompact`, `Stop`,`SessionEnd`, `SubagentStart` and `SubagentStop`. Capture exclusions apply toQwen's Gemini-like tools (`write_file`, `read_file`, `run_shell_command`,-`grep_search`, `glob`).+`grep_search`, `glob`). User-prompt capture uses only Qwen's+provenance-bearing `submitted_prompt`; automated continuation or retry content+that appears only in `prompt` is not stored or interpreted as a reload request.The `SessionStart` hook delivers the prior session's handoff through`hookSpecificOutput.additionalContext`. With nothing to deliver, `SessionStart`@@ -1642,7 +1644,9 @@ handoff; the baton stays open for `memory_handoff_accept`. Qwen fires a real`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+`QWEN.md`; a Qwen-only `backup-agents` run preserves both files,+`~/.qwen/settings.json`, `~/.qwen/skills`, and shared `~/.agents/skills`.+Managed `ai-memory run qwen` resume is not supported because Qwendoes not document a stable native transcript store. Start a new Qwen sessionafter installing so it reloads `settings.json`. See [the Qwen Code MCP andhook details](mcp-install.md#qwen-code).diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex a78db935..4492f74e 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -940,10 +940,13 @@ The hook installer registers ten events: `SessionStart`, `UserPromptSubmit`,`matcher`, which Qwen treats as match-all. Each command receives Qwen'sClaude-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`.+tools. For `UserPromptSubmit`, ai-memory captures only Qwen's optional+`submitted_prompt`, which identifies an actual user submission; it does not+fall back to the generic `prompt` field used by continuation and retry paths.+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 notdiff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex f9e2c176..b8cf4a30 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 | 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). |+| 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`). User prompts come only from the provenance-bearing `submitted_prompt`, not continuation/retry `prompt` content. `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. |