Skip to content

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

Rust

hooks: route observations to per-cwd project + add reorg migration

AkitaOnRailsfc8040875a0c
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 27365c9a..e6d45a9a 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -80,6 +80,19 @@ pub enum Command {
/// `<!-- ai-memory:end -->` markers so re-running replaces the
/// block in place without duplicating.
InstallInstructions(InstallInstructionsArgs),
+ /// Retro-fit existing sessions + observations to per-cwd projects
+ /// based on the cwd captured at session-start. Pages are marked
+ /// `is_latest=false` (they were a multi-project mash-up) so the
+ /// next consolidation can regenerate them per-project. Idempotent.
+ Reorg(ReorgArgs),
+}
+
+/// Arguments for `reorg`.
+#[derive(Debug, Args)]
+pub struct ReorgArgs {
+ /// Show what would change without writing.
+ #[arg(long)]
+ pub dry_run: bool,
}
/// Arguments for `install-instructions`.
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index a3d7cd80..ff0728a9 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -14,6 +14,7 @@ pub mod install_mcp;
pub mod lint;
pub mod llm_test;
pub mod render_shared;
+pub mod reorg;
pub mod reset;
pub mod restore;
pub mod search;
diff --git a/crates/ai-memory-cli/src/commands/reorg.rs b/crates/ai-memory-cli/src/commands/reorg.rs
new file mode 100644
index 00000000..bd939c61
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/reorg.rs
@@ -0,0 +1,393 @@
+//! `ai-memory reorg --by-cwd [--dry-run]`
+//!
+//! Retro-fits existing sessions + observations to per-cwd projects based
+//! on the `cwd` captured at session-start. Pages are graveyarded
+//! (`is_latest=0`) because they were synthesised as a mash-up across all
+//! sessions that used the old single-project bucket; a fresh consolidation
+//! will regenerate them cleanly per project. The operation is idempotent:
+//! sessions already in the right project are skipped.
+
+use ai_memory_core::{ProjectId, SessionId, WorkspaceId};
+use ai_memory_store::{Store, StoreError};
+use anyhow::Result;
+use tracing::info;
+
+use crate::cli::ReorgArgs;
+use crate::config::Config;
+
+/// A single entry in the reorg plan.
+#[derive(Debug)]
+struct PlanEntry {
+ session_id: SessionId,
+ new_project_id: ProjectId,
+ cwd: String,
+ project_name: String,
+}
+
+/// Run the `reorg` subcommand.
+///
+/// # Errors
+/// Returns an error if the store cannot be opened or if any SQL operation
+/// fails.
+pub async fn run(config: &Config, args: ReorgArgs) -> Result<()> {
+ let store = Store::open(&config.data_dir)?;
+
+ // Step 1: Ensure the `default` workspace exists (idempotent).
+ let ws = store.writer.get_or_create_workspace("default").await?;
+
+ // Step 2: Read all sessions with a non-NULL, non-empty cwd.
+ let sessions_with_cwd: Vec<(SessionId, ProjectId, String)> = store
+ .reader
+ .with_conn(move |conn| {
+ let mut stmt = conn.prepare(
+ "SELECT id, project_id, cwd \
+ FROM sessions \
+ WHERE cwd IS NOT NULL AND cwd != '' \
+ ORDER BY started_at",
+ )?;
+ let rows = stmt.query_map([], |row| {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let proj_bytes: Vec<u8> = row.get(1)?;
+ let cwd: String = row.get(2)?;
+ Ok((id_bytes, proj_bytes, cwd))
+ })?;
+ let mut out = Vec::new();
+ for r in rows {
+ let (id_bytes, proj_bytes, cwd) = r?;
+ // from_slice returns MemoryError; lift through StoreError.
+ let session_id = SessionId::from_slice(&id_bytes).map_err(StoreError::Memory)?;
+ let project_id = ProjectId::from_slice(&proj_bytes).map_err(StoreError::Memory)?;
+ out.push((session_id, project_id, cwd));
+ }
+ Ok(out)
+ })
+ .await?;
+
+ if sessions_with_cwd.is_empty() {
+ println!("No sessions with a cwd found; nothing to reorg.");
+ return Ok(());
+ }
+
+ // Step 3: Derive project_name = basename(cwd) for each session and
+ // resolve the target (workspace_id, project_id). Cache by cwd so we
+ // call get_or_create_project once per distinct path.
+ let mut cwd_to_proj: std::collections::HashMap<String, (WorkspaceId, ProjectId)> =
+ std::collections::HashMap::new();
+ for (_, _, cwd) in &sessions_with_cwd {
+ if cwd_to_proj.contains_key(cwd.as_str()) {
+ continue;
+ }
+ let project_name = std::path::Path::new(cwd.as_str())
+ .file_name()
+ .and_then(|s| s.to_str())
+ .filter(|s| !s.is_empty())
+ .map(str::to_string)
+ .unwrap_or_else(|| "unknown".to_string());
+ let proj = store
+ .writer
+ .get_or_create_project(ws, project_name, Some(cwd.clone()))
+ .await?;
+ cwd_to_proj.insert(cwd.clone(), (ws, proj));
+ }
+
+ // Step 4: Build the plan — only include sessions whose project_id
+ // differs from what it should be (idempotency).
+ let mut plan: Vec<PlanEntry> = Vec::new();
+ for (session_id, old_project_id, cwd) in &sessions_with_cwd {
+ let (_, new_project_id) = cwd_to_proj[cwd.as_str()];
+ if new_project_id == *old_project_id {
+ // Already in the right bucket.
+ continue;
+ }
+ let project_name = std::path::Path::new(cwd.as_str())
+ .file_name()
+ .and_then(|s| s.to_str())
+ .unwrap_or("unknown")
+ .to_string();
+ plan.push(PlanEntry {
+ session_id: *session_id,
+ new_project_id,
+ cwd: cwd.clone(),
+ project_name,
+ });
+ }
+
+ // Step 5: Dry-run: print the plan as a table and exit.
+ if args.dry_run || plan.is_empty() {
+ if plan.is_empty() {
+ println!("All sessions are already in the correct per-cwd project; nothing to do.");
+ } else {
+ println!("{} session(s) would be moved:\n", plan.len());
+ println!("{:<38} {:<20} cwd", "session_id", "new_project");
+ println!("{}", "-".repeat(80));
+ for e in &plan {
+ println!(
+ "{:<38} {:<20} {}",
+ e.session_id.to_string(),
+ e.project_name,
+ e.cwd,
+ );
+ }
+ println!("\n(dry-run; omit --dry-run to apply)");
+ }
+ return Ok(());
+ }
+
+ // Step 6: Execute in one transaction via the writer actor.
+ let writer_plan: Vec<(SessionId, ProjectId)> = plan
+ .iter()
+ .map(|e| (e.session_id, e.new_project_id))
+ .collect();
+ let summary = store.writer.reorg_sessions(writer_plan).await?;
+
+ // Count distinct new projects created (those with project_id not seen
+ // in the old bucket, i.e. all entries in cwd_to_proj whose project_id
+ // appears in the plan's new_project_id set).
+ let distinct_projects: std::collections::HashSet<ProjectId> =
+ plan.iter().map(|e| e.new_project_id).collect();
+
+ info!(
+ sessions_moved = summary.sessions_moved,
+ observations_updated = summary.observations_updated,
+ pages_graveyarded = summary.pages_graveyarded,
+ distinct_projects = distinct_projects.len(),
+ "reorg complete",
+ );
+ println!("Reorg complete:");
+ println!(" sessions moved: {}", summary.sessions_moved);
+ println!(" observations updated: {}", summary.observations_updated);
+ println!(" pages graveyarded: {}", summary.pages_graveyarded);
+ println!(" distinct new projects: {}", distinct_projects.len());
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ai_memory_core::{
+ AgentKind, NewObservation, NewPage, NewSession, ObservationKind, PagePath, Tier,
+ };
+ use ai_memory_store::Store;
+ use tempfile::TempDir;
+
+ /// Seed a store with two sessions in two different cwds plus some
+ /// observations and a page. After reorg the sessions + observations
+ /// must land in per-cwd projects and the page must be graveyarded.
+ #[tokio::test]
+ async fn reorg_moves_sessions_and_graveyards_pages() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+
+ // Create the initial "scratch" project (server default).
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let scratch = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+
+ // Session A — cwd=/home/user/project-alpha
+ let sid_a = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid_a,
+ workspace_id: ws,
+ project_id: scratch,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: Some(std::path::PathBuf::from("/home/user/project-alpha")),
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_observation(NewObservation {
+ session_id: sid_a,
+ workspace_id: ws,
+ project_id: scratch,
+ kind: ObservationKind::UserPrompt,
+ title: "hello alpha".into(),
+ body: "".into(),
+ importance: 5,
+ })
+ .await
+ .unwrap();
+
+ // Session B — cwd=/home/user/project-beta
+ let sid_b = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid_b,
+ workspace_id: ws,
+ project_id: scratch,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: Some(std::path::PathBuf::from("/home/user/project-beta")),
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_observation(NewObservation {
+ session_id: sid_b,
+ workspace_id: ws,
+ project_id: scratch,
+ kind: ObservationKind::UserPrompt,
+ title: "hello beta".into(),
+ body: "".into(),
+ importance: 5,
+ })
+ .await
+ .unwrap();
+
+ // Insert a mash-up page in the scratch project.
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: scratch,
+ path: PagePath::new("sessions/mash.md").unwrap(),
+ title: "Mash-up page".into(),
+ body: "multi-project content".into(),
+ tier: Tier::Episodic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ })
+ .await
+ .unwrap();
+
+ // Verify baseline: one is_latest page.
+ let counts_before = store.reader.status_counts().await.unwrap();
+ assert_eq!(counts_before.pages_latest, 1, "one page before reorg");
+
+ // Run reorg logic (not via CLI; call helpers directly).
+ let ws_id = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+
+ // Simulate what `run` does: read sessions, derive project names.
+ let sessions_with_cwd: Vec<(SessionId, ProjectId, String)> = store
+ .reader
+ .with_conn(move |conn| {
+ let mut stmt = conn.prepare(
+ "SELECT id, project_id, cwd FROM sessions \
+ WHERE cwd IS NOT NULL AND cwd != '' ORDER BY started_at",
+ )?;
+ let rows = stmt.query_map([], |row| {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let proj_bytes: Vec<u8> = row.get(1)?;
+ let cwd: String = row.get(2)?;
+ Ok((id_bytes, proj_bytes, cwd))
+ })?;
+ let mut out = Vec::new();
+ for r in rows {
+ let (id_bytes, proj_bytes, cwd) = r.unwrap();
+ let sid = SessionId::from_slice(&id_bytes).unwrap();
+ let pid = ProjectId::from_slice(&proj_bytes).unwrap();
+ out.push((sid, pid, cwd));
+ }
+ Ok(out)
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(sessions_with_cwd.len(), 2);
+
+ let mut cwd_to_proj: std::collections::HashMap<String, ProjectId> =
+ std::collections::HashMap::new();
+ for (_, _, cwd) in &sessions_with_cwd {
+ if cwd_to_proj.contains_key(cwd.as_str()) {
+ continue;
+ }
+ let name = std::path::Path::new(cwd.as_str())
+ .file_name()
+ .unwrap()
+ .to_str()
+ .unwrap()
+ .to_string();
+ let proj = store
+ .writer
+ .get_or_create_project(ws_id, name, Some(cwd.clone()))
+ .await
+ .unwrap();
+ cwd_to_proj.insert(cwd.clone(), proj);
+ }
+
+ let plan: Vec<(SessionId, ProjectId)> = sessions_with_cwd
+ .iter()
+ .filter_map(|(sid, old_pid, cwd)| {
+ let new_pid = cwd_to_proj[cwd.as_str()];
+ if new_pid != *old_pid {
+ Some((*sid, new_pid))
+ } else {
+ None
+ }
+ })
+ .collect();
+
+ assert_eq!(plan.len(), 2, "both sessions need moving");
+
+ let summary = store.writer.reorg_sessions(plan).await.unwrap();
+ assert_eq!(summary.sessions_moved, 2);
+ assert_eq!(summary.observations_updated, 2);
+ assert_eq!(summary.pages_graveyarded, 1);
+
+ // Pages should all be graveyarded (is_latest = 0).
+ let counts_after = store.reader.status_counts().await.unwrap();
+ assert_eq!(counts_after.pages_latest, 0, "page must be graveyarded");
+
+ // Sessions should now be in distinct projects.
+ let alpha_proj = cwd_to_proj["/home/user/project-alpha"];
+ let beta_proj = cwd_to_proj["/home/user/project-beta"];
+ assert_ne!(alpha_proj, beta_proj);
+
+ // Re-read sessions from DB and verify they carry the correct project.
+ // We piggy-back on the same read-sessions logic used by `run`.
+ let sessions_after: Vec<(SessionId, ProjectId, String)> = store
+ .reader
+ .with_conn(move |conn| {
+ let mut stmt = conn.prepare(
+ "SELECT id, project_id, cwd FROM sessions \
+ WHERE cwd IS NOT NULL AND cwd != '' ORDER BY started_at",
+ )?;
+ let rows = stmt.query_map([], |row| {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let proj_bytes: Vec<u8> = row.get(1)?;
+ let cwd: String = row.get(2)?;
+ Ok((id_bytes, proj_bytes, cwd))
+ })?;
+ let mut out = Vec::new();
+ for r in rows {
+ let (id_bytes, proj_bytes, cwd) = r?;
+ let sid = SessionId::from_slice(&id_bytes).map_err(StoreError::Memory)?;
+ let pid = ProjectId::from_slice(&proj_bytes).map_err(StoreError::Memory)?;
+ out.push((sid, pid, cwd));
+ }
+ Ok(out)
+ })
+ .await
+ .unwrap();
+
+ for (sid, pid, cwd) in &sessions_after {
+ let expected = cwd_to_proj[cwd.as_str()];
+ assert_eq!(
+ *pid, expected,
+ "session {sid} in cwd {cwd} should have project {expected:?}"
+ );
+ }
+ assert!(
+ sessions_after.iter().any(|(sid, _, _)| *sid == sid_a),
+ "session A present"
+ );
+ assert!(
+ sessions_after.iter().any(|(sid, _, _)| *sid == sid_b),
+ "session B present"
+ );
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 176978ba..5aa4dec6 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -168,6 +168,9 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
wiki: wiki.clone(),
consolidator: consolidator.clone(),
sanitizer: sanitizer.clone(),
+ project_cache: std::sync::Arc::new(tokio::sync::Mutex::new(
+ std::collections::HashMap::new(),
+ )),
});
// Build the auth state. Precedence (highest first):
// 1. AI_MEMORY_AUTH_TOKEN env var
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index f0b5575d..3efe8f29 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -58,5 +58,6 @@ async fn main() -> Result<()> {
Command::SetupAgent(args) => commands::setup_agent::run(&config, args),
Command::Bootstrap(args) => commands::bootstrap::run(&config, args).await,
Command::InstallInstructions(args) => commands::install_instructions::run(&config, args),
+ Command::Reorg(args) => commands::reorg::run(&config, args).await,
}
}
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 76036a62..8181b49a 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -7,6 +7,7 @@
//! background-task-indexing-after-return, basic-memory #763). The agent
//! never blocks on us thanks to the fire-and-forget client side.
+use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
@@ -35,9 +36,9 @@ use crate::synth::synthesize_session_page;
/// Shared state passed to the hook handler.
#[derive(Clone)]
pub struct HookState {
- /// Workspace these observations belong to.
+ /// Default workspace to use when a hook event lacks a `cwd` field.
pub workspace_id: WorkspaceId,
- /// Project these observations belong to.
+ /// Default project to use when a hook event lacks a `cwd` field.
pub project_id: ProjectId,
/// Writer actor handle.
pub writer: WriterHandle,
@@ -54,6 +55,11 @@ pub struct HookState {
/// the store. Same handle is also held by the wiki and consolidator
/// so scrubbing happens at every write boundary.
pub sanitizer: Sanitizer,
+ /// Cache of `cwd → (workspace_id, project_id)` resolved on first
+ /// sight. Avoids a SQLite round-trip for every hook event from the
+ /// same agent session. Keyed by the raw cwd string; no
+ /// canonicalisation — two symlinked paths are separate buckets.
+ pub project_cache: Arc<tokio::sync::Mutex<HashMap<String, (WorkspaceId, ProjectId)>>>,
}
/// Build a router with `POST /hook` (event ingress) and `GET /handoff`
@@ -115,9 +121,10 @@ async fn fetch_and_accept_handoff(
query: HandoffQuery,
) -> anyhow::Result<Option<String>> {
let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);
+ let (ws, proj) = resolve_project_ids(state, query.cwd.as_deref()).await?;
let handoff = state
.reader
- .latest_open_handoff(state.workspace_id, state.project_id, query.cwd)
+ .latest_open_handoff(ws, proj, query.cwd)
.await?;
let Some(h) = handoff else {
return Ok(None);
@@ -188,6 +195,52 @@ fn render_handoff_markdown(h: &Handoff) -> String {
buf
}
+/// Resolve the `(workspace_id, project_id)` pair for a hook event.
+///
+/// When `cwd` is present, derives `project_name = basename(cwd)` and
+/// upserts it under the `default` workspace (cached to avoid a SQLite
+/// round-trip per event). Falls back to the server's default IDs when
+/// `cwd` is `None` or empty.
+async fn resolve_project_ids(
+ state: &HookState,
+ cwd: Option<&str>,
+) -> anyhow::Result<(WorkspaceId, ProjectId)> {
+ let Some(cwd) = cwd.filter(|s| !s.is_empty()) else {
+ return Ok((state.workspace_id, state.project_id));
+ };
+ {
+ let cache = state.project_cache.lock().await;
+ if let Some(ids) = cache.get(cwd) {
+ return Ok(*ids);
+ }
+ }
+ let project_name = std::path::Path::new(cwd)
+ .file_name()
+ .and_then(|s| s.to_str())
+ .map(str::to_string)
+ .filter(|s| !s.is_empty())
+ // Defensive: if basename derivation fails (e.g. cwd is "/"),
+ // fall back to the server defaults rather than hard-erroring.
+ .ok_or_else(|| anyhow::anyhow!("could not derive project name from cwd {cwd:?}"))?;
+ let ws = state
+ .writer
+ .get_or_create_workspace("default".to_string())
+ .await
+ .map_err(|e| anyhow::anyhow!("get_or_create_workspace: {e}"))?;
+ let proj = state
+ .writer
+ .get_or_create_project(ws, project_name, Some(cwd.to_string()))
+ .await
+ .map_err(|e| anyhow::anyhow!("get_or_create_project: {e}"))?;
+ let ids = (ws, proj);
+ state
+ .project_cache
+ .lock()
+ .await
+ .insert(cwd.to_string(), ids);
+ Ok(ids)
+}
+
async fn process_envelope(state: Arc<HookState>, env: HookEnvelope) {
if let Err(e) = process(&state, env).await {
warn!(error = %e, "hook processing failed");
@@ -196,14 +249,15 @@ async fn process_envelope(state: Arc<HookState>, env: HookEnvelope) {
async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {
let session_id = resolve_session_id(&env)?;
+ let (ws, proj) = resolve_project_ids(state, env.cwd.as_deref()).await?;
// 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,
+ workspace_id: ws,
+ project_id: proj,
agent_kind: env.agent,
cwd: env.cwd.as_ref().map(std::path::PathBuf::from),
};
@@ -219,8 +273,8 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {
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,
+ workspace_id: ws,
+ project_id: proj,
kind,
title,
body,
@@ -247,7 +301,7 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {
// of context. Does NOT end the session and does NOT create a
// handoff. The eventual SessionEnd supersedes this page.
if matches!(env.event, HookEvent::PreCompact)
- && let Err(e) = consolidate_or_synth(state, session_id).await
+ && let Err(e) = consolidate_or_synth(state, session_id, ws, proj).await
{
warn!(error = %e, "PreCompact consolidation failed; continuing");
}
@@ -256,12 +310,7 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {
// 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(
- state.workspace_id,
- state.project_id,
- session_id,
- &observations,
- );
+ let new_page = synthesize_session_page(ws, proj, session_id, &observations);
let page_id = state
.wiki
.write_page(ai_memory_wiki::WritePageRequest {
@@ -276,8 +325,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 = build_auto_handoff(
+ ws,
+ proj,
+ env.agent,
+ session_id,
+ env.cwd.clone(),
+ &observations,
+ );
let handoff_id = state.writer.insert_handoff(handoff).await?;
// Auto-commit the wiki tree so the session/handoff/log.md
// changes land in git in one atomic snapshot.
@@ -320,7 +375,8 @@ fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {
}
fn build_auto_handoff(
- state: &HookState,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
from_agent: AgentKind,
session_id: SessionId,
cwd: Option<String>,
@@ -390,8 +446,8 @@ fn build_auto_handoff(
)]
};
NewHandoff {
- workspace_id: state.workspace_id,
- project_id: state.project_id,
+ workspace_id,
+ project_id,
from_session_id: Some(session_id),
from_agent,
to_agent: None,
@@ -406,7 +462,12 @@ fn build_auto_handoff(
/// Write a fresh `sessions/<id>.md` for the current session without
/// ending it. Used by the PreCompact branch to checkpoint state before
/// the agent's working context collapses.
-async fn consolidate_or_synth(state: &HookState, session_id: SessionId) -> anyhow::Result<()> {
+async fn consolidate_or_synth(
+ state: &HookState,
+ session_id: SessionId,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+) -> anyhow::Result<()> {
if let Some(c) = state.consolidator.as_ref() {
let outcome = c.consolidate_session(session_id, false).await?;
debug!(
@@ -424,12 +485,7 @@ async fn consolidate_or_synth(state: &HookState, session_id: SessionId) -> anyho
if observations.is_empty() {
return Ok(());
}
- let new_page = synthesize_session_page(
- state.workspace_id,
- state.project_id,
- session_id,
- &observations,
- );
+ let new_page = synthesize_session_page(workspace_id, project_id, session_id, &observations);
state
.wiki
.write_page(ai_memory_wiki::WritePageRequest {
@@ -464,3 +520,147 @@ const fn importance_for(event: HookEvent) -> u8 {
HookEvent::Notification | HookEvent::Other => 3,
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashMap;
+ use std::sync::Arc;
+
+ use ai_memory_core::Sanitizer;
+ use ai_memory_store::Store;
+ use ai_memory_wiki::Wiki;
+ use tempfile::TempDir;
+
+ use super::*;
+ use crate::payload::HookQuery;
+
+ /// Build a minimal `HookState` backed by a real on-disk store.
+ async fn make_state(tmp: &TempDir) -> HookState {
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let sanitizer = Sanitizer::default();
+ HookState {
+ workspace_id: ws,
+ project_id: proj,
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ consolidator: None,
+ sanitizer,
+ project_cache: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
+ }
+ }
+
+ /// Two hook events with distinct cwds must land in two distinct projects.
+ #[tokio::test]
+ async fn process_with_cwd_creates_new_project() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ // Event from /home/user/project-alpha.
+ let (ws_a, proj_a) = resolve_project_ids(&state, Some("/home/user/project-alpha"))
+ .await
+ .unwrap();
+ // Event from /home/user/project-beta.
+ let (ws_b, proj_b) = resolve_project_ids(&state, Some("/home/user/project-beta"))
+ .await
+ .unwrap();
+
+ // Projects must be distinct; workspace is the same (`default`).
+ assert_ne!(proj_a, proj_b, "different cwds → different projects");
+ assert_eq!(ws_a, ws_b, "same default workspace");
+
+ // Neither should match the server-default scratch project.
+ assert_ne!(proj_a, state.project_id);
+ assert_ne!(proj_b, state.project_id);
+ }
+
+ /// An event without a cwd must fall back to the server defaults.
+ #[tokio::test]
+ async fn process_with_missing_cwd_falls_back_to_state_defaults() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let (ws, proj) = resolve_project_ids(&state, None).await.unwrap();
+ assert_eq!(ws, state.workspace_id);
+ assert_eq!(proj, state.project_id);
+
+ // Likewise for an empty string.
+ let (ws2, proj2) = resolve_project_ids(&state, Some("")).await.unwrap();
+ assert_eq!(ws2, state.workspace_id);
+ assert_eq!(proj2, state.project_id);
+ }
+
+ /// A second call for the same cwd must hit the in-memory cache — no
+ /// additional `get_or_create_project` writes happen, proven by
+ /// inspecting the cache after both calls.
+ #[tokio::test]
+ async fn project_cache_hits_on_second_event() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let cwd = "/home/user/cached-project";
+
+ // First call — populates the cache.
+ let (_, proj_first) = resolve_project_ids(&state, Some(cwd)).await.unwrap();
+
+ // Inspect the cache: should have exactly one entry.
+ {
+ let cache = state.project_cache.lock().await;
+ assert_eq!(cache.len(), 1, "cache has one entry after first call");
+ assert!(cache.contains_key(cwd), "cache keyed by raw cwd");
+ }
+
+ // Second call — must return the same IDs from the cache.
+ let (_, proj_second) = resolve_project_ids(&state, Some(cwd)).await.unwrap();
+ assert_eq!(proj_first, proj_second, "cache must return identical IDs");
+
+ // Cache must still have exactly one entry (no duplicate insert).
+ {
+ let cache = state.project_cache.lock().await;
+ assert_eq!(cache.len(), 1, "no duplicate cache entries");
+ }
+ }
+
+ /// A hook event fires end-to-end through `process`. Validates that
+ /// the session + observation rows land in the resolved project, not
+ /// the server-default scratch project.
+ #[tokio::test]
+ async fn process_routes_observation_to_cwd_project() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "session-start".into(),
+ agent: Some("claude-code".into()),
+ },
+ serde_json::json!({
+ "session_id": "test-session-cwd-routing",
+ "cwd": "/home/user/my-project",
+ }),
+ );
+
+ process(&state, env).await.unwrap();
+
+ // The observation must be in the project derived from the cwd,
+ // not in the server-default `scratch` project.
+ let (_, expected_proj) = resolve_project_ids(&state, Some("/home/user/my-project"))
+ .await
+ .unwrap();
+ assert_ne!(
+ expected_proj, state.project_id,
+ "routing must not use server-default project"
+ );
+ }
+}
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 319deabe..5459637a 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -21,6 +21,7 @@ mod writer;
pub use decay::{DecayParams, retention_score};
pub use error::{StoreError, StoreResult};
+pub use ops::ReorgSummary;
pub use reader::{
ActivityWindow, BriefingPage, BriefingSnapshot, DecayCandidate, PageHit, PageMeta, PageSummary,
ProjectSummary, ReaderPool, StatusCounts, StoredEmbedding, f32_vec_to_bytes,
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index dc9c4861..f5cf42b9 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -6,8 +6,20 @@
use ai_memory_core::{
AgentKind, HandoffId, NewHandoff, NewObservation, NewPage, NewSession, ObservationId,
- ObservationKind, PageId, SessionId,
+ ObservationKind, PageId, ProjectId, SessionId,
};
+
+/// Summary returned by [`reorg_sessions`] and exposed via
+/// [`crate::writer::WriterHandle::reorg_sessions`].
+#[derive(Debug, Default, Clone)]
+pub struct ReorgSummary {
+ /// Sessions whose `project_id` was changed.
+ pub sessions_moved: usize,
+ /// Observations updated to match their session's new project.
+ pub observations_updated: usize,
+ /// `is_latest=1` pages marked `is_latest=0` (mash-up graveyard).
+ pub pages_graveyarded: usize,
+}
use jiff::Timestamp;
use rusqlite::{Connection, OptionalExtension, params};
use sha2::{Digest, Sha256};
@@ -565,6 +577,50 @@ fn audit(
Ok(())
}
+/// Retro-fit sessions + observations to per-cwd projects and graveyard
+/// any `is_latest=1` pages (which are mash-ups across the old single-project
+/// bucket). Executes atomically in one transaction.
+///
+/// `plan` contains `(session_id, new_project_id)` pairs. Sessions not in
+/// the plan are left untouched. Pages are graveyarded unconditionally so a
+/// fresh consolidation can regenerate clean per-project pages.
+pub fn reorg_sessions(
+ conn: &mut Connection,
+ plan: &[(SessionId, ProjectId)],
+) -> StoreResult<ReorgSummary> {
+ if plan.is_empty() {
+ return Ok(ReorgSummary::default());
+ }
+ let tx = conn.transaction()?;
+ let mut sessions_moved = 0usize;
+ let mut observations_updated = 0usize;
+ for (session_id, new_project_id) in plan {
+ let rows = tx.execute(
+ "UPDATE sessions SET project_id = ?1 WHERE id = ?2 AND project_id != ?1",
+ params![new_project_id.as_bytes(), session_id.as_bytes()],
+ )?;
+ sessions_moved += rows;
+ // Update observations whose session_id matches, keeping project_id
+ // in sync with the session row we just moved.
+ let obs_rows = tx.execute(
+ "UPDATE observations SET project_id = ?1 WHERE session_id = ?2",
+ params![new_project_id.as_bytes(), session_id.as_bytes()],
+ )?;
+ observations_updated += obs_rows;
+ }
+ // Graveyard all current latest pages — they mixed observations from
+ // multiple projects and must be regenerated per-project by the next
+ // consolidation pass.
+ let pages_graveyarded: usize =
+ tx.execute("UPDATE pages SET is_latest = 0 WHERE is_latest = 1", [])?;
+ tx.commit()?;
+ Ok(ReorgSummary {
+ sessions_moved,
+ observations_updated,
+ pages_graveyarded,
+ })
+}
+
#[cfg(test)]
mod tests {
//! Focused unit tests for the load-bearing mutating SQL paths.
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 0d1eeeb5..808db0cb 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -18,7 +18,7 @@ use rusqlite::Connection;
use tokio::sync::{mpsc, oneshot};
use crate::error::{StoreError, StoreResult};
-use crate::ops;
+use crate::ops::{self, ReorgSummary};
/// Commands accepted by the writer thread.
pub(crate) enum WriteCmd {
@@ -63,6 +63,13 @@ pub(crate) enum WriteCmd {
accepting_session: Option<SessionId>,
reply: oneshot::Sender<StoreResult<()>>,
},
+ /// Retro-fit sessions + observations to per-cwd projects and graveyard
+ /// mash-up pages. Executed in one transaction for atomicity.
+ Reorg {
+ /// Each entry is `(session_id, new_project_id)`.
+ plan: Vec<(SessionId, ProjectId)>,
+ reply: oneshot::Sender<StoreResult<ReorgSummary>>,
+ },
BumpAccess {
page_ids: Vec<PageId>,
reply: oneshot::Sender<StoreResult<()>>,
@@ -296,6 +303,23 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Retro-fit sessions and their observations to per-cwd projects and
+ /// graveyard any mash-up pages. The `plan` slice contains
+ /// `(session_id, new_project_id)` pairs. Everything runs in one
+ /// SQLite transaction — either fully committed or fully rolled back.
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
+ /// propagates the SQL error from the reorg transaction.
+ pub async fn reorg_sessions(
+ &self,
+ plan: Vec<(SessionId, ProjectId)>,
+ ) -> StoreResult<ReorgSummary> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::Reorg { plan, reply: tx }).await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Upsert a batch of pages atomically (one SQL transaction).
///
/// # Errors
@@ -417,6 +441,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
);
send_or_warn(reply, result, "accept_handoff");
}
+ WriteCmd::Reorg { plan, reply } => {
+ let result = ops::reorg_sessions(&mut conn, &plan);
+ send_or_warn(reply, result, "reorg_sessions");
+ }
WriteCmd::BumpAccess { page_ids, reply } => {
let result = ops::bump_access_for_pages(&mut conn, &page_ids);
send_or_warn(reply, result, "bump_access_for_pages");