Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
M12: harden privacy strip — patterns, boundaries, config
AkitaOnRailsd8361d3c3a86
diff --git a/.gitignore b/.gitignoreindex b303142f..f5e685cc 100644--- a/.gitignore+++ b/.gitignore@@ -23,3 +23,4 @@ perf.data*# Sandbox marker (not project content)..ai-jail+.claude/diff --git a/Cargo.lock b/Cargo.lockindex ecb295ea..275bcc80 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -85,9 +85,11 @@ name = "ai-memory-core"version = "0.1.0"dependencies = ["jiff",+ "regex","serde","serde_json","thiserror 2.0.18",+ "tracing","uuid",]diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 33b9e9c8..7a7169a8 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -3,6 +3,7 @@use std::sync::Arc;use ai_memory_consolidate::Consolidator;+use ai_memory_core::Sanitizer;use ai_memory_hooks::{HookState, hook_router};use ai_memory_llm::{build_embedder, embedder_from_env, provider_from_env};use ai_memory_mcp::AiMemoryServer;@@ -36,7 +37,13 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {.writer.get_or_create_project(ws, args.project.clone(), None).await?;- let mut wiki = Wiki::new(&config.data_dir, store.writer.clone())?;+ // Build the privacy strip from config. Compile errors in+ // user-supplied regex abort startup with a clear message so+ // operators discover misconfiguration immediately.+ let sanitizer = Sanitizer::new(&config.sanitize)+ .context("compiling sanitizer.extra_patterns from config")?;+ let mut wiki =+ Wiki::new(&config.data_dir, store.writer.clone())?.with_sanitizer(sanitizer.clone());// M9 — pluggable embedder. Refuse to start if any stored// embeddings disagree with the configured (provider, model, dim).@@ -82,7 +89,8 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {let mut server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj).with_wiki(wiki.clone())- .with_decay_params(config.decay);+ .with_decay_params(config.decay)+ .with_sanitizer(sanitizer.clone());if let Some(e) = embedder.clone() {server = server.with_embedder(e);}@@ -136,6 +144,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {reader: store.reader.clone(),wiki: wiki.clone(),consolidator: consolidator.clone(),+ sanitizer: sanitizer.clone(),});let router = axum::Router::new().nest_service("/mcp", mcp_service)diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 10ce5d17..c1c06470 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -31,6 +31,9 @@ pub struct Config {/// hard-deletion. Tune `decay.lambda` down to slow decay or/// `decay.cold_threshold` to evict more / less aggressively.pub decay: ai_memory_store::DecayParams,+ /// Privacy-strip tuning. Built-in patterns always run; this section+ /// lets the operator extend or punch holes in them.+ pub sanitize: ai_memory_core::SanitizeConfig,}impl Default for Config {@@ -40,6 +43,7 @@ impl Default for Config {bind: "127.0.0.1:49374".into(),log_level: "info".into(),decay: ai_memory_store::DecayParams::default(),+ sanitize: ai_memory_core::SanitizeConfig::default(),}}}diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.tomlindex 3d7f8392..852e8056 100644--- a/crates/ai-memory-cli/templates/config.default.toml+++ b/crates/ai-memory-cli/templates/config.default.toml@@ -33,3 +33,38 @@ mu = 0.04salience_default = 1.0cold_threshold = 0.20hard_delete_after_days = 180++# Privacy strip.+#+# Built-in patterns ALWAYS run; they cover bearer tokens, vendor-prefixed+# API keys (sk-, sk_live_, ghp_, github_pat_, AKIA, AIza, xoxb/xoxp/xoxa/+# xapp, Slack-shaped tokens), JWTs, PEM-bracketed private keys,+# URL-embedded credentials (postgres://user:pass@host), the named env+# vars for every supported provider, the generic `*_(KEY|TOKEN|SECRET|+# PASSWORD|CREDENTIAL)=…` shape, and filesystem paths under ~/.ssh,+# ~/.aws, ~/.kube, ~/.config/gcloud, ~/.gnupg.+#+# Two optional fields tune the strip:+#+# extra_patterns — additional regex patterns to redact. Compiled once+# at startup; an invalid regex aborts startup with a+# clear error.+# allowlist — substrings that should never be redacted, even if a+# pattern matches them. Useful when a project codename+# or stable identifier collides with the generic+# env-var catch-all.+#+# Examples (uncomment to use):+#+# extra_patterns = [+# # Internal project token format: PROJ-<32 hex chars>.+# "PROJ-[0-9a-f]{32}",+# ]+# allowlist = [+# # We don't want this public identifier redacted by the generic+# # *_KEY catch-all even though it ends in "_KEY".+# "PUBLIC_VERIFY_KEY",+# ]+[sanitize]+extra_patterns = []+allowlist = []diff --git a/crates/ai-memory-core/Cargo.toml b/crates/ai-memory-core/Cargo.tomlindex 47077ff8..1b36bf68 100644--- a/crates/ai-memory-core/Cargo.toml+++ b/crates/ai-memory-core/Cargo.toml@@ -14,6 +14,8 @@ serde_json.workspace = truethiserror.workspace = trueuuid.workspace = truejiff.workspace = true+regex.workspace = true+tracing.workspace = true[lints]workspace = truediff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex b2e0b2b2..95e42109 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -1,14 +1,16 @@//! Core domain types and errors for ai-memory.//!//! This crate is the closure of the project's vocabulary: identifiers, agent-//! kinds, and the workspace-wide error type. Nothing in here performs I/O,-//! which keeps it trivially unit-testable and free of platform concerns.+//! kinds, the workspace-wide error type, and the privacy strip (which is+//! pure-compute, no IO). Nothing in here performs I/O, which keeps it+//! trivially unit-testable and free of platform concerns.pub mod error;pub mod handoff;pub mod ids;pub mod observation;pub mod page;+pub mod sanitize;pub use error::{MemoryError, MemoryResult};pub use handoff::{Handoff, HandoffState, NewHandoff};@@ -17,3 +19,4 @@ pub use ids::{};pub use observation::{NewObservation, NewSession, Observation, ObservationKind};pub use page::{NewPage, Page, Tier};+pub use sanitize::{SanitizeConfig, Sanitized, Sanitizer};diff --git a/crates/ai-memory-core/src/sanitize.rs b/crates/ai-memory-core/src/sanitize.rsnew file mode 100644index 00000000..8ec9e15b--- /dev/null+++ b/crates/ai-memory-core/src/sanitize.rs@@ -0,0 +1,324 @@+//! Privacy strip — redacts secrets before they reach durable storage.+//!+//! Two surfaces live here:+//!+//! - [`Sanitizer`] is a stateful, config-driven scrubber. Build it once+//! at startup from `SanitizeConfig` and pass `Arc<Sanitizer>` to every+//! subsystem that writes user-facing text to disk (hook ingress,+//! consolidator, wiki writer, MCP `memory_handoff_begin`).+//! - [`Sanitized<T>`] is the typed boundary: the *only* way to construct+//! one is through [`Sanitized::new`], which forces the caller to hand+//! over an already-scrubbed value. Without this, you can't accidentally+//! persist raw text by skipping the sanitizer.+//!+//! ## What we redact+//!+//! Built-in patterns cover bearer tokens, vendor-prefixed API keys+//! (Anthropic / OpenAI / OpenRouter sk-…, Stripe sk_live_…, GitHub PATs,+//! Google AIza…, Slack xoxb/xoxp…, AWS AKIA…), PEM-bracketed private+//! keys, URL-embedded credentials (`postgres://user:pass@host`), and+//! anything matching the generic `*_(KEY|TOKEN|SECRET|PASSWORD|+//! CREDENTIAL)=value` shape. Operators can extend the list via+//! `[sanitize].extra_patterns` and exempt substrings via+//! `[sanitize].allowlist` — the allowlist is checked *per match*, so a+//! pattern still runs but an allowlisted span survives unchanged.+//!+//! ## What we deliberately do not catch+//!+//! Standalone high-entropy strings (e.g. a 32-char random hex) cannot+//! be safely redacted without knowing their structure — too many false+//! positives. Operators who care about that level of paranoia should+//! add a custom pattern via `extra_patterns`.++use std::sync::Arc;++use regex::Regex;+use tracing::debug;++use crate::NewObservation;++/// Compile-time list of redaction patterns. Order is intentional:+/// more-specific patterns first. False positives are acceptable —+/// better to redact a stray hash than to leak a credential.+const BUILTIN_PATTERN_STRS: &[&str] = &[+ // Bearer-style tokens.+ r#"(?i)bearer\s+[A-Za-z0-9._\-+/=]{16,}"#,+ // Vendor-prefixed API keys.+ r"sk-[A-Za-z0-9_\-]{16,}",+ r"sk_live_[A-Za-z0-9_\-]{16,}",+ r"ghp_[A-Za-z0-9]{20,}",+ r"github_pat_[A-Za-z0-9_]{20,}",+ r"AKIA[0-9A-Z]{12,}",+ // Naked Google / Gemini API keys.+ r"AIza[A-Za-z0-9_\-]{30,}",+ // Slack tokens (bot/user/admin/app-level/refresh).+ r"xox[abprs]-[A-Za-z0-9\-]{10,}",+ r"xapp-[A-Za-z0-9\-]{10,}",+ // JWTs (three base64url segments separated by dots).+ r"eyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}",+ // PEM private key blocks — multi-line, lazy match.+ r"(?s)-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----",+ // URL-embedded credentials: scheme://user:pass@host.+ r"[a-zA-Z][a-zA-Z0-9+\-.]*://[^:/\s]+:[^@\s]+@[^\s]+",+ // Provider-specific env-var assignments (kept explicit for clarity+ // and so that bare `OPENAI_API_KEY=anything-at-all` still triggers+ // even without `sk-` shape).+ r#"(?i)(ANTHROPIC_API_KEY|OPENAI_API_KEY|OPENROUTER_API_KEY|VOYAGE_API_KEY|MISTRAL_API_KEY|GROQ_API_KEY|HF_TOKEN|HUGGINGFACE_TOKEN|AWS_(SECRET_)?ACCESS_KEY[A-Z_]*|GITHUB_TOKEN|GH_TOKEN|GITLAB_TOKEN|GOOGLE_API_KEY|GEMINI_API_KEY|OLLAMA_API_KEY)\s*[=:]\s*\S+"#,+ // Generic env-var catch-all: any *_KEY / *_TOKEN / *_SECRET /+ // *_PASSWORD / *_CREDENTIAL[S] / *_PRIVATE_KEY assignment.+ r#"(?i)\b[A-Z][A-Z0-9_]*_(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|CREDENTIALS|PRIVATE_KEY)\s*[=:]\s*\S+"#,+ // Filesystem paths that commonly contain credentials.+ r"(?:/[^/\s]+)*/\.ssh(?:/[^\s]+)?",+ r"(?:/[^/\s]+)*/\.aws(?:/[^\s]+)?",+ r"(?:/[^/\s]+)*/\.kube(?:/[^\s]+)?",+ r"(?:/[^/\s]+)*/\.config/gcloud(?:/[^\s]+)?",+ r"(?:/[^/\s]+)*/\.gnupg(?:/[^\s]+)?",+];++/// Stateful sanitizer. Cheap to clone — wraps an `Arc` of compiled+/// patterns. Construct once at startup, then pass everywhere by clone.+#[derive(Clone)]+pub struct Sanitizer {+ inner: Arc<SanitizerInner>,+}++struct SanitizerInner {+ patterns: Vec<Regex>,+ allowlist: Vec<String>,+}++impl std::fmt::Debug for Sanitizer {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Sanitizer")+ .field("patterns", &self.inner.patterns.len())+ .field("allowlist", &self.inner.allowlist.len())+ .finish()+ }+}++/// User-tunable sanitizer settings. Mirrors the `[sanitize]` section+/// of `config.toml`.+#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]+#[serde(default)]+pub struct SanitizeConfig {+ /// Additional regex patterns to redact. Compiled once at startup;+ /// invalid regex aborts startup with a clear error.+ pub extra_patterns: Vec<String>,+ /// Substrings that should *never* be redacted, even if a pattern+ /// matches them. Useful when a project codename collides with the+ /// generic env-var catch-all (e.g. "PROJECT_TOKEN" the user wants+ /// to keep visible).+ pub allowlist: Vec<String>,+}++impl Sanitizer {+ /// Build a sanitizer from built-in patterns plus the operator's+ /// extras. Returns an error if any extra pattern fails to compile.+ ///+ /// # Errors+ /// Returns [`regex::Error`] when an entry in `extra_patterns` is+ /// not a valid regex.+ pub fn new(cfg: &SanitizeConfig) -> Result<Self, regex::Error> {+ let mut patterns =+ Vec::with_capacity(BUILTIN_PATTERN_STRS.len() + cfg.extra_patterns.len());+ for p in BUILTIN_PATTERN_STRS {+ patterns.push(Regex::new(p)?);+ }+ for p in &cfg.extra_patterns {+ patterns.push(Regex::new(p)?);+ }+ Ok(Self {+ inner: Arc::new(SanitizerInner {+ patterns,+ allowlist: cfg.allowlist.clone(),+ }),+ })+ }++ /// Built-in-only sanitizer (no operator extras, no allowlist).+ /// Convenient for tests and zero-config callers.+ #[must_use]+ pub fn builtin() -> Self {+ Self::new(&SanitizeConfig::default()).expect("built-in patterns compile")+ }++ /// Scrub a single string. Each match is replaced with `[REDACTED]`+ /// unless the matched substring contains an allowlist entry, in+ /// which case it is left alone.+ #[must_use]+ pub fn scrub(&self, input: &str) -> String {+ let mut out = input.to_string();+ for re in &self.inner.patterns {+ out = re+ .replace_all(&out, |caps: ®ex::Captures<'_>| {+ let m = caps.get(0).map(|m| m.as_str()).unwrap_or_default();+ if self.inner.allowlist.iter().any(|a| m.contains(a)) {+ m.to_string()+ } else {+ debug!(pattern = re.as_str(), "sanitize: redacted match");+ "[REDACTED]".to_string()+ }+ })+ .into_owned();+ }+ out+ }+}++impl Default for Sanitizer {+ fn default() -> Self {+ Self::builtin()+ }+}++/// Marker carried by every value that has passed through the privacy+/// strip. The wrapped value is private and reachable only via+/// [`Sanitized::inner`] / [`Sanitized::into_inner`].+#[derive(Debug, Clone)]+pub struct Sanitized<T>(T);++impl<T> Sanitized<T> {+ /// Borrow the inner sanitized value.+ pub fn inner(&self) -> &T {+ &self.0+ }+ /// Consume and return the inner sanitized value.+ pub fn into_inner(self) -> T {+ self.0+ }+}++impl Sanitized<NewObservation> {+ /// Apply the privacy strip to an observation's title + body.+ #[must_use]+ pub fn new(mut obs: NewObservation, sanitizer: &Sanitizer) -> Self {+ obs.title = sanitizer.scrub(&obs.title);+ obs.body = sanitizer.scrub(&obs.body);+ Self(obs)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{ObservationKind, ProjectId, SessionId, WorkspaceId};++ fn s() -> Sanitizer {+ Sanitizer::builtin()+ }++ #[test]+ fn scrubs_bearer_token() {+ let out = s().scrub("Authorization: Bearer abcdef0123456789ABCDEF0123456789");+ assert!(out.contains("[REDACTED]"));+ assert!(!out.contains("abcdef0123"));+ }++ #[test]+ fn scrubs_openrouter_key_via_sk_prefix() {+ let out = s().scrub("key=sk-or-v1-deadbeefcafebabe1234567890abcdef");+ assert!(out.contains("[REDACTED]"));+ assert!(!out.contains("deadbeef"));+ }++ #[test]+ fn scrubs_naked_google_api_key() {+ let out = s().scrub("the key AIzaSyB3tCIXhU0PWMv8hugqbKwKP3ZxBhAFpaY is leaked");+ assert!(out.contains("[REDACTED]"));+ assert!(!out.contains("AIzaSy"));+ }++ #[test]+ fn scrubs_slack_bot_token() {+ let out = s().scrub("slack=xoxb-1234567890-abcdefghij");+ assert!(out.contains("[REDACTED]"));+ assert!(!out.contains("xoxb-1234"));+ }++ #[test]+ fn scrubs_pem_private_key_block() {+ let pem = "before\n-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA\n-----END OPENSSH PRIVATE KEY-----\nafter";+ let out = s().scrub(pem);+ assert!(out.contains("[REDACTED]"));+ assert!(!out.contains("b3BlbnNz"));+ assert!(out.contains("before"));+ assert!(out.contains("after"));+ }++ #[test]+ fn scrubs_url_embedded_credentials() {+ let out = s().scrub("connect to postgres://admin:[email protected]/prod");+ assert!(out.contains("[REDACTED]"));+ assert!(!out.contains("hunter2"));+ }++ #[test]+ fn scrubs_generic_env_var_assignments() {+ let out = s().scrub("MY_INTERNAL_API_KEY=abcdef123456");+ assert!(out.contains("[REDACTED]"));+ let out2 = s().scrub("SOMETHING_SECRET=foo");+ assert!(out2.contains("[REDACTED]"));+ let out3 = s().scrub("DB_PASSWORD=hunter2");+ assert!(out3.contains("[REDACTED]"));+ }++ #[test]+ fn scrubs_cloud_credential_paths() {+ let out = s().scrub("read /home/user/.aws/credentials");+ assert!(out.contains("[REDACTED]"));+ let out2 = s().scrub("set KUBECONFIG=/home/user/.kube/config");+ assert!(out2.contains("[REDACTED]"));+ }++ #[test]+ fn observation_round_trip() {+ let raw = NewObservation {+ session_id: SessionId::new(),+ workspace_id: WorkspaceId::new(),+ project_id: ProjectId::new(),+ kind: ObservationKind::UserPrompt,+ title: "OPENAI_API_KEY=sk-leak-1234567890abcdef".into(),+ body: "see /home/user/.ssh/id_ed25519".into(),+ importance: 5,+ };+ let scrubbed = Sanitized::new(raw, &s()).into_inner();+ assert!(scrubbed.title.contains("[REDACTED]"));+ assert!(scrubbed.body.contains("[REDACTED]"));+ }++ #[test]+ fn extra_patterns_compile_and_apply() {+ let cfg = SanitizeConfig {+ extra_patterns: vec![r"CANARY-[0-9]+".to_string()],+ allowlist: vec![],+ };+ let sn = Sanitizer::new(&cfg).unwrap();+ let out = sn.scrub("found CANARY-42 here");+ assert!(out.contains("[REDACTED]"));+ }++ #[test]+ fn invalid_extra_pattern_errors() {+ let cfg = SanitizeConfig {+ extra_patterns: vec!["[unterminated".to_string()],+ allowlist: vec![],+ };+ assert!(Sanitizer::new(&cfg).is_err());+ }++ #[test]+ fn allowlist_substring_survives_redaction() {+ // The generic env-var pattern would match this, but the+ // allowlist exempts spans containing "PROJECT_TOKEN".+ let cfg = SanitizeConfig {+ extra_patterns: vec![],+ allowlist: vec!["PROJECT_TOKEN_PUBLIC".to_string()],+ };+ let sn = Sanitizer::new(&cfg).unwrap();+ let out = sn.scrub("we use PROJECT_TOKEN_PUBLIC=abc internally");+ assert!(+ out.contains("PROJECT_TOKEN_PUBLIC"),+ "allowlist span should survive; got: {out}"+ );+ }+}diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 5b659593..f7f7398a 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -10,9 +10,10 @@//! (lesson from agentmemory #221 — hooks that `await` REST round-trips//! can deadlock the engine under fan-out).//! 3. The server parses the body as JSON, runs it through the-//! [`sanitize`] redaction layer, and forwards a [`Sanitized<NewObservation>`]-//! to the store writer. On `SessionEnd` it also synthesises a wiki-//! page summarising the session via [`synth`].+//! [`ai_memory_core::Sanitizer`] redaction layer, and forwards a+//! [`ai_memory_core::Sanitized<NewObservation>`] to the store writer.+//! On `SessionEnd` it also synthesises a wiki page summarising the+//! session via [`synth`].//!//! Privacy strip is a *typed* boundary: there is no way to write an//! observation without first passing through `Sanitized::new`.@@ -20,10 +21,11 @@pub mod log;pub mod payload;pub mod router;-pub mod sanitize;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 payload::{HookEnvelope, HookEvent};pub use router::{HookState, hook_router};-pub use sanitize::Sanitized;pub use synth::synthesize_session_page;diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 108edd96..4c2cd210 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -13,7 +13,7 @@ use std::sync::Arc;use ai_memory_consolidate::Consolidator;use ai_memory_core::{AgentKind, Handoff, NewHandoff, NewObservation, NewSession, ObservationKind, ProjectId,- SessionId, WorkspaceId,+ Sanitized, Sanitizer, SessionId, WorkspaceId,};use ai_memory_store::WriterHandle;use ai_memory_wiki::Wiki;@@ -30,7 +30,6 @@ use uuid::Uuid;use crate::log;use crate::payload::{HookEnvelope, HookEvent, HookQuery, parse_agent};-use crate::sanitize::Sanitized;use crate::synth::synthesize_session_page;/// Shared state passed to the hook handler.@@ -51,6 +50,10 @@ pub struct HookState {/// working context. When `None`, falls back to the deterministic/// rule-based synth (still useful, just lower-signal).pub consolidator: Option<Arc<Consolidator>>,+ /// Privacy strip applied to every observation before it lands in+ /// the store. Same handle is also held by the wiki and consolidator+ /// so scrubbing happens at every write boundary.+ pub sanitizer: Sanitizer,}/// Build a router with `POST /hook` (event ingress) and `GET /handoff`@@ -196,7 +199,7 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {body,importance: importance_for(env.event),};- let sanitized = Sanitized::new(raw_obs);+ let sanitized = Sanitized::new(raw_obs, &state.sanitizer);let _ = state.writer.insert_observation(sanitized.inner().clone())@@ -216,10 +219,10 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {// the working state before the agent's compaction throws it out// of context. Does NOT end the session and does NOT create a// handoff. The eventual SessionEnd supersedes this page.- if matches!(env.event, HookEvent::PreCompact) {- if let Err(e) = consolidate_or_synth(state, session_id).await {- warn!(error = %e, "PreCompact consolidation failed; continuing");- }+ if matches!(env.event, HookEvent::PreCompact)+ && let Err(e) = consolidate_or_synth(state, session_id).await+ {+ warn!(error = %e, "PreCompact consolidation failed; continuing");}// On SessionEnd, synthesize the summary page, end the session, anddiff --git a/crates/ai-memory-hooks/src/sanitize.rs b/crates/ai-memory-hooks/src/sanitize.rsdeleted file mode 100644index f627d4f0..00000000--- a/crates/ai-memory-hooks/src/sanitize.rs+++ /dev/null@@ -1,134 +0,0 @@-//! Privacy strip — the **only** way to construct an [`Observation`]-//! from an inbound hook payload.-//!-//! The type [`Sanitized<T>`] is a thin newtype wrapper. Callers obtain-//! it exclusively via [`Sanitized::new`], which scrubs the inner value's-//! string fields of common secrets. There is no other constructor and-//! the inner value is `pub(crate)` — preventing the "hook handler forgot-//! to call `sanitize()` before persisting" failure mode entirely.--use std::sync::OnceLock;--use ai_memory_core::NewObservation;-use regex::Regex;-use tracing::debug;--/// Marker carried by every observation-shaped value once it has passed-/// through the privacy strip.-#[derive(Debug, Clone)]-pub struct Sanitized<T>(T);--impl<T> Sanitized<T> {- /// Borrow the inner sanitized value.- pub fn inner(&self) -> &T {- &self.0- }-- /// Consume and return the inner sanitized value.- pub fn into_inner(self) -> T {- self.0- }-}--impl Sanitized<NewObservation> {- /// Run privacy strip rules over an inbound observation.- #[must_use]- pub fn new(mut obs: NewObservation) -> Self {- obs.title = scrub(&obs.title);- obs.body = scrub(&obs.body);- Self(obs)- }-}--/// Run privacy strip rules over an arbitrary text payload.-#[must_use]-pub fn scrub(input: &str) -> String {- let mut out = input.to_string();- for re in regex_set() {- let before_len = out.len();- out = re.replace_all(&out, "[REDACTED]").into_owned();- if out.len() != before_len {- debug!(pattern = %re.as_str(), "sanitize: redacted match");- }- }- out-}--fn regex_set() -> &'static [Regex] {- static SET: OnceLock<Vec<Regex>> = OnceLock::new();- SET.get_or_init(|| {- // Order matters: more-specific patterns first. We intentionally- // accept some false positives in v1 — better to redact a stray- // hash than to leak an API key.- let raw_patterns: &[&str] = &[- // Bearer-style tokens.- r#"(?i)bearer\s+[A-Za-z0-9._\-+/=]{16,}"#,- // sk-..., pk_live_..., GitHub PATs, AWS access keys, etc.- r"sk-[A-Za-z0-9_\-]{16,}",- r"sk_live_[A-Za-z0-9_\-]{16,}",- r"ghp_[A-Za-z0-9]{20,}",- r"github_pat_[A-Za-z0-9_]{20,}",- r"AKIA[0-9A-Z]{12,}",- // JWTs.- r"eyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}",- // Explicit env-var assignments commonly containing secrets.- r#"(?i)(ANTHROPIC_API_KEY|OPENAI_API_KEY|VOYAGE_API_KEY|MISTRAL_API_KEY|GROQ_API_KEY|HF_TOKEN|HUGGINGFACE_TOKEN|AWS_(SECRET_)?ACCESS_KEY[A-Z_]*|GITHUB_TOKEN|GH_TOKEN|GITLAB_TOKEN|GOOGLE_API_KEY|GEMINI_API_KEY)\s*[=:]\s*\S+"#,- // Paths under ~/.ssh.- r"(?:/[^/\s]+)*/\.ssh(?:/[^\s]+)?",- ];- raw_patterns- .iter()- .map(|p| Regex::new(p).expect("compile sanitizer regex"))- .collect()- })-}--#[cfg(test)]-mod tests {- use super::*;- use ai_memory_core::{NewObservation, ObservationKind, ProjectId, SessionId, WorkspaceId};-- #[test]- fn scrubs_bearer_tokens() {- let s = scrub("Authorization: Bearer abcdef0123456789ABCDEF0123456789");- assert!(s.contains("[REDACTED]"));- assert!(!s.contains("abcdef"));- }-- #[test]- fn scrubs_anthropic_key() {- let s = scrub("env: ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxx");- assert!(s.contains("[REDACTED]"));- assert!(!s.contains("sk-ant"));- }-- #[test]- fn scrubs_jwt() {- let s = scrub("token: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkw.abcdefABCDEF123456");- assert!(s.contains("[REDACTED]"));- }-- #[test]- fn scrubs_ssh_paths() {- let s = scrub("found in /home/user/.ssh/id_ed25519");- assert!(s.contains("[REDACTED]"));- assert!(!s.contains("id_ed25519"));- }-- #[test]- fn observation_round_trip_through_sanitized() {- let raw = NewObservation {- session_id: SessionId::new(),- workspace_id: WorkspaceId::new(),- project_id: ProjectId::new(),- kind: ObservationKind::UserPrompt,- title: "fix the OPENAI_API_KEY=sk-1234567890abcdef in env".into(),- body: "see ~/.ssh/secret.pem".into(),- importance: 5,- };- let sanitized = Sanitized::new(raw);- let obs = sanitized.into_inner();- assert!(obs.title.contains("[REDACTED]"));- assert!(obs.body.contains("[REDACTED]"));- }-}diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 0aee2a9b..77d02648 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -48,6 +48,10 @@ pub struct AiMemoryServer {/// M9 embedder for hybrid query. When `None`, `memory_query`/// falls back to pure FTS5.embedder: Option<Arc<dyn Embedder>>,+ /// Privacy strip. Applied to agent-supplied handoff fields in+ /// `memory_handoff_begin` (handoffs bypass `Wiki::write_page` so+ /// the wiki-level scrub doesn't cover them).+ sanitizer: ai_memory_core::Sanitizer,// Read by the `#[tool_handler]` macro expansion; rustc's dead-code// analysis can't see that, so the lint must be allowed explicitly.#[allow(dead_code)]@@ -155,10 +159,19 @@ impl AiMemoryServer {wiki: None,decay_params: DecayParams::default(),embedder: None,+ sanitizer: ai_memory_core::Sanitizer::builtin(),tool_router: Self::tool_router(),}}+ /// Replace the default built-in-only sanitizer with one carrying+ /// the operator's `[sanitize]` extras + allowlist.+ #[must_use]+ pub fn with_sanitizer(mut self, sanitizer: ai_memory_core::Sanitizer) -> Self {+ self.sanitizer = sanitizer;+ self+ }+/// Attach an embedder for hybrid (FTS5 + vector RRF) query. Without/// this, `memory_query` runs pure FTS5.#[must_use]@@ -381,6 +394,12 @@ impl AiMemoryServer {&self,Parameters(args): Parameters<HandoffBeginArgs>,) -> Result<CallToolResult, McpError> {+ // Handoffs bypass `Wiki::write_page` (they live in their own+ // table), so scrub the agent-supplied free-text here. We don't+ // touch `cwd` or `files_touched` — they're path lists that the+ // path-pattern regexes already cover when applicable, but we+ // pass each entry through anyway as defence-in-depth.+ let s = &self.sanitizer;let handoff = NewHandoff {workspace_id: self.workspace_id,project_id: self.project_id,@@ -388,10 +407,10 @@ impl AiMemoryServer {from_agent: AgentKind::Other,to_agent: None,cwd: args.cwd.map(std::path::PathBuf::from),- summary: args.summary,- open_questions: args.open_questions,- next_steps: args.next_steps,- files_touched: args.files_touched,+ summary: s.scrub(&args.summary),+ open_questions: args.open_questions.iter().map(|q| s.scrub(q)).collect(),+ next_steps: args.next_steps.iter().map(|n| s.scrub(n)).collect(),+ files_touched: args.files_touched.iter().map(|f| s.scrub(f)).collect(),};let id = self.writerdiff --git a/crates/ai-memory-wiki/src/git.rs b/crates/ai-memory-wiki/src/git.rsindex 60c231d3..9a0f9689 100644--- a/crates/ai-memory-wiki/src/git.rs+++ b/crates/ai-memory-wiki/src/git.rs@@ -80,7 +80,7 @@ impl GitAdapter {// is nothing staged. Otherwise we'd produce an "initial" commit// pointing at the empty tree, which surprises both `git log`// and our own callers.- if repo.head().is_err() && index.len() == 0 {+ if repo.head().is_err() && index.is_empty() {debug!("fresh repo, empty index; no commit");return Ok(None);}diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex e1fb3e39..24019d69 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -3,7 +3,7 @@use std::path::{Path, PathBuf};use std::sync::Arc;-use ai_memory_core::{NewPage, PageId, PagePath, ProjectId, Tier, WorkspaceId};+use ai_memory_core::{NewPage, PageId, PagePath, ProjectId, Sanitizer, Tier, WorkspaceId};use ai_memory_llm::Embedder;use ai_memory_store::{WriterHandle, f32_vec_to_bytes};@@ -25,6 +25,11 @@ pub struct Wiki {writer: WriterHandle,git: GitAdapter,embedder: Option<Arc<dyn Embedder>>,+ /// Privacy strip applied to every page body before persistence.+ /// Defence-in-depth: any caller path (LLM consolidation, manual+ /// write-page CLI, agent-supplied tool input) still gets scrubbed+ /// at the wiki boundary even if upstream forgot.+ sanitizer: Sanitizer,}impl Wiki {@@ -43,9 +48,18 @@ impl Wiki {writer,git,embedder: None,+ sanitizer: Sanitizer::builtin(),})}+ /// Replace the default built-in-only sanitizer with one carrying+ /// the operator's `[sanitize].extra_patterns` + `allowlist`.+ #[must_use]+ pub fn with_sanitizer(mut self, sanitizer: Sanitizer) -> Self {+ self.sanitizer = sanitizer;+ self+ }+/// Attach an embedder. When set, every successful `write_page` //// `apply_batch` also computes + stores an embedding for the new/// version. Without this, vector search is unavailable and@@ -158,7 +172,12 @@ impl Wiki {tempfile::NamedTempFile,std::path::PathBuf,)> = Vec::with_capacity(requests.len());- for req in requests {+ for mut req in requests {+ // Defence-in-depth scrub at the batch boundary too.+ req.body = self.sanitizer.scrub(&req.body);+ if let Some(t) = req.title.take() {+ req.title = Some(self.sanitizer.scrub(&t));+ }let title = derive_title(&req.frontmatter, &req.body, &req.path);let markdown = Markdown {frontmatter: req.frontmatter.clone(),@@ -229,8 +248,16 @@ impl Wiki {title: explicit_title,} = req;+ // Defence-in-depth: scrub the body before we touch disk or the+ // store, regardless of caller. The hook ingress already scrubs+ // observation text; this catches LLM-rewritten consolidation+ // bodies, manual `write-page` CLI inputs, and anything an MCP+ // tool slips through.+ let body = self.sanitizer.scrub(&body);+let title = explicit_title.clone()+ .map(|t| self.sanitizer.scrub(&t)).unwrap_or_else(|| derive_title(&frontmatter, &body, &path));let markdown = Markdown {frontmatter: frontmatter.clone(),@@ -378,6 +405,71 @@ mod tests {assert!(hits[0].snippet.contains("compile"));}+ /// Defence-in-depth: anything that reaches `write_page` gets+ /// scrubbed at the wiki boundary, even if upstream callers (LLM+ /// consolidation output, manual `write-page` CLI input, MCP tool+ /// args) skipped the hook-ingress sanitizer.+ #[tokio::test]+ async fn write_page_scrubs_secrets_at_the_wiki_boundary() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();++ let body = "we agreed to use ANTHROPIC_API_KEY=sk-ant-leak-1234567890abcdef \+ and the canary id sk-canary-LEAK_ME_PLEASE_xxxxxxxxxxxx — see \+ postgres://admin:[email protected]/prod for details";+ wiki.write_page(req(+ ws,+ proj,+ "notes/leaky.md",+ body,+ serde_json::json!({ "title": "leaky" }),+ ))+ .await+ .unwrap();++ let on_disk = std::fs::read_to_string(tmp.path().join("wiki/notes/leaky.md")).unwrap();+ // The on-disk page must not contain any of the planted+ // secrets; each should have been replaced with [REDACTED].+ assert!(+ on_disk.contains("[REDACTED]"),+ "expected redaction in: {on_disk}"+ );+ assert!(+ !on_disk.contains("sk-ant-leak"),+ "anthropic key leaked: {on_disk}"+ );+ assert!(+ !on_disk.contains("LEAK_ME_PLEASE"),+ "canary leaked: {on_disk}"+ );+ assert!(+ !on_disk.contains("hunter2"),+ "DB password leaked: {on_disk}"+ );++ // The store-indexed body must also be scrubbed (so FTS5 + the+ // MCP query path never surface the raw secret either).+ let hits = store+ .reader+ .search_pages("REDACTED".into(), 5)+ .await+ .unwrap();+ assert_eq!(hits.len(), 1);+ assert!(!hits[0].snippet.contains("sk-ant-leak"));+ assert!(!hits[0].snippet.contains("hunter2"));+ }+#[tokio::test]async fn apply_batch_persists_all_pages_in_one_transaction() {let tmp = TempDir::new().unwrap();