Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hooks): script hooks fail closed on a server profile (#992)
Talysson de Oliveira Cassiano0983341094f5
diff --git a/crates/ai-memory-hooks/tests/suite/mod.rs b/crates/ai-memory-hooks/tests/suite/mod.rsindex a1a0946b..c13e37e9 100644--- a/crates/ai-memory-hooks/tests/suite/mod.rs+++ b/crates/ai-memory-hooks/tests/suite/mod.rs@@ -3,4 +3,5 @@//! no extra binary; a new file must be declared below.mod powershell_home;+mod powershell_server_routed;mod powershell_utf8;diff --git a/crates/ai-memory-hooks/tests/suite/powershell_server_routed.rs b/crates/ai-memory-hooks/tests/suite/powershell_server_routed.rsnew file mode 100644index 00000000..70785998--- /dev/null+++ b/crates/ai-memory-hooks/tests/suite/powershell_server_routed.rs@@ -0,0 +1,141 @@+//! Windows PowerShell regression test for the server-profile guard (#992).+//!+//! The script hooks cannot route a `server` profile, so+//! `Test-AiMemoryServerRouted` must make them emit nothing for a routed+//! repository instead of delivering it to the install default. This runs the+//! real function against a fixture tree and checks it mirrors the native+//! walk: routing is inherited down the tree, any value shape counts and a+//! BOM cannot hide the key, look-alike keys do not count, the walk stops at+//! `$HOME` but continues past a checkout root outside it, and no argument+//! means the current directory.++#![cfg(windows)]++use std::path::{Path, PathBuf};+use std::process::Command;++fn repo_root() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .and_then(Path::parent)+ .expect("crate should live under crates/ai-memory-hooks")+ .to_path_buf()+}++fn write(path: &Path, bytes: &[u8]) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, bytes).unwrap();+}++/// Each case sets `$env:HOME` (the walk boundary) and asks whether `cwd` is+/// routed; the script prints one `T`/`F` per case in order.+const PROGRAM: &str = r#". '__HELPER__'; $Error.Clear()+$r = $env:AI_MEMORY_TEST_ROOT+$h = Join-Path $r 'home'+$h2 = Join-Path $r 'home2'+function Case([string]$hm, [string]$cwd) {+ $env:HOME = $hm; $env:USERPROFILE = $hm+ if (Test-AiMemoryServerRouted -Cwd $cwd) { 'T' } else { 'F' }+}+$out = @(+ (Case $h (Join-Path $h 'routed')),+ (Case $h (Join-Path $h 'routed\sub')),+ (Case $h (Join-Path $h 'bom')),+ (Case $h (Join-Path $h 'plain')),+ (Case $h (Join-Path $h 'lookalike')),+ (Case $h (Join-Path $h 'nothing')),+ (Case (Join-Path $h2 'inner') (Join-Path $h2 'inner\repo')),+ (Case $h2 (Join-Path $h2 'inner\repo')),+ (Case $h (Join-Path $r 'org\repo')),+ (Case $h (Join-Path $r 'outside\repo'))+)+$env:HOME = $h; $env:USERPROFILE = $h+Set-Location (Join-Path $h 'routed')+$out += $(if (Test-AiMemoryServerRouted) { 'T' } else { 'F' })+if ($Error.Count -ne 0) { [Console]::Error.Write(($Error | Out-String)); exit 17 }+[Console]::Out.Write(($out -join ''))+"#;++#[test]+fn server_routed_guard_mirrors_the_native_walk() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path();+ // Inside home: inherited down the tree, any value shape, BOM-proof.+ write(+ &root.join("home/routed/.ai-memory.toml"),+ b"workspace = \"b\"\nserver = \"team-b\"\n",+ );+ write(+ &root.join("home/routed/sub/.ai-memory.toml"),+ b"workspace = \"sub\"\n",+ );+ write(+ &root.join("home/bom/.ai-memory.toml"),+ b"\xEF\xBB\xBFserver = team-b\n",+ );+ write(+ &root.join("home/plain/.ai-memory.toml"),+ b"workspace = \"a\"\n",+ );+ write(+ &root.join("home/lookalike/.ai-memory.toml"),+ b"# server = \"x\"\nservers = \"x\"\nmy_server = \"x\"\n",+ );+ std::fs::create_dir_all(root.join("home/nothing")).unwrap();+ // A marker above $HOME is out of reach; the same cwd with a wider home+ // sees it, so the boundary and not the fixture is what hides it.+ write(+ &root.join("home2/.ai-memory.toml"),+ b"server = \"team-b\"\n",+ );+ std::fs::create_dir_all(root.join("home2/inner/repo")).unwrap();+ // Outside home: the walk continues past a checkout root to an+ // organisation-level marker, and finds nothing when there is none.+ write(&root.join("org/.ai-memory.toml"), b"server = \"team-b\"\n");+ std::fs::create_dir_all(root.join("org/repo/.git")).unwrap();+ write(+ &root.join("org/repo/.ai-memory.toml"),+ b"workspace = \"api\"\n",+ );+ std::fs::create_dir_all(root.join("outside/repo/.git")).unwrap();+ write(+ &root.join("outside/repo/.ai-memory.toml"),+ b"workspace = \"api\"\n",+ );++ let helper = repo_root()+ .join("hooks")+ .join("lib")+ .join("ai-memory-hook.ps1");+ let helper = helper.to_string_lossy().replace('\'', "''");+ let program = PROGRAM.replace("__HELPER__", &helper);+ let output = Command::new(ai_memory_test_support::powershell_exe())+ .args([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-ExecutionPolicy",+ "Bypass",+ "-Command",+ &program,+ ])+ .env("AI_MEMORY_TEST_ROOT", root)+ .output()+ .expect("run PowerShell server-routed guard");+ assert!(+ output.status.success(),+ "PowerShell guard failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(+ output.stderr.is_empty(),+ "PowerShell guard polluted stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert_eq!(+ String::from_utf8_lossy(&output.stdout),+ "TTTFFFFTTFT",+ "routed, inherited, bom, plain, lookalike, none, above-home, \+ above-home-control, org-outside-home, outside-none, current-dir"+ );+}diff --git a/hooks/_lib.sh b/hooks/_lib.shindex 1e806857..cde5925a 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -83,12 +83,59 @@ ai_memory_marker_declares_settings() {for key in workspace project project_strategy drop_subagent_captures identity; do[ -n "$(ai_memory_parse_toml_key "$file" "$key")" ] && return 0done+ ai_memory_marker_declares_server "$file" && return 0for key in default_global inject_on_session_start max_chars; do[ -n "$(ai_memory_parse_toml_flag "$file" "$key")" ] && return 0donereturn 1}+# Whether marker "$1" declares a `server = ...` profile selection (#992), in+# any value shape. Line-based and section-blind like marker.rs+# `server_selection_in`; the leading class also skips a UTF-8 BOM, which is+# not whitespace to grep. An unreadable marker counts as declaring one.+ai_memory_marker_declares_server() {+ [ -r "$1" ] || return 0+ LC_ALL=C grep -Eq '^[^A-Za-z0-9_#"]*server[[:space:]]*=' "$1"+}++# Whether any marker on the walk from "$1" (default: the process cwd)+# selects a server profile (#992). These script hooks cannot route profiles+# — only native `ai-memory hook` commands can — so a routed repository must+# emit nothing rather than reach the install-default server. Mirrors the+# native walk: inside $HOME it stops at $HOME; outside it continues past the+# checkout root, so an organisation-level marker above a repository counts.+ai_memory_server_routed() {+ _amsr_dir="${1:-${PWD:-}}"+ [ -z "$_amsr_dir" ] && return 1+ _amsr_boundary=""+ if [ -n "${HOME:-}" ]; then+ case "$_amsr_dir" in+ "$HOME"|"$HOME"/*) _amsr_boundary="$HOME" ;;+ esac+ fi+ while [ -n "$_amsr_dir" ]; do+ if [ -f "$_amsr_dir/.ai-memory.toml" ] \+ && ai_memory_marker_declares_server "$_amsr_dir/.ai-memory.toml"; then+ return 0+ fi+ [ "$_amsr_dir" = "$_amsr_boundary" ] && return 1+ [ "$_amsr_dir" = "/" ] && return 1+ # Parameter expansion, not `dirname`: this walk runs on every hook+ # event, and a fork per directory level adds up.+ _amsr_parent="${_amsr_dir%/*}"+ [ "$_amsr_parent" = "$_amsr_dir" ] && return 1+ _amsr_dir="${_amsr_parent:-/}"+ done+ return 1+}++# Query-string flag `ai_memory_marker_qs` appends for a profile-routed+# repository. `ai_memory_post_hook` and `ai_memory_get_handoff` refuse any URL+# carrying it, so every script that builds its URL from the marker query —+# all of them — fails closed without a per-script check.+AI_MEMORY_SERVER_ROUTED_QS="&server_routed=1"+# Like ai_memory_find_marker, but skips a marker that declares nothing beyond# `[capture]` (see ai_memory_marker_declares_settings) and continues the walk# to the next ancestor. Resolves workspace/project/project_strategy and the@@ -382,6 +429,10 @@ ai_memory_identity_qs() {# as the prior hook events even when no marker file exists.ai_memory_marker_qs() {cwd="$1"+ if ai_memory_server_routed "$cwd"; then+ printf '%s' "$AI_MEMORY_SERVER_ROUTED_QS"+ return 0+ fiif [ -z "$cwd" ]; thenai_memory_managed_qsreturn 0@@ -597,6 +648,7 @@ ai_memory_post_hook() {cat >/dev/null 2>&1 || truereturn 0fi+ case "$1" in *"$AI_MEMORY_SERVER_ROUTED_QS"*) cat >/dev/null; return 0 ;; esac_amurl=$(ai_memory_url_with_ingest_key "$1")_ambody=$(cat)_amhdr=$(ai_memory_auth_header_file || printf '')@@ -635,6 +687,7 @@ ai_memory_post_hook() {# stdout (and prepended to the agent's context), so we want to avoid# truncating a handoff that was almost ready.ai_memory_get_handoff() {+ case "$1" in *"$AI_MEMORY_SERVER_ROUTED_QS"*) return 0 ;; esac_amhdr=$(ai_memory_auth_header_file)if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; thencurl -s --max-time 1.0 "$1" \diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index 63f8f172..30611af8 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -81,6 +81,41 @@ function Get-AiMemoryMarkerToml {return $null}+# Whether any marker on the walk from $Cwd (default: the current directory)+# selects a server profile (`server = ...`, #992). This script fallback cannot+# route profiles — only native `ai-memory hook` commands can — so a routed+# repository must emit nothing rather than reach the install-default server.+# Mirrors the native walk: inside home it stops at home; outside it continues+# past the checkout root. An unreadable marker counts as a selection.+function Test-AiMemoryServerRouted {+ param([string] $Cwd)+ $dir = if ($Cwd) { $Cwd } else { (Get-Location).Path }+ $userHome = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }+ $boundary = $null+ if ($userHome) {+ $userHomePrefix = $userHome.TrimEnd([char[]]@('/', '\')) + [IO.Path]::DirectorySeparatorChar+ if (($dir -eq $userHome) -or $dir.StartsWith($userHomePrefix, [StringComparison]::OrdinalIgnoreCase)) {+ $boundary = $userHome+ }+ }+ while ($dir) {+ $candidate = Join-Path $dir ".ai-memory.toml"+ if (Test-Path $candidate -PathType Leaf) {+ try {+ $text = [IO.File]::ReadAllText($candidate)+ } catch {+ return $true+ }+ if ([regex]::IsMatch($text, '(?m)^[\s]*server\s*=')) { return $true }+ }+ if ($boundary -and $dir -eq $boundary) { return $false }+ $parent = Split-Path $dir -Parent+ if (-not $parent -or $parent -eq $dir) { return $false }+ $dir = $parent+ }+ return $false+}+function Get-AiMemoryTomlKey {param([string] $File, [string] $Key)if (-not (Test-Path $File -PathType Leaf)) { return $null }@@ -444,6 +479,10 @@ function Invoke-AiMemoryHook {return}$Cwd = Resolve-AiMemoryCwd -Payload $Payload -Agent $Agent+ if (Test-AiMemoryServerRouted -Cwd $Cwd) {+ if ($AntigravityPreInvocationOutput) { [Console]::Out.Write("{}") }+ return+ }$QS = Get-AiMemoryMarkerQuery -Cwd $Cwdif ($env:AI_MEMORY_RUN_ID) {$QS += "&managed_run=$([Uri]::EscapeDataString($env:AI_MEMORY_RUN_ID))"diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex ebdee138..ccec7453 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -193,6 +193,16 @@ PS_HOME_STATIC=$(grep -Fq '$userHome = if ($env:HOME)' hooks/lib/ai-memory-hook.&& ! grep -Eq '\$home[[:space:]]*=' hooks/lib/ai-memory-hook.ps1 \&& printf 'ok' || printf 'missing')assert_eq "powershell marker helper avoids read-only HOME" "ok" "$PS_HOME_STATIC"+# The guard's own behaviour is exercised by the Windows-only Rust test+# (`powershell_server_routed.rs`); this pins that the hook entry point calls+# it before it builds the query, on every platform the shell suite runs.+PS_ROUTED_STATIC=$(grep -q 'function Test-AiMemoryServerRouted' hooks/lib/ai-memory-hook.ps1 \+ && awk '/function Invoke-AiMemoryHook/ {f=1}+ f && /Test-AiMemoryServerRouted/ && !t {t=NR}+ f && /Get-AiMemoryMarkerQuery/ && !q {q=NR}+ END {exit !(t && q && t < q)}' hooks/lib/ai-memory-hook.ps1 \+ && printf 'ok' || printf 'missing')+assert_eq "powershell hook refuses a routed repository before building its query" "ok" "$PS_ROUTED_STATIC"# --- json_string -------------------------------------------------------JSON_INPUT='quoted "thing" \ path@@ -680,6 +690,50 @@ elseprintf ' skip grok ps behavioral probe (pwsh unavailable)\n'fi+# --- server profiles (#992) --------------------------------------------+# Script hooks cannot route a `server` profile, so a routed repository must+# reach neither the install-default server nor the spool.+mkdir -p "$TMP/routed/sub" "$TMP/routed-bom" "$TMP/server-only/inner"+printf 'workspace = "team-b"\nserver = "team-b"\n' >"$TMP/routed/.ai-memory.toml"+printf 'workspace = "sub"\n' >"$TMP/routed/sub/.ai-memory.toml"+printf '\357\273\277server = team-b\n' >"$TMP/routed-bom/.ai-memory.toml"+printf 'workspace = "outer"\n' >"$TMP/server-only/.ai-memory.toml"+printf 'server = "team-b"\n' >"$TMP/server-only/inner/.ai-memory.toml"++assert_eq "routed marker: marker_qs carries only the routed flag" \+ "&server_routed=1" "$(ai_memory_marker_qs "$TMP/routed")"+assert_eq "routed marker is inherited past a nested workspace-only marker" \+ "&server_routed=1" "$(ai_memory_marker_qs "$TMP/routed/sub")"+assert_eq "a BOM cannot hide the server key" \+ "&server_routed=1" "$(ai_memory_marker_qs "$TMP/routed-bom")"+assert_eq "a server-only marker is a settings boundary" \+ "$TMP/server-only/inner/.ai-memory.toml" \+ "$(ai_memory_find_settings_marker "$TMP/server-only/inner")"+assert_eq "an unrouted repository is unchanged" \+ "&cwd=$(ai_memory_url_encode "$TMP/scope/inner")" \+ "$(ai_memory_marker_qs "$TMP/scope/inner")"++AI_MEMORY_DATA_DIR="$TMP/routed-data"+export AI_MEMORY_DATA_DIR+CURL_CALLED="$TMP/curl-called"+rm -f "$CURL_CALLED"+curl() {+ : >"$CURL_CALLED"+ cat >/dev/null+ return 7+}+printf '%s' '{"e":"routed"}' \+ | ai_memory_post_hook "http://127.0.0.1:1/hook?event=user-prompt&agent=cursor$(ai_memory_marker_qs "$TMP/routed")" \+ >/dev/null 2>&1+ROUTED_HANDOFF=$(ai_memory_get_handoff "http://127.0.0.1:1/handoff?agent=cursor$(ai_memory_marker_qs "$TMP/routed")")+unset -f curl+assert_eq "a routed post and handoff never call curl" "no" \+ "$([ -e "$CURL_CALLED" ] && echo yes || echo no)"+assert_eq "a routed post is not spooled" "0" \+ "$(ls "$TMP/routed-data/hook-spool/"*.json 2>/dev/null | wc -l | tr -d ' ')"+assert_eq "a routed handoff fetch prints nothing" "" "$ROUTED_HANDOFF"+unset AI_MEMORY_DATA_DIR+# --- summary ----------------------------------------------------------printf '\n%d passed, %d failed\n' "$PASS" "$FAIL"[ "$FAIL" -eq 0 ]