Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): post PowerShell JSON as UTF-8 (#504)
YANGYUae9c1ae5298e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 47b2bf1e..079975cd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,28 +7,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]-### Fixed### Added- Generated `sessions/<id>.md` pages now surface the originating harness as`agent` frontmatter alongside `session_id`. The value comes from thepersisted session row, so LLM rewrites, compaction checkpoints, spooldrains, and superseding versions do not mistake the later writer for theorigin; manual page writes remain unattributed. (#494)++### Fixed+- Made managed routing `SKILL.md` payloads byte-identical across release+ platforms. Windows builds previously embedded CRLF from the runner checkout+ while Linux and macOS builds embedded LF, so one tag returned different+ bytes through CLI installs and `memory_install_self_routing`. The embedded+ assets now use LF everywhere without rewriting user-authored files. (#502)- PowerShell compatibility hooks no longer assign to a local `$home` variable.PowerShell names are case-insensitive, so that collided with the automaticread-only `$HOME` variable and emitted `VariableNotWritable` for every hookpayload carrying a cwd. The marker-boundary helper now uses `$userHome`, withnative Windows and static shell regressions covering the error stream andreserved-name contract (#498).+- PowerShell compatibility hooks now encode JSON request bodies as explicit+ UTF-8 bytes and declare `charset=utf-8`. Windows PowerShell 5.1 otherwise+ encoded string bodies using a host-dependent legacy code page, so prompts,+ paths, or tool content containing non-ASCII text could make `/hook` return+ HTTP 400 and disappear from memory while ASCII events still worked. A native+ Windows loopback test now round-trips Chinese and Portuguese text byte for+ byte (#500).## [1.32.2] - 2026-08-26### Fixed-- Made managed routing `SKILL.md` payloads byte-identical across release- platforms. Windows builds previously embedded CRLF from the runner checkout- while Linux and macOS builds embedded LF, so one tag returned different- bytes through CLI installs and `memory_install_self_routing`. The embedded- assets now use LF everywhere without rewriting user-authored files. (#502)- The native client now trusts CAs from the platform trust store. It was builtwith reqwest's `rustls-tls`, which bundles the Mozilla webpki roots andignores the OS store, so a CA the operator had installed locally — Caddy's@@ -41,7 +49,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0Switched to `rustls-tls-native-roots`; the runtime image installs`ca-certificates`, so the server path keeps a populated store. Reported by@alanmatiasdev (#492).-- Made `hook-drain` say what a pass actually did. The drain already returned`sent`/`remaining`/`dropped` counts and `run_drain` discarded all three, sothree passes that mean opposite things — everything delivered, every queued@@ -77,8 +84,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0327 keeping a real title. `looks_like_scaffolding` is re-exported from`ai-memory-core`, so its narrowing is a public-API behaviour change eventhough `derive_title` is its only caller in tree. (#484)--### Docs- Documented why registering ai-memory through Kimi Code's own`kimi mcp add` breaks every model turn: that command writes the plain`/mcp` URL with no `?flavor=moonshot`, so Moonshot rejectsdiff --git a/crates/ai-memory-hooks/tests/powershell_utf8.rs b/crates/ai-memory-hooks/tests/powershell_utf8.rsnew file mode 100644index 00000000..3a92e7f6--- /dev/null+++ b/crates/ai-memory-hooks/tests/powershell_utf8.rs@@ -0,0 +1,130 @@+//! Windows PowerShell compatibility-hook transport regression tests.++#![cfg(windows)]++use std::io::{Read as _, Write as _};+use std::net::TcpListener;+use std::path::{Path, PathBuf};+use std::process::Command;+use std::thread;+use std::time::{Duration, Instant};++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 header_end(bytes: &[u8]) -> Option<usize> {+ bytes.windows(4).position(|window| window == b"\r\n\r\n")+}++fn receive_one_request(listener: TcpListener) -> (String, Vec<u8>) {+ listener.set_nonblocking(true).unwrap();+ let deadline = Instant::now() + Duration::from_secs(10);+ let (mut stream, _) = loop {+ match listener.accept() {+ Ok(connection) => break connection,+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ assert!(Instant::now() < deadline, "PowerShell hook never connected");+ thread::sleep(Duration::from_millis(10));+ }+ Err(error) => panic!("mock hook server accept failed: {error}"),+ }+ };+ stream.set_nonblocking(false).unwrap();+ stream+ .set_read_timeout(Some(Duration::from_secs(10)))+ .unwrap();++ let mut request = Vec::new();+ let (body_start, body_len) = loop {+ let mut chunk = [0_u8; 4096];+ let read = stream.read(&mut chunk).expect("read hook request");+ assert!(read > 0, "hook request ended before its headers");+ request.extend_from_slice(&chunk[..read]);+ if let Some(end) = header_end(&request) {+ let headers = String::from_utf8_lossy(&request[..end]);+ let len = headers+ .lines()+ .find_map(|line| {+ let (name, value) = line.split_once(':')?;+ name.eq_ignore_ascii_case("content-length")+ .then(|| value.trim().parse::<usize>().ok())+ .flatten()+ })+ .expect("PowerShell request should carry Content-Length");+ break (end + 4, len);+ }+ };+ while request.len() < body_start + body_len {+ let mut chunk = [0_u8; 4096];+ let read = stream.read(&mut chunk).expect("read hook request body");+ assert!(read > 0, "hook request body ended early");+ request.extend_from_slice(&chunk[..read]);+ }++ stream+ .write_all(b"HTTP/1.1 202 Accepted\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")+ .unwrap();+ let headers = String::from_utf8(request[..body_start - 4].to_vec()).unwrap();+ let body = request[body_start..body_start + body_len].to_vec();+ (headers, body)+}++#[test]+fn powershell_hook_posts_json_as_utf8_bytes() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let server = format!("http://{}", listener.local_addr().unwrap());+ let receiver = thread::spawn(move || receive_one_request(listener));++ let payload = serde_json::json!({+ "session_id": "utf8-regression",+ "prompt": "中文记忆测试:行动完成 — Validação: não, memória, correção, ação"+ })+ .to_string();+ let script = repo_root()+ .join("hooks")+ .join("lib")+ .join("ai-memory-hook.ps1");+ let script = script.to_string_lossy().replace('\'', "''");+ let program = format!(+ ". '{script}'; function Read-AiMemoryStdin {{ $env:AI_MEMORY_TEST_PAYLOAD }}; \+ Invoke-AiMemoryHook -Event 'user-prompt' -Agent 'codex'"+ );+ let output = Command::new("powershell.exe")+ .args([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-ExecutionPolicy",+ "Bypass",+ "-Command",+ &program,+ ])+ .env("AI_MEMORY_HOOK_URL", server)+ .env("AI_MEMORY_TEST_PAYLOAD", &payload)+ .output()+ .expect("run PowerShell hook");+ assert!(+ output.status.success(),+ "PowerShell hook failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let (headers, body) = receiver.join().unwrap();+ assert!(+ headers+ .lines()+ .any(|line| line.eq_ignore_ascii_case("Content-Type: application/json; charset=utf-8")),+ "request did not declare UTF-8 JSON: {headers}"+ );+ assert_eq!(body, payload.as_bytes());+ let parsed: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(+ parsed["prompt"],+ "中文记忆测试:行动完成 — Validação: não, memória, correção, ação"+ );+}diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index 195319ab..f818c861 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -324,6 +324,7 @@ function Invoke-AiMemoryHook {$Headers["Authorization"] = "Bearer $env:AI_MEMORY_AUTH_TOKEN"}+ $BodyBytes = [Text.Encoding]::UTF8.GetBytes($Payload)try {Invoke-WebRequest `-UseBasicParsing `@@ -331,8 +332,8 @@ function Invoke-AiMemoryHook {-Method Post `-Uri "$Server/hook?event=$Event&agent=$Agent$QS$SessionQS" `-Headers $Headers `- -ContentType "application/json" `- -Body $Payload | Out-Null+ -ContentType "application/json; charset=utf-8" `+ -Body $BodyBytes | Out-Null} catch {}if ($Agent -eq "devin" -and $Event -eq "session-end") {diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex ab26b564..9f06260d 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -144,6 +144,11 @@ PS_ANTIGRAVITY_STATIC=$(grep -q 'function Test-AiMemoryAntigravityInitialInvocat&& printf 'ok' || printf 'missing')assert_eq "powershell antigravity hook has invocation guard" "ok" "$PS_ANTIGRAVITY_STATIC"+PS_UTF8_STATIC=$(grep -Fq '$BodyBytes = [Text.Encoding]::UTF8.GetBytes($Payload)' hooks/lib/ai-memory-hook.ps1 \+ && grep -Fq 'application/json; charset=utf-8' hooks/lib/ai-memory-hook.ps1 \+ && grep -Fq -- '-Body $BodyBytes' hooks/lib/ai-memory-hook.ps1 \+ && printf 'ok' || printf 'missing')+assert_eq "powershell hook posts explicit UTF-8 JSON bytes" "ok" "$PS_UTF8_STATIC"PS_HOME_STATIC=$(grep -Fq '$userHome = if ($env:HOME)' hooks/lib/ai-memory-hook.ps1 \&& ! grep -Eq '\$home[[:space:]]*=' hooks/lib/ai-memory-hook.ps1 \&& printf 'ok' || printf 'missing')