Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): RFC 3986 allow-list URL encoding + handoff-fetch diagnostics (#188)
AkitaOnRails8e610dad39b0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ab90847f..fe62248f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0idempotent) ([#187]).### Fixed+- Hook query values are now percent-encoded with an RFC 3986 allow-list+ (everything outside `A-Za-z0-9-_.~`) in both the native helper and the+ POSIX `hooks/_lib.sh`, and the shell cwd extractor unescapes JSON `\\` /+ `\/`. Previously a Windows cwd like `C:\dev\myproject` went into the query+ string with raw backslashes — confirmed to break the shell-script hook+ fallback outside Git Bash, and the suspected cause of the native+ session-start hook returning `{}` on Windows while the pending handoff+ stayed unconsumed. The session-start hook also now prints a stderr+ warning when the handoff fetch fails (server unreachable, bad URL)+ instead of being indistinguishable from "no pending handoff" — exit code+ stays 0, hooks never break the agent ([#188]).- `install-mcp --server-url` now appends the `/mcp` path when given a baseURL (the same value `install-hooks --server-url` takes), instead ofrendering a client config that points at the server root and 404s. Thediff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 33d8dac1..bb065e87 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -47,20 +47,25 @@ pub fn resolve_cwd_with_fallbacks(})}-/// URL-encode the reserved characters `ai_memory_url_encode` handles.+/// Percent-encode everything outside the RFC 3986 unreserved set+/// (`A-Z a-z 0-9 - _ . ~`), byte-wise, so multibyte UTF-8 is encoded+/// per byte. Parity with `ai_memory_url_encode` in `hooks/_lib.sh`.+///+/// An allow-list on purpose: the old deny-list missed `\` (and friends),+/// so a Windows cwd like `C:\dev\myproject` went into the query string+/// raw and the HTTP layer refused the request — the session-start hook+/// printed `{}` and the pending handoff was never fetched (#188).+/// Over-encoding is always safe; the server percent-decodes uniformly.pub fn url_encode(s: &str) -> String {let mut out = String::with_capacity(s.len());- for c in s.chars() {- match c {- '%' => out.push_str("%25"),- '+' => out.push_str("%2B"),- '&' => out.push_str("%26"),- '=' => out.push_str("%3D"),- '?' => out.push_str("%3F"),- '#' => out.push_str("%23"),- ' ' => out.push_str("%20"),- '/' => out.push_str("%2F"),- other => out.push(other),+ for b in s.bytes() {+ match b {+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {+ out.push(b as char);+ }+ other => {+ out.push_str(&format!("%{other:02X}"));+ }}}out@@ -403,7 +408,19 @@ pub async fn get_handoff(if let Some(t) = token {req = req.bearer_auth(t);}- let resp = req.send().await.ok()?;+ // Warn on stderr instead of failing silently: the hook still exits 0 (a+ // hook must never break the agent), but an unreachable server would+ // otherwise be indistinguishable from "no pending handoff" (#188).+ let resp = match req.send().await {+ Ok(r) => r,+ Err(e) => {+ eprintln!(+ "ai-memory hook warning: handoff fetch failed ({e}); \+ a pending handoff (if any) was NOT injected"+ );+ return None;+ }+ };if !resp.status().is_success() {return None;}@@ -598,6 +615,40 @@ project = "infra" # this is fine/// `marker_query_suffix` appends `&workspace=…&project=…` (and/// `&project_strategy=…`, `&drop_subagent=…`) when the marker declares them./// Each value is URL-encoded, so a workspace with a space round-trips as `%20`.+ /// Regression for #188: a Windows cwd must be fully percent-encoded or+ /// the HTTP layer refuses the request URL and the session-start hook+ /// silently returns `{}` while the handoff stays pending.+ #[test]+ fn url_encode_is_an_unreserved_allow_list() {+ // The reported case: raw `\` and `:` broke the request outright.+ assert_eq!(url_encode(r"C:\dev\myproject"), "C%3A%5Cdev%5Cmyproject");+ // RFC 3986 unreserved passes through untouched.+ assert_eq!(url_encode("abc-XYZ_0.9~"), "abc-XYZ_0.9~");+ // Previous deny-list behavior is preserved (space, slash, etc.).+ assert_eq!(url_encode("/home/u/my repo"), "%2Fhome%2Fu%2Fmy%20repo");+ // Multibyte UTF-8 is encoded per byte.+ assert_eq!(url_encode("r\u{e9}po"), "r%C3%A9po");+ }++ /// The full marker suffix built from a Windows cwd must parse as a real+ /// URL query — the end-to-end guarantee behind the #188 fix.+ #[test]+ fn marker_query_suffix_windows_cwd_yields_parseable_url() {+ let qs = marker_query_suffix(r"C:\dev\myproject", None);+ assert!(qs.contains("cwd=C%3A%5Cdev%5Cmyproject"), "{qs}");+ let url = format!("http://127.0.0.1:49374/handoff?agent=claude-code{qs}");+ let parsed = reqwest::Url::parse(&url).expect("must be a valid URL");+ let cwd = parsed+ .query_pairs()+ .find(|(k, _)| k == "cwd")+ .map(|(_, v)| v.into_owned())+ .expect("cwd param present");+ assert_eq!(+ cwd, r"C:\dev\myproject",+ "round-trips through percent-decoding"+ );+ }+#[test]fn marker_query_suffix_appends_marker_fields() {let tmp = tempfile::TempDir::new().unwrap();diff --git a/hooks/_lib.sh b/hooks/_lib.shindex 2274ad0d..d5f425ba 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -41,20 +41,29 @@ ai_memory_parse_toml_key() {# not a JSON parser; taking the first match preserves the top-level cwd when# tool payloads contain nested `cwd` fields later in the object. Antigravity# CLI sends `workspacePaths: ["/repo", ...]` instead of `cwd`.+# Undo the JSON string escapes that can appear in a path value: \\ -> \+# and \/ -> /. Windows payloads carry cwd as "C:\\dev\\proj"; without this+# the doubled backslashes leak into the query string (#188).+ai_memory_json_unescape_path() {+ printf '%s' "$1" | sed 's/\\\\/\\/g; s/\\\//\//g'+}+ai_memory_extract_cwd() {payload="${1:-$(cat)}"rest=${payload#*\"cwd\"}if [ "$rest" != "$payload" ]; then- printf '%s' "$rest" \+ raw=$(printf '%s' "$rest" \| sed -n -E 's/^[[:space:]]*:[[:space:]]*"([^"]*)".*/\1/p' \- | head -n 1+ | head -n 1)+ ai_memory_json_unescape_path "$raw"return 0firest=${payload#*\"workspacePaths\"}[ "$rest" = "$payload" ] && return 0- printf '%s' "$rest" \+ raw=$(printf '%s' "$rest" \| sed -n -E 's/^[[:space:]]*:[[:space:]]*\[[[:space:]]*"([^"]*)".*/\1/p' \- | head -n 1+ | head -n 1)+ ai_memory_json_unescape_path "$raw"}# Resolve cwd for agents whose native hook payload omits it. Payload wins,@@ -76,9 +85,26 @@ ai_memory_resolve_cwd() {# 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.+# Percent-encode everything outside the RFC 3986 unreserved set+# (A-Z a-z 0-9 - _ . ~), byte-wise under LC_ALL=C so multibyte UTF-8 is+# encoded per byte. Allow-list on purpose: the old deny-list missed+# backslash, so a Windows cwd went into the query string raw and the+# request never reached the server (#188). Parity with the native+# helper's url_encode in hook_capture.rs.ai_memory_url_encode() {- printf '%s' "$1" \- | sed 's/%/%25/g; s/+/%2B/g; s/&/%26/g; s/=/%3D/g; s/?/%3F/g; s/#/%23/g; s/ /%20/g'+ LC_ALL=C+ s="$1"+ out=""+ while [ -n "$s" ]; do+ rest="${s#?}"+ c="${s%"$rest"}"+ s="$rest"+ case $c in+ [A-Za-z0-9._~-]) out="$out$c" ;;+ *) out="$out$(printf '%%%02X' "'$c")" ;;+ esac+ done+ printf '%s' "$out"}# Resolve the basename of the MAIN git repository root for "$1" (a cwd),