Skip to content

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

Rust

fix(move-session): name every scope the move will drain

AkitaOnRailsc1b859aa130e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14b8c9b1..86e5d9c9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,7 +34,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
when its page needs nothing), 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)
+ admission op `move_session`. The dry run and the `/admin/move-session`
+ response name every scope the move would drain (`source_scopes`), because
+ gathering by session id can empty a project the caller never named and
+ moving back does not restore the original split. (#402)
- Added a read path for one session's raw hook observations, before any
consolidation: the MCP tool `memory_read_session_observations` and the
`/api/v1` routes `GET .../projects/{project}/sessions` and
diff --git a/crates/ai-memory-cli/src/commands/move_session.rs b/crates/ai-memory-cli/src/commands/move_session.rs
index 475e25a6..16dee086 100644
--- a/crates/ai-memory-cli/src/commands/move_session.rs
+++ b/crates/ai-memory-cli/src/commands/move_session.rs
@@ -116,6 +116,7 @@ fn print_session_report(report: &serde_json::Value, applied: bool) {
&report["summary"],
report["page"].as_str().unwrap_or("none"),
);
+ print_source_scopes(report, &scope(&report["to"]));
if let Some(warning) = report["cwd_warning"].as_str() {
println!("Warning: {warning}");
}
@@ -201,6 +202,43 @@ fn print_batch_report(report: &serde_json::Value, applied: bool) {
print_checkpoints(report);
}
+/// Name every scope the move will drain, when it is more than the one the
+/// caller asked about.
+///
+/// A move gathers dependent rows by session id alone, so it can empty a
+/// project nobody named — and moving back afterwards cannot restore the
+/// original split. The operator sees that here, in the dry run, rather than
+/// inferring it from a count that came out larger than expected.
+fn print_source_scopes(report: &serde_json::Value, destination: &str) {
+ let Some(scopes) = report["source_scopes"].as_array() else {
+ return;
+ };
+ let others: Vec<_> = scopes
+ .iter()
+ .filter(|s| s["observations"].as_u64().unwrap_or(0) > 0)
+ .collect();
+ if others.len() < 2 {
+ return;
+ }
+ println!(
+ " gathering observations out of {} scopes into {destination}:",
+ others.len()
+ );
+ for s in &others {
+ println!(
+ " {}/{}: {} observation(s)",
+ s["workspace"].as_str().unwrap_or("?"),
+ s["project"].as_str().unwrap_or("?"),
+ s["observations"].as_u64().unwrap_or(0),
+ );
+ }
+ println!(
+ " Note: this empties every scope listed above, not only the one named as the source. \
+ Moving the session back later returns all rows to a single project — the split shown \
+ here is not restored."
+ );
+}
+
fn print_counts(summary: &serde_json::Value, page: &str) {
let n = |key: &str| summary[key].as_u64().unwrap_or(0);
println!(" observations: {}", n("observations"));
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 96f4df2a..8ab19790 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -4251,6 +4251,17 @@ pub struct MoveSessionCounts {
pub pages_regenerated: u64,
}
+/// One scope a move gathers observations out of, for the operator's report.
+#[derive(Debug, Serialize)]
+pub struct MoveSessionScopeCount {
+ /// Workspace name.
+ pub workspace: String,
+ /// Project name.
+ pub project: String,
+ /// Observations of the session currently stamped into that scope.
+ pub observations: u64,
+}
+
/// Wire-format report for one session in `POST /admin/move-session`.
#[derive(Debug, Serialize)]
pub struct MoveSessionReport {
@@ -4266,6 +4277,12 @@ pub struct MoveSessionReport {
/// the confirm run will create it. Never set on a confirmed move.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub would_create_project: bool,
+ /// Every scope holding observations of this session other than the
+ /// destination, with counts. More than one entry — or one that is not
+ /// `from` — means the move drains a project the caller did not name.
+ /// Empty when everything already sits in the destination.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub source_scopes: Vec<MoveSessionScopeCount>,
/// Scope the session came from.
pub from: ScopeLabel,
/// Scope the session now belongs to.
@@ -4552,6 +4569,20 @@ fn move_session_cwd_warning(cwd: Option<&str>, to_project: &str) -> Option<Strin
))
}
+fn move_session_source_scopes(
+ summary: &ai_memory_store::MoveSessionSummary,
+) -> Vec<MoveSessionScopeCount> {
+ summary
+ .source_scopes
+ .iter()
+ .map(|scope| MoveSessionScopeCount {
+ workspace: scope.workspace_name.clone(),
+ project: scope.project_name.clone(),
+ observations: scope.observations,
+ })
+ .collect()
+}
+
fn move_session_counts(summary: &ai_memory_store::MoveSessionSummary) -> MoveSessionCounts {
MoveSessionCounts {
observations: summary.observations,
@@ -4650,6 +4681,7 @@ async fn move_planned_session(
dry_run: true,
session_moved: true,
would_create_project: true,
+ source_scopes: Vec::new(),
from: plan.from_label,
to: plan.to_label,
page: move_session_page_label(req.pages, touched_rows, src_file.is_file(), false),
@@ -4690,6 +4722,7 @@ async fn move_planned_session(
dry_run: true,
session_moved: summary.session_moved,
would_create_project: false,
+ source_scopes: move_session_source_scopes(&summary),
from: plan.from_label,
to: plan.to_label,
summary: move_session_counts(&summary),
@@ -4729,6 +4762,7 @@ async fn move_planned_session(
dry_run: false,
session_moved: outcome.summary.session_moved,
would_create_project: false,
+ source_scopes: move_session_source_scopes(&outcome.summary),
from: plan.from_label,
to: plan.to_label,
summary: move_session_counts(&outcome.summary),
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index dd941855..ee740f19 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -58,8 +58,7 @@ pub use reader::{
PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool,
ReindexTargetStatus, RelatedPage, RrfContributions, ScopeRow, SearchExplain,
SessionDependentRows, SessionEndDisposition, SessionSummary, StatusCounts, StoredEmbedding,
- StoredPageBody,
- WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
+ StoredPageBody, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
};
pub use scope::{
ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, WORKSPACE_PROJECT_PAIR_REQUIRED,
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 99dccdc5..41ef311c 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -3071,6 +3071,29 @@ pub enum PagesMode {
Regenerate,
}
+/// One scope a move drained observations out of, and how many.
+///
+/// A move matches dependent rows by session id alone, so it gathers rows from
+/// EVERY scope they landed in — not just the one the caller named as the
+/// source. That is deliberate (it is what repairs a session scattered by
+/// pre-sticky mid-session routing), but it is not cleanly reversible: moving
+/// back sends every row to one scope, and the original per-row attribution is
+/// gone. So the caller is told which scopes it is about to drain, by name,
+/// before it commits.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct MoveSessionSourceScope {
+ /// Workspace the rows are currently stamped with.
+ pub workspace_id: WorkspaceId,
+ /// Project the rows are currently stamped with.
+ pub project_id: ProjectId,
+ /// Workspace name, resolved for the operator-facing report.
+ pub workspace_name: String,
+ /// Project name, resolved for the operator-facing report.
+ pub project_name: String,
+ /// Observations of this session currently in that scope.
+ pub observations: u64,
+}
+
/// Summary returned by [`move_session`] and exposed via
/// [`crate::writer::WriterHandle::move_session`]. Populated identically for a
/// dry run (`commit = false`), whose transaction is rolled back after counting.
@@ -3117,6 +3140,11 @@ pub struct MoveSessionSummary {
/// (historical truth; the caller may warn when it no longer matches the
/// destination project).
pub cwd: Option<String>,
+ /// Scopes holding observations of this session that are NOT the target,
+ /// with their counts, newest-largest first. More than one entry means the
+ /// move will drain a project the caller did not name; an empty list means
+ /// everything already sits in the target.
+ pub source_scopes: Vec<MoveSessionSourceScope>,
}
/// Re-stamp one session and every row that hangs off it (`observations`,
@@ -3202,6 +3230,7 @@ pub fn move_session(
to_workspace: target_workspace,
to_project: target_project,
cwd,
+ source_scopes: Vec::new(),
};
let rehome = from_workspace == target_workspace && from_project == target_project;
@@ -3227,6 +3256,42 @@ pub fn move_session(
)?;
summary.session_moved = sessions_updated == 1;
}
+ // Which scopes this move is about to drain, resolved to names BEFORE the
+ // re-stamp moves the rows. A move gathers by session id alone, so it can
+ // empty a project the caller never named; the operator sees that in the
+ // dry run rather than discovering it afterwards, when the original
+ // attribution is no longer recoverable.
+ {
+ let mut stmt = tx.prepare(
+ "SELECT o.workspace_id, o.project_id, w.name, p.name, COUNT(*) \
+ FROM observations o \
+ JOIN workspaces w ON w.id = o.workspace_id \
+ JOIN projects p ON p.id = o.project_id \
+ WHERE o.session_id = ?1 AND NOT (o.workspace_id = ?2 AND o.project_id = ?3) \
+ GROUP BY o.workspace_id, o.project_id \
+ ORDER BY COUNT(*) DESC",
+ )?;
+ let rows = stmt.query_map(params![&sid[..], &to_ws[..], &to_proj[..]], |row| {
+ Ok((
+ row.get::<_, Vec<u8>>(0)?,
+ row.get::<_, Vec<u8>>(1)?,
+ row.get::<_, String>(2)?,
+ row.get::<_, String>(3)?,
+ row.get::<_, i64>(4)?,
+ ))
+ })?;
+ for row in rows {
+ let (ws_bytes, proj_bytes, workspace_name, project_name, count) = row?;
+ summary.source_scopes.push(MoveSessionSourceScope {
+ workspace_id: WorkspaceId::from_slice(&ws_bytes)?,
+ project_id: ProjectId::from_slice(&proj_bytes)?,
+ workspace_name,
+ project_name,
+ observations: u64::try_from(count).unwrap_or(0),
+ });
+ }
+ }
+
// 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
@@ -5768,6 +5833,55 @@ pub(crate) mod tests {
}
}
+ /// A move gathers dependent rows by session id alone, so it drains every
+ /// scope they landed in — including projects the caller never named. That
+ /// is deliberate, but it is not cleanly reversible, so the dry run has to
+ /// say which scopes it is about to empty before anything is committed.
+ #[test]
+ fn move_session_dry_run_names_every_scope_it_will_drain() {
+ let (_tmp, mut conn, ws, target) = fresh_db();
+ let unnamed_a = get_or_create_project(&mut conn, &ws, "scratchpad", None).unwrap();
+ let unnamed_b = get_or_create_project(&mut conn, &ws, "tmp", None).unwrap();
+ let sid = seed_movable_session(&mut conn, ws, target);
+ scatter_observations(&mut conn, sid, ws, unnamed_a, 3);
+ scatter_observations(&mut conn, sid, ws, unnamed_b, 1);
+
+ // Dry run: nothing is written, but the report must already name both
+ // scopes it would empty.
+ let summary =
+ move_session(&mut conn, sid, ws, target, PagesMode::Move, None, false).unwrap();
+
+ let named: Vec<(String, u64)> = summary
+ .source_scopes
+ .iter()
+ .map(|s| (s.project_name.clone(), s.observations))
+ .collect();
+ assert_eq!(
+ named,
+ vec![("scratchpad".to_string(), 3), ("tmp".to_string(), 1)],
+ "both drained scopes must be named, largest first"
+ );
+ assert!(
+ summary.source_scopes.iter().all(|s| s.workspace_id == ws),
+ "each entry carries its resolved scope ids"
+ );
+ // The dry run really was a dry run.
+ assert_eq!(
+ session_rows_in_scope(&conn, "observations", "session_id", sid, ws, unnamed_a),
+ 3
+ );
+
+ // The destination itself is never listed as a scope to drain.
+ let confirmed =
+ move_session(&mut conn, sid, ws, target, PagesMode::Move, None, true).unwrap();
+ assert_eq!(confirmed.observations, 4);
+ let after = move_session(&mut conn, sid, ws, target, PagesMode::Move, None, false).unwrap();
+ assert!(
+ after.source_scopes.is_empty(),
+ "with everything in the destination there is nothing left to drain"
+ );
+ }
+
/// 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.
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 4330fc68..430669ca 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -485,6 +485,28 @@ Failure modes:
- **Store failure after the file moved** → 500, file renamed back; the
error names the manual repair if that rollback also fails.
+**It drains every scope, not just the one you named.** Dependent rows are
+matched by session id alone, so a session whose observations were scattered
+across projects (pre-`sticky` mid-session routing, for instance) is gathered
+whole. That is the point of the command — but it means a move can empty a
+project you did not mention, and it is **not cleanly reversible**: moving the
+session back later returns every row to a single project, and the original
+per-row split is gone.
+
+The dry run therefore names each scope it would drain, with counts:
+
+```text
+ gathering observations out of 2 scopes into default/acme-api:
+ default/scratchpad: 3 observation(s)
+ default/tmp: 1 observation(s)
+ Note: this empties every scope listed above, not only the one named as the
+ source. Moving the session back later returns all rows to a single project —
+ the split shown here is not restored.
+```
+
+`POST /admin/move-session` reports the same list as `source_scopes`. Read it
+before confirming.
+
### `checkpoints`
```bash