Skip to content

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

Rust

feat(hooks): implement subagent payload checks and context clipping

Test4efe275497cf
diff --git a/crates/ai-memory-cli/src/commands/upgrade.rs b/crates/ai-memory-cli/src/commands/upgrade.rs
index 4cd55e2e..191e413c 100644
--- a/crates/ai-memory-cli/src/commands/upgrade.rs
+++ b/crates/ai-memory-cli/src/commands/upgrade.rs
@@ -10,6 +10,15 @@
//!
//! Client-only: never claims to upgrade a remote/homelab server.
//!
+//! Egress decisions (AR004-style, cited): **timeout** — every request runs
+//! with a hard 120 s client timeout and non-2xx fail-fast
+//! ([`HTTP_TIMEOUT_SECS`]); **cache** — explicit none, this is a one-shot
+//! CLI fetch, the extract `TempDir` is discarded after the replace, and a
+//! cached archive would only add a stale-binary risk; **rate limit / load
+//! shedding** — n/a (single outbound GET from a user-invoked CLI command,
+//! no ingress). The 128 MiB body cap is a security limit, not a resilience
+//! decision (see [`MAX_RELEASE_DOWNLOAD_BYTES`]).
+//!
//! Ownership (live CLI command — kept in one module by convention):
//! - install classification (container / package-managed / writable)
//! - release fetch + checksum
@@ -1014,6 +1023,40 @@ mod tests {
assert!(package_managed_refusal(exe).is_some());
}
+ /// Focused predicate test for the writability refusal (the composite
+ /// `classify_install` cases above would all pass if the refusal branch
+ /// were deleted). Skipped when the effective uid ignores directory
+ /// permission bits (root CI runners).
+ #[cfg(unix)]
+ #[test]
+ fn classify_refuses_unwritable_parent_directory() -> Result<()> {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir()?;
+ let parent = dir.path().join("ro");
+ fs::create_dir(&parent)?;
+ let exe = parent.join(shipped_binary_name());
+ fs::write(&exe, b"fake")?;
+ fs::set_permissions(&parent, fs::Permissions::from_mode(0o555))?;
+ let probe = parent.join(".root-probe");
+ if fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&probe)
+ .is_ok()
+ {
+ let _ = fs::remove_file(&probe);
+ eprintln!("skipping: uid ignores directory permissions (root runner)");
+ return Ok(());
+ }
+ let class = classify_install(&exe)?;
+ assert!(
+ matches!(class, InstallClass::Unsupported(ref reason) if reason.contains("writable")),
+ "expected a writability refusal, got {class:?}"
+ );
+ fs::set_permissions(&parent, fs::Permissions::from_mode(0o755))?;
+ Ok(())
+ }
+
#[test]
fn classify_accepts_writable_user_prefix() -> Result<()> {
let dir = tempfile::tempdir()?;
diff --git a/hooks/grok/post-tool-use.sh b/hooks/grok/post-tool-use.sh
index a57e5045..9d8504c7 100755
--- a/hooks/grok/post-tool-use.sh
+++ b/hooks/grok/post-tool-use.sh
@@ -29,8 +29,11 @@ if [ -f "$SHOWN" ]; then
exit 0
fi
+# Subagent payloads must not take the parent's handoff — same key set as
+# the native router (`commands/hook.rs::payload_is_subagent`): subagentType,
+# subagent_type, agent_type, agent_id, parentSessionId.
case "$PAYLOAD" in
- *'"subagentType"'*|*'\"subagentType\"'*|*'"parentSessionId"'*)
+ *'"subagentType"'*|*'"subagent_type"'*|*'"agent_type"'*|*'"agent_id"'*|*'"parentSessionId"'*|*'\"subagentType\"'*)
printf '{}\n'
exit 0
;;
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index 236d7043..aefa40e6 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -296,6 +296,32 @@ function Test-AiMemoryCaptureOwnedExternally {
return (-not [string]::IsNullOrWhiteSpace($env:AI_MEMORY_CAPTURE_OWNER))
}
+# Parity with `payload_is_subagent` in the native router
+# (`commands/hook.rs`): a subagent/child payload must not take the parent
+# session's handoff. True when any known child-session marker key holds a
+# non-empty string.
+function Test-AiMemorySubagentPayload {
+ param([object] $ParsedPayload)
+ if ($null -eq $ParsedPayload) { return $false }
+ foreach ($Name in @(
+ "subagentType", "subagent_type", "agent_type", "agent_id", "parentSessionId"
+ )) {
+ $Value = $ParsedPayload.$Name
+ if ($Value -is [string] -and $Value.Trim().Length -gt 0) { return $true }
+ }
+ return $false
+}
+
+# Parity with `clip_chars` in the native router: Grok's additionalContext
+# is capped (10 000 chars) so an oversized handoff cannot flood the model
+# context through the script fallback either.
+function Clip-AiMemoryChars {
+ param([string] $Text, [int] $MaxChars)
+ if ($Text.Length -le $MaxChars) { return $Text }
+ $keep = [Math]::Max(0, $MaxChars - 12)
+ return ($Text.Substring(0, $keep) + "`n[truncated]")
+}
+
function Invoke-AiMemoryHook {
param(
[Parameter(Mandatory = $true)] [string] $Event,
@@ -382,8 +408,24 @@ function Invoke-AiMemoryHook {
}
$Shown = $null
if ($GrokPostTool) {
+ if (Test-AiMemorySubagentPayload $ParsedPayload) {
+ # A child session must not accept the parent handoff (and the
+ # GET is destructive), so bail before any fetch. Parity with
+ # the native router and the shell `post-tool-use.sh` gate.
+ [Console]::Out.Write("{}")
+ return
+ }
$ShownKey = [string]$NativeSessionId
- if (-not $ShownKey) { $ShownKey = "grok-post-$PID" }
+ if (-not $ShownKey) {
+ # Stable fallback (parity with the shell bundle's
+ # `cksum("grok:$CWD")`): hash agent+cwd, never the process id —
+ # each hook invocation is a new process, so a `$PID`-keyed
+ # marker would never match and the destructive GET would run
+ # on every tool call.
+ $Sha = [System.Security.Cryptography.SHA256]::Create()
+ $Bytes = $Sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes("grok:$Cwd"))
+ $ShownKey = "grok-post-" + (($Bytes | ForEach-Object { $_.ToString("x2") }) -join "").Substring(0, 16)
+ }
$Shown = Get-AiMemoryBriefedFile -Key "post-$ShownKey"
if (Test-Path $Shown -PathType Leaf) {
[Console]::Out.Write("{}")
@@ -424,7 +466,7 @@ function Invoke-AiMemoryHook {
$Wrapped = @{
hookSpecificOutput = @{
hookEventName = "PostToolUse"
- additionalContext = $Response.Content
+ additionalContext = (Clip-AiMemoryChars ([string]$Response.Content) 10000)
}
}
[Console]::Out.Write(($Wrapped | ConvertTo-Json -Depth 5 -Compress))
diff --git a/tests/hooks/test_grok_ps.ps1 b/tests/hooks/test_grok_ps.ps1
new file mode 100644
index 00000000..f4894d00
--- /dev/null
+++ b/tests/hooks/test_grok_ps.ps1
@@ -0,0 +1,36 @@
+# Behavioral evidence for the Grok PowerShell handoff helpers (pure
+# functions only — no HTTP, no process state). Invoked by
+# tests/hooks/test_lib.sh when pwsh is available; exits non-zero on any
+# failed assertion.
+
+param([Parameter(Mandatory = $true)] [string] $PsLib)
+
+$ErrorActionPreference = "Stop"
+. $PsLib
+
+function Assert-True($value, $label) {
+ if (-not $value) { throw "grok ps probe failed: $label" }
+}
+
+# 1. Child-session gate: every key the native router checks, and the
+# negative cases.
+foreach ($key in @("subagentType", "subagent_type", "agent_type", "agent_id", "parentSessionId")) {
+ $payload = ConvertFrom-Json ('{"' + $key + '":"planner-a"}')
+ Assert-True (Test-AiMemorySubagentPayload $payload) "child key $key detected"
+ $blank = ConvertFrom-Json ('{"' + $key + '":" "}')
+ Assert-True (-not (Test-AiMemorySubagentPayload $blank)) "blank $key is not a child session"
+}
+$parent = ConvertFrom-Json '{"session_id":"g-sess","cwd":"/tmp","tool_name":"read_file"}'
+Assert-True (-not (Test-AiMemorySubagentPayload $parent)) "parent payload is not a child session"
+Assert-True (-not (Test-AiMemorySubagentPayload $null)) "unparsed payload is not a child session"
+
+# 2. additionalContext clip parity with the native 10 000-char cap.
+$long = ("x" * 10100)
+$clipped = Clip-AiMemoryChars $long 10000
+Assert-True ($clipped.Length -le 10000) "clipped length"
+Assert-True ($clipped.EndsWith("`n[truncated]")) "clip marker present"
+$short = Clip-AiMemoryChars "short" 10000
+Assert-True ($short -eq "short") "short text passes through unchanged"
+
+Write-Output "grok ps behavioral probe: ok checks=15"
+exit 0
\ No newline at end of file
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index dfe60fea..efe960dc 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -523,6 +523,115 @@ unset -f curl
unset AI_MEMORY_CAPTURE_OWNER
unset AI_MEMORY_DATA_DIR
+# --- grok post-tool-use.sh: shipped shell handoff path -----------------
+# The native router (`commands/hook.rs`) and this script implement the same
+# contract: one destructive `GET /handoff` per Grok session on the first
+# PostToolUse, wrapped as PostToolUse additionalContext; child-session
+# payloads never fetch (the GET would burn the parent's baton). A PATH curl
+# shim runs the real shipped script, so what is asserted is what ships.
+GROK_HOOK="$(dirname "$0")/../../hooks/grok/post-tool-use.sh"
+mkdir -p "$TMP/bin"
+cat >"$TMP/bin/curl" <<'EOF'
+#!/bin/sh
+# Fake curl: log "METHOD URL"; answer 200 to a POST, HANDOFF BODY to a GET.
+_gm=GET
+_gu=""
+while [ $# -gt 0 ]; do
+ case "$1" in
+ -X) shift; [ $# -gt 0 ] || break; _gm=$1 ;;
+ http://* | https://*) _gu=$1 ;;
+ esac
+ shift
+done
+printf '%s %s\n' "$_gm" "$_gu" >>"$GROK_LOG"
+if [ "$_gm" = POST ]; then printf '200'; else printf 'HANDOFF BODY'; fi
+EOF
+chmod +x "$TMP/bin/curl"
+PATH="$TMP/bin:$PATH"
+export PATH
+
+grok_case() {
+ GROK_CASE_DIR="$TMP/grok-$1"
+ mkdir -p "$GROK_CASE_DIR/data"
+ AI_MEMORY_DATA_DIR="$GROK_CASE_DIR/data"
+ export AI_MEMORY_DATA_DIR
+ GROK_LOG="$GROK_CASE_DIR/curl.log"
+ : >"$GROK_LOG"
+ export GROK_LOG
+}
+grok_gets() { awk '/^GET /{ n++ } END { print n + 0 }' "$GROK_LOG"; }
+grok_run() {
+ printf '%s' "$1" | sh "$(dirname "$0")/../../hooks/grok/post-tool-use.sh" 2>/dev/null
+}
+grok_payload() {
+ printf '{"session_id":"%s","cwd":"%s","tool_name":"read_file"}' "$1" "$GROK_CASE_DIR"
+}
+
+# 1. First PostToolUse of a session: fetches once and wraps as additionalContext.
+grok_case first
+OUT=$(grok_run "$(grok_payload g-sess)")
+case "$OUT" in
+ *'"hookSpecificOutput"'*'"PostToolUse"'*'"additionalContext":"HANDOFF BODY"'*)
+ PASS=$((PASS + 1)); printf ' ok %s\n' "grok: first post-tool-use wraps the handoff" ;;
+ *) FAIL=$((FAIL + 1)); printf ' FAIL grok: first post-tool-use wraps the handoff\n got =%s\n' "$OUT" ;;
+esac
+assert_eq "grok: first post-tool-use GETs the handoff with session id" "1" "$(grok_gets)"
+[ -f "$AI_MEMORY_DATA_DIR/briefed/post-g-sess" ] && PASS=$((PASS + 1)) || {
+ FAIL=$((FAIL + 1)); printf ' FAIL grok: shown marker post-g-sess missing\n'
+}
+
+# 2. Second call in the same session: `{}`, no second (destructive) GET.
+OUT=$(grok_run "$(grok_payload g-sess)")
+assert_eq "grok: second post-tool-use prints empty object" "{}" "$OUT"
+assert_eq "grok: second call does not re-fetch the handoff" "1" "$(grok_gets)"
+
+# 3. Subagent payloads never fetch — every key the native router knows.
+grok_child_payload() {
+ printf '{"session_id":"child","cwd":"%s","tool_name":"read_file","%s":"planner-a"}' \
+ "$GROK_CASE_DIR" "$1"
+}
+for key in subagentType subagent_type agent_type agent_id parentSessionId; do
+ grok_case "child-$key"
+ OUT=$(grok_run "$(grok_child_payload "$key")")
+ assert_eq "grok: $key payload does not fetch the handoff" "{}" "$OUT"
+ assert_eq "grok: $key payload sent zero GETs" "0" "$(grok_gets)"
+done
+
+unset AI_MEMORY_DATA_DIR GROK_LOG
+PATH=${PATH#"$TMP/bin:"}
+export PATH
+
+# --- grok PowerShell bundle parity -------------------------------------
+# The PS lib is the documented fallback when the native binary is absent.
+# Static parity first (no pwsh needed): the child-session key set must
+# match the native router's five keys, and the per-process `$PID` fallback
+# key must never come back (it breaks the once-per-session gate).
+PS_LIB="$(dirname "$0")/../../hooks/lib/ai-memory-hook.ps1"
+for key in subagentType subagent_type agent_type agent_id parentSessionId; do
+ if grep -q "\"$key\"" "$PS_LIB"; then
+ PASS=$((PASS + 1))
+ else
+ FAIL=$((FAIL + 1))
+ printf ' FAIL grok ps: child key %s missing from the subagent gate\n' "$key"
+ fi
+done
+if grep -q 'grok-post-\$PID' "$PS_LIB"; then
+ FAIL=$((FAIL + 1)); printf ' FAIL grok ps: per-process $PID shown-key fallback is back\n'
+else
+ PASS=$((PASS + 1)); printf ' ok grok ps: shown-key fallback is stable, not per-process\n'
+fi
+
+# Behavioral probe: pure functions only, so a pwsh run adds real evidence
+# where pwsh exists (Windows CI / dev boxes) and skips elsewhere (same
+# posture as the Node-required runtime evidence in render_shared.rs).
+if command -v pwsh >/dev/null 2>&1; then
+ PS_OUT=$(pwsh -NoProfile -File "$(dirname "$0")/test_grok_ps.ps1" "$PS_LIB" 2>&1) \
+ && PASS=$((PASS + $(printf '%s\n' "$PS_OUT" | sed -n 's/.*checks=\([0-9]*\).*/\1/p') )) \
+ || { FAIL=$((FAIL + 1)); printf ' FAIL grok ps behavioral probe\n%s\n' "$PS_OUT"; }
+else
+ printf ' skip grok ps behavioral probe (pwsh unavailable)\n'
+fi
+
# --- summary ----------------------------------------------------------
printf '\n%d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]