Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
refactor(hooks): single source-of-truth _lib.sh + DRY post_hook
Pablo Winter358bf8ecffab
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex b3fba286..a82295fe 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -1010,27 +1010,49 @@ fn stage_hook_scripts(source_dir: &Path, agent_label: &str) -> Result<PathBuf> {if !from.is_file() || !is_hook_script_file(&from) {continue;}- let to = dest_root.join(from.file_name().context("bad source file name")?);- fs::copy(&from, &to)- .with_context(|| format!("copying {} → {}", from.display(), to.display()))?;- // Preserve the executable bit — the scripts need to be- // directly invokable by the agent's hook runner.- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mut perms = fs::metadata(&to)?.permissions();- perms.set_mode(0o755);- fs::set_permissions(&to, perms)?;- }+ copy_hook_file(&from, &dest_root)?;copied += 1;}copy_support_hook_scripts(source_dir, &dest_root)?;+ // Stage the shared `_lib.sh` helper alongside the event scripts so+ // they can `. "$(dirname "$0")/_lib.sh"` without depending on the+ // user's PATH or repo layout. The helper lives ONCE in+ // `hooks/_lib.sh` (one parent up from the agent-specific dir) —+ // staging it here is what keeps every agent's runtime view+ // consistent with the source of truth.+ if let Some(shared) = source_dir.parent().map(|p| p.join("_lib.sh"))+ && shared.is_file()+ {+ copy_hook_file(&shared, &dest_root)?;+ }+eprintln!("✓ staged {copied} hook script(s) → {}", dest_root.display());Ok(dest_root)}+/// Copy a single hook file (event script or shared `_lib.sh`) into the+/// staging dir, preserving the executable bit on Unix. Centralised so+/// the script bulk-copy and the `_lib.sh` companion follow the same+/// rules without duplicating permission-handling.+fn copy_hook_file(from: &Path, dest_root: &Path) -> Result<()> {+ let to = dest_root.join(from.file_name().context("bad source file name")?);+ fs::copy(from, &to)+ .with_context(|| format!("copying {} → {}", from.display(), to.display()))?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mut perms = fs::metadata(&to)?.permissions();+ perms.set_mode(0o755);+ fs::set_permissions(&to, perms)?;+ }+ Ok(())+}++/// Copy the optional `lib/` support directory (currently PowerShell+/// helpers for Windows hook parity) alongside the event scripts.+/// No-op when the source bundle doesn't ship it.fn copy_support_hook_scripts(source_dir: &Path, dest_root: &Path) -> Result<()> {let Some(source_hooks_root) = source_dir.parent() else {return Ok(());@@ -1292,6 +1314,61 @@ mod tests {.to_string()}+ // ----------------------------------------------------------------+ // Shared `_lib.sh` staging+ // ----------------------------------------------------------------++ /// `stage_hook_scripts` copies the parent dir's `_lib.sh` alongside+ /// the agent's event scripts so the runtime layout doesn't depend+ /// on the source-tree shape. This is the only piece of evidence we+ /// have that the marker-file walk-up helper actually ships — the+ /// scripts themselves source it with `. "$(dirname "$0")/_lib.sh"`+ /// and a missing helper would surface as a runtime "command not+ /// found" much further from the cause.+ #[test]+ fn stage_hook_scripts_copies_shared_lib_sh() {+ // Distinct agent_label per test: `stage_hook_scripts` writes+ // under `dirs::data_local_dir()/.../hooks/<agent_label>` and+ // the test binary runs cases in parallel, so two tests using+ // the same label race on the same staging dir.+ let tmp = TempDir::new().unwrap();+ let bundle = tmp.path().join("hooks");+ let agent_src = bundle.join("stage-shared-lib");+ fs::create_dir_all(&agent_src).unwrap();+ fs::write(bundle.join("_lib.sh"), "# shared helper\n").unwrap();+ stub_scripts(&agent_src, &["session-start.sh", "post-tool-use.sh"]);++ let staged = stage_hook_scripts(&agent_src, "stage-shared-lib").unwrap();+ assert!(staged.join("session-start.sh").exists());+ assert!(staged.join("post-tool-use.sh").exists());+ assert!(+ staged.join("_lib.sh").exists(),+ "_lib.sh must be staged alongside event scripts",+ );++ let lib = fs::read_to_string(staged.join("_lib.sh")).unwrap();+ assert!(+ lib.contains("shared helper"),+ "staged _lib.sh must match the source-of-truth"+ );+ }++ /// Skipping `_lib.sh` is fine — older source bundles without the+ /// marker-walk-up feature should still install cleanly.+ #[test]+ fn stage_hook_scripts_tolerates_missing_lib_sh() {+ let tmp = TempDir::new().unwrap();+ let bundle = tmp.path().join("hooks");+ let agent_src = bundle.join("stage-no-lib");+ fs::create_dir_all(&agent_src).unwrap();+ // Note: no _lib.sh in `bundle`.+ stub_scripts(&agent_src, &["session-start.sh"]);++ let staged = stage_hook_scripts(&agent_src, "stage-no-lib").unwrap();+ assert!(staged.join("session-start.sh").exists());+ assert!(!staged.join("_lib.sh").exists());+ }+// ----------------------------------------------------------------// OpenCode tests// ----------------------------------------------------------------diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 309e3256..2f0c89ab 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -285,7 +285,18 @@ async fn resolve_project_ids(return Ok((state.workspace_id, state.project_id));}},- (None, None) => unreachable!("guarded above by the early return"),+ (None, None) => {+ // The early-return at the top of the function guards+ // against this branch; the explicit fallback here keeps+ // the resolver panic-free if that guard ever moves or+ // gets refactored. Same effect as `unreachable!`, but+ // visible at compile time instead of inside the panic+ // message.+ state+ .active_project+ .set(state.workspace_id, state.project_id);+ return Ok((state.workspace_id, state.project_id));+ }};let ws = statediff --git a/hooks/_lib.sh b/hooks/_lib.shindex 2703f597..be741996 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -69,3 +69,36 @@ ai_memory_marker_qs() {[ -n "$pr" ] && qs="${qs}&project=$(ai_memory_url_encode "$pr")"printf '%s' "$qs"}++# 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 budget+# (never block the agent), and the trailing `|| true` makes the+# function safe to call from `set -e` scripts.+ai_memory_post_hook() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \+ --data-binary @-+ else+ curl -s --max-time 0.5 -X POST "$1" \+ -H "Content-Type: application/json" \+ --data-binary @-+ fi+}++# GET "$1" with the same auth-header rules as `ai_memory_post_hook`.+# Used by `session-start.sh` to pull the cross-agent handoff before+# the resuming agent's first prompt. 1s budget — slightly more+# generous than POST because the result is *synchronously* fed to+# stdout (and prepended to the agent's context), so we want to avoid+# truncating a handoff that was almost ready.+ai_memory_get_handoff() {+ if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then+ curl -s --max-time 1.0 "$1" \+ -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN"+ else+ curl -s --max-time 1.0 "$1"+ fi+}diff --git a/hooks/claude-code/_lib.sh b/hooks/claude-code/_lib.shdeleted file mode 100644index 9dd9bb58..00000000--- a/hooks/claude-code/_lib.sh+++ /dev/null@@ -1,74 +0,0 @@-# COPY of ../_lib.sh — do not edit directly.-# Source of truth: hooks/_lib.sh.-# Keep in sync by re-running install-hooks or copying manually.-# ai-memory hook helper — find marker file + parse minimal TOML.-# Sourced by per-agent lifecycle hook scripts. POSIX shell only —-# no bash-isms, no external deps (no jq, no toml crate). Keep changes-# byte-trivial because every supported agent (claude-code, codex,-# cursor, gemini-cli, opencode, omp) sources this same file.--# Walk up from "$1" toward $HOME (or /) looking for `.ai-memory.toml`.-# Prints the absolute path of the first marker found, or nothing.-# Stops at $HOME to avoid leaking declarations from a shared system-# user's home into another user's session on multi-user boxes.-ai_memory_find_marker() {- dir="$1"- [ -z "$dir" ] && return 0- while [ -n "$dir" ] && [ "$dir" != "/" ]; do- if [ -f "$dir/.ai-memory.toml" ]; then- printf '%s\n' "$dir/.ai-memory.toml"- return 0- fi- if [ -n "${HOME:-}" ] && [ "$dir" = "$HOME" ]; then- return 0- fi- parent=$(dirname "$dir")- [ "$parent" = "$dir" ] && return 0- dir="$parent"- done-}--# Parse `key = "value"` at the TOML root (no nesting, no arrays, no-# tables). Returns the first match or nothing. Ignores comments and-# blank lines by construction (the regex only matches the `key = "..."`-# shape).-ai_memory_parse_toml_key() {- file="$1"; key="$2"- [ -f "$file" ] || return 0- sed -n -E "s/^[[:space:]]*${key}[[:space:]]*=[[:space:]]*\"([^\"]*)\".*/\1/p" \- "$file" | head -n 1-}--# Extract `cwd` from a JSON payload on stdin or in $1. Returns the-# value or nothing. Tolerates leading whitespace and escaped quotes-# inside other keys by anchoring on the `cwd` key explicitly.-ai_memory_extract_cwd() {- payload="${1:-$(cat)}"- printf '%s' "$payload" \- | sed -n -E 's/.*"cwd"[[:space:]]*:[[:space:]]*"([^"]*)".*/\1/p' \- | head -n 1-}--# 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.-ai_memory_url_encode() {- printf '%s' "$1" \- | sed 's/%/%25/g; s/&/%26/g; s/=/%3D/g; s/?/%3F/g; s/#/%23/g; s/ /%20/g'-}--# Build a `&workspace=X&project=Y` suffix from the marker file walked up-# from "$1". Returns the suffix (with the leading `&`) or nothing. The-# server tolerates either key being absent.-ai_memory_marker_qs() {- cwd="$1"- [ -z "$cwd" ] && return 0- marker=$(ai_memory_find_marker "$cwd")- [ -z "$marker" ] && return 0- ws=$(ai_memory_parse_toml_key "$marker" workspace)- pr=$(ai_memory_parse_toml_key "$marker" project)- qs=""- [ -n "$ws" ] && qs="${qs}&workspace=$(ai_memory_url_encode "$ws")"- [ -n "$pr" ] && qs="${qs}&project=$(ai_memory_url_encode "$pr")"- printf '%s' "$qs"-}diff --git a/hooks/claude-code/post-tool-use.sh b/hooks/claude-code/post-tool-use.shindex 3fbb9c74..84718824 100755--- a/hooks/claude-code/post-tool-use.sh+++ b/hooks/claude-code/post-tool-use.sh@@ -12,19 +12,6 @@ PAYLOAD=$(cat)CWD=$(ai_memory_extract_cwd "$PAYLOAD")QS=$(ai_memory_marker_qs "$CWD")-post_hook() {- if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \- --data-binary @-- else- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- --data-binary @-- fi-}-printf '%s' "$PAYLOAD" \- | post_hook "$SERVER/hook?event=post-tool-use&agent=claude-code${QS}" >/dev/null 2>&1 || true+ | ai_memory_post_hook "$SERVER/hook?event=post-tool-use&agent=claude-code${QS}" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/pre-compact.sh b/hooks/claude-code/pre-compact.shindex f1dda770..5a0a39cb 100755--- a/hooks/claude-code/pre-compact.sh+++ b/hooks/claude-code/pre-compact.sh@@ -12,19 +12,6 @@ PAYLOAD=$(cat)CWD=$(ai_memory_extract_cwd "$PAYLOAD")QS=$(ai_memory_marker_qs "$CWD")-post_hook() {- if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \- --data-binary @-- else- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- --data-binary @-- fi-}-printf '%s' "$PAYLOAD" \- | post_hook "$SERVER/hook?event=pre-compact&agent=claude-code${QS}" >/dev/null 2>&1 || true+ | ai_memory_post_hook "$SERVER/hook?event=pre-compact&agent=claude-code${QS}" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/pre-tool-use.sh b/hooks/claude-code/pre-tool-use.shindex e288467d..1d4c27b1 100755--- a/hooks/claude-code/pre-tool-use.sh+++ b/hooks/claude-code/pre-tool-use.sh@@ -12,19 +12,6 @@ PAYLOAD=$(cat)CWD=$(ai_memory_extract_cwd "$PAYLOAD")QS=$(ai_memory_marker_qs "$CWD")-post_hook() {- if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \- --data-binary @-- else- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- --data-binary @-- fi-}-printf '%s' "$PAYLOAD" \- | post_hook "$SERVER/hook?event=pre-tool-use&agent=claude-code${QS}" >/dev/null 2>&1 || true+ | ai_memory_post_hook "$SERVER/hook?event=pre-tool-use&agent=claude-code${QS}" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/session-end.sh b/hooks/claude-code/session-end.shindex 45e51b13..ba73dea9 100755--- a/hooks/claude-code/session-end.sh+++ b/hooks/claude-code/session-end.sh@@ -12,19 +12,6 @@ PAYLOAD=$(cat)CWD=$(ai_memory_extract_cwd "$PAYLOAD")QS=$(ai_memory_marker_qs "$CWD")-post_hook() {- if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \- --data-binary @-- else- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- --data-binary @-- fi-}-printf '%s' "$PAYLOAD" \- | post_hook "$SERVER/hook?event=session-end&agent=claude-code${QS}" >/dev/null 2>&1 || true+ | ai_memory_post_hook "$SERVER/hook?event=session-end&agent=claude-code${QS}" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/session-start.sh b/hooks/claude-code/session-start.shindex cefa4077..673983da 100755--- a/hooks/claude-code/session-start.sh+++ b/hooks/claude-code/session-start.sh@@ -7,10 +7,9 @@# human in the loop.## Walks up from the payload's cwd for a .ai-memory.toml marker file-# and appends `&workspace=X&project=Y` to both URLs when found, so the-# handoff lookup hits the workspace declared by the marker (otherwise-# a session resuming under a marker would never see the handoff stored-# under `default`).+# and appends `&workspace=X&project=Y` to both URLs when found — so a+# session resuming under a marker-declared workspace doesn't query the+# `default` bucket and miss its own handoff.. "$(dirname "$0")/_lib.sh"SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"@@ -18,30 +17,8 @@ PAYLOAD=$(cat)CWD=$(ai_memory_extract_cwd "$PAYLOAD")QS=$(ai_memory_marker_qs "$CWD")-post_hook() {- if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \- --data-binary @-- else- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- --data-binary @-- fi-}--get_handoff() {- if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- curl -s --max-time 1.0 "$1" \- -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN"- else- curl -s --max-time 1.0 "$1"- fi-}-printf '%s' "$PAYLOAD" \- | post_hook "$SERVER/hook?event=session-start&agent=claude-code${QS}" >/dev/null 2>&1 || true+ | ai_memory_post_hook "$SERVER/hook?event=session-start&agent=claude-code${QS}" >/dev/null 2>&1 || true-get_handoff "$SERVER/handoff?agent=claude-code${QS}" 2>/dev/null || true+ai_memory_get_handoff "$SERVER/handoff?agent=claude-code${QS}" 2>/dev/null || trueexit 0diff --git a/hooks/claude-code/stop.sh b/hooks/claude-code/stop.shindex d1bbf263..0b799ccc 100755--- a/hooks/claude-code/stop.sh+++ b/hooks/claude-code/stop.sh@@ -12,19 +12,6 @@ PAYLOAD=$(cat)CWD=$(ai_memory_extract_cwd "$PAYLOAD")QS=$(ai_memory_marker_qs "$CWD")-post_hook() {- if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \- --data-binary @-- else- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- --data-binary @-- fi-}-printf '%s' "$PAYLOAD" \- | post_hook "$SERVER/hook?event=stop&agent=claude-code${QS}" >/dev/null 2>&1 || true+ | ai_memory_post_hook "$SERVER/hook?event=stop&agent=claude-code${QS}" >/dev/null 2>&1 || trueexit 0diff --git a/hooks/claude-code/user-prompt-submit.sh b/hooks/claude-code/user-prompt-submit.shindex eb1de011..243679bb 100755--- a/hooks/claude-code/user-prompt-submit.sh+++ b/hooks/claude-code/user-prompt-submit.sh@@ -12,19 +12,6 @@ PAYLOAD=$(cat)CWD=$(ai_memory_extract_cwd "$PAYLOAD")QS=$(ai_memory_marker_qs "$CWD")-post_hook() {- if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- -H "Authorization: Bearer $AI_MEMORY_AUTH_TOKEN" \- --data-binary @-- else- curl -s --max-time 0.5 -X POST "$1" \- -H "Content-Type: application/json" \- --data-binary @-- fi-}-printf '%s' "$PAYLOAD" \- | post_hook "$SERVER/hook?event=user-prompt&agent=claude-code${QS}" >/dev/null 2>&1 || true+ | ai_memory_post_hook "$SERVER/hook?event=user-prompt&agent=claude-code${QS}" >/dev/null 2>&1 || trueexit 0