Skip to content

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

Rust

fix(admin,cli): move-session dry-run never creates, clearer re-home labels and messages (#402)

Sergio Aguirre3f3e18f9f366
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 42c23d7b..1d205bd0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,17 +18,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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
+ regenerate` retires the source page (clearing the session's
+ `summary_page_id`) 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
+ run and the CLI prints the command to apply (with `--create` the dry run
+ reports `would_create_project` and creates nothing). 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. 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
+ (`session_moved: false`, open-session guard not applied) and only its rows
+ still lying in other scopes are gathered (`page: already in destination`
+ 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)
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 43bc1926..12970c3f 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -613,15 +613,15 @@ pub struct MoveProjectArgs {
}
/// Arguments for `move-session`.
+///
+/// Exactly one of `<SESSION_ID>` and `--from-project` names what moves; the
+/// `what` group makes clap's error name both when neither is given.
#[derive(Debug, Args)]
+#[command(group = clap::ArgGroup::new("what").required(true).args(["session_id", "from_project"]))]
pub struct MoveSessionArgs {
/// Session id (UUID) to move. Omit it and pass `--from-project` to move
/// 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 touching this project (a session row
/// here or observations stamped into it). Resolved like other commands
diff --git a/crates/ai-memory-cli/src/commands/move_session.rs b/crates/ai-memory-cli/src/commands/move_session.rs
index 7dec10e3..475e25a6 100644
--- a/crates/ai-memory-cli/src/commands/move_session.rs
+++ b/crates/ai-memory-cli/src/commands/move_session.rs
@@ -107,6 +107,7 @@ fn print_session_report(report: &serde_json::Value, applied: bool) {
scope(&report["from"]),
scope(&report["to"]),
);
+ print_would_create(report);
println!(
" session row: {}",
session_row_line(report, applied)
@@ -118,6 +119,26 @@ fn print_session_report(report: &serde_json::Value, applied: bool) {
if let Some(warning) = report["cwd_warning"].as_str() {
println!("Warning: {warning}");
}
+ print_checkpoints(report);
+}
+
+/// Dry run with `--create` against a destination that does not exist yet.
+fn print_would_create(report: &serde_json::Value) {
+ if report["would_create_project"].as_bool().unwrap_or(false) {
+ println!(
+ " would create project {} (absent; created on --confirm)",
+ scope(&report["to"])
+ );
+ }
+}
+
+/// The wiki checkpoints a confirmed run took: `pre_checkpoint` only when the
+/// tree had uncommitted changes before the move, `checkpoint` when the move
+/// changed the tree.
+fn print_checkpoints(report: &serde_json::Value) {
+ if let Some(oid) = report["pre_checkpoint"].as_str() {
+ println!("Pre-move checkpoint: {oid}");
+ }
if let Some(oid) = report["checkpoint"].as_str() {
println!("Checkpoint: {oid}");
}
@@ -132,15 +153,16 @@ fn print_batch_report(report: &serde_json::Value, applied: bool) {
scope(&report["from"]),
scope(&report["to"]),
);
+ print_would_create(report);
if let Some(sessions) = report["sessions"].as_array() {
println!(
- "{:<38} {:<8} {:>6} {:>8} {:>5} {:<12} cwd",
+ "{:<38} {:<8} {:>6} {:>8} {:>5} {:<22} cwd",
"session_id", "row", "obs", "handoffs", "jobs", "page"
);
- println!("{}", "-".repeat(99));
+ println!("{}", "-".repeat(109));
for s in sessions {
println!(
- "{:<38} {:<8} {:>6} {:>8} {:>5} {:<12} {}",
+ "{:<38} {:<8} {:>6} {:>8} {:>5} {:<22} {}",
s["session_id"].as_str().unwrap_or("?"),
if s["session_moved"].as_bool().unwrap_or(false) {
"moved"
@@ -176,9 +198,7 @@ fn print_batch_report(report: &serde_json::Value, applied: bool) {
);
}
}
- if let Some(oid) = report["checkpoint"].as_str() {
- println!("Checkpoint: {oid}");
- }
+ print_checkpoints(report);
}
fn print_counts(summary: &serde_json::Value, page: &str) {
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 70ffe7c4..96f4df2a 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -4217,6 +4217,8 @@ struct MoveSessionRequest {
#[serde(default)]
force: bool,
/// Create the destination workspace/project when absent instead of 404.
+ /// A dry run never creates: it reports `would_create_project: true` and
+ /// the counts computed against an absent target.
#[serde(default)]
create: bool,
}
@@ -4260,6 +4262,10 @@ pub struct MoveSessionReport {
/// row already sat in the destination and only stray rows (the counts
/// below) were gathered into it.
pub session_moved: bool,
+ /// Dry run with `create` against a destination that does not exist yet:
+ /// 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,
/// Scope the session came from.
pub from: ScopeLabel,
/// Scope the session now belongs to.
@@ -4267,7 +4273,9 @@ pub struct MoveSessionReport {
/// Row counts.
pub summary: MoveSessionCounts,
/// What happened (or would happen) to `sessions/<id>.md`: `"moved"`,
- /// `"regenerated"`, or `"none"` when the session has no page.
+ /// `"regenerated"`, `"already in destination"` (re-home whose page rows
+ /// all sit in the destination), or `"none"` when the session has no page
+ /// anywhere.
pub page: &'static str,
/// The session's recorded working directory, left untouched.
#[serde(skip_serializing_if = "Option::is_none")]
@@ -4288,6 +4296,9 @@ pub struct MoveSessionReport {
pub struct MoveSessionBatchReport {
/// `true` when nothing was written (no `confirm`).
pub dry_run: bool,
+ /// Dry run with `create` against a destination that does not exist yet.
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub would_create_project: bool,
/// Source scope.
pub from: ScopeLabel,
/// Destination scope.
@@ -4316,7 +4327,7 @@ struct MoveSessionPlan {
/// well sit elsewhere, even in `to`).
from: (WorkspaceId, ProjectId),
from_label: ScopeLabel,
- to: (WorkspaceId, ProjectId),
+ to: MoveTarget,
to_label: ScopeLabel,
/// Where the `sessions` row sits right now.
row_scope: (WorkspaceId, ProjectId),
@@ -4326,7 +4337,24 @@ struct MoveSessionPlan {
impl MoveSessionPlan {
/// The row already sits in the destination: only stray rows move.
fn is_rehome(&self) -> bool {
- self.row_scope == self.to
+ self.to.existing() == Some(self.row_scope)
+ }
+}
+
+/// The destination of a move: an existing scope, or (dry run with `create`
+/// only) a scope that does not exist yet and would be created on confirm.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum MoveTarget {
+ Existing((WorkspaceId, ProjectId)),
+ WouldCreate,
+}
+
+impl MoveTarget {
+ fn existing(self) -> Option<(WorkspaceId, ProjectId)> {
+ match self {
+ Self::Existing(scope) => Some(scope),
+ Self::WouldCreate => None,
+ }
}
}
@@ -4384,20 +4412,54 @@ async fn scope_label(state: &AdminState, ws: WorkspaceId, proj: ProjectId) -> Sc
ScopeLabel { workspace, project }
}
-/// Resolve the destination scope: existing only (404) unless `create`.
+/// Resolve the destination scope: existing only (404) unless `create`. A
+/// dry run never writes, so with `create` and no `confirm` an absent
+/// destination resolves to [`MoveTarget::WouldCreate`] instead of a row.
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
+ confirm: bool,
+) -> Result<MoveTarget, MoveErr> {
+ if create && confirm {
+ return create_ws_proj(state, workspace, project)
+ .await
+ .map(MoveTarget::Existing);
+ }
+ match lookup_existing_scope(&state.reader, workspace, project).await {
+ Ok(scope) => Ok(MoveTarget::Existing(scope.as_tuple())),
+ Err(e) if create && e.is_not_found() => Ok(MoveTarget::WouldCreate),
+ Err(e) => Err(scope_err(e)),
}
}
+/// Dry-run counts of a move into a destination that does not exist yet:
+/// nothing of the session can already be there, so every row keyed to it
+/// moves, and the page rows are those of `from` (moved or retired per
+/// `pages`). Read-only; the store never sees the absent target.
+async fn preview_move_into_absent_target(
+ reader: &ReaderPool,
+ session_id: SessionId,
+ from: (WorkspaceId, ProjectId),
+ pages: PagesMode,
+) -> Result<MoveSessionCounts, StoreError> {
+ let rows = reader.session_dependent_rows(session_id, from).await?;
+ let (page_versions_moved, pages_regenerated) = match pages {
+ PagesMode::Move => (rows.page_versions, 0),
+ PagesMode::Regenerate => (0, rows.page_latest),
+ };
+ Ok(MoveSessionCounts {
+ observations: rows.observations,
+ handoffs: rows.handoffs,
+ consolidation_jobs: rows.consolidation_jobs,
+ auto_improve_runs: rows.auto_improve_runs,
+ auto_improve_claims: rows.auto_improve_claims,
+ page_versions_moved,
+ pages_regenerated,
+ })
+}
+
/// `(session still open, consolidation job pending or running)` for the
/// live-session guards.
async fn session_move_blockers(
@@ -4506,8 +4568,10 @@ fn move_session_page_label(
pages: PagesMode,
touched_rows: bool,
touched_file: bool,
+ already_in_target: bool,
) -> &'static str {
match (pages, touched_rows || touched_file) {
+ (_, false) if already_in_target => "already in destination",
(_, false) => "none",
(PagesMode::Move, true) => "moved",
(PagesMode::Regenerate, true) => "regenerated",
@@ -4541,7 +4605,7 @@ async fn move_planned_session(
Json(serde_json::json!({
"error": format!(
"session {sid} is still open (no session end recorded); \
- finish it or re-run with force=true"
+ finish it or force the move (--force / force: true)"
)
})),
));
@@ -4552,41 +4616,72 @@ async fn move_planned_session(
Json(serde_json::json!({
"error": format!(
"session {sid} has a pending or running consolidation job; \
- wait for it or re-run with force=true"
+ wait for it or force the move (--force / 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. 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 cwd_warning = move_session_cwd_warning(plan.cwd.as_deref(), &plan.to_label.project);
let file_name = format!("{sid}.md");
let src_file = state
.wiki
.project_root(plan.from.0, plan.from.1)
.join("sessions")
.join(&file_name);
+
+ // Dry run with `create` against an absent destination: nothing exists to
+ // collide with, and the store cannot re-stamp into a scope that has no
+ // row, so the counts come from a read-only preview.
+ let to = match plan.to {
+ MoveTarget::Existing(to) => to,
+ MoveTarget::WouldCreate => {
+ debug_assert!(
+ !req.confirm,
+ "an absent target is only planned for a dry run"
+ );
+ let counts = preview_move_into_absent_target(&state.reader, sid, plan.from, req.pages)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ let touched_rows = counts.page_versions_moved > 0 || counts.pages_regenerated > 0;
+ return Ok(MoveSessionReport {
+ session_id: sid.to_string(),
+ dry_run: true,
+ session_moved: true,
+ would_create_project: true,
+ from: plan.from_label,
+ to: plan.to_label,
+ page: move_session_page_label(req.pages, touched_rows, src_file.is_file(), false),
+ summary: counts,
+ cwd: plan.cwd,
+ cwd_warning,
+ pre_checkpoint: None,
+ checkpoint: None,
+ });
+ }
+ };
+
+ // 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. 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 dst_file = state
.wiki
- .project_root(plan.to.0, plan.to.1)
+ .project_root(to.0, to.1)
.join("sessions")
.join(&file_name);
- let file_moves = plan.from != plan.to && src_file.is_file();
+ let file_moves = plan.from != 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(),
)));
}
- 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)
+ .move_session(sid, to.0, 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;
@@ -4594,10 +4689,16 @@ async fn move_planned_session(
session_id: sid.to_string(),
dry_run: true,
session_moved: summary.session_moved,
+ would_create_project: false,
from: plan.from_label,
to: plan.to_label,
summary: move_session_counts(&summary),
- page: move_session_page_label(req.pages, touched_rows, file_moves),
+ page: move_session_page_label(
+ req.pages,
+ touched_rows,
+ file_moves,
+ summary.page_versions_in_target > 0,
+ ),
cwd: plan.cwd,
cwd_warning,
pre_checkpoint: None,
@@ -4618,14 +4719,7 @@ async fn move_planned_session(
// 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),
- )
+ .move_session_page(sid, plan.from, to, req.pages, author_id, Some(move_ctx))
.await
.map_err(move_session_wiki_err)?;
let touched_rows =
@@ -4634,6 +4728,7 @@ async fn move_planned_session(
session_id: sid.to_string(),
dry_run: false,
session_moved: outcome.summary.session_moved,
+ would_create_project: false,
from: plan.from_label,
to: plan.to_label,
summary: move_session_counts(&outcome.summary),
@@ -4641,6 +4736,7 @@ async fn move_planned_session(
req.pages,
touched_rows,
outcome.file != SessionPageFile::Absent,
+ outcome.summary.page_versions_in_target > 0,
),
cwd: plan.cwd,
cwd_warning,
@@ -4672,7 +4768,9 @@ async fn move_single_session(
.workspace
.clone()
.unwrap_or_else(|| from_label.workspace.clone());
- let to = resolve_move_session_target(state, &to_workspace, &req.project, req.create).await?;
+ let to =
+ resolve_move_session_target(state, &to_workspace, &req.project, req.create, req.confirm)
+ .await?;
let plan = MoveSessionPlan {
session_id,
from: (from_ws, from_proj),
@@ -4725,9 +4823,16 @@ async fn move_session_batch(
.workspace
.clone()
.unwrap_or_else(|| from_workspace.clone());
- let to = match resolve_move_session_target(state, &to_workspace, &req.project, req.create).await
+ let to = match resolve_move_session_target(
+ state,
+ &to_workspace,
+ &req.project,
+ req.create,
+ req.confirm,
+ )
+ .await
{
- Ok(ids) => ids,
+ Ok(target) => target,
Err(e) => return e.into_response(),
};
let from_label = ScopeLabel {
@@ -4738,7 +4843,7 @@ async fn move_session_batch(
workspace: to_workspace,
project: req.project.clone(),
};
- if from == to {
+ if to.existing() == Some(from) {
return (
StatusCode::UNPROCESSABLE_ENTITY,
Json(serde_json::json!({
@@ -4754,8 +4859,8 @@ async fn move_session_batch(
StatusCode::CONFLICT,
Json(serde_json::json!({
"error": format!(
- "{}/{} is the active session's project; re-run with force=true to move its \
- sessions anyway",
+ "{}/{} is the active session's project; force the move (--force / \
+ force: true) to move its sessions anyway",
from_label.workspace, from_label.project
)
})),
@@ -4789,7 +4894,8 @@ async fn move_session_batch(
// 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 {
+ let (plan_from, plan_from_label) = if row_scope == from || to.existing() == Some(row_scope)
+ {
(from, from_label.clone())
} else {
(
@@ -4844,6 +4950,7 @@ async fn move_session_batch(
}
let report = MoveSessionBatchReport {
dry_run: !req.confirm,
+ would_create_project: to == MoveTarget::WouldCreate,
from: from_label,
to: to_label,
total,
diff --git a/crates/ai-memory-mcp/tests/admin_move_session.rs b/crates/ai-memory-mcp/tests/admin_move_session.rs
index 9e157643..d8cec5e7 100644
--- a/crates/ai-memory-mcp/tests/admin_move_session.rs
+++ b/crates/ai-memory-mcp/tests/admin_move_session.rs
@@ -737,6 +737,70 @@ async fn move_session_target_404_unless_create() {
(1, 2, 1, 1)
);
+ // Dry run with create: the full plan is reported, nothing is created.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({
+ "session_id": sid.to_string(),
+ "workspace": "fresh-ws",
+ "project": "brand-new",
+ "create": true
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["dry_run"], true, "{body}");
+ assert_eq!(body["would_create_project"], true, "{body}");
+ assert_eq!(body["session_moved"], true, "{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!(
+ store
+ .reader
+ .find_workspace("fresh-ws".to_string())
+ .await
+ .unwrap()
+ .is_none(),
+ "a dry run must not create the workspace"
+ );
+ let dst_projects: i64 = store
+ .reader
+ .with_conn(|conn| {
+ Ok(conn.query_row(
+ "SELECT COUNT(*) FROM projects WHERE name = 'brand-new'",
+ [],
+ |r| r.get(0),
+ )?)
+ })
+ .await
+ .unwrap();
+ assert_eq!(dst_projects, 0, "a dry run must not create the project row");
+ // Batch dry run with create behaves the same.
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({ "from_project": "src", "project": "brand-new", "create": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["would_create_project"], true, "{body}");
+ assert_eq!(body["total"], 1, "{body}");
+ assert_eq!(body["sessions"][0]["would_create_project"], true, "{body}");
+ assert!(
+ store
+ .reader
+ .find_project(scopes.ws, "brand-new".to_string())
+ .await
+ .unwrap()
+ .is_none()
+ );
+
let resp = post(
&state,
"/admin/move-session",
@@ -752,6 +816,7 @@ async fn move_session_target_404_unless_create() {
assert_eq!(resp.status(), StatusCode::OK);
let body = body_json(resp).await;
assert_eq!(body["to"]["workspace"], "fresh-ws", "{body}");
+ assert!(body.get("would_create_project").is_none(), "{body}");
let new_ws = store
.reader
.find_workspace("fresh-ws".to_string())
@@ -826,7 +891,7 @@ async fn move_session_rejects_bad_shapes() {
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!(body["page"], "already in destination", "{body}");
assert_eq!(
rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
(1, 2, 1, 1)
@@ -905,7 +970,7 @@ async fn move_session_batch_empties_phantom_bucket_with_only_observations() {
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!(s["page"], "already in destination", "{body}");
assert_eq!(
rows_in_scope(&store, sid, scopes.ws, scopes.src).await,
(0, 4, 0, 0)
@@ -988,6 +1053,7 @@ async fn move_session_rehome_of_open_session_needs_no_force() {
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!(body["sessions"][0]["page"], "none", "{body}");
assert_eq!(
rows_in_scope(&store, sid, scopes.ws, scopes.dst).await,
(1, 2, 0, 0)
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index dc9f6d08..e3c3e68d 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -56,8 +56,8 @@ pub use reader::{
FeedbackFinding, GraphVia, HealthDetail, HealthPage, ObservationHit, OpenSession, PageAuthor,
PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool,
ReindexTargetStatus, RelatedPage, RrfContributions, ScopeRow, SearchExplain,
- SessionEndDisposition, StatusCounts, StoredEmbedding, StoredPageBody, WorkspaceScopeRow,
- WorkspaceSummary, f32_vec_to_bytes,
+ SessionDependentRows, SessionEndDisposition, StatusCounts, StoredEmbedding, 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 f84f1a22..99dccdc5 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -3065,7 +3065,8 @@ pub enum PagesMode {
/// a latest page at that path.
#[default]
Move,
- /// Leave the rows in the source scope but clear `is_latest`, so the next
+ /// Leave the rows in the source scope but clear `is_latest` (and the
+ /// session's `summary_page_id` when it pointed at them), so the next
/// consolidation of the session writes a fresh page in the destination.
Regenerate,
}
@@ -3100,6 +3101,10 @@ pub struct MoveSessionSummary {
/// The session page path when the source scope held at least one version
/// of it, so the caller can move or retire the on-disk file too.
pub page_path: Option<String>,
+ /// `pages` versions of `sessions/<id>.md` sitting in the target scope
+ /// once the call is done (moved there now or already there before), so
+ /// a caller can tell "nothing to move" from "no page anywhere".
+ pub page_versions_in_target: u64,
/// Scope the session was read from.
pub from_workspace: WorkspaceId,
/// Scope the session was read from.
@@ -3191,6 +3196,7 @@ pub fn move_session(
page_versions_moved: 0,
pages_regenerated: 0,
page_path: None,
+ page_versions_in_target: 0,
from_workspace,
from_project,
to_workspace: target_workspace,
@@ -3302,10 +3308,30 @@ pub fn move_session(
),
params![page_scope_params.0, page_scope_params.1, page_path.as_str()],
)? as u64;
+ // The session's summary pointer targeted the page just
+ // retired; the next consolidation sets it again.
+ tx.execute(
+ &format!(
+ "UPDATE sessions SET summary_page_id = NULL \
+ WHERE id = ?4 AND summary_page_id IN ( \
+ SELECT id FROM pages WHERE {page_scope_sql} AND path = ?3)"
+ ),
+ params![
+ page_scope_params.0,
+ page_scope_params.1,
+ page_path.as_str(),
+ &sid[..],
+ ],
+ )?;
}
}
- summary.page_path = Some(page_path);
+ summary.page_path = Some(page_path.clone());
}
+ summary.page_versions_in_target = tx.query_row(
+ "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3",
+ params![&to_ws[..], &to_proj[..], page_path.as_str()],
+ |row| row.get::<_, i64>(0),
+ )? as u64;
audit(
&tx,
@@ -5464,6 +5490,8 @@ pub(crate) mod tests {
let dst_ws = get_or_create_workspace(&mut conn, "other").unwrap();
let dst_proj = get_or_create_project(&mut conn, &dst_ws, "target", None).unwrap();
let sid = seed_movable_session(&mut conn, src_ws, src_proj);
+ point_summary_at_latest(&mut conn, sid, src_ws, src_proj);
+ let pointer = summary_page_id(&conn, sid);
let summary = move_session(
&mut conn,
@@ -5479,6 +5507,9 @@ pub(crate) mod tests {
assert_eq!(summary.observations, 2);
assert_eq!(summary.page_versions_moved, 2);
assert_eq!(summary.pages_regenerated, 0);
+ assert_eq!(summary.page_versions_in_target, 2);
+ // The page kept its id, so the pointer is still right.
+ assert_eq!(summary_page_id(&conn, sid), pointer);
assert_session_bundle_in_scope(&conn, sid, (dst_ws, dst_proj), (src_ws, src_proj));
// Both versions moved and the supersession chain kept exactly one latest.
@@ -5546,6 +5577,9 @@ pub(crate) mod tests {
// A latest page at the path in the target is fine under Regenerate.
let path = format!("sessions/{sid}.md");
upsert_page(&mut conn, &page(dst_ws, dst_proj, &path, "already here")).unwrap();
+ // The session points at its (source) latest page, as consolidation
+ // leaves it.
+ point_summary_at_latest(&mut conn, sid, src_ws, src_proj);
let summary = move_session(
&mut conn,
@@ -5563,9 +5597,40 @@ pub(crate) mod tests {
assert_eq!(summary.page_path.as_deref(), Some(path.as_str()));
assert_session_bundle_in_scope(&conn, sid, (dst_ws, dst_proj), (src_ws, src_proj));
- // Source versions stay where they are, none of them latest anymore.
+ // Source versions stay where they are, none of them latest anymore,
+ // and the session no longer points at the retired page.
assert_eq!(session_page_versions(&conn, sid, src_ws, src_proj), (2, 0));
assert_eq!(session_page_versions(&conn, sid, dst_ws, dst_proj), (1, 1));
+ assert_eq!(summary_page_id(&conn, sid), None);
+ }
+
+ /// Point `sessions.summary_page_id` at the session's latest page in a
+ /// scope, the way session consolidation does.
+ fn point_summary_at_latest(
+ conn: &mut Connection,
+ sid: SessionId,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ ) {
+ let path = format!("sessions/{sid}.md");
+ conn.execute(
+ "UPDATE sessions SET summary_page_id = ( \
+ SELECT id FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1) \
+ WHERE id = ?4",
+ params![ws.as_bytes(), proj.as_bytes(), path, sid.as_bytes()],
+ )
+ .unwrap();
+ assert!(summary_page_id(conn, sid).is_some());
+ }
+
+ fn summary_page_id(conn: &Connection, sid: SessionId) -> Option<Vec<u8>> {
+ conn.query_row(
+ "SELECT summary_page_id FROM sessions WHERE id = ?1",
+ params![sid.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap()
}
#[test]
@@ -5594,6 +5659,7 @@ pub(crate) mod tests {
assert_eq!(summary.page_versions_moved, 0);
assert_eq!(summary.pages_regenerated, 0);
assert_eq!(summary.page_path, None);
+ assert_eq!(summary.page_versions_in_target, 0);
}
#[test]
@@ -5742,6 +5808,7 @@ pub(crate) mod tests {
summary.page_path, None,
"the page already sits in the target"
);
+ assert_eq!(summary.page_versions_in_target, 2);
assert_eq!(summary.from_project, target);
assert_eq!(summary.to_project, target);
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index a05a5a42..26eb75e5 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -221,6 +221,26 @@ fn rerank_page_hits_with_meta(
hits
}
+/// Rows keyed to one session (see [`ReaderPool::session_dependent_rows`]).
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct SessionDependentRows {
+ /// `observations` rows of the session, in any scope.
+ pub observations: u64,
+ /// `handoffs` rows the session produced, in any scope.
+ pub handoffs: u64,
+ /// `session_consolidation_jobs` rows, in any scope.
+ pub consolidation_jobs: u64,
+ /// `auto_improve_runs` rows, in any scope.
+ pub auto_improve_runs: u64,
+ /// `auto_improve_scheduler_claims` rows, in any scope.
+ pub auto_improve_claims: u64,
+ /// Versions of `sessions/<id>.md` in the queried page scope.
+ pub page_versions: u64,
+ /// Latest versions of `sessions/<id>.md` in the queried page scope
+ /// (0 or 1).
+ pub page_latest: u64,
+}
+
/// One page flagged by `stale`/`wrong` feedback on its current version,
/// aggregated per (page, kind) for the lint pass.
#[derive(Debug, Clone, Serialize)]
@@ -2061,6 +2081,52 @@ impl ReaderPool {
.await
}
+ /// Rows keyed to a session across every scope, plus its
+ /// `sessions/<id>.md` page rows in one scope: what a `move_session` into
+ /// a scope that holds nothing of the session yet would touch. Used for
+ /// the dry run of a move whose destination does not exist yet.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_dependent_rows(
+ &self,
+ session_id: SessionId,
+ page_scope: (WorkspaceId, ProjectId),
+ ) -> StoreResult<SessionDependentRows> {
+ self.with_conn(move |conn| {
+ let sid = session_id.as_bytes();
+ let count = |sql: &str| -> StoreResult<u64> {
+ Ok(conn.query_row(sql, [sid.as_slice()], |r| r.get::<_, i64>(0))? as u64)
+ };
+ let (page_versions, page_latest): (i64, i64) = conn.query_row(
+ "SELECT COUNT(*), COALESCE(SUM(is_latest), 0) FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3",
+ params![
+ page_scope.0.as_bytes(),
+ page_scope.1.as_bytes(),
+ format!("sessions/{session_id}.md"),
+ ],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )?;
+ Ok(SessionDependentRows {
+ observations: count("SELECT COUNT(*) FROM observations WHERE session_id = ?1")?,
+ handoffs: count("SELECT COUNT(*) FROM handoffs WHERE from_session_id = ?1")?,
+ consolidation_jobs: count(
+ "SELECT COUNT(*) FROM session_consolidation_jobs WHERE session_id = ?1",
+ )?,
+ auto_improve_runs: count(
+ "SELECT COUNT(*) FROM auto_improve_runs WHERE session_id = ?1",
+ )?,
+ auto_improve_claims: count(
+ "SELECT COUNT(*) FROM auto_improve_scheduler_claims WHERE session_id = ?1",
+ )?,
+ page_versions: page_versions as u64,
+ page_latest: page_latest as u64,
+ })
+ })
+ .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/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 9500822c..4330fc68 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -402,9 +402,10 @@ scope), the `handoffs` it produced (`from_session_id`), its
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
+- `--pages regenerate`: the source versions are retired (`is_latest = 0`),
+ the session's `summary_page_id` is cleared when it pointed at them, 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.
@@ -435,13 +436,18 @@ 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.
+is written and no audit row is left; with `--create` against a destination
+that does not exist yet the dry run does not create it either: it reports
+`would_create_project: true` with the counts of what would move (the CLI
+says "would create project"), and only the `--confirm` run creates it.
**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
+`--force` proceeds. A re-home (the session row already sits in the
+destination) skips the open-session guard: the row does not move, so an
+open session only has its stray rows gathered; the job guard still applies. 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.
@@ -456,9 +462,13 @@ Response (`MoveSessionReport`): `session_id`, `dry_run`, `session_moved`
(`{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: [...]}`.
+`regenerated` | `already in destination` for a re-home whose page rows all
+sit in the destination | `none` when the session has no page anywhere),
+`cwd`, `cwd_warning`, `would_create_project` (dry run with `create` only),
+`pre_checkpoint` (only when the wiki tree had uncommitted changes before the
+move), `checkpoint` (only when the move changed the tree). The batch wraps
+them in `{dry_run, would_create_project?, from, to, total, moved, sessions:
+[...]}`.
Failure modes: