Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hooks): strip raw assistant-message before spool and wire (#196)
Samir Hanna Verzafe404c0ed73c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 312ab7c4..74a71e16 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0model now selects the documented recommended defaults, `claude-haiku-4-5`and `gpt-5.4-mini`, instead of the older `claude-sonnet-4-6` and`gpt-4o-mini` fallbacks. Explicit `AI_MEMORY_LLM_MODEL` values are unchanged.+- The native hook binary now drops any raw assistant-message field (Claude+ Code's `last_assistant_message` on `Stop`) before it can reach the local+ spool or the wire, and drains pre-existing spooled entries with the field+ stripped too. The server applies the same strip defensively on `/hook` and+ `/hook/batch` before building an envelope. This field was already never+ persisted, so there is no behavior change; it closes a raw-text exposure in+ the spool/wire ahead of the opt-in assistant/Stop capture landing in a later+ release. Upgrading the binary is sufficient for native Claude Code installs;+ script-fallback installs (Docker wrapper, `AI_MEMORY_HOOK_PLATFORM=posix`)+ should run `ai-memory install-hooks --agent claude-code --apply` to migrate to+ native commands and close the residual local-wire vector ([#196]).### Fixed- User-facing help and current-reference documentation now match the shippeddiff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex e7870571..3ff27b9f 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -315,6 +315,16 @@ wherereturn Ok(());}};+ // Defensively drop any raw assistant-message field (e.g. Claude Code's+ // `last_assistant_message` on Stop) BEFORE it can reach the local spool or+ // the wire (#196). The explicit opt-in capture path lands in a later PR;+ // today this field is never persisted, so stripping it pre-spool closes a+ // raw-text exposure with no behavior change. Reserialize only when we+ // actually removed something, so unrelated events keep byte-exact spool+ // bodies (see `native_hook_accepts_plain_and_bom_prefixed_json`).+ if ai_memory_hooks::strip_assistant_message_raw(&mut json) {+ payload = serde_json::to_string(&json)?;+ }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);diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rsindex e9e04a9e..a2f6e4af 100644--- a/crates/ai-memory-cli/src/commands/hook_spool.rs+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs@@ -120,7 +120,7 @@ fn now_ms() -> u64 {/// # Errors/// Returns an error only when the spool file cannot be written.pub fn enqueue(spool: &Path, entry: &SpoolEntry) -> std::io::Result<()> {- std::fs::create_dir_all(spool)?;+ create_spool_dir(spool)?;let seq = ENQUEUE_SEQ.fetch_add(1, Ordering::Relaxed);let name = format!("{:013}-{}-{seq:016x}.json",@@ -136,6 +136,41 @@ pub fn enqueue(spool: &Path, entry: &SpoolEntry) -> std::io::Result<()> {Ok(())}+/// Create the spool directory `0700` on Unix so the excerpt bodies that reside+/// there (up to `MAX_AGE_MS`) — and even the timestamp+pid metadata in the file+/// names — are only reachable by the owner (#196). The spool holds private+/// capture until it drains; a world-readable directory would leak that. On+/// non-Unix the mode is a no-op (falls back to `create_dir_all`). Idempotent:+/// an existing directory's mode is left untouched (never widened, never+/// narrowed) to avoid churning a path an operator may have set deliberately.+fn create_spool_dir(spool: &Path) -> std::io::Result<()> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::DirBuilderExt as _;+ if spool.is_dir() {+ return Ok(());+ }+ match std::fs::DirBuilder::new()+ .recursive(true)+ .mode(0o700)+ .create(spool)+ {+ Ok(()) => Ok(()),+ // A concurrent drainer/enqueue may have created it between the check+ // and the call; treat an existing directory as success.+ Err(e) if spool.is_dir() => {+ let _ = e;+ Ok(())+ }+ Err(e) => Err(e),+ }+ }+ #[cfg(not(unix))]+ {+ std::fs::create_dir_all(spool)+ }+}+fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {use std::io::Write as _;let mut opts = std::fs::OpenOptions::new();@@ -624,7 +659,7 @@ fn load_live_entry(path: &Path, result: &mut DrainResult) -> Option<SpoolEntry>result.remaining += 1;return None;};- let Ok(entry) = serde_json::from_slice::<SpoolEntry>(&bytes) else {+ let Ok(mut entry) = serde_json::from_slice::<SpoolEntry>(&bytes) else {// Unparseable spool file: drop it so it can't wedge the queue.let _ = std::fs::remove_file(path);result.dropped += 1;@@ -635,9 +670,29 @@ fn load_live_entry(path: &Path, result: &mut DrainResult) -> Option<SpoolEntry>result.dropped += 1;return None;}+ // Backstop for entries spooled by a pre-#196 binary: strip any raw+ // assistant-message field before this entry can reach either drain path+ // (`/hook/batch` chunk or the per-event fallback). Loading is the single+ // choke point both paths pass through, so one strip here covers both.+ strip_assistant_from_entry(&mut entry);Some(entry)}+/// Drop any raw assistant-message field (#196) from a spooled entry's body.+/// Reserializes only when the field was actually present, so untouched entries+/// keep byte-exact bodies. A body that no longer parses is left as-is; the+/// downstream `body_is_malformed` check already drops/retries it.+fn strip_assistant_from_entry(entry: &mut SpoolEntry) {+ let Ok(mut body) = serde_json::from_str::<serde_json::Value>(&entry.body) else {+ return;+ };+ if ai_memory_hooks::strip_assistant_message_raw(&mut body)+ && let Ok(reserialized) = serde_json::to_string(&body)+ {+ entry.body = reserialized;+ }+}+fn body_is_malformed(entry: &SpoolEntry) -> bool {serde_json::from_str::<serde_json::Value>(&entry.body).is_err()}@@ -832,6 +887,76 @@ mod tests {assert_eq!(loaded.token.as_deref(), Some("tok"));}+ #[test]+ fn load_live_entry_strips_legacy_assistant_message() {+ // Simulate a spool entry written by a pre-#196 binary: the raw body+ // still carries `last_assistant_message`. Loading it for a drain must+ // strip the field so neither drain path (batch or per-event fallback)+ // can put it on the wire.+ let tmp = tempfile::tempdir().unwrap();+ let spool = spool_dir(tmp.path());+ let dirty = entry_for(+ "https://x/hook?event=stop&agent=claude-code".into(),+ r#"{"session_id":"legacy","last_assistant_message":"SENTINEL_ASSISTANT_MESSAGE"}"#+ .into(),+ None,+ false,+ );+ enqueue(&spool, &dirty).unwrap();+ let path = list_entries(&spool).unwrap().into_iter().next().unwrap();++ let mut result = DrainResult::default();+ let loaded = load_live_entry(&path, &mut result).expect("entry is live");+ assert!(+ !loaded.body.contains("SENTINEL_ASSISTANT_MESSAGE"),+ "drain load left the assistant message in the body: {}",+ loaded.body+ );+ assert!(+ !loaded.body.contains("last_assistant_message"),+ "drain load left the raw field key in the body: {}",+ loaded.body+ );+ assert!(+ loaded.body.contains("legacy"),+ "unrelated field was dropped"+ );+ }++ #[test]+ fn load_live_entry_keeps_clean_body_byte_exact() {+ // An entry with no assistant field must not be reserialized (its bytes+ // are preserved), so the strip never churns unrelated events.+ let tmp = tempfile::tempdir().unwrap();+ let spool = spool_dir(tmp.path());+ let body = r#"{"session_id":"s","prompt":"hi"}"#;+ let clean = entry_for(+ "https://x/hook?event=user-prompt-submit&agent=claude-code".into(),+ body.into(),+ None,+ false,+ );+ enqueue(&spool, &clean).unwrap();+ let path = list_entries(&spool).unwrap().into_iter().next().unwrap();++ let mut result = DrainResult::default();+ let loaded = load_live_entry(&path, &mut result).expect("entry is live");+ assert_eq!(loaded.body, body, "clean body must stay byte-exact");+ }++ #[cfg(unix)]+ #[test]+ fn enqueue_creates_spool_dir_private() {+ use std::os::unix::fs::PermissionsExt as _;+ let tmp = tempfile::tempdir().unwrap();+ // A nested path that does not exist yet, so `create_spool_dir` builds it.+ let spool = tmp.path().join("nested").join("hook-spool");+ let entry = entry_for("https://x/hook".into(), "{}".into(), None, false);+ enqueue(&spool, &entry).unwrap();+ let mode = std::fs::metadata(&spool).unwrap().permissions().mode() & 0o777;+ assert_eq!(mode, 0o700, "spool dir must be owner-only");+ }+#[test]fn enqueue_names_are_unique_in_tight_loop() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/tests/hook_payload.rs b/crates/ai-memory-cli/tests/hook_payload.rsindex a199548b..023aa3f4 100644--- a/crates/ai-memory-cli/tests/hook_payload.rs+++ b/crates/ai-memory-cli/tests/hook_payload.rs@@ -9,13 +9,17 @@ fn bin() -> &'static str {}fn run_hook(data_dir: &Path, payload: &[u8]) -> Output {+ run_hook_event(data_dir, "pre-tool-use", payload)+}++fn run_hook_event(data_dir: &Path, event: &str, payload: &[u8]) -> Output {let mut child = Command::new(bin()).args(["--data-dir"]).arg(data_dir).args(["hook","--event",- "pre-tool-use",+ event,"--agent","claude-code","--server-url",@@ -90,3 +94,65 @@ fn malformed_native_hook_payload_warns_without_leaking_or_spooling() {assert!(!stderr.contains("SENTINEL_PRIVATE_PAYLOAD"));assert!(!tmp.path().join("hook-spool").exists());}++#[test]+fn stop_hook_strips_last_assistant_message_from_spool_and_stderr() {+ // A well-formed Stop payload carrying Claude Code's `last_assistant_message`+ // must be spooled WITHOUT that raw field (#196): the opt-in capture path+ // lands later; until then the field never reaches spool, wire, or stderr.+ let tmp = tempfile::tempdir().expect("tempdir");+ let payload = br#"{"session_id":"stop-strip","cwd":"/tmp/project","last_assistant_message":"SENTINEL_ASSISTANT_MESSAGE"}"#;++ let output = run_hook_event(tmp.path(), "stop", payload);+ assert!(output.status.success());+ assert_eq!(output.stdout, b"{}\n");+ assert!(+ output.stderr.is_empty(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let body = spooled_body(tmp.path());+ assert!(+ !body.contains("SENTINEL_ASSISTANT_MESSAGE"),+ "spooled body still carries the assistant message: {body}"+ );+ assert!(+ !body.contains("last_assistant_message"),+ "spooled body still carries the raw field key: {body}"+ );+ // Unrelated fields survive so the Stop event is still ingested.+ assert!(+ body.contains("stop-strip"),+ "session_id was dropped: {body}"+ );+}++#[test]+fn spool_files_never_leak_the_assistant_field_on_disk() {+ // Byte-level check across the whole spool file (not just the parsed body):+ // neither the value nor the raw key may survive anywhere in the entry.+ let tmp = tempfile::tempdir().expect("tempdir");+ let payload =+ br#"{"session_id":"disk-scan","last_assistant_message":"SENTINEL_ASSISTANT_MESSAGE"}"#;++ let output = run_hook_event(tmp.path(), "stop", payload);+ assert!(output.status.success());++ let spool = tmp.path().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 bytes = std::fs::read(entries[0].path()).expect("read spool entry");+ let text = String::from_utf8_lossy(&bytes);+ assert!(+ !text.contains("SENTINEL_ASSISTANT_MESSAGE"),+ "assistant message leaked into the spool file bytes"+ );+ assert!(+ !text.contains("last_assistant_message"),+ "raw assistant field key leaked into the spool file bytes"+ );+}diff --git a/crates/ai-memory-hooks/src/assistant_capture.rs b/crates/ai-memory-hooks/src/assistant_capture.rsnew file mode 100644index 00000000..7e79d525--- /dev/null+++ b/crates/ai-memory-hooks/src/assistant_capture.rs@@ -0,0 +1,163 @@+//! Assistant-message capture plumbing (issue #196).+//!+//! Some agent harnesses attach the assistant's final turn to their `Stop`+//! lifecycle event — Claude Code sends it as a top-level `last_assistant_message`+//! string. That text is high-value for recall but privacy-sensitive: it can+//! quote code, secrets, or content from paths ai-memory never sees. Capturing+//! it is therefore an explicit, opt-in feature landing across later PRs.+//!+//! This module owns the single source of truth for WHICH raw field carries the+//! assistant message per agent/event, plus the unconditional strip that keeps+//! that raw field off the local spool, the wire, tracing, and storage until the+//! opt-in path deliberately re-introduces a sanitized, capped excerpt.++use ai_memory_core::AgentKind;++use crate::payload::HookEvent;++/// Protocol version for the opt-in `_ai_memory_assistant` body marker the client+/// attaches once capture is enabled (later PR). Defined here so the wire+/// contract has one home from the start.+pub const ASSISTANT_PROTOCOL_VERSION: u8 = 1;++/// Hard ceiling on the raw assistant-message string the client reads before+/// sanitizing/truncating (later PR). Oversized input is treated as absent.+pub const ASSISTANT_MESSAGE_MAX_INPUT_BYTES: usize = 64 * 1024;++/// Byte cap on the sanitized excerpt the opt-in path persists (later PR). Kept+/// equal to `truncate_excerpt`'s existing 2 KB excerpt contract so Stop bodies+/// do not become a second, larger excerpt norm.+pub const ASSISTANT_EXCERPT_MAX_BYTES: usize = 2_000;++/// Every raw top-level field name known to carry an assistant message across+/// supported agents. The unconditional strip removes each of these; the closed+/// per-agent table below decides which is a *candidate* for opt-in capture. The+/// union is kept tiny on purpose — one entry per distinct wire spelling.+const ASSISTANT_MESSAGE_FIELDS: &[&str] = &["last_assistant_message"];++/// The raw field that carries the assistant's final message for `(agent, event)`,+/// or `None` when the pair has no verified assistant-message field.+///+/// Closed table: only `ClaudeCode + Stop` is supported today. Extend+/// deliberately — a new entry opts an agent/event into capture and MUST have its+/// field name present in [`ASSISTANT_MESSAGE_FIELDS`] so the strip covers it+/// (enforced by `closed_table_fields_are_all_stripped`).+#[must_use]+pub fn assistant_message_field(agent: AgentKind, event: HookEvent) -> Option<&'static str> {+ match (agent, event) {+ (AgentKind::ClaudeCode, HookEvent::Stop) => Some("last_assistant_message"),+ _ => None,+ }+}++/// Unconditionally remove every known assistant-message field from a raw hook+/// payload's top-level object, returning whether anything was removed.+///+/// This is a defense applied on BOTH sides of the wire (client pre-spool and+/// server pre-envelope) and for EVERY agent/event, not just the supported pair:+/// a raw assistant-message field must never reach the spool, the wire, tracing,+/// or storage unless the explicit opt-in path (later PR) re-introduces it as a+/// sanitized, capped excerpt. Only top-level keys are inspected — the same scope+/// as `body_is_subagent`, and where every supported harness places the field.+pub fn strip_assistant_message_raw(raw: &mut serde_json::Value) -> bool {+ let Some(object) = raw.as_object_mut() else {+ return false;+ };+ let mut removed = false;+ for field in ASSISTANT_MESSAGE_FIELDS {+ if object.remove(*field).is_some() {+ removed = true;+ }+ }+ removed+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Only `ClaudeCode + Stop` is a capture candidate; every other agent/event+ /// pair across the full agent surface must return `None`.+ #[test]+ fn only_claude_stop_is_a_capture_candidate() {+ let events = [+ HookEvent::SessionStart,+ HookEvent::UserPrompt,+ HookEvent::PreToolUse,+ HookEvent::PostToolUse,+ HookEvent::PreCompact,+ HookEvent::PostCompaction,+ HookEvent::Notification,+ HookEvent::Stop,+ HookEvent::SessionEnd,+ HookEvent::SubagentStart,+ HookEvent::SubagentStop,+ HookEvent::Other,+ ];+ for agent in AgentKind::ALL {+ for event in events {+ let expected = agent == AgentKind::ClaudeCode && event == HookEvent::Stop;+ assert_eq!(+ assistant_message_field(agent, event).is_some(),+ expected,+ "agent={agent:?} event={event:?}"+ );+ }+ }+ }++ /// The strip must cover every field the closed table can name, or an opted-in+ /// agent/event could carry a raw field the strip misses.+ #[test]+ fn closed_table_fields_are_all_stripped() {+ let events = [+ HookEvent::SessionStart,+ HookEvent::UserPrompt,+ HookEvent::PreToolUse,+ HookEvent::PostToolUse,+ HookEvent::PreCompact,+ HookEvent::PostCompaction,+ HookEvent::Notification,+ HookEvent::Stop,+ HookEvent::SessionEnd,+ HookEvent::SubagentStart,+ HookEvent::SubagentStop,+ HookEvent::Other,+ ];+ for agent in AgentKind::ALL {+ for event in events {+ if let Some(field) = assistant_message_field(agent, event) {+ assert!(+ ASSISTANT_MESSAGE_FIELDS.contains(&field),+ "closed-table field {field:?} is not in the strip set"+ );+ }+ }+ }+ }++ /// The strip is unconditional: it removes the raw field regardless of agent+ /// and reports the removal, so a client that never verified the agent still+ /// cannot leak it.+ #[test]+ fn strip_removes_field_and_reports_change() {+ let mut raw = serde_json::json!({+ "session_id": "s1",+ "last_assistant_message": "SENTINEL_ASSISTANT_MESSAGE",+ });+ assert!(strip_assistant_message_raw(&mut raw));+ assert!(raw.get("last_assistant_message").is_none());+ assert_eq!(raw.get("session_id").and_then(|v| v.as_str()), Some("s1"));+ }++ #[test]+ fn strip_is_noop_when_absent_or_not_object() {+ let mut without = serde_json::json!({"session_id": "s1"});+ assert!(!strip_assistant_message_raw(&mut without));+ assert_eq!(without, serde_json::json!({"session_id": "s1"}));++ let mut array = serde_json::json!(["last_assistant_message"]);+ assert!(!strip_assistant_message_raw(&mut array));+ assert_eq!(array, serde_json::json!(["last_assistant_message"]));+ }+}diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 69021b26..ec0fe49e 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -21,6 +21,7 @@//! This crate does not read process environment directly; server configuration//! is resolved once by `ai-memory-cli` and threaded in as typed state.+pub mod assistant_capture;pub mod capture_policy;pub mod log;pub mod payload;@@ -30,6 +31,10 @@ pub mod synth;// Re-export the sanitizer types from core so callers that grew up// pointing at this crate's `sanitize` module keep working.pub use ai_memory_core::{SanitizeConfig, Sanitized, Sanitizer};+pub use assistant_capture::{+ ASSISTANT_EXCERPT_MAX_BYTES, ASSISTANT_MESSAGE_MAX_INPUT_BYTES, ASSISTANT_PROTOCOL_VERSION,+ assistant_message_field, strip_assistant_message_raw,+};pub use capture_policy::{CaptureConfig, CaptureDecision, CaptureDisposition, CapturePolicy, CaptureProtocol,CaptureSource, ExtractionState, PolicyState, ToolFamily,diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 4dd16c11..f6ee25eb 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -60,7 +60,7 @@ pub struct HookQuery {/// Coalesced view of an incoming hook event after light parsing of the/// body. We keep the original raw JSON around so consumers can extract/// agent-specific fields they care about.-#[derive(Debug, Clone, Serialize)]+#[derive(Clone, Serialize)]pub struct HookEnvelope {/// Mapped lifecycle event.pub event: HookEvent,@@ -102,6 +102,35 @@ pub struct HookEnvelope {pub raw: serde_json::Value,}+/// Manual `Debug` that never renders `raw` (#196). `raw` is the agent's full+/// payload; a stray `?env` / `%env` in a future tracing span would otherwise+/// copy it verbatim into the rolling log file on disk — including the opt-in+/// assistant excerpt landing in a later PR. Every other field stays visible so+/// the envelope is still debuggable.+impl std::fmt::Debug for HookEnvelope {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("HookEnvelope")+ .field("event", &self.event)+ .field("agent", &self.agent)+ .field("session_id", &self.session_id)+ .field("cwd", &self.cwd)+ .field("workspace_override", &self.workspace_override)+ .field("project_override", &self.project_override)+ .field("project_strategy", &self.project_strategy)+ .field("drop_subagent_requested", &self.drop_subagent_requested)+ .field(+ "recall_default_global_requested",+ &self.recall_default_global_requested,+ )+ .field("extension", &self.extension)+ .field("source_event", &self.source_event)+ .field("title_hint", &self.title_hint)+ .field("body_excerpt", &self.body_excerpt)+ .field("raw", &"<redacted>")+ .finish()+ }+}+/// Keys by which agent harnesses tag a hook event as belonging to a SUBAGENT/// (a nested/spawned agent session) rather than the top-level session. Grok/// sets `subagentType` (on its tool-use events); Claude Code sets `agent_type`@@ -784,6 +813,32 @@ mod tests {assert_eq!(HookEvent::parse("bogus"), HookEvent::Other);}+ #[test]+ fn debug_never_renders_raw_payload() {+ // `raw` holds the agent's full payload; the manual Debug impl must redact+ // it so a stray `?env` in a tracing span cannot copy it into the rolling+ // log file on disk (#196). Other fields stay visible for debugging.+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "stop".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "dbg",+ "secret": "SENTINEL_RAW_PAYLOAD"+ }),+ );+ let rendered = format!("{env:?}");+ assert!(+ !rendered.contains("SENTINEL_RAW_PAYLOAD"),+ "Debug leaked the raw payload: {rendered}"+ );+ assert!(rendered.contains("<redacted>"), "raw was not redacted");+ // Sanity: the redaction did not blank the whole struct.+ assert!(rendered.contains("Stop"), "event field went missing");+ }+#[test]fn extension_event_preserves_source_event_when_opted_in() {let env = HookEnvelope::from_query_and_body(diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 91870f8c..863e0a93 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -437,8 +437,12 @@ async fn handle_hook(State(state): State<Arc<HookState>>,Query(query): Query<HookQuery>,actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,- Json(body): Json<serde_json::Value>,+ Json(mut body): Json<serde_json::Value>,) -> impl IntoResponse {+ // Incondicional backstop (#196): drop any raw assistant-message field on the+ // `Value` before it becomes a `HookEnvelope`, so the field can never reach+ // `body_excerpt`, tracing, or the store — regardless of client version.+ crate::assistant_capture::strip_assistant_message_raw(&mut body);let env = HookEnvelope::from_query_and_body(query, body);let Some(env) = inspect_capture_envelope(env) else {return (StatusCode::ACCEPTED, "capture policy dropped");@@ -596,7 +600,10 @@ async fn handle_hook_batch(.map(|axum::Extension(ctx)| ctx.user).unwrap_or_default();let mut accepted_indices = Vec::new();- for (idx, item) in items.into_iter().enumerate() {+ for (idx, mut item) in items.into_iter().enumerate() {+ // Same unconditional assistant-message backstop as `handle_hook`, applied+ // per item before the envelope is built (#196).+ crate::assistant_capture::strip_assistant_message_raw(&mut item.body);let query = parse_hook_query(&item.url);let env = HookEnvelope::from_query_and_body(query, item.body);let Some(env) = inspect_capture_envelope(env) else {@@ -2701,6 +2708,93 @@ mod tests {assert_eq!(ack["accepted"], 2, "both events committed, oldest-first");}+ /// Recursively scan every file under `dir` for a byte pattern. Used to prove+ /// a stripped field left no trace anywhere in the on-disk store (any column,+ /// the WAL, etc.), not just in the read-back observation body.+ fn any_file_contains(dir: &std::path::Path, needle: &[u8]) -> bool {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return false;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ if any_file_contains(&path, needle) {+ return true;+ }+ } else if let Ok(bytes) = std::fs::read(&path)+ && bytes.windows(needle.len()).any(|window| window == needle)+ {+ return true;+ }+ }+ false+ }++ #[tokio::test]+ async fn handle_hook_batch_strips_assistant_message_before_persist() {+ let tmp = TempDir::new().unwrap();+ let state = Arc::new(make_state(&tmp).await);++ // Mixed batch: a Stop carrying `last_assistant_message` (must be stripped+ // and persisted empty) plus a clean UserPrompt (must be untouched). Proves+ // the server backstop runs per item and does not disturb siblings (#196).+ let stop_body = serde_json::json!({+ "session_id": "stop-batch",+ "last_assistant_message": "SENTINEL_ASSISTANT_MESSAGE"+ });+ let items = vec![+ HookBatchItem {+ url: "http://h/hook?event=stop&agent=claude-code".into(),+ body: stop_body.clone(),+ },+ HookBatchItem {+ url: "http://h/hook?event=user-prompt-submit&agent=claude-code".into(),+ body: serde_json::json!({ "session_id": "stop-batch", "prompt": "hello world" }),+ },+ ];++ let response = handle_hook_batch(State(state.clone()), None, Json(items))+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::OK);++ let sid = resolve_session_id(&HookEnvelope::from_query_and_body(+ HookQuery {+ event: "stop".into(),+ agent: Some("claude-code".into()),+ session_id: Some("stop-batch".into()),+ ..Default::default()+ },+ stop_body,+ ))+ .unwrap();+ let observations = state.reader.observations_for_session(sid).await.unwrap();++ let stop = observations+ .iter()+ .find(|o| o.kind == ai_memory_core::ObservationKind::Stop)+ .expect("Stop event is still persisted");+ assert!(+ !stop.body.contains("SENTINEL_ASSISTANT_MESSAGE"),+ "Stop body carried the assistant message: {:?}",+ stop.body+ );+ let prompt = observations+ .iter()+ .find(|o| o.kind == ai_memory_core::ObservationKind::UserPrompt)+ .expect("clean sibling UserPrompt is persisted");+ assert!(+ prompt.body.contains("hello world"),+ "sibling prompt was disturbed by the strip: {:?}",+ prompt.body+ );++ assert!(+ !any_file_contains(tmp.path(), b"SENTINEL_ASSISTANT_MESSAGE"),+ "assistant message leaked into the on-disk store"+ );+ }+/// `pre-tool-use` query+agent for building an env to recompute a SessionId.fn grok_tool_query() -> HookQuery {HookQuery {diff --git a/docs/install.md b/docs/install.mdindex 3e891161..12a44479 100644--- a/docs/install.md+++ b/docs/install.md@@ -378,6 +378,18 @@ Docker script bundles do not enforce it. Re-run `install-hooks --agent <agent>capability output reflects the selected integration. See the canonical[capture exclusions reference](marker-file.md#capture-exclusions).+Some agent harnesses attach the assistant's final turn to their `Stop` event —+Claude Code sends it as a raw `last_assistant_message`. That text is never+persisted, and the native hook binary now strips the raw field before it can+reach the local spool or the wire; the server strips it defensively on arrival+too. Explicit, sanitized opt-in capture of this text ships in a later release.+Upgrading the binary is sufficient for native Claude Code installs, and pending+spooled events drain with the field stripped as well. Installs that run the+`.sh`/`.ps1` script fallback (the Docker script bundle or an explicit+`AI_MEMORY_HOOK_PLATFORM=posix`) still POST the raw field on the local wire+until they move to native commands: run `install-hooks --agent claude-code+--apply`, which installs native `ai-memory hook` commands where supported.+Native `ai-memory hook --event ...` commands spool events locally. Session startdoes a short bounded cleanup drain before fetching a handoff; cancellation-proneboundary events (`stop`, `pre-compact`, and `session-end`) start a detached