Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(agents): add Devin as a first-class supported agent
zapatald0021e9dda3d
diff --git a/.gitignore b/.gitignoreindex a17aab5b..68921328 100644--- a/.gitignore+++ b/.gitignore@@ -36,3 +36,6 @@ evals/runs/# ai-memory atomic-write backups (apply_atomic in apply_shared.rs)*.bak-*++# SonarQube scanner working directory.+.scannerwork/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b6560a4c..b7adf504 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0audited, scoped to the handoff's workspace/project with a NULL author bydesign — handoffs are agent/session-keyed, not owned by a DB user([#179]).+- Devin CLI is now a supported MCP + lifecycle-hook integration. `install-mcp+ --client devin` writes Devin's `mcpServers` config, `install-hooks --agent+ devin` writes Devin lifecycle hooks, `setup-agent --agent devin` emits+ host-copyable hook snippets, and `uninstall` removes only ai-memory-owned+ Devin entries. Devin hook capture covers `SessionStart`,+ `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostCompaction`, `Stop`,+ and `SessionEnd`; `PostCompaction` is stored as a dedicated observation kind+ and captures Devin's `summary` field. Devin does not expose subagent hook+ events, so subagent capture is not installed for Devin.+- Managed Agent Skills can now target Devin: project installs use+ `.devin/skills`; global installs use `%APPDATA%\devin\skills` on Windows and+ `~/.devin/skills` elsewhere.+- The store migration set now admits `devin` as a persisted+ `sessions.agent_kind`, preserving the same workspace/project invariants as+ the other supported agents.++### Fixed+- `install-mcp` and `install-hooks` now honor an explicit `--server-url` even+ when it matches the compiled default. Previously that value was+ indistinguishable from "flag omitted" and could be overridden by+ `AI_MEMORY_SERVER_URL`, which could write config for the wrong local server.+- Devin hook capture now derives `cwd` when the native payload omits it:+ payload `cwd` still wins, followed by `DEVIN_PROJECT_DIR`, then the hook+ process working directory. This keeps real Devin `SessionStart` /+ `PostToolUse` fixtures routable without inventing a payload field.## [1.12.0] - 2026-07-12@@ -257,7 +282,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0'{{.SecurityOptions}}'` and runs as `-u 0:0` for just the commands thatwrite host-side files; thin-client commands (`status`, `bootstrap`, …)are unaffected since they only touch the `/data` named volume.-## [1.8.0] - 2026-07-04### Addeddiff --git a/README.md b/README.mdindex 8c524168..66f48483 100644--- a/README.md+++ b/README.md@@ -24,6 +24,7 @@| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Claude Code uses Claude exec form with a real native `ai-memory.exe` by default; other script-hook agents use the current PowerShell defaults pending harness feedback. See [`docs/windows.md`](docs/windows.md). || Claude Code | Supported | MCP config + lifecycle hooks. || Codex | Supported | MCP config + lifecycle hooks; no automatic true session-end hook, so run `ai-memory finalize-session` when you need a final summary/handoff. |+| Devin CLI | Supported | MCP config + lifecycle hooks. Hooks use Devin's `PostCompaction` event, inject handoffs via `hookSpecificOutput.additionalContext`, and omit subagent events because Devin does not expose them. || OpenCode | Supported | Remote MCP config + generated TypeScript plugin. || Cursor | Supported | MCP config + lifecycle hooks. || Gemini CLI | Supported | MCP config + lifecycle hooks. |@@ -90,7 +91,7 @@ priors are at the [bottom](#influences-and-prior-art).project list, folder tree, FTS5 search, markdown rendering, darkmode. Mounted on the same axum server as MCP.- **Multi-agent + multi-machine ready.** Supported clients: Claude- Code, Codex, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),+ Code, Codex, Devin CLI, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),Gemini CLI, Antigravity CLI, Grok Build CLI, OpenClaw, Oh My Pi / OMP(`omp` / `oh-my-pi`), Pi via generated bridge extension, and VS Code GitHubCopilot agent mode@@ -225,8 +226,8 @@ packaged unit. Full user-service, system-service, auth, and provider setup is in### Docker-You need: Docker + an agent CLI (Claude Code, Codex, OpenCode, OMP, Cursor,-Antigravity CLI, Grok Build CLI, or anything else that speaks MCP).+You need: Docker + an agent CLI (Claude Code, Codex, Devin CLI, OpenCode, OMP,+Cursor, Antigravity CLI, Grok Build CLI, or anything else that speaks MCP).The published Docker image includes `linux/amd64` and `linux/arm64` variants,so Apple Silicon Macs and ARM64 Linux hosts can pull `akitaonrails/ai-memory`@@ -268,7 +269,7 @@ docker run -d --name ai-memory \# 3. Wire your agent CLI in two commands. The wrapper takes care of# mounts + auto-detecting ~/.claude/settings.json. Re-run with-# `--agent codex`, `--agent opencode`, `--agent gemini-cli`,+# `--agent codex`, `--agent devin`, `--agent opencode`, `--agent gemini-cli`,# `--agent omp`, `--agent oh-my-pi`, `--client cursor`,# `--client gemini-cli`, etc.# for additional agents; full list in docs/install.md.@@ -340,8 +341,9 @@ one matching entry.projects) when you want new tool guidance. The refresh writes the slimmarkered snippet and managed Agent Skills from the same binary-owned assets.-For Codex, OpenCode, OMP, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI,-Grok Build CLI, OpenClaw, VS Code Copilot, curl-based hook installs, source builds,+For Codex, Devin CLI, OpenCode, OMP, Cursor, Claude Desktop, Gemini CLI,+Antigravity CLI, Grok Build CLI, OpenClaw, VS Code Copilot,+curl-based hook installs, source builds,CLI env vars, and the full subcommand reference, see [`docs/install.md`](docs/install.md).## Securitydiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 1ccb3c90..a105dfc5 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -481,6 +481,8 @@ pub enum InstallSkillsAgent {ClaudeCode,/// Cross-agent `.agents/skills` directory.Agents,+ /// Devin's `.devin/skills` directory.+ Devin,/// Install into both Claude Code and `.agents` skill directories.Both,}@@ -825,6 +827,12 @@ pub enum AgentChoice {/// handoff injection does not — recover the prior session's handoff/// via the MCP `memory_handoff_accept` tool.Zero,+ /// Devin CLI — JSON-config hooks in+ /// `~/.devin/hooks.v1.json` or `~/.devin/config.json` hooks key.+ /// Native `ai-memory hook --event` integration using Devin-specific+ /// hook scripts. Devin consumes the handoff via+ /// `hookSpecificOutput.additionalContext` on `SessionStart`.+ Devin,}impl AgentChoice {@@ -848,6 +856,7 @@ impl AgentChoice {Self::AntigravityCli => AgentKind::AntigravityCli,Self::Grok => AgentKind::Grok,Self::Zero => AgentKind::Zero,+ Self::Devin => AgentKind::Devin,}}@@ -922,6 +931,8 @@ pub enum McpClient {/// Zero coding agent (Gitlawb/zero) — `~/.config/zero/config.json`,/// `mcp.servers` map with native HTTP transport + bearer headers.Zero,+ /// Devin CLI — `~/.devin/config.json`.+ Devin,/// VS Code GitHub Copilot (agent mode) — per-workspace/// `.vscode/mcp.json`. Copilot's agent mode reads MCP servers/// from VS Code's own MCP framework (top-level `servers` key),@@ -1246,8 +1257,15 @@ pub struct InstallHooksArgs {/// `server_url` / AI_MEMORY_SERVER_URL when set, else loopback. If neither/// is configured, apply-mode also reuses an existing ai-memory MCP entry/// for the same agent when one is present.- #[arg(long, default_value_t = crate::config::DEFAULT_SERVER_URL.to_string())]- pub server_url: String,+ ///+ /// `Option` (no `default_value_t`) is deliberate: it lets+ /// `effective_hook_server_url` distinguish "not passed" from "passed+ /// and happens to equal the compiled default" — a plain `String` with+ /// a default can't tell those apart, which let `AI_MEMORY_SERVER_URL`+ /// silently override an explicit `--server-url <default>` (found+ /// 2026-07-12 during Devin real-acceptance A/B testing).+ #[arg(long)]+ pub server_url: Option<String>,/// Bearer token to embed in the hook config's `env` block. When/// set, every hook call carries `Authorization: Bearer <token>`,/// matching what the server requires when AI_MEMORY_AUTH_TOKEN@@ -1297,7 +1315,7 @@ pub struct InstallHooksArgs {}/// Arguments for `install-mcp`.-#[derive(Debug, Args)]+#[derive(Debug, Clone, Args)]pub struct InstallMcpArgs {/// Which MCP client to render configuration for.#[arg(long, value_enum, default_value_t = McpClient::ClaudeCode)]@@ -1305,8 +1323,11 @@ pub struct InstallMcpArgs {/// MCP HTTP endpoint URL the client should connect to. Defaults to the/// configured `server_url` / AI_MEMORY_SERVER_URL plus `/mcp` when set,/// else loopback.- #[arg(long, default_value_t = crate::config::DEFAULT_MCP_URL.to_string())]- pub server_url: String,+ ///+ /// `Option` (no `default_value_t`) is deliberate: see the matching+ /// comment on `InstallHooksArgs::server_url` — same bug, same fix.+ #[arg(long)]+ pub server_url: Option<String>,/// Friendly name the client should show for this server entry.#[arg(long, default_value = "ai-memory")]pub name: String,@@ -1731,6 +1752,23 @@ mod tests {assert!(matches!(hook_args.agent, AgentChoice::Grok));}+ #[test]+ fn devin_hook_agent_parses() {+ let hook_cli = Cli::try_parse_from([+ "ai-memory",+ "install-hooks",+ "--agent",+ "devin",+ "--server-url",+ "http://example.test:49374",+ ])+ .unwrap_or_else(|e| panic!("failed to parse install-hooks --agent devin: {e}"));+ let Command::InstallHooks(hook_args) = hook_cli.command else {+ panic!("expected install-hooks command for devin");+ };+ assert!(matches!(hook_args.agent, AgentChoice::Devin));+ }+#[test]fn install_hooks_project_strategy_repo_root_parses() {let cli = Cli::try_parse_from([diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 2881eff6..a967fbb9 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -11,16 +11,20 @@//!//! See `docs/windows.md#native-hook-command-claude-code-on-windows`.+use std::fs;use std::io::Read;use std::path::{Path, PathBuf};use std::time::Duration;-use ai_memory_core::AgentKind;+use ai_memory_core::{AgentKind, SessionId};use ai_memory_llm::OidcToken;use crate::cli::HookArgs;-use super::hook_capture::{build_client, extract_cwd, get_handoff, marker_query_suffix};+use super::hook_capture::{+ build_client, extract_cwd, get_handoff, marker_query_suffix, resolve_cwd_with_fallbacks,+ url_encode,+};use super::hook_drain_process;use super::hook_spool;use super::path_util::strip_windows_verbatim_prefix;@@ -119,6 +123,100 @@ fn should_spawn_background_drainer(event: &str) -> bool {matches!(event, "session-end" | "stop" | "pre-compact")}+fn session_id_state_path(data_dir: &Path, agent: AgentKind) -> PathBuf {+ data_dir+ .join("hook-state")+ .join(format!("{}-session-id", agent.as_str()))+}++fn stored_session_id(data_dir: &Path, agent: AgentKind) -> Option<String> {+ let path = session_id_state_path(data_dir, agent);+ let raw = fs::read_to_string(path).ok()?;+ let trimmed = raw.trim();+ (!trimmed.is_empty()).then(|| trimmed.to_owned())+}++fn store_session_id(data_dir: &Path, agent: AgentKind, session_id: &str) {+ let path = session_id_state_path(data_dir, agent);+ if let Some(parent) = path.parent() {+ let _ = fs::create_dir_all(parent);+ }+ let _ = fs::write(path, session_id);+}++fn clear_session_id(data_dir: &Path, agent: AgentKind) {+ let _ = fs::remove_file(session_id_state_path(data_dir, agent));+}++fn fresh_session_id(data_dir: &Path, agent: AgentKind) -> String {+ let session_id = SessionId::new().to_string();+ store_session_id(data_dir, agent, &session_id);+ session_id+}++fn payload_has_session_id(raw: &serde_json::Value) -> bool {+ [+ "session_id",+ "sessionId",+ "sessionID",+ "session",+ "conversationId",+ ]+ .iter()+ .any(|key| {+ raw.get(*key)+ .and_then(serde_json::Value::as_str)+ .is_some_and(|value| !value.trim().is_empty())+ })+}++fn session_id_query_suffix(+ data_dir: &Path,+ agent: &str,+ event: &str,+ raw: &serde_json::Value,+) -> String {+ let agent_kind = AgentKind::from_wire(agent);+ if agent_kind != AgentKind::Devin || payload_has_session_id(raw) {+ return String::new();+ }++ let session_id = if event == "session-start" {+ fresh_session_id(data_dir, agent_kind)+ } else {+ stored_session_id(data_dir, agent_kind)+ .unwrap_or_else(|| fresh_session_id(data_dir, agent_kind))+ };+ format!("&session_id={}", url_encode(&session_id))+}++fn cwd_query_suffix_with(+ agent: &str,+ raw: &serde_json::Value,+ default_strategy: Option<&str>,+ env_lookup: impl FnMut(&str) -> Option<String>,+ current_dir: impl FnOnce() -> Option<PathBuf>,+) -> String {+ let agent_kind = AgentKind::from_wire(agent);+ let cwd = if agent_kind == AgentKind::Devin {+ resolve_cwd_with_fallbacks(raw, env_lookup, current_dir)+ } else {+ extract_cwd(raw).filter(|s| !s.trim().is_empty())+ };+ cwd.map(|cwd| marker_query_suffix(&cwd, default_strategy))+ .unwrap_or_default()+}++fn cwd_query_suffix(+ agent: &str,+ raw: &serde_json::Value,+ default_strategy: Option<&str>,+) -> String {+ cwd_query_suffix_with(agent, raw, default_strategy, env_lookup, || {+ std::env::current_dir().ok()+ })+}+fn after_background_drain_event_enqueue(data_dir: &Path,spawn: impl FnOnce(&Path) -> std::io::Result<()>,@@ -204,12 +302,16 @@ where{let json: serde_json::Value = serde_json::from_str(&payload).unwrap_or(serde_json::Value::Null);- let qs = extract_cwd(&json)- .map(|cwd| marker_query_suffix(&cwd, args.project_strategy.and_then(|s| s.baked())))- .unwrap_or_default();+ let qs = cwd_query_suffix(+ &args.agent,+ &json,+ args.project_strategy.and_then(|s| s.baked()),+ );let base = args.server_url.trim_end_matches('/');let dd = resolve_data_dir(data_dir.as_deref());let spool = hook_spool::spool_dir(&dd);+ let session_qs = session_id_query_suffix(&dd, &args.agent, &args.event, &json);+ let hook_qs = format!("{qs}{session_qs}");// Spool THIS event — an instant local write, never the network. The auth// mode is decided without a round-trip: an explicit `--auth-token` is@@ -220,7 +322,10 @@ where.ok().flatten().is_some();- let event_url = format!("{base}/hook?event={}&agent={}{qs}", args.event, args.agent);+ let event_url = format!(+ "{base}/hook?event={}&agent={}{}",+ args.event, args.agent, hook_qs+ );let entry = hook_spool::entry_for(event_url,payload.clone(),@@ -232,6 +337,9 @@ where"ai-memory hook warning: failed to spool lifecycle event; capture for this event was skipped");}+ if AgentKind::from_wire(&args.agent) == AgentKind::Devin && args.event == "session-end" {+ clear_session_id(&dd, AgentKind::Devin);+ }// Mid-session catch-up: per-event hooks only enqueue, so a heavy session// outpaces the boundary-only drain and the spool grows until the next@@ -328,6 +436,37 @@ fn resolve_data_dir(data_dir: Option<&Path>) -> PathBuf {mod tests {use super::*;+ fn devin_hook_args(event: &str) -> HookArgs {+ HookArgs {+ event: event.into(),+ agent: "devin".into(),+ server_url: "http://127.0.0.1:1".into(),+ auth_token: None,+ project_strategy: None,+ }+ }++ fn read_spooled_entries(spool: &Path) -> Vec<hook_spool::SpoolEntry> {+ let mut entries = std::fs::read_dir(spool)+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("json"))+ .collect::<Vec<_>>();+ entries.sort();+ entries+ .into_iter()+ .map(|path| serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap())+ .collect()+ }++ fn query_param<'a>(url: &'a str, key: &str) -> Option<&'a str> {+ url.split('?')+ .nth(1)?+ .split('&')+ .filter_map(|part| part.split_once('='))+ .find_map(|(name, value)| (name == key).then_some(value))+ }+#[test]fn resolve_data_dir_strips_verbatim_prefix_from_baked_arg() {// Recover safe verbatim data dirs baked by older installs (#116).@@ -446,6 +585,320 @@ mod tests {);}+ #[test]+ fn devin_query_session_id_is_stable_across_payloads_without_native_id() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path();+ let session_start = serde_json::json!({+ "hook_event_name": "SessionStart",+ "source": "startup"+ });+ let post_tool_use = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "tool_name": "exec",+ "tool_input": {"command": "ls"},+ "tool_use_id": "call_c101a272288d400b831e1498",+ "tool_response": {"success": true, "output": "ok", "error": null}+ });++ let first = session_id_query_suffix(data_dir, "devin", "session-start", &session_start);+ let second = session_id_query_suffix(data_dir, "devin", "post-tool-use", &post_tool_use);++ assert!(first.starts_with("&session_id="), "{first}");+ assert_eq!(second, first);+ assert_eq!(+ stored_session_id(data_dir, AgentKind::Devin).as_deref(),+ first.strip_prefix("&session_id=")+ );+ }++ #[tokio::test]+ async fn devin_session_start_real_fixture_without_session_id_or_cwd_is_accepted() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().to_path_buf();+ let spool = hook_spool::spool_dir(&data_dir);+ let mut stdout = Vec::new();+ let payload = serde_json::json!({+ "hook_event_name": "SessionStart",+ "source": "startup"+ });++ run_with_payload(+ Some(data_dir),+ devin_hook_args("session-start"),+ payload.to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"{}\n");+ let entries = read_spooled_entries(&spool);+ assert_eq!(entries.len(), 1);+ assert!(entries[0].url.contains("event=session-start"));+ assert!(entries[0].url.contains("agent=devin"));+ assert!(+ query_param(&entries[0].url, "session_id").is_some(),+ "{}",+ entries[0].url+ );+ assert!(+ query_param(&entries[0].url, "cwd").is_some(),+ "{}",+ entries[0].url+ );+ }++ #[tokio::test]+ async fn devin_post_tool_use_real_fixture_without_session_id_or_cwd_is_accepted() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().to_path_buf();+ let spool = hook_spool::spool_dir(&data_dir);+ let mut stdout = Vec::new();+ let payload = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "tool_name": "exec",+ "tool_input": {"command": "ls"},+ "tool_use_id": "call_c101a272288d400b831e1498",+ "tool_response": {"success": true, "output": "ok", "error": null}+ });++ run_with_payload(+ Some(data_dir),+ devin_hook_args("post-tool-use"),+ payload.to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"{}\n");+ let entries = read_spooled_entries(&spool);+ assert_eq!(entries.len(), 1);+ assert!(entries[0].url.contains("event=post-tool-use"));+ assert!(entries[0].url.contains("agent=devin"));+ assert!(+ query_param(&entries[0].url, "session_id").is_some(),+ "{}",+ entries[0].url+ );+ assert!(+ query_param(&entries[0].url, "cwd").is_some(),+ "{}",+ entries[0].url+ );+ }++ #[tokio::test]+ async fn devin_events_share_session_id_when_payload_omits_it() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().to_path_buf();+ let spool = hook_spool::spool_dir(&data_dir);+ let mut stdout = Vec::new();++ run_with_payload(+ Some(data_dir.clone()),+ devin_hook_args("session-start"),+ serde_json::json!({+ "hook_event_name": "SessionStart",+ "source": "startup"+ })+ .to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();+ run_with_payload(+ Some(data_dir),+ devin_hook_args("post-tool-use"),+ serde_json::json!({+ "hook_event_name": "PostToolUse",+ "tool_name": "exec",+ "tool_input": {"command": "ls"},+ "tool_use_id": "call_c101a272288d400b831e1498",+ "tool_response": {"success": true, "output": "ok", "error": null}+ })+ .to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();++ let entries = read_spooled_entries(&spool);+ assert_eq!(entries.len(), 2);+ let first = query_param(&entries[0].url, "session_id").unwrap();+ let second = query_param(&entries[1].url, "session_id").unwrap();+ assert_eq!(first, second);+ }++ #[test]+ fn devin_query_session_id_does_not_override_native_payload_id() {+ let tmp = tempfile::tempdir().unwrap();+ let with_session = serde_json::json!({+ "session_id": "native-session",+ "hook_event_name": "PostToolUse"+ });++ let suffix = session_id_query_suffix(tmp.path(), "devin", "post-tool-use", &with_session);++ assert!(suffix.is_empty());+ assert!(stored_session_id(tmp.path(), AgentKind::Devin).is_none());+ }++ #[test]+ fn session_id_query_suffix_is_devin_only() {+ let tmp = tempfile::tempdir().unwrap();+ let raw = serde_json::json!({"hook_event_name": "PostToolUse"});++ let suffix = session_id_query_suffix(tmp.path(), "claude-code", "post-tool-use", &raw);++ assert!(suffix.is_empty());+ assert!(stored_session_id(tmp.path(), AgentKind::ClaudeCode).is_none());+ }++ #[test]+ fn devin_missing_cwd_uses_devin_project_dir_before_process_cwd() {+ let raw = serde_json::json!({+ "hook_event_name": "SessionStart",+ "source": "startup"+ });++ let suffix = cwd_query_suffix_with(+ "devin",+ &raw,+ None,+ |name| (name == "DEVIN_PROJECT_DIR").then(|| "env-project".into()),+ || Some(PathBuf::from("process-project")),+ );++ assert_eq!(suffix, "&cwd=env-project");+ }++ #[test]+ fn devin_missing_cwd_uses_process_cwd_when_env_is_missing() {+ let raw = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "tool_name": "exec"+ });++ let suffix = cwd_query_suffix_with(+ "devin",+ &raw,+ None,+ |_| None,+ || Some(PathBuf::from("process-project")),+ );++ assert_eq!(suffix, "&cwd=process-project");+ }++ #[test]+ fn devin_missing_cwd_uses_env_or_process_cwd() {+ let raw = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "tool_name": "exec"+ });++ let from_env = cwd_query_suffix_with(+ "devin",+ &raw,+ None,+ |name| (name == "DEVIN_PROJECT_DIR").then(|| "env-project".into()),+ || Some(PathBuf::from("process-project")),+ );+ let from_process = cwd_query_suffix_with(+ "devin",+ &raw,+ None,+ |_| None,+ || Some(PathBuf::from("process-project")),+ );++ assert_eq!(from_env, "&cwd=env-project");+ assert_eq!(from_process, "&cwd=process-project");+ }++ #[test]+ fn devin_payload_cwd_wins_over_fallbacks() {+ let raw = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "cwd": "payload-project"+ });++ let suffix = cwd_query_suffix_with(+ "devin",+ &raw,+ None,+ |name| (name == "DEVIN_PROJECT_DIR").then(|| "env-project".into()),+ || Some(PathBuf::from("process-project")),+ );++ assert_eq!(suffix, "&cwd=payload-project");+ }++ #[test]+ fn missing_cwd_process_fallback_is_devin_only() {+ let raw = serde_json::json!({"hook_event_name": "PostToolUse"});++ let suffix = cwd_query_suffix_with(+ "claude-code",+ &raw,+ None,+ |_| Some("env-project".into()),+ || Some(PathBuf::from("process-project")),+ );++ assert!(suffix.is_empty());+ }++ #[tokio::test]+ async fn devin_post_compaction_summary_without_payload_cwd_uses_same_session() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().to_path_buf();+ let spool = hook_spool::spool_dir(&data_dir);+ let summary = "Context compacted: 15000/20000 tokens used";+ let mut stdout = Vec::new();++ run_with_payload(+ Some(data_dir.clone()),+ devin_hook_args("session-start"),+ serde_json::json!({+ "hook_event_name": "SessionStart",+ "source": "startup"+ })+ .to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();+ run_with_payload(+ Some(data_dir),+ devin_hook_args("post-compaction"),+ serde_json::json!({+ "hook_event_name": "PostCompaction",+ "summary": summary+ })+ .to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();++ let entries = read_spooled_entries(&spool);+ assert_eq!(entries.len(), 2);+ let first = query_param(&entries[0].url, "session_id").unwrap();+ let second = query_param(&entries[1].url, "session_id").unwrap();+ assert_eq!(first, second);+ assert!(query_param(&entries[1].url, "cwd").is_some());+ assert!(entries[1].body.contains(summary));+ }+#[tokio::test]async fn session_end_run_enqueues_outputs_empty_json_and_spawns_after_enqueue() {let tmp = tempfile::tempdir().unwrap();@@ -550,6 +1003,47 @@ mod tests {assert_eq!(hook_spool::spool_len(&spool), 1);}+ #[tokio::test]+ async fn devin_session_end_spools_stored_session_id_then_clears_state() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().to_path_buf();+ let spool = hook_spool::spool_dir(&data_dir);+ store_session_id(&data_dir, AgentKind::Devin, "stable-devin-session");+ let mut stdout = Vec::new();+ let args = HookArgs {+ event: "session-end".into(),+ agent: "devin".into(),+ server_url: "http://127.0.0.1:1".into(),+ auth_token: None,+ project_strategy: None,+ };++ run_with_payload(+ Some(data_dir.clone()),+ args,+ r#"{"hook_event_name":"SessionEnd"}"#.into(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"{}\n");+ assert!(stored_session_id(&data_dir, AgentKind::Devin).is_none());+ let entries: Vec<_> = std::fs::read_dir(&spool)+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .collect();+ assert_eq!(entries.len(), 1);+ let entry: hook_spool::SpoolEntry =+ serde_json::from_slice(&std::fs::read(&entries[0]).unwrap()).unwrap();+ assert!(+ entry.url.contains("&session_id=stable-devin-session"),+ "{}",+ entry.url+ );+ }+#[test]fn session_end_spawn_failure_is_returned_for_warning_only() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 875ebf18..33d8dac1 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -21,6 +21,32 @@ pub fn extract_cwd(payload: &serde_json::Value) -> Option<String> {.map(str::to_owned)}+fn non_empty(value: Option<String>) -> Option<String> {+ value.filter(|s| !s.trim().is_empty())+}++/// Resolve the cwd for hook bridges whose native payload may omit it.+///+/// Ordered fallback:+///+/// 1. `cwd` in the payload, if present.+/// 2. `DEVIN_PROJECT_DIR`, when the launcher provides it.+/// 3. The native hook process current directory.+pub fn resolve_cwd_with_fallbacks(+ payload: &serde_json::Value,+ mut env_lookup: impl FnMut(&str) -> Option<String>,+ current_dir: impl FnOnce() -> Option<PathBuf>,+) -> Option<String> {+ non_empty(extract_cwd(payload))+ .or_else(|| non_empty(env_lookup("DEVIN_PROJECT_DIR")))+ .or_else(|| {+ current_dir().and_then(|path| {+ let cwd = path.to_string_lossy().into_owned();+ non_empty(Some(cwd))+ })+ })+}+/// URL-encode the reserved characters `ai_memory_url_encode` handles.pub fn url_encode(s: &str) -> String {let mut out = String::with_capacity(s.len());@@ -419,6 +445,42 @@ mod tests {assert_eq!(extract_cwd(&p), None);}+ #[test]+ fn resolve_cwd_prefers_payload_over_env_and_process_cwd() {+ let p: serde_json::Value = serde_json::from_str(r#"{"cwd":"/payload"}"#).unwrap();++ let cwd = resolve_cwd_with_fallbacks(+ &p,+ |_| Some("/env".into()),+ || Some(PathBuf::from("/process")),+ );++ assert_eq!(cwd.as_deref(), Some("/payload"));+ }++ #[test]+ fn resolve_cwd_uses_devin_project_dir_when_payload_omits_cwd() {+ let p: serde_json::Value = serde_json::from_str(r#"{"source":"startup"}"#).unwrap();++ let cwd = resolve_cwd_with_fallbacks(+ &p,+ |name| (name == "DEVIN_PROJECT_DIR").then(|| "/env-project".into()),+ || Some(PathBuf::from("/process")),+ );++ assert_eq!(cwd.as_deref(), Some("/env-project"));+ }++ #[test]+ fn resolve_cwd_uses_process_cwd_when_payload_and_env_omit_cwd() {+ let p: serde_json::Value = serde_json::from_str(r#"{"source":"startup"}"#).unwrap();++ let cwd =+ resolve_cwd_with_fallbacks(&p, |_| None, || Some(PathBuf::from("process-project")));++ assert_eq!(cwd.as_deref(), Some("process-project"));+ }+#[test]fn query_suffix_without_marker_has_only_cwd() {let qs = marker_query_suffix("/nonexistent/path/xyz", None);diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 941a7e7a..19706017 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -27,9 +27,9 @@ use crate::commands::path_util::home_dir;use crate::commands::render_shared::{ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,GEMINI_PROFILE, build_antigravity_payload_with_data_dir,- build_claude_code_payload_with_data_dir, build_grok_payload_with_data_dir,- build_profile_payload_for_agent, hook_script_for_claude_code, hook_script_for_current_platform,- ts_string_literal,+ build_claude_code_payload_with_data_dir, build_devin_payload_with_data_dir,+ build_grok_payload_with_data_dir, build_profile_payload_for_agent, hook_script_for_claude_code,+ hook_script_for_current_platform, ts_string_literal,};use crate::config::{Config, DEFAULT_SERVER_URL};@@ -95,6 +95,22 @@ pub(crate) fn zero_hooks_path() -> anyhow::Result<std::path::PathBuf> {.join("hooks.json"))}+/// `~/.devin/hooks.v1.json` — Devin CLI lifecycle hooks (default target).+pub(crate) fn devin_hooks_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(home_dir()+ .context("could not locate $HOME for ~/.devin/hooks.v1.json")?+ .join(".devin")+ .join("hooks.v1.json"))+}++/// `~/.devin/config.json` — Devin CLI lifecycle hooks (alternative target under `hooks` key).+pub(crate) fn devin_config_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(home_dir()+ .context("could not locate $HOME for ~/.devin/config.json")?+ .join(".devin")+ .join("config.json"))+}+/// `~/.config/opencode/plugins/ai-memory.ts` — OpenCode's plugin file.pub(crate) fn opencode_plugin_path() -> anyhow::Result<std::path::PathBuf> {Ok(home_dir()@@ -130,7 +146,7 @@ pub(crate) fn pi_extension_path() -> anyhow::Result<std::path::PathBuf> {/// # Errors/// Returns an error if the hook script directory cannot be located.pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {- let inferred = if args.server_url == DEFAULT_SERVER_URL {+ let inferred = if args.server_url.is_none() {infer_installed_mcp_config(args.agent)} else {None@@ -196,6 +212,10 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {apply_to_grok_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)}AgentChoice::Zero => apply_to_zero_hooks(&server_url, auth, &config.data_dir, &args),+ AgentChoice::Devin => {+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ apply_to_devin_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)+ }AgentChoice::Openclaw => openclaw_plugin::apply(&server_url, auth, &args),};}@@ -257,6 +277,10 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {render_grok(&hooks_dir, &server_url, auth, &config.data_dir, strategy)}AgentChoice::Zero => render_zero(&server_url, auth, &config.data_dir, strategy),+ AgentChoice::Devin => {+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ render_devin(&hooks_dir, &server_url, auth, &config.data_dir, strategy)+ }AgentChoice::Openclaw => {openclaw_plugin::render(&server_url, auth, strategy);Ok(())@@ -299,14 +323,14 @@ fn effective_hook_server_url(args: &InstallHooksArgs,inferred: Option<&InferredMcpConfig>,) -> String {- let raw = if args.server_url != DEFAULT_SERVER_URL {- args.server_url.clone()+ let raw = if let Some(url) = &args.server_url {+ url.clone()} else if config.server_url_configured() {config.server_url.clone()} else if let Some(url) = inferred.and_then(|mcp| mcp.hook_server_url.clone()) {url} else {- return args.server_url.clone();+ return DEFAULT_SERVER_URL.to_string();};apply_base_path_to_hook_url(&normalise_hook_server_url(&raw), &config.base_path)}@@ -359,6 +383,7 @@ fn infer_installed_mcp_config(agent: AgentChoice) -> Option<InferredMcpConfig> {McpClient::AntigravityCli => {infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "serverUrl")}+ McpClient::Devin => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),McpClient::ClaudeDesktop => None,// MCP-only client: no AgentChoice counterpart routes here.// Reachable only if a future install_hooks flow targets VS@@ -380,9 +405,9 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {AgentChoice::Openclaw => Some(McpClient::Openclaw),AgentChoice::AntigravityCli => Some(McpClient::AntigravityCli),AgentChoice::Zero => Some(McpClient::Zero),- // Grok manages its own MCP config under ~/.grok/; we don't- // auto-infer a hook server URL from it.- AgentChoice::Pi | AgentChoice::Grok => None,+ // Grok and Devin manage their own MCP config under ~/.grok/ and ~/.devin/;+ // we don't auto-infer a hook server URL from it.+ AgentChoice::Pi | AgentChoice::Grok | AgentChoice::Devin => None,}}@@ -640,6 +665,73 @@ fn apply_to_grok_settings(Ok(())}+/// Mutate Devin's hook config (either `~/.devin/hooks.v1.json` or `~/.devin/config.json` hooks key).+/// Devin uses the same nested hook JSON shape as Claude Code/Grok, but with DEVIN_EVENTS+/// (PostCompaction instead of PreCompact, no subagent events). SessionStart injects+/// the handoff via hookSpecificOutput.additionalContext.+fn apply_to_devin_settings(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ let path = match &args.config_file {+ Some(p) => p.clone(),+ None => devin_hooks_path()?,+ };+ let staged = stage_hook_scripts(hooks_dir, "devin")?;+ let command_dir = staged_command_dir(&staged, "devin");+ let strategy = args.project_strategy.baked();+ let payload = build_devin_payload_with_data_dir(+ &command_dir,+ server_url,+ auth_token,+ Some(data_dir),+ strategy,+ );+ let our_hooks = payload+ .get("hooks")+ .and_then(|v| v.as_object())+ .context("internal: build_devin_payload didn't return a hooks object")?+ .clone();+ let outcome = apply_atomic(&path, |existing| {+ // For hooks.v1.json, the entire file IS the hooks object+ // For config.json hooks key, we merge into the hooks object+ if path.file_name() == Some("hooks.v1.json".as_ref()) {+ mutate_json(existing, |root| {+ for (event, value) in &our_hooks {+ overlay_event_hooks(root, event, value);+ }+ Ok(())+ })+ } else {+ 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 config.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",+ }+ );+ Ok(())+}+/// Mutate `~/.codex/hooks.json` (creating it if absent) so Codex's/// lifecycle hook runner fires the ai-memory scripts on every/// session/prompt/tool event.@@ -2604,6 +2696,56 @@ fn render_zero(Ok(())}+fn render_devin(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+) -> Result<()> {+ // Soft check (same rationale as render_claude_code): warn, don't bail,+ // so the docker host-path flow still works.+ for (_, script) in super::render_shared::DEVIN_EVENTS {+ let script = hook_script_for_claude_code(script);+ let abs = hooks_dir.join(script.as_ref());+ if !abs.exists() {+ eprintln!(+ "# warning: {} not present on this filesystem. \+ If this command is running inside docker against a \+ host path, you can ignore this; otherwise extract \+ the scripts first with `ai-memory setup-agent`.",+ abs.display()+ );+ }+ }+ let payload = build_devin_payload_with_data_dir(+ hooks_dir,+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ let serialized =+ serde_json::to_string_pretty(&payload).context("serializing devin hook config")?;+ println!(+ "# Devin CLI hook config — write to ~/.devin/hooks.v1.json or ~/.devin/config.json hooks key"+ );+ println!("# Hook scripts: {}", hooks_dir.display());+ println!("# AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("# Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook command below.");+ println!(+ "# Treat ~/.devin/hooks.v1.json or ~/.devin/config.json as sensitive (chmod 600)."+ );+ }+ println!(+ "# NOTE: Devin consumes the handoff via hookSpecificOutput.additionalContext on SessionStart."+ );+ println!();+ println!("{serialized}");+ Ok(())+}+#[cfg(test)]mod tests {use super::*;@@ -2753,7 +2895,7 @@ mod tests {InstallHooksArgs {agent: AgentChoice::OpenCode,hooks_dir: None,- server_url: DEFAULT_SERVER_URL.into(),+ server_url: None,auth_token: None,as_user: None,apply: true,@@ -2906,7 +3048,7 @@ mod tests {..Config::default()};let mut args = default_hook_args();- args.server_url = "http://explicit:49374/".into();+ args.server_url = Some("http://explicit:49374/".into());assert_eq!(effective_hook_server_url(&config, &args, None),@@ -2914,6 +3056,33 @@ mod tests {);}+ /// Regression (found 2026-07-12 during Devin real-acceptance A/B+ /// testing): an explicit `--server-url` that happens to equal the+ /// compiled-in `DEFAULT_SERVER_URL` must still win over a configured+ /// (env/config.toml) server_url pointing somewhere else. Before the+ /// `Option<String>` fix, `args.server_url` was a plain `String` with+ /// `default_value_t = DEFAULT_SERVER_URL`, so clap couldn't+ /// distinguish "operator explicitly typed the default value" from+ /// "operator passed nothing at all" — both produced the same string,+ /// so this exact case silently fell through to `AI_MEMORY_SERVER_URL`+ /// / config.toml instead of honouring the explicit flag.+ #[test]+ fn hook_server_url_explicit_flag_matching_compiled_default_still_wins() {+ let config = Config {+ server_url: "http://127.0.0.1:49375".into(),+ ..Config::default()+ };+ let mut args = default_hook_args();+ args.server_url = Some(DEFAULT_SERVER_URL.to_string());++ assert_eq!(+ effective_hook_server_url(&config, &args, None),+ DEFAULT_SERVER_URL,+ "an explicit --server-url matching the compiled default must not be \+ silently overridden by a differently-configured server_url"+ );+ }+/// Post-audit P1 — the new `ai-memory hook` subcommand (#84) builds/// its request URL by hand, skipping `Config::load` for latency. PR/// #82 made thin-client commands respect `AI_MEMORY_BASE_PATH` via@@ -3084,6 +3253,16 @@ mod tests {);}+ #[test]+ fn resolve_hooks_dir_uses_devin_bundle_for_devin() {+ let tmp = TempDir::new().unwrap();+ fs::create_dir_all(tmp.path().join("devin")).unwrap();+ fs::create_dir_all(tmp.path().join("claude-code")).unwrap();++ let resolved = resolve_hooks_dir(Some(tmp.path()), AgentChoice::Devin).unwrap();+ assert_eq!(resolved, tmp.path().join("devin"));+ }+#[test]fn opencode_mcp_inference_supplies_hook_origin_and_token() {let inferred = infer_json_mcp_config(@@ -3200,6 +3379,7 @@ model = "gpt-5""cursor","gemini-cli","grok",+ "devin","opencode","antigravity-cli",] {@@ -3267,6 +3447,57 @@ model = "gpt-5"(event, agent)}+ #[test]+ fn devin_bundle_has_no_subagent_scripts() {+ let hooks_root = Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("..")+ .join("..")+ .join("hooks");+ let devin_dir = hooks_root.join("devin");++ for entry in fs::read_dir(&devin_dir).unwrap() {+ let path = entry.unwrap().path();+ if !path.is_file() {+ continue;+ }+ let stem = path+ .file_stem()+ .and_then(|s| s.to_str())+ .unwrap_or("unknown");+ assert!(+ !stem.contains("subagent"),+ "Devin bundle should not contain subagent scripts, found: {}",+ path.display()+ );+ }+ }++ #[test]+ fn devin_bundle_has_post_compaction_not_pre_compact() {+ let hooks_root = Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("..")+ .join("..")+ .join("hooks");+ let devin_dir = hooks_root.join("devin");++ assert!(+ devin_dir.join("post-compaction.sh").is_file(),+ "Devin bundle must have post-compaction.sh"+ );+ assert!(+ devin_dir.join("post-compaction.ps1").is_file(),+ "Devin bundle must have post-compaction.ps1"+ );+ assert!(+ !devin_dir.join("pre-compact.sh").exists(),+ "Devin bundle should not have pre-compact.sh"+ );+ assert!(+ !devin_dir.join("pre-compact.ps1").exists(),+ "Devin bundle should not have pre-compact.ps1"+ );+ }+fn extract_ps1_hook_metadata(path: &Path) -> (String, String) {let text = fs::read_to_string(path).unwrap();let line = text@@ -3711,7 +3942,7 @@ model = "gpt-5"let args = InstallHooksArgs {agent: AgentChoice::Omp,hooks_dir: None,- server_url: "http://127.0.0.1:49374".into(),+ server_url: Some("http://127.0.0.1:49374".into()),auth_token: None,as_user: None,apply: true,@@ -3739,7 +3970,7 @@ model = "gpt-5"let args = InstallHooksArgs {agent: AgentChoice::Pi,hooks_dir: None,- server_url: "http://127.0.0.1:49374".into(),+ server_url: Some("http://127.0.0.1:49374".into()),auth_token: None,as_user: None,apply: true,@@ -4230,4 +4461,333 @@ model = "gpt-5".unwrap();assert_eq!(second, ApplyOutcome::NoOp, "second apply must be a no-op");}++ // ----------------------------------------------------------------+ // Devin tests+ // ----------------------------------------------------------------++ #[test]+ fn devin_apply_writes_hooks_v1_json_by_default() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "session-end.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "post-compaction.sh",+ "stop.sh",+ ],+ );++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("hooks.v1.json");++ apply_to_devin_settings(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ &InstallHooksArgs {+ agent: AgentChoice::Devin,+ hooks_dir: Some(hooks_tmp.path().to_path_buf()),+ server_url: Some("http://127.0.0.1:49374".to_string()),+ auth_token: None,+ config_file: Some(config_path.clone()),+ project_strategy: crate::cli::ProjectStrategyArg::Basename,+ as_user: None,+ apply: false,+ },+ )+ .unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // hooks.v1.json: the entire file IS the hooks object (no wrapper)+ assert!(+ parsed["SessionStart"].is_array(),+ "SessionStart hook should be present"+ );+ assert!(+ parsed["PostCompaction"].is_array(),+ "PostCompaction hook should be present"+ );+ assert!(+ parsed.get("hooks").is_none(),+ "hooks.v1.json should not have a 'hooks' wrapper"+ );+ }++ #[test]+ fn devin_apply_config_json_hooks_key_via_flag() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "session-end.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "post-compaction.sh",+ "stop.sh",+ ],+ );++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("config.json");++ // Pre-existing config.json with mcpServers+ fs::write(+ &config_path,+ r#"{"mcpServers":{"other-server":{"url":"http://example.com"}}}"#,+ )+ .unwrap();++ apply_to_devin_settings(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ &InstallHooksArgs {+ agent: AgentChoice::Devin,+ hooks_dir: Some(hooks_tmp.path().to_path_buf()),+ server_url: Some("http://127.0.0.1:49374".to_string()),+ auth_token: None,+ config_file: Some(config_path.clone()),+ project_strategy: crate::cli::ProjectStrategyArg::Basename,+ as_user: None,+ apply: false,+ },+ )+ .unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // config.json: hooks are nested under the "hooks" key+ assert!(+ parsed["hooks"]["SessionStart"].is_array(),+ "SessionStart hook should be present"+ );+ assert!(+ parsed["hooks"]["PostCompaction"].is_array(),+ "PostCompaction hook should be present"+ );+ // mcpServers should be preserved+ assert!(+ parsed["mcpServers"]["other-server"].is_object(),+ "mcpServers should be preserved"+ );+ }++ #[test]+ fn devin_apply_both_targets_are_idempotent() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "session-end.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "post-compaction.sh",+ "stop.sh",+ ],+ );++ // Test hooks.v1.json idempotency+ let config_tmp = TempDir::new().unwrap();+ let hooks_v1_path = config_tmp.path().join("hooks.v1.json");++ let args_v1 = InstallHooksArgs {+ agent: AgentChoice::Devin,+ hooks_dir: Some(hooks_tmp.path().to_path_buf()),+ server_url: Some("http://127.0.0.1:49374".to_string()),+ auth_token: None,+ config_file: Some(hooks_v1_path.clone()),+ project_strategy: crate::cli::ProjectStrategyArg::Basename,+ as_user: None,+ apply: false,+ };++ apply_to_devin_settings(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ &args_v1,+ )+ .unwrap();++ apply_to_devin_settings(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ &args_v1,+ )+ .unwrap();++ // Idempotency check: second apply should be a no-op+ let v1_first_content = fs::read_to_string(&hooks_v1_path).unwrap();+ let v1_second_content = fs::read_to_string(&hooks_v1_path).unwrap();+ assert_eq!(+ v1_first_content, v1_second_content,+ "hooks.v1.json should be unchanged after second apply"+ );++ // Test config.json hooks key idempotency+ let config_tmp2 = TempDir::new().unwrap();+ let config_path = config_tmp2.path().join("config.json");+ fs::write(&config_path, "{}").unwrap();++ let args_config = InstallHooksArgs {+ agent: AgentChoice::Devin,+ hooks_dir: Some(hooks_tmp.path().to_path_buf()),+ server_url: Some("http://127.0.0.1:49374".to_string()),+ auth_token: None,+ config_file: Some(config_path.clone()),+ project_strategy: crate::cli::ProjectStrategyArg::Basename,+ as_user: None,+ apply: false,+ };++ apply_to_devin_settings(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp2.path(),+ &args_config,+ )+ .unwrap();++ apply_to_devin_settings(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp2.path(),+ &args_config,+ )+ .unwrap();++ // Idempotency check: second apply should be a no-op+ let config_first_content = fs::read_to_string(&config_path).unwrap();+ let config_second_content = fs::read_to_string(&config_path).unwrap();+ assert_eq!(+ config_first_content, config_second_content,+ "config.json should be unchanged after second apply"+ );+ }++ #[test]+ fn devin_preserves_existing_hooks_and_adds_ours() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "post-compaction.sh",+ "stop.sh",+ ],+ );++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("hooks.v1.json");+ // Pre-existing settings with another named hook group.+ fs::write(+ &config_path,+ r#"{"my-linter":{"PostToolUse":[{"matcher":"run_command","hooks":[{"type":"command","command":"lint.sh"}]}]}}"#,+ )+ .unwrap();++ apply_to_devin_settings(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ &InstallHooksArgs {+ agent: AgentChoice::Devin,+ hooks_dir: Some(hooks_tmp.path().to_path_buf()),+ server_url: Some("http://127.0.0.1:49374".to_string()),+ auth_token: None,+ config_file: Some(config_path.clone()),+ project_strategy: crate::cli::ProjectStrategyArg::Basename,+ as_user: None,+ apply: false,+ },+ )+ .unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // The pre-existing my-linter group survives.+ assert!(+ parsed["my-linter"]["PostToolUse"].is_array(),+ "my-linter.PostToolUse must survive"+ );+ // Our hooks are present at the top level (hooks.v1.json format).+ assert!(+ parsed["SessionStart"].is_array(),+ "SessionStart hook should be present"+ );+ assert!(+ parsed["PostCompaction"].is_array(),+ "PostCompaction hook should be present"+ );+ assert!(+ parsed["PostToolUse"].is_array(),+ "PostToolUse hook should be present"+ );+ }++ #[test]+ fn devin_session_start_injects_handoff_additional_context() {+ let hooks_root = Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("..")+ .join("..")+ .join("hooks");+ let devin_session_start = hooks_root.join("devin").join("session-start.sh");++ // Normalized because this is the only assertion below that spans a+ // line break: on a Windows checkout with core.autocrlf=true the+ // working-tree copy has CRLF even though the committed blob is+ // LF-only, which breaks an exact multi-line substring match.+ let script_content = fs::read_to_string(&devin_session_start)+ .unwrap()+ .replace("\r\n", "\n");+ // Verify the script injects handoff via hookSpecificOutput.additionalContext+ assert!(+ script_content.contains("hookSpecificOutput"),+ "Devin session-start.sh must inject handoff via hookSpecificOutput"+ );+ assert!(+ script_content.contains("additionalContext"),+ "Devin session-start.sh must use additionalContext field"+ );+ assert!(+ script_content.contains("ai_memory_get_handoff"),+ "Devin session-start.sh must fetch handoff"+ );+ assert!(+ script_content.contains("$SERVER/handoff?agent=devin${QS}"),+ "Devin session-start.sh must use the registered /handoff endpoint with agent=devin"+ );+ assert!(+ !script_content.contains("/handoff/latest"),+ "Devin session-start.sh must not call the removed /handoff/latest route"+ );+ assert!(+ script_content.contains("ai_memory_json_string"),+ "Devin session-start.sh must JSON-escape handoff text before embedding it"+ );+ assert!(+ script_content.contains("else\n printf '{}\\n'\nfi"),+ "Devin session-start.sh must print {{}} only when no handoff is available"+ );+ }}diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 7430bb69..42ccf3bf 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -48,7 +48,7 @@ enum JsonMcpLocation {pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {let server_url = effective_mcp_server_url(config, &args);let args = InstallMcpArgs {- server_url,+ server_url: Some(server_url),auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),..args};@@ -67,6 +67,7 @@ pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {McpClient::Omp => render_omp(&args)?,McpClient::AntigravityCli => render_antigravity_cli(&args)?,McpClient::Zero => render_zero(&args)?,+ McpClient::Devin => render_devin(&args)?,McpClient::VsCodeCopilot => render_vscode_copilot(&args)?,};println!("{snippet}");@@ -74,13 +75,13 @@ pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {}fn effective_mcp_server_url(config: &Config, args: &InstallMcpArgs) -> String {- if args.server_url != DEFAULT_MCP_URL {- return args.server_url.clone();+ if let Some(url) = &args.server_url {+ return url.clone();}if config.server_url_configured() {return mcp_server_url_from_base(&config.server_url);}- args.server_url.clone()+ DEFAULT_MCP_URL.to_string()}fn mcp_server_url_from_base(server_url: &str) -> String {@@ -157,6 +158,7 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>// to ~/.config; we target the default and --config-file covers// non-default XDG setups (same policy as OpenCode above).McpClient::Zero => home()?.join(".config").join("zero").join("config.json"),+ McpClient::Devin => home()?.join(".devin").join("config.json"),// VS Code MCP is workspace-scoped by default: `.vscode/mcp.json`// at the current workspace root. The user-profile alternative// lives under VS Code's profile-specific data dir; use VS@@ -214,7 +216,8 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {| McpClient::Cursor| McpClient::GeminiCli| McpClient::Omp- | McpClient::AntigravityCli => Some(JsonMcpLocation::RootMcpServers),+ | McpClient::AntigravityCli+ | McpClient::Devin => Some(JsonMcpLocation::RootMcpServers),McpClient::OpenCode => Some(JsonMcpLocation::RootMcp),// Zero's config.json nests servers under `mcp.servers`, the same// shape OpenClaw uses.@@ -310,7 +313,10 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {match args.client {McpClient::ClaudeCode => {entry.insert("type".into(), json!("http"));- entry.insert("url".into(), json!(args.server_url));+ entry.insert(+ "url".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );if let Some(b) = &bearer {entry.insert("headers".into(), json!({"Authorization": b}));}@@ -318,7 +324,11 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {McpClient::ClaudeDesktop => {// Stdio shim via mcp-remote — Claude Desktop's JSON// doesn't accept HTTP transport directly.- let mut cmd_args = vec![json!("-y"), json!("mcp-remote"), json!(args.server_url)];+ let mut cmd_args = vec![+ json!("-y"),+ json!("mcp-remote"),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ ];if let Some(b) = &bearer {cmd_args.push(json!("--header"));cmd_args.push(json!("Authorization:${AI_MEMORY_AUTH_HEADER}"));@@ -328,13 +338,19 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {entry.insert("args".into(), serde_json::Value::Array(cmd_args));}McpClient::Cursor => {- entry.insert("url".into(), json!(args.server_url));+ entry.insert(+ "url".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );if let Some(b) = &bearer {entry.insert("headers".into(), json!({"Authorization": b}));}}McpClient::GeminiCli => {- entry.insert("httpUrl".into(), json!(args.server_url));+ entry.insert(+ "httpUrl".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );entry.insert("timeout".into(), json!(GEMINI_MCP_TIMEOUT_MS));if let Some(b) = &bearer {entry.insert("headers".into(), json!({"Authorization": b}));@@ -342,19 +358,35 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {}McpClient::Omp => {entry.insert("type".into(), json!("http"));- entry.insert("url".into(), json!(args.server_url));+ entry.insert(+ "url".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );entry.insert("enabled".into(), json!(true));if let Some(b) = &bearer {entry.insert("headers".into(), json!({"Authorization": b}));}}McpClient::AntigravityCli => {- entry.insert("serverUrl".into(), json!(args.server_url));+ entry.insert(+ "serverUrl".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );entry.insert("timeout".into(), json!(GEMINI_MCP_TIMEOUT_MS));if let Some(b) = &bearer {entry.insert("headers".into(), json!({"Authorization": b}));}}+ McpClient::Devin => {+ entry.insert(+ "url".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );+ entry.insert("transport".into(), json!("http"));+ if let Some(b) = &bearer {+ entry.insert("headers".into(), json!({"Authorization": b}));+ }+ }McpClient::VsCodeCopilot => {// VS Code MCP framework schema: `type: "http"` + `url`,// headers map for auth. Verified against@@ -362,7 +394,10 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {// The `mcpServers` key (used by Claude Code/Cursor/Gemini)// is silently ignored here — VS Code reads `servers`.entry.insert("type".into(), json!("http"));- entry.insert("url".into(), json!(args.server_url));+ entry.insert(+ "url".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );if let Some(b) = &bearer {entry.insert("headers".into(), json!({"Authorization": b}));}@@ -376,7 +411,10 @@ fn build_mcp_entry_opencode(args: &InstallMcpArgs) -> Result<serde_json::Value>let bearer = bearer_header_value(args.auth_token.as_deref());let mut entry = serde_json::Map::new();entry.insert("type".into(), json!("remote"));- entry.insert("url".into(), json!(args.server_url));+ entry.insert(+ "url".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );entry.insert("enabled".into(), json!(true));if let Some(b) = bearer {entry.insert("headers".into(), json!({"Authorization": b}));@@ -387,7 +425,10 @@ fn build_mcp_entry_opencode(args: &InstallMcpArgs) -> Result<serde_json::Value>fn build_mcp_entry_openclaw(args: &InstallMcpArgs) -> Result<serde_json::Value> {let bearer = bearer_header_value(args.auth_token.as_deref());let mut entry = serde_json::Map::new();- entry.insert("url".into(), json!(args.server_url));+ entry.insert(+ "url".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );entry.insert("transport".into(), json!("streamable-http"));if let Some(b) = bearer {entry.insert("headers".into(), json!({"Authorization": b}));@@ -402,7 +443,10 @@ fn build_mcp_entry_zero(args: &InstallMcpArgs) -> Result<serde_json::Value> {let bearer = bearer_header_value(args.auth_token.as_deref());let mut entry = serde_json::Map::new();entry.insert("type".into(), json!("http"));- entry.insert("url".into(), json!(args.server_url));+ entry.insert(+ "url".into(),+ json!(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),+ );if let Some(b) = bearer {entry.insert("headers".into(), json!({"Authorization": b}));}@@ -470,7 +514,7 @@ fn codex_upsert_mcp_server(// `Authorization = "Bearer ..."`. Codex schema-validates// and uses it as a static auth header.let mut server = Table::new();- server["url"] = value(args.server_url.clone());+ server["url"] = value(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL));// Auto-approve ai-memory's tool calls. Without this, Codex// prompts on EVERY tool invocation ("approve memory_query?"// "approve memory_briefing?" …) which makes the MCP unusable@@ -510,14 +554,14 @@ fn render_claude_code(args: &InstallMcpArgs) -> Result<String> {format!("claude mcp add --transport http {name} {url} \\\n --header \"Authorization: {b}\"",name = args.name,- url = args.server_url,+ url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),b = b,)} else {format!("claude mcp add --transport http {name} {url}",name = args.name,- url = args.server_url,+ url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),)};let snippet = render_json_mcp_fragment(args)?;@@ -553,7 +597,7 @@ fn render_codex(args: &InstallMcpArgs) -> String {# approval friction makes it unusable otherwise.\n\default_tools_approval_mode = \"approve\"\n",name = args.name,- url = args.server_url,+ url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),);if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {out.push_str(&format!(@@ -657,7 +701,7 @@ fn pi_mcp_render_guidance(args: &InstallMcpArgs) -> String {# lifecycle capture and an HTTP MCP bridge that registers tools in Pi.\n\ai-memory install-hooks --agent pi --apply --server-url {}{}\n\# Restart Pi after installing ~/.pi/agent/extensions/ai-memory.ts.\n",- hook_server_url_from_mcp_url(&args.server_url),+ hook_server_url_from_mcp_url(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),if args.auth_token.is_some() {" --auth-token <token>"} else {@@ -669,7 +713,7 @@ fn pi_mcp_render_guidance(args: &InstallMcpArgs) -> String {fn pi_mcp_apply_guidance(args: &InstallMcpArgs) -> String {format!("Pi has no native mcp.json; refusing to write MCP config. Install the generated bridge instead: ai-memory install-hooks --agent pi --apply --server-url {}{}",- hook_server_url_from_mcp_url(&args.server_url),+ hook_server_url_from_mcp_url(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL)),if args.auth_token.is_some() {" --auth-token <token>"} else {@@ -705,6 +749,16 @@ fn render_antigravity_cli(args: &InstallMcpArgs) -> Result<String> {))}+fn render_devin(args: &InstallMcpArgs) -> Result<String> {+ Ok(format!(+ "# Devin CLI — merge into ~/.devin/config.json:\n\+ #\n\+ # Devin uses `mcpServers` with HTTP transport and optional Bearer auth.\n\+ {snippet}\n",+ snippet = render_json_mcp_fragment(args)?,+ ))+}+fn render_vscode_copilot(args: &InstallMcpArgs) -> Result<String> {Ok(format!("# VS Code GitHub Copilot (agent mode) — write to one of:\n\@@ -732,11 +786,14 @@ fn render_vscode_copilot(args: &InstallMcpArgs) -> Result<String> {#[cfg(test)]mod tests {use super::*;+ use clap::Parser;+ use std::fs;+ use tempfile;fn args_for(client: McpClient) -> InstallMcpArgs {InstallMcpArgs {client,- server_url: "http://127.0.0.1:49374/mcp".into(),+ server_url: None,name: "ai-memory".into(),auth_token: None,apply: false,@@ -747,7 +804,7 @@ mod tests {fn args_with_token(client: McpClient) -> InstallMcpArgs {InstallMcpArgs {client,- server_url: "http://127.0.0.1:49374/mcp".into(),+ server_url: None,name: "ai-memory".into(),auth_token: Some("test-token-deadbeef".into()),apply: false,@@ -769,6 +826,7 @@ mod tests {McpClient::Omp => render_omp(&args).unwrap(),McpClient::AntigravityCli => render_antigravity_cli(&args).unwrap(),McpClient::Zero => render_zero(&args).unwrap(),+ McpClient::Devin => render_devin(&args).unwrap(),McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),}}@@ -788,6 +846,7 @@ mod tests {McpClient::Omp,McpClient::AntigravityCli,McpClient::Zero,+ McpClient::Devin,McpClient::VsCodeCopilot,] {let out = render_with_token(client);@@ -821,6 +880,7 @@ mod tests {McpClient::Omp,McpClient::AntigravityCli,McpClient::Zero,+ McpClient::Devin,McpClient::VsCodeCopilot,] {let out = render_for_test(client);@@ -845,6 +905,7 @@ mod tests {McpClient::Omp => render_omp(&args).unwrap(),McpClient::AntigravityCli => render_antigravity_cli(&args).unwrap(),McpClient::Zero => render_zero(&args).unwrap(),+ McpClient::Devin => render_devin(&args).unwrap(),McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),}}@@ -884,7 +945,7 @@ mod tests {..Config::default()};let mut args = args_for(McpClient::OpenCode);- args.server_url = "http://explicit:49374/mcp".into();+ args.server_url = Some("http://explicit:49374/mcp".into());assert_eq!(effective_mcp_server_url(&config, &args),@@ -892,6 +953,29 @@ mod tests {);}+ /// Regression (found 2026-07-12 during Devin real-acceptance A/B+ /// testing): an explicit `--server-url` that happens to equal the+ /// compiled-in `DEFAULT_MCP_URL` must still win over a configured+ /// (env/config.toml) server_url pointing somewhere else. Mirrors+ /// `hook_server_url_explicit_flag_matching_compiled_default_still_wins`+ /// in install_hooks.rs -- same bug class, same fix, both commands.+ #[test]+ fn mcp_server_url_explicit_flag_matching_compiled_default_still_wins() {+ let config = Config {+ server_url: "http://127.0.0.1:49375".into(),+ ..Config::default()+ };+ let mut args = args_for(McpClient::OpenCode);+ args.server_url = Some(DEFAULT_MCP_URL.to_string());++ assert_eq!(+ effective_mcp_server_url(&config, &args),+ DEFAULT_MCP_URL,+ "an explicit --server-url matching the compiled default must not be \+ silently overridden by a differently-configured server_url"+ );+ }+/// Specific shape checks — each client has a distinguishing key/// in its JSON snippet. This catches accidental cross-pollination/// between renderers (e.g. Gemini's `httpUrl` showing up under@@ -910,6 +994,14 @@ mod tests {assert!(pi.contains("~/.pi/agent/extensions/ai-memory.ts"));assert!(!pi.contains("~/.omp"));assert!(render_for_test(McpClient::AntigravityCli).contains("\"serverUrl\""));+ let devin = render_for_test(McpClient::Devin);+ assert!(devin.contains("\"mcpServers\""));+ assert!(devin.contains("\"url\""));+ assert!(devin.contains("\"transport\": \"http\""));+ assert!(!devin.contains("\"httpUrl\""));+ let devin_with_token = render_with_token(McpClient::Devin);+ assert!(devin_with_token.contains("\"headers\""));+ assert!(devin_with_token.contains("\"Authorization\": \"Bearer test-token-deadbeef\""));// VS Code Copilot must use the `servers` top-level key — the// `mcpServers` form is silently ignored by VS Code's MCP// framework. Regression guard against a future copy-paste@@ -944,7 +1036,7 @@ mod tests {#[test]fn pi_guidance_derives_hook_url_from_mcp_url() {let mut args = args_for(McpClient::Pi);- args.server_url = "http://host:49374/base/mcp".into();+ args.server_url = Some("http://host:49374/base/mcp".into());args.auth_token = Some("tok".into());let guidance = render_pi(&args).unwrap();@@ -1049,4 +1141,102 @@ mod tests {assert!(out.contains("http://other"));assert!(out.contains("[mcp_servers.ai-memory]"));}++ #[test]+ fn devin_mcp_client_parses() {+ let cli = crate::cli::Cli::parse_from([+ "ai-memory",+ "install-mcp",+ "--client",+ "devin",+ "--server-url",+ "http://example.test:49374",+ ]);+ let crate::cli::Command::InstallMcp(mcp_args) = cli.command else {+ panic!("expected install-mcp command for devin");+ };+ assert!(matches!(mcp_args.client, crate::cli::McpClient::Devin));+ }++ #[test]+ fn devin_apply_writes_mcp_servers() {+ let args = args_with_token(McpClient::Devin);+ let tmp = tempfile::TempDir::new().unwrap();+ let config_path = tmp.path().join("config.json");++ let entry = build_json_mcp_entry(&args).unwrap();+ let root = serde_json::json!({+ "mcpServers": {+ "ai-memory": entry+ }+ });++ fs::write(&config_path, serde_json::to_string_pretty(&root).unwrap()).unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ assert!(+ parsed["mcpServers"]["ai-memory"].is_object(),+ "Devin config must have mcpServers.ai-memory"+ );+ assert_eq!(+ parsed["mcpServers"]["ai-memory"]["url"],+ "http://127.0.0.1:49374/mcp"+ );+ assert_eq!(parsed["mcpServers"]["ai-memory"]["transport"], "http");+ }++ #[test]+ fn devin_apply_preserves_sibling_mcp_servers() {+ let args = args_with_token(McpClient::Devin);+ let tmp = tempfile::TempDir::new().unwrap();+ let config_path = tmp.path().join("config.json");++ // Pre-existing config with sibling MCP server+ fs::write(+ &config_path,+ r#"{"mcpServers":{"other-server":{"url":"http://example.com","transport":"http"}}}"#,+ )+ .unwrap();++ let mut args_with_path = args.clone();+ args_with_path.config_file = Some(config_path.clone());++ apply_to_config_file(&args_with_path).unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // Sibling must be preserved+ assert!(+ parsed["mcpServers"]["other-server"].is_object(),+ "other-server must be preserved"+ );+ // ai-memory must be added+ assert!(+ parsed["mcpServers"]["ai-memory"].is_object(),+ "ai-memory must be added"+ );+ }++ #[test]+ fn devin_apply_mcp_is_idempotent() {+ let args = args_with_token(McpClient::Devin);+ let tmp = tempfile::TempDir::new().unwrap();+ let config_path = tmp.path().join("config.json");++ let mut args_with_path = args.clone();+ args_with_path.config_file = Some(config_path.clone());++ apply_to_config_file(&args_with_path).unwrap();++ let first_content = fs::read_to_string(&config_path).unwrap();++ apply_to_config_file(&args_with_path).unwrap();++ let second_content = fs::read_to_string(&config_path).unwrap();+ assert_eq!(+ first_content, second_content,+ "second apply must produce identical bytes"+ );+ }}diff --git a/crates/ai-memory-cli/src/commands/install_skills.rs b/crates/ai-memory-cli/src/commands/install_skills.rsindex 0c108953..8083f416 100644--- a/crates/ai-memory-cli/src/commands/install_skills.rs+++ b/crates/ai-memory-cli/src/commands/install_skills.rs@@ -4,7 +4,8 @@ use std::fs;use std::path::{Path, PathBuf};use ai_memory_core::routing_skills::{- AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, MANAGED_MARKER, MANAGED_SKILLS, ManagedSkill, SKILLS_DIR,+ AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, DEVIN_SKILL_DIR, MANAGED_MARKER, MANAGED_SKILLS,+ ManagedSkill, SKILLS_DIR,};use anyhow::{Context, Result, bail};@@ -81,13 +82,31 @@ fn print_reports(reports: Vec<InstallReport>) {fn resolve_target_roots_from_env(args: &InstallSkillsArgs) -> Result<Vec<TargetRoot>> {let cwd = std::env::current_dir().context("getting CWD for install-skills target")?;let home = home_dir();- resolve_target_roots(args, &cwd, home.as_deref())+ let appdata = std::env::var_os("APPDATA").map(PathBuf::from);+ resolve_target_roots_for_platform(+ args,+ &cwd,+ home.as_deref(),+ appdata.as_deref(),+ SkillHostPlatform::current(),+ )}+#[cfg(test)]fn resolve_target_roots(args: &InstallSkillsArgs,cwd: &Path,home: Option<&Path>,+) -> Result<Vec<TargetRoot>> {+ resolve_target_roots_for_platform(args, cwd, home, None, SkillHostPlatform::Other)+}++fn resolve_target_roots_for_platform(+ args: &InstallSkillsArgs,+ cwd: &Path,+ home: Option<&Path>,+ appdata: Option<&Path>,+ platform: SkillHostPlatform,) -> Result<Vec<TargetRoot>> {if let Some(target_dir) = &args.target_dir {return Ok(vec![TargetRoot::new(target_dir.clone())]);@@ -95,24 +114,79 @@ fn resolve_target_roots(let roots = match args.agent {InstallSkillsAgent::ClaudeCode => {- vec![agent_root(args.scope, SkillRootKind::Claude, cwd, home)?]+ vec![agent_root(+ args.scope,+ SkillRootKind::Claude,+ cwd,+ home,+ appdata,+ platform,+ )?]}InstallSkillsAgent::Agents => {- vec![agent_root(args.scope, SkillRootKind::Agents, cwd, home)?]+ vec![agent_root(+ args.scope,+ SkillRootKind::Agents,+ cwd,+ home,+ appdata,+ platform,+ )?]+ }+ InstallSkillsAgent::Devin => {+ vec![agent_root(+ args.scope,+ SkillRootKind::Devin,+ cwd,+ home,+ appdata,+ platform,+ )?]}InstallSkillsAgent::Both => vec![- agent_root(args.scope, SkillRootKind::Claude, cwd, home)?,- agent_root(args.scope, SkillRootKind::Agents, cwd, home)?,+ agent_root(+ args.scope,+ SkillRootKind::Claude,+ cwd,+ home,+ appdata,+ platform,+ )?,+ agent_root(+ args.scope,+ SkillRootKind::Agents,+ cwd,+ home,+ appdata,+ platform,+ )?,],};Ok(roots.into_iter().map(TargetRoot::new).collect())}-#[derive(Debug, Clone, Copy)]+#[derive(Debug, Clone, Copy, Eq, PartialEq)]+enum SkillHostPlatform {+ Windows,+ Other,+}++impl SkillHostPlatform {+ fn current() -> Self {+ if cfg!(windows) {+ Self::Windows+ } else {+ Self::Other+ }+ }+}++#[derive(Debug, Clone, Copy, Eq, PartialEq)]enum SkillRootKind {Claude,Agents,+ Devin,}fn agent_root(@@ -120,7 +194,18 @@ fn agent_root(kind: SkillRootKind,cwd: &Path,home: Option<&Path>,+ appdata: Option<&Path>,+ platform: SkillHostPlatform,) -> Result<PathBuf> {+ if scope == InstallSkillsScope::Global+ && kind == SkillRootKind::Devin+ && platform == SkillHostPlatform::Windows+ {+ let appdata = appdata+ .context("could not locate %APPDATA% for global Devin skill install on Windows")?;+ return Ok(appdata.join("devin").join(SKILLS_DIR));+ }+let base = match scope {InstallSkillsScope::Project => cwd,InstallSkillsScope::Global => {@@ -130,6 +215,7 @@ fn agent_root(let agent_dir = match kind {SkillRootKind::Claude => CLAUDE_SKILL_DIR,SkillRootKind::Agents => AGENTS_SKILL_DIR,+ SkillRootKind::Devin => DEVIN_SKILL_DIR,};Ok(base.join(agent_dir).join(SKILLS_DIR))}@@ -259,6 +345,14 @@ mod tests {.unwrap();assert_eq!(root_names(&project_agents), ["/repo/.agents/skills"]);+ let project_devin = resolve_target_roots(+ &args(InstallSkillsScope::Project, InstallSkillsAgent::Devin),+ cwd,+ Some(home),+ )+ .unwrap();+ assert_eq!(root_names(&project_devin), ["/repo/.devin/skills"]);+let project_both = resolve_target_roots(&args(InstallSkillsScope::Project, InstallSkillsAgent::Both),cwd,@@ -280,6 +374,52 @@ mod tests {root_names(&global_both),["/home/alice/.claude/skills", "/home/alice/.agents/skills"]);++ let global_devin = resolve_target_roots(+ &args(InstallSkillsScope::Global, InstallSkillsAgent::Devin),+ cwd,+ Some(home),+ )+ .unwrap();+ assert_eq!(root_names(&global_devin), ["/home/alice/.devin/skills"]);+ }++ #[test]+ fn devin_global_skill_root_matches_confirmed_windows_path() {+ let cwd = Path::new("/repo");+ let home = Path::new("/home/alice");+ let appdata = Path::new("C:/Users/Alice/AppData/Roaming");++ let global_devin = resolve_target_roots_for_platform(+ &args(InstallSkillsScope::Global, InstallSkillsAgent::Devin),+ cwd,+ Some(home),+ Some(appdata),+ SkillHostPlatform::Windows,+ )+ .unwrap();++ assert_eq!(+ root_names(&global_devin),+ ["C:/Users/Alice/AppData/Roaming/devin/skills"]+ );+ }++ #[test]+ fn devin_global_skill_root_requires_appdata_on_windows() {+ let cwd = Path::new("/repo");+ let home = Path::new("/home/alice");++ let err = resolve_target_roots_for_platform(+ &args(InstallSkillsScope::Global, InstallSkillsAgent::Devin),+ cwd,+ Some(home),+ None,+ SkillHostPlatform::Windows,+ )+ .unwrap_err();++ assert!(err.to_string().contains("%APPDATA%"));}#[test]@@ -315,6 +455,22 @@ mod tests {);}+ #[test]+ fn install_writes_managed_skills_to_devin_root() {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path().join(".devin/skills");+ let reports = install_managed_skills(&[TargetRoot::new(root.clone())], false).unwrap();++ assert_eq!(reports.len(), MANAGED_SKILLS.len());+ for skill in MANAGED_SKILLS {+ let path = root.join(skill.relative_path);+ let content = fs::read_to_string(&path)+ .unwrap_or_else(|err| panic!("expected Devin skill {}: {err}", path.display()));+ assert!(content.contains(MANAGED_MARKER));+ assert!(content.contains(skill.description));+ }+ }+#[test]fn refuses_to_overwrite_unmanaged_same_name_skill() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 08f8468e..06b5dc6a 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -47,6 +47,22 @@ pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 9] = [("SubagentStop", "subagent-stop.sh"),];+/// Devin lifecycle events ai-memory hooks. Each pair is+/// `(event-name-in-Devin-settings, POSIX hook-script-filename)`.+///+/// Devin uses the same event vocabulary as Claude Code, but with two differences:+/// - `PostCompaction` instead of `PreCompact` (triggers *after* compaction with a `summary` field)+/// - No `SubagentStart`/`SubagentStop` (Devin does not expose subagent boundaries as hook events)+pub(crate) const DEVIN_EVENTS: [(&str, &str); 7] = [+ ("SessionStart", "session-start.sh"),+ ("UserPromptSubmit", "user-prompt-submit.sh"),+ ("PreToolUse", "pre-tool-use.sh"),+ ("PostToolUse", "post-tool-use.sh"),+ ("PostCompaction", "post-compaction.sh"),+ ("Stop", "stop.sh"),+ ("SessionEnd", "session-end.sh"),+];+/// Format an `Authorization: Bearer <token>` header value, or `None`/// when no token is supplied. Used by every MCP client renderer in/// `install-mcp` and every hook-config renderer that wants to@@ -238,6 +254,30 @@ pub(crate) fn build_zero_hooks_config(serde_json::json!({ "enabled": true, "hooks": hooks })}+/// Devin hook payload for docker/setup-agent script snippets.+/// Devin uses HookShape::Nested (same as Claude Code/Grok) but with+/// DEVIN_EVENTS (PostCompaction instead of PreCompact, no subagent events).+#[must_use]+pub(crate) fn build_devin_payload(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+) -> serde_json::Value {+ build_hook_payload_for_platform(+ &DEVIN_EVENTS,+ emit_root,+ server_url,+ auth_token,+ HookShape::Nested,+ HookCommandContext::new(+ HookCommandPlatform::for_bash_script_runner(),+ "devin",+ None,+ None,+ ),+ )+}+/// Grok Build CLI hook payload for apply/render paths. Native commands are the/// default; explicit script fallback still points at the Grok script bundle.pub(crate) fn build_grok_payload_with_data_dir(@@ -262,6 +302,33 @@ pub(crate) fn build_grok_payload_with_data_dir()}+/// Devin hook payload for apply/render paths. Native commands are the+/// default; explicit script fallback still points at the Devin script bundle.+/// Devin uses HookShape::Nested (same as Claude Code/Grok) but with+/// DEVIN_EVENTS (PostCompaction instead of PreCompact, no subagent events).+#[must_use]+pub(crate) fn build_devin_payload_with_data_dir(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> serde_json::Value {+ build_hook_payload_for_platform(+ &DEVIN_EVENTS,+ emit_root,+ server_url,+ auth_token,+ HookShape::Nested,+ HookCommandContext::new(+ HookCommandPlatform::for_bash_runner(),+ "devin",+ data_dir,+ project_strategy,+ ),+ )+}+/// Different agents nest hook entries differently. Two shapes/// cover everyone we support:#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -1068,6 +1135,59 @@ mod tests {assert!(!command.contains("claude-code"), "{command}");}+ #[test]+ fn devin_payload_has_all_events() {+ let root = PathBuf::from("/host/hooks/devin");+ let v = build_devin_payload(&root, "http://localhost:49374", None);+ let hooks = v.get("hooks").and_then(|h| h.as_object()).unwrap();+ assert_eq!(hooks.len(), DEVIN_EVENTS.len());+ for (event, _) in DEVIN_EVENTS {+ assert!(hooks.contains_key(event), "missing event {event}");+ }+ }++ #[test]+ fn devin_native_payload_uses_devin_agent() {+ let root = PathBuf::from("/host/hooks/devin");+ let v = build_hook_payload_for_platform(+ &DEVIN_EVENTS,+ &root,+ "http://localhost:49374",+ None,+ HookShape::Nested,+ HookCommandContext::new(HookCommandPlatform::PosixNative, "devin", None, None),+ );+ let command = v+ .pointer("/hooks/SessionStart/0/hooks/0/command")+ .and_then(|s| s.as_str())+ .unwrap();+ assert!(command.contains("--agent devin"), "{command}");+ assert!(!command.contains("grok"), "{command}");+ }++ #[test]+ fn devin_script_payload_uses_devin_bundle() {+ let root = PathBuf::from("/host/hooks/devin");+ let v = build_hook_payload_for_platform(+ &DEVIN_EVENTS,+ &root,+ "http://localhost:49374",+ None,+ HookShape::Nested,+ HookCommandContext::new(HookCommandPlatform::Posix, "devin", None, None),+ );+ let command = v+ .pointer("/hooks/SessionStart/0/hooks/0/command")+ .and_then(|s| s.as_str())+ .unwrap();+ let normalized = command.replace('\\', "/");+ assert!(+ normalized.contains("/host/hooks/devin/session-start.sh"),+ "{command}"+ );+ assert!(!command.contains("grok"), "{command}");+ }+#[test]fn claude_code_payload_embeds_auth_token_when_provided() {let root = PathBuf::from("/host/hooks/claude-code");diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 7998816e..e64b949b 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -37,7 +37,7 @@ use anyhow::{Context, Result, bail};use crate::cli::{AgentChoice, SetupAgentArgs};use crate::commands::render_shared::{ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,- GEMINI_PROFILE, build_claude_code_payload, build_grok_payload,+ GEMINI_PROFILE, build_claude_code_payload, build_devin_payload, build_grok_payload,hook_script_for_current_platform,};use crate::config::{Config, DEFAULT_SERVER_URL};@@ -129,6 +129,7 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {match args.agent {AgentChoice::ClaudeCode => emit_claude_code(&emit_root, &args)?,AgentChoice::Grok => emit_grok(&emit_root, &args)?,+ AgentChoice::Devin => emit_devin(&emit_root, &args)?,AgentChoice::Codex => emit_other(&emit_root, agent_sub, &args, &[CODEX_PROFILE.events]),AgentChoice::Cursor => emit_other(&emit_root, agent_sub, &args, &[CURSOR_PROFILE.events]),AgentChoice::GeminiCli => {@@ -276,6 +277,37 @@ fn emit_grok(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {Ok(())}+fn emit_devin(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {+ print!("{}", render_devin_setup_output(emit_root, args)?);+ Ok(())+}++fn render_devin_setup_output(emit_root: &Path, args: &SetupAgentArgs) -> Result<String> {+ let payload = build_devin_payload(emit_root, &args.server_url, args.auth_token.as_deref());+ let serialized =+ serde_json::to_string_pretty(&payload).context("serializing Devin hook config")?;+ let mut out = String::new();+ out.push_str(+ "# Devin CLI — write to ~/.devin/hooks.v1.json or ~/.devin/config.json hooks key\n",+ );+ out.push_str("# Hook scripts (must be reachable from the host that runs Devin):\n");+ out.push_str(&format!("# {}\n", emit_root.display()));+ out.push_str(&format!("# AI-memory server: {}\n", args.server_url));+ if args.auth_token.is_some() {+ out.push_str("# Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook command below.\n");+ out.push_str(+ "# Treat ~/.devin/hooks.v1.json or ~/.devin/config.json as sensitive (chmod 600).\n",+ );+ }+ out.push_str(+ "# NOTE: Devin consumes the handoff via hookSpecificOutput.additionalContext on SessionStart.\n",+ );+ out.push('\n');+ out.push_str(&serialized);+ out.push('\n');+ Ok(out)+}+fn emit_other(emit_root: &Path,label: &str,@@ -323,13 +355,21 @@ fn copy_support_hook_scripts(source_dir: &Path, dest_dir: &Path) -> Result<()> {let Some(source_hooks_root) = source_dir.parent() else {return Ok(());};+ let Some(dest_hooks_root) = dest_dir.parent() else {+ return Ok(());+ };+ let shared_lib = source_hooks_root.join("_lib.sh");+ if shared_lib.is_file() {+ let to = dest_hooks_root.join("_lib.sh");+ fs::copy(&shared_lib, &to)+ .with_context(|| format!("copying {} → {}", shared_lib.display(), to.display()))?;+ }+let source_lib = source_hooks_root.join("lib");if !source_lib.is_dir() {return Ok(());}- let Some(dest_hooks_root) = dest_dir.parent() else {- return Ok(());- };+let dest_lib = dest_hooks_root.join("lib");fs::create_dir_all(&dest_lib).with_context(|| format!("creating hook support dir {}", dest_lib.display()))?;@@ -462,6 +502,85 @@ mod tests {assert!(!tmp.path().join("hooks").exists());}+ #[test]+ fn devin_setup_emits_script_hook_config() {+ let args = SetupAgentArgs {+ agent: AgentChoice::Devin,+ to: PathBuf::from("/container/hooks"),+ host_prefix: Some(PathBuf::from("/host/hooks")),+ server_url: "http://127.0.0.1:49374".into(),+ auth_token: Some("token-for-test".into()),+ source: None,+ };+ let emit_root = Path::new("/host/hooks/devin");++ let rendered = render_devin_setup_output(emit_root, &args).unwrap();++ assert!(rendered.contains("# Devin CLI"));+ assert!(rendered.contains("~/.devin/hooks.v1.json"));+ assert!(rendered.contains("hookSpecificOutput.additionalContext"));+ assert!(rendered.contains("AI_MEMORY_AUTH_TOKEN"));++ let json_start = rendered.find('{').expect("rendered Devin config JSON");+ let parsed: serde_json::Value = serde_json::from_str(&rendered[json_start..]).unwrap();+ let hooks = parsed["hooks"].as_object().expect("hooks object");+ assert!(hooks["SessionStart"].is_array());+ assert!(hooks["PostCompaction"].is_array());+ assert!(hooks.get("PreCompact").is_none());+ assert!(hooks.get("SubagentStart").is_none());+ assert!(hooks.get("SubagentStop").is_none());++ let session_start = hooks["SessionStart"][0]["hooks"][0]["command"]+ .as_str()+ .unwrap();+ assert!(session_start.contains("/host/hooks/devin/session-start.sh"));+ // Script-mode handlers inline env vars into the command string+ // itself (see `claude_code_payload_embeds_auth_token_when_provided`+ // in render_shared.rs) rather than using a separate `env` field.+ assert!(+ session_start.contains("AI_MEMORY_AUTH_TOKEN=token-for-test"),+ "command should inline the auth token; got: {session_start}"+ );++ let post_compaction = hooks["PostCompaction"][0]["hooks"][0]["command"]+ .as_str()+ .unwrap();+ assert!(post_compaction.contains("/host/hooks/devin/post-compaction.sh"));+ }++ #[test]+ fn devin_setup_copies_event_scripts_and_shared_lib() {+ let tmp = tempfile::TempDir::new().unwrap();+ let source_root = tmp.path().join("source");+ let source_devin = source_root.join("devin");+ fs::create_dir_all(&source_devin).unwrap();+ fs::write(+ source_devin.join("session-start.sh"),+ "#!/bin/sh\n. \"$(dirname \"$0\")/../_lib.sh\"\n",+ )+ .unwrap();+ fs::write(+ source_root.join("_lib.sh"),+ "ai_memory_json_string() { cat; }\n",+ )+ .unwrap();++ let dest = tmp.path().join("dest");+ let args = SetupAgentArgs {+ agent: AgentChoice::Devin,+ to: dest.clone(),+ host_prefix: None,+ server_url: "http://127.0.0.1:49374".into(),+ auth_token: None,+ source: Some(source_root),+ };++ run(&Config::default(), args).unwrap();++ assert!(dest.join("devin/session-start.sh").exists());+ assert!(dest.join("_lib.sh").exists());+ }+#[test]fn manual_script_paths_use_agent_specific_events() {let root = Path::new("/hooks/gemini-cli");diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 04dcc891..b0daabaa 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -15,7 +15,7 @@ use crate::commands::path_util::home_dir;use crate::commands::{data_purge, install_hooks, install_mcp, openclaw_plugin};use crate::config::Config;use ai_memory_core::routing_skills::{- AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, MANAGED_MARKER, MANAGED_SKILLS, SKILLS_DIR,+ AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, DEVIN_SKILL_DIR, MANAGED_MARKER, MANAGED_SKILLS, SKILLS_DIR,};use ai_memory_core::{MARKER_END, MARKER_START, find_marker_line};use anyhow::{Context, Result};@@ -33,7 +33,7 @@ enum RewriteOp {/// CLAUDE.md / AGENTS.md routing block.Instructions,/// Standard JSON hook table under `hooks`.- HooksJson,+ HooksJson(HookConfigShape),/// Antigravity CLI named hook group under top-level `ai-memory`.AntigravityHooksJson,/// Zero hooks.json — `hooks` array entries whose `id` carries the@@ -45,6 +45,14 @@ enum RewriteOp {McpToml,}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum HookConfigShape {+ /// Standard agent configs: `{ "hooks": { "Event": [...] } }`.+ NestedHooksKey,+ /// Devin `hooks.v1.json`: the file itself is `{ "Event": [...] }`.+ FlatHookFile,+}+/// Generated files that uninstall may delete after content re-validation.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum DeleteKind {@@ -129,26 +137,55 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {// ---- Hooks (JSON configs) ----if want(crate::cli::UninstallOnly::Hooks) {let hook_files = [- install_hooks::claude_settings_path()?,- install_hooks::codex_hooks_path()?,- install_hooks::cursor_hooks_path()?,- install_hooks::gemini_settings_path()?,+ (+ install_hooks::claude_settings_path()?,+ HookConfigShape::NestedHooksKey,+ ),+ (+ install_hooks::codex_hooks_path()?,+ HookConfigShape::NestedHooksKey,+ ),+ (+ install_hooks::cursor_hooks_path()?,+ HookConfigShape::NestedHooksKey,+ ),+ (+ install_hooks::gemini_settings_path()?,+ HookConfigShape::NestedHooksKey,+ ),// Grok's ~/.grok/hooks/ai-memory.json shares Claude Code's// JSON shape, so the same strip pass removes our entries.- install_hooks::grok_hooks_path()?,+ (+ install_hooks::grok_hooks_path()?,+ HookConfigShape::NestedHooksKey,+ ),+ // Devin's default hooks.v1.json is flat: the file itself is the+ // event map. Its config.json alternative stores the same entries+ // under the usual hooks key.+ (+ install_hooks::devin_hooks_path()?,+ HookConfigShape::FlatHookFile,+ ),+ (+ install_hooks::devin_config_path()?,+ HookConfigShape::NestedHooksKey,+ ),];- for path in hook_files {+ for (path, shape) in hook_files {if !path.exists() {continue;}let content = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;- let removal = strip_ai_memory_hooks(&content)?;+ let removal = match shape {+ HookConfigShape::NestedHooksKey => strip_ai_memory_hooks(&content)?,+ HookConfigShape::FlatHookFile => strip_ai_memory_hooks_flat(&content)?,+ };push_rewrite(&mut plan,path,removal.removed_events,- RewriteOp::HooksJson,+ RewriteOp::HooksJson(shape),);}@@ -220,6 +257,7 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {AntigravityCli,Zero,VsCodeCopilot,+ Devin,] {let Ok(path) = install_mcp::mcp_config_path(client) else {continue;@@ -284,12 +322,14 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {}fn skill_roots(cwd: &Path, home: Option<&Path>) -> Vec<PathBuf> {- let mut roots = Vec::with_capacity(4);+ let mut roots = Vec::with_capacity(6);push_unique_skill_root(&mut roots, cwd.join(CLAUDE_SKILL_DIR).join(SKILLS_DIR));push_unique_skill_root(&mut roots, cwd.join(AGENTS_SKILL_DIR).join(SKILLS_DIR));+ push_unique_skill_root(&mut roots, cwd.join(DEVIN_SKILL_DIR).join(SKILLS_DIR));if let Some(home) = home {push_unique_skill_root(&mut roots, home.join(CLAUDE_SKILL_DIR).join(SKILLS_DIR));push_unique_skill_root(&mut roots, home.join(AGENTS_SKILL_DIR).join(SKILLS_DIR));+ push_unique_skill_root(&mut roots, home.join(DEVIN_SKILL_DIR).join(SKILLS_DIR));}roots}@@ -351,7 +391,12 @@ fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhowfor op in ops {out = match *op {RewriteOp::Instructions => strip_instructions_block(&out).0,- RewriteOp::HooksJson => strip_ai_memory_hooks(&out)?.new_content,+ RewriteOp::HooksJson(HookConfigShape::NestedHooksKey) => {+ strip_ai_memory_hooks(&out)?.new_content+ }+ RewriteOp::HooksJson(HookConfigShape::FlatHookFile) => {+ strip_ai_memory_hooks_flat(&out)?.new_content+ }RewriteOp::AntigravityHooksJson => {strip_antigravity_hooks(&out)?.new_content}@@ -584,6 +629,30 @@ fn strip_hook_entry(entry: &mut serde_json::Value) -> (bool, bool) {(false, false)}+fn strip_hook_events(+ hooks: &mut serde_json::Map<String, serde_json::Value>,+ removed_events: &mut Vec<String>,+) {+ let events: Vec<String> = hooks.keys().cloned().collect();+ for event in events {+ let Some(arr) = hooks.get_mut(&event).and_then(|v| v.as_array_mut()) else {+ continue;+ };+ let mut removed_from_event = false;+ arr.retain_mut(|entry| {+ let (removed, remove_entry) = strip_hook_entry(entry);+ removed_from_event |= removed;+ !remove_entry+ });+ if removed_from_event {+ removed_events.push(event.clone());+ }+ if arr.is_empty() {+ hooks.remove(&event);+ }+ }+}+/// Remove ai-memory hook entries from a settings/hooks JSON document./// Preserves third-party entries (including siblings under the same/// event). Prunes an event key when emptied and the `hooks` object@@ -595,24 +664,7 @@ fn strip_ai_memory_hooks(content: &str) -> Result<HookRemoval> {let Some(hooks) = root.get_mut("hooks").and_then(|h| h.as_object_mut()) else {return Ok(());};- let events: Vec<String> = hooks.keys().cloned().collect();- for event in events {- let Some(arr) = hooks.get_mut(&event).and_then(|v| v.as_array_mut()) else {- continue;- };- let mut removed_from_event = false;- arr.retain_mut(|entry| {- let (removed, remove_entry) = strip_hook_entry(entry);- removed_from_event |= removed;- !remove_entry- });- if removed_from_event {- removed_events.push(event.clone());- }- if arr.is_empty() {- hooks.remove(&event);- }- }+ strip_hook_events(hooks, &mut removed_events);if hooks.is_empty() {root.remove("hooks");}@@ -653,6 +705,21 @@ fn strip_zero_hooks(content: &str) -> Result<HookRemoval> {})}+/// Remove ai-memory hook entries from Devin's `hooks.v1.json`, whose root+/// object is the hook-event map. This is intentionally separate from+/// `strip_ai_memory_hooks` so we never infer a flat shape for other agents.+fn strip_ai_memory_hooks_flat(content: &str) -> Result<HookRemoval> {+ let mut removed_events = Vec::new();+ let new_content = mutate_json(content, |root| {+ strip_hook_events(root, &mut removed_events);+ Ok(())+ })?;+ Ok(HookRemoval {+ new_content,+ removed_events,+ })+}+/// Remove ai-memory's named Antigravity CLI hook group entries. The group/// name alone is not enough to prove ownership; every removed entry must still/// carry ai-memory's hook command signature.@@ -757,7 +824,8 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {| McpClient::Cursor| McpClient::GeminiCli| McpClient::Omp- | McpClient::AntigravityCli => Some(&["mcpServers"]),+ | McpClient::AntigravityCli+ | McpClient::Devin => Some(&["mcpServers"]),McpClient::OpenCode => Some(&["mcp"]),McpClient::Openclaw | McpClient::Zero => Some(&["mcp", "servers"]),McpClient::VsCodeCopilot => Some(&["servers"]),@@ -1177,6 +1245,40 @@ mod tests {);}+ // Devin's hooks.v1.json: the root object IS the event map (no "hooks"+ // wrapper). Mirrors strip_zero_hooks_removes_only_prefixed_ids above,+ // but for Devin's flat shape and command-signature ownership (entries+ // have no "id" field to prefix-match on).+ #[test]+ fn strip_ai_memory_hooks_flat_removes_only_ours_and_preserves_third_party() {+ let content = r#"{+ "SessionStart": [+ {"type": "command", "command": "AI_MEMORY_HOOK_URL=http://h /x/session-start.sh"}+ ],+ "PostToolUse": [+ {"type": "command", "command": "AI_MEMORY_HOOK_URL=http://h /x/post-tool-use.sh"},+ {"type": "command", "command": "/home/u/scripts/my-logger.sh"}+ ]+ }"#;+ let out = strip_ai_memory_hooks_flat(content).unwrap();+ assert_eq!(+ out.removed_events,+ vec!["SessionStart".to_string(), "PostToolUse".to_string()]+ );+ let v: serde_json::Value = serde_json::from_str(&out.new_content).unwrap();+ assert!(v.get("SessionStart").is_none(), "emptied event key removed");+ let post_tool_use = v["PostToolUse"].as_array().unwrap();+ assert_eq!(post_tool_use.len(), 1, "only ours removed");+ assert_eq!(+ post_tool_use[0]["command"].as_str(),+ Some("/home/u/scripts/my-logger.sh")+ );+ assert!(+ v.get("hooks").is_none(),+ "flat file must not gain a nested 'hooks' wrapper"+ );+ }+#[test]fn strip_antigravity_hooks_removes_only_signed_entries() {let content = r#"{diff --git a/crates/ai-memory-cli/tests/packaging.rs b/crates/ai-memory-cli/tests/packaging.rsindex 54476de8..1cb3d4c7 100644--- a/crates/ai-memory-cli/tests/packaging.rs+++ b/crates/ai-memory-cli/tests/packaging.rs@@ -214,6 +214,13 @@ fn run_wrapper_with_fake_docker(args: &[&str], docker_info_stdout: &str) -> Strirun_wrapper_with_fake_docker_and_uname(args, docker_info_stdout, None)}+// The wrapper also shells out to `id -u` / `id -g` when choosing its default+// Docker uid mapping. Arch container tests often run as root, which would make+// the default mapping `-u 0:0` and produce a false positive in the assertions+// below. Shadow `id` too so these tests exercise the rootless/rootful branch+// logic, not the uid of the test runner. This shadow is unconditional+// (unlike `uname`, which only matters for the macOS-simulation callers)+// because every caller of this helper is exposed to the flakiness.#[cfg(unix)]fn run_wrapper_with_fake_docker_and_uname(args: &[&str],@@ -224,6 +231,7 @@ fn run_wrapper_with_fake_docker_and_uname(let docker_args = tmp.path().join("docker-args.txt");let docker = tmp.path().join("docker");let uname = tmp.path().join("uname");+ let id = tmp.path().join("id");std::fs::write(&docker,format!(@@ -243,6 +251,16 @@ fn run_wrapper_with_fake_docker_and_uname().unwrap();}+ std::fs::write(+ &id,+ "#!/usr/bin/env bash\n\+ case \"$1\" in\n\+ -u) printf '1000\\n' ;;\n\+ -g) printf '1000\\n' ;;\n\+ *) printf 'uid=1000 gid=1000 groups=1000\\n' ;;\n\+ esac\n",+ )+ .unwrap();#[cfg(unix)]{use std::os::unix::fs::PermissionsExt;@@ -250,29 +268,26 @@ fn run_wrapper_with_fake_docker_and_uname(if uname_stdout.is_some() {std::fs::set_permissions(&uname, std::fs::Permissions::from_mode(0o755)).unwrap();}+ std::fs::set_permissions(&id, std::fs::Permissions::from_mode(0o755)).unwrap();}- let path = if uname_stdout.is_some() {- Some(format!(- "{}:{}",- shell_path(tmp.path()),- std::env::var("PATH").unwrap_or_default()- ))- } else {- None- };-+ // Always prepend the fake-binary dir to PATH: `id` is shadowed+ // unconditionally (see comment above), so PATH must always change, even+ // when `uname_stdout` is None and only `docker`/`id` are shadowed.+ let path = format!(+ "{}:{}",+ shell_path(tmp.path()),+ std::env::var("PATH").unwrap_or_default()+ );let mut command = shell_script_command(&repo_root().join("bin/ai-memory"));command.args(args)+ .env("PATH", path).env("AI_MEMORY_DOCKER", shell_path(&docker)).env("AI_MEMORY_NO_VERSION_CHECK", "1").env("AI_MEMORY_DATA_VOLUME", "test-ai-memory-data").env("HOME", shell_path(tmp.path())).env_remove("AI_MEMORY_SERVER_URL");- if let Some(path) = path {- command.env("PATH", path);- }let output = command.output().unwrap();assert!(output.status.success(),diff --git a/crates/ai-memory-cli/tests/removal.rs b/crates/ai-memory-cli/tests/removal.rsindex d04929f7..093fa1a8 100644--- a/crates/ai-memory-cli/tests/removal.rs+++ b/crates/ai-memory-cli/tests/removal.rs@@ -468,14 +468,18 @@ fn default_uninstall_removes_managed_skills_across_roots_and_preserves_user_contlet project_claude = project.path().join(".claude/skills");let project_agents = project.path().join(".agents/skills");+ let project_devin = project.path().join(".devin/skills");let global_claude = home.path().join(".claude/skills");let global_agents = home.path().join(".agents/skills");+ let global_devin = home.path().join(".devin/skills");let managed_paths = [project_claude.join(MANAGED_SKILLS[0].relative_path),project_agents.join(MANAGED_SKILLS[2].relative_path),+ project_devin.join(MANAGED_SKILLS[1].relative_path),global_claude.join(MANAGED_SKILLS[3].relative_path),global_agents.join(MANAGED_SKILLS[4].relative_path),+ global_devin.join(MANAGED_SKILLS[0].relative_path),];for path in &managed_paths {write_file(path, &managed_content);@@ -526,7 +530,11 @@ fn default_uninstall_removes_managed_skills_across_roots_and_preserves_user_cont"empty managed skill directory should be removed");assert!(- !global_claude.exists() && !global_agents.exists(),+ !project_devin.exists(),+ "empty Devin skills root should be removed"+ );+ assert!(+ !global_claude.exists() && !global_agents.exists() && !global_devin.exists(),"empty global skill roots should be removed");}@@ -781,3 +789,126 @@ fn purge_data_refuses_when_sibling_alive() {"no wiring should be removed when the purge is refused up front");}++#[test]+fn uninstall_devin_hooks_preserves_user_entries() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let devin = home.path().join(".devin");+ std::fs::create_dir_all(&devin).unwrap();+ let hooks = devin.join("hooks.v1.json");+ std::fs::write(+ &hooks,+ r#"{+ "SessionStart": [+ {"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/session-start.sh"},+ {"type":"command","command":"/usr/bin/user-session-start"}+ ],+ "SessionEnd": [+ {"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/session-end.sh"}+ ]+ }"#,+ )+ .unwrap();++ let status = command_with_home(home.path())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let after: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&hooks).unwrap()).unwrap();+ assert_eq!(+ after["SessionStart"].as_array().unwrap().len(),+ 1,+ "third-party entry in same event must survive"+ );+ assert!(after.get("SessionEnd").is_none());+ assert!(+ after.get("hooks").is_none(),+ "hooks.v1.json must remain flat"+ );+}++#[test]+fn uninstall_devin_removes_from_both_targets() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let devin = home.path().join(".devin");+ std::fs::create_dir_all(&devin).unwrap();++ // Both hooks.v1.json and config.json with ai-memory entries+ let hooks_v1 = devin.join("hooks.v1.json");+ std::fs::write(+ &hooks_v1,+ r#"{"SessionStart":[{"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/session-start.sh"}]}"#,+ )+ .unwrap();++ let config = devin.join("config.json");+ std::fs::write(+ &config,+ r#"{"hooks":{"SessionStart":[{"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/session-start.sh"}]}}"#,+ )+ .unwrap();++ let status = command_with_home(home.path())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let after_hooks: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&hooks_v1).unwrap()).unwrap();+ assert!(after_hooks.get("SessionStart").is_none());+ assert!(+ after_hooks.get("hooks").is_none(),+ "hooks.v1.json must remain flat"+ );++ let after_config: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();+ assert!(after_config["hooks"].get("SessionStart").is_none());+}++#[test]+fn uninstall_mcp_removes_devin_only() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let devin = home.path().join(".devin");+ std::fs::create_dir_all(&devin).unwrap();+ let config = devin.join("config.json");+ std::fs::write(+ &config,+ r#"{+ "mcpServers": {+ "ai-memory": {"url":"http://127.0.0.1:49374/mcp"},+ "other-mcp": {"url":"http://other/mcp"}+ }+ }"#,+ )+ .unwrap();++ let status = command_with_home(home.path())+ .args([+ "uninstall",+ "--apply",+ "--only",+ "mcp",+ "--mcp-url",+ "http://127.0.0.1:49374/mcp",+ "--yes",+ ])+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let after: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();+ assert!(after["mcpServers"].get("ai-memory").is_none());+ assert!(+ after["mcpServers"].get("other-mcp").is_some(),+ "third-party MCP server must survive"+ );+}diff --git a/crates/ai-memory-cli/tests/routing_instructions.rs b/crates/ai-memory-cli/tests/routing_instructions.rsindex 2023acfd..82fca471 100644--- a/crates/ai-memory-cli/tests/routing_instructions.rs+++ b/crates/ai-memory-cli/tests/routing_instructions.rs@@ -340,3 +340,57 @@ fn legacy_long_marker_block_rerun_upgrades_in_place_to_slim_snippet() {1);}++#[test]+fn devin_install_instructions_targets_agents_md() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();++ // Create AGENTS.md first so it gets picked up instead of defaulting to CLAUDE.md+ fs::write(project.path().join("AGENTS.md"), "# Project\n").unwrap();++ let output = run_ai_memory(+ project.path(),+ home.path(),+ &[+ "install-instructions",+ "--skills-agent",+ "devin",+ "--no-skills",+ ],+ );+ assert_success(output);++ let agents_md = fs::read_to_string(project.path().join("AGENTS.md")).unwrap();+ assert!(agents_md.contains(MARKER_START));+ assert!(agents_md.contains("Use the installed ai-memory Agent Skills"));+ assert!(!project.path().join("CLAUDE.md").exists());+}++#[test]+fn devin_install_instructions_writes_project_devin_skills() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();++ fs::write(project.path().join("AGENTS.md"), "# Project\n").unwrap();++ let output = run_ai_memory(+ project.path(),+ home.path(),+ &["install-instructions", "--skills-agent", "devin"],+ );+ assert_success(output);++ let agents_md = fs::read_to_string(project.path().join("AGENTS.md")).unwrap();+ assert!(agents_md.contains(MARKER_START));+ assert!(agents_md.contains("Use the installed ai-memory Agent Skills"));++ let devin_skill = project+ .path()+ .join(".devin/skills/ai-memory-handoff/SKILL.md");+ let skill_content = fs::read_to_string(&devin_skill)+ .unwrap_or_else(|err| panic!("expected Devin skill {}: {err}", devin_skill.display()));+ assert!(skill_content.contains(MANAGED_MARKER));+ assert!(!project.path().join(".claude/skills").exists());+ assert!(!project.path().join(".agents/skills").exists());+}diff --git a/crates/ai-memory-consolidate/src/projection.rs b/crates/ai-memory-consolidate/src/projection.rsindex 9bb40bca..9844a4c2 100644--- a/crates/ai-memory-consolidate/src/projection.rs+++ b/crates/ai-memory-consolidate/src/projection.rs@@ -351,8 +351,9 @@ fn observation_score(obs: &Observation, idx: usize, total: usize) -> i32 {score += match obs.kind {ObservationKind::UserPrompt => 100,ObservationKind::SessionEnd => 95,- ObservationKind::Stop => 55,ObservationKind::PreCompact => 90,+ ObservationKind::PostCompaction => 85,+ ObservationKind::Stop => 55,ObservationKind::PostToolUse => 30,ObservationKind::Notification => 25,ObservationKind::SessionStart => 20,diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 12b1e547..14638b47 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -200,6 +200,8 @@ pub enum AgentKind {Grok,/// Zero coding agent (Gitlawb/zero).Zero,+ /// Devin CLI (Cognition).+ Devin,/// Anything else (manual capture, future agents).Other,}@@ -210,7 +212,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; 13] = [+ pub const ALL: [Self; 14] = [Self::ClaudeCode,Self::Codex,Self::OpenCode,@@ -223,6 +225,7 @@ impl AgentKind {Self::Pi,Self::Grok,Self::Zero,+ Self::Devin,Self::Other,];@@ -242,6 +245,7 @@ impl AgentKind {Self::Pi => "pi",Self::Grok => "grok",Self::Zero => "zero",+ Self::Devin => "devin",Self::Other => "other",}}@@ -264,6 +268,7 @@ impl AgentKind {"omp" | "oh-my-pi" => Self::Omp,"grok" => Self::Grok,"zero" => Self::Zero,+ "devin" => Self::Devin,_ => Self::Other,}}@@ -335,6 +340,25 @@ mod tests {assert!(!AgentKind::Other.session_start_injects_handoff());}+ #[test]+ fn agent_kind_devin_round_trips() {+ assert_eq!(AgentKind::Devin.as_str(), "devin");+ assert_eq!(AgentKind::from_wire("devin"), AgentKind::Devin);+ // serde uses rename_all = "kebab-case" → "devin".+ assert_eq!(+ serde_json::to_string(&AgentKind::Devin).unwrap(),+ "\"devin\""+ );+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"devin\"").unwrap(),+ AgentKind::Devin+ );+ // Unknown tags still degrade to Other.+ assert_eq!(AgentKind::from_wire("devin-2"), AgentKind::Other);+ // Devin can inject the session-start handoff (consumes additionalContext).+ assert!(AgentKind::Devin.session_start_injects_handoff());+ }+#[test]fn page_path_rejects_backslashes_and_windows_prefixes() {assert!(PagePath::new(r"notes\secret.md").is_err());@@ -400,5 +424,14 @@ mod tests {let antigravity = serde_json::to_string(&AgentKind::AntigravityCli).unwrap();assert_eq!(antigravity, "\"antigravity-cli\"");++ let devin = serde_json::to_string(&AgentKind::Devin).unwrap();+ assert_eq!(devin, "\"devin\"");+ assert_eq!(AgentKind::Devin.as_str(), "devin");+ assert_eq!(AgentKind::from_wire("devin"), AgentKind::Devin);+ assert_eq!(+ serde_json::from_str::<AgentKind>(&devin).unwrap(),+ AgentKind::Devin+ );}}diff --git a/crates/ai-memory-core/src/observation.rs b/crates/ai-memory-core/src/observation.rsindex c8775e35..c45ceef3 100644--- a/crates/ai-memory-core/src/observation.rs+++ b/crates/ai-memory-core/src/observation.rs@@ -27,6 +27,8 @@ pub enum ObservationKind {PostToolUse,/// Compaction event (context window pressure).PreCompact,+ /// Post-compaction event (Devin-specific, after context compaction).+ PostCompaction,/// Agent emitted a notification.Notification,/// Agent finished its turn.@@ -47,6 +49,7 @@ impl ObservationKind {Self::PreToolUse => "pre-tool-use",Self::PostToolUse => "post-tool-use",Self::PreCompact => "pre-compact",+ Self::PostCompaction => "post-compaction",Self::Notification => "notification",Self::Stop => "stop",Self::SessionEnd => "session-end",@@ -65,6 +68,7 @@ impl std::str::FromStr for ObservationKind {"pre-tool-use" | "pre_tool_use" | "PreToolUse" => Ok(Self::PreToolUse),"post-tool-use" | "post_tool_use" | "PostToolUse" => Ok(Self::PostToolUse),"pre-compact" | "pre_compact" | "PreCompact" => Ok(Self::PreCompact),+ "post-compaction" | "post_compaction" | "PostCompaction" => Ok(Self::PostCompaction),"notification" | "Notification" => Ok(Self::Notification),"stop" | "Stop" => Ok(Self::Stop),"session-end" | "session_end" | "SessionEnd" => Ok(Self::SessionEnd),@@ -158,6 +162,7 @@ mod tests {ObservationKind::PreToolUse,ObservationKind::PostToolUse,ObservationKind::PreCompact,+ ObservationKind::PostCompaction,ObservationKind::Notification,ObservationKind::Stop,ObservationKind::SessionEnd,@@ -177,5 +182,9 @@ mod tests {"session_start".parse::<ObservationKind>().unwrap(),ObservationKind::SessionStart,);+ assert_eq!(+ "PostCompaction".parse::<ObservationKind>().unwrap(),+ ObservationKind::PostCompaction,+ );}}diff --git a/crates/ai-memory-core/src/routing_skills.rs b/crates/ai-memory-core/src/routing_skills.rsindex 963e28dc..4e99ed84 100644--- a/crates/ai-memory-core/src/routing_skills.rs+++ b/crates/ai-memory-core/src/routing_skills.rs@@ -10,6 +10,8 @@ pub const MANAGED_MARKER: &str = "<!-- ai-memory-managed: routing-skill -->";pub const CLAUDE_SKILL_DIR: &str = ".claude";/// AGENTS-aware cross-client Agent Skill directory below a project or home root.pub const AGENTS_SKILL_DIR: &str = ".agents";+/// Devin-compatible Agent Skill directory below a project or home root.+pub const DEVIN_SKILL_DIR: &str = ".devin";/// Leaf directory that contains individual Agent Skill directories.pub const SKILLS_DIR: &str = "skills";diff --git a/crates/ai-memory-hooks/src/log.rs b/crates/ai-memory-hooks/src/log.rsindex 994e99da..80303ddc 100644--- a/crates/ai-memory-hooks/src/log.rs+++ b/crates/ai-memory-hooks/src/log.rs@@ -89,6 +89,7 @@ fn format_line(when: Timestamp, event: HookEvent, title: &str) -> String {HookEvent::PreToolUse => "pre-tool-use",HookEvent::PostToolUse => "post-tool-use",HookEvent::PreCompact => "pre-compact",+ HookEvent::PostCompaction => "post-compaction",HookEvent::Notification => "notification",HookEvent::Stop => "stop",HookEvent::SessionEnd => "session-end",diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 948987cc..79198d27 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -22,6 +22,9 @@ pub struct HookQuery {/// Project name override (same source as `workspace`). When/// `None` the server falls back to `basename(cwd)`.pub project: Option<String>,+ /// Session identifier supplied by a host-side bridge when the agent's+ /// native hook payload does not include one. Body values still win.+ pub session_id: Option<String>,/// Optional project derivation strategy from `.ai-memory.toml`./// `repo-root` makes the server derive project identity from the/// main git repository root instead of `basename(cwd)`.@@ -59,8 +62,9 @@ pub struct HookEnvelope {pub event: HookEvent,/// Agent CLI identifier.pub agent: AgentKind,- /// Session identifier, if found in the body. Required for everything- /// except the initial `SessionStart`.+ /// Session identifier from the body, or from the query string when a+ /// host-side bridge had to supply it. Required for everything except the+ /// initial `SessionStart`.pub session_id: Option<String>,/// Current working directory at the time of the event.pub cwd: Option<String>,@@ -171,6 +175,8 @@ pub enum HookEvent {PostToolUse,/// Compaction event (context window pressure).PreCompact,+ /// Post-compaction event (Devin-specific, after context compaction).+ PostCompaction,/// Agent emitted a notification.Notification,/// Agent finished its turn (interactive `/stop` or natural end).@@ -203,6 +209,7 @@ impl HookEvent {"pre-compact" | "pre_compact" | "PreCompact" | "preCompact" | "PreCompress" => {Self::PreCompact}+ "post-compaction" | "post_compaction" | "PostCompaction" => Self::PostCompaction,"notification" | "Notification" => Self::Notification,"stop" | "Stop" => Self::Stop,"session-end" | "session_end" | "SessionEnd" | "sessionEnd" => Self::SessionEnd,@@ -224,6 +231,7 @@ impl HookEvent {Self::PreToolUse => ObservationKind::PreToolUse,Self::PostToolUse => ObservationKind::PostToolUse,Self::PreCompact => ObservationKind::PreCompact,+ Self::PostCompaction => ObservationKind::PostCompaction,Self::Notification => ObservationKind::Notification,Self::Stop => ObservationKind::Stop,Self::SessionEnd => ObservationKind::SessionEnd,@@ -256,7 +264,7 @@ impl HookEnvelope {// Codex `sessionId`, and Antigravity CLI uses `conversationId`.// JSON keys are case-sensitive, so all spellings must be listed// or tool events fail the router's "missing session_id" check.- let session_id = extract_string(+ let body_session_id = extract_string(&raw,&["session_id",@@ -281,6 +289,7 @@ impl HookEnvelope {],)});+ let session_id = body_session_id.or_else(|| query.session_id.filter(|s| !s.is_empty()));let body_cwd = extract_string(&raw, &["cwd", "current_dir", "working_dir", "directory"]).or_else(|| extract_first_string_array_item(&raw, &["workspacePaths"])).or_else(|| {@@ -462,6 +471,7 @@ fn best_title_hint(event: HookEvent, raw: &serde_json::Value) -> Option<String>})}HookEvent::Notification => extract_string(raw, &["message", "text"]),+ HookEvent::PostCompaction => extract_string(raw, &["summary"]),_ => None,}}@@ -553,6 +563,7 @@ fn best_body_excerpt(event: HookEvent, raw: &serde_json::Value) -> Option<StringSome(format!("tool: {tool}\n---\n{}", truncate_excerpt(&result)))}HookEvent::Notification => extract_content(raw, &["message", "text"]),+ HookEvent::PostCompaction => extract_content(raw, &["summary"]),_ => None,}}@@ -725,6 +736,28 @@ mod tests {HookEvent::SessionEnd.to_observation_kind(),ObservationKind::SessionEnd);+ assert_eq!(+ HookEvent::PostCompaction.to_observation_kind(),+ ObservationKind::PostCompaction+ );+ }++ #[test]+ fn hook_event_parses_post_compaction() {+ assert_eq!(+ HookEvent::parse("post-compaction"),+ HookEvent::PostCompaction+ );+ assert_eq!(+ HookEvent::parse("post_compaction"),+ HookEvent::PostCompaction+ );+ assert_eq!(+ HookEvent::parse("PostCompaction"),+ HookEvent::PostCompaction+ );+ // Unknown event still maps to Other.+ assert_eq!(HookEvent::parse("unknown-event"), HookEvent::Other);}#[test]@@ -764,6 +797,107 @@ mod tests {assert_eq!(env.title_hint.as_deref(), Some("claude-sonnet-4-6"));}+ #[test]+ fn envelope_uses_query_session_id_when_body_omits_it() {+ let q = HookQuery {+ event: "post-tool-use".into(),+ agent: Some("devin".into()),+ session_id: Some("bridge-session-123".into()),+ ..Default::default()+ };+ let raw = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "tool_name": "exec",+ "tool_input": {"command": "ls"},+ "tool_use_id": "call_c101a272288d400b831e1498",+ "tool_response": {"success": true, "output": "ok", "error": null}+ });++ let env = HookEnvelope::from_query_and_body(q, raw);++ assert_eq!(env.event, HookEvent::PostToolUse);+ assert_eq!(env.agent, AgentKind::Devin);+ assert_eq!(env.session_id.as_deref(), Some("bridge-session-123"));+ }++ #[test]+ fn envelope_body_session_id_wins_over_query_session_id() {+ let q = HookQuery {+ event: "post-tool-use".into(),+ agent: Some("devin".into()),+ session_id: Some("bridge-session-123".into()),+ ..Default::default()+ };+ let raw = serde_json::json!({+ "session_id": "body-session-456",+ "hook_event_name": "PostToolUse",+ "tool_name": "exec"+ });++ let env = HookEnvelope::from_query_and_body(q, raw);++ assert_eq!(env.session_id.as_deref(), Some("body-session-456"));+ }++ #[test]+ fn envelope_uses_query_cwd_when_body_omits_it() {+ let q = HookQuery {+ event: "post-tool-use".into(),+ agent: Some("devin".into()),+ cwd: Some("/resolved/from/hook".into()),+ session_id: Some("bridge-session-123".into()),+ ..Default::default()+ };+ let raw = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "tool_name": "exec",+ "tool_input": {"command": "ls"},+ "tool_use_id": "call_c101a272288d400b831e1498",+ "tool_response": {"success": true, "output": "ok", "error": null}+ });++ let env = HookEnvelope::from_query_and_body(q, raw);++ assert_eq!(env.agent, AgentKind::Devin);+ assert_eq!(env.session_id.as_deref(), Some("bridge-session-123"));+ assert_eq!(env.cwd.as_deref(), Some("/resolved/from/hook"));+ }++ #[test]+ fn envelope_body_cwd_wins_over_query_cwd() {+ let q = HookQuery {+ event: "post-tool-use".into(),+ agent: Some("devin".into()),+ cwd: Some("/resolved/from/hook".into()),+ ..Default::default()+ };+ let raw = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "cwd": "/native/from/body"+ });++ let env = HookEnvelope::from_query_and_body(q, raw);++ assert_eq!(env.cwd.as_deref(), Some("/native/from/body"));+ }++ #[test]+ fn devin_real_session_start_fixture_has_no_native_session_or_cwd() {+ let q = HookQuery {+ event: "session-start".into(),+ agent: Some("devin".into()),+ ..Default::default()+ };+ let raw = serde_json::json!({+ "source": "startup"+ });+ let env = HookEnvelope::from_query_and_body(q, raw);+ assert_eq!(env.event, HookEvent::SessionStart);+ assert_eq!(env.agent, AgentKind::Devin);+ assert!(env.session_id.is_none());+ assert!(env.cwd.is_none());+ }+#[test]fn envelope_parses_project_strategy_query() {let env = HookEnvelope::from_query_and_body(diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 87602316..a8296652 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -1551,10 +1551,21 @@ async fn process(// the working state before the agent's compaction throws it out// of context. Does NOT end the session and does NOT create a// handoff. The eventual SessionEnd supersedes this page.- if matches!(env.event, HookEvent::PreCompact)- && let Err(e) = consolidate_or_synth(state, session_id, ws, proj).await+ //+ // On PostCompaction (Devin), refresh `sessions/<id>.md` after the+ // agent's compaction has completed. This is a post-facto checkpoint+ // that captures the state after compaction. Does NOT end the session+ // and does NOT create a handoff. The eventual SessionEnd supersedes+ // this page.+ let checkpoint_label = match env.event {+ HookEvent::PreCompact => Some("pre-compact"),+ HookEvent::PostCompaction => Some("post-compaction"),+ _ => None,+ };+ if let Some(checkpoint_label) = checkpoint_label+ && let Err(e) = consolidate_or_synth(state, session_id, ws, proj, checkpoint_label).await{- warn!(error = %e, "PreCompact consolidation failed; continuing");+ warn!(error = %e, "PreCompact/PostCompaction consolidation failed; continuing");}// On SessionEnd, synthesize the summary page, end the session, and@@ -1735,23 +1746,26 @@ fn build_auto_handoff(}/// Write a fresh `sessions/<id>.md` for the current session without-/// ending it. Used by the PreCompact branch to checkpoint state before-/// the agent's working context collapses.+/// ending it. Used by the PreCompact and PostCompaction branches to checkpoint+/// state before/after the agent's working context collapses.async fn consolidate_or_synth(state: &HookState,session_id: SessionId,workspace_id: WorkspaceId,project_id: ProjectId,+ checkpoint_label: &str,) -> anyhow::Result<()> {if let Some(c) = state.consolidator.as_ref() {let outcome = c.consolidate_session(session_id, false).await?;debug!(session = %session_id,path = %outcome.path,- "PreCompact: LLM consolidation written",+ "{}: LLM consolidation written",+ checkpoint_label);let _ = state.wiki.commit_all(&format!(- "pre-compact(session {}): checkpoint",+ "{}(session {}): checkpoint",+ checkpoint_label,short_id(&session_id.to_string()),));return Ok(());@@ -1778,10 +1792,11 @@ async fn consolidate_or_synth(}).await?;let _ = state.wiki.commit_all(&format!(- "pre-compact(session {}): checkpoint",+ "{}(session {}): checkpoint",+ checkpoint_label,short_id(&session_id.to_string()),));- debug!(session = %session_id, "PreCompact: rule-based checkpoint written");+ debug!(session = %session_id, "{}: rule-based checkpoint written", checkpoint_label);Ok(())}@@ -1794,7 +1809,7 @@ const fn importance_for(event: HookEvent) -> u8 {HookEvent::SessionStart | HookEvent::SessionEnd => 7,HookEvent::UserPrompt => 8,HookEvent::PostToolUse | HookEvent::PreToolUse => 5,- HookEvent::Stop | HookEvent::PreCompact => 6,+ HookEvent::Stop | HookEvent::PreCompact | HookEvent::PostCompaction => 6,HookEvent::Notification| HookEvent::Other| HookEvent::SubagentStart@@ -5437,4 +5452,229 @@ mod tests {"Windows path must not fall back to the server-default project");}++ #[tokio::test]+ async fn post_compaction_captures_summary_field() {+ let tmp = TempDir::new().unwrap();+ let _state = make_state(&tmp).await;++ let query = HookQuery {+ event: "post-compaction".into(),+ agent: Some("devin".into()),+ ..Default::default()+ };+ let raw = serde_json::json!({+ "hook_event_name": "PostCompaction",+ "summary": "Test summary field"+ });++ let env = HookEnvelope::from_query_and_body(query, raw);+ assert_eq!(+ env.title_hint.as_deref(),+ Some("Test summary field"),+ "PostCompaction should extract summary as title hint"+ );+ assert_eq!(+ env.body_excerpt.as_deref(),+ Some("Test summary field"),+ "PostCompaction should extract summary as body excerpt"+ );+ }++ #[tokio::test]+ async fn post_compaction_priority_is_mapped() {+ let tmp = TempDir::new().unwrap();+ let _state = make_state(&tmp).await;++ let query = HookQuery {+ event: "post-compaction".into(),+ agent: Some("devin".into()),+ ..Default::default()+ };+ let raw = serde_json::json!({+ "hook_event_name": "PostCompaction",+ "summary": "Test"+ });++ let env = HookEnvelope::from_query_and_body(query, raw);+ assert_eq!(+ importance_for(env.event),+ 6,+ "PostCompaction should have importance 6 (same as Stop/PreCompact)"+ );+ }++ #[test]+ fn post_compaction_router_branch_exists() {+ // Verify that PostCompaction is handled in the router+ // by checking that the importance_for function includes it.+ // The consolidation branch is covered by the importance check+ // and by the explicit branch in process() that calls consolidate_or_synth.+ assert_eq!(importance_for(HookEvent::PostCompaction), 6);+ }++ #[tokio::test]+ async fn post_compaction_triggers_consolidation() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let sid = "44444444-4444-4444-4444-444444444444";+ let session_path = format!("sessions/{sid}.md");+ let summary = "Context compacted: 15000/20000 tokens used";++ let start = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-start".into(),+ agent: Some("devin".into()),+ ..Default::default()+ },+ serde_json::json!({+ "hook_event_name": "SessionStart",+ "session_id": sid,+ "source": "startup"+ }),+ );+ process(&state, start, None).await.unwrap();++ let pages_before = state+ .reader+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)+ .await+ .unwrap();+ assert!(+ pages_before.iter().all(|p| p.path.as_str() != session_path),+ "SessionStart alone must not write a sessions/<id>.md checkpoint"+ );++ let post_compaction = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-compaction".into(),+ agent: Some("devin".into()),+ ..Default::default()+ },+ serde_json::json!({+ "hook_event_name": "PostCompaction",+ "session_id": sid,+ "summary": summary+ }),+ );+ process(&state, post_compaction, None).await.unwrap();++ let pages_after = state+ .reader+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)+ .await+ .unwrap();+ assert!(+ pages_after.iter().any(|p| p.path.as_str() == session_path),+ "PostCompaction must write a sessions/<id>.md checkpoint"+ );+ }++ #[tokio::test]+ async fn post_compaction_writes_rule_based_session_checkpoint_without_consolidator() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let sid = "44444444-4444-4444-4444-444444444444";+ let session_path = format!("sessions/{sid}.md");+ let summary = "Context compacted: 15000/20000 tokens used";++ let start = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-start".into(),+ agent: Some("devin".into()),+ ..Default::default()+ },+ serde_json::json!({+ "hook_event_name": "SessionStart",+ "session_id": sid,+ "source": "startup"+ }),+ );+ process(&state, start, None).await.unwrap();++ let pages_before = state+ .reader+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)+ .await+ .unwrap();+ assert!(+ pages_before.iter().all(|p| p.path.as_str() != session_path),+ "SessionStart alone must not write a sessions/<id>.md checkpoint"+ );++ let post_compaction = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-compaction".into(),+ agent: Some("devin".into()),+ ..Default::default()+ },+ serde_json::json!({+ "hook_event_name": "PostCompaction",+ "session_id": sid,+ "summary": summary+ }),+ );+ process(&state, post_compaction, None).await.unwrap();++ let pages_after = state+ .reader+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)+ .await+ .unwrap();+ assert!(+ pages_after.iter().any(|p| p.path.as_str() == session_path),+ "PostCompaction must write the rule-based sessions/<id>.md checkpoint; got {:?}",+ pages_after+ .iter()+ .map(|p| p.path.as_str())+ .collect::<Vec<_>>()+ );++ let page = state+ .reader+ .page_body_by_ids(state.workspace_id, state.project_id, &session_path)+ .await+ .unwrap()+ .expect("PostCompaction checkpoint page must be readable from the store");+ assert!(+ page.body.contains("post-compaction"),+ "checkpoint body must include the PostCompaction raw observation: {}",+ page.body+ );+ assert!(+ page.body.contains(summary),+ "checkpoint body must include the Devin summary field: {}",+ page.body+ );+ let checkpoints = state.wiki.recent_checkpoints(5).unwrap();+ assert!(+ checkpoints+ .iter()+ .any(|checkpoint| checkpoint.summary.starts_with("post-compaction(")),+ "PostCompaction checkpoint must use the post-compaction commit label; got {:?}",+ checkpoints+ .iter()+ .map(|checkpoint| checkpoint.summary.as_str())+ .collect::<Vec<_>>()+ );+ assert!(+ checkpoints+ .iter()+ .all(|checkpoint| !checkpoint.summary.starts_with("pre-compact(")),+ "PostCompaction checkpoint must not be labelled as pre-compact; got {:?}",+ checkpoints+ .iter()+ .map(|checkpoint| checkpoint.summary.as_str())+ .collect::<Vec<_>>()+ );+ assert!(+ state+ .reader+ .latest_open_handoff(state.workspace_id, state.project_id, None)+ .await+ .unwrap()+ .is_none(),+ "PostCompaction checkpoint must not create a handoff"+ );+ }}diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 935a3c5b..fae1bafe 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -252,8 +252,9 @@ should be proposed from a completed session, or at explicit wrap-up \ai-memory routing into this project' or 'add ai-memory to \CLAUDE.md / AGENTS.md'. Returns the managed routing package: the \slim markered snippet (`markered_block`), filename hints, \- `managed_skills` payloads, `target_hints` for `.claude/skills` or \- `.agents/skills`, and overwrite guidance. Use your own Write/Edit \+ `managed_skills` payloads, `target_hints` for `.claude/skills`, \+ `.agents/skills`, `.devin/skills`, and Devin's Windows global \+ `%APPDATA%\\devin\\skills` root, and overwrite guidance. Use your own Write/Edit \tool to replace only the ai-memory marker block in the rules file, \then write each managed skill under the selected skill root. Only \replace same-name skill files that contain the ai-memory managed \@@ -2381,7 +2382,7 @@ impl AiMemoryServer {`markered_block` for the slim CLAUDE.md / AGENTS.md snippet, \`agent_filenames` for rules-file targets, `managed_skills` for \Agent Skill files, and `target_hints` for project/global \- `.claude/skills` and `.agents/skills` roots. Use when the user \+ `.claude/skills`, `.agents/skills`, `.devin/skills`, and Devin Windows global roots. Use when the user \asks to install or refresh ai-memory routing in this project. \After calling, use your Write/Edit tool to preserve non-ai-memory \user content: replace only an existing `<!-- ai-memory:start -->` \@@ -2418,17 +2419,23 @@ impl AiMemoryServer {"gemini_cli": "AGENTS.md","antigravity_cli": "AGENTS.md","zero": "AGENTS.md",+ "devin": "AGENTS.md","default": "AGENTS.md"},"managed_skills": managed_skills,"target_hints": {"project": {"claude_code": ".claude/skills",- "agents": ".agents/skills"+ "agents": ".agents/skills",+ "devin": ".devin/skills"},"global": {"claude_code": "~/.claude/skills",- "agents": "~/.agents/skills"+ "agents": "~/.agents/skills",+ "devin": {+ "windows": "%APPDATA%\\devin\\skills",+ "non_windows": "~/.devin/skills"+ }}},"overwrite_guidance": {@@ -2441,7 +2448,7 @@ impl AiMemoryServer {"If the target file already contains <!-- ai-memory:start --> / <!-- ai-memory:end --> delimiters alone on their own lines, replace ONLY that line-delimited block in place; ignore inline mentions and preserve every other line.","If the file doesn't exist, create it with just the markered_block (plus a trailing newline).","If the file exists but has no ai-memory markers, append the markered_block with one blank line of separation from existing content.",- "Install each managed_skills item under the selected skill root from target_hints using its relative_path, for example .claude/skills/<relative_path> or .agents/skills/<relative_path>.",+ "Install each managed_skills item under the selected skill root from target_hints using its relative_path, for example .claude/skills/<relative_path>, .agents/skills/<relative_path>, .devin/skills/<relative_path>, or %APPDATA%\\devin\\skills\\<relative_path> on Windows global Devin installs.","Existing skill files containing the managed marker <!-- ai-memory-managed: routing-skill --> may be replaced; unmanaged same-name skills must not be overwritten unless the human explicitly forces replacement."]});@@ -3234,6 +3241,19 @@ mod tests {response["agent_filenames"]["default"].as_str().unwrap(),"AGENTS.md");+ assert_eq!(+ response["agent_filenames"]["devin"].as_str().unwrap(),+ "AGENTS.md"+ );+ // Proposed symmetrically alongside the devin assertion above:+ // upstream added "zero" to this same payload (issue #156) without a+ // matching assertion. Not validated against a live Zero agent in+ // this environment — for the Zero team to confirm "AGENTS.md" is+ // still the intended target file before relying on this.+ assert_eq!(+ response["agent_filenames"]["zero"].as_str().unwrap(),+ "AGENTS.md"+ );let managed_skills = response["managed_skills"].as_array()@@ -3275,6 +3295,12 @@ mod tests {.unwrap(),".agents/skills");+ assert_eq!(+ response["target_hints"]["project"]["devin"]+ .as_str()+ .unwrap(),+ ".devin/skills"+ );assert_eq!(response["target_hints"]["global"]["claude_code"].as_str()@@ -3287,6 +3313,18 @@ mod tests {.unwrap(),"~/.agents/skills");+ assert_eq!(+ response["target_hints"]["global"]["devin"]["windows"]+ .as_str()+ .unwrap(),+ "%APPDATA%\\devin\\skills"+ );+ assert_eq!(+ response["target_hints"]["global"]["devin"]["non_windows"]+ .as_str()+ .unwrap(),+ "~/.devin/skills"+ );let notes = response["notes"].as_array()@@ -3297,6 +3335,7 @@ mod tests {.join("\n");assert!(notes.contains(ai_memory_core::routing_skills::MANAGED_MARKER));assert!(notes.contains("unmanaged same-name skills"));+ assert!(notes.contains("%APPDATA%\\devin\\skills"));assert!(notes.contains("explicitly forces replacement"));}@@ -3318,8 +3357,10 @@ mod tests {"tool description must tell agents to install snippet and skill payloads; got: {desc}");assert!(- desc.contains(".claude/skills") && desc.contains(".agents/skills"),- "tool description must name Claude and .agents skill targets; got: {desc}"+ desc.contains(".claude/skills")+ && desc.contains(".agents/skills")+ && desc.contains(".devin/skills"),+ "tool description must name Claude, .agents, and Devin skill targets; got: {desc}");assert!(desc.contains("preserve non-ai-memory user content"),diff --git a/crates/ai-memory-store/migrations/V28__sessions_devin_agent_kind.sql b/crates/ai-memory-store/migrations/V28__sessions_devin_agent_kind.sqlnew file mode 100644index 00000000..7d2fd42f--- /dev/null+++ b/crates/ai-memory-store/migrations/V28__sessions_devin_agent_kind.sql@@ -0,0 +1,62 @@+-- Expand sessions.agent_kind CHECK for Devin CLI (Cognition).+--+-- V09/V11/V20/V25/V26 intentionally enumerated every supported agent. Adding+-- a concrete AgentKind must update the persisted CHECK too, or Devin hook+-- events fail at begin_session on upgraded databases (the hook router would+-- WARN and drop the session, silently breaking Devin capture server-side).+-- V26 (the Zero coding agent) landed first, so this migration's CHECK list+-- carries 'zero' forward in addition to adding 'devin' — dropping it here+-- would silently break Zero the same way omitting 'devin' would break us.++PRAGMA foreign_keys = OFF;++DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_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','grok','zero','devin','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL+);++INSERT INTO sessions_new SELECT * 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;++-- Recreate the V18 pairing-enforcement trigger: dropping the old `sessions`+-- table above also dropped its triggers. Every sessions-table rebuild after+-- V18 must reinstate it or the (workspace_id, project_id) pairing invariant+-- silently stops being enforced on inserts.+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;++-- Recreate the V22 claim/session pairing trigger, which references `sessions`+-- and must be dropped before the table rebuild above.+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;++PRAGMA foreign_keys = ON;diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex bdc13181..4fbf3b00 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -2571,6 +2571,7 @@ mod tests {AgentKind::Omp,AgentKind::Pi,AgentKind::Grok,+ AgentKind::Devin,AgentKind::Other,] {let sid = SessionId::new();@@ -3545,6 +3546,113 @@ mod tests {"V25 must recreate the V22 scheduler/session pairing trigger");+ let fk_violations: i64 = conn+ .query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |r| {+ r.get(0)+ })+ .unwrap();+ assert_eq!(fk_violations, 0, "V25 must leave foreign keys clean");+ }++ #[test]+ fn v28_adds_devin_and_preserves_sessions_invariants_on_upgraded_db() {+ use ai_memory_core::{AgentKind, NewSession, SessionId};++ let tmp = TempDir::new().unwrap();+ let db_path = tmp.path().join("test.sqlite");+ let ws;+ let proj;+ let existing_sid = SessionId::new();++ {+ let mut conn = Connection::open(&db_path).unwrap();+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ crate::migrations::run_to(&mut conn, 25).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ ws = get_or_create_workspace(&mut conn, "default").unwrap();+ proj = get_or_create_project(&mut conn, &ws, "scratch", None).unwrap();+ begin_session(+ &mut conn,+ &NewSession {+ id: existing_sid,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::ClaudeCode,+ cwd: None,+ },+ )+ .unwrap();+ }++ // Run through V26 (Zero) and V27 (unrelated data repair) too, not+ // just straight to V28: this proves the whole upgrade chain composes+ // on a pre-V26 database, not just V28 applied in isolation.+ let mut conn = Connection::open(&db_path).unwrap();+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ crate::migrations::run_to(&mut conn, 28).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++ begin_session(+ &mut conn,+ &NewSession {+ id: SessionId::new(),+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Devin,+ cwd: None,+ },+ )+ .unwrap();++ let session_count: i64 = conn+ .query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))+ .unwrap();+ assert_eq!(session_count, 2, "V28 must preserve existing sessions");++ let index_count: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM sqlite_master \+ WHERE type = 'index' \+ AND name IN ('idx_sessions_recent', 'idx_sessions_project', 'idx_sessions_started_at', 'idx_sessions_scope_ended')",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(index_count, 4, "V28 must recreate sessions indexes");++ let trigger_count: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM sqlite_master \+ WHERE type = 'trigger' AND name = 'sessions_ws_proj_pairing_ai'",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(+ trigger_count, 1,+ "V28 must recreate the V18 pairing trigger"+ );++ let scheduler_trigger_count: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM sqlite_master \+ WHERE type = 'trigger' AND name = 'auto_improve_scheduler_claims_session_pairing_ai'",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(+ scheduler_trigger_count, 1,+ "V28 must recreate the V22 scheduler/session pairing trigger"+ );++ let fk_violations: i64 = conn+ .query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |r| {+ r.get(0)+ })+ .unwrap();+ assert_eq!(fk_violations, 0, "V28 must leave foreign keys clean");+let other_ws = get_or_create_workspace(&mut conn, "other").unwrap();let other_proj =get_or_create_project(&mut conn, &other_ws, "other-project", None).unwrap();@@ -3554,7 +3662,7 @@ mod tests {id: SessionId::new(),workspace_id: ws,project_id: other_proj,- agent_kind: AgentKind::Pi,+ agent_kind: AgentKind::Devin,cwd: None,},)@@ -3562,7 +3670,7 @@ mod tests {assert!(err.to_string().contains("sessions.workspace_id does not match"),- "pairing trigger must reject split-brain sessions after V25: {err}"+ "pairing trigger must reject split-brain sessions after V28: {err}");let fk_violations: i64 = conn@@ -3570,7 +3678,10 @@ mod tests {r.get(0)}).unwrap();- assert_eq!(fk_violations, 0, "V25 must leave foreign keys clean");+ assert_eq!(+ fk_violations, 0,+ "V28 must leave foreign keys clean after pairing test"+ );}/// V19 is idempotent: re-running on a repaired DB is a no-op.diff --git a/docs/install.md b/docs/install.mdindex 32b0d221..ba25bd8a 100644--- a/docs/install.md+++ b/docs/install.md@@ -9,7 +9,7 @@ path (docker + Claude Code). This page covers everything else:- [Arch Linux native packages (AUR)](#arch-linux-native-packages-aur)(systemd system service or user service)- [Configuring other agent CLIs](#configuring-other-agent-clis)- (Codex, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, OpenClaw, VS Code Copilot)+ (Codex, Devin CLI, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, OpenClaw, VS Code Copilot)- [Installing hooks without docker](#installing-hooks-without-docker)(curl-based installer)- [Running ai-memory without docker](#running-ai-memory-without-docker)@@ -488,12 +488,12 @@ Each agent CLI needs two things:Without this, the agent can still query memory but capturebecomes manual.-Claude Desktop is MCP-only today. Claude Code, Codex, OpenCode, OMP,-Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, and OpenClaw have lifecycle capture paths through+Claude Desktop is MCP-only today. Claude Code, Codex, Devin CLI, OpenCode,+OMP, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, and OpenClaw have lifecycle capture paths through`install-hooks`.> **Two-step hook install pattern.** Claude Code, Codex, Cursor,-> Gemini CLI, Antigravity CLI, and Grok Build CLI use shell/PowerShell hook scripts: (1) `docker cp` the+> Gemini CLI, Antigravity CLI, Grok Build CLI, and Devin CLI use shell/PowerShell hook scripts: (1) `docker cp` the> bundled scripts to your home dir, (2) `docker run --rm install-hooks`> to render the config snippet.> On native Windows, Claude Code is the exception to the PowerShell default:@@ -534,6 +534,39 @@ ai-memory finalize-session# add --all to close every matching open Codex session in this workspace/project```+### Devin CLI++Devin uses `~/.devin/config.json` for MCP servers and `~/.devin/hooks.v1.json`+for lifecycle hooks by default. If you prefer one combined Devin config file,+pass `--config-file ~/.devin/config.json` to `install-hooks`; ai-memory then+merges the hook entries under that file's `hooks` key.++```bash+ai-memory install-mcp --client devin --apply \+ --server-url "http://homelab:49374/mcp" \+ --auth-token "$TOKEN"++ai-memory install-hooks --agent devin --apply \+ --server-url "http://homelab:49374" \+ --auth-token "$TOKEN"++ai-memory install-skills --agent devin+```++Devin's hook vocabulary is close to Claude Code's, with two important+differences:++- Devin emits `PostCompaction` after compaction and includes a `summary` field;+ ai-memory records it as `post-compaction`.+- Devin does not expose subagent start/stop hooks, so ai-memory cannot capture+ nested subagent boundaries for Devin.++The `SessionStart` hook injects pending handoffs through Devin's+`hookSpecificOutput.additionalContext`. Real Devin `SessionStart` and+`PostToolUse` payloads may omit `session_id` and `cwd`; ai-memory derives stable+session/cwd context from its hook state and process environment so those events+are still captured.+### OpenCode```bash@@ -1057,7 +1090,7 @@ without that marker are preserved unless you explicitly force replacement.|---|---|| `--no-skills` | Refresh only the markered instruction block. || `--skills-scope <scope>` | Choose project-local or user-global skill roots. Values: `project`, `global`. Defaults to `project`. |-| `--skills-agent <agent>` | Choose `.claude/skills`, `.agents/skills`, or both. Values: `claude-code`, `agents`, `both`. By default, `CLAUDE.md` targets imply `claude-code`, `AGENTS.md` targets imply `agents`, and both instruction files imply `both`. |+| `--skills-agent <agent>` | Choose `.claude/skills`, `.agents/skills`, `.devin/skills`, or both Claude/Agents roots. Values: `claude-code`, `agents`, `devin`, `both`. By default, `CLAUDE.md` targets imply `claude-code`, `AGENTS.md` targets imply `agents`, and both instruction files imply `both`. || `--skills-target-dir <dir>` | Write managed skill directories below an explicit root instead of inferring from scope and agent. || `--skills-force` | Replace unmanaged same-name skills during `install-instructions`; without it, they are left untouched and the command exits with an actionable error. |@@ -1067,6 +1100,7 @@ Agent Skill files need a refresh:```bashai-memory install-skillsai-memory install-skills --scope global --agent agents+ai-memory install-skills --scope global --agent devinai-memory install-skills --agent both --printai-memory install-skills --target-dir .custom/skills --force```@@ -1076,17 +1110,17 @@ ai-memory install-skills --target-dir .custom/skills --force| Flag | Meaning ||---|---|| `--scope <scope>` | Install into this project or the current user's global skill roots. Values: `project`, `global`. Defaults to `project`. |-| `--agent <agent>` | Install into Claude Code's skill root, the cross-agent skill root, or both. Values: `claude-code`, `agents`, `both`. Defaults to `claude-code`. |+| `--agent <agent>` | Install into Claude Code's skill root, the cross-agent skill root, Devin's skill root, or both Claude/Agents roots. Values: `claude-code`, `agents`, `devin`, `both`. Defaults to `claude-code`. || `--target-dir <dir>` | Write managed skill directories below an explicit root; `--scope` and `--agent` are ignored. || `--print` | Print target paths and `SKILL.md` contents without writing files. || `--force` | Replace unmanaged same-name skills; without it, user-authored same-name skills are preserved. |Default skill target roots:-| Scope | `--agent claude-code` | `--agent agents` |-|---|---|---|-| `project` | `.claude/skills` | `.agents/skills` |-| `global` | `~/.claude/skills` | `~/.agents/skills` |+| Scope | `--agent claude-code` | `--agent agents` | `--agent devin` |+|---|---|---|---|+| `project` | `.claude/skills` | `.agents/skills` | `.devin/skills` |+| `global` | `~/.claude/skills` | `~/.agents/skills` | Windows: `%APPDATA%\devin\skills`; non-Windows: `~/.devin/skills` |Each managed skill is written as `<root>/<skill-name>/SKILL.md`.diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 25af9c5e..0a7620c1 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -19,9 +19,9 @@This page documents how to register ai-memory as an MCP server withagent CLIs beyond the README quick start.-Claude Code, OpenAI Codex, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, OpenClaw, OpenCode, and+Claude Code, OpenAI Codex, Devin CLI, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, OpenClaw, OpenCode, andOMP have automatic capture integrations (shell/PowerShell hooks for-Claude Code / Codex / Cursor / Gemini CLI / Antigravity CLI / Grok Build CLI, TypeScript plugin/extension+Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Grok Build CLI, TypeScript plugin/extensionfiles for OpenClaw / OpenCode / OMP) and are covered in the[main README](../README.md#quick-start). On native Windows, Claude Code usesGit Bash `.sh` hooks rather than the PowerShell default used by other@@ -447,6 +447,51 @@ capture and session-end handoff *creation* work, but handoff *injection*does not — ask Zero to call `memory_handoff_accept` at the start of aresumed session.+## Devin CLI++Devin manages MCP servers in `~/.devin/config.json` under `mcpServers`:++```bash+ai-memory install-mcp --client devin --apply \+ --server-url "http://homelab:49374/mcp" --auth-token "$TOKEN"+```++which merges:++```json+{+ "mcpServers": {+ "ai-memory": {+ "url": "http://homelab:49374/mcp",+ "transport": "http",+ "headers": { "Authorization": "Bearer <token>" }+ }+ }+}+```++Lifecycle capture is separate:++```bash+ai-memory install-hooks --agent devin --apply \+ --server-url "http://homelab:49374" --auth-token "$TOKEN"+```++By default this writes `~/.devin/hooks.v1.json`, whose root object is the+event map. If you want the hook entries inside `~/.devin/config.json` instead,+pass that path with `--config-file`; ai-memory then merges them under the+`hooks` key.++Devin's supported lifecycle events are `SessionStart`, `UserPromptSubmit`,+`PreToolUse`, `PostToolUse`, `PostCompaction`, `Stop`, and `SessionEnd`.+`PostCompaction` is a Devin post-compaction event with a `summary` field; it is+not Claude Code's `PreCompact`. Devin does not currently expose subagent+start/stop hooks, so there is no Devin subagent capture surface to install.++Session-start handoff injection is built in: the generated Devin SessionStart+hook returns `hookSpecificOutput.additionalContext` when a pending handoff is+available.+## OpenClaw**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via a native@@ -607,8 +652,8 @@ that *starts* the next one - to play nicely with ai-memory:| Side | What's needed | Covered by ||---|---|---|-| **Ending side** | The agent must create a handoff, either through a true session-end hook, the supported Codex manual finalizer, or by calling `memory_handoff_begin`. | Built-in automatically for Claude Code, Cursor, Gemini CLI, Grok Build CLI, Zero, OpenClaw, OpenCode, and OMP. Codex has no reliable true session-end event, so run `ai-memory finalize-session` when you need the final summary/handoff/auto-improve eligibility. Antigravity CLI has no true session-end event in the current integration, so ask it to call `memory_handoff_begin` before quitting when you need a handoff. |-| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Cursor / Gemini CLI / Antigravity CLI / OpenClaw / OpenCode / OMP. Grok is explicitly excluded because it ignores SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |+| **Ending side** | The agent must create a handoff, either through a true session-end hook, the supported Codex manual finalizer, or by calling `memory_handoff_begin`. | Built-in automatically for Claude Code, Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, OpenClaw, OpenCode, and OMP. Codex has no reliable true session-end event, so run `ai-memory finalize-session` when you need the final summary/handoff/auto-improve eligibility. Antigravity CLI has no true session-end event in the current integration, so ask it to call `memory_handoff_begin` before quitting when you need a handoff. |+| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / OpenClaw / OpenCode / OMP. Grok is explicitly excluded because it ignores SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |OpenCode uses its official `session.deleted` plugin event for true session-enddelivery. Its generated plugin also sends a deduped best-effort close for anydiff --git a/docs/usage.md b/docs/usage.mdindex 0a60aa5b..87ac2a38 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -100,7 +100,7 @@ and writes a timestamped backup before changing an existing instruction file.`install-instructions --print` previews the instruction snippet only; use`install-skills --print` to preview skill payloads. Skill flags mirror`install-skills` with an `--skills-` prefix:-`--skills-scope project|global`, `--skills-agent claude-code|agents|both`,+`--skills-scope project|global`, `--skills-agent claude-code|agents|devin|both`,`--skills-target-dir <dir>`, and `--skills-force`.Auto-detect extends `CLAUDE.md` when it exists, `AGENTS.md` when it@@ -115,18 +115,25 @@ To refresh only the managed Agent Skills:```bashai-memory install-skillsai-memory install-skills --scope global --agent agents+ai-memory install-skills --scope global --agent devinai-memory install-skills --agent both --printai-memory install-skills --target-dir .custom/skills --force```-Project-local skill roots are `.claude/skills` for Claude-compatible installs-and `.agents/skills` for cross-client installs. Global roots are-`~/.claude/skills` and `~/.agents/skills`. `--target-dir` points at an explicit-skill root and bypasses scope/agent inference. `--print` previews target paths-and `SKILL.md` contents. `--force` allows replacement of unmanaged same-name-skills; without it, user-authored skills are preserved. Uninstall removes-ai-memory-managed skills from the default project/global roots after marker-validation; custom `--target-dir` roots are a manual cleanup path.+For Devin, project-local skills are installed under `.devin/skills`. Global+Devin installs use `%APPDATA%\devin\skills` on Windows and `~/.devin/skills`+on non-Windows systems.++Project-local skill roots are `.claude/skills` for Claude-compatible installs,+`.agents/skills` for cross-client installs, and `.devin/skills` for Devin+installs. Global Claude/Agents roots are `~/.claude/skills` and+`~/.agents/skills`; global Devin roots are platform-specific as described+above. `--target-dir` points at an explicit skill root and bypasses scope/agent+inference. `--print` previews target paths and `SKILL.md` contents. `--force`+allows replacement of unmanaged same-name skills; without it, user-authored+skills are preserved. Uninstall removes ai-memory-managed skills from the+default project/global roots after marker validation; custom `--target-dir`+roots are a manual cleanup path.This is prompt packaging only. ai-memory does not run a runtime skill router,does not store durable memory in `SKILL.md`, and does not turn the@@ -183,6 +190,8 @@ Client cleanup hints:- Claude Code: check plugins, hooks, old SessionStart injection, and MCP servers.- Codex: check MCP config plus session/user-prompt/tool/compaction/stop hooks.+- Devin CLI: check `.devin/config.json`, `.devin/hooks.v1.json`, and+ `.devin/skills` for stale MCP, hook, or routing-skill entries.- Gemini CLI and Antigravity CLI: check `settings.json` or equivalent hook/MCPconfig files.- OpenCode, OpenClaw, and OMP: check MCP config and plugin/extension directories;@@ -277,7 +286,7 @@ docker exec ai-memory git -C /data/wiki log --oneline## Rules vs factsDurable project rules belong in the agent's rules file, not only in the-wiki. For Claude Code that is `CLAUDE.md`; for Codex, OpenCode,+wiki. For Claude Code that is `CLAUDE.md`; for Codex, Devin CLI, OpenCode,Cursor, and Gemini CLI it is usually `AGENTS.md`.The consolidator classifies compiled observations as `decision`,diff --git a/docs/windows.md b/docs/windows.mdindex 77a3500d..f5d1d447 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -6,7 +6,7 @@ agent CLI actually runs.## Rule Of ThumbRun `install-mcp` and `install-hooks` from the same environment that-launches Claude Code, Codex, Cursor, Gemini CLI, or another agent.+launches Claude Code, Codex, Devin CLI, Cursor, Gemini CLI, or another agent.- If the agent runs inside WSL2, install ai-memory inside WSL2.- If the agent runs as a native Windows process, install ai-memory from@@ -22,8 +22,8 @@ Claude Code invokes its hooks with Claude's direct exec formCommand](#native-hook-command-claude-code-on-windows). Set`AI_MEMORY_HOOK_PLATFORM=windows-bash` to fall back to the older`bash -c` + `.sh` Git Bash commands. Other native Windows script-hook-agents keep the PowerShell `.ps1` default until their harness behavior-is verified.+agents, including Devin CLI, keep the current script-command defaults for+their harness.## Scenario A: Everything Inside WSL2@@ -108,11 +108,17 @@ the CLI to render hook commands for the native Windows agent:exec form (`command` executable + `args` argv array), no shell — set`AI_MEMORY_HOOK_PLATFORM=windows-bash` for the old `bash -c` + `.sh`Git Bash path.-- Other native Windows script-hook agents currently call `powershell.exe` and- point at `.ps1` scripts.+- Other native Windows script-hook agents, including Devin CLI, use their+ generated script-command hook entries for the selected platform.Use the matching `--client` / `--agent` values for other clients, for-example `codex`, `cursor`, or `gemini-cli`.+example `codex`, `devin`, `cursor`, or `gemini-cli`.++For Devin, `install-mcp --client devin --apply` writes MCP config to+`%USERPROFILE%\.devin\config.json`. `install-hooks --agent devin --apply`+writes lifecycle hooks to `%USERPROFILE%\.devin\hooks.v1.json` by default;+pass `--config-file "%USERPROFILE%\.devin\config.json"` if you want hooks under+the `hooks` key in Devin's main config file.## Scenario C: Prebuilt Release Binary (No Toolchain)@@ -292,7 +298,7 @@ Windows agent builds.Claude Code invokes hooks as a direct binary call (no shell) by default;`AI_MEMORY_HOOK_PLATFORM=windows-bash` restores the Git Bash `bash -c`path. WSL2 Claude Code uses normal WSL `.sh` paths.-- Codex, OpenCode, Cursor, Gemini CLI, Grok Build CLI, and OpenClaw may each choose different+- Codex, Devin CLI, OpenCode, Cursor, Gemini CLI, Grok Build CLI, and OpenClaw may each choose differentWindows config locations or shell execution behavior. ai-memory usesthe current best-known defaults, but they need validation on realinstallations.@@ -322,7 +328,8 @@ For native Windows:2. Confirm generated hook commands match the agent: Claude Code should usethe native `"…ai-memory.exe" hook --event …` command (or `bash -c` + `.sh`when `AI_MEMORY_HOOK_PLATFORM=windows-bash`); other script-hook agents- should use `.ps1` files under your Windows home directory.+ should use their generated script-command hook entries under your Windows+ home directory.3. Launch the native Windows agent.4. Call `memory_status` from the agent.5. Send a prompt, then run `ai-memory status` or `ai-memory recent`.diff --git a/hooks/_lib.sh b/hooks/_lib.shindex 9b33321a..2274ad0d 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -57,6 +57,22 @@ ai_memory_extract_cwd() {| head -n 1}+# Resolve cwd for agents whose native hook payload omits it. Payload wins,+# then Devin's project env var, then the hook process cwd.+ai_memory_resolve_cwd() {+ payload="${1:-$(cat)}"+ cwd=$(ai_memory_extract_cwd "$payload")+ if [ -n "$cwd" ]; then+ printf '%s' "$cwd"+ return 0+ fi+ if [ -n "${DEVIN_PROJECT_DIR:-}" ]; then+ printf '%s' "$DEVIN_PROJECT_DIR"+ return 0+ fi+ pwd 2>/dev/null || true+}+# URL-encode the minimal set of characters that have meaning in a query# string. Sufficient for the schema's value regex (`^[a-z0-9][a-z0-9._-]*$`)# plus a defensive pass for anything a hand-edited marker might contain.@@ -138,6 +154,58 @@ ai_memory_marker_qs() {printf '%s' "$qs"}+# Local bridge state for agents whose hook payloads do not carry a session id.+# The value is intentionally non-secret; the server hashes non-UUID ids into its+# typed SessionId domain. `AI_MEMORY_SESSION_ID` may be supplied by advanced+# launchers to pin an externally managed run id.+ai_memory_state_dir() {+ if [ -n "${AI_MEMORY_DATA_DIR:-}" ]; then+ printf '%s' "$AI_MEMORY_DATA_DIR"+ elif [ -n "${XDG_DATA_HOME:-}" ]; then+ printf '%s/ai-memory' "$XDG_DATA_HOME"+ elif [ -n "${HOME:-}" ]; then+ printf '%s/.local/share/ai-memory' "$HOME"+ else+ printf '.ai-memory'+ fi+}++ai_memory_session_id_file() {+ agent="$1"+ printf '%s/hook-state/%s-session-id' "$(ai_memory_state_dir)" "$agent"+}++ai_memory_new_session_id() {+ agent="$1"+ now=$(date +%s 2>/dev/null || printf '0')+ printf '%s-%s-%s' "$agent" "$now" "$$"+}++ai_memory_session_id_qs() {+ agent="$1"; event="$2"+ if [ -n "${AI_MEMORY_SESSION_ID:-}" ]; then+ printf '&session_id=%s' "$(ai_memory_url_encode "$AI_MEMORY_SESSION_ID")"+ return 0+ fi+ file=$(ai_memory_session_id_file "$agent")+ sid=""+ if [ "$event" != "session-start" ] && [ -f "$file" ]; then+ sid=$(sed -n '1p' "$file" 2>/dev/null)+ fi+ if [ -z "$sid" ]; then+ sid=$(ai_memory_new_session_id "$agent")+ dir=$(dirname "$file")+ mkdir -p "$dir" 2>/dev/null || true+ printf '%s\n' "$sid" > "$file" 2>/dev/null || true+ fi+ printf '&session_id=%s' "$(ai_memory_url_encode "$sid")"+}++ai_memory_clear_session_id() {+ agent="$1"+ rm -f "$(ai_memory_session_id_file "$agent")" 2>/dev/null || true+}+# POST stdin to "$1" as JSON, fire-and-forget. Adds an# `Authorization: Bearer` header when `AI_MEMORY_AUTH_TOKEN` is set.# The 0.5s timeout matches the project-wide hook latency budgetdiff --git a/hooks/devin/post-compaction.ps1 b/hooks/devin/post-compaction.ps1new file mode 100644index 00000000..a6c3c110--- /dev/null+++ b/hooks/devin/post-compaction.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "post-compaction" -Agent "devin"+exit 0diff --git a/hooks/devin/post-compaction.sh b/hooks/devin/post-compaction.shnew file mode 100644index 00000000..c4deddf0--- /dev/null+++ b/hooks/devin/post-compaction.sh@@ -0,0 +1,17 @@+#!/bin/sh+# Devin CLI post-compaction hook.+# Triggers *after* compaction with a summary field (Devin-specific).+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_resolve_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")+SID_QS=$(ai_memory_session_id_qs devin post-compaction)++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=post-compaction&agent=devin${QS}${SID_QS}" >/dev/null 2>&1 || true+printf '{}\n'+exit 0diff --git a/hooks/devin/post-tool-use.ps1 b/hooks/devin/post-tool-use.ps1new file mode 100644index 00000000..2854c717--- /dev/null+++ b/hooks/devin/post-tool-use.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "devin"+exit 0diff --git a/hooks/devin/post-tool-use.sh b/hooks/devin/post-tool-use.shnew file mode 100644index 00000000..8126ba91--- /dev/null+++ b/hooks/devin/post-tool-use.sh@@ -0,0 +1,16 @@+#!/bin/sh+# Devin CLI post-tool-use hook.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_resolve_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")+SID_QS=$(ai_memory_session_id_qs devin post-tool-use)++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=post-tool-use&agent=devin${QS}${SID_QS}" >/dev/null 2>&1 || true+printf '{}\n'+exit 0diff --git a/hooks/devin/pre-tool-use.ps1 b/hooks/devin/pre-tool-use.ps1new file mode 100644index 00000000..a328be38--- /dev/null+++ b/hooks/devin/pre-tool-use.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "devin"+exit 0diff --git a/hooks/devin/pre-tool-use.sh b/hooks/devin/pre-tool-use.shnew file mode 100644index 00000000..1a085552--- /dev/null+++ b/hooks/devin/pre-tool-use.sh@@ -0,0 +1,16 @@+#!/bin/sh+# Devin CLI pre-tool-use hook.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_resolve_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")+SID_QS=$(ai_memory_session_id_qs devin pre-tool-use)++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=pre-tool-use&agent=devin${QS}${SID_QS}" >/dev/null 2>&1 || true+printf '{}\n'+exit 0diff --git a/hooks/devin/session-end.ps1 b/hooks/devin/session-end.ps1new file mode 100644index 00000000..04d30fae--- /dev/null+++ b/hooks/devin/session-end.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "session-end" -Agent "devin"+exit 0diff --git a/hooks/devin/session-end.sh b/hooks/devin/session-end.shnew file mode 100644index 00000000..e2e61650--- /dev/null+++ b/hooks/devin/session-end.sh@@ -0,0 +1,17 @@+#!/bin/sh+# Devin CLI session-end hook.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_resolve_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")+SID_QS=$(ai_memory_session_id_qs devin session-end)++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=session-end&agent=devin${QS}${SID_QS}" >/dev/null 2>&1 || true+ai_memory_clear_session_id devin+printf '{}\n'+exit 0diff --git a/hooks/devin/session-start.ps1 b/hooks/devin/session-start.ps1new file mode 100644index 00000000..c60138cb--- /dev/null+++ b/hooks/devin/session-start.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "session-start" -Agent "devin" -FetchHandoff+exit 0diff --git a/hooks/devin/session-start.sh b/hooks/devin/session-start.shnew file mode 100644index 00000000..3ea0e739--- /dev/null+++ b/hooks/devin/session-start.sh@@ -0,0 +1,27 @@+#!/bin/sh+# Devin CLI SessionStart hook.+# 1. Forwards the event JSON to ai-memory.+# 2. Synchronously fetches the pending handoff and injects it through+# hookSpecificOutput.additionalContext, which Devin consumes as+# additional session context.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_resolve_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")+SID_QS=$(ai_memory_session_id_qs devin session-start)++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=session-start&agent=devin${QS}${SID_QS}" >/dev/null 2>&1 || true++HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=devin${QS}" 2>/dev/null || true)+if [ -n "$HANDOFF" ]; then+ printf '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":%s}}\n' \+ "$(printf '%s' "$HANDOFF" | ai_memory_json_string)"+else+ printf '{}\n'+fi+exit 0diff --git a/hooks/devin/stop.ps1 b/hooks/devin/stop.ps1new file mode 100644index 00000000..2f8dd667--- /dev/null+++ b/hooks/devin/stop.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "stop" -Agent "devin"+exit 0diff --git a/hooks/devin/stop.sh b/hooks/devin/stop.shnew file mode 100644index 00000000..0c2031b1--- /dev/null+++ b/hooks/devin/stop.sh@@ -0,0 +1,16 @@+#!/bin/sh+# Devin CLI stop hook.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_resolve_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")+SID_QS=$(ai_memory_session_id_qs devin stop)++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=stop&agent=devin${QS}${SID_QS}" >/dev/null 2>&1 || true+printf '{}\n'+exit 0diff --git a/hooks/devin/user-prompt-submit.ps1 b/hooks/devin/user-prompt-submit.ps1new file mode 100644index 00000000..c796c542--- /dev/null+++ b/hooks/devin/user-prompt-submit.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "user-prompt" -Agent "devin"+exit 0diff --git a/hooks/devin/user-prompt-submit.sh b/hooks/devin/user-prompt-submit.shnew file mode 100644index 00000000..4085c082--- /dev/null+++ b/hooks/devin/user-prompt-submit.sh@@ -0,0 +1,16 @@+#!/bin/sh+# Devin CLI user-prompt hook.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_resolve_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")+SID_QS=$(ai_memory_session_id_qs devin user-prompt)++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=user-prompt&agent=devin${QS}${SID_QS}" >/dev/null 2>&1 || true+printf '{}\n'+exit 0diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index 339c25c9..d50a026b 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -20,6 +20,21 @@ function Get-AiMemoryCwd {return $null}+function Resolve-AiMemoryCwd {+ param([string] $Payload, [string] $Agent)+ $Cwd = Get-AiMemoryCwd -Payload $Payload+ if ($Cwd) { return $Cwd }+ if ($Agent -eq "devin" -and $env:DEVIN_PROJECT_DIR) { return $env:DEVIN_PROJECT_DIR }+ if ($Agent -eq "devin") {+ try {+ $Location = (Get-Location).Path+ if ($Location) { return $Location }+ } catch {+ }+ }+ return $null+}+function Get-AiMemoryMarkerToml {param([string] $Cwd)if (-not $Cwd) { return $null }@@ -99,6 +114,50 @@ function Get-AiMemoryMarkerQuery {return $qs}+function Get-AiMemoryStateDir {+ if ($env:AI_MEMORY_DATA_DIR) { return $env:AI_MEMORY_DATA_DIR }+ if ($env:XDG_DATA_HOME) { return (Join-Path $env:XDG_DATA_HOME "ai-memory") }+ if ($env:LOCALAPPDATA) { return (Join-Path $env:LOCALAPPDATA "ai-memory") }+ if ($env:HOME) { return (Join-Path $env:HOME ".local/share/ai-memory") }+ return ".ai-memory"+}++function Get-AiMemorySessionIdPath {+ param([string] $Agent)+ return (Join-Path (Join-Path (Get-AiMemoryStateDir) "hook-state") "$Agent-session-id")+}++function New-AiMemorySessionId {+ param([string] $Agent)+ return "$Agent-$([DateTimeOffset]::UtcNow.ToUnixTimeSeconds())-$PID"+}++function Get-AiMemorySessionIdQuery {+ param([string] $Agent, [string] $Event)+ if ($env:AI_MEMORY_SESSION_ID) {+ return "&session_id=$([uri]::EscapeDataString($env:AI_MEMORY_SESSION_ID))"+ }++ $Path = Get-AiMemorySessionIdPath -Agent $Agent+ $SessionId = $null+ if ($Event -ne "session-start" -and (Test-Path $Path -PathType Leaf)) {+ $SessionId = (Get-Content $Path -TotalCount 1 -ErrorAction SilentlyContinue)+ }+ if (-not $SessionId) {+ $SessionId = New-AiMemorySessionId -Agent $Agent+ $Parent = Split-Path $Path -Parent+ New-Item -ItemType Directory -Force -Path $Parent -ErrorAction SilentlyContinue | Out-Null+ Set-Content -Path $Path -Value $SessionId -NoNewline -ErrorAction SilentlyContinue+ }+ return "&session_id=$([uri]::EscapeDataString($SessionId))"+}++function Clear-AiMemorySessionId {+ param([string] $Agent)+ $Path = Get-AiMemorySessionIdPath -Agent $Agent+ Remove-Item -Force -ErrorAction SilentlyContinue $Path+}+function Read-AiMemoryStdin {try {if (-not [Console]::IsInputRedirected) { return "" }@@ -128,8 +187,12 @@ function Invoke-AiMemoryHook {$Server = if ($env:AI_MEMORY_HOOK_URL) { $env:AI_MEMORY_HOOK_URL } else { "http://127.0.0.1:49374" }$Payload = Read-AiMemoryStdin- $Cwd = Get-AiMemoryCwd -Payload $Payload+ $Cwd = Resolve-AiMemoryCwd -Payload $Payload -Agent $Agent$QS = Get-AiMemoryMarkerQuery -Cwd $Cwd+ $SessionQS = ""+ if ($Agent -eq "devin") {+ $SessionQS = Get-AiMemorySessionIdQuery -Agent $Agent -Event $Event+ }$Headers = @{}if ($env:AI_MEMORY_AUTH_TOKEN) {@@ -141,12 +204,15 @@ function Invoke-AiMemoryHook {-UseBasicParsing `-TimeoutSec 3 `-Method Post `- -Uri "$Server/hook?event=$Event&agent=$Agent$QS" `+ -Uri "$Server/hook?event=$Event&agent=$Agent$QS$SessionQS" `-Headers $Headers `-ContentType "application/json" `-Body $Payload | Out-Null} catch {}+ if ($Agent -eq "devin" -and $Event -eq "session-end") {+ Clear-AiMemorySessionId -Agent $Agent+ }if ($FetchHandoff) {try {