Skip to content

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

Rust

fix(hooks): spool and drain PowerShell capture during outages

AkitaOnRailsadc65423be5e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 09477532..a1869c1f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,8 +18,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
file cap and 7-day spool TTL bounds are unchanged. Also corrected the
stale `hooks/_lib.sh` comment that claimed the backlog is drained at
session boundaries only (a piggyback drain also runs after any
- successful 2xx POST). (#NNN)
-
+ successful 2xx POST). (#1121)
+- Fixed the PowerShell hook bundle silently losing every capture event
+ during a server outage: the `.ps1` path now spools an undeliverable POST
+ (connection failure, timeout, or 5xx) to the same `<data_dir>/hook-spool/`
+ on-disk contract the shell bundle, the native hooks, and
+ `ai-memory hook-drain` share — same `<ms>-<pid>-<seq>.json` entry names,
+ same `SpoolEntry` JSON — and, like `ai_memory_post_hook`, kicks a detached
+ bounded drain (≤64 entries) after the next successful delivery, retires
+ entries on a 2xx or a terminal 4xx, and never spools a routed-repository
+ or externally-owned capture event. The PowerShell POST also mints an
+ idempotency `ingest_key` before its initial attempt and keeps it on the
+ spooled replay, so an ambiguous delivery that committed server-side is
+ discarded on replay instead of double-ingested. (#1122)
## [2.6.0] - 2026-10-07
diff --git a/crates/ai-memory-hooks/tests/suite/mod.rs b/crates/ai-memory-hooks/tests/suite/mod.rs
index 24cb3789..125c4a8d 100644
--- a/crates/ai-memory-hooks/tests/suite/mod.rs
+++ b/crates/ai-memory-hooks/tests/suite/mod.rs
@@ -5,4 +5,5 @@
mod powershell_home;
mod powershell_marker_aliases;
mod powershell_server_routed;
+mod powershell_spool;
mod powershell_utf8;
diff --git a/crates/ai-memory-hooks/tests/suite/powershell_spool.rs b/crates/ai-memory-hooks/tests/suite/powershell_spool.rs
new file mode 100644
index 00000000..526f863e
--- /dev/null
+++ b/crates/ai-memory-hooks/tests/suite/powershell_spool.rs
@@ -0,0 +1,294 @@
+//! Windows PowerShell offline-spool regression tests: the `.ps1` bundle
+//! must survive a server outage the way the shell bundle and the native
+//! hooks do (#580 parity) — spool an undeliverable event in the shared
+//! `hook-spool` on-disk contract, and drain the backlog (retiring on 2xx
+//! or terminal 4xx, keeping it on connection failure).
+
+#![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};
+
+use ai_memory_test_support::powershell_exe;
+
+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 hook_lib() -> String {
+ repo_root()
+ .join("hooks")
+ .join("lib")
+ .join("ai-memory-hook.ps1")
+ .to_string_lossy()
+ .replace('\'', "''")
+}
+
+fn header_end(bytes: &[u8]) -> Option<usize> {
+ bytes.windows(4).position(|window| window == b"\r\n\r\n")
+}
+
+/// Read one full HTTP request and answer it with `response`. A cold
+/// PowerShell start on a loaded windows-latest runner can take well over
+/// ten seconds before opening a connection, so the accept window only
+/// bounds failure detection (same posture as `powershell_utf8.rs`).
+fn serve_one(listener: &TcpListener, response: &[u8]) -> (String, Vec<u8>) {
+ listener.set_nonblocking(true).unwrap();
+ let deadline = Instant::now() + Duration::from_secs(60);
+ 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 drain never connected"
+ );
+ thread::sleep(Duration::from_millis(10));
+ }
+ Err(error) => panic!("mock drain 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 drain request");
+ assert!(read > 0, "drain 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("drain 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 drain request body");
+ assert!(read > 0, "drain request body ended early");
+ request.extend_from_slice(&chunk[..read]);
+ }
+
+ stream.write_all(response).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)
+}
+
+/// Run a PowerShell program with HOME/USERPROFILE and the data dir pinned
+/// inside `home`, returning the process output.
+fn run_powershell(program: &str, home: &Path, envs: &[(&str, &str)]) -> std::process::Output {
+ let mut command = Command::new(powershell_exe());
+ command
+ .args([
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-Command",
+ program,
+ ])
+ .env("HOME", home)
+ .env("USERPROFILE", home)
+ .env_remove("AI_MEMORY_AUTH_TOKEN")
+ .env_remove("AI_MEMORY_HOOK_URL")
+ .env_remove("AI_MEMORY_SESSION_ID")
+ .env_remove("AI_MEMORY_CAPTURE_OWNER");
+ for (key, value) in envs {
+ command.env(key, value);
+ }
+ command.output().expect("run PowerShell")
+}
+
+fn spool_files(data_dir: &Path) -> Vec<PathBuf> {
+ let mut files: Vec<PathBuf> = std::fs::read_dir(data_dir.join("hook-spool"))
+ .expect("spool dir should exist")
+ .map(|entry| entry.unwrap().path())
+ .filter(|path| {
+ path.extension()
+ .is_some_and(|extension| extension == "json")
+ })
+ .collect();
+ files.sort();
+ files
+}
+
+#[test]
+fn powershell_hook_spools_when_server_unreachable() {
+ // A port that nothing listens on: connection refused, immediately.
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let server = format!("http://{}", listener.local_addr().unwrap());
+ drop(listener);
+
+ let home = tempfile::tempdir().unwrap();
+ let data_dir = home.path().join("data");
+ let payload = r#"{"session_id":"ps-spool-regression","prompt":"outage capture"}"#;
+ let program = format!(
+ ". '{lib}'; function Read-AiMemoryStdin {{ $env:AI_MEMORY_TEST_PAYLOAD }}; \
+ Invoke-AiMemoryHook -Event 'user-prompt' -Agent 'codex'",
+ lib = hook_lib()
+ );
+ let output = run_powershell(
+ &program,
+ home.path(),
+ &[
+ ("AI_MEMORY_HOOK_URL", server.as_str()),
+ ("AI_MEMORY_TEST_PAYLOAD", payload),
+ ("AI_MEMORY_DATA_DIR", data_dir.to_str().unwrap()),
+ ],
+ );
+ assert!(
+ output.status.success(),
+ "PowerShell hook failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ output.stdout.is_empty(),
+ "hook must keep stdout empty on this path: {}",
+ String::from_utf8_lossy(&output.stdout)
+ );
+
+ let files = spool_files(&data_dir);
+ assert_eq!(files.len(), 1, "one spool entry after a refused POST");
+ let name = files[0].file_name().unwrap().to_string_lossy().to_string();
+ assert!(
+ name.len() == "0000000000000-0-0000000000000000.json".len()
+ && name
+ .split('-')
+ .next()
+ .is_some_and(|stamp| stamp.len() == 13 && stamp.bytes().all(|b| b.is_ascii_digit()))
+ && name.ends_with(".json"),
+ "entry name follows <ms:013>-<pid>-<seq:x016>: {name}"
+ );
+
+ let raw = std::fs::read(&files[0]).unwrap();
+ assert!(
+ raw.first() != Some(&0xEF),
+ "entry must be UTF-8 without a BOM for the native drainer"
+ );
+ let entry: serde_json::Value = serde_json::from_slice(&raw).unwrap();
+ let url = entry["url"].as_str().unwrap();
+ assert!(
+ url.contains("/hook?event=user-prompt&agent=codex") && url.contains("&ingest_key=ps"),
+ "spooled url carries the event/agent query and an idempotency key: {url}"
+ );
+ assert!(
+ url.starts_with(&server),
+ "spooled url points at the attempted server: {url} vs {server}"
+ );
+ assert_eq!(entry["body"].as_str(), Some(payload));
+ assert_eq!(entry["auth_mode"].as_str(), Some("none"));
+ assert_eq!(entry["attempts"].as_u64(), Some(0));
+ assert!(
+ entry.get("token").is_none() || entry["token"].is_null(),
+ "no token stored when the hook had none"
+ );
+}
+
+#[test]
+fn powershell_drain_delivers_and_retires_entries() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let server = format!("http://{}", listener.local_addr().unwrap());
+ let receiver = thread::spawn(move || {
+ // 202 retires the first entry; a terminal 400 retires the second
+ // (permanent rejection, not retried).
+ let (headers1, body1) = serve_one(
+ &listener,
+ b"HTTP/1.1 202 Accepted\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ );
+ let (headers2, body2) = serve_one(
+ &listener,
+ b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ );
+ (headers1, body1, headers2, body2)
+ });
+
+ let home = tempfile::tempdir().unwrap();
+ let data_dir = home.path().join("data");
+ let spool = data_dir.join("hook-spool");
+ std::fs::create_dir_all(&spool).unwrap();
+ let body_one = r#"{"e":"backlog-one"}"#;
+ let body_two = r#"{"e":"backlog-two"}"#;
+ // Entry one carries a static bearer (the shape the shell bundle and the
+ // native hooks write); entry two is anonymous.
+ std::fs::write(
+ spool.join("0000000000005-1-0000000000000001.json"),
+ serde_json::json!({
+ "url": format!("{server}/hook?event=stop&agent=codex&ingest_key=psaaaaaaaaaaaaaaaa"),
+ "body": body_one,
+ "created_ms": 5_u64,
+ "auth_mode": "static",
+ "token": "drain-bearer",
+ "attempts": 0,
+ })
+ .to_string(),
+ )
+ .unwrap();
+ std::fs::write(
+ spool.join("0000000000006-1-0000000000000002.json"),
+ serde_json::json!({
+ "url": format!("{server}/hook?event=stop&agent=codex&ingest_key=psbbbbbbbbbbbbbbbb"),
+ "body": body_two,
+ "created_ms": 6_u64,
+ "auth_mode": "none",
+ "attempts": 0,
+ })
+ .to_string(),
+ )
+ .unwrap();
+
+ let program = format!(
+ ". '{lib}'; Invoke-AiMemoryDrainSpool -Max 8",
+ lib = hook_lib()
+ );
+ let output = run_powershell(
+ &program,
+ home.path(),
+ &[("AI_MEMORY_DATA_DIR", data_dir.to_str().unwrap())],
+ );
+ assert!(
+ output.status.success(),
+ "PowerShell drain failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let (headers1, body1, headers2, body2) = receiver.join().unwrap();
+ assert!(
+ headers1
+ .lines()
+ .any(|line| line.eq_ignore_ascii_case("Authorization: Bearer drain-bearer")),
+ "first entry's static token must reach the server: {headers1}"
+ );
+ assert_eq!(body1, body_one.as_bytes());
+ assert!(
+ !headers2
+ .lines()
+ .any(|line| line.to_ascii_lowercase().starts_with("authorization:")),
+ "anonymous entry must not send a bearer: {headers2}"
+ );
+ assert_eq!(body2, body_two.as_bytes());
+ assert!(
+ spool_files(&data_dir).is_empty(),
+ "2xx and terminal 4xx both retire their entries"
+ );
+}
diff --git a/docs/install.md b/docs/install.md
index 8c9e5231..24c7e6ad 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -663,17 +663,17 @@ verbatim. Even when that fallback is retained, the server strips any raw field
on receipt before persistence.
Native `ai-memory hook --event ...` commands spool events locally. The POSIX
-shell bundle spools too, but only on failure: it POSTs first and writes the
-event to the same `<data_dir>/hook-spool/` contract when the server is
-unreachable or answers 5xx, then flushes the backlog behind the next delivery
-that succeeds. A 4xx is a permanent rejection and is not retried. (The
-PowerShell bundle still drops an undelivered event.) Session start
+shell bundle and the PowerShell (`.ps1`) bundle spool too, but only on
+failure: they POST first and write the event to the same
+`<data_dir>/hook-spool/` contract when the server is unreachable or answers
+5xx, then flush the backlog behind the next delivery that succeeds. A 4xx
+is a permanent rejection and is not retried. Session start
does a short bounded cleanup drain before fetching a handoff; cancellation-prone
boundary events (`stop`, `pre-compact`, and `session-end`) start a detached
`hook-drain` helper so delivery does not depend on one shutdown hook surviving.
-The POSIX bundle assigns one idempotency key before its initial POST and keeps
-that key if the event enters the spool. A server that processed an event but
-lost the response will not duplicate its observation or completed session-end
+The script bundles assign one idempotency key before their initial POST and
+keep that key if the event enters the spool. A server that processed an event
+but lost the response will not duplicate its observation or completed session-end
effects; if processing stopped after the observation commit, the retry re-runs
downstream work. SessionEnd atomically
commits its end watermark with its automatic handoff; a retry that finds that
diff --git a/docs/windows.md b/docs/windows.md
index 4705e299..98477768 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -533,6 +533,11 @@ native on an i7-6700HQ). Notes:
`ai-memory.exe`, so release binaries and Cargo-built binaries work directly.
- The `.sh`/`.ps1` scripts stay bundled as a fallback — the Docker /
`setup-agent` flow (no local binary) keeps emitting the shell command.
+ For outage parity with the native hooks, both script bundles spool an
+ undeliverable event (connection failure, timeout, 5xx) to the same
+ `<data_dir>/hook-spool/` contract `ai-memory hook-drain` reads, and flush
+ the backlog after the next successful delivery; a terminal 4xx is not
+ retried.
- `AI_MEMORY_HOOK_PLATFORM` accepts five values:
- `windows-native` — Claude exec-form direct binary call (default on native Windows).
- `windows` — PowerShell `-EncodedCommand` + staged `.ps1` script. The native
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index 356e19ee..022c0885 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -673,6 +673,191 @@ function Get-AiMemoryStateDir {
return ".ai-memory"
}
+# --- offline spool -----------------------------------------------------
+# Parity with the shell bundle (`ai_memory_spool_event` /
+# `ai_memory_drain_spool` / `ai_memory_kick_drain` in hooks/_lib.sh): an
+# undelivered event is written to `<state dir>/hook-spool/` in the same
+# on-disk contract `ai-memory hook-drain` reads — same
+# `<ms:013>-<pid>-<seq:016x>.json` file name, same `SpoolEntry` JSON
+# fields, tmp+rename — so the native drainer, the shell bundle, and this
+# bundle consume one another's entries on a shared data dir. A down server
+# then costs latency instead of the event.
+
+function Get-AiMemorySpoolDir {
+ return (Join-Path (Get-AiMemoryStateDir) "hook-spool")
+}
+
+# Best-effort chmod for the pwsh-on-Unix case: the shell and native writers
+# keep the spool 0700/0600 (the spool holds private capture until it
+# drains). `chmod` is absent or a no-op on Windows, where the profile-scoped
+# data dir already restricts access.
+function Set-AiMemoryPrivateMode {
+ param([string] $Path, [string] $Mode)
+ if (Get-Command chmod -ErrorAction SilentlyContinue) {
+ & chmod $Mode $Path 2>$null
+ }
+}
+
+# Persist one undelivered event. Like every capture path here this is
+# best-effort: each failure is swallowed so a hook never fails because of
+# the spool.
+function Write-AiMemorySpoolEvent {
+ param([string] $Url, [string] $Body)
+ try {
+ $dir = Get-AiMemorySpoolDir
+ New-Item -ItemType Directory -Force -Path $dir -ErrorAction Stop | Out-Null
+ Set-AiMemoryPrivateMode -Path $dir -Mode "700"
+ if (-not $script:AiMemorySpoolSeq) { $script:AiMemorySpoolSeq = 0 }
+ $script:AiMemorySpoolSeq = $script:AiMemorySpoolSeq + 1
+ $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
+ # Same name shape as the shell/native writers, so lexical order is
+ # enqueue order for every reader of the directory.
+ $name = "{0:D13}-{1}-{2:x16}.json" -f $now, $PID, $script:AiMemorySpoolSeq
+ $entry = [ordered]@{
+ url = $Url
+ body = $Body
+ created_ms = $now
+ }
+ if ($env:AI_MEMORY_AUTH_TOKEN) {
+ # The credential this hook's own POST would have carried, stored
+ # in the 0600 entry rather than on any command line.
+ $entry["auth_mode"] = "static"
+ $entry["token"] = $env:AI_MEMORY_AUTH_TOKEN
+ } else {
+ $entry["auth_mode"] = "none"
+ }
+ $entry["attempts"] = 0
+ # PS 5.1 escapes a few ASCII characters (`<`, `&`, …) as \uXXXX. The
+ # emitted JSON stays a valid SpoolEntry; the shell drain leaves such
+ # entries to `ai-memory hook-drain` by design, and the native
+ # drainer and ConvertFrom-Json decode them.
+ $json = ConvertTo-Json -InputObject $entry -Compress
+ $tmp = Join-Path $dir "$name.tmp"
+ $final = Join-Path $dir $name
+ # WriteAllText is UTF-8 without a BOM in both engines, which the
+ # native drainer's parser requires.
+ [IO.File]::WriteAllText($tmp, $json)
+ Set-AiMemoryPrivateMode -Path $tmp -Mode "600"
+ Move-Item -Force -Path $tmp -Destination $final -ErrorAction Stop
+ } catch {
+ if ($tmp -and (Test-Path $tmp -ErrorAction SilentlyContinue)) {
+ Remove-Item -Force -LiteralPath $tmp -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+# Deliver the queued backlog, oldest first (name order is enqueue order).
+# Mirrors `ai_memory_drain_spool`: bounded by count so a pass never becomes
+# an unbounded upload, a 2xx or a 4xx retires the entry (delivered, or a
+# permanent rejection that must not be retried), and anything else stops
+# the pass and keeps the remainder for the next one. The per-entry timeout
+# is this bundle's own POST budget. ConvertFrom-Json reads every escape
+# either serializer emits, so entries written by the shell bundle or the
+# native binary drain here too.
+function Invoke-AiMemoryDrainSpool {
+ param([int] $Max = 64)
+ try {
+ $dir = Get-AiMemorySpoolDir
+ if (-not (Test-Path $dir -PathType Container)) { return }
+ # -Filter alone can match 8.3 short names on Windows; the extension
+ # re-check keeps a writer's in-flight `*.json.tmp` out of the pass.
+ $files = @(
+ Get-ChildItem -LiteralPath $dir -Filter "*.json" -File -ErrorAction Stop |
+ Where-Object { $_.Extension -eq ".json" } |
+ Sort-Object Name
+ )
+ } catch {
+ return
+ }
+ $count = 0
+ foreach ($file in $files) {
+ if ($count -ge $Max) { break }
+ $count = $count + 1
+ try {
+ $entry = [IO.File]::ReadAllText($file.FullName) | ConvertFrom-Json -ErrorAction Stop
+ } catch {
+ continue
+ }
+ if (-not $entry.url) { continue }
+ $headers = @{}
+ if ($entry.auth_mode -eq "static" -and $entry.token) {
+ $headers["Authorization"] = "Bearer $($entry.token)"
+ }
+ $code = 0
+ try {
+ Invoke-WebRequest `
+ -UseBasicParsing `
+ -TimeoutSec 3 `
+ -Method Post `
+ -Uri ([string]$entry.url) `
+ -Headers $headers `
+ -ContentType "application/json" `
+ -Body ([Text.Encoding]::UTF8.GetBytes([string]$entry.body)) | Out-Null
+ $code = 200
+ } catch {
+ $response = $_.Exception.Response
+ if ($response) {
+ try { $code = [int]$response.StatusCode } catch { $code = 0 }
+ }
+ }
+ if (($code -ge 200 -and $code -lt 300) -or ($code -ge 400 -and $code -lt 500)) {
+ Remove-Item -Force -LiteralPath $file.FullName -ErrorAction SilentlyContinue
+ } else {
+ break
+ }
+ }
+}
+
+# Piggyback drain: a delivery that just succeeded proves the server is
+# reachable, so flush the backlog behind it — detached, so the agent never
+# waits, and a no-op when nothing is queued (every call on a healthy
+# install).
+#
+# Detach idiom: this bundle had no background-job or Start-Process pattern
+# to copy (each hook script is already its own short-lived process), so the
+# kick re-runs the running engine on this same lib file in drain mode
+# through System.Diagnostics.Process:
+# - CreateNoWindow with UseShellExecute=$false never flashes a console
+# window on Windows and behaves identically under pwsh on Linux/macOS;
+# - RedirectStandardOutput/Error keep the child off THIS hook's stdout
+# pipe — the agent reads that pipe to EOF, and a detached child holding
+# the inherited handle would stall the hook's own completion (the shell
+# bundle's `( ... >/dev/null 2>&1 &)` is that same protection). Drain
+# mode writes nothing, so the unread redirected pipes never fill.
+function Invoke-AiMemoryKickDrain {
+ try {
+ $dir = Get-AiMemorySpoolDir
+ if (-not (Test-Path $dir -PathType Container)) { return }
+ $queued = @(
+ Get-ChildItem -LiteralPath $dir -Filter "*.json" -File -ErrorAction Stop |
+ Where-Object { $_.Extension -eq ".json" } |
+ Select-Object -First 1
+ )
+ if (-not $queued.Count) { return }
+ if (-not $script:AiMemoryLibFile) { return }
+ # Re-invoke the engine already running this hook; fall back to any
+ # PowerShell on PATH if the current process's binary cannot be
+ # resolved.
+ $engine = $null
+ try { $engine = (Get-Process -Id $PID -ErrorAction Stop).Path } catch { }
+ if (-not $engine) {
+ $cmd = Get-Command pwsh -ErrorAction SilentlyContinue
+ if (-not $cmd) { $cmd = Get-Command powershell -ErrorAction SilentlyContinue }
+ if ($cmd) { $engine = $cmd.Source }
+ }
+ if (-not $engine) { return }
+ $startInfo = New-Object System.Diagnostics.ProcessStartInfo
+ $startInfo.FileName = $engine
+ $startInfo.Arguments = '-NoProfile -ExecutionPolicy Bypass -File "{0}" --ai-memory-drain-spool 64' -f $script:AiMemoryLibFile
+ $startInfo.UseShellExecute = $false
+ $startInfo.CreateNoWindow = $true
+ $startInfo.RedirectStandardOutput = $true
+ $startInfo.RedirectStandardError = $true
+ $null = [System.Diagnostics.Process]::Start($startInfo)
+ } catch {
+ }
+}
+
function Get-AiMemorySessionIdPath {
param([string] $Agent)
return (Join-Path (Join-Path (Get-AiMemoryStateDir) "hook-state") "$Agent-session-id")
@@ -833,21 +1018,40 @@ function Invoke-AiMemoryHook {
$Headers["Authorization"] = "Bearer $env:AI_MEMORY_AUTH_TOKEN"
}
- # This POST is the only producer on this path (no spool, no drain here).
- # Session identity and the handoff/briefing GET below are delivery, so an
- # external owner leaves them, and the stdout contract, alone.
+ # Capture producer path, with the shell bundle's offline-spool parity
+ # (hooks/_lib.sh): a 2xx kicks a detached backlog drain, a terminal 4xx
+ # is a permanent rejection and is dropped, and anything undeliverable
+ # (connection failure, timeout, 5xx) is spooled for the drain to retry.
+ # Session identity and the handoff/briefing GET below are delivery, so
+ # an external owner leaves them, and the stdout contract, alone.
if (-not (Test-AiMemoryCaptureOwnedExternally)) {
$BodyBytes = [Text.Encoding]::UTF8.GetBytes($Payload)
+ # The idempotency key is minted before the POST and rides any spooled
+ # replay too, so the server can discard a replay whose original
+ # response was lost after the observation committed — the same
+ # reason the shell bundle mints `ai_memory_ingest_key`. `ps` plus a
+ # GUID's hex fits the server's key grammar.
+ $HookUrl = "$Server/hook?event=$Event&agent=$Agent$QS$SessionQS&ingest_key=ps$([Guid]::NewGuid().ToString('N').Substring(0, 16))"
try {
Invoke-WebRequest `
-UseBasicParsing `
-TimeoutSec 3 `
-Method Post `
- -Uri "$Server/hook?event=$Event&agent=$Agent$QS$SessionQS" `
+ -Uri $HookUrl `
-Headers $Headers `
-ContentType "application/json; charset=utf-8" `
-Body $BodyBytes | Out-Null
+ Invoke-AiMemoryKickDrain
} catch {
+ $Status = 0
+ if ($_.Exception.Response) {
+ try { $Status = [int]$_.Exception.Response.StatusCode } catch { $Status = 0 }
+ }
+ # 4xx = permanent rejection (not retried); everything else that
+ # failed to deliver is spooled.
+ if ($Status -lt 400 -or $Status -ge 500) {
+ Write-AiMemorySpoolEvent -Url $HookUrl -Body $Payload
+ }
}
}
if ($Agent -eq "devin" -and $Event -eq "session-end") {
@@ -990,3 +1194,24 @@ function Invoke-AiMemoryHook {
[Console]::Out.Write("{}")
}
}
+
+# This file's own path, captured at load time: top-level `$PSCommandPath` is
+# the lib's full path whether a hook script dot-sources it or the engine
+# runs it directly in drain mode, so `Invoke-AiMemoryKickDrain`'s child can
+# be pointed back at exactly this file.
+$script:AiMemoryLibFile = $PSCommandPath
+
+# Detached-drain entry mode: `Invoke-AiMemoryKickDrain` re-runs this file as
+# `powershell -NoProfile -ExecutionPolicy Bypass -File <lib>
+# --ai-memory-drain-spool <max>`. The bespoke token cannot arrive from an
+# agent (hook input is stdin JSON, and dot-sourcing passes no arguments),
+# and this mode prints nothing and always exits 0, so a redirected detached
+# child can never pollute or stall a hook's stdout.
+if ($args -contains "--ai-memory-drain-spool") {
+ $AiMemoryDrainMax = 64
+ foreach ($AiMemoryArg in $args) {
+ if ($AiMemoryArg -match '^[0-9]+$') { $AiMemoryDrainMax = [int]$AiMemoryArg }
+ }
+ $null = Invoke-AiMemoryDrainSpool -Max $AiMemoryDrainMax
+ exit 0
+}
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index 38c902fd..6d333462 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -640,6 +640,43 @@ assert_eq "post_hook spools an undelivered event" "1" \
unset AI_MEMORY_DATA_DIR
+# --- PowerShell bundle spool parity (static) ---------------------------
+# The PS lib shares this offline-spool contract (same <data>/hook-spool
+# dir, same entry writer, same dispatch as `ai_memory_post_hook`: 2xx kicks
+# a detached drain, a terminal 4xx is dropped, everything undeliverable is
+# spooled), so a Windows script install loses no events during a server
+# outage either (#580 parity). Static first — no pwsh needed — then a
+# behavioral probe where pwsh exists.
+PS_LIB="$(dirname "$0")/../../hooks/lib/ai-memory-hook.ps1"
+PS_SPOOL_STATIC=$(grep -q 'function Write-AiMemorySpoolEvent' "$PS_LIB" \
+ && grep -q 'function Invoke-AiMemoryDrainSpool' "$PS_LIB" \
+ && grep -q 'function Invoke-AiMemoryKickDrain' "$PS_LIB" \
+ && grep -Fq '"hook-spool"' "$PS_LIB" \
+ && grep -Fq '"{0:D13}-{1}-{2:x16}.json"' "$PS_LIB" \
+ && grep -Fq '"auth_mode"' "$PS_LIB" \
+ && grep -Fq 'Write-AiMemorySpoolEvent -Url' "$PS_LIB" \
+ && grep -Fq 'Invoke-AiMemoryKickDrain' "$PS_LIB" \
+ && grep -Fq 'if ($Status -lt 400 -or $Status -ge 500) {' "$PS_LIB" \
+ && grep -Fq -- '--ai-memory-drain-spool' "$PS_LIB" \
+ && grep -Fq '$script:AiMemoryLibFile = $PSCommandPath' "$PS_LIB" \
+ && grep -Fq 'RedirectStandardOutput' "$PS_LIB" \
+ && printf ok || printf bad)
+assert_eq "powershell bundle spools undelivered events (static)" "ok" "$PS_SPOOL_STATIC"
+# The ingest key must ride the initial POST too, or an ambiguous delivery
+# and its spooled replay could double-ingest (the reason the shell bundle
+# mints `ai_memory_ingest_key` before the first POST).
+PS_KEY_STATIC=$(grep -Fq '&ingest_key=ps$(' "$PS_LIB" \
+ && printf ok || printf bad)
+assert_eq "powershell POST and spool replay share an ingest key (static)" "ok" "$PS_KEY_STATIC"
+
+if command -v pwsh >/dev/null 2>&1; then
+ PS_SPOOL_OUT=$(pwsh -NoProfile -File "$(dirname "$0")/test_spool_ps.ps1" "$(host_path "$PS_LIB")" 2>&1) \
+ && PASS=$((PASS + $(printf '%s\n' "$PS_SPOOL_OUT" | sed -n 's/.*checks=\([0-9]*\).*/\1/p') )) \
+ || { FAIL=$((FAIL + 1)); printf ' FAIL powershell spool behavioral probe\n%s\n' "$PS_SPOOL_OUT"; }
+else
+ printf ' skip powershell spool behavioral probe (pwsh unavailable)\n'
+fi
+
# --- external capture ownership (AI_MEMORY_CAPTURE_OWNER) -------------
# A wrapper, extension or managed launcher that already produces this
# session's capture events announces itself with AI_MEMORY_CAPTURE_OWNER.
diff --git a/tests/hooks/test_spool_ps.ps1 b/tests/hooks/test_spool_ps.ps1
new file mode 100644
index 00000000..e12f2775
--- /dev/null
+++ b/tests/hooks/test_spool_ps.ps1
@@ -0,0 +1,69 @@
+# Behavioral evidence for the PowerShell bundle's offline spool: the
+# entry writer's on-disk contract (file name, SpoolEntry fields, no BOM,
+# token handling) and a refused-connection drain pass that keeps the
+# backlog. Pure functions plus a connection-refused loopback POST — no
+# live server. 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 "spool ps probe failed: $label" }
+}
+
+$root = Join-Path ([IO.Path]::GetTempPath()) ("am-spool-" + [Guid]::NewGuid().ToString("N"))
+New-Item -ItemType Directory -Force -Path $root | Out-Null
+$env:AI_MEMORY_DATA_DIR = (Join-Path $root "data")
+# Port 1 is reserved and never listens: connection refused, immediately.
+$RefusedUrl = "http://127.0.0.1:1/hook?event=stop&agent=codex&ingest_key=ps0123456789abcdef"
+
+# 1. The lib captured its own path so the detached drain child can be
+# pointed back at this exact file.
+Assert-True ($script:AiMemoryLibFile -and ((Split-Path $script:AiMemoryLibFile -Leaf) -eq "ai-memory-hook.ps1")) "lib path captured"
+
+# 2. An undelivered event lands in <data>/hook-spool with the shared name
+# shape and entry fields.
+Write-AiMemorySpoolEvent -Url $RefusedUrl -Body '{"e":"outage"}'
+$dir = Get-AiMemorySpoolDir
+$files = @(Get-ChildItem -LiteralPath $dir -Filter "*.json" -File)
+Assert-True ($files.Count -eq 1) "one entry written"
+Assert-True ($files[0].Name -match '^[0-9]{13}-[0-9]+-[0-9a-f]{16}\.json$') "entry name is <ms>-<pid>-<seq>"
+$bytes = [IO.File]::ReadAllBytes($files[0].FullName)
+Assert-True ($bytes.Length -gt 1 -and $bytes[0] -ne 0xEF) "entry has no UTF-8 BOM"
+$entry = [Text.Encoding]::UTF8.GetString($bytes) | ConvertFrom-Json
+Assert-True ($entry.url -eq $RefusedUrl) "url round-trips"
+Assert-True ($entry.body -eq '{"e":"outage"}') "body round-trips"
+Assert-True ($entry.created_ms -ge 1000000000000) "created_ms is unix milliseconds"
+Assert-True ($entry.auth_mode -eq "none") "no token means auth_mode none"
+Assert-True ($null -eq $entry.token) "no token field when auth_mode is none"
+Assert-True ($entry.attempts -eq 0) "attempts starts at 0"
+
+# 3. The auth token rides the entry when set.
+$env:AI_MEMORY_AUTH_TOKEN = "probe-bearer"
+Write-AiMemorySpoolEvent -Url $RefusedUrl -Body '{"e":"auth"}'
+$tokenEntry = Get-ChildItem -LiteralPath $dir -Filter "*.json" -File | Sort-Object Name | Select-Object -Last 1
+$tokenParsed = [IO.File]::ReadAllText($tokenEntry.FullName) | ConvertFrom-Json
+Assert-True ($tokenParsed.auth_mode -eq "static") "token entry is static auth"
+Assert-True ($tokenParsed.token -eq "probe-bearer") "token round-trips"
+Remove-Item Env:\AI_MEMORY_AUTH_TOKEN -ErrorAction SilentlyContinue
+
+# 4. Two entries in the same process get distinct, ordered names.
+$names = @(Get-ChildItem -LiteralPath $dir -Filter "*.json" -File | Sort-Object Name | ForEach-Object { $_.Name })
+Assert-True ($names.Count -eq 2 -and $names[0] -cne $names[1]) "entry names are unique per write"
+
+# 5. A drain pass against a refused connection keeps every entry (the
+# 000/5xx "stop the pass, keep the remainder" semantics).
+Invoke-AiMemoryDrainSpool -Max 8
+$kept = @(Get-ChildItem -LiteralPath $dir -Filter "*.json" -File)
+Assert-True ($kept.Count -eq 2) "refused connection keeps the backlog"
+
+# 6. A missing spool directory is a no-op, not an error.
+Remove-Item -Recurse -Force (Join-Path $root "data")
+Invoke-AiMemoryDrainSpool -Max 8
+
+Remove-Item -Recurse -Force $root -ErrorAction SilentlyContinue
+Write-Output "spool ps behavioral probe: ok checks=15"
+exit 0