Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(hooks): harden routing and uninstall cleanup

AkitaOnRails8e655cd8183e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 78e52890..da5ceb26 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,6 +52,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
hook events.
- README support matrix for operating systems, agent integrations, LLM
providers, and embedding providers.
+- `ai-memory uninstall` — removes ai-memory's hooks, MCP registration, and
+ CLAUDE.md/AGENTS.md instruction block across all detected agents (dry-run by
+ default; `--apply` to execute, with timestamped backups). `--purge-data`
+ wipes wiki/db/raw via the reset guard. `--only hooks|mcp|instructions` to
+ narrow. MCP matching is endpoint-based by default; pass `--mcp-url` when the
+ server was installed with a custom endpoint and `--mcp-name` only to narrow
+ removal to one matching entry. Docker/volume teardown is printed as a hint,
+ not executed.
### Changed
- Same-body page upserts are now true no-ops, avoiding periodic watcher
@@ -71,6 +79,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
updated Cursor / Claude Desktop / OpenClaw support docs against current
upstream MCP and hook documentation.
- Docker images now bundle both POSIX and PowerShell hook scripts.
+- `ai-memory uninstall --purge-data` now previews the `wiki/`/`db/`/`raw/`
+ wipe in dry-run (mirroring `reset`) and refuses **up front** if an
+ `ai-memory` process is alive (all-or-nothing) instead of removing the
+ wiring and then skipping the purge. The data wipe is now shared with
+ `reset` via a single internal helper.
+- `ai-memory uninstall` only deletes generated plugin/extension files after
+ re-validating their ai-memory-generated content, and never treats a matching
+ filename or MCP server name alone as proof of ownership.
### Fixed
- `serve` now warns and starts when stored embedding rows were created with a
@@ -104,26 +120,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Hook routing now evicts a stale project-cache entry and retries once when a
live server sees a cached project deleted underneath it, such as after
`purge-project`, so capture resumes without restarting the server.
-
-### Added
-- `ai-memory uninstall` — removes ai-memory's hooks, MCP registration, and
- CLAUDE.md/AGENTS.md instruction block across all detected agents (dry-run by
- default; `--apply` to execute, with timestamped backups). `--purge-data`
- wipes wiki/db/raw via the reset guard. `--only hooks|mcp|instructions` to
- narrow. MCP matching is endpoint-based by default; pass `--mcp-url` when the
- server was installed with a custom endpoint and `--mcp-name` only to narrow
- removal to one matching entry. Docker/volume teardown is printed as a hint,
- not executed.
-
-### Changed
-- `ai-memory uninstall --purge-data` now previews the `wiki/`/`db/`/`raw/`
- wipe in dry-run (mirroring `reset`) and refuses **up front** if an
- `ai-memory` process is alive (all-or-nothing) instead of removing the
- wiring and then skipping the purge. The data wipe is now shared with
- `reset` via a single internal helper.
-- `ai-memory uninstall` only deletes generated plugin/extension files after
- re-validating their ai-memory-generated content, and never treats a matching
- filename or MCP server name alone as proof of ownership.
+- Session-start handoff hooks now include `cwd` even without a marker file, so
+ default `project = basename(cwd)` projects receive pending handoffs without
+ requiring `.ai-memory.toml`.
+- `ai-memory uninstall` now removes only ai-memory commands from mixed nested
+ hook entries, preserves third-party commands in the same matcher, and removes
+ legacy Codex inline-table MCP entries.
+- Generated POSIX hook commands now shell-quote script paths and env values
+ with metacharacters, fixing custom hook directories containing spaces and
+ preventing shell-active token/URL fragments.
+- OpenClaw's generated plugin now forwards marker-file routing params just like
+ the OpenCode and OMP generated integrations.
## [0.1.3] - 2026-05-24
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index 2d47c636..963a44c4 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -198,6 +198,9 @@ fn build_plugin(server_url: &str, auth_token: Option<&str>) -> String {
// this local OpenClaw plugin package.
import {{ definePluginEntry }} from "openclaw/plugin-sdk/plugin-entry";
+import {{ existsSync, readFileSync }} from "node:fs";
+import {{ dirname, join, resolve }} from "node:path";
+import {{ homedir }} from "node:os";
const SERVER = {server_literal}.replace(/\/+$/, "");
const AGENT = "openclaw";
@@ -213,6 +216,45 @@ function authHeaders(): Record<string, string> {{
return TOKEN ? {{ Authorization: `Bearer ${{TOKEN}}` }} : {{}};
}}
+function findMarker(cwd: string | undefined): string | undefined {{
+ if (!cwd) return undefined;
+ let dir = resolve(cwd);
+ const home = homedir();
+ while (dir && dir !== dirname(dir)) {{
+ const marker = join(dir, ".ai-memory.toml");
+ if (existsSync(marker)) return marker;
+ if (home && dir === home) return undefined;
+ dir = dirname(dir);
+ }}
+ return undefined;
+}}
+
+function tomlKey(text: string, key: string): string | undefined {{
+ const re = new RegExp(`^\\s*${{key}}\\s*=\\s*"([^"]*)"`);
+ for (const line of text.split(/\r?\n/)) {{
+ const match = re.exec(line);
+ if (match) return match[1];
+ }}
+ return undefined;
+}}
+
+function applyMarkerParams(url: URL, cwd: string | undefined): void {{
+ if (!cwd) return;
+ url.searchParams.set("cwd", cwd);
+ const marker = findMarker(cwd);
+ if (!marker) return;
+ try {{
+ const body = readFileSync(marker, "utf8");
+ const workspace = tomlKey(body, "workspace");
+ const project = tomlKey(body, "project");
+ const projectStrategy = tomlKey(body, "project_strategy");
+ if (workspace) url.searchParams.set("workspace", workspace);
+ if (project) url.searchParams.set("project", project);
+ if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
+ }} catch (_e) {{
+ }}
+}}
+
function textFrom(value: unknown): string {{
if (value === null || value === undefined) return "";
if (typeof value === "string") return value;
@@ -274,6 +316,7 @@ function postHook(eventName: string, body: Record<string, unknown>): void {{
const url = new URL(`${{SERVER}}/hook`);
url.searchParams.set("event", eventName);
url.searchParams.set("agent", AGENT);
+ applyMarkerParams(url, typeof body.cwd === "string" ? body.cwd : undefined);
try {{
void fetch(url, {{
method: "POST",
@@ -291,7 +334,7 @@ async function fetchHandoff(event: any, ctx: any): Promise<string | undefined> {
if (!currentCwd) return undefined;
const url = new URL(`${{SERVER}}/handoff`);
url.searchParams.set("agent", AGENT);
- url.searchParams.set("cwd", currentCwd);
+ applyMarkerParams(url, currentCwd);
try {{
const response = await fetch(url, {{
headers: authHeaders(),
@@ -396,6 +439,12 @@ mod tests {
assert!(plugin.contains("api.on(\"agent_end\""));
assert!(plugin.contains("postHook(\"session-start\""));
assert!(plugin.contains("postHook(\"user-prompt\""));
+ assert!(plugin.contains("function applyMarkerParams"));
+ assert!(plugin.contains("tomlKey(body, \"project_strategy\")"));
+ assert!(plugin.contains(
+ "applyMarkerParams(url, typeof body.cwd === \"string\" ? body.cwd : undefined);"
+ ));
+ assert!(plugin.contains("applyMarkerParams(url, currentCwd);"));
assert!(plugin.contains("fetchHandoff"));
assert!(plugin.contains("prependContext: handoff"));
assert!(plugin.contains("Bearer ${TOKEN}"));
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 42dc3765..2693a951 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -429,7 +429,7 @@ fn hook_command(
if let Some(t) = auth_token {
prefix.push_str(&format!("AI_MEMORY_AUTH_TOKEN={} ", shell_quote(t)));
}
- format!("{prefix}{}", script.to_string_lossy())
+ format!("{prefix}{}", shell_quote(&script.to_string_lossy()))
}
HookCommandPlatform::Windows => {
let mut setup = format!("$env:AI_MEMORY_HOOK_URL={}", powershell_quote(server_url));
@@ -447,12 +447,15 @@ fn hook_command(
}
}
-/// Minimal shell quoting for embedding values into a `VAR=val cmd`
-/// prefix. Wraps in single quotes; embedded `'` is escaped via
-/// `'\''`. Safe for the URLs and bearer tokens we embed (no
-/// realistic value contains anything else weird).
+/// Minimal shell quoting for embedding values into a `VAR=val cmd` prefix or
+/// command path. Leaves only conservative shell-safe characters unquoted;
+/// wraps everything else in single quotes and escapes embedded `'` via
+/// `'\''`.
fn shell_quote(s: &str) -> String {
- if !s.contains(['\'', ' ', '"', '$', '`', '\\']) {
+ if s.chars().all(|c| {
+ c.is_ascii_alphanumeric()
+ || matches!(c, '-' | '_' | '.' | '/' | ':' | '@' | '%' | '+' | '=' | ',')
+ }) {
return s.to_string();
}
let escaped = s.replace('\'', "'\\''");
@@ -689,6 +692,29 @@ mod tests {
);
}
+ #[test]
+ fn posix_hook_command_quotes_script_path_and_shell_metachars() {
+ let cmd = hook_command(
+ &PathBuf::from("/tmp/hooks dir/session-start.sh"),
+ "http://localhost:49374/mcp?x=1&y=2",
+ Some("tok;rm -rf /"),
+ HookCommandPlatform::Posix,
+ );
+
+ assert!(
+ cmd.contains("AI_MEMORY_HOOK_URL='http://localhost:49374/mcp?x=1&y=2'"),
+ "URL with query metacharacters must be quoted: {cmd}"
+ );
+ assert!(
+ cmd.contains("AI_MEMORY_AUTH_TOKEN='tok;rm -rf /'"),
+ "token with shell metacharacters must be quoted: {cmd}"
+ );
+ assert!(
+ cmd.ends_with("'/tmp/hooks dir/session-start.sh'"),
+ "script path with spaces must be quoted: {cmd}"
+ );
+ }
+
#[test]
fn windows_payload_uses_powershell_and_ps1_hooks() {
let root = PathBuf::from("C:/Users/alice/.local/share/ai-memory/hooks/claude-code");
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 4e5ba45b..e066cbc8 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -418,23 +418,26 @@ struct HookRemoval {
removed_events: Vec<String>,
}
-/// An entry (one element of an event's array) is ai-memory's when its
-/// command carries the signature — at the entry level (Flat shape) or
-/// inside its nested `hooks` array (Nested shape).
-fn hook_entry_is_ours(entry: &serde_json::Value) -> bool {
+/// Remove ai-memory commands from one hook entry. Returns `(removed_any,
+/// remove_entry)`. Flat entries are removed whole; nested entries only lose the
+/// matching inner commands and survive when third-party inner hooks remain.
+fn strip_hook_entry(entry: &mut serde_json::Value) -> (bool, bool) {
if let Some(cmd) = entry.get("command").and_then(|c| c.as_str())
&& hook_command_is_ours(cmd)
{
- return true;
+ return (true, true);
}
- if let Some(inner) = entry.get("hooks").and_then(|h| h.as_array()) {
- return inner.iter().any(|h| {
- h.get("command")
+ if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
+ let before = inner.len();
+ inner.retain(|h| {
+ !h.get("command")
.and_then(|c| c.as_str())
.is_some_and(hook_command_is_ours)
});
+ let removed = inner.len() != before;
+ return (removed, inner.is_empty());
}
- false
+ (false, false)
}
/// Remove ai-memory hook entries from a settings/hooks JSON document.
@@ -453,9 +456,13 @@ fn strip_ai_memory_hooks(content: &str) -> Result<HookRemoval> {
let Some(arr) = hooks.get_mut(&event).and_then(|v| v.as_array_mut()) else {
continue;
};
- let before = arr.len();
- arr.retain(|entry| !hook_entry_is_ours(entry));
- if arr.len() != before {
+ 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() {
@@ -487,9 +494,13 @@ fn strip_antigravity_hooks(content: &str) -> Result<HookRemoval> {
let Some(arr) = group.get_mut(&event).and_then(|v| v.as_array_mut()) else {
continue;
};
- let before = arr.len();
- arr.retain(|entry| !hook_entry_is_ours(entry));
- if arr.len() != before {
+ 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(format!("ai-memory.{event}"));
}
if arr.is_empty() {
@@ -525,8 +536,36 @@ fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {
&& content.contains("definePluginEntry")
&& content.contains("id: \"ai-memory\"")
}
- DeleteKind::OpenClawPackageJson => content == openclaw_plugin::package_json(),
- DeleteKind::OpenClawManifest => content == openclaw_plugin::manifest_json(),
+ DeleteKind::OpenClawPackageJson => serde_json::from_str::<serde_json::Value>(&content)
+ .ok()
+ .is_some_and(|v| {
+ v.get("name").and_then(|name| name.as_str()) == Some(openclaw_plugin::PACKAGE_NAME)
+ && v.get("private").and_then(|private| private.as_bool()) == Some(true)
+ && v.get("type").and_then(|ty| ty.as_str()) == Some("module")
+ && v.pointer("/openclaw/extensions")
+ .and_then(|extensions| extensions.as_array())
+ .is_some_and(|extensions| {
+ extensions.len() == 1
+ && extensions[0].as_str()
+ == Some(&format!("./{}", openclaw_plugin::ENTRYPOINT_TS))
+ })
+ }),
+ DeleteKind::OpenClawManifest => serde_json::from_str::<serde_json::Value>(&content)
+ .ok()
+ .is_some_and(|v| {
+ v.get("id").and_then(|id| id.as_str()) == Some(openclaw_plugin::PLUGIN_ID)
+ && v.get("name").and_then(|name| name.as_str()) == Some("ai-memory")
+ && v.pointer("/activation/onCapabilities")
+ .and_then(|capabilities| capabilities.as_array())
+ .is_some_and(|capabilities| {
+ capabilities
+ .iter()
+ .any(|entry| entry.as_str() == Some("hook"))
+ })
+ && v.pointer("/configSchema/additionalProperties")
+ .and_then(|additional| additional.as_bool())
+ == Some(false)
+ }),
}
}
@@ -619,23 +658,52 @@ fn strip_mcp_json(
/// Remove ai-memory's Codex MCP table by name or `url`. Returns new
/// content and removed names. Preserves comments + other tables.
fn strip_mcp_toml(content: &str, name: Option<&str>, url: &str) -> Result<(String, Vec<String>)> {
+ use toml_edit::{Item, Value};
+
let mut removed = Vec::new();
let new_content = mutate_toml(content, |doc| {
- let Some(servers) = doc.get_mut("mcp_servers").and_then(|i| i.as_table_mut()) else {
+ let Some(servers_item) = doc.get_mut("mcp_servers") else {
return Ok(());
};
- let keys: Vec<String> = servers.iter().map(|(k, _)| k.to_string()).collect();
- for k in keys {
- let matches_url = servers
- .get(&k)
- .and_then(|item| item.as_table())
- .and_then(|t| t.get("url"))
- .and_then(|u| u.as_str())
- == Some(url);
- if name.is_none_or(|name| k == name) && matches_url {
- servers.remove(&k);
- removed.push(k);
+ let mut remove_mcp_servers = false;
+ match servers_item {
+ Item::Table(servers) => {
+ let keys: Vec<String> = servers.iter().map(|(k, _)| k.to_string()).collect();
+ for k in keys {
+ let matches_url = servers
+ .get(&k)
+ .and_then(|item| item.as_table())
+ .and_then(|t| t.get("url"))
+ .and_then(|u| u.as_str())
+ == Some(url);
+ if name.is_none_or(|name| k == name) && matches_url {
+ servers.remove(&k);
+ removed.push(k);
+ }
+ }
+ }
+ Item::Value(Value::InlineTable(servers)) => {
+ let keys: Vec<String> = servers.iter().map(|(k, _)| k.to_string()).collect();
+ for k in keys {
+ let matches_url = servers
+ .get(&k)
+ .and_then(|value| value.as_inline_table())
+ .and_then(|table| table.get("url"))
+ .and_then(|value| value.as_str())
+ == Some(url);
+ if name.is_none_or(|name| k == name) && matches_url {
+ servers.remove(&k);
+ removed.push(k);
+ }
+ }
+ if servers.is_empty() {
+ remove_mcp_servers = true;
+ }
}
+ _ => {}
+ }
+ if remove_mcp_servers {
+ doc.remove("mcp_servers");
}
Ok(())
})?;
@@ -764,6 +832,30 @@ mod tests {
);
}
+ #[test]
+ fn strip_hooks_nested_mixed_inner_commands_preserves_user_hook() {
+ let content = r#"{
+ "hooks": {
+ "Stop": [
+ {"matcher":"","hooks":[
+ {"type":"command","command":"AI_MEMORY_HOOK_URL=x /a/stop.sh"},
+ {"type":"command","command":"/home/u/scripts/my-stop.sh"}
+ ]}
+ ]
+ }
+ }"#;
+
+ let out = strip_ai_memory_hooks(content).unwrap();
+ assert_eq!(out.removed_events, vec!["Stop".to_string()]);
+ let v: serde_json::Value = serde_json::from_str(&out.new_content).unwrap();
+ let inner = v["hooks"]["Stop"][0]["hooks"].as_array().unwrap();
+ assert_eq!(inner.len(), 1, "third-party inner hook must survive");
+ assert_eq!(
+ inner[0]["command"].as_str(),
+ Some("/home/u/scripts/my-stop.sh")
+ );
+ }
+
#[test]
fn strip_hooks_no_hooks_key_is_noop() {
let content = r#"{"unrelated":true}"#;
@@ -802,6 +894,27 @@ mod tests {
assert!(v.get("my-group").is_some());
}
+ #[test]
+ fn strip_antigravity_hooks_preserves_mixed_nested_user_hook() {
+ let content = r#"{
+ "ai-memory": {
+ "Stop": [
+ {"matcher":"","hooks":[
+ {"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/stop.sh"},
+ {"type":"command","command":"/usr/bin/user-stop"}
+ ]}
+ ]
+ }
+ }"#;
+
+ let out = strip_antigravity_hooks(content).unwrap();
+ assert_eq!(out.removed_events, vec!["ai-memory.Stop".to_string()]);
+ let v: serde_json::Value = serde_json::from_str(&out.new_content).unwrap();
+ let inner = v["ai-memory"]["Stop"][0]["hooks"].as_array().unwrap();
+ assert_eq!(inner.len(), 1);
+ assert_eq!(inner[0]["command"].as_str(), Some("/usr/bin/user-stop"));
+ }
+
#[test]
fn generated_file_detection_rejects_user_files_at_ours_path() {
let tmp = tempfile::tempdir().unwrap();
@@ -834,10 +947,20 @@ mod tests {
&path,
DeleteKind::OpenClawPackageJson
));
+
+ std::fs::write(
+ &path,
+ r#"{"name":"@ai-memory/openclaw-plugin","version":"0.0.1","private":true,"type":"module","openclaw":{"extensions":["./index.ts"]}}"#,
+ )
+ .unwrap();
+ assert!(
+ generated_file_is_ours(&path, DeleteKind::OpenClawPackageJson),
+ "older generated package versions should still uninstall"
+ );
}
#[test]
- fn generated_openclaw_manifest_detection_requires_exact_metadata() {
+ fn generated_openclaw_manifest_detection_requires_our_shape() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("openclaw.plugin.json");
std::fs::write(
@@ -850,6 +973,16 @@ mod tests {
std::fs::write(&path, openclaw_plugin::manifest_json()).unwrap();
assert!(generated_file_is_ours(&path, DeleteKind::OpenClawManifest));
+
+ std::fs::write(
+ &path,
+ r#"{"id":"ai-memory","name":"ai-memory","description":"older generated text","activation":{"onCapabilities":["hook"]},"configSchema":{"type":"object","additionalProperties":false,"properties":{}}}"#,
+ )
+ .unwrap();
+ assert!(
+ generated_file_is_ours(&path, DeleteKind::OpenClawManifest),
+ "older generated manifest descriptions should still uninstall"
+ );
}
#[test]
@@ -999,6 +1132,23 @@ mod tests {
assert!(!out.contains("custom"));
}
+ #[test]
+ fn strip_mcp_toml_inline_table_by_url_under_custom_name() {
+ let content = "mcp_servers = { custom = { url = \"http://127.0.0.1:49374/mcp\" }, other = { url = \"http://x\" } }\n";
+ let (out, removed) = strip_mcp_toml(content, None, "http://127.0.0.1:49374/mcp").unwrap();
+ assert_eq!(removed, vec!["custom".to_string()]);
+ assert!(!out.contains("custom"));
+ assert!(out.contains("other"));
+ }
+
+ #[test]
+ fn strip_mcp_toml_inline_table_prunes_when_empty() {
+ let content = "mcp_servers = { ai-memory = { url = \"http://127.0.0.1:49374/mcp\" } }\n";
+ let (out, removed) = strip_mcp_toml(content, None, "http://127.0.0.1:49374/mcp").unwrap();
+ assert_eq!(removed, vec!["ai-memory".to_string()]);
+ assert!(!out.contains("mcp_servers"));
+ }
+
#[test]
fn strip_mcp_toml_no_match_is_noop() {
let content = "[mcp_servers.other]\nurl = \"http://x\"\n";
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 11801a37..5e64dd3c 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -1281,6 +1281,54 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn handoff_with_no_marker_uses_cwd_basename_project() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let cwd = "/home/u/plain-repo";
+
+ let (ws, proj) =
+ resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
+ .await
+ .unwrap();
+ state
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: Some(std::path::PathBuf::from(cwd)),
+ summary: "handoff summary".to_string(),
+ open_questions: Vec::new(),
+ next_steps: vec!["resume plain repo".to_string()],
+ files_touched: Vec::new(),
+ })
+ .await
+ .unwrap();
+
+ let rendered = fetch_and_accept_handoff(
+ &state,
+ HandoffQuery {
+ agent: Some("codex".into()),
+ cwd: Some(cwd.into()),
+ workspace: None,
+ project: None,
+ project_strategy: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ rendered
+ .as_deref()
+ .is_some_and(|s| s.contains("resume plain repo")),
+ "no-marker handoff lookup must still resolve basename(cwd)"
+ );
+ }
+
/// A marker file with `project = "pe-portais"` replaces the
/// basename-derived project name for every descendant `cwd`.
#[tokio::test]
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index a4547ac9..4a858e3a 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -225,15 +225,17 @@ MCP parameter aliases are intentionally sparse: `memory_query.query` accepts
`q|search`, and limit fields accept `n` / `top_k` where shipped. Project and
cwd parameters use their canonical names.
-## CLI subcommand surface (17 commands)
+## CLI subcommand surface
```
-init watch embed
-status serve forget-sweep
-search reset lint
-write-page backup commit
- restore llm-test
- install-hooks
+init status search
+write-page serve reset
+backup restore install-hooks
+install-mcp commit llm-test
+forget-sweep lint embed
+generate-auth-token setup-agent bootstrap
+install-instructions reorg purge-project
+rename-project uninstall
```
Run `ai-memory --help` for the full tree.
@@ -261,7 +263,8 @@ that touch the relevant area.
modes; no XML, no Instructor wrapping. (agentmemory #492 / #539,
cognee #2840.)
8. **`{provider, model, dim}` denormalised next to every embedding.**
- Refuse-on-mismatch at startup. (agentmemory #469.)
+ Warn and ignore stale vectors on mismatch until re-embedding completes.
+ (agentmemory #469.)
9. **Live-process check before destructive ops.** `ai-memory reset`,
`backup`, `restore` all consult `sysinfo`. (basic-memory #765.)
10. **Atomic file writes** (tmp + rename + fsync). Watcher ignores
diff --git a/docs/deploy.md b/docs/deploy.md
index a3a4b290..3fd8cda7 100644
--- a/docs/deploy.md
+++ b/docs/deploy.md
@@ -90,7 +90,7 @@ curl -sI http://homelab:49374/handoff \
**Then update every MCP client** to send the same token. `ai-memory
install-mcp --client <name> --auth-token <token>` prints the exact
snippet per client (Claude Code, Codex, OpenCode, Cursor, Claude
-Desktop, Gemini CLI, OpenClaw). The agent CLI sends an
+Desktop, Gemini CLI, OpenClaw, OMP/Pi, Antigravity CLI). The agent CLI sends an
`Authorization: Bearer <token>` header on every call; ai-memory's
middleware validates with a constant-time comparison.
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 172171af..5fa5ec29 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -8,8 +8,8 @@
A self-contained Rust binary that:
-1. Runs as an **MCP server** (stdio + HTTP/SSE) for coding-agent CLIs (Claude Code, OpenAI Codex, Cursor, Gemini CLI, OpenClaw, OpenCode, OMP, and MCP-capable clients).
-2. Captures the agent's session **automatically** - no `write_note` ceremony - via hook scripts or generated extensions that the agent CLIs invoke (Claude Code / Codex / Cursor / Gemini CLI lifecycle hooks, OpenClaw / OpenCode / OMP TypeScript integrations). Optional transcript-tail fallback for agents without hook APIs.
+1. Runs as an **MCP server** (stdio + HTTP/SSE) for coding-agent CLIs (Claude Code, OpenAI Codex, Cursor, Gemini CLI, Antigravity CLI, OpenClaw, OpenCode, OMP, and MCP-capable clients).
+2. Captures the agent's session **automatically** - no `write_note` ceremony - via hook scripts or generated extensions that the agent CLIs invoke (Claude Code / Codex / Cursor / Gemini CLI / Antigravity CLI lifecycle hooks, OpenClaw / OpenCode / OMP TypeScript integrations). Optional transcript-tail fallback for agents without hook APIs.
3. Maintains a **Karpathy-style wiki**: incrementally-compiled markdown pages with cross-links, supersession, an `index.md` and a `log.md`.
4. Serves retrieval via the MCP `tools/list` to coding agents: a handful of *narrow* tools, not 50.
5. Ships a **Docker image** (`docker run -v ai-memory-data:/data -p 49374:49374 ai-memory`) so it can move between desktop and homelab.
@@ -80,7 +80,7 @@ Why not LanceDB/Qdrant/Kuzu/CozoDB/SurrealDB?
**Embeddings:**
- Default: **local model via `ort` (ONNX Runtime) crate or `fastembed-rs`** running `bge-small-en-v1.5` (384 dim) or `bge-small-en-v1.5-q` quantized. Same model basic-memory uses.
-- Persist `{provider, model, dim}` next to every vector. Refuse to load on mismatch with clear remediation (agentmemory #469 lesson).
+- Persist `{provider, model, dim}` next to every vector. On mismatch, warn and ignore stale vectors until `ai-memory embed --force` or scheduled backfill re-embeds them (agentmemory #469 lesson, without blocking startup).
- Cache path: `<data_dir>/models/`, never `/tmp` (basic-memory #741).
- Trait-based: `trait Embedder { ... }` with implementations `LocalOrtEmbedder`, `OpenAIEmbedder`, `VoyageEmbedder`. User configures one.
@@ -95,7 +95,7 @@ Why not LanceDB/Qdrant/Kuzu/CozoDB/SurrealDB?
Three capture surfaces, in priority order:
-1. **Lifecycle hooks/extensions** (Claude Code, Codex, OpenCode, OMP). These are fast, reliable, structured. We ship hook scripts or generated TypeScript integrations the user installs once. Lessons from agentmemory:
+1. **Lifecycle hooks/extensions** (Claude Code, Codex, Cursor, Gemini CLI, Antigravity CLI, OpenClaw, OpenCode, OMP). These are fast, reliable, structured. We ship hook scripts or generated TypeScript integrations the user installs once. Lessons from agentmemory:
- Hooks must be **fire-and-forget** (#221). No `await fetch()` blocking session start.
- Sub-second hard timeouts on the writer side (`tokio::time::timeout`).
- All hooks → single HTTP/Unix-socket POST → server queues → returns 202
diff --git a/docs/marker-file.md b/docs/marker-file.md
index e6d8fbc6..0a4ae50e 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -31,10 +31,11 @@ workspace-only markers can still resolve `project = basename(cwd)` for
handoff lookups.
The marker path is shared by the POSIX/PowerShell hook scripts and the
-generated OpenCode / OMP TypeScript integrations. In all cases, hook
-capture and handoff lookup send the same `cwd`, `workspace`, `project`,
-and `project_strategy` query params to the server when a marker is
-present.
+generated OpenCode / OMP / OpenClaw TypeScript integrations. In all cases,
+hook capture and handoff lookup send the same `cwd`, `workspace`, `project`,
+and `project_strategy` query params to the server when a marker is present;
+handoff lookup also sends `cwd` when no marker exists so the default
+`project = basename(cwd)` route works consistently.
## Schema
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index abbe3248..e7f3fe5e 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -433,7 +433,7 @@ 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 or by calling `memory_handoff_begin`. | Built-in for Claude Code, Codex, Cursor, Gemini CLI, OpenClaw, and OMP. OpenCode and Antigravity CLI have no true session-end event, so ask them to call `memory_handoff_begin` before quitting when you need a handoff. |
+| **Ending side** | The agent must create a handoff, either through a true session-end hook or by calling `memory_handoff_begin`. | Built-in for Claude Code, Cursor, Gemini CLI, OpenClaw, and OMP. Codex, OpenCode, and Antigravity CLI have no true session-end event in the current integration, so ask them 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. (b) works for any MCP-capable client if you nudge the model - see [the routing snippet](usage.md#install-the-routing-snippet). |
So a typical mixed workflow looks like:
diff --git a/hooks/_lib.sh b/hooks/_lib.sh
index c2707ad6..e4dad52b 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -65,20 +65,19 @@ ai_memory_url_encode() {
| sed 's/%/%25/g; s/+/%2B/g; s/&/%26/g; s/=/%3D/g; s/?/%3F/g; s/#/%23/g; s/ /%20/g'
}
-# Build a query-string suffix from the marker file walked up from "$1".
-# Returns the suffix (with the leading `&`) or nothing. `cwd` is included
-# whenever a marker exists so `GET /handoff` can resolve workspace-only
-# markers by combining `workspace` with basename(cwd), or apply an opt-in
-# project strategy.
+# Build a query-string suffix from "$1" plus any marker file walked up from
+# it. Returns the suffix with the leading `&`, or nothing when cwd is absent.
+# `cwd` is always included so `GET /handoff` resolves the same basename project
+# as the prior hook events even when no marker file exists.
ai_memory_marker_qs() {
cwd="$1"
[ -z "$cwd" ] && return 0
+ qs="&cwd=$(ai_memory_url_encode "$cwd")"
marker=$(ai_memory_find_marker "$cwd")
- [ -z "$marker" ] && return 0
+ [ -z "$marker" ] && { printf '%s' "$qs"; return 0; }
ws=$(ai_memory_parse_toml_key "$marker" workspace)
pr=$(ai_memory_parse_toml_key "$marker" project)
st=$(ai_memory_parse_toml_key "$marker" project_strategy)
- qs="&cwd=$(ai_memory_url_encode "$cwd")"
[ -n "$ws" ] && qs="${qs}&workspace=$(ai_memory_url_encode "$ws")"
[ -n "$pr" ] && qs="${qs}&project=$(ai_memory_url_encode "$pr")"
[ -n "$st" ] && qs="${qs}&project_strategy=$(ai_memory_url_encode "$st")"
diff --git a/hooks/claude-code/session-start.sh b/hooks/claude-code/session-start.sh
index 7236a420..1c905f0c 100755
--- a/hooks/claude-code/session-start.sh
+++ b/hooks/claude-code/session-start.sh
@@ -7,8 +7,8 @@
# human in the loop.
#
# Walks up from the payload's cwd for a .ai-memory.toml marker file
-# and appends marker query params to both URLs when found — so a
-# session resuming under marker-declared routing doesn't query the
+# and appends cwd plus marker query params to both URLs — so a session
+# resuming under basename or marker-declared routing doesn't query the
# wrong bucket and miss its own handoff.
# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
# alongside this script. From the source tree it lives one dir up.
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index 3f6b0455..92a93afa 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -1,6 +1,18 @@
function Get-AiMemoryCwd {
param([string] $Payload)
if (-not $Payload) { return $null }
+ try {
+ $Parsed = $Payload | ConvertFrom-Json -ErrorAction Stop
+ foreach ($Name in @("cwd", "current_dir", "working_dir", "directory")) {
+ $Value = $Parsed.$Name
+ if ($Value -is [string] -and $Value.Length -gt 0) { return $Value }
+ }
+ $Paths = $Parsed.workspacePaths
+ if ($null -ne $Paths -and $Paths.Count -gt 0 -and $Paths[0] -is [string] -and $Paths[0].Length -gt 0) {
+ return $Paths[0]
+ }
+ } catch {
+ }
$match = [regex]::Match($Payload, '"cwd"\s*:\s*"([^"]*)"')
if ($match.Success) { return $match.Groups[1].Value }
$workspaceMatch = [regex]::Match($Payload, '"workspacePaths"\s*:\s*\[\s*"([^"]*)"')
@@ -36,9 +48,10 @@ function Get-AiMemoryTomlKey {
function Get-AiMemoryMarkerQuery {
param([string] $Cwd)
- $marker = Get-AiMemoryMarkerToml -Cwd $Cwd
- if (-not $marker) { return "" }
+ if (-not $Cwd) { return "" }
$qs = "&cwd=$([uri]::EscapeDataString($Cwd))"
+ $marker = Get-AiMemoryMarkerToml -Cwd $Cwd
+ if (-not $marker) { return $qs }
$ws = Get-AiMemoryTomlKey -File $marker -Key "workspace"
if ($ws) { $qs += "&workspace=$([uri]::EscapeDataString($ws))" }
$proj = Get-AiMemoryTomlKey -File $marker -Key "project"
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index cf098859..c08f3b32 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -78,7 +78,7 @@ QS2=$(ai_memory_marker_qs "$TMP/a/b/c")
assert_eq "closer marker wins" "&cwd=$TMP/a/b/c&workspace=ws1&project=p1&project_strategy=repo-root" "$QS2"
QS3=$(ai_memory_marker_qs "$TMP/nonexistent")
-assert_eq "no marker -> empty qs" "" "$QS3"
+assert_eq "no marker -> cwd only" "&cwd=$TMP/nonexistent" "$QS3"
# --- url_encode -------------------------------------------------------
assert_eq "url_encode passes safe slug" "movvia" "$(ai_memory_url_encode "movvia")"