Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
M4: cross-agent handoff + Codex/OpenCode hook bundles
AkitaOnRailsc384b536e929
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 3b0f20fb..e75962aa 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -121,6 +121,10 @@ pub struct RestoreArgs {pub enum AgentChoice {/// Anthropic Claude Code.ClaudeCode,+ /// OpenAI Codex CLI.+ Codex,+ /// OpenCode (open-source coding agent).+ OpenCode,}/// Arguments for `install-hooks`.diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 20cfa7ad..2c768b6a 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -23,12 +23,33 @@ 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),+ AgentChoice::Codex => render_agent("codex", &hooks_dir, &args.server_url),+ AgentChoice::OpenCode => render_agent("opencode", &hooks_dir, &args.server_url),}}+fn render_agent(label: &str, hooks_dir: &Path, server_url: &str) -> Result<()> {+ println!("# {label} hook scripts (manual install — wire each to the matching event)");+ println!("# Hook scripts: {}", hooks_dir.display());+ println!("# AI-memory server URL: {server_url}");+ println!();+ for entry in std::fs::read_dir(hooks_dir)? {+ let entry = entry?;+ let p = entry.path();+ if p.is_file() && p.extension().is_some_and(|e| e == "sh") {+ println!("- {}", p.display());+ }+ }+ println!();+ println!("Set AI_MEMORY_HOOK_URL in each hook's environment to override the default.");+ Ok(())+}+fn resolve_hooks_dir(explicit: Option<&Path>, agent: AgentChoice) -> Result<PathBuf> {let sub = match agent {AgentChoice::ClaudeCode => "claude-code",+ AgentChoice::Codex => "codex",+ AgentChoice::OpenCode => "opencode",};if let Some(p) = explicit {let path = p.join(sub);diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 02b29b1c..32b57eff 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -48,7 +48,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {Some(WatcherHandle::start(wiki.clone(), ws, proj)?)};- let server = AiMemoryServer::new(store.reader.clone());+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj);match args.transport {TransportKind::Stdio => {diff --git a/crates/ai-memory-core/src/handoff.rs b/crates/ai-memory-core/src/handoff.rsnew file mode 100644index 00000000..268de0e4--- /dev/null+++ b/crates/ai-memory-core/src/handoff.rs@@ -0,0 +1,116 @@+//! Cross-agent handoff type.+//!+//! A handoff is a typed snapshot of "where we are" — created when one+//! agent CLI ends a session, accepted when the next one starts in the+//! same project. Stored explicitly (vs. inferring from the+//! observations log) because cross-agent continuity is the project's+//! headline feature and deserves a first-class schema.++use std::path::PathBuf;++use jiff::Timestamp;+use serde::{Deserialize, Serialize};++use crate::ids::{AgentKind, HandoffId, ProjectId, SessionId, WorkspaceId};++/// State machine of a single handoff row.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum HandoffState {+ /// Created, not yet picked up by the next agent.+ Open,+ /// Another agent has called `memory_handoff_accept` on it.+ Accepted,+ /// Aged out (decay sweep).+ Expired,+}++impl HandoffState {+ /// Canonical wire string.+ #[must_use]+ pub const fn as_str(&self) -> &'static str {+ match self {+ Self::Open => "open",+ Self::Accepted => "accepted",+ Self::Expired => "expired",+ }+ }+}++impl std::str::FromStr for HandoffState {+ type Err = crate::MemoryError;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "open" => Ok(Self::Open),+ "accepted" => Ok(Self::Accepted),+ "expired" => Ok(Self::Expired),+ other => Err(crate::MemoryError::MalformedRecord(format!(+ "unknown handoff state: {other}"+ ))),+ }+ }+}++/// Input for inserting a new handoff.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct NewHandoff {+ /// Owning workspace.+ pub workspace_id: WorkspaceId,+ /// Owning project.+ pub project_id: ProjectId,+ /// Session this handoff captures (None for manual handoffs).+ pub from_session_id: Option<SessionId>,+ /// Agent CLI that produced this handoff.+ pub from_agent: AgentKind,+ /// Optional explicit target hint (`claude-code`, `codex`, …).+ pub to_agent: Option<AgentKind>,+ /// Working directory at handoff time. Used to match the next+ /// session's `memory_handoff_accept` call.+ pub cwd: Option<PathBuf>,+ /// One-paragraph summary of where we left off.+ pub summary: String,+ /// Open questions for the next agent.+ pub open_questions: Vec<String>,+ /// Suggested next steps.+ pub next_steps: Vec<String>,+ /// Files touched in the session.+ pub files_touched: Vec<String>,+}++/// Materialised view of a handoff row.+#[derive(Debug, Clone, Serialize)]+pub struct Handoff {+ /// Stable identifier.+ pub id: HandoffId,+ /// Owning workspace.+ pub workspace_id: WorkspaceId,+ /// Owning project.+ pub project_id: ProjectId,+ /// Session that produced this handoff, if any.+ pub from_session_id: Option<SessionId>,+ /// Agent CLI that produced this handoff.+ pub from_agent: AgentKind,+ /// Optional target hint.+ pub to_agent: Option<AgentKind>,+ /// Working directory at handoff time.+ pub cwd: Option<String>,+ /// Summary.+ pub summary: String,+ /// Open questions.+ pub open_questions: Vec<String>,+ /// Next steps.+ pub next_steps: Vec<String>,+ /// Files touched.+ pub files_touched: Vec<String>,+ /// State.+ pub state: HandoffState,+ /// Creation timestamp.+ pub created_at: Timestamp,+ /// Agent CLI that accepted, if any.+ pub accepted_by: Option<AgentKind>,+ /// Acceptance timestamp.+ pub accepted_at: Option<Timestamp>,+ /// Session that accepted, if any.+ pub accepted_by_session: Option<SessionId>,+}diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 183fe425..ae092bb9 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -81,6 +81,7 @@ id_newtype!(pub ProjectId, "Project identifier (middle of the 3-tuple).");id_newtype!(pub SessionId, "Identifier for a single agent run.");id_newtype!(pub ObservationId, "Identifier for a single observation captured during a session.");id_newtype!(pub PageId, "Identifier for a single wiki page version.");+id_newtype!(pub HandoffId, "Identifier for a cross-agent handoff record.");/// Relative path of a page within the wiki tree.///diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 5ad37dfc..b2e0b2b2 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -5,11 +5,15 @@//! 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 use error::{MemoryError, MemoryResult};-pub use ids::{AgentKind, ObservationId, PageId, PagePath, ProjectId, SessionId, WorkspaceId};+pub use handoff::{Handoff, HandoffState, NewHandoff};+pub use ids::{+ AgentKind, HandoffId, 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-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 556a22aa..b42ca274 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -10,7 +10,10 @@use std::str::FromStr;use std::sync::Arc;-use ai_memory_core::{AgentKind, NewObservation, NewSession, ProjectId, SessionId, WorkspaceId};+use ai_memory_core::{+ AgentKind, NewHandoff, NewObservation, NewSession, ObservationKind, ProjectId, SessionId,+ WorkspaceId,+};use ai_memory_store::WriterHandle;use ai_memory_wiki::Wiki;use axum::Json;@@ -115,7 +118,8 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {warn!(error = %e, "log.md append failed");}- // On SessionEnd, synthesize the summary page and end the session.+ // On SessionEnd, synthesize the summary page, end the session, and+ // auto-create a handoff so the next agent can pick up.if matches!(env.event, HookEvent::SessionEnd) {let observations = state.reader.observations_for_session(session_id).await?;let new_page = synthesize_session_page(@@ -124,8 +128,6 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {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 {@@ -139,10 +141,14 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {}).await?;state.writer.end_session(session_id, Some(page_id)).await?;+ let handoff =+ build_auto_handoff(state, env.agent, session_id, env.cwd.clone(), &observations);+ let handoff_id = state.writer.insert_handoff(handoff).await?;info!(session = %session_id,page = %new_page.path,- "session ended; synthesized summary page",+ handoff = %handoff_id,+ "session ended; summary page + open handoff created",);}@@ -166,6 +172,65 @@ fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {anyhow::bail!("hook payload missing session_id and event is not session-start")}+fn build_auto_handoff(+ state: &HookState,+ from_agent: AgentKind,+ session_id: SessionId,+ cwd: Option<String>,+ observations: &[ai_memory_core::Observation],+) -> NewHandoff {+ let mut prompts: Vec<&str> = Vec::new();+ let mut tools: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();+ for obs in observations {+ match obs.kind {+ ObservationKind::UserPrompt if !obs.title.is_empty() => prompts.push(&obs.title),+ ObservationKind::PostToolUse | ObservationKind::PreToolUse if !obs.title.is_empty() => {+ tools.insert(&obs.title);+ }+ _ => {}+ }+ }+ let last_prompt = prompts.last().copied();+ let summary = match (prompts.first().copied(), last_prompt) {+ (Some(first), Some(last)) if first == last => format!("Session focused on: {first}"),+ (Some(first), Some(last)) => format!("Started: {first}. Last: {last}."),+ (Some(first), None) => format!("Started: {first}."),+ _ => format!(+ "Session ended; {} observations recorded.",+ observations.len()+ ),+ };+ let open_questions = if prompts.is_empty() {+ Vec::new()+ } else {+ // Heuristic: last user prompt often *is* the open question.+ vec![format!(+ "Continue from: {}",+ last_prompt.unwrap_or_default()+ )]+ };+ let next_steps = if tools.is_empty() {+ Vec::new()+ } else {+ vec![format!(+ "Tools used: {}",+ tools.into_iter().collect::<Vec<_>>().join(", ")+ )]+ };+ NewHandoff {+ workspace_id: state.workspace_id,+ project_id: state.project_id,+ from_session_id: Some(session_id),+ from_agent,+ to_agent: None,+ cwd: cwd.map(std::path::PathBuf::from),+ summary,+ open_questions,+ next_steps,+ files_touched: Vec::new(),+ }+}+const fn importance_for(event: HookEvent) -> u8 {match event {HookEvent::SessionStart | HookEvent::SessionEnd => 7,diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex c29926ad..ac7c92d8 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -1,6 +1,7 @@//! [`AiMemoryServer`] — the MCP server skeleton + tool router.-use ai_memory_store::ReaderPool;+use ai_memory_core::{AgentKind, NewHandoff, ProjectId, WorkspaceId};+use ai_memory_store::{ReaderPool, WriterHandle};use rmcp::handler::server::router::tool::ToolRouter;use rmcp::handler::server::wrapper::Parameters;use rmcp::model::{@@ -21,6 +22,9 @@ automatically via hooks and the watcher.";#[derive(Clone)]pub struct AiMemoryServer {reader: ReaderPool,+ writer: WriterHandle,+ workspace_id: WorkspaceId,+ project_id: ProjectId,default_limit: usize,// Read by the `#[tool_handler]` macro expansion; rustc's dead-code// analysis can't see that, so the lint must be allowed explicitly.@@ -55,13 +59,48 @@ struct StatusResponse {counts: ai_memory_store::StatusCounts,}+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]+struct HandoffBeginArgs {+ /// Short prose summary of where the session left off.+ summary: String,+ /// Questions the next agent should resolve.+ #[serde(default)]+ open_questions: Vec<String>,+ /// Suggested next steps.+ #[serde(default)]+ next_steps: Vec<String>,+ /// Files touched during the session.+ #[serde(default)]+ files_touched: Vec<String>,+ /// Working directory at the time of handoff. Used to match the+ /// next agent's `memory_handoff_accept` call.+ #[serde(default)]+ cwd: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]+struct HandoffAcceptArgs {+ /// Restrict the search to handoffs created for a specific cwd.+ #[serde(default)]+ cwd: Option<String>,+}+#[tool_router]impl AiMemoryServer {- /// Construct a server backed by the given reader pool.+ /// Construct a server backed by the given reader/writer + 3-tuple+ /// identity coordinates.#[must_use]- pub fn new(reader: ReaderPool) -> Self {+ pub fn new(+ reader: ReaderPool,+ writer: WriterHandle,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ ) -> Self {Self {reader,+ writer,+ workspace_id,+ project_id,default_limit: 10,tool_router: Self::tool_router(),}@@ -105,6 +144,61 @@ impl AiMemoryServer {ok_json(&response)}+ /// Create a handoff snapshot for the next agent CLI.+ #[tool(description = "Record a cross-agent handoff snapshot. Call this \+ before quitting one CLI so the next one (e.g. Codex picking up \+ after Claude Code) can fetch context via memory_handoff_accept. \+ Use cwd to scope the handoff to a specific working directory.")]+ async fn memory_handoff_begin(+ &self,+ Parameters(args): Parameters<HandoffBeginArgs>,+ ) -> Result<CallToolResult, McpError> {+ let handoff = NewHandoff {+ workspace_id: self.workspace_id,+ project_id: self.project_id,+ from_session_id: None,+ 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,+ };+ let id = self+ .writer+ .insert_handoff(handoff)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ ok_json(&serde_json::json!({ "handoff_id": id.to_string() }))+ }++ /// Fetch the latest open handoff for this project (optionally filtered+ /// by cwd) and mark it accepted.+ #[tool(description = "Fetch the latest open handoff for this project \+ and mark it accepted. Returns the summary + open questions + next \+ steps so the agent can prepend them to the session context.")]+ async fn memory_handoff_accept(+ &self,+ Parameters(args): Parameters<HandoffAcceptArgs>,+ ) -> Result<CallToolResult, McpError> {+ let handoff = self+ .reader+ .latest_open_handoff(self.workspace_id, self.project_id, args.cwd)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ match handoff {+ None => ok_json(&serde_json::json!({ "handoff": null })),+ Some(h) => {+ self.writer+ .accept_handoff(h.id, AgentKind::Other, None)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ ok_json(&serde_json::json!({ "handoff": h }))+ }+ }+ }+/// Report aggregate counts (pages, sessions, observations).#[tool(description = "Report aggregate memory counts and runtime status \(pages latest, pages all versions, sessions, observations). \@@ -150,7 +244,7 @@ mod tests {use ai_memory_store::Store;use tempfile::TempDir;- async fn setup_server() -> (TempDir, Store, AiMemoryServer) {+ async fn setup_server() -> (TempDir, Store, AiMemoryServer, WorkspaceId, ProjectId) {let tmp = TempDir::new().unwrap();let store = Store::open(tmp.path()).unwrap();let ws = store@@ -178,18 +272,18 @@ mod tests {.await.unwrap();- let server = AiMemoryServer::new(store.reader.clone());- (tmp, store, server)+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj);+ (tmp, store, server, ws, proj)}#[tokio::test]async fn server_constructs_with_tool_router() {- let (_tmp, _store, _server) = setup_server().await;+ let (_tmp, _store, _server, _ws, _pj) = setup_server().await;}#[tokio::test]async fn memory_query_returns_hits_via_tool_method() {- let (_tmp, _store, server) = setup_server().await;+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;let result = server.memory_query(Parameters(QueryArgs {query: "karpathy".into(),@@ -206,7 +300,7 @@ mod tests {#[tokio::test]async fn memory_status_returns_counts() {- let (_tmp, _store, server) = setup_server().await;+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;let result = server.memory_status().await.unwrap();let text = result.content@@ -219,7 +313,7 @@ mod tests {#[tokio::test]async fn memory_recent_returns_one_hit() {- let (_tmp, _store, server) = setup_server().await;+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;let result = server.memory_recent(Parameters(RecentArgs { limit: Some(5) })).await@@ -232,4 +326,57 @@ mod tests {.unwrap();assert!(text.contains("foo.md"), "expected hit; got {text}");}++ #[tokio::test]+ async fn handoff_begin_then_accept_round_trips() {+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;+ let begin = server+ .memory_handoff_begin(Parameters(HandoffBeginArgs {+ summary: "left mid-refactor of writer actor".into(),+ open_questions: vec!["what max channel size?".into()],+ next_steps: vec!["finish supersession path".into()],+ files_touched: vec!["crates/ai-memory-store/src/writer.rs".into()],+ cwd: Some("/tmp/aim".into()),+ }))+ .await+ .unwrap();+ let begin_text = begin+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(begin_text.contains("handoff_id"));++ // Accepting with matching cwd returns the handoff.+ let accept = server+ .memory_handoff_accept(Parameters(HandoffAcceptArgs {+ cwd: Some("/tmp/aim".into()),+ }))+ .await+ .unwrap();+ let accept_text = accept+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(accept_text.contains("left mid-refactor"));+ assert!(accept_text.contains("what max channel size?"));++ // Second accept returns null (handoff is now accepted).+ let again = server+ .memory_handoff_accept(Parameters(HandoffAcceptArgs {+ cwd: Some("/tmp/aim".into()),+ }))+ .await+ .unwrap();+ let again_text = again+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(again_text.contains("\"handoff\": null"));+ }}diff --git a/crates/ai-memory-store/migrations/V02__handoffs.sql b/crates/ai-memory-store/migrations/V02__handoffs.sqlnew file mode 100644index 00000000..17b6223a--- /dev/null+++ b/crates/ai-memory-store/migrations/V02__handoffs.sql@@ -0,0 +1,33 @@+-- Handoff table. A handoff is a typed snapshot of "where we are" so+-- the next agent CLI can pick up. Created on SessionEnd (auto) or+-- explicitly via the memory_handoff_begin MCP tool. Accepted by the+-- next agent via memory_handoff_accept.++CREATE TABLE handoffs (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ from_session_id BLOB, -- references sessions(id), nullable for manual ones+ from_agent TEXT NOT NULL,+ to_agent TEXT, -- optional target hint+ cwd TEXT,+ summary TEXT NOT NULL,+ open_questions TEXT NOT NULL DEFAULT '[]', -- JSON array of strings+ next_steps TEXT NOT NULL DEFAULT '[]',+ files_touched TEXT NOT NULL DEFAULT '[]',+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open','accepted','expired')),+ created_at INTEGER NOT NULL,+ accepted_by TEXT,+ accepted_at INTEGER,+ accepted_by_session BLOB,+ FOREIGN KEY (from_session_id) REFERENCES sessions(id) ON DELETE SET NULL,+ FOREIGN KEY (accepted_by_session) REFERENCES sessions(id) ON DELETE SET NULL+);++CREATE INDEX idx_handoffs_open_recent+ ON handoffs(workspace_id, project_id, created_at DESC)+ WHERE state = 'open';++CREATE INDEX idx_handoffs_cwd_open+ ON handoffs(workspace_id, project_id, cwd, created_at DESC)+ WHERE state = 'open';diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 49aaec99..26d70447 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -5,8 +5,8 @@//! [`crate::writer`]).use ai_memory_core::{- AgentKind, NewObservation, NewPage, NewSession, ObservationId, ObservationKind, PageId,- SessionId,+ AgentKind, HandoffId, NewHandoff, NewObservation, NewPage, NewSession, ObservationId,+ ObservationKind, PageId, SessionId,};use jiff::Timestamp;use rusqlite::{Connection, OptionalExtension, params};@@ -257,6 +257,59 @@ pub fn insert_observation(Ok(id)}+/// Insert a new handoff in state=open.+pub fn insert_handoff(conn: &mut Connection, h: &NewHandoff) -> StoreResult<HandoffId> {+ let id = HandoffId::new();+ let now = Timestamp::now().as_microsecond();+ let open_q = serde_json::to_string(&h.open_questions)?;+ let next_s = serde_json::to_string(&h.next_steps)?;+ let files = serde_json::to_string(&h.files_touched)?;+ let from_session: Option<&[u8]> = h.from_session_id.as_ref().map(|s| &s.as_bytes()[..]);+ let cwd: Option<String> = h.cwd.as_ref().map(|p| p.to_string_lossy().into_owned());+ let from_agent = agent_kind_as_str(h.from_agent);+ let to_agent = h.to_agent.map(agent_kind_as_str);+ conn.execute(+ "INSERT INTO handoffs \+ (id, workspace_id, project_id, from_session_id, from_agent, to_agent, cwd, summary, \+ open_questions, next_steps, files_touched, state, created_at) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'open', ?12)",+ params![+ id.as_bytes(),+ h.workspace_id.as_bytes(),+ h.project_id.as_bytes(),+ from_session,+ from_agent,+ to_agent,+ cwd,+ h.summary,+ open_q,+ next_s,+ files,+ now,+ ],+ )?;+ Ok(id)+}++/// Mark a handoff accepted by `accepting_agent` / `accepting_session`.+pub fn accept_handoff(+ conn: &mut Connection,+ handoff_id: &HandoffId,+ accepting_agent: AgentKind,+ accepting_session: Option<&SessionId>,+) -> StoreResult<()> {+ let now = Timestamp::now().as_microsecond();+ let agent = agent_kind_as_str(accepting_agent);+ let session: Option<&[u8]> = accepting_session.map(|s| &s.as_bytes()[..]);+ conn.execute(+ "UPDATE handoffs SET state = 'accepted', accepted_by = ?1, accepted_at = ?2, \+ accepted_by_session = ?3 \+ WHERE id = ?4 AND state = 'open'",+ params![agent, now, session, handoff_id.as_bytes()],+ )?;+ Ok(())+}+fn agent_kind_as_str(kind: AgentKind) -> &'static str {match kind {AgentKind::ClaudeCode => "claude-code",diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 1617a174..0b170e63 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -10,8 +10,8 @@ use std::path::{Path, PathBuf};use std::sync::Arc;use ai_memory_core::{- Observation, ObservationId, ObservationKind, PageId, PagePath, ProjectId, SessionId,- WorkspaceId,+ AgentKind, Handoff, HandoffId, HandoffState, Observation, ObservationId, ObservationKind,+ PageId, PagePath, ProjectId, SessionId, WorkspaceId,};use parking_lot::Mutex;use rusqlite::{Connection, OpenFlags, OptionalExtension, params};@@ -211,6 +211,77 @@ impl ReaderPool {.await}+ /// Return the latest open handoff for the project, optionally+ /// filtered to a specific `cwd`.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn latest_open_handoff(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ cwd_filter: Option<String>,+ ) -> StoreResult<Option<Handoff>> {+ self.with_conn(move |conn| {+ let mut stmt: rusqlite::Statement<'_> = if let Some(_cwd) = cwd_filter.as_deref() {+ conn.prepare(+ "SELECT id, workspace_id, project_id, from_session_id, from_agent, to_agent, \+ cwd, summary, open_questions, next_steps, files_touched, state, \+ created_at, accepted_by, accepted_at, accepted_by_session \+ FROM handoffs \+ WHERE workspace_id = ?1 AND project_id = ?2 AND cwd = ?3 \+ AND state = 'open' \+ ORDER BY created_at DESC LIMIT 1",+ )?+ } else {+ conn.prepare(+ "SELECT id, workspace_id, project_id, from_session_id, from_agent, to_agent, \+ cwd, summary, open_questions, next_steps, files_touched, state, \+ created_at, accepted_by, accepted_at, accepted_by_session \+ FROM handoffs \+ WHERE workspace_id = ?1 AND project_id = ?2 AND state = 'open' \+ ORDER BY created_at DESC LIMIT 1",+ )?+ };+ let row_opt = if let Some(c) = cwd_filter.as_deref() {+ stmt.query_row(+ params![workspace_id.as_bytes(), project_id.as_bytes(), c],+ row_to_handoff,+ )+ .optional()?+ } else {+ stmt.query_row(+ params![workspace_id.as_bytes(), project_id.as_bytes()],+ row_to_handoff,+ )+ .optional()?+ };+ row_opt.transpose()+ })+ .await+ }++ /// Look up a handoff by id.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn handoff_by_id(&self, handoff_id: HandoffId) -> StoreResult<Option<Handoff>> {+ self.with_conn(move |conn| {+ let row = conn+ .query_row(+ "SELECT id, workspace_id, project_id, from_session_id, from_agent, to_agent, \+ cwd, summary, open_questions, next_steps, files_touched, state, \+ created_at, accepted_by, accepted_at, accepted_by_session \+ FROM handoffs WHERE id = ?1",+ params![handoff_id.as_bytes()],+ row_to_handoff,+ )+ .optional()?;+ row.transpose()+ })+ .await+ }+/// Snapshot the database to `dest_path` using SQLite's online backup/// API. The source DB stays writable for the duration of the copy.///@@ -300,6 +371,113 @@ fn materialise_observation(})}+fn row_to_handoff(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<Handoff>> {+ let id_bytes: Vec<u8> = row.get(0)?;+ let ws_bytes: Vec<u8> = row.get(1)?;+ let pj_bytes: Vec<u8> = row.get(2)?;+ let from_session_bytes: Option<Vec<u8>> = row.get(3)?;+ let from_agent: String = row.get(4)?;+ let to_agent: Option<String> = row.get(5)?;+ let cwd: Option<String> = row.get(6)?;+ let summary: String = row.get(7)?;+ let open_q_json: String = row.get(8)?;+ let next_s_json: String = row.get(9)?;+ let files_json: String = row.get(10)?;+ let state: String = row.get(11)?;+ let created_us: i64 = row.get(12)?;+ let accepted_by: Option<String> = row.get(13)?;+ let accepted_at_us: Option<i64> = row.get(14)?;+ let accepted_by_session_bytes: Option<Vec<u8>> = row.get(15)?;+ Ok(materialise_handoff(+ id_bytes,+ ws_bytes,+ pj_bytes,+ from_session_bytes,+ from_agent,+ to_agent,+ cwd,+ summary,+ open_q_json,+ next_s_json,+ files_json,+ state,+ created_us,+ accepted_by,+ accepted_at_us,+ accepted_by_session_bytes,+ ))+}++#[allow(clippy::too_many_arguments)]+fn materialise_handoff(+ id_bytes: Vec<u8>,+ ws_bytes: Vec<u8>,+ pj_bytes: Vec<u8>,+ from_session_bytes: Option<Vec<u8>>,+ from_agent: String,+ to_agent: Option<String>,+ cwd: Option<String>,+ summary: String,+ open_q_json: String,+ next_s_json: String,+ files_json: String,+ state: String,+ created_us: i64,+ accepted_by: Option<String>,+ accepted_at_us: Option<i64>,+ accepted_by_session_bytes: Option<Vec<u8>>,+) -> StoreResult<Handoff> {+ let open_questions: Vec<String> = serde_json::from_str(&open_q_json)?;+ let next_steps: Vec<String> = serde_json::from_str(&next_s_json)?;+ let files_touched: Vec<String> = serde_json::from_str(&files_json)?;+ let from_session = from_session_bytes+ .as_deref()+ .map(SessionId::from_slice)+ .transpose()?;+ let accepted_session = accepted_by_session_bytes+ .as_deref()+ .map(SessionId::from_slice)+ .transpose()?;+ Ok(Handoff {+ id: HandoffId::from_slice(&id_bytes)?,+ workspace_id: WorkspaceId::from_slice(&ws_bytes)?,+ project_id: ProjectId::from_slice(&pj_bytes)?,+ from_session_id: from_session,+ from_agent: parse_agent(&from_agent),+ to_agent: to_agent.as_deref().map(parse_agent),+ cwd,+ summary,+ open_questions,+ next_steps,+ files_touched,+ state: state.parse::<HandoffState>().map_err(StoreError::from)?,+ created_at: jiff::Timestamp::from_microsecond(created_us).map_err(|e| {+ StoreError::Memory(ai_memory_core::MemoryError::MalformedRecord(format!(+ "bad created_at: {e}"+ )))+ })?,+ accepted_by: accepted_by.as_deref().map(parse_agent),+ accepted_at: accepted_at_us+ .map(jiff::Timestamp::from_microsecond)+ .transpose()+ .map_err(|e| {+ StoreError::Memory(ai_memory_core::MemoryError::MalformedRecord(format!(+ "bad accepted_at: {e}"+ )))+ })?,+ accepted_by_session: accepted_session,+ })+}++fn parse_agent(s: &str) -> AgentKind {+ match s {+ "claude-code" => AgentKind::ClaudeCode,+ "codex" => AgentKind::Codex,+ "open-code" => AgentKind::OpenCode,+ _ => AgentKind::Other,+ }+}+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.rsindex 16f6f37e..bb17836a 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -11,7 +11,8 @@ use std::sync::{Arc, Mutex};use std::thread::{self, JoinHandle};use ai_memory_core::{- NewObservation, NewPage, NewSession, ObservationId, PageId, ProjectId, SessionId, WorkspaceId,+ AgentKind, HandoffId, NewHandoff, NewObservation, NewPage, NewSession, ObservationId, PageId,+ ProjectId, SessionId, WorkspaceId,};use rusqlite::Connection;use tokio::sync::{mpsc, oneshot};@@ -48,6 +49,16 @@ pub(crate) enum WriteCmd {obs: NewObservation,reply: oneshot::Sender<StoreResult<ObservationId>>,},+ InsertHandoff {+ handoff: NewHandoff,+ reply: oneshot::Sender<StoreResult<HandoffId>>,+ },+ AcceptHandoff {+ handoff_id: HandoffId,+ accepting_agent: AgentKind,+ accepting_session: Option<SessionId>,+ reply: oneshot::Sender<StoreResult<()>>,+ },Shutdown,}@@ -161,6 +172,38 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Insert a new handoff in `open` state.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.+ pub async fn insert_handoff(&self, handoff: NewHandoff) -> StoreResult<HandoffId> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::InsertHandoff { handoff, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Mark a handoff accepted by the given agent / session.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.+ pub async fn accept_handoff(+ &self,+ handoff_id: HandoffId,+ accepting_agent: AgentKind,+ accepting_session: Option<SessionId>,+ ) -> StoreResult<()> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::AcceptHandoff {+ handoff_id,+ accepting_agent,+ accepting_session,+ 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).///@@ -233,6 +276,24 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = ops::insert_observation(&mut conn, &obs);let _ = reply.send(result);}+ WriteCmd::InsertHandoff { handoff, reply } => {+ let result = ops::insert_handoff(&mut conn, &handoff);+ let _ = reply.send(result);+ }+ WriteCmd::AcceptHandoff {+ handoff_id,+ accepting_agent,+ accepting_session,+ reply,+ } => {+ let result = ops::accept_handoff(+ &mut conn,+ &handoff_id,+ accepting_agent,+ accepting_session.as_ref(),+ );+ let _ = reply.send(result);+ }}}tracing::debug!("writer thread exiting cleanly");diff --git a/hooks/codex/post-tool-use.sh b/hooks/codex/post-tool-use.shnew file mode 100755index 00000000..88006c98--- /dev/null+++ b/hooks/codex/post-tool-use.sh@@ -0,0 +1,8 @@+#!/bin/sh+# codex post-tool-use 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=codex" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/codex/pre-compact.sh b/hooks/codex/pre-compact.shnew file mode 100755index 00000000..3ccda804--- /dev/null+++ b/hooks/codex/pre-compact.sh@@ -0,0 +1,8 @@+#!/bin/sh+# codex pre-compact 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=codex" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/codex/pre-tool-use.sh b/hooks/codex/pre-tool-use.shnew file mode 100755index 00000000..a7087b5d--- /dev/null+++ b/hooks/codex/pre-tool-use.sh@@ -0,0 +1,8 @@+#!/bin/sh+# codex pre-tool-use 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=codex" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/codex/session-end.sh b/hooks/codex/session-end.shnew file mode 100755index 00000000..1f805c80--- /dev/null+++ b/hooks/codex/session-end.sh@@ -0,0 +1,8 @@+#!/bin/sh+# codex session-end hook.+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=codex" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/codex/session-start.sh b/hooks/codex/session-start.shnew file mode 100755index 00000000..2873c4c3--- /dev/null+++ b/hooks/codex/session-start.sh@@ -0,0 +1,8 @@+#!/bin/sh+# codex session-start hook.+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=codex" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/codex/stop.sh b/hooks/codex/stop.shnew file mode 100755index 00000000..e85ca8de--- /dev/null+++ b/hooks/codex/stop.sh@@ -0,0 +1,8 @@+#!/bin/sh+# codex stop hook.+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:7777}"+curl -s --max-time 0.5 \+ -X POST "$SERVER/hook?event=stop&agent=codex" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/codex/user-prompt-submit.sh b/hooks/codex/user-prompt-submit.shnew file mode 100755index 00000000..bda90a9a--- /dev/null+++ b/hooks/codex/user-prompt-submit.sh@@ -0,0 +1,8 @@+#!/bin/sh+# codex user-prompt-submit 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=codex" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/opencode/post-tool-use.sh b/hooks/opencode/post-tool-use.shnew file mode 100755index 00000000..6dfec34f--- /dev/null+++ b/hooks/opencode/post-tool-use.sh@@ -0,0 +1,8 @@+#!/bin/sh+# opencode post-tool-use 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=open-code" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/opencode/pre-compact.sh b/hooks/opencode/pre-compact.shnew file mode 100755index 00000000..664ea9e3--- /dev/null+++ b/hooks/opencode/pre-compact.sh@@ -0,0 +1,8 @@+#!/bin/sh+# opencode pre-compact 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=open-code" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/opencode/pre-tool-use.sh b/hooks/opencode/pre-tool-use.shnew file mode 100755index 00000000..0270f7c0--- /dev/null+++ b/hooks/opencode/pre-tool-use.sh@@ -0,0 +1,8 @@+#!/bin/sh+# opencode pre-tool-use 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=open-code" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/opencode/session-end.sh b/hooks/opencode/session-end.shnew file mode 100755index 00000000..0138ccee--- /dev/null+++ b/hooks/opencode/session-end.sh@@ -0,0 +1,8 @@+#!/bin/sh+# opencode session-end hook.+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=open-code" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/opencode/session-start.sh b/hooks/opencode/session-start.shnew file mode 100755index 00000000..3a635031--- /dev/null+++ b/hooks/opencode/session-start.sh@@ -0,0 +1,8 @@+#!/bin/sh+# opencode session-start hook.+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=open-code" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/opencode/stop.sh b/hooks/opencode/stop.shnew file mode 100755index 00000000..7efc1c9b--- /dev/null+++ b/hooks/opencode/stop.sh@@ -0,0 +1,8 @@+#!/bin/sh+# opencode stop hook.+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:7777}"+curl -s --max-time 0.5 \+ -X POST "$SERVER/hook?event=stop&agent=open-code" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0diff --git a/hooks/opencode/user-prompt-submit.sh b/hooks/opencode/user-prompt-submit.shnew file mode 100755index 00000000..0277da2e--- /dev/null+++ b/hooks/opencode/user-prompt-submit.sh@@ -0,0 +1,8 @@+#!/bin/sh+# opencode user-prompt-submit 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=open-code" \+ -H "Content-Type: application/json" \+ --data-binary @- >/dev/null 2>&1 || true+exit 0