Skip to content

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

Rust

M3: hooks crate + auto-capture (synthetic, no-LLM)

AkitaOnRails747c32d50f82
diff --git a/Cargo.lock b/Cargo.lock
index d305c2d8..65d96268 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -34,6 +34,7 @@ name = "ai-memory-cli"
version = "0.1.0"
dependencies = [
"ai-memory-core",
+ "ai-memory-hooks",
"ai-memory-mcp",
"ai-memory-store",
"ai-memory-wiki",
@@ -79,6 +80,19 @@ name = "ai-memory-hooks"
version = "0.1.0"
dependencies = [
"ai-memory-core",
+ "ai-memory-store",
+ "ai-memory-wiki",
+ "anyhow",
+ "axum",
+ "jiff",
+ "regex",
+ "serde",
+ "serde_json",
+ "tempfile",
+ "thiserror 2.0.18",
+ "tokio",
+ "tracing",
+ "uuid",
]
[[package]]
@@ -1934,6 +1948,12 @@ dependencies = [
"unsafe-libyaml",
]
+[[package]]
+name = "sha1_smol"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
+
[[package]]
name = "sha2"
version = "0.10.9"
@@ -2467,6 +2487,7 @@ dependencies = [
"getrandom 0.4.2",
"js-sys",
"serde_core",
+ "sha1_smol",
"wasm-bindgen",
]
diff --git a/Cargo.toml b/Cargo.toml
index 3a4c5695..f6c18640 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -29,6 +29,8 @@ ai-memory-hooks = { path = "crates/ai-memory-hooks", version = "0.1.0" }
ai-memory-llm = { path = "crates/ai-memory-llm", version = "0.1.0" }
ai-memory-consolidate = { path = "crates/ai-memory-consolidate", version = "0.1.0" }
+# (Workspace shared deps follow below)
+
# Error handling.
anyhow = "1"
thiserror = "2"
@@ -49,7 +51,7 @@ tracing-appender = "0.2"
# Time & IDs.
jiff = { version = "0.2", features = ["serde"] }
-uuid = { version = "1", features = ["v4", "v7", "serde"] }
+uuid = { version = "1", features = ["v4", "v5", "v7", "serde"] }
# Config & CLI.
figment = { version = "0.10", features = ["toml", "env"] }
@@ -79,6 +81,9 @@ axum = "0.8"
tar = "0.4"
flate2 = "1"
+# Text munging / hook payload sanitisation.
+regex = "1"
+
# Testing.
tempfile = "3"
diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.toml
index 6b00a5ca..d49398a1 100644
--- a/crates/ai-memory-cli/Cargo.toml
+++ b/crates/ai-memory-cli/Cargo.toml
@@ -14,6 +14,7 @@ path = "src/main.rs"
[dependencies]
ai-memory-core.workspace = true
+ai-memory-hooks.workspace = true
ai-memory-mcp.workspace = true
ai-memory-store.workspace = true
ai-memory-wiki.workspace = true
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 71921865..3b0f20fb 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -45,6 +45,8 @@ pub enum Command {
Backup(BackupArgs),
/// Restore a backup tarball into the data directory.
Restore(RestoreArgs),
+ /// Print (or apply) lifecycle-hook configuration for an agent CLI.
+ InstallHooks(InstallHooksArgs),
}
/// Arguments for `init`.
@@ -114,6 +116,28 @@ pub struct RestoreArgs {
pub force: bool,
}
+/// Agent CLI to install hooks for.
+#[derive(Debug, Clone, Copy, clap::ValueEnum)]
+pub enum AgentChoice {
+ /// Anthropic Claude Code.
+ ClaudeCode,
+}
+
+/// Arguments for `install-hooks`.
+#[derive(Debug, Args)]
+pub struct InstallHooksArgs {
+ /// Which agent's hooks to render.
+ #[arg(long, value_enum, default_value_t = AgentChoice::ClaudeCode)]
+ pub agent: AgentChoice,
+ /// Filesystem root that contains the vendored hook scripts (defaults
+ /// to the repo's `hooks/` if known, else `/usr/local/share/ai-memory/hooks`).
+ #[arg(long)]
+ pub hooks_dir: Option<PathBuf>,
+ /// Server URL the hooks will POST to.
+ #[arg(long, default_value = "http://127.0.0.1:7777")]
+ pub server_url: String,
+}
+
/// Transport for the MCP server.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum TransportKind {
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
new file mode 100644
index 00000000..20cfa7ad
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -0,0 +1,105 @@
+//! `ai-memory install-hooks` — print the suggested lifecycle-hook
+//! configuration for the chosen agent CLI.
+//!
+//! In M3 this is *non-destructive*: we render the JSON snippet the user
+//! should merge into their agent CLI's settings file, plus the absolute
+//! paths to the vendored shell scripts. We intentionally do not mutate
+//! `~/.claude/settings.json` automatically — agent CLI hook formats are
+//! still in flux and bad merges are very user-visible.
+
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result};
+use serde_json::json;
+
+use crate::cli::{AgentChoice, InstallHooksArgs};
+use crate::config::Config;
+
+/// Run the `install-hooks` subcommand.
+///
+/// # Errors
+/// Returns an error if the hook script directory cannot be located.
+pub fn run(_config: &Config, args: InstallHooksArgs) -> Result<()> {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ match args.agent {
+ AgentChoice::ClaudeCode => render_claude_code(&hooks_dir, &args.server_url),
+ }
+}
+
+fn resolve_hooks_dir(explicit: Option<&Path>, agent: AgentChoice) -> Result<PathBuf> {
+ let sub = match agent {
+ AgentChoice::ClaudeCode => "claude-code",
+ };
+ if let Some(p) = explicit {
+ let path = p.join(sub);
+ if path.is_dir() {
+ return Ok(path);
+ }
+ anyhow::bail!("hooks directory {} does not exist", path.display());
+ }
+
+ // Probe candidates in order. The first dir that exists wins.
+ let candidates: [PathBuf; 3] = [
+ // Cargo-run from the repo.
+ repo_root_guess()
+ .map(|r| r.join("hooks").join(sub))
+ .unwrap_or_default(),
+ // Docker image lays them out under /usr/local/share/ai-memory/.
+ PathBuf::from(format!("/usr/local/share/ai-memory/hooks/{sub}")),
+ // Local install honourable mention.
+ dirs::data_local_dir()
+ .map(|d| d.join("ai-memory/hooks").join(sub))
+ .unwrap_or_default(),
+ ];
+ for path in &candidates {
+ if !path.as_os_str().is_empty() && path.is_dir() {
+ return Ok(path.clone());
+ }
+ }
+ anyhow::bail!("could not locate hooks directory. Tried: {:?}", candidates,);
+}
+
+fn repo_root_guess() -> Option<PathBuf> {
+ // When the binary lives under target/{debug,release}/<name>, the
+ // workspace root is two parents up.
+ std::env::current_exe()
+ .ok()
+ .and_then(|p| p.parent()?.parent()?.parent().map(Path::to_path_buf))
+}
+
+fn render_claude_code(hooks_dir: &Path, server_url: &str) -> Result<()> {
+ let scripts: [(&str, &str); 7] = [
+ ("SessionStart", "session-start.sh"),
+ ("UserPromptSubmit", "user-prompt-submit.sh"),
+ ("PreToolUse", "pre-tool-use.sh"),
+ ("PostToolUse", "post-tool-use.sh"),
+ ("PreCompact", "pre-compact.sh"),
+ ("Stop", "stop.sh"),
+ ("SessionEnd", "session-end.sh"),
+ ];
+
+ let mut hooks_block = serde_json::Map::new();
+ for (event, script) in scripts {
+ let abs = hooks_dir.join(script);
+ if !abs.exists() {
+ anyhow::bail!("missing hook script: {}", abs.display());
+ }
+ hooks_block.insert(
+ event.into(),
+ json!([{
+ "command": abs.to_string_lossy().into_owned(),
+ "env": { "AI_MEMORY_HOOK_URL": server_url },
+ }]),
+ );
+ }
+ let payload = json!({ "hooks": hooks_block });
+
+ let serialized =
+ serde_json::to_string_pretty(&payload).context("serializing claude code hook config")?;
+ println!("# Claude Code hook config — merge into ~/.claude/settings.json");
+ println!("# Hook scripts: {}", hooks_dir.display());
+ println!("# AI-memory server URL: {server_url}");
+ println!();
+ println!("{serialized}");
+ Ok(())
+}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 3e94ffec..94745773 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -2,6 +2,7 @@
pub mod backup;
pub mod init;
+pub mod install_hooks;
pub mod reset;
pub mod restore;
pub mod search;
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 09f8f09b..02b29b1c 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -1,5 +1,6 @@
//! `ai-memory serve` — MCP server with optional filesystem watcher.
+use ai_memory_hooks::{HookState, hook_router};
use ai_memory_mcp::AiMemoryServer;
use ai_memory_store::Store;
use ai_memory_wiki::{WatcherHandle, Wiki};
@@ -59,16 +60,28 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
let bind = args.bind.unwrap_or_else(|| config.bind.clone());
let cancel = CancellationToken::new();
let server_clone = server.clone();
- let service = StreamableHttpService::new(
+ let mcp_service = StreamableHttpService::new(
move || Ok(server_clone.clone()),
LocalSessionManager::default().into(),
StreamableHttpServerConfig::default().with_cancellation_token(cancel.child_token()),
);
- let router = axum::Router::new().nest_service("/mcp", service);
+ let hooks = hook_router(HookState {
+ workspace_id: ws,
+ project_id: proj,
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki: wiki.clone(),
+ });
+ let router = axum::Router::new()
+ .nest_service("/mcp", mcp_service)
+ .merge(hooks);
let listener = tokio::net::TcpListener::bind(&bind)
.await
.with_context(|| format!("binding {bind}"))?;
- info!(%bind, "MCP HTTP server ready (POST /mcp, Ctrl-C to stop)");
+ info!(
+ %bind,
+ "MCP HTTP server ready (POST /mcp, POST /hook, Ctrl-C to stop)",
+ );
axum::serve(listener, router)
.with_graceful_shutdown(async move {
let _ = tokio::signal::ctrl_c().await;
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 258da7e7..e70835cb 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -46,5 +46,6 @@ async fn main() -> Result<()> {
Command::Reset(args) => commands::reset::run(&config, args),
Command::Backup(args) => commands::backup::run(&config, args).await,
Command::Restore(args) => commands::restore::run(&config, args),
+ Command::InstallHooks(args) => commands::install_hooks::run(&config, args),
}
}
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index e3816153..5ad37dfc 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -6,8 +6,10 @@
pub mod error;
pub mod ids;
+pub mod observation;
pub mod page;
pub use error::{MemoryError, MemoryResult};
pub use ids::{AgentKind, ObservationId, PageId, PagePath, ProjectId, SessionId, WorkspaceId};
+pub use observation::{NewObservation, NewSession, Observation, ObservationKind};
pub use page::{NewPage, Page, Tier};
diff --git a/crates/ai-memory-core/src/observation.rs b/crates/ai-memory-core/src/observation.rs
new file mode 100644
index 00000000..aeda8dbe
--- /dev/null
+++ b/crates/ai-memory-core/src/observation.rs
@@ -0,0 +1,168 @@
+//! Session and observation domain types.
+//!
+//! An *observation* is one ambient capture event from an agent CLI's
+//! lifecycle hook — a session start, a user prompt, a tool use, etc.
+//! Observations are the raw input to the consolidation pipeline; they
+//! are never user-facing.
+
+use std::path::PathBuf;
+
+use jiff::Timestamp;
+use serde::{Deserialize, Serialize};
+
+use crate::ids::{AgentKind, ObservationId, ProjectId, SessionId, WorkspaceId};
+
+/// Classification of a single observation, mirroring the headline
+/// Claude Code / Codex lifecycle hook events.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum ObservationKind {
+ /// Session began (cwd captured, agent identified).
+ SessionStart,
+ /// User submitted a prompt.
+ UserPrompt,
+ /// Agent is about to use a tool.
+ PreToolUse,
+ /// Agent finished using a tool.
+ PostToolUse,
+ /// Compaction event (context window pressure).
+ PreCompact,
+ /// Agent emitted a notification.
+ Notification,
+ /// Agent finished its turn.
+ Stop,
+ /// Session ended (final).
+ SessionEnd,
+ /// Anything else.
+ Other,
+}
+
+impl ObservationKind {
+ /// Canonical kebab-case string for storage and wire format.
+ #[must_use]
+ pub const fn as_str(&self) -> &'static str {
+ match self {
+ Self::SessionStart => "session-start",
+ Self::UserPrompt => "user-prompt",
+ Self::PreToolUse => "pre-tool-use",
+ Self::PostToolUse => "post-tool-use",
+ Self::PreCompact => "pre-compact",
+ Self::Notification => "notification",
+ Self::Stop => "stop",
+ Self::SessionEnd => "session-end",
+ Self::Other => "other",
+ }
+ }
+}
+
+impl std::str::FromStr for ObservationKind {
+ type Err = crate::MemoryError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s {
+ "session-start" | "session_start" | "SessionStart" => Ok(Self::SessionStart),
+ "user-prompt" | "user_prompt" | "UserPromptSubmit" => Ok(Self::UserPrompt),
+ "pre-tool-use" | "pre_tool_use" | "PreToolUse" => Ok(Self::PreToolUse),
+ "post-tool-use" | "post_tool_use" | "PostToolUse" => Ok(Self::PostToolUse),
+ "pre-compact" | "pre_compact" | "PreCompact" => Ok(Self::PreCompact),
+ "notification" | "Notification" => Ok(Self::Notification),
+ "stop" | "Stop" => Ok(Self::Stop),
+ "session-end" | "session_end" | "SessionEnd" => Ok(Self::SessionEnd),
+ "other" | "Other" => Ok(Self::Other),
+ _ => Err(crate::MemoryError::MalformedRecord(format!(
+ "unknown observation kind: {s}"
+ ))),
+ }
+ }
+}
+
+/// Input for inserting an observation.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct NewObservation {
+ /// Owning session.
+ pub session_id: SessionId,
+ /// Owning workspace.
+ pub workspace_id: WorkspaceId,
+ /// Owning project.
+ pub project_id: ProjectId,
+ /// Event classification.
+ pub kind: ObservationKind,
+ /// Short title (auto-derived from event when blank).
+ pub title: String,
+ /// Sanitised body (may include excerpts of prompts or tool I/O).
+ pub body: String,
+ /// 1..=10. Default 5.
+ pub importance: u8,
+}
+
+/// Materialised view of an observation row.
+#[derive(Clone, Debug)]
+pub struct Observation {
+ /// Unique identifier.
+ pub id: ObservationId,
+ /// Owning session.
+ pub session_id: SessionId,
+ /// Owning workspace.
+ pub workspace_id: WorkspaceId,
+ /// Owning project.
+ pub project_id: ProjectId,
+ /// Event classification.
+ pub kind: ObservationKind,
+ /// Short title.
+ pub title: String,
+ /// Sanitised body.
+ pub body: String,
+ /// 1..=10 importance.
+ pub importance: u8,
+ /// Wall-clock capture time.
+ pub created_at: Timestamp,
+}
+
+/// Input for beginning a session row.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct NewSession {
+ /// Session identifier (caller-provided, idempotent).
+ pub id: SessionId,
+ /// Owning workspace.
+ pub workspace_id: WorkspaceId,
+ /// Owning project.
+ pub project_id: ProjectId,
+ /// Which agent CLI is running this session.
+ pub agent_kind: AgentKind,
+ /// Working directory at session start.
+ pub cwd: Option<PathBuf>,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn observation_kind_round_trips() {
+ for k in [
+ ObservationKind::SessionStart,
+ ObservationKind::UserPrompt,
+ ObservationKind::PreToolUse,
+ ObservationKind::PostToolUse,
+ ObservationKind::PreCompact,
+ ObservationKind::Notification,
+ ObservationKind::Stop,
+ ObservationKind::SessionEnd,
+ ObservationKind::Other,
+ ] {
+ assert_eq!(k.as_str().parse::<ObservationKind>().unwrap(), k);
+ }
+ }
+
+ #[test]
+ fn observation_kind_accepts_snake_and_pascal() {
+ assert_eq!(
+ "PostToolUse".parse::<ObservationKind>().unwrap(),
+ ObservationKind::PostToolUse,
+ );
+ assert_eq!(
+ "session_start".parse::<ObservationKind>().unwrap(),
+ ObservationKind::SessionStart,
+ );
+ }
+}
diff --git a/crates/ai-memory-hooks/Cargo.toml b/crates/ai-memory-hooks/Cargo.toml
index 6abd7fd3..f28637c5 100644
--- a/crates/ai-memory-hooks/Cargo.toml
+++ b/crates/ai-memory-hooks/Cargo.toml
@@ -10,6 +10,21 @@ description = "Hook payload schemas, sanitisation, and HTTP ingress for agent li
[dependencies]
ai-memory-core.workspace = true
+ai-memory-store.workspace = true
+ai-memory-wiki.workspace = true
+anyhow.workspace = true
+thiserror.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+tokio.workspace = true
+tracing.workspace = true
+jiff.workspace = true
+uuid.workspace = true
+axum.workspace = true
+regex.workspace = true
+
+[dev-dependencies]
+tempfile.workspace = true
[lints]
workspace = true
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rs
index c4372ba8..5b659593 100644
--- a/crates/ai-memory-hooks/src/lib.rs
+++ b/crates/ai-memory-hooks/src/lib.rs
@@ -1,5 +1,29 @@
-//! Agent lifecycle hook plumbing.
+//! Agent lifecycle hook plumbing for ai-memory.
//!
-//! Typed payload schemas for Claude Code / Codex / OpenCode hook events,
-//! the `Sanitized<Observation>` boundary, and the HTTP ingress handler.
-//! Implementation lands in milestone M3.
+//! Wire flow:
+//!
+//! 1. The agent CLI (Claude Code, Codex, OpenCode) emits a lifecycle event
+//! JSON over stdin to one of the vendored hook scripts under `hooks/`.
+//! 2. The script `curl`s the JSON to `POST /hook?event=<kind>&agent=<kind>`
+//! on the running ai-memory server with a sub-second timeout. The
+//! script exits 0 unconditionally so the agent never blocks on us
+//! (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`].
+//!
+//! Privacy strip is a *typed* boundary: there is no way to write an
+//! observation without first passing through `Sanitized::new`.
+
+pub mod log;
+pub mod payload;
+pub mod router;
+pub mod sanitize;
+pub mod synth;
+
+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/log.rs b/crates/ai-memory-hooks/src/log.rs
new file mode 100644
index 00000000..b0f783e9
--- /dev/null
+++ b/crates/ai-memory-hooks/src/log.rs
@@ -0,0 +1,105 @@
+//! `log.md` append helper.
+//!
+//! The log is the chronological ledger Karpathy's gist insists on — a
+//! grep-able audit trail of "what happened, when". Lines use the exact
+//! prefix `## [YYYY-MM-DDTHH:MM:SSZ] <event> | <title>` so unix tools
+//! (`grep "^## \["`) can parse it without a markdown library.
+
+use std::io::Write;
+use std::path::Path;
+
+use jiff::{Timestamp, ToSpan, tz::TimeZone};
+use tracing::debug;
+
+use crate::payload::HookEvent;
+
+/// Append one line to `<wiki_root>/log.md`. POSIX `O_APPEND` writes of
+/// less than `PIPE_BUF` (4 KiB) are atomic, so concurrent appenders do
+/// not interleave.
+///
+/// # Errors
+/// Propagates any I/O failure from opening or writing the file.
+pub fn append_event(
+ wiki_root: &Path,
+ when: Timestamp,
+ event: HookEvent,
+ title: &str,
+) -> std::io::Result<()> {
+ let log_path = wiki_root.join("log.md");
+ let line = format_line(when, event, title);
+ debug!(path = %log_path.display(), bytes = line.len(), "appending log entry");
+
+ if let Some(parent) = log_path.parent()
+ && !parent.as_os_str().is_empty()
+ {
+ std::fs::create_dir_all(parent)?;
+ }
+ let mut file = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&log_path)?;
+ file.write_all(line.as_bytes())?;
+ file.sync_data()?;
+ Ok(())
+}
+
+fn format_line(when: Timestamp, event: HookEvent, title: &str) -> String {
+ let stamp = when.to_zoned(TimeZone::UTC).strftime("%Y-%m-%dT%H:%M:%SZ");
+ let kind = match event {
+ HookEvent::SessionStart => "session-start",
+ HookEvent::UserPrompt => "user-prompt",
+ HookEvent::PreToolUse => "pre-tool-use",
+ HookEvent::PostToolUse => "post-tool-use",
+ HookEvent::PreCompact => "pre-compact",
+ HookEvent::Notification => "notification",
+ HookEvent::Stop => "stop",
+ HookEvent::SessionEnd => "session-end",
+ HookEvent::Other => "other",
+ };
+ let one_line: String = title
+ .chars()
+ .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
+ .take(120)
+ .collect();
+ format!("## [{stamp}] {kind} | {one_line}\n")
+}
+
+#[allow(dead_code)] // Helper kept for parity with the original Karpathy CLAUDE.md grep pattern.
+fn now() -> Timestamp {
+ Timestamp::now() - 0.seconds()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use jiff::civil::DateTime;
+ use tempfile::TempDir;
+
+ #[test]
+ fn formats_line_with_expected_prefix() {
+ let when: Timestamp = DateTime::new(2026, 5, 21, 12, 34, 56, 0)
+ .unwrap()
+ .to_zoned(TimeZone::UTC)
+ .unwrap()
+ .timestamp();
+ let line = format_line(when, HookEvent::SessionStart, "hello world");
+ assert_eq!(
+ line,
+ "## [2026-05-21T12:34:56Z] session-start | hello world\n",
+ );
+ }
+
+ #[test]
+ fn append_creates_file_and_grows() {
+ let tmp = TempDir::new().unwrap();
+ let root = tmp.path();
+ let now = Timestamp::now();
+ append_event(root, now, HookEvent::SessionStart, "first").unwrap();
+ append_event(root, now, HookEvent::UserPrompt, "second").unwrap();
+ let contents = std::fs::read_to_string(root.join("log.md")).unwrap();
+ assert!(contents.contains("session-start | first"));
+ assert!(contents.contains("user-prompt | second"));
+ // Two lines.
+ assert_eq!(contents.matches("\n## [").count(), 1);
+ }
+}
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
new file mode 100644
index 00000000..008e2ac0
--- /dev/null
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -0,0 +1,232 @@
+//! Wire envelope received on `POST /hook`.
+
+use ai_memory_core::{AgentKind, ObservationKind};
+use serde::{Deserialize, Serialize};
+
+/// Query-string parameters on `POST /hook`.
+#[derive(Debug, Clone, Deserialize)]
+pub struct HookQuery {
+ /// Lifecycle event identifier (kebab-case or snake_case).
+ pub event: String,
+ /// Agent CLI identifier (`claude-code`, `codex`, `open-code`).
+ pub agent: Option<String>,
+}
+
+/// 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)]
+pub struct HookEnvelope {
+ /// Mapped lifecycle event.
+ pub event: HookEvent,
+ /// Agent CLI identifier.
+ pub agent: AgentKind,
+ /// Session identifier, if found in the body. Required for everything
+ /// except the initial `SessionStart`.
+ pub session_id: Option<String>,
+ /// Current working directory at the time of the event.
+ pub cwd: Option<String>,
+ /// Optional title hint extracted from the body.
+ pub title_hint: Option<String>,
+ /// Optional body excerpt extracted from the agent's raw payload.
+ pub body_excerpt: Option<String>,
+ /// The agent's raw JSON, kept for forensics.
+ pub raw: serde_json::Value,
+}
+
+/// Discriminator for the lifecycle event that triggered the hook.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum HookEvent {
+ /// New session started (capture cwd + model).
+ SessionStart,
+ /// User submitted a prompt.
+ UserPrompt,
+ /// Agent is about to call a tool.
+ PreToolUse,
+ /// Agent finished a tool call.
+ PostToolUse,
+ /// Compaction event (context window pressure).
+ PreCompact,
+ /// Agent emitted a notification.
+ Notification,
+ /// Agent finished its turn (interactive `/stop` or natural end).
+ Stop,
+ /// Session ended (final).
+ SessionEnd,
+ /// Anything else.
+ Other,
+}
+
+impl HookEvent {
+ /// Parse a kebab- or snake-case event identifier into [`HookEvent`].
+ #[must_use]
+ pub fn parse(s: &str) -> Self {
+ match s {
+ "session-start" | "session_start" | "SessionStart" => Self::SessionStart,
+ "user-prompt" | "user_prompt" | "UserPromptSubmit" => Self::UserPrompt,
+ "pre-tool-use" | "pre_tool_use" | "PreToolUse" => Self::PreToolUse,
+ "post-tool-use" | "post_tool_use" | "PostToolUse" => Self::PostToolUse,
+ "pre-compact" | "pre_compact" | "PreCompact" => Self::PreCompact,
+ "notification" | "Notification" => Self::Notification,
+ "stop" | "Stop" => Self::Stop,
+ "session-end" | "session_end" | "SessionEnd" => Self::SessionEnd,
+ _ => Self::Other,
+ }
+ }
+
+ /// Map to the storage-level [`ObservationKind`].
+ #[must_use]
+ pub const fn to_observation_kind(self) -> ObservationKind {
+ match self {
+ Self::SessionStart => ObservationKind::SessionStart,
+ Self::UserPrompt => ObservationKind::UserPrompt,
+ Self::PreToolUse => ObservationKind::PreToolUse,
+ Self::PostToolUse => ObservationKind::PostToolUse,
+ Self::PreCompact => ObservationKind::PreCompact,
+ Self::Notification => ObservationKind::Notification,
+ Self::Stop => ObservationKind::Stop,
+ Self::SessionEnd => ObservationKind::SessionEnd,
+ Self::Other => ObservationKind::Other,
+ }
+ }
+}
+
+/// Parse an agent identifier into [`AgentKind`]. Unknown values map to
+/// [`AgentKind::Other`].
+#[must_use]
+pub fn parse_agent(s: &str) -> AgentKind {
+ match s {
+ "claude-code" | "claude_code" | "claude" => AgentKind::ClaudeCode,
+ "codex" => AgentKind::Codex,
+ "open-code" | "opencode" => AgentKind::OpenCode,
+ _ => AgentKind::Other,
+ }
+}
+
+impl HookEnvelope {
+ /// Build an envelope from the parsed query + the body JSON. Performs
+ /// best-effort extraction of `session_id` / `cwd` / a body excerpt
+ /// from common shapes used by Claude Code, Codex, and OpenCode hook
+ /// payloads.
+ #[must_use]
+ pub fn from_query_and_body(query: HookQuery, raw: serde_json::Value) -> Self {
+ let event = HookEvent::parse(&query.event);
+ let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);
+ let session_id = extract_string(&raw, &["session_id", "sessionId", "session"]);
+ let cwd = extract_string(&raw, &["cwd", "current_dir", "working_dir"]);
+ let title_hint = best_title_hint(event, &raw);
+ let body_excerpt = best_body_excerpt(event, &raw);
+ Self {
+ event,
+ agent,
+ session_id,
+ cwd,
+ title_hint,
+ body_excerpt,
+ raw,
+ }
+ }
+}
+
+fn extract_string(value: &serde_json::Value, keys: &[&str]) -> Option<String> {
+ for key in keys {
+ if let Some(s) = value.get(*key).and_then(serde_json::Value::as_str)
+ && !s.is_empty()
+ {
+ return Some(s.to_string());
+ }
+ }
+ None
+}
+
+fn best_title_hint(event: HookEvent, raw: &serde_json::Value) -> Option<String> {
+ match event {
+ HookEvent::SessionStart => extract_string(raw, &["model", "title"]),
+ HookEvent::UserPrompt => {
+ extract_string(raw, &["prompt", "message", "text"]).map(|s| truncate_for_title(&s))
+ }
+ HookEvent::PreToolUse | HookEvent::PostToolUse => {
+ extract_string(raw, &["tool", "tool_name", "name"])
+ }
+ HookEvent::Notification => extract_string(raw, &["message", "text"]),
+ _ => None,
+ }
+}
+
+fn best_body_excerpt(event: HookEvent, raw: &serde_json::Value) -> Option<String> {
+ match event {
+ HookEvent::UserPrompt => extract_string(raw, &["prompt", "message", "text"]),
+ HookEvent::PostToolUse => {
+ let tool = extract_string(raw, &["tool", "tool_name", "name"])?;
+ let result = extract_string(raw, &["tool_response", "tool_output", "output", "result"])
+ .unwrap_or_else(|| "(no output captured)".into());
+ Some(format!("tool: {tool}\n---\n{}", truncate_excerpt(&result)))
+ }
+ HookEvent::Notification => extract_string(raw, &["message", "text"]),
+ _ => None,
+ }
+}
+
+fn truncate_for_title(s: &str) -> String {
+ const MAX: usize = 80;
+ let one_line: String = s.chars().take_while(|c| *c != '\n').collect();
+ if one_line.chars().count() <= MAX {
+ one_line
+ } else {
+ let mut buf: String = one_line.chars().take(MAX - 1).collect();
+ buf.push('…');
+ buf
+ }
+}
+
+fn truncate_excerpt(s: &str) -> String {
+ const MAX: usize = 2_000;
+ if s.len() <= MAX {
+ s.to_string()
+ } else {
+ let mut buf = String::with_capacity(MAX + 1);
+ buf.push_str(&s[..MAX]);
+ buf.push('…');
+ buf
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_known_events() {
+ assert_eq!(HookEvent::parse("session-start"), HookEvent::SessionStart);
+ assert_eq!(HookEvent::parse("PreToolUse"), HookEvent::PreToolUse);
+ assert_eq!(HookEvent::parse("user_prompt"), HookEvent::UserPrompt);
+ assert_eq!(HookEvent::parse("bogus"), HookEvent::Other);
+ }
+
+ #[test]
+ fn maps_to_observation_kind() {
+ assert_eq!(
+ HookEvent::SessionEnd.to_observation_kind(),
+ ObservationKind::SessionEnd
+ );
+ }
+
+ #[test]
+ fn envelope_extracts_session_and_cwd() {
+ let q = HookQuery {
+ event: "session-start".into(),
+ agent: Some("claude-code".into()),
+ };
+ let raw = serde_json::json!({
+ "session_id": "abc-123",
+ "cwd": "/tmp/x",
+ "model": "claude-sonnet-4-7"
+ });
+ let env = HookEnvelope::from_query_and_body(q, raw);
+ assert_eq!(env.event, HookEvent::SessionStart);
+ assert_eq!(env.session_id.as_deref(), Some("abc-123"));
+ assert_eq!(env.cwd.as_deref(), Some("/tmp/x"));
+ assert_eq!(env.title_hint.as_deref(), Some("claude-sonnet-4-7"));
+ }
+}
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
new file mode 100644
index 00000000..556a22aa
--- /dev/null
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -0,0 +1,180 @@
+//! axum router exposing `POST /hook`.
+//!
+//! Always returns 202 immediately. Heavy work (DB writes, session-page
+//! synthesis) happens *after* the response is sent — but we still
+//! `await` the writer ack to honour the cross-cutting invariant that
+//! "indexes commit in the same transaction as the data" (no
+//! background-task-indexing-after-return, basic-memory #763). The agent
+//! never blocks on us thanks to the fire-and-forget client side.
+
+use std::str::FromStr;
+use std::sync::Arc;
+
+use ai_memory_core::{AgentKind, NewObservation, NewSession, ProjectId, SessionId, WorkspaceId};
+use ai_memory_store::WriterHandle;
+use ai_memory_wiki::Wiki;
+use axum::Json;
+use axum::Router;
+use axum::extract::{Query, State};
+use axum::http::StatusCode;
+use axum::response::IntoResponse;
+use axum::routing::post;
+use jiff::Timestamp;
+use tracing::{info, warn};
+use uuid::Uuid;
+
+use crate::log;
+use crate::payload::{HookEnvelope, HookEvent, HookQuery};
+use crate::sanitize::Sanitized;
+use crate::synth::synthesize_session_page;
+
+/// Shared state passed to the hook handler.
+#[derive(Clone)]
+pub struct HookState {
+ /// Workspace these observations belong to.
+ pub workspace_id: WorkspaceId,
+ /// Project these observations belong to.
+ pub project_id: ProjectId,
+ /// Writer actor handle.
+ pub writer: WriterHandle,
+ /// Reader pool — needed for session-end synthesis.
+ pub reader: ai_memory_store::ReaderPool,
+ /// Wiki handle — used to write the session-summary page.
+ pub wiki: Wiki,
+}
+
+/// Build a router with the single `POST /hook` route mounted on the
+/// returned [`Router`].
+pub fn hook_router(state: HookState) -> Router {
+ Router::new()
+ .route("/hook", post(handle_hook))
+ .with_state(Arc::new(state))
+}
+
+async fn handle_hook(
+ State(state): State<Arc<HookState>>,
+ Query(query): Query<HookQuery>,
+ Json(body): Json<serde_json::Value>,
+) -> impl IntoResponse {
+ let env = HookEnvelope::from_query_and_body(query, body);
+ tokio::spawn(process_envelope(state.clone(), env));
+ (StatusCode::ACCEPTED, "queued")
+}
+
+async fn process_envelope(state: Arc<HookState>, env: HookEnvelope) {
+ if let Err(e) = process(&state, env).await {
+ warn!(error = %e, "hook processing failed");
+ }
+}
+
+async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {
+ let session_id = resolve_session_id(&env)?;
+
+ // Begin the session row if SessionStart, otherwise no-op (the
+ // `INSERT OR IGNORE` makes this safe).
+ if matches!(env.event, HookEvent::SessionStart) {
+ let new_session = NewSession {
+ id: session_id,
+ workspace_id: state.workspace_id,
+ project_id: state.project_id,
+ agent_kind: env.agent,
+ cwd: env.cwd.as_ref().map(std::path::PathBuf::from),
+ };
+ state.writer.begin_session(new_session).await?;
+ }
+
+ // Persist the observation row.
+ let kind = env.event.to_observation_kind();
+ let title = env
+ .title_hint
+ .clone()
+ .unwrap_or_else(|| kind.as_str().to_string());
+ let body = env.body_excerpt.clone().unwrap_or_default();
+ let raw_obs = NewObservation {
+ session_id,
+ workspace_id: state.workspace_id,
+ project_id: state.project_id,
+ kind,
+ title,
+ body,
+ importance: importance_for(env.event),
+ };
+ let sanitized = Sanitized::new(raw_obs);
+ let _ = state
+ .writer
+ .insert_observation(sanitized.inner().clone())
+ .await?;
+
+ // Append the log line.
+ if let Err(e) = log::append_event(
+ state.wiki.root(),
+ Timestamp::now(),
+ env.event,
+ sanitized.inner().title.as_str(),
+ ) {
+ warn!(error = %e, "log.md append failed");
+ }
+
+ // On SessionEnd, synthesize the summary page and end the session.
+ if matches!(env.event, HookEvent::SessionEnd) {
+ let observations = state.reader.observations_for_session(session_id).await?;
+ let new_page = synthesize_session_page(
+ state.workspace_id,
+ state.project_id,
+ session_id,
+ &observations,
+ );
+ // The wiki write_page method does the atomic file + store
+ // upsert in one go.
+ let page_id = state
+ .wiki
+ .write_page(ai_memory_wiki::WritePageRequest {
+ workspace_id: new_page.workspace_id,
+ project_id: new_page.project_id,
+ path: new_page.path.clone(),
+ frontmatter: new_page.frontmatter_json.clone(),
+ body: new_page.body.clone(),
+ tier: new_page.tier,
+ pinned: new_page.pinned,
+ })
+ .await?;
+ state.writer.end_session(session_id, Some(page_id)).await?;
+ info!(
+ session = %session_id,
+ page = %new_page.path,
+ "session ended; synthesized summary page",
+ );
+ }
+
+ Ok(())
+}
+
+fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {
+ if let Some(raw) = &env.session_id {
+ // Accept either a UUID (canonical) or any string, hashing the
+ // latter to a deterministic UUID v5 so each agent's session id
+ // maps cleanly into our schema.
+ if let Ok(id) = SessionId::from_str(raw) {
+ return Ok(id);
+ }
+ let uuid = Uuid::new_v5(&Uuid::NAMESPACE_OID, raw.as_bytes());
+ return Ok(SessionId(uuid));
+ }
+ if matches!(env.event, HookEvent::SessionStart) {
+ return Ok(SessionId::new());
+ }
+ anyhow::bail!("hook payload missing session_id and event is not session-start")
+}
+
+const fn importance_for(event: HookEvent) -> u8 {
+ match event {
+ HookEvent::SessionStart | HookEvent::SessionEnd => 7,
+ HookEvent::UserPrompt => 8,
+ HookEvent::PostToolUse | HookEvent::PreToolUse => 5,
+ HookEvent::Stop | HookEvent::PreCompact => 6,
+ HookEvent::Notification | HookEvent::Other => 3,
+ }
+}
+
+#[allow(dead_code)]
+fn _agent_kind_marker(_k: AgentKind) {}
diff --git a/crates/ai-memory-hooks/src/sanitize.rs b/crates/ai-memory-hooks/src/sanitize.rs
new file mode 100644
index 00000000..f627d4f0
--- /dev/null
+++ b/crates/ai-memory-hooks/src/sanitize.rs
@@ -0,0 +1,134 @@
+//! 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-hooks/src/synth.rs b/crates/ai-memory-hooks/src/synth.rs
new file mode 100644
index 00000000..7e335f35
--- /dev/null
+++ b/crates/ai-memory-hooks/src/synth.rs
@@ -0,0 +1,184 @@
+//! Rule-based session-page synthesis (no LLM).
+//!
+//! At `SessionEnd` we already have N observation rows for the session.
+//! We turn them into a single markdown page under `wiki/sessions/<id>.md`
+//! using only deterministic heuristics: first-prompt as title, files
+//! touched, tool-call counts. Once the LLM provider lands in M6 we'll
+//! add an opt-in path that re-narrates the page.
+
+use std::collections::BTreeMap;
+
+use ai_memory_core::{
+ NewPage, Observation, ObservationKind, PagePath, ProjectId, SessionId, Tier, WorkspaceId,
+};
+use jiff::tz::TimeZone;
+
+/// Build a [`NewPage`] from the observations collected during a session.
+///
+/// The returned page is *always* under `sessions/<session-id>.md` so each
+/// session has a stable URL the user can bookmark.
+#[must_use]
+pub fn synthesize_session_page(
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ session_id: SessionId,
+ observations: &[Observation],
+) -> NewPage {
+ let title = derive_title(observations);
+ let body = render_body(session_id, observations, &title);
+ let path = PagePath::new(format!("sessions/{session_id}.md"))
+ .expect("hard-coded sessions/<uuid>.md is always valid");
+ NewPage {
+ workspace_id,
+ project_id,
+ path,
+ title: title.clone(),
+ body,
+ tier: Tier::Episodic,
+ frontmatter_json: serde_json::json!({
+ "title": title,
+ "session_id": session_id.to_string(),
+ "tier": "episodic",
+ }),
+ pinned: false,
+ }
+}
+
+fn derive_title(observations: &[Observation]) -> String {
+ for obs in observations {
+ if obs.kind == ObservationKind::UserPrompt && !obs.title.is_empty() {
+ return obs.title.clone();
+ }
+ }
+ for obs in observations {
+ if !obs.title.is_empty() {
+ return obs.title.clone();
+ }
+ }
+ "session".to_string()
+}
+
+fn render_body(session_id: SessionId, observations: &[Observation], title: &str) -> String {
+ let mut tool_counts: BTreeMap<&str, usize> = BTreeMap::new();
+ let mut prompts: Vec<&Observation> = Vec::new();
+ let mut start: Option<&Observation> = None;
+ let mut end: Option<&Observation> = None;
+
+ for obs in observations {
+ match obs.kind {
+ ObservationKind::SessionStart => start = Some(obs),
+ ObservationKind::SessionEnd => end = Some(obs),
+ ObservationKind::UserPrompt => prompts.push(obs),
+ ObservationKind::PostToolUse | ObservationKind::PreToolUse if !obs.title.is_empty() => {
+ *tool_counts.entry(obs.title.as_str()).or_insert(0) += 1;
+ }
+ _ => {}
+ }
+ }
+
+ let mut buf = String::with_capacity(2048);
+ buf.push_str(&format!("# {title}\n\n"));
+
+ buf.push_str("## Session metadata\n\n");
+ buf.push_str(&format!("- **session_id:** `{session_id}`\n"));
+ if let Some(s) = start {
+ buf.push_str(&format!("- **started_at:** {}\n", human_ts(&s.created_at),));
+ }
+ if let Some(e) = end {
+ buf.push_str(&format!("- **ended_at:** {}\n", human_ts(&e.created_at),));
+ }
+ buf.push_str(&format!("- **observations:** {}\n\n", observations.len()));
+
+ if !prompts.is_empty() {
+ buf.push_str("## Prompts\n\n");
+ for (i, p) in prompts.iter().enumerate() {
+ buf.push_str(&format!("{}. {}\n", i + 1, p.title));
+ }
+ buf.push('\n');
+ }
+
+ if !tool_counts.is_empty() {
+ buf.push_str("## Tool calls\n\n");
+ for (name, count) in &tool_counts {
+ buf.push_str(&format!("- `{name}`: {count}\n"));
+ }
+ buf.push('\n');
+ }
+
+ buf.push_str("## Raw observations\n\n");
+ for obs in observations {
+ buf.push_str(&format!(
+ "- `{}` @ {} — {}\n",
+ obs.kind.as_str(),
+ human_ts(&obs.created_at),
+ obs.title.chars().take(80).collect::<String>(),
+ ));
+ }
+
+ buf.push_str("\n_Synthesised by ai-memory (M3, no-LLM heuristic)._\n");
+ buf
+}
+
+fn human_ts(ts: &jiff::Timestamp) -> String {
+ ts.to_zoned(TimeZone::UTC)
+ .strftime("%Y-%m-%dT%H:%M:%SZ")
+ .to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ai_memory_core::{ObservationId, SessionId};
+ use jiff::Timestamp;
+
+ fn obs(kind: ObservationKind, title: &str) -> Observation {
+ Observation {
+ id: ObservationId::new(),
+ session_id: SessionId::new(),
+ workspace_id: WorkspaceId::new(),
+ project_id: ProjectId::new(),
+ kind,
+ title: title.into(),
+ body: String::new(),
+ importance: 5,
+ created_at: Timestamp::now(),
+ }
+ }
+
+ #[test]
+ fn title_falls_back_through_kinds() {
+ let no_prompt = vec![obs(ObservationKind::PostToolUse, "Edit")];
+ assert_eq!(derive_title(&no_prompt), "Edit");
+
+ let empty: Vec<Observation> = vec![];
+ assert_eq!(derive_title(&empty), "session");
+
+ let with_prompt = vec![
+ obs(ObservationKind::PostToolUse, "Edit"),
+ obs(ObservationKind::UserPrompt, "fix the auth bug"),
+ ];
+ assert_eq!(derive_title(&with_prompt), "fix the auth bug");
+ }
+
+ #[test]
+ fn body_includes_tool_counts_and_prompts() {
+ let observations = vec![
+ obs(ObservationKind::SessionStart, "session"),
+ obs(ObservationKind::UserPrompt, "build the thing"),
+ obs(ObservationKind::PostToolUse, "Edit"),
+ obs(ObservationKind::PostToolUse, "Edit"),
+ obs(ObservationKind::PostToolUse, "Bash"),
+ obs(ObservationKind::SessionEnd, "session"),
+ ];
+ let page = synthesize_session_page(
+ WorkspaceId::new(),
+ ProjectId::new(),
+ SessionId::new(),
+ &observations,
+ );
+ assert!(page.title.contains("build the thing"));
+ assert!(page.body.contains("`Edit`: 2"));
+ assert!(page.body.contains("`Bash`: 1"));
+ assert!(page.body.contains("build the thing"));
+ }
+}
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 98e74f1c..49aaec99 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -4,7 +4,10 @@
//! the writer thread would violate the single-writer invariant (see
//! [`crate::writer`]).
-use ai_memory_core::{NewPage, PageId};
+use ai_memory_core::{
+ AgentKind, NewObservation, NewPage, NewSession, ObservationId, ObservationKind, PageId,
+ SessionId,
+};
use jiff::Timestamp;
use rusqlite::{Connection, OptionalExtension, params};
use sha2::{Digest, Sha256};
@@ -184,6 +187,89 @@ pub fn get_or_create_project(
Ok(id)
}
+/// Begin (or re-affirm) a session row keyed on the caller-supplied id.
+/// Idempotent: a second call with the same id leaves the row untouched.
+pub fn begin_session(conn: &mut Connection, session: &NewSession) -> StoreResult<()> {
+ let now = Timestamp::now().as_microsecond();
+ let agent = agent_kind_as_str(session.agent_kind);
+ let cwd: Option<String> = session
+ .cwd
+ .as_ref()
+ .map(|p| p.to_string_lossy().into_owned());
+ conn.execute(
+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6) \
+ ON CONFLICT(id) DO NOTHING",
+ params![
+ session.id.as_bytes(),
+ session.workspace_id.as_bytes(),
+ session.project_id.as_bytes(),
+ agent,
+ cwd,
+ now,
+ ],
+ )?;
+ Ok(())
+}
+
+/// Stamp a session as ended, optionally linking the synthesised summary
+/// page.
+pub fn end_session(
+ conn: &mut Connection,
+ session_id: &SessionId,
+ summary_page_id: Option<&PageId>,
+) -> StoreResult<()> {
+ let now = Timestamp::now().as_microsecond();
+ let page_blob: Option<&[u8]> = summary_page_id.map(|p| &p.as_bytes()[..]);
+ conn.execute(
+ "UPDATE sessions SET ended_at = ?1, summary_page_id = ?2 WHERE id = ?3",
+ params![now, page_blob, session_id.as_bytes()],
+ )?;
+ Ok(())
+}
+
+/// Append a single observation. Caller is expected to have already
+/// inserted the parent session via [`begin_session`].
+pub fn insert_observation(
+ conn: &mut Connection,
+ obs: &NewObservation,
+) -> StoreResult<ObservationId> {
+ let id = ObservationId::new();
+ let now = Timestamp::now().as_microsecond();
+ let kind = observation_kind_as_str(obs.kind);
+ let importance: i64 = i64::from(obs.importance.clamp(1, 10));
+ conn.execute(
+ "INSERT INTO observations \
+ (id, session_id, workspace_id, project_id, kind, title, body, importance, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
+ params![
+ id.as_bytes(),
+ obs.session_id.as_bytes(),
+ obs.workspace_id.as_bytes(),
+ obs.project_id.as_bytes(),
+ kind,
+ obs.title,
+ obs.body,
+ importance,
+ now,
+ ],
+ )?;
+ Ok(id)
+}
+
+fn agent_kind_as_str(kind: AgentKind) -> &'static str {
+ match kind {
+ AgentKind::ClaudeCode => "claude-code",
+ AgentKind::Codex => "codex",
+ AgentKind::OpenCode => "open-code",
+ AgentKind::Other => "other",
+ }
+}
+
+fn observation_kind_as_str(kind: ObservationKind) -> &'static str {
+ kind.as_str()
+}
+
fn audit(
tx: &rusqlite::Transaction<'_>,
op: &str,
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 209809b5..1617a174 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -9,7 +9,10 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
-use ai_memory_core::{PageId, PagePath};
+use ai_memory_core::{
+ Observation, ObservationId, ObservationKind, PageId, PagePath, ProjectId, SessionId,
+ WorkspaceId,
+};
use parking_lot::Mutex;
use rusqlite::{Connection, OpenFlags, OptionalExtension, params};
use serde::Serialize;
@@ -181,6 +184,33 @@ impl ReaderPool {
.await
}
+ /// Return all observations for the given session, ordered by
+ /// `created_at` ascending.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn observations_for_session(
+ &self,
+ session_id: SessionId,
+ ) -> StoreResult<Vec<Observation>> {
+ self.with_conn(move |conn| {
+ let mut stmt = conn.prepare(
+ "SELECT id, session_id, workspace_id, project_id, kind, title, body, \
+ importance, created_at \
+ FROM observations \
+ WHERE session_id = ?1 \
+ ORDER BY created_at ASC",
+ )?;
+ let rows = stmt.query_map(params![session_id.as_bytes()], row_to_observation)?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r??);
+ }
+ Ok(out)
+ })
+ .await
+ }
+
/// Snapshot the database to `dest_path` using SQLite's online backup
/// API. The source DB stays writable for the duration of the copy.
///
@@ -215,6 +245,61 @@ impl ReaderPool {
}
}
+fn row_to_observation(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<Observation>> {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let session_bytes: Vec<u8> = row.get(1)?;
+ let workspace_bytes: Vec<u8> = row.get(2)?;
+ let project_bytes: Vec<u8> = row.get(3)?;
+ let kind_str: String = row.get(4)?;
+ let title: String = row.get(5)?;
+ let body: String = row.get(6)?;
+ let importance: i64 = row.get(7)?;
+ let created_us: i64 = row.get(8)?;
+ Ok(materialise_observation(
+ id_bytes,
+ session_bytes,
+ workspace_bytes,
+ project_bytes,
+ kind_str,
+ title,
+ body,
+ importance,
+ created_us,
+ ))
+}
+
+#[allow(clippy::too_many_arguments)]
+fn materialise_observation(
+ id_bytes: Vec<u8>,
+ session_bytes: Vec<u8>,
+ workspace_bytes: Vec<u8>,
+ project_bytes: Vec<u8>,
+ kind_str: String,
+ title: String,
+ body: String,
+ importance: i64,
+ created_us: i64,
+) -> StoreResult<Observation> {
+ Ok(Observation {
+ id: ObservationId::from_slice(&id_bytes)?,
+ session_id: SessionId::from_slice(&session_bytes)?,
+ workspace_id: WorkspaceId::from_slice(&workspace_bytes)?,
+ project_id: ProjectId::from_slice(&project_bytes)?,
+ kind: kind_str
+ .parse::<ObservationKind>()
+ .map_err(StoreError::from)?,
+ title,
+ body,
+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ importance: importance.clamp(1, 10) as u8,
+ created_at: jiff::Timestamp::from_microsecond(created_us).map_err(|e| {
+ StoreError::Memory(ai_memory_core::MemoryError::MalformedRecord(format!(
+ "bad timestamp: {e}"
+ )))
+ })?,
+ })
+}
+
fn count(conn: &Connection, sql: &str) -> StoreResult<u64> {
let n: Option<i64> = conn.query_row(sql, [], |row| row.get(0)).optional()?;
Ok(u64::try_from(n.unwrap_or(0)).unwrap_or(0))
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index e0fbf533..16f6f37e 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -10,7 +10,9 @@
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
-use ai_memory_core::{NewPage, PageId, ProjectId, WorkspaceId};
+use ai_memory_core::{
+ NewObservation, NewPage, NewSession, ObservationId, PageId, ProjectId, SessionId, WorkspaceId,
+};
use rusqlite::Connection;
use tokio::sync::{mpsc, oneshot};
@@ -33,6 +35,19 @@ pub(crate) enum WriteCmd {
page: NewPage,
reply: oneshot::Sender<StoreResult<PageId>>,
},
+ BeginSession {
+ session: NewSession,
+ reply: oneshot::Sender<StoreResult<()>>,
+ },
+ EndSession {
+ session_id: SessionId,
+ summary_page_id: Option<PageId>,
+ reply: oneshot::Sender<StoreResult<()>>,
+ },
+ InsertObservation {
+ obs: NewObservation,
+ reply: oneshot::Sender<StoreResult<ObservationId>>,
+ },
Shutdown,
}
@@ -105,6 +120,47 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Begin a session (idempotent on the supplied id).
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
+ pub async fn begin_session(&self, session: NewSession) -> StoreResult<()> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::BeginSession { session, reply: tx })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Mark a session ended, optionally linking its summary page.
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
+ pub async fn end_session(
+ &self,
+ session_id: SessionId,
+ summary_page_id: Option<PageId>,
+ ) -> StoreResult<()> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::EndSession {
+ session_id,
+ summary_page_id,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Append an observation row.
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
+ pub async fn insert_observation(&self, obs: NewObservation) -> StoreResult<ObservationId> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::InsertObservation { obs, reply: tx })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Upsert a page (creating it or superseding the existing latest
/// version when the body has changed).
///
@@ -161,6 +217,22 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = ops::upsert_page(&mut conn, &page);
let _ = reply.send(result);
}
+ WriteCmd::BeginSession { session, reply } => {
+ let result = ops::begin_session(&mut conn, &session);
+ let _ = reply.send(result);
+ }
+ WriteCmd::EndSession {
+ session_id,
+ summary_page_id,
+ reply,
+ } => {
+ let result = ops::end_session(&mut conn, &session_id, summary_page_id.as_ref());
+ let _ = reply.send(result);
+ }
+ WriteCmd::InsertObservation { obs, reply } => {
+ let result = ops::insert_observation(&mut conn, &obs);
+ let _ = reply.send(result);
+ }
}
}
tracing::debug!("writer thread exiting cleanly");
diff --git a/hooks/claude-code/post-tool-use.sh b/hooks/claude-code/post-tool-use.sh
new file mode 100755
index 00000000..53bf5643
--- /dev/null
+++ b/hooks/claude-code/post-tool-use.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+# Claude Code PostToolUse hook.
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:7777}"
+curl -s --max-time 0.5 \
+ -X POST "$SERVER/hook?event=post-tool-use&agent=claude-code" \
+ -H "Content-Type: application/json" \
+ --data-binary @- >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/claude-code/pre-compact.sh b/hooks/claude-code/pre-compact.sh
new file mode 100755
index 00000000..9696ea33
--- /dev/null
+++ b/hooks/claude-code/pre-compact.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+# Claude Code PreCompact hook.
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:7777}"
+curl -s --max-time 0.5 \
+ -X POST "$SERVER/hook?event=pre-compact&agent=claude-code" \
+ -H "Content-Type: application/json" \
+ --data-binary @- >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/claude-code/pre-tool-use.sh b/hooks/claude-code/pre-tool-use.sh
new file mode 100755
index 00000000..7b97351d
--- /dev/null
+++ b/hooks/claude-code/pre-tool-use.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+# Claude Code PreToolUse hook.
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:7777}"
+curl -s --max-time 0.5 \
+ -X POST "$SERVER/hook?event=pre-tool-use&agent=claude-code" \
+ -H "Content-Type: application/json" \
+ --data-binary @- >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/claude-code/session-end.sh b/hooks/claude-code/session-end.sh
new file mode 100755
index 00000000..3f79811d
--- /dev/null
+++ b/hooks/claude-code/session-end.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Claude Code SessionEnd hook (final).
+# We give the session-end hook a longer timeout because the server
+# synthesises a wiki page from the observation log here.
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:7777}"
+curl -s --max-time 2.0 \
+ -X POST "$SERVER/hook?event=session-end&agent=claude-code" \
+ -H "Content-Type: application/json" \
+ --data-binary @- >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/claude-code/session-start.sh b/hooks/claude-code/session-start.sh
new file mode 100755
index 00000000..e47618dc
--- /dev/null
+++ b/hooks/claude-code/session-start.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Claude Code SessionStart hook.
+# Reads the event JSON from stdin and forwards it to a running
+# ai-memory server. Fire-and-forget: never blocks the agent.
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:7777}"
+curl -s --max-time 0.5 \
+ -X POST "$SERVER/hook?event=session-start&agent=claude-code" \
+ -H "Content-Type: application/json" \
+ --data-binary @- >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/claude-code/stop.sh b/hooks/claude-code/stop.sh
new file mode 100755
index 00000000..ad6ef60d
--- /dev/null
+++ b/hooks/claude-code/stop.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+# Claude Code Stop hook (agent finished one turn).
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:7777}"
+curl -s --max-time 0.5 \
+ -X POST "$SERVER/hook?event=stop&agent=claude-code" \
+ -H "Content-Type: application/json" \
+ --data-binary @- >/dev/null 2>&1 || true
+exit 0
diff --git a/hooks/claude-code/user-prompt-submit.sh b/hooks/claude-code/user-prompt-submit.sh
new file mode 100755
index 00000000..f958bf6d
--- /dev/null
+++ b/hooks/claude-code/user-prompt-submit.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+# Claude Code UserPromptSubmit hook.
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:7777}"
+curl -s --max-time 0.5 \
+ -X POST "$SERVER/hook?event=user-prompt&agent=claude-code" \
+ -H "Content-Type: application/json" \
+ --data-binary @- >/dev/null 2>&1 || true
+exit 0