Skip to content

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

Rust

feat(wiki): move_session_page with rollback (#402)

Sergio Aguirre2a0545bece87
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index e23395fd..95036809 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -3056,12 +3056,14 @@ pub fn move_project_workspace(
/// How [`move_session`] treats the session's consolidated wiki page
/// (`sessions/<session_id>.md`) when the session changes scope.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "lowercase")]
pub enum PagesMode {
/// Re-stamp every version of the page into the destination scope so the
/// curated page and its supersession history follow the session. Fails
/// with [`StoreError::PagePathTaken`] when the destination already holds
/// a latest page at that path.
+ #[default]
Move,
/// Leave the rows in the source scope but clear `is_latest`, so the next
/// consolidation of the session writes a fresh page in the destination.
@@ -3117,6 +3119,8 @@ pub struct MoveSessionSummary {
/// `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`].
///
/// The `workspace_id`/`project_id` pairing triggers only guard INSERT, so the
/// target pair is validated against `projects` here before any UPDATE runs.
@@ -3133,6 +3137,7 @@ pub fn move_session(
target_workspace: WorkspaceId,
target_project: ProjectId,
pages: PagesMode,
+ author_id: Option<ai_memory_core::UserId>,
commit: bool,
) -> StoreResult<MoveSessionSummary> {
let tx = conn.transaction()?;
@@ -3275,7 +3280,7 @@ pub fn move_session(
Some(to_ws),
Some(to_proj),
None,
- None,
+ author_id.as_ref().map(ai_memory_core::UserId::as_bytes),
Timestamp::now().as_microsecond(),
)?;
@@ -5377,8 +5382,16 @@ pub(crate) mod tests {
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);
- let summary =
- move_session(&mut conn, sid, dst_ws, dst_proj, PagesMode::Move, false).unwrap();
+ let summary = move_session(
+ &mut conn,
+ sid,
+ dst_ws,
+ dst_proj,
+ PagesMode::Move,
+ None,
+ false,
+ )
+ .unwrap();
assert!(summary.session_moved);
assert_eq!(summary.observations, 2);
assert_eq!(summary.handoffs, 1);
@@ -5419,8 +5432,16 @@ pub(crate) mod tests {
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);
- let summary =
- move_session(&mut conn, sid, dst_ws, dst_proj, PagesMode::Move, true).unwrap();
+ let summary = move_session(
+ &mut conn,
+ sid,
+ dst_ws,
+ dst_proj,
+ PagesMode::Move,
+ None,
+ true,
+ )
+ .unwrap();
assert!(summary.session_moved);
assert_eq!(summary.observations, 2);
assert_eq!(summary.page_versions_moved, 2);
@@ -5462,8 +5483,16 @@ pub(crate) mod tests {
let path = format!("sessions/{sid}.md");
upsert_page(&mut conn, &page(dst_ws, dst_proj, &path, "already here")).unwrap();
- let err = move_session(&mut conn, sid, dst_ws, dst_proj, PagesMode::Move, true)
- .expect_err("latest page at the same path in the target must block the move");
+ let err = move_session(
+ &mut conn,
+ sid,
+ dst_ws,
+ dst_proj,
+ PagesMode::Move,
+ None,
+ true,
+ )
+ .expect_err("latest page at the same path in the target must block the move");
assert!(
matches!(&err, StoreError::PagePathTaken { path: p } if *p == path),
"unexpected error: {err:?}"
@@ -5491,6 +5520,7 @@ pub(crate) mod tests {
dst_ws,
dst_proj,
PagesMode::Regenerate,
+ None,
true,
)
.unwrap();
@@ -5517,8 +5547,16 @@ pub(crate) mod tests {
)
.unwrap();
- let summary =
- move_session(&mut conn, sid, dst_ws, dst_proj, PagesMode::Move, true).unwrap();
+ let summary = move_session(
+ &mut conn,
+ sid,
+ dst_ws,
+ dst_proj,
+ PagesMode::Move,
+ None,
+ true,
+ )
+ .unwrap();
assert!(summary.session_moved);
assert_eq!(summary.page_versions_moved, 0);
assert_eq!(summary.pages_regenerated, 0);
@@ -5528,8 +5566,16 @@ pub(crate) mod tests {
#[test]
fn move_session_unknown_session_is_not_found() {
let (_tmp, mut conn, ws, proj) = fresh_db();
- let err = move_session(&mut conn, SessionId::new(), ws, proj, PagesMode::Move, true)
- .expect_err("unknown session must not succeed");
+ let err = move_session(
+ &mut conn,
+ SessionId::new(),
+ ws,
+ proj,
+ PagesMode::Move,
+ None,
+ true,
+ )
+ .expect_err("unknown session must not succeed");
assert!(
matches!(err, StoreError::NotFound(_)),
"unexpected error: {err:?}"
@@ -5544,8 +5590,16 @@ pub(crate) mod tests {
// A project id that exists, but not in the requested workspace: the
// pairing triggers only guard INSERT, so the op must refuse it itself.
- let err = move_session(&mut conn, sid, dst_ws, src_proj, PagesMode::Move, true)
- .expect_err("target project outside the target workspace must be refused");
+ let err = move_session(
+ &mut conn,
+ sid,
+ dst_ws,
+ src_proj,
+ PagesMode::Move,
+ None,
+ true,
+ )
+ .expect_err("target project outside the target workspace must be refused");
assert!(
matches!(err, StoreError::NotFound(_)),
"unexpected error: {err:?}"
@@ -5558,7 +5612,7 @@ pub(crate) mod tests {
let (_tmp, mut conn, ws, proj) = fresh_db();
let sid = seed_movable_session(&mut conn, ws, proj);
- let summary = move_session(&mut conn, sid, ws, proj, PagesMode::Move, true).unwrap();
+ let summary = move_session(&mut conn, sid, ws, proj, PagesMode::Move, None, true).unwrap();
assert!(!summary.session_moved);
assert_eq!(summary.observations, 0);
assert_eq!(summary.handoffs, 0);
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 071bb350..e509efe4 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -317,6 +317,7 @@ pub(crate) enum WriteCmd {
target_workspace: WorkspaceId,
target_project: ProjectId,
pages: PagesMode,
+ author_id: Option<UserId>,
commit: bool,
reply: oneshot::Sender<StoreResult<MoveSessionSummary>>,
},
@@ -1258,7 +1259,8 @@ impl WriterHandle {
/// `(target_workspace, target_project)` in one transaction. With
/// `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.
+ /// the caller moves the on-disk page file afterwards. `author_id` is the
+ /// operator recorded on the audit row.
///
/// # Errors
/// Returns [`StoreError::WriterClosed`] if the actor has shut down,
@@ -1272,6 +1274,7 @@ impl WriterHandle {
target_workspace: WorkspaceId,
target_project: ProjectId,
pages: PagesMode,
+ author_id: Option<UserId>,
commit: bool,
) -> StoreResult<MoveSessionSummary> {
let (tx, rx) = oneshot::channel();
@@ -1280,6 +1283,7 @@ impl WriterHandle {
target_workspace,
target_project,
pages,
+ author_id,
commit,
reply: tx,
})
@@ -2188,6 +2192,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
target_workspace,
target_project,
pages,
+ author_id,
commit,
reply,
} => {
@@ -2197,6 +2202,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
target_workspace,
target_project,
pages,
+ author_id,
commit,
);
send_or_warn(reply, result, "move_session");
@@ -2627,7 +2633,7 @@ mod tests {
let dry = store
.writer
- .move_session(sid, ws, dst, PagesMode::Move, false)
+ .move_session(sid, ws, dst, PagesMode::Move, None, false)
.await
.unwrap();
assert!(dry.session_moved);
@@ -2639,7 +2645,7 @@ mod tests {
let moved = store
.writer
- .move_session(sid, ws, dst, PagesMode::Move, true)
+ .move_session(sid, ws, dst, PagesMode::Move, None, true)
.await
.unwrap();
assert!(moved.session_moved);
diff --git a/crates/ai-memory-wiki/src/admission.rs b/crates/ai-memory-wiki/src/admission.rs
index 05f8803a..3adf11ac 100644
--- a/crates/ai-memory-wiki/src/admission.rs
+++ b/crates/ai-memory-wiki/src/admission.rs
@@ -63,6 +63,12 @@ pub enum AdmissionOp {
/// project id. Carries source names in `workspace`/`project` and
/// destination names in `destination_workspace`/`destination_project`.
MoveProject,
+ /// One session (its rows and its `sessions/<id>.md` page) is being moved
+ /// to another project. Carries the source names in `workspace`/`project`
+ /// and the destination names in `destination_workspace`/
+ /// `destination_project`; no page path. Lets a mirror move or drop the
+ /// session page file.
+ MoveSession,
/// A handoff is being created. Carries the workspace/project; no page path,
/// since handoffs live in their own table rather than the wiki tree.
///
@@ -88,6 +94,7 @@ impl AdmissionOp {
AdmissionOp::PurgeProject => "purge_project",
AdmissionOp::PurgeWorkspace => "purge_workspace",
AdmissionOp::MoveProject => "move_project",
+ AdmissionOp::MoveSession => "move_session",
AdmissionOp::HandoffBegin => "handoff_begin",
AdmissionOp::HandoffAccept => "handoff_accept",
AdmissionOp::HandoffCancel => "handoff_cancel",
@@ -782,6 +789,7 @@ mod tests {
assert_eq!(AdmissionOp::WritePage.as_header_value(), "write_page");
assert_eq!(AdmissionOp::Consolidate.as_header_value(), "consolidate");
assert_eq!(AdmissionOp::MoveProject.as_header_value(), "move_project");
+ assert_eq!(AdmissionOp::MoveSession.as_header_value(), "move_session");
}
#[tokio::test]
diff --git a/crates/ai-memory-wiki/src/error.rs b/crates/ai-memory-wiki/src/error.rs
index 31b6b129..c440f8a2 100644
--- a/crates/ai-memory-wiki/src/error.rs
+++ b/crates/ai-memory-wiki/src/error.rs
@@ -42,6 +42,12 @@ pub enum WikiError {
/// already exists.
#[error("destination dir already exists: {0}")]
DestinationExists(String),
+
+ /// A move-session refused to overwrite an existing page file at the
+ /// destination (`<wiki_root>/<ws>/<proj>/sessions/<id>.md`). Surfaced as
+ /// `409 Conflict` at the admin layer.
+ #[error("destination page file already exists: {0}")]
+ DestinationPageExists(String),
}
impl From<serde_yaml::Error> for WikiError {
diff --git a/crates/ai-memory-wiki/src/lib.rs b/crates/ai-memory-wiki/src/lib.rs
index 69a9d8bd..4fee256b 100644
--- a/crates/ai-memory-wiki/src/lib.rs
+++ b/crates/ai-memory-wiki/src/lib.rs
@@ -24,4 +24,4 @@ pub use git::{COMMIT_AUTHOR_EMAIL, COMMIT_AUTHOR_NAME, GitAdapter};
pub use markdown::{Markdown, derive_title, emit, parse};
pub use migrations::run_pending as run_wiki_migrations;
pub use watcher::{DEBOUNCE_WINDOW, RECONCILE_INTERVAL, WatcherHandle};
-pub use wiki::{Wiki, WritePageRequest};
+pub use wiki::{MoveSessionOutcome, SessionPageFile, Wiki, WritePageRequest};
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index a0455afc..2001e073 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -4,14 +4,14 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;
use ai_memory_core::{
- ActorContext, AutoImproveProposalId, NewPage, PageId, PagePath, ProjectId, Sanitizer, Tier,
- UserId, WorkspaceId,
+ ActorContext, AutoImproveProposalId, NewPage, PageId, PagePath, ProjectId, Sanitizer,
+ SessionId, Tier, UserId, WorkspaceId,
};
use ai_memory_llm::Embedder;
use ai_memory_store::{
ApproveAutoImproveProposal, ApproveAutoImproveProposalResult, AutoImproveProposalDetail,
- FailAutoImproveProposal, MoveSummary, ReaderPool, WriterHandle, artifact_path_for,
- f32_vec_to_bytes,
+ FailAutoImproveProposal, MoveSessionSummary, MoveSummary, PagesMode, ReaderPool, WriterHandle,
+ artifact_path_for, f32_vec_to_bytes,
};
use tokio::sync::RwLock;
@@ -43,6 +43,31 @@ enum PageStoreRemoval {
},
}
+/// What [`Wiki::move_session_page`] did with the on-disk
+/// `sessions/<session_id>.md` file of the moved session.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionPageFile {
+ /// Renamed from the source project directory into the destination one
+ /// ([`PagesMode::Move`]).
+ Moved,
+ /// Removed from the source project directory ([`PagesMode::Regenerate`]),
+ /// so the watcher cannot re-index it as a live page after its rows were
+ /// retired; the next consolidation writes a fresh page in the destination.
+ Removed,
+ /// No file existed in the source project directory.
+ Absent,
+}
+
+/// Result of [`Wiki::move_session_page`]: the store summary plus what
+/// happened to the page file.
+#[derive(Debug, Clone)]
+pub struct MoveSessionOutcome {
+ /// Row counts and scopes as reported by the store re-stamp.
+ pub summary: MoveSessionSummary,
+ /// Disposition of the on-disk session page file.
+ pub file: SessionPageFile,
+}
+
/// Wiki filesystem handle.
///
/// Owns the path of the wiki root (`<data_dir>/wiki/`) and a cloneable
@@ -324,6 +349,120 @@ impl Wiki {
}
}
+ /// Move one session to another project: relocate its `sessions/<id>.md`
+ /// file on disk and re-stamp its store rows in one transaction
+ /// ([`WriterHandle::move_session`]).
+ ///
+ /// Same critical section and ordering as [`Self::move_project_workspace`]:
+ /// the exclusive mutation guard is held across the admission chain, the
+ /// file step and the store step; disk goes first and SQL last, so the DB
+ /// is never ahead of disk. Under [`PagesMode::Move`] the file is renamed
+ /// into the destination project directory (refused when a file already
+ /// sits there). Under [`PagesMode::Regenerate`] the file is first parked
+ /// 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.
+ ///
+ /// # Errors
+ /// Returns [`WikiError::DestinationPageExists`] when the destination
+ /// already holds a page file at that path, [`WikiError::Store`] for store
+ /// refusals (`NotFound`, `PagePathTaken`), or an I/O error when the file
+ /// step or its rollback fails.
+ pub async fn move_session_page(
+ &self,
+ session_id: SessionId,
+ from: (WorkspaceId, ProjectId),
+ to: (WorkspaceId, ProjectId),
+ pages: PagesMode,
+ author_id: Option<UserId>,
+ admission_ctx: Option<AdmissionContext>,
+ ) -> WikiResult<MoveSessionOutcome> {
+ let _guard = self.mutation_lock.write().await;
+ let resolved_ctx = if let Some(chain) = &self.admission_chain {
+ let mut ctx = admission_ctx.unwrap_or_default();
+ ctx.op = AdmissionOp::MoveSession;
+ self.resolve_admission_names(from.0, from.1, &mut ctx).await;
+ chain.notify(None, &ctx).await?;
+ Some(ctx)
+ } else {
+ None
+ };
+
+ let file_name = format!("{session_id}.md");
+ let src = self
+ .project_root(from.0, from.1)
+ .join("sessions")
+ .join(&file_name);
+ let parked = if src.is_file() {
+ let target = match pages {
+ PagesMode::Move => {
+ let dst = self
+ .project_root(to.0, to.1)
+ .join("sessions")
+ .join(&file_name);
+ if dst.exists() {
+ return Err(WikiError::DestinationPageExists(dst.display().to_string()));
+ }
+ dst
+ }
+ // Same directory, watcher-ignored name: invisible to
+ // reindex/reconcile, trivially renamed back on failure.
+ PagesMode::Regenerate => {
+ src.with_file_name(format!(".ai-memory-tmp.move-session.{file_name}"))
+ }
+ };
+ if let Some(parent) = target.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::rename(&src, &target)?;
+ Some(target)
+ } else {
+ None
+ };
+
+ match self
+ .writer
+ .move_session(session_id, to.0, to.1, pages, author_id, true)
+ .await
+ {
+ Ok(summary) => {
+ let file = match (&parked, pages) {
+ (None, _) => SessionPageFile::Absent,
+ (Some(_), PagesMode::Move) => SessionPageFile::Moved,
+ (Some(tmp), PagesMode::Regenerate) => {
+ // The rows are retired; a leftover temp file is
+ // ignored by the watcher, so this is best-effort.
+ if let Err(e) = std::fs::remove_file(tmp) {
+ tracing::warn!(
+ error = %e,
+ path = %tmp.display(),
+ "move-session: could not remove parked session page file"
+ );
+ }
+ SessionPageFile::Removed
+ }
+ };
+ if let (Some(chain), Some(ctx)) = (&self.admission_chain, &resolved_ctx) {
+ chain.dispatch_async(None, &serde_json::Value::Null, "", ctx);
+ }
+ Ok(MoveSessionOutcome { summary, file })
+ }
+ Err(e) => {
+ if let Some(target) = parked
+ && let Err(rollback_err) = std::fs::rename(&target, &src)
+ {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "INCONSISTENT STATE: session page file moved but DB re-stamp failed ({e}) and moving it back also failed ({rollback_err}); manually move {} -> {}",
+ target.display(),
+ src.display()
+ ))));
+ }
+ Err(e.into())
+ }
+ }
+ }
+
async fn ensure_project_workspace(
&self,
workspace_id: WorkspaceId,
@@ -4028,4 +4167,246 @@ mod tests {
.expect_err("a string instead of a list is a structural error");
assert!(err.to_string().contains("non-array entities"), "{err}");
}
+
+ /// Two projects in one workspace, one ended session in the first with a
+ /// consolidated `sessions/<id>.md` page written through the wiki.
+ async fn session_with_page(
+ tmp: &TempDir,
+ ) -> (
+ Store,
+ Wiki,
+ WorkspaceId,
+ ProjectId,
+ ProjectId,
+ SessionId,
+ PagePath,
+ ) {
+ let (store, wiki, ws, src) = scoped(tmp).await;
+ let dst = store
+ .writer
+ .get_or_create_project(ws, "target", None)
+ .await
+ .unwrap();
+ let sid = SessionId::new();
+ store
+ .writer
+ .begin_session(ai_memory_core::NewSession {
+ id: sid,
+ workspace_id: ws,
+ project_id: src,
+ agent_kind: ai_memory_core::AgentKind::ClaudeCode,
+ cwd: Some("/repo/src".into()),
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ store.writer.end_session(sid, None).await.unwrap();
+ let path = PagePath::new(format!("sessions/{sid}.md")).unwrap();
+ wiki.write_page(req(
+ ws,
+ src,
+ path.as_str(),
+ "consolidated session body",
+ serde_json::json!({ "title": "Session" }),
+ ))
+ .await
+ .unwrap();
+ (store, wiki, ws, src, dst, sid, path)
+ }
+
+ fn leftover_tempfiles(dir: &Path) -> Vec<String> {
+ std::fs::read_dir(dir)
+ .map(|rd| {
+ rd.filter_map(Result::ok)
+ .map(|e| e.file_name().to_string_lossy().into_owned())
+ .filter(|n| n.starts_with(".ai-memory-tmp."))
+ .collect()
+ })
+ .unwrap_or_default()
+ }
+
+ #[tokio::test]
+ async fn move_session_page_moves_file_and_rows() {
+ let tmp = TempDir::new().unwrap();
+ let (store, wiki, ws, src, dst, sid, path) = session_with_page(&tmp).await;
+
+ let outcome = wiki
+ .move_session_page(sid, (ws, src), (ws, dst), PagesMode::Move, None, None)
+ .await
+ .unwrap();
+ assert_eq!(outcome.file, SessionPageFile::Moved);
+ assert!(outcome.summary.session_moved);
+ assert_eq!(outcome.summary.page_versions_moved, 1);
+
+ assert!(
+ !wiki.abs_path(ws, src, &path).exists(),
+ "source file must be gone"
+ );
+ let moved = std::fs::read_to_string(wiki.abs_path(ws, dst, &path)).unwrap();
+ assert!(moved.contains("consolidated session body"));
+ assert_eq!(
+ store.reader.session_project_ids(sid).await.unwrap(),
+ Some((ws, dst))
+ );
+ assert!(
+ store
+ .reader
+ .page_body_by_ids(ws, dst, path.as_str())
+ .await
+ .unwrap()
+ .is_some(),
+ "latest page row must now sit in the destination"
+ );
+ assert!(
+ store
+ .reader
+ .page_body_by_ids(ws, src, path.as_str())
+ .await
+ .unwrap()
+ .is_none()
+ );
+ // The moved file is byte-identical to what the store indexed, so the
+ // watcher's follow-up reindex in the destination is a no-op.
+ wiki.reindex_page(ws, dst, path.clone()).await.unwrap();
+ assert_eq!(
+ store
+ .reader
+ .page_body_by_ids(ws, dst, path.as_str())
+ .await
+ .unwrap()
+ .unwrap()
+ .body,
+ "consolidated session body"
+ );
+ }
+
+ #[tokio::test]
+ async fn move_session_page_regenerate_removes_source_file() {
+ let tmp = TempDir::new().unwrap();
+ let (store, wiki, ws, src, dst, sid, path) = session_with_page(&tmp).await;
+
+ let outcome = wiki
+ .move_session_page(sid, (ws, src), (ws, dst), PagesMode::Regenerate, None, None)
+ .await
+ .unwrap();
+ assert_eq!(outcome.file, SessionPageFile::Removed);
+ assert_eq!(outcome.summary.pages_regenerated, 1);
+
+ let src_abs = wiki.abs_path(ws, src, &path);
+ assert!(!src_abs.exists(), "retired page file must not linger");
+ assert!(!wiki.abs_path(ws, dst, &path).exists());
+ assert!(
+ leftover_tempfiles(src_abs.parent().unwrap()).is_empty(),
+ "parked copy must be deleted after the store commit"
+ );
+ assert!(
+ store
+ .reader
+ .page_body_by_ids(ws, src, path.as_str())
+ .await
+ .unwrap()
+ .is_none(),
+ "no latest version left in the source"
+ );
+ assert_eq!(
+ store.reader.session_project_ids(sid).await.unwrap(),
+ Some((ws, dst))
+ );
+ }
+
+ #[tokio::test]
+ async fn move_session_page_puts_file_back_when_store_refuses() {
+ let tmp = TempDir::new().unwrap();
+ let (store, wiki, ws, src, dst, sid, path) = session_with_page(&tmp).await;
+ // A latest page row at the same path in the destination, without a
+ // file, so the disk step succeeds and only the SQL step refuses.
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: dst,
+ path: path.clone(),
+ title: "taken".into(),
+ body: "already here".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: vec![],
+ author_id: None,
+ expires_at: None,
+ entities: vec![],
+ })
+ .await
+ .unwrap();
+
+ let err = wiki
+ .move_session_page(sid, (ws, src), (ws, dst), PagesMode::Move, None, None)
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(
+ err,
+ WikiError::Store(ai_memory_store::StoreError::PagePathTaken { .. })
+ ),
+ "unexpected error: {err}"
+ );
+ assert!(
+ wiki.abs_path(ws, src, &path).exists(),
+ "source file must be back after the store refused"
+ );
+ assert!(!wiki.abs_path(ws, dst, &path).exists());
+ assert_eq!(
+ store.reader.session_project_ids(sid).await.unwrap(),
+ Some((ws, src))
+ );
+ }
+
+ #[tokio::test]
+ async fn move_session_page_refuses_existing_destination_file() {
+ let tmp = TempDir::new().unwrap();
+ let (store, wiki, ws, src, dst, sid, path) = session_with_page(&tmp).await;
+ wiki.write_page(req(
+ ws,
+ dst,
+ path.as_str(),
+ "destination already has this page",
+ serde_json::json!({}),
+ ))
+ .await
+ .unwrap();
+
+ let err = wiki
+ .move_session_page(sid, (ws, src), (ws, dst), PagesMode::Move, None, None)
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(err, WikiError::DestinationPageExists(_)),
+ "unexpected error: {err}"
+ );
+ assert!(wiki.abs_path(ws, src, &path).exists());
+ assert_eq!(
+ store.reader.session_project_ids(sid).await.unwrap(),
+ Some((ws, src)),
+ "nothing may move when the destination file exists"
+ );
+ }
+
+ #[tokio::test]
+ async fn move_session_page_without_file_reports_absent() {
+ let tmp = TempDir::new().unwrap();
+ let (store, wiki, ws, src, dst, sid, path) = session_with_page(&tmp).await;
+ std::fs::remove_file(wiki.abs_path(ws, src, &path)).unwrap();
+
+ let outcome = wiki
+ .move_session_page(sid, (ws, src), (ws, dst), PagesMode::Move, None, None)
+ .await
+ .unwrap();
+ assert_eq!(outcome.file, SessionPageFile::Absent);
+ // The rows still move even though the file was already gone.
+ assert_eq!(outcome.summary.page_versions_moved, 1);
+ assert_eq!(
+ store.reader.session_project_ids(sid).await.unwrap(),
+ Some((ws, dst))
+ );
+ }
}