Skip to content

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

Rust

fix(hooks): diagnose malformed native payloads

AkitaOnRails429dfb616c60
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b070eb04..c8ee956f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+- Native lifecycle hooks now accept one leading UTF-8 BOM on JSON stdin, which
+ covers PowerShell pipelines on Windows. Other malformed payloads are dropped
+ before spool or network delivery with a bounded content-free stderr warning;
+ hooks still return `{}` and exit successfully ([#197]).
+
## [1.15.0] - 2026-07-19
### Added
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index f01d5d8d..e7870571 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -297,7 +297,7 @@ pub async fn run(data_dir: Option<PathBuf>, args: HookArgs) -> anyhow::Result<()
async fn run_with_payload<W, S>(
data_dir: Option<PathBuf>,
args: HookArgs,
- mut payload: String,
+ payload: String,
stdout: &mut W,
spawn_background_drainer: S,
) -> anyhow::Result<()>
@@ -305,8 +305,16 @@ where
W: std::io::Write,
S: FnOnce(&Path) -> std::io::Result<()>,
{
- let mut json: serde_json::Value =
- serde_json::from_str(&payload).unwrap_or(serde_json::Value::Null);
+ let (mut payload, mut json) = match parse_hook_payload(payload) {
+ Ok(parsed) => parsed,
+ Err(_) => {
+ eprintln!(
+ "ai-memory hook warning: could not parse event payload as JSON; nothing was captured"
+ );
+ writeln!(stdout, "{{}}")?;
+ return Ok(());
+ }
+ };
let (policy_cwd, canonical_session_id) = hook_context(&args.agent, &json);
let policy = policy_cwd.as_deref().map(capture_policy);
let tool_event = is_tool_event(&args.event);
@@ -468,6 +476,14 @@ where
Ok(())
}
+fn parse_hook_payload(mut payload: String) -> serde_json::Result<(String, serde_json::Value)> {
+ if payload.starts_with('\u{feff}') {
+ payload.drain(..'\u{feff}'.len_utf8());
+ }
+ let json = serde_json::from_str(&payload)?;
+ Ok((payload, json))
+}
+
fn hook_context(agent: &str, raw: &serde_json::Value) -> (Option<String>, Option<String>) {
let (cwd, session_id) = canonical_context(raw);
if cwd.is_some() {
diff --git a/crates/ai-memory-cli/tests/hook_payload.rs b/crates/ai-memory-cli/tests/hook_payload.rs
new file mode 100644
index 00000000..a199548b
--- /dev/null
+++ b/crates/ai-memory-cli/tests/hook_payload.rs
@@ -0,0 +1,92 @@
+//! Native hook stdin parsing regressions, including PowerShell's UTF-8 BOM.
+
+use std::io::Write;
+use std::path::Path;
+use std::process::{Command, Output, Stdio};
+
+fn bin() -> &'static str {
+ env!("CARGO_BIN_EXE_ai-memory")
+}
+
+fn run_hook(data_dir: &Path, payload: &[u8]) -> Output {
+ let mut child = Command::new(bin())
+ .args(["--data-dir"])
+ .arg(data_dir)
+ .args([
+ "hook",
+ "--event",
+ "pre-tool-use",
+ "--agent",
+ "claude-code",
+ "--server-url",
+ "http://127.0.0.1:1",
+ ])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("spawn native hook");
+ child
+ .stdin
+ .take()
+ .expect("hook stdin")
+ .write_all(payload)
+ .expect("write hook payload");
+ child.wait_with_output().expect("wait for native hook")
+}
+
+fn spooled_body(data_dir: &Path) -> String {
+ let spool = data_dir.join("hook-spool");
+ let entries = std::fs::read_dir(spool)
+ .expect("hook spool")
+ .collect::<Result<Vec<_>, _>>()
+ .expect("spool entries");
+ assert_eq!(entries.len(), 1);
+ let entry: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(entries[0].path()).expect("read spool entry"))
+ .expect("parse spool entry");
+ entry["body"].as_str().expect("spooled body").to_owned()
+}
+
+#[test]
+fn native_hook_accepts_plain_and_bom_prefixed_json() {
+ let payload = br#"{"session_id":"windows-test","cwd":"C:\\dev\\project","tool_name":"Read","tool_input":{"file_path":"README.md"}}"#;
+
+ for with_bom in [false, true] {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let mut stdin = Vec::new();
+ if with_bom {
+ stdin.extend_from_slice(&[0xef, 0xbb, 0xbf]);
+ }
+ stdin.extend_from_slice(payload);
+
+ let output = run_hook(tmp.path(), &stdin);
+ assert!(output.status.success());
+ assert_eq!(output.stdout, b"{}\n");
+ assert!(
+ output.stderr.is_empty(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(spooled_body(tmp.path()).as_bytes(), payload);
+ }
+}
+
+#[test]
+fn malformed_native_hook_payload_warns_without_leaking_or_spooling() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let output = run_hook(
+ tmp.path(),
+ b"\xef\xbb\xbf{\"secret\":\"SENTINEL_PRIVATE_PAYLOAD\"",
+ );
+
+ assert!(output.status.success());
+ assert_eq!(output.stdout, b"{}\n");
+ let stderr = String::from_utf8(output.stderr).expect("stderr utf8");
+ assert_eq!(
+ stderr,
+ "ai-memory hook warning: could not parse event payload as JSON; nothing was captured\n"
+ );
+ assert!(!stderr.contains("SENTINEL_PRIVATE_PAYLOAD"));
+ assert!(!tmp.path().join("hook-spool").exists());
+}
diff --git a/docs/windows.md b/docs/windows.md
index 5d21963f..8cf8d8b0 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -275,6 +275,12 @@ large-backlog instances can raise them with whole-minute overrides. Unlike
`AI_MEMORY_HOOK_PLATFORM`, these are read by the hook **at runtime**, so they
apply to the agent's environment (no re-`install-hooks` needed):
+Native hooks accept well-formed JSON with or without one leading UTF-8 BOM, as
+some PowerShell pipelines add that marker when writing to a native process. Any
+other malformed stdin is not spooled or sent; the hook prints a fixed warning
+to stderr, returns `{}` on stdout, and exits successfully so it cannot break the
+host agent. The warning never includes payload contents.
+
| Env var | Built-in default | Max override | What it caps |
|---|---:|---:|---|
| `AI_MEMORY_HOOK_DRAIN_TIMEOUT_MINUTES` | 3 seconds | 60 minutes | each event POST during a drain |