Skip to content

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

Rust

fix(store,admin): move-session re-homes stray rows and enumerates observation-only sessions (#402)

Sergio Aguirrea7ff446de69f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c3be154..42c23d7b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,11 +11,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- 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
+ to move one session (or every session touching a project) to another
+ project, in the same or another workspace. One transaction per session
+ re-stamps the `sessions` row, its `observations` (wherever they landed), 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
@@ -24,8 +25,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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)
+ `entities` and `page_feedback` are not re-stamped. A session already rooted
+ in the destination is re-homed instead of refused: its row stays
+ (`session_moved: false`) and only its rows still lying in other scopes are
+ gathered, and the batch form enumerates sessions with a `sessions` row in
+ the source OR observations stamped into it, so a phantom project holding
+ only observations of sessions rooted elsewhere can be emptied. New
+ admission op `move_session`. (#402)
## [1.27.0] - 2026-08-16
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 36471698..43bc1926 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -616,15 +616,17 @@ pub struct MoveProjectArgs {
#[derive(Debug, Args)]
pub struct MoveSessionArgs {
/// Session id (UUID) to move. Omit it and pass `--from-project` to move
- /// every session of one project.
+ /// every session touching one project. A session already rooted in the
+ /// destination is re-homed: its row stays and only its stray rows move.
#[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.
+ /// Batch form: move every session touching this project (a session row
+ /// here or observations stamped into it). 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
diff --git a/crates/ai-memory-cli/src/commands/move_session.rs b/crates/ai-memory-cli/src/commands/move_session.rs
index b80af717..7dec10e3 100644
--- a/crates/ai-memory-cli/src/commands/move_session.rs
+++ b/crates/ai-memory-cli/src/commands/move_session.rs
@@ -33,9 +33,14 @@ struct MoveSessionRequest {
/// transaction and this prints what would change plus the exact command to
/// apply it. With `--confirm` it prints the report.
///
+/// A session already rooted in the destination is re-homed: the report says
+/// `session row: already in destination` and the counts are the stray rows
+/// gathered into it (zero when there were none).
+///
/// # 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).
+/// unknown session/target, 409 guard or page collision, 422 batch source
+/// equal to the destination).
pub async fn run(config: &Config, args: MoveSessionArgs) -> Result<()> {
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
@@ -84,6 +89,16 @@ fn scope(label: &serde_json::Value) -> String {
)
}
+/// One line saying whether the `sessions` row itself changes scope; a
+/// re-home leaves it and only gathers stray rows.
+fn session_row_line(report: &serde_json::Value, applied: bool) -> &'static str {
+ match (report["session_moved"].as_bool().unwrap_or(false), applied) {
+ (true, true) => "moved",
+ (true, false) => "would move",
+ (false, _) => "already in destination (re-home: only stray rows gathered)",
+ }
+}
+
fn print_session_report(report: &serde_json::Value, applied: bool) {
let verb = if applied { "Moved" } else { "Would move" };
println!(
@@ -92,6 +107,10 @@ fn print_session_report(report: &serde_json::Value, applied: bool) {
scope(&report["from"]),
scope(&report["to"]),
);
+ println!(
+ " session row: {}",
+ session_row_line(report, applied)
+ );
print_counts(
&report["summary"],
report["page"].as_str().unwrap_or("none"),
@@ -115,14 +134,19 @@ fn print_batch_report(report: &serde_json::Value, applied: bool) {
);
if let Some(sessions) = report["sessions"].as_array() {
println!(
- "{:<38} {:>6} {:>8} {:>5} {:<12} cwd",
- "session_id", "obs", "handoffs", "jobs", "page"
+ "{:<38} {:<8} {:>6} {:>8} {:>5} {:<12} cwd",
+ "session_id", "row", "obs", "handoffs", "jobs", "page"
);
- println!("{}", "-".repeat(90));
+ println!("{}", "-".repeat(99));
for s in sessions {
println!(
- "{:<38} {:>6} {:>8} {:>5} {:<12} {}",
+ "{:<38} {:<8} {:>6} {:>8} {:>5} {:<12} {}",
s["session_id"].as_str().unwrap_or("?"),
+ if s["session_moved"].as_bool().unwrap_or(false) {
+ "moved"
+ } else {
+ "re-home"
+ },
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),
@@ -130,6 +154,16 @@ fn print_batch_report(report: &serde_json::Value, applied: bool) {
s["cwd"].as_str().unwrap_or(""),
);
}
+ let rehomed = sessions
+ .iter()
+ .filter(|s| !s["session_moved"].as_bool().unwrap_or(false))
+ .count();
+ if rehomed > 0 {
+ println!(
+ "Note: {rehomed} session(s) marked re-home already had their session row in the \
+ destination; only their stray rows (the counts above) were gathered."
+ );
+ }
let warned = sessions
.iter()
.filter(|s| s["cwd_warning"].is_string())
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index fef38e5f..70ffe7c4 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -4181,7 +4181,10 @@ async fn move_project_core(
///
/// 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.
+/// session touching that scope (a `sessions` row there OR observations
+/// stamped into it). Exactly one of the two must be present. A session whose
+/// row already sits in the destination is re-homed: only its rows still
+/// lying elsewhere move (`session_moved: false`).
#[derive(Deserialize)]
struct MoveSessionRequest {
/// The session to move (single form).
@@ -4190,7 +4193,7 @@ struct MoveSessionRequest {
/// 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.
+ /// Source project of the batch form: every session touching it moves.
#[serde(default)]
from_project: Option<String>,
/// Destination workspace. Defaults to the source workspace.
@@ -4208,8 +4211,9 @@ struct MoveSessionRequest {
#[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.
+ /// recorded; not applied to a re-home, whose row does not move), 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.
@@ -4252,6 +4256,10 @@ pub struct MoveSessionReport {
pub session_id: String,
/// `true` when nothing was written (no `confirm`).
pub dry_run: bool,
+ /// Whether the `sessions` row changed scope. `false` for a re-home: the
+ /// row already sat in the destination and only stray rows (the counts
+ /// below) were gathered into it.
+ pub session_moved: bool,
/// Scope the session came from.
pub from: ScopeLabel,
/// Scope the session now belongs to.
@@ -4284,11 +4292,13 @@ pub struct MoveSessionBatchReport {
pub from: ScopeLabel,
/// Destination scope.
pub to: ScopeLabel,
- /// Sessions found in the source scope.
+ /// Sessions touching the source scope (a `sessions` row there or at
+ /// least one observation stamped into it).
pub total: usize,
- /// Sessions moved (or, for a dry run, that would move).
+ /// Sessions moved or re-homed (or, for a dry run, that would be).
pub moved: usize,
- /// One report per session, in `started_at` order.
+ /// One report per session, oldest first (row `started_at` or first
+ /// observation in the source).
pub sessions: Vec<MoveSessionReport>,
/// Pre-move checkpoint, if the tree had uncommitted changes.
#[serde(skip_serializing_if = "Option::is_none")]
@@ -4301,13 +4311,25 @@ pub struct MoveSessionBatchReport {
/// One session move, resolved and validated, before any guard runs.
struct MoveSessionPlan {
session_id: SessionId,
+ /// Scope the rows are gathered from: the session row's own scope in the
+ /// single form, the batch source in the batch form (where the row may
+ /// well sit elsewhere, even in `to`).
from: (WorkspaceId, ProjectId),
from_label: ScopeLabel,
to: (WorkspaceId, ProjectId),
to_label: ScopeLabel,
+ /// Where the `sessions` row sits right now.
+ row_scope: (WorkspaceId, ProjectId),
cwd: Option<String>,
}
+impl MoveSessionPlan {
+ /// The row already sits in the destination: only stray rows move.
+ fn is_rehome(&self) -> bool {
+ self.row_scope == self.to
+ }
+}
+
async fn handle_move_session(
State(state): State<Arc<AdminState>>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
@@ -4400,41 +4422,27 @@ async fn session_move_blockers(
.await
}
-/// `(session_id, cwd)` of every session in a scope, oldest first.
+/// `(session_id, row scope, cwd)` of every session touching a scope (a
+/// `sessions` row there or observations stamped into it), oldest first. The
+/// row scope may differ from the queried scope: that is the phantom-bucket
+/// case the batch re-homes.
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
+) -> Result<Vec<(SessionId, (WorkspaceId, ProjectId), Option<String>)>, StoreError> {
+ let ids = reader
+ .session_ids_touching_scope(workspace_id, project_id)
+ .await?;
+ let mut out = Vec::with_capacity(ids.len());
+ for sid in ids {
+ // Observations reference `sessions` (FK on), so a listed id always
+ // has a row; a concurrent purge is the only way to lose it here.
+ if let Some((ws, proj, cwd)) = reader.find_session_scope(sid).await? {
+ out.push((sid, (ws, proj), cwd));
+ }
+ }
+ Ok(out)
}
fn move_session_store_err(e: StoreError) -> MoveErr {
@@ -4517,26 +4525,17 @@ async fn move_planned_session(
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
- )
- })),
- ));
- }
+ let rehome = plan.is_rehome();
// 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`.
+ // are the operator's call with `force`. A re-home leaves the row where
+ // it is, so an open session is no reason to refuse gathering its strays.
let (open, pending_job) = session_move_blockers(&state.reader, sid)
.await
.map_err(|e| internal_err(e.to_string()))?;
if !req.force {
- if open {
+ if open && !rehome {
return Err((
StatusCode::CONFLICT,
Json(serde_json::json!({
@@ -4561,7 +4560,9 @@ async fn move_planned_session(
}
// 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.
+ // too so the dry run predicts what the wiki re-checks under its lock. When
+ // the source scope IS the destination (single-form re-home) there is no
+ // file to move and the wiki skips the file step too.
let file_name = format!("{sid}.md");
let src_file = state
.wiki
@@ -4573,7 +4574,8 @@ async fn move_planned_session(
.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() {
+ let file_moves = plan.from != plan.to && src_file.is_file();
+ if req.pages == PagesMode::Move && file_moves && dst_file.exists() {
return Err(move_session_wiki_err(WikiError::DestinationPageExists(
dst_file.display().to_string(),
)));
@@ -4591,10 +4593,11 @@ async fn move_planned_session(
return Ok(MoveSessionReport {
session_id: sid.to_string(),
dry_run: true,
+ session_moved: summary.session_moved,
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()),
+ page: move_session_page_label(req.pages, touched_rows, file_moves),
cwd: plan.cwd,
cwd_warning,
pre_checkpoint: None,
@@ -4630,6 +4633,7 @@ async fn move_planned_session(
Ok(MoveSessionReport {
session_id: sid.to_string(),
dry_run: false,
+ session_moved: outcome.summary.session_moved,
from: plan.from_label,
to: plan.to_label,
summary: move_session_counts(&outcome.summary),
@@ -4678,6 +4682,7 @@ async fn move_single_session(
workspace: to_workspace,
project: req.project.clone(),
},
+ row_scope: (from_ws, from_proj),
cwd,
};
@@ -4778,13 +4783,27 @@ async fn move_session_batch(
let total = sessions.len();
let mut reports = Vec::with_capacity(total);
let mut failure: Option<(SessionId, MoveErr)> = None;
- for (session_id, cwd) in sessions {
+ for (session_id, row_scope, cwd) in sessions {
+ // The page file follows the page rows: a session rooted in a third
+ // scope (only some observations in the source) is moved whole from
+ // where its row sits; a session already rooted in the destination is
+ // re-homed and its stray page file, if any, is looked for in the
+ // source.
+ let (plan_from, plan_from_label) = if row_scope == from || row_scope == to {
+ (from, from_label.clone())
+ } else {
+ (
+ row_scope,
+ scope_label(state, row_scope.0, row_scope.1).await,
+ )
+ };
let plan = MoveSessionPlan {
session_id,
- from,
- from_label: from_label.clone(),
+ from: plan_from,
+ from_label: plan_from_label,
to,
to_label: to_label.clone(),
+ row_scope,
cwd,
};
match move_planned_session(state, req, plan, author_id, &actor).await {
diff --git a/crates/ai-memory-mcp/tests/admin_move_session.rs b/crates/ai-memory-mcp/tests/admin_move_session.rs
index b109e6f3..9e157643 100644
--- a/crates/ai-memory-mcp/tests/admin_move_session.rs
+++ b/crates/ai-memory-mcp/tests/admin_move_session.rs
@@ -814,16 +814,192 @@ async fn move_session_rejects_bad_shapes() {
)
.await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
- // Same scope.
+ // Same scope in the single form is a re-home, not an error: nothing is
+ // stray here, so every count is zero and the row stays.
let resp = post(
&state,
"/admin/move-session",
- json!({ "session_id": sid.to_string(), "project": "src" }),
+ json!({ "session_id": sid.to_string(), "project": "src", "confirm": true }),
)
.await;
- assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["session_moved"], false, "{body}");
+ assert_eq!(body["summary"]["observations"], 0, "{body}");
+ assert_eq!(body["page"], "none", "{body}");
assert_eq!(
rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
(1, 2, 1, 1)
);
+ // Same scope in the batch form stays a 422.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "from_project": "src", "project": "src" }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
+}
+
+/// Scatter `n` observations of `sid` into `(ws, proj)` the way pre-sticky
+/// mid-session routing did: rows stamped into a project the session row
+/// never belonged to.
+async fn scatter_observations(
+ store: &Store,
+ sid: SessionId,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ n: usize,
+) {
+ for i in 0..n {
+ store
+ .writer
+ .insert_observation(Sanitized::new(
+ NewObservation {
+ session_id: sid,
+ workspace_id: ws,
+ project_id: proj,
+ kind: ObservationKind::PostToolUse,
+ extension: None,
+ source_event: None,
+ title: format!("stray {i}"),
+ body: "landed in the wrong bucket".into(),
+ importance: 5,
+ },
+ &Sanitizer::builtin(),
+ ))
+ .await
+ .unwrap();
+ }
+}
+
+#[tokio::test]
+async fn move_session_batch_empties_phantom_bucket_with_only_observations() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ // The session is rooted in `dst` (row, 2 observations, handoff, job,
+ // page all there); 4 of its observations landed in `src`, which has no
+ // `sessions` row at all: the phantom bucket.
+ let sid = seed_session(&store, &state.wiki, scopes.ws, scopes.dst, "/repo/dst").await;
+ scatter_observations(&store, sid, scopes.ws, scopes.src, 4).await;
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (0, 4, 0, 0)
+ );
+
+ // Dry run sees the session through its observations and reports them.
+ 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"], 1, "{body}");
+ assert_eq!(body["moved"], 1, "{body}");
+ let s = &body["sessions"][0];
+ assert_eq!(s["session_id"], sid.to_string(), "{body}");
+ assert_eq!(s["session_moved"], false, "{body}");
+ assert_eq!(s["summary"]["observations"], 4, "{body}");
+ assert_eq!(s["summary"]["handoffs"], 0, "{body}");
+ assert_eq!(s["page"], "none", "{body}");
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (0, 4, 0, 0)
+ );
+
+ // Confirm: the strays are gathered, the bucket is empty, the row and the
+ // page never moved.
+ 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["total"], 1, "{body}");
+ assert_eq!(body["moved"], 1, "{body}");
+ assert_eq!(body["sessions"][0]["session_moved"], false, "{body}");
+ assert_eq!(body["sessions"][0]["summary"]["observations"], 4, "{body}");
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
+ (0, 0, 0, 0)
+ );
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.dst).await,
+ (1, 6, 1, 1)
+ );
+ assert!(
+ state
+ .wiki
+ .abs_path(scopes.ws, scopes.dst, &page_path(sid))
+ .exists()
+ );
+ assert_eq!(
+ read_page(&state, "default", "dst", sid).await,
+ StatusCode::OK
+ );
+ // Nothing left touching the bucket.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "from_project": "src", "project": "dst" }),
+ )
+ .await;
+ assert_eq!(body_json(resp).await["total"], 0);
+}
+
+/// An open session whose row already sits in the destination is re-homed
+/// without `force`: the row does not move, so the open-session guard does not
+/// apply (a pending job still does).
+#[tokio::test]
+async fn move_session_rehome_of_open_session_needs_no_force() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let sid = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid,
+ workspace_id: scopes.ws,
+ project_id: scopes.dst,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: Some("/repo/dst".into()),
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ scatter_observations(&store, sid, scopes.ws, scopes.src, 2).await;
+
+ 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["moved"], 1, "{body}");
+ assert_eq!(body["sessions"][0]["session_moved"], false, "{body}");
+ assert_eq!(body["sessions"][0]["summary"]["observations"], 2, "{body}");
+ assert_eq!(
+ rows_in_scope(&store, sid, scopes.ws, scopes.dst).await,
+ (1, 2, 0, 0)
+ );
+
+ // The same open session, batch-moved out of its own scope, still needs
+ // force: the row would move.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "from_project": "dst", "project": "src", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::CONFLICT);
}
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 95036809..f84f1a22 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -3075,11 +3075,14 @@ pub enum PagesMode {
/// dry run (`commit = false`), whose transaction is rolled back after counting.
#[derive(Debug, Clone)]
pub struct MoveSessionSummary {
- /// Whether the `sessions` row changed scope. `false` when the target
- /// scope equals the source scope (no-op; every count is zero).
+ /// Whether the `sessions` row changed scope. `false` when the row already
+ /// sat in the target scope: the call is then a "re-home" that only
+ /// re-stamps the session's rows still lying in other scopes, and every
+ /// count says how many of those there were (all zero when none).
pub session_moved: bool,
- /// `observations` rows re-stamped (every row of the session, including
- /// any that landed outside the session row's own scope).
+ /// `observations` rows re-stamped: every row of the session that was
+ /// outside the target scope, including any that landed outside the
+ /// session row's own scope. Rows already in the target are not counted.
pub observations: u64,
/// `handoffs` rows re-stamped (`from_session_id` = the session).
pub handoffs: u64,
@@ -3116,11 +3119,25 @@ pub struct MoveSessionSummary {
/// scheduler claim) into `(target_workspace, target_project)` in ONE
/// transaction, plus its `sessions/<session_id>.md` page per `pages`.
///
+/// Dependent rows are matched by session id alone, so a hybrid session whose
+/// events were scattered over other scopes (mid-session routing before the
+/// sticky mode) is gathered whole; only rows not already in the target are
+/// touched and counted.
+///
+/// A target equal to the session row's own scope is a **re-home**: the row
+/// stays put (`session_moved = false`) and the same sweep re-stamps every
+/// dependent row still lying in any other scope; a session with nothing
+/// outside the target reports zero counts (not an error). Its page rows are
+/// then handled wherever they sit outside the target: under
+/// [`PagesMode::Move`] they are re-stamped (refused with
+/// [`StoreError::PagePathTaken`] when the target already holds a latest page
+/// or more than one outside scope does), under [`PagesMode::Regenerate`]
+/// their latest rows are retired. In a real move the page rows handled are
+/// those of the source scope, as before.
+///
/// `commit = false` performs the same work and rolls the transaction back
-/// before returning, so the summary is an exact dry run. A target equal to the
-/// source is a no-op that reports zero counts and `session_moved = false`.
-/// `author_id` is the operator recorded on the `audit_log` row, as in
-/// [`rename_project`].
+/// before returning, so the summary is an exact dry run. `author_id` is the
+/// operator recorded on the `audit_log` row, as in [`rename_project`].
///
/// The `workspace_id`/`project_id` pairing triggers only guard INSERT, so the
/// target pair is validated against `projects` here before any UPDATE runs.
@@ -3180,9 +3197,7 @@ pub fn move_session(
to_project: target_project,
cwd,
};
- if from_workspace == target_workspace && from_project == target_project {
- return Ok(summary);
- }
+ let rehome = from_workspace == target_workspace && from_project == target_project;
let to_ws = target_workspace.as_bytes();
let to_proj = target_project.as_bytes();
@@ -3199,43 +3214,55 @@ pub fn move_session(
)));
}
- let sessions_updated = tx.execute(
- "UPDATE sessions SET workspace_id = ?1, project_id = ?2 WHERE id = ?3",
- params![&to_ws[..], &to_proj[..], &sid[..]],
- )?;
- summary.session_moved = sessions_updated == 1;
- // Fires `observations_fts_au` per row (delete + reinsert of the same
- // text); the FTS index stays consistent inside this transaction.
- summary.observations = tx.execute(
- "UPDATE observations SET workspace_id = ?1, project_id = ?2 WHERE session_id = ?3",
- params![&to_ws[..], &to_proj[..], &sid[..]],
- )? as u64;
- summary.handoffs = tx.execute(
- "UPDATE handoffs SET workspace_id = ?1, project_id = ?2 WHERE from_session_id = ?3",
- params![&to_ws[..], &to_proj[..], &sid[..]],
- )? as u64;
- summary.consolidation_jobs = tx.execute(
- "UPDATE session_consolidation_jobs SET workspace_id = ?1, project_id = ?2 \
- WHERE session_id = ?3",
- params![&to_ws[..], &to_proj[..], &sid[..]],
- )? as u64;
- summary.auto_improve_runs = tx.execute(
- "UPDATE auto_improve_runs SET workspace_id = ?1, project_id = ?2 WHERE session_id = ?3",
- params![&to_ws[..], &to_proj[..], &sid[..]],
- )? as u64;
- summary.auto_improve_claims = tx.execute(
- "UPDATE auto_improve_scheduler_claims SET workspace_id = ?1, project_id = ?2 \
- WHERE session_id = ?3",
- params![&to_ws[..], &to_proj[..], &sid[..]],
- )? as u64;
-
+ if !rehome {
+ let sessions_updated = tx.execute(
+ "UPDATE sessions SET workspace_id = ?1, project_id = ?2 WHERE id = ?3",
+ params![&to_ws[..], &to_proj[..], &sid[..]],
+ )?;
+ summary.session_moved = sessions_updated == 1;
+ }
+ // Every dependent row of the session not already in the target, whatever
+ // scope it lies in. Fires `observations_fts_au` per observation row
+ // (delete + reinsert of the same text); the FTS index stays consistent
+ // inside this transaction.
+ let restamp = |table: &str, session_col: &str| -> StoreResult<u64> {
+ Ok(tx.execute(
+ &format!(
+ "UPDATE {table} SET workspace_id = ?1, project_id = ?2 \
+ WHERE {session_col} = ?3 \
+ AND NOT (workspace_id = ?1 AND project_id = ?2)"
+ ),
+ params![&to_ws[..], &to_proj[..], &sid[..]],
+ )? as u64)
+ };
+ summary.observations = restamp("observations", "session_id")?;
+ summary.handoffs = restamp("handoffs", "from_session_id")?;
+ summary.consolidation_jobs = restamp("session_consolidation_jobs", "session_id")?;
+ summary.auto_improve_runs = restamp("auto_improve_runs", "session_id")?;
+ summary.auto_improve_claims = restamp("auto_improve_scheduler_claims", "session_id")?;
+
+ // Page rows to handle: the source scope's in a real move; in a re-home,
+ // any scope other than the target (the source IS the target).
let page_path = format!("sessions/{session_id}.md");
- let source_versions: i64 = tx.query_row(
- "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3",
- params![&from_ws[..], &from_proj[..], page_path.as_str()],
- |row| row.get(0),
+ let page_scope_sql = if rehome {
+ "NOT (workspace_id = ?1 AND project_id = ?2)"
+ } else {
+ "workspace_id = ?1 AND project_id = ?2"
+ };
+ let page_scope_params = if rehome {
+ (&to_ws[..], &to_proj[..])
+ } else {
+ (&from_ws[..], &from_proj[..])
+ };
+ let (candidate_versions, candidate_latest): (i64, i64) = tx.query_row(
+ &format!(
+ "SELECT COUNT(*), COALESCE(SUM(is_latest), 0) FROM pages \
+ WHERE {page_scope_sql} AND path = ?3"
+ ),
+ params![page_scope_params.0, page_scope_params.1, page_path.as_str()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
)?;
- if source_versions > 0 {
+ if candidate_versions > 0 {
match pages {
PagesMode::Move => {
let taken: Option<i64> = tx
@@ -3247,27 +3274,33 @@ pub fn move_session(
|row| row.get(0),
)
.optional()?;
- if taken.is_some() {
+ // Two latest rows cannot share the path in the target
+ // (`idx_pages_latest_path`): a re-home that finds latest
+ // rows in more than one outside scope is a collision too.
+ if taken.is_some() || candidate_latest > 1 {
return Err(StoreError::PagePathTaken { path: page_path });
}
summary.page_versions_moved = tx.execute(
- "UPDATE pages SET workspace_id = ?1, project_id = ?2 \
- WHERE workspace_id = ?3 AND project_id = ?4 AND path = ?5",
+ &format!(
+ "UPDATE pages SET workspace_id = ?4, project_id = ?5 \
+ WHERE {page_scope_sql} AND path = ?3"
+ ),
params![
+ page_scope_params.0,
+ page_scope_params.1,
+ page_path.as_str(),
&to_ws[..],
&to_proj[..],
- &from_ws[..],
- &from_proj[..],
- page_path.as_str()
],
)? as u64;
}
PagesMode::Regenerate => {
summary.pages_regenerated = tx.execute(
- "UPDATE pages SET is_latest = 0 \
- WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 \
- AND is_latest = 1",
- params![&from_ws[..], &from_proj[..], page_path.as_str()],
+ &format!(
+ "UPDATE pages SET is_latest = 0 \
+ WHERE {page_scope_sql} AND path = ?3 AND is_latest = 1"
+ ),
+ params![page_scope_params.0, page_scope_params.1, page_path.as_str()],
)? as u64;
}
}
@@ -5607,8 +5640,10 @@ pub(crate) mod tests {
assert_session_bundle_in_scope(&conn, sid, (src_ws, src_proj), (dst_ws, src_proj));
}
+ /// Same scope, nothing stray: a re-home with every count at zero, not
+ /// an error (the audit row is still written).
#[test]
- fn move_session_same_scope_is_a_noop_summary() {
+ fn move_session_same_scope_with_nothing_stray_reports_zero_counts() {
let (_tmp, mut conn, ws, proj) = fresh_db();
let sid = seed_movable_session(&mut conn, ws, proj);
@@ -5625,7 +5660,159 @@ pub(crate) mod tests {
assert_eq!(summary.from_workspace, ws);
assert_eq!(summary.to_project, proj);
assert_eq!(summary.cwd.as_deref(), Some("/repo/src"));
+ assert_session_bundle_in_scope(&conn, sid, (ws, proj), (WorkspaceId::new(), proj));
assert_eq!(session_page_versions(&conn, sid, ws, proj), (2, 1));
+ let audited: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM audit_log WHERE op = 'move_session'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(audited, 1);
+ }
+
+ /// Insert `n` observations of `sid` stamped into `(ws, proj)` directly,
+ /// the way mid-session routing before the sticky mode scattered events
+ /// into phantom projects.
+ fn scatter_observations(
+ conn: &mut Connection,
+ sid: SessionId,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ n: usize,
+ ) {
+ use ai_memory_core::ObservationKind;
+ for i in 0..n {
+ insert_observation(
+ conn,
+ &NewObservation {
+ session_id: sid,
+ workspace_id: ws,
+ project_id: proj,
+ kind: ObservationKind::PostToolUse,
+ extension: None,
+ source_event: None,
+ title: format!("stray-obs-{i}"),
+ body: "zebra token body".into(),
+ importance: 5,
+ },
+ )
+ .unwrap();
+ }
+ }
+
+ /// The phantom-bucket case: the session row already sits in the target,
+ /// some of its observations landed in another scope. Moving the session
+ /// to its own scope re-homes those rows and reports the real counts.
+ #[test]
+ fn move_session_rehomes_stray_rows_when_session_row_already_in_target() {
+ let (_tmp, mut conn, ws, target) = fresh_db();
+ let stray = get_or_create_project(&mut conn, &ws, "tmp", None).unwrap();
+ // Session (row, 2 observations, handoff, job, run, claim, page) in T.
+ let sid = seed_movable_session(&mut conn, ws, target);
+ // 3 observations of the same session stamped into S.
+ scatter_observations(&mut conn, sid, ws, stray, 3);
+ assert_eq!(
+ session_rows_in_scope(&conn, "observations", "session_id", sid, ws, stray),
+ 3
+ );
+
+ // Dry run: same counts, nothing changes.
+ let summary =
+ move_session(&mut conn, sid, ws, target, PagesMode::Move, None, false).unwrap();
+ assert!(!summary.session_moved);
+ assert_eq!(summary.observations, 3);
+ assert_eq!(
+ session_rows_in_scope(&conn, "observations", "session_id", sid, ws, stray),
+ 3
+ );
+
+ let summary =
+ move_session(&mut conn, sid, ws, target, PagesMode::Move, None, true).unwrap();
+ assert!(!summary.session_moved, "the row was already in the target");
+ assert_eq!(summary.observations, 3, "only the stray rows are counted");
+ assert_eq!(summary.handoffs, 0);
+ assert_eq!(summary.consolidation_jobs, 0);
+ assert_eq!(summary.auto_improve_runs, 0);
+ assert_eq!(summary.auto_improve_claims, 0);
+ assert_eq!(summary.page_versions_moved, 0);
+ assert_eq!(summary.pages_regenerated, 0);
+ assert_eq!(
+ summary.page_path, None,
+ "the page already sits in the target"
+ );
+ assert_eq!(summary.from_project, target);
+ assert_eq!(summary.to_project, target);
+
+ assert_eq!(
+ session_rows_in_scope(&conn, "observations", "session_id", sid, ws, target),
+ 5
+ );
+ assert_eq!(
+ session_rows_in_scope(&conn, "observations", "session_id", sid, ws, stray),
+ 0
+ );
+ assert_eq!(fts_hits_in_scope(&conn, sid, ws, target), 5);
+ assert_eq!(fts_hits_in_scope(&conn, sid, ws, stray), 0);
+ assert_eq!(
+ session_rows_in_scope(&conn, "sessions", "id", sid, ws, target),
+ 1
+ );
+ assert_eq!(session_page_versions(&conn, sid, ws, target), (2, 1));
+ }
+
+ /// A re-home also gathers the session page when its rows lie outside the
+ /// target: moved under `Move` (collision rule against the target),
+ /// retired under `Regenerate`.
+ #[test]
+ fn move_session_rehome_handles_page_rows_outside_target() {
+ let (_tmp, mut conn, ws, target) = fresh_db();
+ let stray = get_or_create_project(&mut conn, &ws, "tmp", None).unwrap();
+ let sid = seed_movable_session(&mut conn, ws, target);
+ let path = format!("sessions/{sid}.md");
+ // Park the page in the stray scope: nothing at the path in T.
+ conn.execute(
+ "UPDATE pages SET workspace_id = ?1, project_id = ?2 WHERE path = ?3",
+ params![ws.as_bytes(), stray.as_bytes(), path],
+ )
+ .unwrap();
+ assert_eq!(session_page_versions(&conn, sid, ws, target), (0, 0));
+ assert_eq!(session_page_versions(&conn, sid, ws, stray), (2, 1));
+
+ let summary =
+ move_session(&mut conn, sid, ws, target, PagesMode::Move, None, true).unwrap();
+ assert!(!summary.session_moved);
+ assert_eq!(summary.observations, 0);
+ assert_eq!(summary.page_versions_moved, 2);
+ assert_eq!(summary.page_path.as_deref(), Some(path.as_str()));
+ assert_eq!(session_page_versions(&conn, sid, ws, target), (2, 1));
+ assert_eq!(session_page_versions(&conn, sid, ws, stray), (0, 0));
+
+ // Stray latest AND a latest in the target: Move collides, Regenerate
+ // retires the stray one and leaves the target's page alone.
+ upsert_page(&mut conn, &page(ws, stray, &path, "stray again")).unwrap();
+ let err = move_session(&mut conn, sid, ws, target, PagesMode::Move, None, true)
+ .expect_err("a latest page at the path in the target must block the page move");
+ assert!(
+ matches!(&err, StoreError::PagePathTaken { path: p } if *p == path),
+ "unexpected error: {err:?}"
+ );
+ assert_eq!(session_page_versions(&conn, sid, ws, stray), (1, 1));
+ let summary = move_session(
+ &mut conn,
+ sid,
+ ws,
+ target,
+ PagesMode::Regenerate,
+ None,
+ true,
+ )
+ .unwrap();
+ assert_eq!(summary.pages_regenerated, 1);
+ assert_eq!(summary.page_versions_moved, 0);
+ assert_eq!(session_page_versions(&conn, sid, ws, stray), (1, 0));
+ assert_eq!(session_page_versions(&conn, sid, ws, target), (2, 1));
}
#[test]
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 5ccad44c..a05a5a42 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -2020,6 +2020,47 @@ impl ReaderPool {
.await
}
+ /// Ids of every session that touches `(workspace_id, project_id)`: a
+ /// `sessions` row in the scope OR at least one observation stamped into
+ /// it. The second leg catches the phantom projects that mid-session
+ /// routing before the sticky mode filled with observations of sessions
+ /// rooted elsewhere (no `sessions` row of their own), so a batch
+ /// `move-session` can empty such a bucket. Ordered by first touch (the
+ /// row's `started_at` or the earliest observation in the scope), then id.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_ids_touching_scope(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> StoreResult<Vec<SessionId>> {
+ self.with_conn(move |conn| {
+ let mut stmt = conn.prepare(
+ "SELECT id FROM ( \
+ SELECT id, started_at AS first_seen FROM sessions \
+ WHERE workspace_id = ?1 AND project_id = ?2 \
+ UNION ALL \
+ SELECT session_id AS id, MIN(created_at) AS first_seen FROM observations \
+ WHERE workspace_id = ?1 AND project_id = ?2 \
+ GROUP BY session_id \
+ ) \
+ GROUP BY id \
+ ORDER BY MIN(first_seen), id",
+ )?;
+ let rows = stmt.query_map(
+ params![workspace_id.as_bytes(), project_id.as_bytes()],
+ |row| row.get::<_, Vec<u8>>(0),
+ )?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(SessionId::from_slice(&r?)?);
+ }
+ Ok(out)
+ })
+ .await
+ }
+
/// How a `SessionEnd` should treat its target session (issue #152).
///
/// The old boolean ("is the session open?") conflated two very different
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index e509efe4..a5ba035b 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -1260,7 +1260,9 @@ impl WriterHandle {
/// `commit = false` the transaction is rolled back after counting, so the
/// summary is an exact dry run. The target project must already exist;
/// the caller moves the on-disk page file afterwards. `author_id` is the
- /// operator recorded on the audit row.
+ /// operator recorded on the audit row. A target equal to the session
+ /// row's own scope re-homes only the rows still lying elsewhere
+ /// (`session_moved = false`); see [`ops::move_session`].
///
/// # Errors
/// Returns [`StoreError::WriterClosed`] if the actor has shut down,
diff --git a/crates/ai-memory-store/tests/session_ids_touching_scope.rs b/crates/ai-memory-store/tests/session_ids_touching_scope.rs
new file mode 100644
index 00000000..9bf9044c
--- /dev/null
+++ b/crates/ai-memory-store/tests/session_ids_touching_scope.rs
@@ -0,0 +1,113 @@
+//! Integration tests for `ReaderPool::session_ids_touching_scope` (#402).
+//!
+//! A phantom project filled by pre-sticky mid-session routing holds
+//! observations of sessions rooted elsewhere and no `sessions` row of its
+//! own. The batch `move-session` must see those sessions, so "touching a
+//! scope" is: a `sessions` row in it OR at least one observation in it.
+
+use ai_memory_core::{ProjectId, SessionId, WorkspaceId};
+use ai_memory_store::Store;
+use rusqlite::{Connection, params};
+
+fn id(n: u8) -> [u8; 16] {
+ let mut b = [0u8; 16];
+ b[15] = n;
+ b
+}
+
+/// Workspace `w` with projects `a` and `b`; session 10 rooted in `b` with 3
+/// observations in `a` and 1 in `b`; session 11 rooted in `a` (started later)
+/// with 1 observation in `a`; session 12 rooted in `b` with no observations.
+fn seed(db_path: &std::path::Path) {
+ let conn = Connection::open(db_path).unwrap();
+ let now = 1_700_000_000_000_i64;
+ let (ws, a, b) = (id(1), id(2), id(3));
+
+ conn.execute(
+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'w', ?2)",
+ params![&ws[..], now],
+ )
+ .unwrap();
+ for (pid, name, rp) in [(&a, "proj-a", "/w/a"), (&b, "proj-b", "/w/b")] {
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5)",
+ params![&pid[..], &ws[..], name, rp, now],
+ )
+ .unwrap();
+ }
+ for (sid, proj, started) in [(10u8, &b, now), (11, &a, now + 10), (12, &b, now + 20)] {
+ conn.execute(
+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \
+ VALUES (?1, ?2, ?3, 'claude-code', '/w', ?4)",
+ params![&id(sid)[..], &ws[..], &proj[..], started],
+ )
+ .unwrap();
+ }
+ for (n, sid, proj, ts) in [
+ (20u8, 10u8, &a, now + 1),
+ (21, 10, &a, now + 2),
+ (22, 10, &a, now + 3),
+ (23, 10, &b, now + 4),
+ (24, 11, &a, now + 11),
+ ] {
+ conn.execute(
+ "INSERT INTO observations \
+ (id, session_id, workspace_id, project_id, kind, title, body, created_at) \
+ VALUES (?1, ?2, ?3, ?4, 'note', 't', 'x', ?5)",
+ params![&id(n)[..], &id(sid)[..], &ws[..], &proj[..], ts],
+ )
+ .unwrap();
+ }
+}
+
+fn sid(n: u8) -> SessionId {
+ SessionId::from_slice(&id(n)).unwrap()
+}
+
+#[tokio::test]
+async fn lists_sessions_with_a_row_or_an_observation_in_the_scope_oldest_first() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ seed(store.db_path());
+ let ws = WorkspaceId::from_slice(&id(1)).unwrap();
+ let a = ProjectId::from_slice(&id(2)).unwrap();
+ let b = ProjectId::from_slice(&id(3)).unwrap();
+
+ // `a`: session 10 through its observations (first at now+1), session 11
+ // through its row (now+10). Session 12 never touched `a`.
+ assert_eq!(
+ store
+ .reader
+ .session_ids_touching_scope(ws, a)
+ .await
+ .unwrap(),
+ vec![sid(10), sid(11)]
+ );
+ // `b`: session 10 through its row (now) and its late observation,
+ // session 12 through its row alone; each id once.
+ assert_eq!(
+ store
+ .reader
+ .session_ids_touching_scope(ws, b)
+ .await
+ .unwrap(),
+ vec![sid(10), sid(12)]
+ );
+}
+
+#[tokio::test]
+async fn empty_scope_lists_nothing() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ seed(store.db_path());
+ let ws = WorkspaceId::from_slice(&id(1)).unwrap();
+ assert!(
+ store
+ .reader
+ .session_ids_touching_scope(ws, ProjectId::from_slice(&id(9)).unwrap())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 2001e073..e144621c 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -362,7 +362,10 @@ impl Wiki {
/// under the watcher-ignored `.ai-memory-tmp.` prefix and deleted once the
/// rows are retired: left in place, the next reconciliation pass would
/// re-index it as a fresh latest page in the source scope. A store failure
- /// puts the file back where it was in both modes.
+ /// puts the file back where it was in both modes. When `from == to` (a
+ /// re-home of a session already rooted in the destination) there is no
+ /// file to relocate: the file step is skipped and only the store sweep
+ /// runs.
///
/// # Errors
/// Returns [`WikiError::DestinationPageExists`] when the destination
@@ -394,7 +397,7 @@ impl Wiki {
.project_root(from.0, from.1)
.join("sessions")
.join(&file_name);
- let parked = if src.is_file() {
+ let parked = if from != to && src.is_file() {
let target = match pages {
PagesMode::Move => {
let dst = self
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 8337de2f..9500822c 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -13,7 +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`. |
+| `move-session <id> --to --confirm` | ✅ yes | no | yes (move it back) | Re-stamps one session (or every session touching `--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. |
@@ -366,14 +366,20 @@ 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
+Moves one session, or every session touching `--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.
+alone. Sessions already rooted in the destination only get their stray rows
+re-homed: the `sessions` row stays, every row of theirs still lying in
+another scope is gathered into the destination, and the report says
+`session_moved: false` with the counts. The batch form therefore sees a
+session through a `sessions` row in the source OR observations stamped into
+it, which is what empties a phantom bucket that holds only observations of
+sessions rooted elsewhere (mid-session routing before sticky).
**Request.** `POST /admin/move-session` takes either
`{"session_id": "<uuid>", "workspace"?, "project", "pages"?, "confirm"?,
@@ -413,7 +419,10 @@ 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
+`create`), reject a batch whose source is the destination (422; the single
+form with the session's own project is a re-home), run the guards (the
+open-session guard does not apply to a re-home, whose row does not move),
+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
@@ -442,7 +451,8 @@ 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`
+Response (`MoveSessionReport`): `session_id`, `dry_run`, `session_moved`
+(`false` for a re-home), `from`/`to`
(`{workspace, project}`), `summary` (`observations`, `handoffs`,
`consolidation_jobs`, `auto_improve_runs`, `auto_improve_claims`,
`page_versions_moved`, `pages_regenerated`), `page` (`moved` |
@@ -455,9 +465,11 @@ 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`.
+- **Batch source equals the destination** → 422 (the single form with the
+ session's own project is a re-home, 200 with `session_moved: false`).
+- **Open session (unless the row already sits in the destination), 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