Skip to content

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

Rust

feat(admin,cli): move-session command and route (#402)

Sergio Aguirre5165e8627b03
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4a0bba80..2c3be154 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- Added `ai-memory move-session <session-id> --to <project> [--to-workspace]
+ [--pages move|regenerate] [--confirm] [--force] [--create]`, its batch form
+ `--from-project <project> [--from-workspace]`, and `POST /admin/move-session`
+ to move one session (or every session of a project) to another project, in
+ the same or another workspace. One transaction per session re-stamps the
+ `sessions` row, its `observations`, the `handoffs` it produced, its
+ consolidation jobs, auto-improve runs and scheduler claim, and its
+ `sessions/<id>.md` page: `--pages move` (default) carries every version and
+ the file along (409 when the destination already has that page), `--pages
+ regenerate` retires the source page and removes its file so the next
+ consolidation rewrites it in the destination. Without `--confirm` the server
+ runs the same transaction and rolls it back, so the summary is an exact dry
+ run and the CLI prints the command to apply. An open session, a pending or
+ running consolidation job, or (batch) the active source project refuse with
+ 409 unless `--force`. `sessions.cwd` stays as recorded (the response warns
+ when its basename is not the destination), and `auto_improve_proposals`,
+ `entities` and `page_feedback` are not re-stamped. New admission op
+ `move_session`. (#402)
+
## [1.27.0] - 2026-08-16
### Added
diff --git a/README.md b/README.md
index 289c2de3..b2df827d 100644
--- a/README.md
+++ b/README.md
@@ -172,6 +172,7 @@ priors are at the [bottom](#influences-and-prior-art).
bridge via `install-mcp --session-aware`.
- **Thin-client CLI.** `ai-memory status`, `bootstrap`, `checkpoints`,
`restore-page`, `purge-project`, `rename-project`, `move-project`,
+ `move-session`,
`audit-contamination`, `lint`, `curator`, `auto-improve`,
`auto-improve-report`, `pending-writes`, `embed`, `forget-sweep`, `backup`,
`finalize-session` are
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 26470549..36471698 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -157,6 +157,11 @@ pub enum Command {
/// copy+purge (only durable pages migrate, source purged). Either way the
/// operation is irreversible — requires `--confirm`.
MoveProject(MoveProjectArgs),
+ /// Move one session (or every session of a project) to another project,
+ /// re-stamping its observations, handoffs, consolidation jobs and its
+ /// `sessions/<id>.md` page in one transaction. Without `--confirm` it
+ /// prints what would move (a real dry run, rolled back server-side).
+ MoveSession(MoveSessionArgs),
/// Remove ai-memory's wiring (hooks, MCP, instructions, and default-root
/// managed skills) from all detected agents. Dry-run unless `--apply`.
Uninstall(UninstallArgs),
@@ -607,6 +612,50 @@ pub struct MoveProjectArgs {
pub on_conflict: String,
}
+/// Arguments for `move-session`.
+#[derive(Debug, Args)]
+pub struct MoveSessionArgs {
+ /// Session id (UUID) to move. Omit it and pass `--from-project` to move
+ /// every session of one project.
+ #[arg(
+ required_unless_present = "from_project",
+ conflicts_with = "from_project"
+ )]
+ pub session_id: Option<ai_memory_core::SessionId>,
+ /// Batch form: move every session of this project. Resolved like other
+ /// commands (marker, else literal); the sessions move one at a time and
+ /// the batch stops at the first refusal, reporting how far it got.
+ #[arg(long)]
+ pub from_project: Option<String>,
+ /// Workspace of `--from-project`. Defaults to the nearest
+ /// `.ai-memory.toml` marker's `workspace`, else `default`.
+ #[arg(long, requires = "from_project")]
+ pub from_workspace: Option<String>,
+ /// Destination project name (literal, not marker-resolved).
+ #[arg(long)]
+ pub to: String,
+ /// Destination workspace. Defaults to the source workspace.
+ #[arg(long)]
+ pub to_workspace: Option<String>,
+ /// What happens to the session's `sessions/<id>.md` page: `move` carries
+ /// the page and its history along (refused when the destination already
+ /// has one at that path); `regenerate` retires it so the next
+ /// consolidation writes a fresh page in the destination.
+ #[arg(long, value_parser = ["move", "regenerate"], default_value = "move")]
+ pub pages: String,
+ /// REQUIRED to apply. Without it the command prints the dry-run summary
+ /// and the exact command to re-run.
+ #[arg(long)]
+ pub confirm: bool,
+ /// Skip the live-session guards (open session, pending consolidation job,
+ /// active project of the hook router in the batch form).
+ #[arg(long)]
+ pub force: bool,
+ /// Create the destination workspace/project when it does not exist yet.
+ #[arg(long)]
+ pub create: bool,
+}
+
/// Arguments for `install-instructions`.
#[derive(Debug, Args)]
pub struct InstallInstructionsArgs {
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 81ba57ca..41e511c2 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -35,6 +35,7 @@ pub mod lint;
pub mod llm_test;
pub mod mcp_bridge;
pub mod move_project;
+pub mod move_session;
pub mod openclaw_plugin;
pub mod path_util;
pub mod pending_writes;
diff --git a/crates/ai-memory-cli/src/commands/move_session.rs b/crates/ai-memory-cli/src/commands/move_session.rs
new file mode 100644
index 00000000..b80af717
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/move_session.rs
@@ -0,0 +1,239 @@
+//! `ai-memory move-session` — thin HTTP client for moving one session (or
+//! every session of a project) to another project.
+
+use anyhow::Result;
+use serde::Serialize;
+
+use crate::cli::MoveSessionArgs;
+use crate::config::Config;
+use crate::http_client::{ServerEndpoint, post_json};
+
+/// Request sent to `POST /admin/move-session`. Exactly one of `session_id`
+/// / `from_project` is set.
+#[derive(Serialize)]
+struct MoveSessionRequest {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ session_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ from_workspace: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ from_project: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ workspace: Option<String>,
+ project: String,
+ pages: String,
+ confirm: bool,
+ force: bool,
+ create: bool,
+}
+
+/// Run the `move-session` subcommand.
+///
+/// Without `--confirm` the server runs the move inside a rolled-back
+/// transaction and this prints what would change plus the exact command to
+/// apply it. With `--confirm` it prints the report.
+///
+/// # Errors
+/// Returns an error when the server is unreachable or answers non-2xx (404
+/// unknown session/target, 409 guard or page collision, 422 same scope).
+pub async fn run(config: &Config, args: MoveSessionArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
+
+ // The batch source is a scope like any other command's: marker, else
+ // literal. The destination stays literal.
+ let (from_workspace, from_project) = match args.from_project.as_deref() {
+ Some(project) => {
+ let (ws, proj) =
+ super::resolve_scope(config, args.from_workspace.as_deref(), Some(project))?;
+ (Some(ws), Some(proj))
+ }
+ None => (None, None),
+ };
+ let request = MoveSessionRequest {
+ session_id: args.session_id.map(|id| id.to_string()),
+ from_workspace,
+ from_project,
+ workspace: args.to_workspace.clone(),
+ project: args.to.clone(),
+ pages: args.pages.clone(),
+ confirm: args.confirm,
+ force: args.force,
+ create: args.create,
+ };
+ let report: serde_json::Value = post_json(&endpoint, "/admin/move-session", &request).await?;
+
+ if request.session_id.is_some() {
+ print_session_report(&report, args.confirm);
+ } else {
+ print_batch_report(&report, args.confirm);
+ }
+ if !args.confirm {
+ println!(
+ "\n(dry run; nothing was written)\nRe-run with --confirm to apply:\n\n {}",
+ apply_command(&args)
+ );
+ }
+ Ok(())
+}
+
+fn scope(label: &serde_json::Value) -> String {
+ format!(
+ "{}/{}",
+ label["workspace"].as_str().unwrap_or("?"),
+ label["project"].as_str().unwrap_or("?")
+ )
+}
+
+fn print_session_report(report: &serde_json::Value, applied: bool) {
+ let verb = if applied { "Moved" } else { "Would move" };
+ println!(
+ "{verb} session {} from {} to {}:",
+ report["session_id"].as_str().unwrap_or("?"),
+ scope(&report["from"]),
+ scope(&report["to"]),
+ );
+ print_counts(
+ &report["summary"],
+ report["page"].as_str().unwrap_or("none"),
+ );
+ if let Some(warning) = report["cwd_warning"].as_str() {
+ println!("Warning: {warning}");
+ }
+ if let Some(oid) = report["checkpoint"].as_str() {
+ println!("Checkpoint: {oid}");
+ }
+}
+
+fn print_batch_report(report: &serde_json::Value, applied: bool) {
+ let verb = if applied { "Moved" } else { "Would move" };
+ let total = report["total"].as_u64().unwrap_or(0);
+ let moved = report["moved"].as_u64().unwrap_or(0);
+ println!(
+ "{verb} {moved} of {total} session(s) from {} to {}:",
+ scope(&report["from"]),
+ scope(&report["to"]),
+ );
+ if let Some(sessions) = report["sessions"].as_array() {
+ println!(
+ "{:<38} {:>6} {:>8} {:>5} {:<12} cwd",
+ "session_id", "obs", "handoffs", "jobs", "page"
+ );
+ println!("{}", "-".repeat(90));
+ for s in sessions {
+ println!(
+ "{:<38} {:>6} {:>8} {:>5} {:<12} {}",
+ s["session_id"].as_str().unwrap_or("?"),
+ s["summary"]["observations"].as_u64().unwrap_or(0),
+ s["summary"]["handoffs"].as_u64().unwrap_or(0),
+ s["summary"]["consolidation_jobs"].as_u64().unwrap_or(0),
+ s["page"].as_str().unwrap_or("none"),
+ s["cwd"].as_str().unwrap_or(""),
+ );
+ }
+ let warned = sessions
+ .iter()
+ .filter(|s| s["cwd_warning"].is_string())
+ .count();
+ if warned > 0 {
+ println!(
+ "Warning: {warned} session(s) have a cwd whose basename is not the destination \
+ project; new sessions from those directories still resolve by basename unless \
+ a .ai-memory.toml marker pins the project."
+ );
+ }
+ }
+ if let Some(oid) = report["checkpoint"].as_str() {
+ println!("Checkpoint: {oid}");
+ }
+}
+
+fn print_counts(summary: &serde_json::Value, page: &str) {
+ let n = |key: &str| summary[key].as_u64().unwrap_or(0);
+ println!(" observations: {}", n("observations"));
+ println!(" handoffs: {}", n("handoffs"));
+ println!(" consolidation jobs: {}", n("consolidation_jobs"));
+ println!(" auto-improve runs: {}", n("auto_improve_runs"));
+ println!(" auto-improve claims: {}", n("auto_improve_claims"));
+ println!(
+ " page: {page} ({} version(s) moved, {} retired)",
+ n("page_versions_moved"),
+ n("pages_regenerated")
+ );
+}
+
+/// The exact command that applies what the dry run showed.
+fn apply_command(args: &MoveSessionArgs) -> String {
+ let mut cmd = String::from("ai-memory move-session");
+ if let Some(id) = args.session_id {
+ cmd.push(' ');
+ cmd.push_str(&id.to_string());
+ }
+ if let Some(project) = &args.from_project {
+ cmd.push_str(&format!(" --from-project {project}"));
+ }
+ if let Some(ws) = &args.from_workspace {
+ cmd.push_str(&format!(" --from-workspace {ws}"));
+ }
+ cmd.push_str(&format!(" --to {}", args.to));
+ if let Some(ws) = &args.to_workspace {
+ cmd.push_str(&format!(" --to-workspace {ws}"));
+ }
+ if args.pages != "move" {
+ cmd.push_str(&format!(" --pages {}", args.pages));
+ }
+ if args.force {
+ cmd.push_str(" --force");
+ }
+ if args.create {
+ cmd.push_str(" --create");
+ }
+ cmd.push_str(" --confirm");
+ cmd
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn args(session_id: Option<&str>, from_project: Option<&str>) -> MoveSessionArgs {
+ MoveSessionArgs {
+ session_id: session_id.map(|s| s.parse().unwrap()),
+ from_project: from_project.map(str::to_string),
+ from_workspace: None,
+ to: "target".into(),
+ to_workspace: None,
+ pages: "move".into(),
+ confirm: false,
+ force: false,
+ create: false,
+ }
+ }
+
+ #[test]
+ fn apply_command_repeats_the_single_form_with_confirm() {
+ let id = "0192b6a1-4c2e-7d3f-8a5b-1234567890ab";
+ let mut a = args(Some(id), None);
+ a.pages = "regenerate".into();
+ a.to_workspace = Some("other".into());
+ assert_eq!(
+ apply_command(&a),
+ format!(
+ "ai-memory move-session {id} --to target --to-workspace other \
+ --pages regenerate --confirm"
+ )
+ );
+ }
+
+ #[test]
+ fn apply_command_repeats_the_batch_form_and_flags() {
+ let mut a = args(None, Some("ghost"));
+ a.from_workspace = Some("default".into());
+ a.force = true;
+ a.create = true;
+ assert_eq!(
+ apply_command(&a),
+ "ai-memory move-session --from-project ghost --from-workspace default --to target \
+ --force --create --confirm"
+ );
+ }
+}
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 2c8c60bd..112a48e6 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -136,6 +136,7 @@ async fn main() -> Result<()> {
Command::PurgeProject(args) => commands::purge_project::run(&config, args).await,
Command::RenameProject(args) => commands::rename_project::run(&config, args).await,
Command::MoveProject(args) => commands::move_project::run(&config, args).await,
+ Command::MoveSession(args) => commands::move_session::run(&config, args).await,
Command::Uninstall(args) => commands::uninstall::run(&config, args),
Command::Auth(args) => commands::auth::run(&config, args).await,
Command::User(args) => commands::user::run(&config, args).await,
diff --git a/crates/ai-memory-cli/tests/completions.rs b/crates/ai-memory-cli/tests/completions.rs
index 430f6889..654b51b5 100644
--- a/crates/ai-memory-cli/tests/completions.rs
+++ b/crates/ai-memory-cli/tests/completions.rs
@@ -67,6 +67,7 @@ fn scripts_cover_subcommands_from_across_the_tree() {
"serve",
"write-page",
"purge-project",
+ "move-session",
"user",
"rotate-token",
"auth",
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index d688eebc..fef38e5f 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -58,11 +58,13 @@ use ai_memory_core::{
use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, ProviderHealthSnapshot};
use ai_memory_store::{
ApproveAutoImproveProposalResult, AutoImproveProposalOperation, AutoImproveProposalStatus,
- DecayParams, NewAutoImproveProposal, ReaderPool, RejectAutoImproveProposal,
+ DecayParams, NewAutoImproveProposal, PagesMode, ReaderPool, RejectAutoImproveProposal,
ScopeResolutionError, SkippedProposal, StageAutoImproveRun, StoreError, WriterHandle,
create_explicit_scope, f32_vec_to_bytes, lookup_existing_scope, lookup_existing_workspace,
};
-use ai_memory_wiki::{AdmissionContext, AdmissionOp, Markdown, Wiki, WikiError, WritePageRequest};
+use ai_memory_wiki::{
+ AdmissionContext, AdmissionOp, Markdown, SessionPageFile, Wiki, WikiError, WritePageRequest,
+};
use axum::Json;
use axum::Router;
use axum::body::Body;
@@ -525,6 +527,7 @@ fn hex_to_sha256(hex: &str) -> Result<[u8; 32], String> {
/// - `POST /admin/purge-project`
/// - `POST /admin/rename-project`
/// - `POST /admin/move-project`
+/// - `POST /admin/move-session`
/// - `POST /admin/merge-workspace`
/// - `POST /admin/write-page`
/// - `POST /admin/delete-page`
@@ -583,6 +586,7 @@ pub fn admin_router_with_decay_breadth(state: AdminState, breadth_weight: f64) -
.route("/admin/purge-project", post(handle_purge_project))
.route("/admin/rename-project", post(handle_rename_project))
.route("/admin/move-project", post(handle_move_project))
+ .route("/admin/move-session", post(handle_move_session))
.route("/admin/delete-workspace", post(handle_delete_workspace))
.route("/admin/rename-workspace", post(handle_rename_workspace))
.route("/admin/merge-workspace", post(handle_merge_workspace))
@@ -4169,6 +4173,669 @@ async fn move_project_core(
.await
}
+// ---------------------------------------------------------------------
+// move-session
+// ---------------------------------------------------------------------
+
+/// JSON request body for `POST /admin/move-session`.
+///
+/// Two shapes share the route: a single move names `session_id`; a batch
+/// names `from_project` (plus optional `from_workspace`) and moves every
+/// session of that scope. Exactly one of the two must be present.
+#[derive(Deserialize)]
+struct MoveSessionRequest {
+ /// The session to move (single form).
+ #[serde(default)]
+ session_id: Option<SessionId>,
+ /// Source workspace of the batch form. Defaults to `default`.
+ #[serde(default)]
+ from_workspace: Option<String>,
+ /// Source project of the batch form: every session in it moves.
+ #[serde(default)]
+ from_project: Option<String>,
+ /// Destination workspace. Defaults to the source workspace.
+ #[serde(default)]
+ workspace: Option<String>,
+ /// Destination project. Must already exist unless `create` is set.
+ project: String,
+ /// What happens to `sessions/<id>.md`: `move` (default) carries the page
+ /// and its history along; `regenerate` retires it in the source so the
+ /// next consolidation writes a fresh one in the destination.
+ #[serde(default)]
+ pages: PagesMode,
+ /// Without `confirm: true` the server runs the move inside a rolled-back
+ /// transaction and reports what would change (`dry_run: true`).
+ #[serde(default)]
+ confirm: bool,
+ /// Skip the live-session guards: an open session (no session end
+ /// recorded), a `pending`/`running` consolidation job, and, for the batch
+ /// form, the hook router's active-project pointer.
+ #[serde(default)]
+ force: bool,
+ /// Create the destination workspace/project when absent instead of 404.
+ #[serde(default)]
+ create: bool,
+}
+
+/// `workspace/project` pair as names, for report labels.
+#[derive(Debug, Clone, Serialize)]
+pub struct ScopeLabel {
+ /// Workspace name.
+ pub workspace: String,
+ /// Project name.
+ pub project: String,
+}
+
+/// Row counts of one session move; identical for the dry run.
+#[derive(Debug, Clone, Serialize)]
+pub struct MoveSessionCounts {
+ /// `observations` rows re-stamped.
+ pub observations: u64,
+ /// `handoffs` rows (produced by the session) re-stamped.
+ pub handoffs: u64,
+ /// `session_consolidation_jobs` rows re-stamped.
+ pub consolidation_jobs: u64,
+ /// `auto_improve_runs` rows re-stamped.
+ pub auto_improve_runs: u64,
+ /// `auto_improve_scheduler_claims` rows re-stamped.
+ pub auto_improve_claims: u64,
+ /// `pages` versions of `sessions/<id>.md` re-stamped (`pages: move`).
+ pub page_versions_moved: u64,
+ /// `pages` rows of `sessions/<id>.md` retired (`pages: regenerate`).
+ pub pages_regenerated: u64,
+}
+
+/// Wire-format report for one session in `POST /admin/move-session`.
+#[derive(Debug, Serialize)]
+pub struct MoveSessionReport {
+ /// The moved session.
+ pub session_id: String,
+ /// `true` when nothing was written (no `confirm`).
+ pub dry_run: bool,
+ /// Scope the session came from.
+ pub from: ScopeLabel,
+ /// Scope the session now belongs to.
+ pub to: ScopeLabel,
+ /// Row counts.
+ pub summary: MoveSessionCounts,
+ /// What happened (or would happen) to `sessions/<id>.md`: `"moved"`,
+ /// `"regenerated"`, or `"none"` when the session has no page.
+ pub page: &'static str,
+ /// The session's recorded working directory, left untouched.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cwd: Option<String>,
+ /// Set when `basename(cwd)` differs from the destination project name.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cwd_warning: Option<String>,
+ /// Pre-move checkpoint, if the tree had uncommitted changes.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub pre_checkpoint: Option<String>,
+ /// Post-move checkpoint, if the move changed the tree.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub checkpoint: Option<String>,
+}
+
+/// Wire-format report for the batch form of `POST /admin/move-session`.
+#[derive(Debug, Serialize)]
+pub struct MoveSessionBatchReport {
+ /// `true` when nothing was written (no `confirm`).
+ pub dry_run: bool,
+ /// Source scope.
+ pub from: ScopeLabel,
+ /// Destination scope.
+ pub to: ScopeLabel,
+ /// Sessions found in the source scope.
+ pub total: usize,
+ /// Sessions moved (or, for a dry run, that would move).
+ pub moved: usize,
+ /// One report per session, in `started_at` order.
+ pub sessions: Vec<MoveSessionReport>,
+ /// Pre-move checkpoint, if the tree had uncommitted changes.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub pre_checkpoint: Option<String>,
+ /// Post-move checkpoint, if the batch changed the tree.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub checkpoint: Option<String>,
+}
+
+/// One session move, resolved and validated, before any guard runs.
+struct MoveSessionPlan {
+ session_id: SessionId,
+ from: (WorkspaceId, ProjectId),
+ from_label: ScopeLabel,
+ to: (WorkspaceId, ProjectId),
+ to_label: ScopeLabel,
+ cwd: Option<String>,
+}
+
+async fn handle_move_session(
+ State(state): State<Arc<AdminState>>,
+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
+ author_ext: Option<axum::Extension<ai_memory_core::UserId>>,
+ Json(req): Json<MoveSessionRequest>,
+) -> Response {
+ let actor = actor_ext
+ .map(|axum::Extension(a)| a)
+ .unwrap_or_else(ai_memory_core::ActorContext::anonymous);
+ let author_id = author_ext.map(|axum::Extension(u)| u);
+ match (req.session_id, req.from_project.as_deref()) {
+ (Some(session_id), None) => {
+ match move_single_session(&state, &req, session_id, author_id, actor).await {
+ Ok(report) => (StatusCode::OK, Json(json_or_empty(&report))).into_response(),
+ Err(resp) => resp.into_response(),
+ }
+ }
+ (None, Some(from_project)) => {
+ move_session_batch(&state, &req, from_project, author_id, actor).await
+ }
+ _ => (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "provide exactly one of session_id (single move) or from_project (batch)"
+ })),
+ )
+ .into_response(),
+ }
+}
+
+fn json_or_empty<T: Serialize>(value: &T) -> serde_json::Value {
+ serde_json::to_value(value).unwrap_or_else(|_| serde_json::json!({}))
+}
+
+/// Best-effort names for a scope; ids stand in when a row vanished
+/// underneath us (a concurrent purge), so a report is still produced.
+async fn scope_label(state: &AdminState, ws: WorkspaceId, proj: ProjectId) -> ScopeLabel {
+ let workspace = state
+ .reader
+ .workspace_name_by_id(ws)
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or_else(|| ws.to_string());
+ let project = state
+ .reader
+ .project_name_by_id(ws, proj)
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or_else(|| proj.to_string());
+ ScopeLabel { workspace, project }
+}
+
+/// Resolve the destination scope: existing only (404) unless `create`.
+async fn resolve_move_session_target(
+ state: &AdminState,
+ workspace: &str,
+ project: &str,
+ create: bool,
+) -> Result<(WorkspaceId, ProjectId), MoveErr> {
+ if create {
+ create_ws_proj(state, workspace, project).await
+ } else {
+ lookup_ws_proj_no_create(state, workspace, project).await
+ }
+}
+
+/// `(session still open, consolidation job pending or running)` for the
+/// live-session guards.
+async fn session_move_blockers(
+ reader: &ReaderPool,
+ session_id: SessionId,
+) -> Result<(bool, bool), StoreError> {
+ reader
+ .with_conn(move |conn| {
+ let open: bool = conn.query_row(
+ "SELECT ended_at IS NULL FROM sessions WHERE id = ?1",
+ [session_id.as_bytes().as_slice()],
+ |row| row.get(0),
+ )?;
+ let pending: bool = conn.query_row(
+ "SELECT EXISTS(SELECT 1 FROM session_consolidation_jobs \
+ WHERE session_id = ?1 AND state IN ('pending', 'running'))",
+ [session_id.as_bytes().as_slice()],
+ |row| row.get(0),
+ )?;
+ Ok((open, pending))
+ })
+ .await
+}
+
+/// `(session_id, cwd)` of every session in a scope, oldest first.
+async fn list_scope_sessions(
+ reader: &ReaderPool,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+) -> Result<Vec<(SessionId, Option<String>)>, StoreError> {
+ reader
+ .with_conn(move |conn| {
+ let mut stmt = conn.prepare(
+ "SELECT id, cwd FROM sessions \
+ WHERE workspace_id = ?1 AND project_id = ?2 \
+ ORDER BY started_at, id",
+ )?;
+ let rows = stmt.query_map(
+ [
+ workspace_id.as_bytes().as_slice(),
+ project_id.as_bytes().as_slice(),
+ ],
+ |row| {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let cwd: Option<String> = row.get(1)?;
+ Ok((id_bytes, cwd))
+ },
+ )?;
+ let mut out = Vec::new();
+ for r in rows {
+ let (id_bytes, cwd) = r?;
+ out.push((
+ SessionId::from_slice(&id_bytes).map_err(StoreError::Memory)?,
+ cwd,
+ ));
+ }
+ Ok(out)
+ })
+ .await
+}
+
+fn move_session_store_err(e: StoreError) -> MoveErr {
+ match e {
+ StoreError::NotFound(msg) => (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": msg })),
+ ),
+ e @ StoreError::PagePathTaken { .. } => (
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({
+ "error": format!(
+ "{e}; re-run with pages=regenerate or resolve the destination page first"
+ )
+ })),
+ ),
+ other => internal_err(other.to_string()),
+ }
+}
+
+fn move_session_wiki_err(e: WikiError) -> MoveErr {
+ match e {
+ WikiError::Store(store_err) => move_session_store_err(store_err),
+ e @ WikiError::DestinationPageExists(_) => (
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ ),
+ other => internal_err(format!("move-session aborted: {other}")),
+ }
+}
+
+/// The session's cwd is historical truth and stays put; say so when the
+/// hook router's basename heuristic would not map it to the destination.
+fn move_session_cwd_warning(cwd: Option<&str>, to_project: &str) -> Option<String> {
+ let cwd = cwd?;
+ let base = std::path::Path::new(cwd).file_name()?.to_str()?;
+ if base == to_project {
+ return None;
+ }
+ Some(format!(
+ "session cwd '{cwd}' resolves to project '{base}' by basename, not '{to_project}'; \
+ the cwd was left as recorded. New sessions started there still land in '{base}' \
+ unless a .ai-memory.toml marker pins project = \"{to_project}\"; with \
+ [routing] mid_session = \"sticky\" the remaining events of this session follow it."
+ ))
+}
+
+fn move_session_counts(summary: &ai_memory_store::MoveSessionSummary) -> MoveSessionCounts {
+ MoveSessionCounts {
+ observations: summary.observations,
+ handoffs: summary.handoffs,
+ consolidation_jobs: summary.consolidation_jobs,
+ auto_improve_runs: summary.auto_improve_runs,
+ auto_improve_claims: summary.auto_improve_claims,
+ page_versions_moved: summary.page_versions_moved,
+ pages_regenerated: summary.pages_regenerated,
+ }
+}
+
+fn move_session_page_label(
+ pages: PagesMode,
+ touched_rows: bool,
+ touched_file: bool,
+) -> &'static str {
+ match (pages, touched_rows || touched_file) {
+ (_, false) => "none",
+ (PagesMode::Move, true) => "moved",
+ (PagesMode::Regenerate, true) => "regenerated",
+ }
+}
+
+/// Guards, then the dry run or the real move of one planned session. The
+/// caller wraps the call in the pre/post checkpoints so a batch takes one
+/// pair, not one per session.
+async fn move_planned_session(
+ state: &Arc<AdminState>,
+ req: &MoveSessionRequest,
+ plan: MoveSessionPlan,
+ author_id: Option<ai_memory_core::UserId>,
+ actor: &ai_memory_core::ActorContext,
+) -> Result<MoveSessionReport, MoveErr> {
+ let sid = plan.session_id;
+ if plan.from == plan.to {
+ return Err((
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({
+ "error": format!(
+ "session {sid} already belongs to {}/{}",
+ plan.to_label.workspace, plan.to_label.project
+ )
+ })),
+ ));
+ }
+
+ // Live-session guards. An open session may still receive events, and a
+ // queued consolidation would write the page under the old scope; both
+ // are the operator's call with `force`.
+ let (open, pending_job) = session_move_blockers(&state.reader, sid)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ if !req.force {
+ if open {
+ return Err((
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({
+ "error": format!(
+ "session {sid} is still open (no session end recorded); \
+ finish it or re-run with force=true"
+ )
+ })),
+ ));
+ }
+ if pending_job {
+ return Err((
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({
+ "error": format!(
+ "session {sid} has a pending or running consolidation job; \
+ wait for it or re-run with force=true"
+ )
+ })),
+ ));
+ }
+ }
+
+ // A page file already at the destination blocks a page move; checked here
+ // too so the dry run predicts what the wiki re-checks under its lock.
+ let file_name = format!("{sid}.md");
+ let src_file = state
+ .wiki
+ .project_root(plan.from.0, plan.from.1)
+ .join("sessions")
+ .join(&file_name);
+ let dst_file = state
+ .wiki
+ .project_root(plan.to.0, plan.to.1)
+ .join("sessions")
+ .join(&file_name);
+ if req.pages == PagesMode::Move && src_file.is_file() && dst_file.exists() {
+ return Err(move_session_wiki_err(WikiError::DestinationPageExists(
+ dst_file.display().to_string(),
+ )));
+ }
+
+ let cwd_warning = move_session_cwd_warning(plan.cwd.as_deref(), &plan.to_label.project);
+
+ if !req.confirm {
+ let summary = state
+ .writer
+ .move_session(sid, plan.to.0, plan.to.1, req.pages, author_id, false)
+ .await
+ .map_err(move_session_store_err)?;
+ let touched_rows = summary.page_versions_moved > 0 || summary.pages_regenerated > 0;
+ return Ok(MoveSessionReport {
+ session_id: sid.to_string(),
+ dry_run: true,
+ from: plan.from_label,
+ to: plan.to_label,
+ summary: move_session_counts(&summary),
+ page: move_session_page_label(req.pages, touched_rows, src_file.is_file()),
+ cwd: plan.cwd,
+ cwd_warning,
+ pre_checkpoint: None,
+ checkpoint: None,
+ });
+ }
+
+ let move_ctx = AdmissionContext {
+ workspace: plan.from_label.workspace.clone(),
+ project: plan.from_label.project.clone(),
+ destination_workspace: Some(plan.to_label.workspace.clone()),
+ destination_project: Some(plan.to_label.project.clone()),
+ op: AdmissionOp::MoveSession,
+ actor: actor.clone(),
+ ..Default::default()
+ };
+ // The wiki owns the critical section: admission, file move, SQL
+ // re-stamp, and the file rollback on SQL failure.
+ let outcome = state
+ .wiki
+ .move_session_page(
+ sid,
+ plan.from,
+ plan.to,
+ req.pages,
+ author_id,
+ Some(move_ctx),
+ )
+ .await
+ .map_err(move_session_wiki_err)?;
+ let touched_rows =
+ outcome.summary.page_versions_moved > 0 || outcome.summary.pages_regenerated > 0;
+ Ok(MoveSessionReport {
+ session_id: sid.to_string(),
+ dry_run: false,
+ from: plan.from_label,
+ to: plan.to_label,
+ summary: move_session_counts(&outcome.summary),
+ page: move_session_page_label(
+ req.pages,
+ touched_rows,
+ outcome.file != SessionPageFile::Absent,
+ ),
+ cwd: plan.cwd,
+ cwd_warning,
+ pre_checkpoint: None,
+ checkpoint: None,
+ })
+}
+
+async fn move_single_session(
+ state: &Arc<AdminState>,
+ req: &MoveSessionRequest,
+ session_id: SessionId,
+ author_id: Option<ai_memory_core::UserId>,
+ actor: ai_memory_core::ActorContext,
+) -> Result<MoveSessionReport, MoveErr> {
+ let (from_ws, from_proj, cwd) = state
+ .reader
+ .find_session_scope(session_id)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?
+ .ok_or_else(|| {
+ (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": format!("session {session_id} not found") })),
+ )
+ })?;
+ let from_label = scope_label(state, from_ws, from_proj).await;
+ let to_workspace = req
+ .workspace
+ .clone()
+ .unwrap_or_else(|| from_label.workspace.clone());
+ let to = resolve_move_session_target(state, &to_workspace, &req.project, req.create).await?;
+ let plan = MoveSessionPlan {
+ session_id,
+ from: (from_ws, from_proj),
+ from_label,
+ to,
+ to_label: ScopeLabel {
+ workspace: to_workspace,
+ project: req.project.clone(),
+ },
+ cwd,
+ };
+
+ if !req.confirm {
+ return move_planned_session(state, req, plan, author_id, &actor).await;
+ }
+ let label = format!(
+ "move-session {session_id} {}/{} -> {}/{}",
+ plan.from_label.workspace,
+ plan.from_label.project,
+ plan.to_label.workspace,
+ plan.to_label.project
+ );
+ let pre_checkpoint = checkpoint_or_500(&state.wiki, format!("pre-{label}"))?;
+ let mut report = move_planned_session(state, req, plan, author_id, &actor).await?;
+ if let Err(e) = state.wiki.backfill_scope_manifests().await {
+ warn!(error = %e, "move-session: scope-manifest backfill failed after move");
+ }
+ report.pre_checkpoint = pre_checkpoint;
+ report.checkpoint = checkpoint_or_warn(&state.wiki, label);
+ Ok(report)
+}
+
+async fn move_session_batch(
+ state: &Arc<AdminState>,
+ req: &MoveSessionRequest,
+ from_project: &str,
+ author_id: Option<ai_memory_core::UserId>,
+ actor: ai_memory_core::ActorContext,
+) -> Response {
+ let from_workspace = req
+ .from_workspace
+ .clone()
+ .unwrap_or_else(|| DEFAULT_WORKSPACE_NAME.to_string());
+ let from = match lookup_ws_proj_no_create(state, &from_workspace, from_project).await {
+ Ok(ids) => ids,
+ Err(e) => return e.into_response(),
+ };
+ let to_workspace = req
+ .workspace
+ .clone()
+ .unwrap_or_else(|| from_workspace.clone());
+ let to = match resolve_move_session_target(state, &to_workspace, &req.project, req.create).await
+ {
+ Ok(ids) => ids,
+ Err(e) => return e.into_response(),
+ };
+ let from_label = ScopeLabel {
+ workspace: from_workspace,
+ project: from_project.to_string(),
+ };
+ let to_label = ScopeLabel {
+ workspace: to_workspace,
+ project: req.project.clone(),
+ };
+ if from == to {
+ return (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({
+ "error": "source and destination scopes are identical"
+ })),
+ )
+ .into_response();
+ }
+ // Same guard as move-project: the project the hook router is writing to
+ // is not emptied out from under it without an explicit `force`.
+ if !req.force && state.active_project.contains_project(from.1) {
+ return (
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({
+ "error": format!(
+ "{}/{} is the active session's project; re-run with force=true to move its \
+ sessions anyway",
+ from_label.workspace, from_label.project
+ )
+ })),
+ )
+ .into_response();
+ }
+ let sessions = match list_scope_sessions(&state.reader, from.0, from.1).await {
+ Ok(v) => v,
+ Err(e) => return internal_err(e.to_string()).into_response(),
+ };
+
+ let label = format!(
+ "move-session {}/{} -> {}/{}",
+ from_label.workspace, from_label.project, to_label.workspace, to_label.project
+ );
+ let pre_checkpoint = if req.confirm && !sessions.is_empty() {
+ match checkpoint_or_500(&state.wiki, format!("pre-{label}")) {
+ Ok(oid) => oid,
+ Err(e) => return e.into_response(),
+ }
+ } else {
+ None
+ };
+
+ let total = sessions.len();
+ let mut reports = Vec::with_capacity(total);
+ let mut failure: Option<(SessionId, MoveErr)> = None;
+ for (session_id, cwd) in sessions {
+ let plan = MoveSessionPlan {
+ session_id,
+ from,
+ from_label: from_label.clone(),
+ to,
+ to_label: to_label.clone(),
+ cwd,
+ };
+ match move_planned_session(state, req, plan, author_id, &actor).await {
+ Ok(report) => reports.push(report),
+ Err(e) => {
+ failure = Some((session_id, e));
+ break;
+ }
+ }
+ }
+
+ let checkpoint = if req.confirm && !reports.is_empty() {
+ if let Err(e) = state.wiki.backfill_scope_manifests().await {
+ warn!(error = %e, "move-session: scope-manifest backfill failed after batch");
+ }
+ checkpoint_or_warn(&state.wiki, label)
+ } else {
+ None
+ };
+
+ // Stop at the first error, but say how far the batch got: the sessions
+ // already moved stay moved (each was its own transaction).
+ if let Some((session_id, (status, Json(mut body)))) = failure {
+ if let Some(obj) = body.as_object_mut() {
+ obj.insert(
+ "session_id".into(),
+ serde_json::json!(session_id.to_string()),
+ );
+ obj.insert("dry_run".into(), serde_json::json!(!req.confirm));
+ obj.insert("total".into(), serde_json::json!(total));
+ obj.insert("moved".into(), serde_json::json!(reports.len()));
+ obj.insert("sessions".into(), json_or_empty(&reports));
+ if let Some(oid) = checkpoint {
+ obj.insert("checkpoint".into(), serde_json::json!(oid));
+ }
+ }
+ return (status, Json(body)).into_response();
+ }
+ let report = MoveSessionBatchReport {
+ dry_run: !req.confirm,
+ from: from_label,
+ to: to_label,
+ total,
+ moved: reports.len(),
+ sessions: reports,
+ pre_checkpoint,
+ checkpoint,
+ };
+ (StatusCode::OK, Json(json_or_empty(&report))).into_response()
+}
+
/// One source page, with everything the copy loop and the block
/// pre-check both need. Built in ONE pass over the source listing so
/// the previous two-pass implementation's double-IO (pre-scan + copy
diff --git a/crates/ai-memory-mcp/tests/admin_move_session.rs b/crates/ai-memory-mcp/tests/admin_move_session.rs
new file mode 100644
index 00000000..b109e6f3
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/admin_move_session.rs
@@ -0,0 +1,829 @@
+//! Integration tests for `POST /admin/move-session` (#402).
+//!
+//! Same harness as `admin_move.rs`: a real [`AdminState`] over a
+//! tmpdir-backed store + wiki, driven through `admin_router` with
+//! `tower::ServiceExt::oneshot`. Two scopes, one session with everything a
+//! move re-stamps (observations, a handoff it produced, a completed
+//! consolidation job) and a `sessions/<id>.md` page written through the wiki
+//! so a real file sits on disk.
+
+use ai_memory_core::{
+ AgentKind, NewHandoff, NewObservation, NewSession, ObservationKind, PagePath, ProjectId,
+ Sanitized, Sanitizer, SessionId, Tier, WorkspaceId,
+};
+use ai_memory_mcp::{AdminState, admin_router};
+use ai_memory_store::{DecayParams, Store};
+use ai_memory_wiki::{Wiki, WritePageRequest};
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use serde_json::json;
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
+ let db_path = store.db_path().to_path_buf();
+ let state = AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm: None,
+ auto_improve_require_approval: false,
+ auto_improve_review_config: Default::default(),
+ embedder: None,
+ provider_health: ai_memory_llm::ProviderHealth::default(),
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ db_path,
+ bind: "127.0.0.1:0".to_string(),
+ home_dir: None,
+ bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
+ token_pepper: None,
+ active_project: ai_memory_core::ActiveProject::new(),
+ scope_invalidator: None,
+ trusted_proxy_identity: false,
+ };
+ (state, store)
+}
+
+async fn body_json(resp: axum::response::Response) -> serde_json::Value {
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)
+}
+
+async fn post(state: &AdminState, uri: &str, body: serde_json::Value) -> axum::response::Response {
+ let router = admin_router(state.clone());
+ let req = Request::builder()
+ .method("POST")
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap();
+ router.oneshot(req).await.unwrap()
+}
+
+async fn get(state: &AdminState, uri: &str) -> axum::response::Response {
+ let router = admin_router(state.clone());
+ let req = Request::builder()
+ .method("GET")
+ .uri(uri)
+ .body(Body::empty())
+ .unwrap();
+ router.oneshot(req).await.unwrap()
+}
+
+/// Two projects in workspace `default`, `src` and `dst`, plus a workspace
+/// `other` with a project `far` for the cross-workspace case.
+struct Scopes {
+ ws: WorkspaceId,
+ src: ProjectId,
+ dst: ProjectId,
+ other_ws: WorkspaceId,
+ far: ProjectId,
+}
+
+async fn seed_scopes(store: &Store) -> Scopes {
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let src = store
+ .writer
+ .get_or_create_project(ws, "src", None)
+ .await
+ .unwrap();
+ let dst = store
+ .writer
+ .get_or_create_project(ws, "dst", None)
+ .await
+ .unwrap();
+ let other_ws = store.writer.get_or_create_workspace("other").await.unwrap();
+ let far = store
+ .writer
+ .get_or_create_project(other_ws, "far", None)
+ .await
+ .unwrap();
+ Scopes {
+ ws,
+ src,
+ dst,
+ other_ws,
+ far,
+ }
+}
+
+/// One ended session in `(ws, proj)` with two observations, a handoff it
+/// produced, a completed consolidation job and a `sessions/<id>.md` page
+/// written through the wiki (so the file exists on disk).
+async fn seed_session(
+ store: &Store,
+ wiki: &Wiki,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ cwd: &str,
+) -> SessionId {
+ let sid = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: Some(cwd.into()),
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ for n in 0..2 {
+ store
+ .writer
+ .insert_observation(Sanitized::new(
+ NewObservation {
+ session_id: sid,
+ workspace_id: ws,
+ project_id: proj,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: format!("prompt {n}"),
+ body: "do the thing".into(),
+ importance: 5,
+ },
+ &Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap();
+ }
+ store.writer.end_session(sid, None).await.unwrap();
+ store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: Some(sid),
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "handoff from the moved session".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+ assert!(
+ store
+ .writer
+ .enqueue_session_consolidation(ws, proj, sid)
+ .await
+ .unwrap()
+ );
+ let job = store
+ .writer
+ .claim_session_consolidation(i64::MAX / 2, 0)
+ .await
+ .unwrap()
+ .expect("the queued job must be claimable");
+ assert_eq!(job.session_id(), sid);
+ store
+ .writer
+ .complete_session_consolidation(job)
+ .await
+ .unwrap();
+ wiki.write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: page_path(sid),
+ frontmatter: json!({ "title": "Session summary" }),
+ body: format!("consolidated body of {sid}"),
+ tier: Tier::Episodic,
+ pinned: false,
+ title: Some("Session summary".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ })
+ .await
+ .unwrap();
+ sid
+}
+
+fn page_path(sid: SessionId) -> PagePath {
+ PagePath::new(format!("sessions/{sid}.md")).unwrap()
+}
+
+/// `(sessions, observations, handoffs, consolidation_jobs)` rows of `sid`
+/// sitting in `(ws, proj)`.
+async fn rows_in_scope(
+ store: &Store,
+ sid: SessionId,
+ ws: WorkspaceId,
+ proj: ProjectId,
+) -> (i64, i64, i64, i64) {
+ // The mcp crate does not depend on rusqlite directly: params go in as
+ // plain byte slices and the closure returns the store's error type.
+ store
+ .reader
+ .with_conn(move |conn| {
+ let params = [
+ sid.as_bytes().as_slice(),
+ ws.as_bytes().as_slice(),
+ proj.as_bytes().as_slice(),
+ ];
+ let mut counts = [0i64; 4];
+ for (slot, sql) in counts.iter_mut().zip([
+ "SELECT COUNT(*) FROM sessions \
+ WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3",
+ "SELECT COUNT(*) FROM observations \
+ WHERE session_id = ?1 AND workspace_id = ?2 AND project_id = ?3",
+ "SELECT COUNT(*) FROM handoffs \
+ WHERE from_session_id = ?1 AND workspace_id = ?2 AND project_id = ?3",
+ "SELECT COUNT(*) FROM session_consolidation_jobs \
+ WHERE session_id = ?1 AND workspace_id = ?2 AND project_id = ?3",
+ ]) {
+ *slot = conn.query_row(sql, params, |r| r.get(0))?;
+ }
+ Ok((counts[0], counts[1], counts[2], counts[3]))
+ })
+ .await
+ .unwrap()
+}
+
+async fn read_page(state: &AdminState, ws: &str, project: &str, sid: SessionId) -> StatusCode {
+ get(
+ state,
+ &format!("/admin/read-page?workspace={ws}&project={project}&path=sessions/{sid}.md"),
+ )
+ .await
+ .status()
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn move_session_dry_run_reports_counts_and_changes_nothing() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let sid = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": sid.to_string(), "project": "dst" }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["dry_run"], true, "{body}");
+ assert_eq!(body["from"]["project"], "src", "{body}");
+ assert_eq!(body["to"]["workspace"], "default", "{body}");
+ assert_eq!(body["to"]["project"], "dst", "{body}");
+ assert_eq!(body["summary"]["observations"], 2, "{body}");
+ assert_eq!(body["summary"]["handoffs"], 1, "{body}");
+ assert_eq!(body["summary"]["consolidation_jobs"], 1, "{body}");
+ assert_eq!(body["summary"]["page_versions_moved"], 1, "{body}");
+ assert_eq!(body["page"], "moved", "{body}");
+ assert_eq!(body["cwd"], "/repo/src", "{body}");
+ assert!(
+ body["cwd_warning"]
+ .as_str()
+ .is_some_and(|w| w.contains("'src'") && w.contains("'dst'")),
+ "basename(cwd) = src differs from dst: {body}"
+ );
+ assert!(body.get("checkpoint").is_none(), "{body}");
+
+ // Nothing moved: rows and file still in the source scope.
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (1, 2, 1, 1)
+ );
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.dst).await,
+ (0, 0, 0, 0)
+ );
+ let path = page_path(sid);
+ assert!(state.wiki.abs_path(scopes.ws, scopes.src, &path).exists());
+ assert!(!state.wiki.abs_path(scopes.ws, scopes.dst, &path).exists());
+ assert_eq!(
+ read_page(&state, "default", "src", sid).await,
+ StatusCode::OK
+ );
+}
+
+#[tokio::test]
+async fn move_session_restamps_rows_moves_file_and_checkpoints() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ // cwd basename equals the destination: no warning expected.
+ let sid = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/dst").await;
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": sid.to_string(), "project": "dst", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["dry_run"], false, "{body}");
+ assert_eq!(body["summary"]["observations"], 2, "{body}");
+ assert_eq!(body["summary"]["page_versions_moved"], 1, "{body}");
+ assert_eq!(body["page"], "moved", "{body}");
+ assert!(body.get("cwd_warning").is_none(), "{body}");
+ assert!(
+ body["checkpoint"].as_str().is_some(),
+ "a real move must checkpoint the wiki: {body}"
+ );
+
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.dst).await,
+ (1, 2, 1, 1)
+ );
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (0, 0, 0, 0)
+ );
+ let path = page_path(sid);
+ assert!(!state.wiki.abs_path(scopes.ws, scopes.src, &path).exists());
+ assert!(state.wiki.abs_path(scopes.ws, scopes.dst, &path).exists());
+ assert_eq!(
+ read_page(&state, "default", "dst", sid).await,
+ StatusCode::OK
+ );
+ assert_eq!(
+ read_page(&state, "default", "src", sid).await,
+ StatusCode::NOT_FOUND
+ );
+ // The move landed in git history.
+ let checkpoints = state.wiki.recent_checkpoints(5).unwrap();
+ assert!(
+ checkpoints
+ .iter()
+ .any(|c| c.summary.contains("move-session")),
+ "{checkpoints:?}"
+ );
+}
+
+#[tokio::test]
+async fn move_session_across_workspaces_and_regenerate() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let sid = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({
+ "session_id": sid.to_string(),
+ "workspace": "other",
+ "project": "far",
+ "pages": "regenerate",
+ "confirm": true
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["to"]["workspace"], "other", "{body}");
+ assert_eq!(body["summary"]["pages_regenerated"], 1, "{body}");
+ assert_eq!(body["summary"]["page_versions_moved"], 0, "{body}");
+ assert_eq!(body["page"], "regenerated", "{body}");
+
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.other_ws, scopes.far).await,
+ (1, 2, 1, 1)
+ );
+ let path = page_path(sid);
+ assert!(
+ !state.wiki.abs_path(scopes.ws, scopes.src, &path).exists(),
+ "retired page file must be removed so the watcher cannot resurrect it"
+ );
+ assert!(
+ !state
+ .wiki
+ .abs_path(scopes.other_ws, scopes.far, &path)
+ .exists()
+ );
+ assert_eq!(
+ read_page(&state, "default", "src", sid).await,
+ StatusCode::NOT_FOUND
+ );
+}
+
+#[tokio::test]
+async fn move_session_page_collision_returns_409_and_leaves_source_intact() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let sid = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+ // A latest page at the same path in the destination, DB row only, so the
+ // wiki's file step succeeds and the store refuses (PagePathTaken).
+ store
+ .writer
+ .upsert_page(ai_memory_core::NewPage {
+ workspace_id: scopes.ws,
+ project_id: scopes.dst,
+ path: page_path(sid),
+ title: "taken".into(),
+ body: "already here".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: json!({}),
+ pinned: false,
+ links: vec![],
+ author_id: None,
+ expires_at: None,
+ entities: vec![],
+ })
+ .await
+ .unwrap();
+
+ for confirm in [false, true] {
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": sid.to_string(), "project": "dst", "confirm": confirm }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::CONFLICT, "confirm={confirm}");
+ let body = body_json(resp).await;
+ assert!(
+ body["error"]
+ .as_str()
+ .is_some_and(|e| e.contains("regenerate")),
+ "{body}"
+ );
+ }
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (1, 2, 1, 1)
+ );
+ let path = page_path(sid);
+ assert!(
+ state.wiki.abs_path(scopes.ws, scopes.src, &path).exists(),
+ "the file must be back in the source after the store refused"
+ );
+ assert!(!state.wiki.abs_path(scopes.ws, scopes.dst, &path).exists());
+
+ // Regenerate side-steps the collision.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({
+ "session_id": sid.to_string(),
+ "project": "dst",
+ "pages": "regenerate",
+ "confirm": true
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.dst).await,
+ (1, 2, 1, 1)
+ );
+}
+
+#[tokio::test]
+async fn move_session_pending_job_or_open_session_needs_force() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let sid = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+ // A second generation waiting in the queue.
+ store
+ .writer
+ .insert_observation(Sanitized::new(
+ NewObservation {
+ session_id: sid,
+ workspace_id: scopes.ws,
+ project_id: scopes.src,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "late prompt".into(),
+ body: "one more".into(),
+ importance: 5,
+ },
+ &Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap();
+ assert!(
+ store
+ .writer
+ .enqueue_session_consolidation(scopes.ws, scopes.src, sid)
+ .await
+ .unwrap()
+ );
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": sid.to_string(), "project": "dst", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::CONFLICT);
+ let body = body_json(resp).await;
+ assert!(
+ body["error"]
+ .as_str()
+ .is_some_and(|e| e.contains("consolidation job")),
+ "{body}"
+ );
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (1, 3, 1, 2)
+ );
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": sid.to_string(), "project": "dst", "confirm": true, "force": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.dst).await,
+ (1, 3, 1, 2)
+ );
+
+ // An open session (no session end) is refused the same way.
+ let open = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: open,
+ workspace_id: scopes.ws,
+ project_id: scopes.src,
+ agent_kind: AgentKind::Codex,
+ cwd: None,
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": open.to_string(), "project": "dst" }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::CONFLICT);
+ let body = body_json(resp).await;
+ assert!(
+ body["error"]
+ .as_str()
+ .is_some_and(|e| e.contains("still open")),
+ "{body}"
+ );
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": open.to_string(), "project": "dst", "force": true }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::OK,
+ "dry run with force passes the guard"
+ );
+}
+
+#[tokio::test]
+async fn move_session_batch_from_project_empties_the_source() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let a = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+ let b = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+
+ // Dry run first: counts, nothing written.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "from_project": "src", "project": "dst" }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["dry_run"], true, "{body}");
+ assert_eq!(body["total"], 2, "{body}");
+ assert_eq!(body["moved"], 2, "{body}");
+ assert_eq!(body["sessions"].as_array().map(Vec::len), Some(2), "{body}");
+ assert_eq!(
+ rows_in_scope(&store, a, scopes.ws, scopes.src).await,
+ (1, 2, 1, 1)
+ );
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "from_project": "src", "project": "dst", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["dry_run"], false, "{body}");
+ assert_eq!(body["moved"], 2, "{body}");
+ assert!(body["checkpoint"].as_str().is_some(), "{body}");
+ for sid in [a, b] {
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.dst).await,
+ (1, 2, 1, 1)
+ );
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (0, 0, 0, 0)
+ );
+ assert!(
+ state
+ .wiki
+ .abs_path(scopes.ws, scopes.dst, &page_path(sid))
+ .exists()
+ );
+ assert_eq!(
+ read_page(&state, "default", "dst", sid).await,
+ StatusCode::OK
+ );
+ }
+ // Source is empty now: a second batch has nothing to do.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "from_project": "src", "project": "dst", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["total"], 0, "{body}");
+}
+
+#[tokio::test]
+async fn move_session_batch_stops_at_first_error_and_reports_progress() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let first = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+ // Second session is still open: refused without force.
+ let open = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: open,
+ workspace_id: scopes.ws,
+ project_id: scopes.src,
+ agent_kind: AgentKind::Codex,
+ cwd: None,
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "from_project": "src", "project": "dst", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::CONFLICT);
+ let body = body_json(resp).await;
+ assert_eq!(body["session_id"], open.to_string(), "{body}");
+ assert_eq!(body["total"], 2, "{body}");
+ assert_eq!(body["moved"], 1, "{body}");
+ assert_eq!(body["sessions"].as_array().map(Vec::len), Some(1), "{body}");
+ // The first session stayed moved (its own transaction), the open one did not.
+ assert_eq!(
+ rows_in_scope(&store, first, scopes.ws, scopes.dst).await,
+ (1, 2, 1, 1)
+ );
+ assert_eq!(
+ rows_in_scope(&store, open, scopes.ws, scopes.src).await.0,
+ 1
+ );
+}
+
+#[tokio::test]
+async fn move_session_target_404_unless_create() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let sid = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": sid.to_string(), "project": "brand-new", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (1, 2, 1, 1)
+ );
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({
+ "session_id": sid.to_string(),
+ "workspace": "fresh-ws",
+ "project": "brand-new",
+ "create": true,
+ "confirm": true
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["to"]["workspace"], "fresh-ws", "{body}");
+ let new_ws = store
+ .reader
+ .find_workspace("fresh-ws".to_string())
+ .await
+ .unwrap()
+ .expect("workspace created");
+ let new_proj = store
+ .reader
+ .find_project(new_ws, "brand-new".to_string())
+ .await
+ .unwrap()
+ .expect("project created");
+ assert_eq!(
+ rows_in_scope(&store, sid, new_ws, new_proj).await,
+ (1, 2, 1, 1)
+ );
+ assert!(
+ state
+ .wiki
+ .abs_path(new_ws, new_proj, &page_path(sid))
+ .exists()
+ );
+ // The new project dir got its scope manifest.
+ assert!(
+ state
+ .wiki
+ .project_root(new_ws, new_proj)
+ .join("_meta.md")
+ .exists()
+ );
+ assert_eq!(
+ read_page(&state, "fresh-ws", "brand-new", sid).await,
+ StatusCode::OK
+ );
+}
+
+#[tokio::test]
+async fn move_session_rejects_bad_shapes() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let sid = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+
+ // Neither session_id nor from_project.
+ let resp = post(&state, "/admin/move-session", json!({ "project": "dst" })).await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+ // Both at once.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": sid.to_string(), "from_project": "src", "project": "dst" }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+ // Unknown session.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": SessionId::new().to_string(), "project": "dst" }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+ // Same scope.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "session_id": sid.to_string(), "project": "src" }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (1, 2, 1, 1)
+ );
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 739b811f..c00e3c88 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -426,8 +426,8 @@ auto-improve finalize-session pending-writes
embed generate-auth-token setup-agent
bootstrap install-instructions install-skills
reorg purge-project rename-project
-move-project uninstall auth
-user completions
+move-project move-session uninstall
+auth user completions
```
Run `ai-memory --help` for the full tree.
diff --git a/docs/admission-webhooks.md b/docs/admission-webhooks.md
index 82ab95d5..51e77d29 100644
--- a/docs/admission-webhooks.md
+++ b/docs/admission-webhooks.md
@@ -72,6 +72,12 @@ Webhooks fire on these `op` values today (extensible enum):
`ctx.destination_workspace` / `ctx.destination_project`, and no page path;
fired before the directory rename + DB re-stamp so a mirror can rename or
reject the project move.
+- `move_session` — one session (its rows and its `sessions/<id>.md` page)
+ is moved to another project (`/admin/move-session`). Carries the source
+ project in `ctx.workspace` / `ctx.project`, destination names in
+ `ctx.destination_workspace` / `ctx.destination_project`, and no page path;
+ fired before the page file moves and the DB re-stamps so a mirror can move
+ or reject it.
- `handoff_begin` / `handoff_accept` / `handoff_cancel` — a handoff is created,
consumed, or discarded. Carries the workspace / project and the acting
operator, no page path (handoffs live in their own table, not the wiki tree).
@@ -121,7 +127,7 @@ within 750 ms is treated as a refusal and the baton remains open. Configure
smaller per-webhook values when you need logs to identify which decider timed
out rather than the aggregate deadline firing first.
-`delete` / `purge_project` / `purge_workspace` / `move_project` are notifications — there is no
+`delete` / `purge_project` / `purge_workspace` / `move_project` / `move_session` are notifications — there is no
body to mutate; a `Reject`-policy webhook still aborts the operation
(admission fires BEFORE the SQL destruction in both the `/admin/purge-project`
and `/admin/delete-workspace` paths, and before source teardown in
@@ -184,10 +190,10 @@ terminal `purge_project` notification is unchanged.
POST <webhook.url>
Content-Type: application/json
X-Memory-Op: write_page | consolidate | delete | purge_project | purge_workspace | move_project
- | handoff_begin | handoff_accept | handoff_cancel
+ | move_session | handoff_begin | handoff_accept | handoff_cancel
```
-(The header is one of those nine values; the second line is a continuation of
+(The header is one of those ten values; the second line is a continuation of
the list, not a second header.)
```jsonc
@@ -200,8 +206,8 @@ the list, not a second header.)
"ctx": {
"workspace": "default", // resolved name (see §5)
"project": "ai-memory-ops", // resolved name
- "destination_workspace": "archive", // move_project only; omitted otherwise
- "destination_project": "ai-memory-ops", // move_project only; omitted otherwise
+ "destination_workspace": "archive", // move_project / move_session only; omitted otherwise
+ "destination_project": "ai-memory-ops", // move_project / move_session only; omitted otherwise
"actor": { // request-layer identity
"agent": "claude-code", // claude-code | codex | opencode | hook | cli | …
"user": "djalmajr", // null when unauthenticated
@@ -209,7 +215,7 @@ the list, not a second header.)
"client": "72836f52-...", // DCR client UUID
"session_id": "019e6d-..."
},
- "op": "write_page", // write_page | consolidate | delete | purge_project | purge_workspace | move_project
+ "op": "write_page", // write_page | consolidate | delete | purge_project | purge_workspace | move_project | move_session
"partial_failure": true // purge_project/purge_workspace only, and ONLY when set
// (skipped on the wire when false).
// true → the DB rows were purged but
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 2dd6ee20..8337de2f 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -13,6 +13,7 @@ on a homelab box where mistakes are harder to undo.
| `/admin/rename-workspace` | ✅ yes | no | yes (rename back) | Column-only update on `workspaces.name`; refreshes `_meta.md` scope manifests and checkpoints the wiki tree. |
| `/admin/delete-workspace` | ✅ yes | the workspace and every child project | no | Runs `purge_workspace` admission first, deletes SQLite rows in one cascade, removes the UUID-keyed workspace directory and managed-workstream raw segments, reports filesystem partial failures, and dispatches mirror notification after durable work. |
| `move-project --confirm` | ✅ yes | source only in the merge case (a `Reject`-policy `purge_project` webhook can still abort the source teardown leaving everything intact) | no | Fresh destination → lossless **true move** (re-stamp `workspace_id`, keep `project_id`, rename the dir): sessions/observations/handoffs + history all survive. Destination with a same-named project → **copy+purge merge**: only latest pages migrate. |
+| `move-session <id> --to --confirm` | ✅ yes | no | yes (move it back) | Re-stamps one session (or every session of `--from-project`) into another project: `sessions`, `observations`, its `handoffs`, consolidation jobs, auto-improve runs/claims and its `sessions/<id>.md` page, one transaction per session; the page file moves with it (`--pages move`, default) or is retired for regeneration. Without `--confirm` it is a real dry run (rolled back). Refuses with `409` an open session or a pending consolidation job unless `--force`. |
| `backup --output-path` | ✅ yes | no | n/a | Streams a gzipped tarball from the server's online `sqlite3 .backup` plus the wiki tree. Safe alongside the live writer. |
| `checkpoints` | ✅ yes | no | n/a | Lists recent wiki git checkpoints. Read-only. |
| `restore-page --path --from` | ✅ yes | overwrites one markdown page version | yes (restore another checkpoint) | Restores one page from wiki git history, reindexes it into SQLite, and writes a post-restore checkpoint. Does not restore DB-only state. |
@@ -353,6 +354,115 @@ Failure modes:
directory moved but before SQL committed, the error includes the
exact manual repair.
+### `move-session`
+
+```bash
+# One session, page and history included (dry run: no --confirm)
+ai-memory move-session 0192b6a1-4c2e-7d3f-8a5b-1234567890ab --to NAS_general
+# Apply
+ai-memory move-session 0192b6a1-4c2e-7d3f-8a5b-1234567890ab --to NAS_general --confirm
+# Every session of a stray project, into another workspace, page regenerated later
+ai-memory move-session --from-project tmp --to NAS_general --to-workspace home \
+ --pages regenerate --confirm
+```
+
+Moves one session, or every session of `--from-project`, into another
+project, in the same or another workspace. Use it when a session was
+captured under the wrong project (a `cd` into `/tmp` before sticky routing,
+a subagent started in a scratch directory, a repo cloned under a temporary
+name) and its observations should live with the project they are about.
+Unlike `reorg`, which re-derives every session's project from its `cwd`,
+this names the destination explicitly and leaves the rest of the store
+alone.
+
+**Request.** `POST /admin/move-session` takes either
+`{"session_id": "<uuid>", "workspace"?, "project", "pages"?, "confirm"?,
+"force"?, "create"?}` or the batch form `{"from_workspace"?, "from_project",
+"workspace"?, "project", "pages"?, "confirm"?, "force"?, "create"?}`.
+`workspace` (the destination) defaults to the source workspace;
+`from_workspace` defaults to `default`. The CLI resolves `--from-project`
+like every other scope argument (marker, else literal); `--to` and
+`--to-workspace` stay literal.
+
+**What moves, per session, in ONE transaction:** the `sessions` row, every
+`observations` row of the session (including any that landed in another
+scope), the `handoffs` it produced (`from_session_id`), its
+`session_consolidation_jobs`, `auto_improve_runs` and
+`auto_improve_scheduler_claims`, and its `sessions/<id>.md` page:
+
+- `--pages move` (default): every version of the page is re-stamped into the
+ destination and the file is renamed into the destination project
+ directory, so the curated page and its supersession history follow the
+ session. Refused with `409` when the destination already has a latest page
+ (or a page file) at that path; retry with `--pages regenerate` or resolve
+ the destination page first.
+- `--pages regenerate`: the source versions are retired (`is_latest = 0`)
+ and the file is removed, so the next consolidation of the session writes a
+ fresh page in the destination. The file has to go: a page file left on
+ disk with no latest row is re-indexed as a new latest page by the next
+ reconciliation pass.
+
+The audit row (`op = move_session`) carries the operator when the request
+was attributed. What does NOT move: `sessions.cwd` (historical truth; the
+response carries `cwd_warning` when its basename is not the destination
+project, since new sessions started there still resolve by basename unless a
+`.ai-memory.toml` marker pins the project), other pages written during the
+session (decisions, gotchas: pages are not tracked per session), handoffs the
+session *accepted*, and `auto_improve_proposals` (they have no `session_id`;
+they target pages in the scope they were staged in). `entities` and
+`page_feedback` are not re-stamped either, the same gap `move-project` has.
+
+**Order of operations (per session):** validate the destination (404 unless
+`create`), reject a same-scope target (422), run the guards, then, under the
+wiki's exclusive mutation gate, fire `op=move_session` admission webhooks
+(source names in `ctx.workspace`/`ctx.project`, destination names in
+`ctx.destination_*`), move the file, and re-stamp SQLite. Disk goes first
+and SQL last, as in `move-project`: a store failure renames the file back,
+so the move is all-or-nothing unless the filesystem also refuses the
+rollback, in which case the error names the manual repair. A `--confirm`
+run takes a wiki checkpoint before and after; a batch takes one pair for
+the whole run.
+
+**Dry run by default.** Without `--confirm` the server runs the same
+transaction and rolls it back, so the counts in the response are exact
+(`dry_run: true`), and the CLI prints the exact command to apply. Nothing
+is written and no audit row is left.
+
+**Guards (409 unless `--force`).** A session that is still open (no session
+end recorded) may still receive events; a `pending`/`running` consolidation
+job would write the page under the old scope; the batch form also refuses
+the project the hook router has published as active, like `move-project`.
+`--force` proceeds. Note that forcing an open session leaves the hook
+router's per-session active pointer on the old scope until it expires;
+sticky routing then keeps following the session row, which is now the
+destination.
+
+**Batch form.** Every session of the source scope moves one at a time, each
+in its own transaction. The batch stops at the first refusal and the error
+body reports `moved`/`total` and the sessions already moved (they stay
+moved). A dry run of the batch shows the whole plan first.
+
+Response (`MoveSessionReport`): `session_id`, `dry_run`, `from`/`to`
+(`{workspace, project}`), `summary` (`observations`, `handoffs`,
+`consolidation_jobs`, `auto_improve_runs`, `auto_improve_claims`,
+`page_versions_moved`, `pages_regenerated`), `page` (`moved` |
+`regenerated` | `none`), `cwd`, `cwd_warning`, `pre_checkpoint`,
+`checkpoint`. The batch wraps them in `{dry_run, from, to, total, moved,
+sessions: [...]}`.
+
+Failure modes:
+
+- **Neither `session_id` nor `from_project`, or both** → 400.
+- **Session or destination not found** → 404 (pass `create` / `--create`
+ to create the destination).
+- **Destination equals the source scope** → 422.
+- **Open session, pending consolidation job, or active source project
+ (batch)** → 409 without `force`.
+- **Latest page or page file already at `sessions/<id>.md` in the
+ destination** (`--pages move`) → 409; nothing moved.
+- **Store failure after the file moved** → 500, file renamed back; the
+ error names the manual repair if that rollback also fails.
+
### `checkpoints`
```bash
@@ -568,6 +678,16 @@ ai-memory rename-project --from old --to new
# is stable.
```
+### "Reattach a session captured under the wrong project"
+
+```bash
+ai-memory move-session <session-id> --to my-project # dry run
+ai-memory move-session <session-id> --to my-project --confirm
+# Or empty a stray project into the right one, then drop the husk:
+ai-memory move-session --from-project tmp --to my-project --confirm
+ai-memory purge-project --project tmp --confirm
+```
+
## Why this matters: the flat-wiki incident
Before the per-project disk layout (commits up to `e7b9a17`), the
diff --git a/docs/marker-file.md b/docs/marker-file.md
index e6cdc490..b549950f 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -392,7 +392,7 @@ Both entry points, as of v1.20:
calling the server — `run`, `bootstrap`, `search`, `read-page`,
`write-page`, `lint`, `curator`, `embed`, `pending-writes`,
`forget-sweep`, `auto-improve`, `purge-project`, `rename-project`,
- `move-project` (source side), and friends.
+ `move-project` and `move-session --from-project` (source side), and friends.
Before v1.20 only the hooks read it. A checkout declaring
`workspace = "acme"` therefore had its captures land in `acme` while every
diff --git a/docs/usage.md b/docs/usage.md
index 26cb805d..5c211ca2 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -399,6 +399,23 @@ docker cp ai-memory:/data/wiki ./my-ai-memory-wiki
docker exec ai-memory git -C /data/wiki log --oneline
```
+## Move a session to another project
+
+A session captured under the wrong project (a `cd` into a scratch
+directory, a subagent started elsewhere) can be reattached without a
+reorg of the whole store:
+
+```bash
+ai-memory move-session <session-id> --to my-project # dry run
+ai-memory move-session <session-id> --to my-project --confirm # apply
+ai-memory move-session --from-project tmp --to my-project --confirm
+```
+
+The session, its observations, handoffs, consolidation jobs and its
+`sessions/<id>.md` page move together; see
+[`docs/lifecycle-ops.md`](lifecycle-ops.md#move-session) for the page modes,
+guards, and what stays behind.
+
## Project consolidation preferences
Create `_prompts/consolidation.md` in a project's wiki when its compiled pages