Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(projects): merge split identities losslessly
AkitaOnRailsa40869e58d13
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9438f1db..1964c124 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,22 @@ version in [`docs/changelog/`](docs/changelog/):### Added+- `ai-memory merge-project --workspace <w> --from <source> --into <target>`+ losslessly joins two project identities inside one workspace. Its default is+ an exact dry run; `--confirm` re-stamps page history, sessions, observations,+ handoffs, embeddings and managed workstreams in one writer transaction, then+ removes the source project. Same-path pages get a new target version that+ appends the source body behind an `ai-memory:merged-from` marker while both+ prior histories remain restorable. The target frontmatter wins, a one-sided+ expiry is removed, and the combined page is flagged stale for consolidation.+ `restore-page --page-id <uuid>` restores either retained history even after+ the source identity is removed. Open sessions and live managed runs refuse+ the merge (#1645).+- `audit-contamination` now reports projects in one workspace whose names+ collide after Unicode compatibility decomposition, case folding, and+ removal of non-spacing marks. Findings distinguish case from accent+ differences and include page/session counts plus last activity (#1645).+- Added `[briefing] inject_on_subagent_start` to `.ai-memory.toml`. A projectthat sets it hands each `claude-code` subagent the project brief when thesubagent starts: the same pinned, `_rules/` and `_slots/` brief thatdiff --git a/Cargo.lock b/Cargo.lockindex 71de19a9..c8a2cfa0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -276,6 +276,7 @@ dependencies = ["tokio","tracing","tracing-subscriber",+ "unicode_categories","uuid",]diff --git a/Cargo.toml b/Cargo.tomlindex 91f8a781..f78e20c6 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -173,6 +173,7 @@ regex = "1"# Unicode NFC for the portable page-path key. Already in the tree via# idna -> idna_adapter, so this adds no new code to the binary.icu_normalizer = "2"+unicode_categories = "0.1"# Wiki git versioning.git2 = { version = "0.21", default-features = false, features = ["vendored-libgit2"] }diff --git a/README.md b/README.mdindex 115ca43a..8a0db1ec 100644--- a/README.md+++ b/README.md@@ -739,7 +739,7 @@ diagram, crate breakdown, schema notes, and invariants.| [`docs/users.md`](docs/users.md) | **Multi-user attribution and human login.** Four-rung bearer ladder, password sessions, `ai-memory user` / `api-key` walkthrough, brownfield migration. || [`docs/management-ui.md`](docs/management-ui.md) | Optional server-rendered console: feature gates, user and session management, MCP keys, public deployment, and frontend checks. || [`docs/https-via-proxy.md`](docs/https-via-proxy.md) | **HTTPS via a reverse proxy.** When you need TLS and when you don't, with copy-paste Caddy / nginx / Cloudflare Tunnel templates and the "secure when you're not" failure modes. |-| [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before purge / rename / backup / restore / reset / reindex / restore-page.** Safety matrix, per-project disk layout, checkpoint page recovery, and operator workflows. |+| [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before purge / rename / merge / backup / restore / reset / reindex / restore-page.** Safety matrix, lossless project-identity merge, per-project disk layout, retained-version recovery, and operator workflows. || [`docs/backup.md`](docs/backup.md) | Backing up the wiki + data dir to a remote git repository: what to include, what to exclude, scheduled push pattern, restore, and security posture. Companion to `docs/lifecycle-ops.md` (which covers the on-box `ai-memory backup` snapshot). || [`docs/design-backup-agent-assets.md`](docs/design-backup-agent-assets.md) | Host agent-asset backup/restore: supported paths, filtering, redaction limits, archive bounds, active-content warning, and rollback behavior. || [`docs/llm-providers.md`](docs/llm-providers.md) | Provider configuration for consolidation and embeddings. |diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex caf7ed07..a0064b15 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -359,6 +359,9 @@ pub enum Command {/// copy+purge (only durable pages migrate, source purged). Either way the/// operation is irreversible — requires `--confirm`.MoveProject(MoveProjectArgs),+ /// Losslessly merge one project into another inside the same workspace.+ /// Without `--confirm`, prints an exact server-side dry run.+ MergeProject(MergeProjectArgs),/// Move one session (or every session of a project) to another project,/// re-stamping its observations, handoffs, consolidation jobs and its/// `sessions/<id>.md` page in one transaction. Without `--confirm` it@@ -1714,6 +1717,30 @@ pub struct MoveProjectArgs {pub allow_lossy_merge: bool,}+/// Arguments for `merge-project`.+#[derive(Debug, Args)]+pub struct MergeProjectArgs {+ /// Workspace containing both projects. Defaults to the nearest marker's+ /// workspace, then `default`.+ #[arg(long)]+ pub workspace: Option<String>,+ /// Source project name. Mutually exclusive with `--from-project-id`.+ #[arg(long, conflicts_with = "from_project_id")]+ pub from: Option<String>,+ /// Source project UUID, for an ambiguous legacy name.+ #[arg(long)]+ pub from_project_id: Option<String>,+ /// Target project name. Mutually exclusive with `--into-project-id`.+ #[arg(long, conflicts_with = "into_project_id")]+ pub into: Option<String>,+ /// Target project UUID, for an ambiguous legacy name.+ #[arg(long)]+ pub into_project_id: Option<String>,+ /// Apply the merge. Omit for an exact dry-run preview.+ #[arg(long)]+ pub confirm: bool,+}+/// Arguments for `move-session`.////// Exactly one of `<SESSION_ID>` and `--from-project` names what moves; the@@ -2407,8 +2434,12 @@ pub struct RestorePageArgs {#[arg(long)]pub path: String,/// Git checkpoint/revision to restore from.- #[arg(long)]- pub from: String,+ #[arg(long, conflicts_with = "page_id", required_unless_present = "page_id")]+ pub from: Option<String>,+ /// Retained page-version UUID to restore, including a version preserved by+ /// `merge-project`. Mutually exclusive with `--from`.+ #[arg(long, conflicts_with = "from", required_unless_present = "from")]+ pub page_id: Option<String>,/// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's/// `workspace`, else `default`.#[arg(long)]@@ -5774,5 +5805,65 @@ mod tests {.is_err(),"--project and --project-id must not both be accepted");++ let cli = Cli::try_parse_from([+ "ai-memory",+ "merge-project",+ "--workspace",+ "default",+ "--from-project-id",+ id,+ "--into",+ "canonical",+ ])+ .unwrap();+ let Command::MergeProject(args) = cli.command else {+ panic!("expected merge-project");+ };+ assert_eq!(args.from_project_id.as_deref(), Some(id));+ assert_eq!(args.into.as_deref(), Some("canonical"));+ assert!(+ Cli::try_parse_from([+ "ai-memory",+ "merge-project",+ "--from",+ "old",+ "--from-project-id",+ id,+ "--into",+ "new",+ ])+ .is_err(),+ "--from and --from-project-id must not both be accepted"+ );++ let cli = Cli::try_parse_from([+ "ai-memory",+ "restore-page",+ "--path",+ "notes/example.md",+ "--page-id",+ id,+ ])+ .unwrap();+ let Command::RestorePage(args) = cli.command else {+ panic!("expected restore-page");+ };+ assert_eq!(args.page_id.as_deref(), Some(id));+ assert!(args.from.is_none());+ assert!(+ Cli::try_parse_from([+ "ai-memory",+ "restore-page",+ "--path",+ "notes/example.md",+ "--from",+ "HEAD",+ "--page-id",+ id,+ ])+ .is_err(),+ "--from and --page-id must not both be accepted"+ );}}diff --git a/crates/ai-memory-cli/src/commands/audit_contamination.rs b/crates/ai-memory-cli/src/commands/audit_contamination.rsindex a4ca5e6c..731d55cd 100644--- a/crates/ai-memory-cli/src/commands/audit_contamination.rs+++ b/crates/ai-memory-cli/src/commands/audit_contamination.rs@@ -46,6 +46,10 @@ struct Finding {pages: Option<u64>,#[serde(default)]sessions: Option<u64>,+ #[serde(default)]+ collision_kind: Option<String>,+ #[serde(default)]+ last_activity_us: Option<i64>,}/// Run the `audit-contamination` subcommand.@@ -87,15 +91,17 @@ pub async fn run(config: &Config, args: AuditContaminationArgs) -> Result<()> {expected,),"project_name_collision" => println!(- " [{}] project {} ({}/{}): {} page(s), {} session(s); collides with {}. \- Add a `.ai-memory.toml` marker, or merge the two once `merge-project` exists \- (#1645).",+ " [{}] project {} ({}/{}): {} page(s), {} session(s), last activity {}; \+ collides by {} with {}. Add a `.ai-memory.toml` marker or run `merge-project`.",f.confidence,f.entity_id,f.landed_workspace,f.landed_project,f.pages.unwrap_or(0),f.sessions.unwrap_or(0),+ f.last_activity_us+ .map_or_else(|| "unknown".into(), |value| value.to_string()),+ f.collision_kind.as_deref().unwrap_or("spelling"),f.peer_projects.as_deref().unwrap_or("?"),),other => println!(diff --git a/crates/ai-memory-cli/src/commands/merge_project.rs b/crates/ai-memory-cli/src/commands/merge_project.rsnew file mode 100644index 00000000..4acbe479--- /dev/null+++ b/crates/ai-memory-cli/src/commands/merge_project.rs@@ -0,0 +1,76 @@+//! `ai-memory merge-project` — losslessly join two project identities.++use anyhow::{Result, bail};+use serde::Serialize;++use crate::cli::MergeProjectArgs;+use crate::config::Config;+use crate::http_client::{ServerEndpoint, post_json};++#[derive(Serialize)]+struct MergeProjectRequest {+ workspace: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ from: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ from_project_id: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ into: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ into_project_id: Option<String>,+ confirm: bool,+}++/// Run the `merge-project` subcommand.+pub async fn run(config: &Config, args: MergeProjectArgs) -> Result<()> {+ super::refuse_empty_explicit(args.workspace.as_deref(), "--workspace")?;+ super::refuse_empty_explicit(args.from.as_deref(), "--from")?;+ super::refuse_empty_explicit(args.from_project_id.as_deref(), "--from-project-id")?;+ super::refuse_empty_explicit(args.into.as_deref(), "--into")?;+ super::refuse_empty_explicit(args.into_project_id.as_deref(), "--into-project-id")?;+ if args.from.is_none() == args.from_project_id.is_none() {+ bail!("exactly one of --from or --from-project-id is required");+ }+ if args.into.is_none() == args.into_project_id.is_none() {+ bail!("exactly one of --into or --into-project-id is required");+ }+ let workspace = super::resolve_workspace(config, args.workspace.as_deref())?;+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let report: serde_json::Value = post_json(+ &endpoint,+ "/admin/merge-project",+ &MergeProjectRequest {+ workspace,+ from: args.from,+ from_project_id: args.from_project_id,+ into: args.into,+ into_project_id: args.into_project_id,+ confirm: args.confirm,+ },+ )+ .await?;++ let verb = if report["dry_run"].as_bool().unwrap_or(true) {+ "Would merge"+ } else {+ "Merged"+ };+ println!(+ "{verb} {} -> {}: {} page versions, {} sessions, {} observations, {} handoffs, {} workstreams, {} page conflicts.",+ report["from"].as_str().unwrap_or("source"),+ report["into"].as_str().unwrap_or("target"),+ report["page_versions"].as_u64().unwrap_or(0),+ report["sessions"].as_u64().unwrap_or(0),+ report["observations"].as_u64().unwrap_or(0),+ report["handoffs"].as_u64().unwrap_or(0),+ report["workstreams"].as_u64().unwrap_or(0),+ report["page_conflicts"].as_u64().unwrap_or(0),+ );+ if !args.confirm {+ println!("Re-run the same command with --confirm to apply this merge.");+ }+ if let Some(warning) = report["manifest_warning"].as_str() {+ eprintln!("warning: merge committed but scope manifest refresh failed: {warning}");+ }+ Ok(())+}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex a88a750a..e29519f8 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -69,6 +69,7 @@ pub mod lint;pub mod list_projects;pub mod llm_test;pub mod mcp_bridge;+pub mod merge_project;pub mod message;pub mod move_project;pub mod move_session;diff --git a/crates/ai-memory-cli/src/commands/restore_page.rs b/crates/ai-memory-cli/src/commands/restore_page.rsindex 166e7630..5a69b6eb 100644--- a/crates/ai-memory-cli/src/commands/restore_page.rs+++ b/crates/ai-memory-cli/src/commands/restore_page.rs@@ -1,4 +1,4 @@-//! `ai-memory restore-page` — restore one wiki page from a git checkpoint.+//! `ai-memory restore-page` — restore one wiki page from retained history.use anyhow::{Context, Result};use serde::{Deserialize, Serialize};@@ -12,7 +12,10 @@ struct RestorePageRequest {workspace: String,project: String,path: String,- rev: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ rev: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ page_id: Option<String>,}#[derive(Deserialize, Serialize)]@@ -30,8 +33,8 @@ struct RestorePageResponse {////// # Errors/// Returns an error if an explicit scope flag is empty, the server is-/// unreachable, the checkpoint/path cannot be restored, or the restored page-/// cannot be reindexed.+/// unreachable, the requested checkpoint or page version cannot be restored,+/// or the restored page cannot be reindexed.pub async fn run(config: &Config, args: RestorePageArgs) -> Result<()> {super::refuse_empty_explicit(args.workspace.as_deref(), "--workspace")?;super::refuse_empty_explicit(args.project.as_deref(), "--project")?;@@ -46,6 +49,7 @@ pub async fn run(config: &Config, args: RestorePageArgs) -> Result<()> {project: project.clone(),path: args.path.clone(),rev: args.from.clone(),+ page_id: args.page_id.clone(),},).awaitdiff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rsindex 39fd3344..c18fdfec 100644--- a/crates/ai-memory-cli/src/lib.rs+++ b/crates/ai-memory-cli/src/lib.rs@@ -195,6 +195,7 @@ pub async fn run() -> Result<()> {Command::PurgeSession(args) => commands::purge_session::run(&config, args).await,Command::RenameProject(args) => commands::rename_project::run(&config, args).await,Command::MoveProject(args) => commands::move_project::run(&config, args).await,+ Command::MergeProject(args) => commands::merge_project::run(&config, args).await,Command::MoveSession(args) => commands::move_session::run(&config, args).await,Command::Uninstall(args) => commands::uninstall::run(&config, args),Command::Upgrade(args) => commands::upgrade::run(&config, args).await,diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 2810150c..9eb2220d 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -24,7 +24,7 @@//! - `POST /admin/embed` — backfill embeddings for latest pages.//! - `POST /admin/commit` — stage + commit the wiki tree via git.//! - `GET /admin/checkpoints` — list recent wiki git checkpoints.-//! - `POST /admin/restore-page` — restore one page from a checkpoint.+//! - `POST /admin/restore-page` — restore one page from retained history.//! - `POST /admin/purge-project` — delete a project's rows and wiki files//! (logical unless `compact` is set; see `ai_memory_store::Compaction`).//! - `POST /admin/purge-session` — delete one session and what it derived.@@ -42,6 +42,7 @@//! - `POST /admin/merge-workspace` — fold every project of one workspace into//! another, then delete the emptied source workspace.//! - `POST /admin/move-project` — move a project into another workspace+//! - `POST /admin/merge-project` — losslessly join two projects in one workspace//! (copy latest pages via the write path, then purge the source).//! - `POST /admin/write-page` — write or update a wiki page atomically.//! - `GET /admin/read-page` — fetch the full body of a single wiki page by path.@@ -69,7 +70,7 @@ use ai_memory_consolidate::{};use ai_memory_core::{ActiveProject, AgentKind, AutoImproveProposalId, Capability, DEFAULT_PROJECT_NAME,- DEFAULT_WORKSPACE_NAME, PagePath, ProjectId, SessionId, Tier, WorkspaceId,+ DEFAULT_WORKSPACE_NAME, PageId, PagePath, ProjectId, SessionId, Tier, WorkspaceId,};use ai_memory_llm::{ChatRequest, Embedder, LlmProvider, ProviderHealth, ProviderHealthSnapshot,@@ -82,7 +83,8 @@ use ai_memory_store::{StoreError, WriterHandle, f32_vec_to_bytes, lookup_existing_scope, lookup_existing_workspace,};use ai_memory_wiki::{- AdmissionContext, AdmissionOp, Markdown, SessionPageFile, Wiki, WikiError, WritePageRequest,+ AdmissionContext, AdmissionOp, Markdown, MergeProjectFile, SessionPageFile, Wiki, WikiError,+ WritePageRequest,};use axum::Json;use axum::Router;@@ -707,6 +709,7 @@ pub fn admin_router_with_sweep_tuning(.route("/admin/purge-session", post(handle_purge_session)).route("/admin/rename-project", post(handle_rename_project)).route("/admin/move-project", post(handle_move_project))+ .route("/admin/merge-project", post(handle_merge_project)).route("/admin/move-session", post(handle_move_session)).route("/admin/repair-session-times",@@ -4606,7 +4609,12 @@ struct RestorePageRequest {/// Relative wiki path to restore.path: String,/// Git revision/commit to restore from.- rev: String,+ #[serde(default)]+ rev: Option<String>,+ /// Retained SQLite page-version id to restore. Mutually exclusive with+ /// `rev`; used for histories moved by `merge-project`.+ #[serde(default)]+ page_id: Option<String>,}#[derive(Serialize)]@@ -4636,6 +4644,26 @@ async fn handle_restore_page()})?;let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;+ let (restore_source, version_id) = match (&req.rev, &req.page_id) {+ (Some(rev), None) if !rev.trim().is_empty() => (rev.clone(), None),+ (None, Some(page_id)) if !page_id.trim().is_empty() => {+ let version = page_id.parse::<PageId>().map_err(|_| {+ (+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({"error": "invalid page_id"})),+ )+ })?;+ (format!("page version {page_id}"), Some(version))+ }+ _ => {+ return Err((+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({+ "error": "exactly one of rev or page_id is required"+ })),+ ));+ }+ };let pre_checkpoint = checkpoint_or_500(&state.wiki,@@ -4647,11 +4675,27 @@ async fn handle_restore_page(),)?;- let page_id = state- .wiki- .restore_page_from_checkpoint(ws, proj, path.clone(), &req.rev)- .await- .map_err(|e| internal_err(e.to_string()))?;+ let page_id = if let Some(rev) = &req.rev {+ state+ .wiki+ .restore_page_from_checkpoint(ws, proj, path.clone(), rev)+ .await+ .map_err(|e| internal_err(e.to_string()))?+ } else {+ let version = version_id+ .ok_or_else(|| internal_err("validated page-version restore lost its version id"))?;+ state+ .wiki+ .restore_page_from_version(ws, proj, path.clone(), version)+ .await+ .map_err(|error| match error {+ WikiError::Store(StoreError::NotFound(_)) => (+ StatusCode::NOT_FOUND,+ Json(serde_json::json!({"error": error.to_string()})),+ ),+ _ => internal_err(error.to_string()),+ })?+ };let checkpoint = checkpoint_or_warn(&state.wiki,format!(@@ -4659,7 +4703,7 @@ async fn handle_restore_page(req.workspace,req.project,path.as_str(),- req.rev+ restore_source),);@@ -4669,7 +4713,7 @@ async fn handle_restore_page(serde_json::to_value(RestorePageResponse {page_id: page_id.to_string(),path: path.to_string(),- restored_from: req.rev,+ restored_from: restore_source,pre_checkpoint,checkpoint,})@@ -6351,9 +6395,256 @@ async fn handle_rename_project(}// ----------------------------------------------------------------------// move-project+// merge-project / move-project// ---------------------------------------------------------------------+#[derive(Deserialize)]+struct MergeProjectRequest {+ workspace: String,+ #[serde(default)]+ from: Option<String>,+ #[serde(default)]+ from_project_id: Option<String>,+ #[serde(default)]+ into: Option<String>,+ #[serde(default)]+ into_project_id: Option<String>,+ #[serde(default)]+ confirm: bool,+}++#[derive(Serialize)]+struct MergeProjectReport {+ from: String,+ into: String,+ dry_run: bool,+ page_versions: u64,+ sessions: u64,+ observations: u64,+ handoffs: u64,+ workstreams: u64,+ page_conflicts: u64,+ #[serde(skip_serializing_if = "Option::is_none")]+ checkpoint: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ manifest_warning: Option<String>,+}++async fn prepare_project_merge(+ state: &AdminState,+ workspace: &str,+ source_name: &str,+ source: ProjectId,+ target_name: &str,+ target: ProjectId,+ workspace_id: WorkspaceId,+) -> Result<Vec<MergeProjectFile>, MoveErr> {+ let summaries = state+ .reader+ .list_pages(workspace, source_name)+ .await+ .map_err(|error| internal_err(error.to_string()))?;+ let mut pages = Vec::with_capacity(summaries.len());+ for summary in summaries {+ let path = PagePath::new(summary.path.clone()).map_err(|error| {+ internal_err(format!(+ "invalid indexed page path '{}': {error}",+ summary.path+ ))+ })?;+ let source_meta = state+ .reader+ .page_meta(workspace, source_name, path.as_str())+ .await+ .map_err(|error| internal_err(error.to_string()))?+ .ok_or_else(|| {+ internal_err(format!(+ "source page '{}' disappeared while preparing merge",+ path.as_str()+ ))+ })?;+ let target_page_id = state+ .reader+ .page_meta(workspace, target_name, path.as_str())+ .await+ .map_err(|error| internal_err(error.to_string()))?+ .map(|meta| meta.id);+ let source_label = format!("{workspace}/{source_name}");+ pages.push(+ state+ .wiki+ .prepare_project_merge_file(+ workspace_id,+ source,+ target,+ ai_memory_store::MergeProjectPage {+ path,+ source_page_id: source_meta.id,+ target_page_id,+ merged_page: None,+ },+ &source_label,+ )+ .map_err(|error| match error {+ WikiError::Io(ref io) if io.kind() == std::io::ErrorKind::NotFound => (+ StatusCode::CONFLICT,+ Json(serde_json::json!({+ "error": "project pages changed while the merge was being prepared"+ })),+ ),+ _ => internal_err(error.to_string()),+ })?,+ );+ }+ Ok(pages)+}++async fn handle_merge_project(+ State(state): State<Arc<AdminState>>,+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,+ Json(req): Json<MergeProjectRequest>,+) -> impl IntoResponse {+ let actor = actor_ext+ .map(|axum::Extension(actor)| actor)+ .unwrap_or_else(ai_memory_core::ActorContext::anonymous);+ let result: Result<MergeProjectReport, MoveErr> = async {+ let (source_ws, source, source_name) = resolve_target_for_admin(+ &state,+ &req.workspace,+ req.from.as_deref(),+ req.from_project_id.as_deref(),+ )+ .await?;+ let (target_ws, target, target_name) = resolve_target_for_admin(+ &state,+ &req.workspace,+ req.into.as_deref(),+ req.into_project_id.as_deref(),+ )+ .await?;+ if source_ws != target_ws {+ return Err((+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({"error": "projects must be in the same workspace"})),+ ));+ }+ if source == target {+ return Err((+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({"error": "source and target project must be different"})),+ ));+ }+ let pages = prepare_project_merge(+ &state,+ &req.workspace,+ &source_name,+ source,+ &target_name,+ target,+ source_ws,+ )+ .await?;+ let store_pages = pages.iter().map(|page| page.store.clone()).collect();+ let summary = if req.confirm {+ let admission = AdmissionContext {+ workspace: req.workspace.clone(),+ project: source_name.clone(),+ destination_workspace: Some(req.workspace.clone()),+ destination_project: Some(target_name.clone()),+ op: AdmissionOp::MoveProject,+ actor,+ ..Default::default()+ };+ state+ .wiki+ .merge_project(source_ws, source, target, pages, Some(admission))+ .await+ .map_err(|error| match error {+ WikiError::Io(ref io) if io.kind() == std::io::ErrorKind::NotFound => (+ StatusCode::CONFLICT,+ Json(serde_json::json!({+ "error": "project pages changed while the merge was committing"+ })),+ ),+ WikiError::Store(StoreError::ManagedRunActive { .. })+ | WikiError::Store(StoreError::ProjectSessionsOpen { .. })+ | WikiError::Store(StoreError::Duplicate(_))+ | WikiError::Store(StoreError::PagePathCollides { .. })+ | WikiError::Store(StoreError::NotFound(_)) => (+ StatusCode::CONFLICT,+ Json(serde_json::json!({"error": error.to_string()})),+ ),+ _ => internal_err(error.to_string()),+ })?+ } else {+ state+ .writer+ .merge_project(source_ws, source, target, store_pages, false)+ .await+ .map_err(|error| match error {+ StoreError::ManagedRunActive { .. }+ | StoreError::ProjectSessionsOpen { .. }+ | StoreError::Duplicate(_)+ | StoreError::PagePathCollides { .. } => (+ StatusCode::CONFLICT,+ Json(serde_json::json!({"error": error.to_string()})),+ ),+ StoreError::NotFound(_) => (+ StatusCode::NOT_FOUND,+ Json(serde_json::json!({"error": error.to_string()})),+ ),+ _ => internal_err(error.to_string()),+ })?+ };+ let (checkpoint, manifest_warning) = if req.confirm {+ state.active_project.clear_project(source);+ invalidate_scope_cache(&state, ScopeInvalidation::Project(source)).await;+ let manifest_warning = state+ .wiki+ .backfill_scope_manifests()+ .await+ .err()+ .map(|error| {+ warn!(%error, "merge-project: scope manifest refresh failed");+ error.to_string()+ });+ (+ checkpoint_or_warn(+ &state.wiki,+ format!(+ "merge-project {}/{} -> {}/{}",+ req.workspace, source_name, req.workspace, target_name+ ),+ ),+ manifest_warning,+ )+ } else {+ (None, None)+ };+ Ok(MergeProjectReport {+ from: format!("{}/{}", req.workspace, source_name),+ into: format!("{}/{}", req.workspace, target_name),+ dry_run: !req.confirm,+ page_versions: summary.page_versions,+ sessions: summary.sessions,+ observations: summary.observations,+ handoffs: summary.handoffs,+ workstreams: summary.workstreams,+ page_conflicts: summary.page_conflicts,+ checkpoint,+ manifest_warning,+ })+ }+ .await;+ match result {+ Ok(report) => (+ StatusCode::OK,+ Json(serde_json::to_value(report).unwrap_or_else(|_| serde_json::json!({}))),+ ),+ Err(error) => error,+ }+}+/// JSON request body for `POST /admin/move-project`.#[derive(Deserialize)]struct MoveProjectRequest {diff --git a/crates/ai-memory-mcp/tests/suite/admin_move.rs b/crates/ai-memory-mcp/tests/suite/admin_move.rsindex c872ee3a..3ec38070 100644--- a/crates/ai-memory-mcp/tests/suite/admin_move.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_move.rs@@ -3458,3 +3458,318 @@ async fn move_project_still_accepts_a_bare_project_name() {.await;assert_eq!(resp.status(), StatusCode::OK);}++#[tokio::test]+async fn merge_project_dry_run_then_preserves_history_and_sessions() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ seed_page(+ &store,+ &state.wiki,+ "default",+ "source",+ "notes/shared.md",+ "source body",+ )+ .await;+ seed_page(+ &store,+ &state.wiki,+ "default",+ "source",+ "notes/source-only.md",+ "source only",+ )+ .await;+ seed_page(+ &store,+ &state.wiki,+ "default",+ "target",+ "notes/shared.md",+ "target body",+ )+ .await;+ let ws = store+ .reader+ .find_workspace("default".into())+ .await+ .unwrap()+ .unwrap();+ let source = store+ .reader+ .find_project(ws, "source".into())+ .await+ .unwrap()+ .unwrap();+ let target = store+ .reader+ .find_project(ws, "target".into())+ .await+ .unwrap()+ .unwrap();+ let source_shared_id = store+ .reader+ .latest_page_id_by_ids(ws, source, "notes/shared.md".into())+ .await+ .unwrap()+ .expect("source page exists");+ let session = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ occurred_at: None,+ id: session,+ workspace_id: ws,+ project_id: source,+ agent_kind: AgentKind::Codex,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();+ store.writer.end_session(session, None).await.unwrap();++ let preview = post(+ state.clone(),+ "/admin/merge-project",+ json!({"workspace": "default", "from": "source", "into": "target"}),+ )+ .await;+ assert_eq!(preview.status(), StatusCode::OK);+ let preview = body_json(preview).await;+ assert_eq!(preview["dry_run"], true);+ assert_eq!(preview["page_versions"], 2);+ assert_eq!(preview["sessions"], 1);+ assert!(+ store+ .reader+ .find_project(ws, "source".into())+ .await+ .unwrap()+ .is_some(),+ "dry run must preserve the source"+ );++ let merged = post(+ state.clone(),+ "/admin/merge-project",+ json!({+ "workspace": "default",+ "from": "source",+ "into": "target",+ "confirm": true+ }),+ )+ .await;+ assert_eq!(+ merged.status(),+ StatusCode::OK,+ "{}",+ body_json(merged).await+ );+ assert!(+ store+ .reader+ .find_project(ws, "source".into())+ .await+ .unwrap()+ .is_none()+ );+ assert_eq!(+ store.reader.session_project_ids(session).await.unwrap(),+ Some((ws, target))+ );+ let shared = state+ .wiki+ .read_page(ws, target, &PagePath::new("notes/shared.md").unwrap())+ .unwrap();+ assert!(shared.body.contains("target body"));+ assert!(shared.body.contains("source body"));+ assert!(shared.body.contains("ai-memory:merged-from default/source"));+ let source_only = state+ .wiki+ .read_page(ws, target, &PagePath::new("notes/source-only.md").unwrap())+ .unwrap();+ assert_eq!(source_only.body, "source only");+ assert_eq!(+ store+ .reader+ .page_versions(ws, target, "notes/shared.md".into(), 10, 0)+ .await+ .unwrap()+ .total,+ 3,+ "both old heads and the merged head remain reachable"+ );++ let restored = post(+ state.clone(),+ "/admin/restore-page",+ json!({+ "workspace": "default",+ "project": "target",+ "path": "notes/shared.md",+ "page_id": source_shared_id.to_string()+ }),+ )+ .await;+ assert_eq!(+ restored.status(),+ StatusCode::OK,+ "{}",+ body_json(restored).await+ );+ let shared = state+ .wiki+ .read_page(ws, target, &PagePath::new("notes/shared.md").unwrap())+ .unwrap();+ assert_eq!(shared.body, "source body");+ assert_eq!(+ store+ .reader+ .page_versions(ws, target, "notes/shared.md".into(), 10, 0)+ .await+ .unwrap()+ .total,+ 4,+ "restoring a retained source version creates a new latest version"+ );+}++#[tokio::test]+async fn merge_project_refuses_open_sessions_and_foreign_ids() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let source = store+ .writer+ .get_or_create_project(ws, "source", None)+ .await+ .unwrap();+ store+ .writer+ .get_or_create_project(ws, "target", None)+ .await+ .unwrap();+ let session = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ occurred_at: None,+ id: session,+ workspace_id: ws,+ project_id: source,+ agent_kind: AgentKind::Codex,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();+ let open = post(+ state.clone(),+ "/admin/merge-project",+ json!({+ "workspace": "default",+ "from": "source",+ "into": "target",+ "confirm": true+ }),+ )+ .await;+ assert_eq!(open.status(), StatusCode::CONFLICT);++ let foreign_ws = store+ .writer+ .get_or_create_workspace("foreign")+ .await+ .unwrap();+ let foreign = store+ .writer+ .get_or_create_project(foreign_ws, "other", None)+ .await+ .unwrap();+ let foreign_response = post(+ state,+ "/admin/merge-project",+ json!({+ "workspace": "default",+ "from_project_id": source.to_string(),+ "into_project_id": foreign.to_string(),+ "confirm": true+ }),+ )+ .await;+ assert_eq!(foreign_response.status(), StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn concurrent_project_merges_have_one_winner_without_losing_the_page() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;+ seed_page(+ &store,+ &state.wiki,+ "default",+ "source",+ "notes/only.md",+ "keep me",+ )+ .await;+ let ws = store+ .reader+ .find_workspace("default".into())+ .await+ .unwrap()+ .unwrap();+ let target = store+ .writer+ .get_or_create_project(ws, "target", None)+ .await+ .unwrap();+ let request = json!({+ "workspace": "default",+ "from": "source",+ "into": "target",+ "confirm": true+ });+ let (first, second) = tokio::join!(+ post(state.clone(), "/admin/merge-project", request.clone()),+ post(state.clone(), "/admin/merge-project", request),+ );+ let statuses = [first.status(), second.status()];+ assert_eq!(+ statuses+ .iter()+ .filter(|status| **status == StatusCode::OK)+ .count(),+ 1,+ "exactly one concurrent merge may commit: {statuses:?}"+ );+ assert!(+ statuses+ .iter()+ .any(|status| matches!(*status, StatusCode::NOT_FOUND | StatusCode::CONFLICT))+ );+ assert_eq!(+ state+ .wiki+ .read_page(ws, target, &PagePath::new("notes/only.md").unwrap())+ .unwrap()+ .body,+ "keep me"+ );+ assert_eq!(+ store+ .reader+ .page_versions(ws, target, "notes/only.md".into(), 10, 0)+ .await+ .unwrap()+ .total,+ 1+ );+}diff --git a/crates/ai-memory-store/Cargo.toml b/crates/ai-memory-store/Cargo.tomlindex 4e0e53ad..8f3bdb5b 100644--- a/crates/ai-memory-store/Cargo.toml+++ b/crates/ai-memory-store/Cargo.toml@@ -20,6 +20,7 @@ serde_json.workspace = truetokio.workspace = truetracing.workspace = trueicu_normalizer.workspace = true+unicode_categories.workspace = truejiff.workspace = trueuuid.workspace = truesha2.workspace = truediff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rsindex bb1a512e..02d2f5c8 100644--- a/crates/ai-memory-store/src/error.rs+++ b/crates/ai-memory-store/src/error.rs@@ -200,6 +200,14 @@ pub enum StoreError {workstreams: String,},+ /// A project merge was refused because sessions can still receive hook+ /// observations under the source coordinate.+ #[error("project has {count} open session(s); finish them before merging the project")]+ ProjectSessionsOpen {+ /// Number of source sessions whose `ended_at` is still NULL.+ count: u64,+ },+/// A workspace rename was rejected because the destination name is already/// in use by another workspace (`workspaces.name` is UNIQUE).#[error("workspace name '{0}' is already taken")]diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex c880bda1..d75b509c 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -65,12 +65,13 @@ pub use ops::{ConditionalUpsert, DateOnlyTtlPage, DeleteWorkspaceSummary, EmbedOutcome, EmbeddingWrite,EntityBackfillSummary, HookSessionAdmission, IdentityResolution, IdleEndAction,IdleEndCandidate, IdleEndResult, IngestObservationOutcome, LifecycleOnlyEndOutcome,- MAX_PENDING_INBOX_MESSAGES, MoveSessionSummary, MoveSummary, ObservationPruneOutcome,- OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH, PagePrecondition, PageWindowBackfillSummary,- PagesMode, ProjectAliasWriteResolution, PurgeMode, PurgeSessionSummary, PurgeSummary,- ReorgSummary, RepairSessionTimesSummary, RepairedSessionTimes, SessionTimesCandidate,- SessionTimesSkipReason, SkippedSessionTimes, StaleAfterRepair, backfill_entity_index,- backfill_page_windows, backfill_page_windows_in_batches, purge_session, record_embed_failure,+ MAX_PENDING_INBOX_MESSAGES, MergeProjectPage, MergeProjectSummary, MoveSessionSummary,+ MoveSummary, ObservationPruneOutcome, OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH,+ PagePrecondition, PageWindowBackfillSummary, PagesMode, ProjectAliasWriteResolution, PurgeMode,+ PurgeSessionSummary, PurgeSummary, ReorgSummary, RepairSessionTimesSummary,+ RepairedSessionTimes, SessionTimesCandidate, SessionTimesSkipReason, SkippedSessionTimes,+ StaleAfterRepair, backfill_entity_index, backfill_page_windows,+ backfill_page_windows_in_batches, purge_session, record_embed_failure,};pub use profile::{NewProfileCandidate, PROFILE_CANDIDATES_LIMIT, PROFILE_ENTRIES_LIMIT, PROFILE_HARVEST_BATCH,diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 6b361506..3f4b1986 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -7692,6 +7692,39 @@ pub struct MoveSummary {pub workstreams_moved: u64,}+/// One latest source page captured by the wiki layer for a same-workspace+/// project merge.+#[derive(Debug, Clone)]+pub struct MergeProjectPage {+ /// Source page path.+ pub path: PagePath,+ /// Latest source version observed while preparing the filesystem change.+ pub source_page_id: PageId,+ /// Latest target version at the same path, when the paths collide.+ pub target_page_id: Option<PageId>,+ /// New combined target version for a collision. `None` means the source's+ /// existing latest row becomes the target latest row unchanged.+ pub merged_page: Option<NewPage>,+}++/// Result of atomically merging one project id into another in the same+/// workspace.+#[derive(Debug, Default, Clone)]+pub struct MergeProjectSummary {+ /// All source page versions re-stamped to the target project.+ pub page_versions: u64,+ /// Source sessions re-stamped to the target project.+ pub sessions: u64,+ /// Source observations re-stamped to the target project.+ pub observations: u64,+ /// Source handoffs re-stamped to the target project.+ pub handoffs: u64,+ /// Source managed workstreams re-stamped to the target project.+ pub workstreams: u64,+ /// New combined page versions created for same-path collisions.+ pub page_conflicts: u64,+}+/// Re-stamp a project's `workspace_id` across every domain table in ONE/// transaction, keeping the same `project_id`. This is a lossless "true move":/// pages, sessions, observations, handoffs and supersession history all stay@@ -7837,6 +7870,435 @@ pub fn move_project_workspace(})}+/// Merge `source_project` into `target_project` inside one workspace.+///+/// Every persisted row is either re-stamped, coalesced under its natural+/// unique key, or retained behind its page/workstream id. Page ids never+/// change, so embeddings, evidence, access rows and graph edges follow their+/// versions automatically. Same-path page collisions are represented by a+/// new target version supplied by the wiki layer; both prior histories remain+/// superseded and queryable.+pub fn merge_project(+ conn: &mut Connection,+ workspace_id: WorkspaceId,+ source_project: ProjectId,+ target_project: ProjectId,+ pages: &[MergeProjectPage],+ commit: bool,+) -> StoreResult<MergeProjectSummary> {+ if source_project == target_project {+ return Err(StoreError::Duplicate(+ "source and target project must be different".into(),+ ));+ }+ let tx = conn.transaction()?;+ let ws = workspace_id.as_bytes();+ let src = source_project.as_bytes();+ let dst = target_project.as_bytes();+ for (id, label) in [(src, "source"), (dst, "target")] {+ let present: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM projects WHERE id = ?1 AND workspace_id = ?2)",+ params![id, ws],+ |row| row.get(0),+ )?;+ if !present {+ return Err(StoreError::NotFound(format!(+ "{label} project does not exist in workspace {workspace_id}"+ )));+ }+ }++ let open_sessions: u64 = tx.query_row(+ "SELECT COUNT(*) FROM sessions WHERE project_id = ?1 AND ended_at IS NULL",+ params![src],+ |row| row.get(0),+ )?;+ if open_sessions > 0 {+ return Err(StoreError::ProjectSessionsOpen {+ count: open_sessions,+ });+ }+ let now = Timestamp::now().as_microsecond();+ let (active_runs, active_names): (u64, String) = tx.query_row(+ "SELECT COUNT(*), COALESCE(group_concat(w.name, ', '), '') \+ FROM managed_runs r JOIN workstreams w ON w.id = r.workstream_id \+ WHERE w.project_id = ?1 AND r.state = 'active' AND r.lease_expires_at > ?2",+ params![src, now],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )?;+ if active_runs > 0 {+ return Err(StoreError::ManagedRunActive {+ count: active_runs,+ workstreams: active_names,+ });+ }++ let expected: std::collections::HashSet<PageId> =+ pages.iter().map(|page| page.source_page_id).collect();+ if expected.len() != pages.len() {+ return Err(StoreError::Duplicate(+ "project merge page plan contains duplicate source versions".into(),+ ));+ }+ let actual: Vec<Vec<u8>> = tx+ .prepare("SELECT id FROM pages WHERE project_id = ?1 AND is_latest = 1")?+ .query_map(params![src], |row| row.get(0))?+ .collect::<Result<_, _>>()?;+ let actual: std::collections::HashSet<PageId> = actual+ .iter()+ .map(|id| PageId::from_slice(id).map_err(StoreError::from))+ .collect::<StoreResult<_>>()?;+ if actual != expected {+ return Err(StoreError::Duplicate(+ "source pages changed while the project merge was being prepared".into(),+ ));+ }+ let target_paths: Vec<String> = tx+ .prepare("SELECT path FROM pages WHERE project_id = ?1 AND is_latest = 1")?+ .query_map(params![dst], |row| row.get(0))?+ .collect::<Result<_, _>>()?;+ for page in pages {+ let requested_key = ai_memory_core::portable_page_key(page.path.as_str());+ if let Some(existing) = target_paths.iter().find(|existing| {+ existing.as_str() != page.path.as_str()+ && ai_memory_core::portable_page_key(existing) == requested_key+ }) {+ return Err(StoreError::PagePathCollides {+ requested: page.path.as_str().to_owned(),+ existing: existing.clone(),+ });+ }+ }+ for page in pages {+ let source_path: Option<String> = tx+ .query_row(+ "SELECT path FROM pages WHERE id = ?1 AND project_id = ?2 AND is_latest = 1",+ params![page.source_page_id.as_bytes(), src],+ |row| row.get(0),+ )+ .optional()?;+ if source_path.as_deref() != Some(page.path.as_str()) {+ return Err(StoreError::Duplicate(format!(+ "source page plan does not match '{}'",+ page.path.as_str()+ )));+ }+ let target: Option<Vec<u8>> = tx+ .query_row(+ "SELECT id FROM pages WHERE project_id = ?1 AND path = ?2 AND is_latest = 1",+ params![dst, page.path.as_str()],+ |row| row.get(0),+ )+ .optional()?;+ let target = target+ .as_deref()+ .map(PageId::from_slice)+ .transpose()+ .map_err(StoreError::from)?;+ if target != page.target_page_id {+ return Err(StoreError::Duplicate(format!(+ "target page '{}' changed while the project merge was being prepared",+ page.path.as_str()+ )));+ }+ if page.target_page_id.is_some() != page.merged_page.is_some() {+ return Err(StoreError::Duplicate(format!(+ "invalid collision plan for '{}'",+ page.path.as_str()+ )));+ }+ if page+ .merged_page+ .as_ref()+ .is_some_and(|merged| merged.path != page.path)+ {+ return Err(StoreError::Duplicate(format!(+ "merged page path does not match '{}'",+ page.path.as_str()+ )));+ }+ }++ // Merging must never relax either project's access or profile privacy.+ // The target identity remains canonical, but the stricter policy wins.+ tx.execute(+ "UPDATE projects SET \+ access_mode = CASE WHEN access_mode = 'restricted' OR \+ (SELECT access_mode FROM projects WHERE id = ?2) = 'restricted' \+ THEN 'restricted' ELSE 'open' END, \+ profile_contribute = min(profile_contribute, \+ (SELECT profile_contribute FROM projects WHERE id = ?2)), \+ profile_consume = min(profile_consume, \+ (SELECT profile_consume FROM projects WHERE id = ?2)) \+ WHERE id = ?1",+ params![dst, src],+ )?;++ // Retire colliding source heads first so moving the full history cannot+ // violate the target's one-latest-version-per-path index.+ for page in pages.iter().filter(|page| page.target_page_id.is_some()) {+ tx.execute(+ "UPDATE pages SET is_latest = 0, valid_to = ?2 WHERE id = ?1 AND is_latest = 1",+ params![page.source_page_id.as_bytes(), now],+ )?;+ tx.execute(+ "UPDATE entity_page_links SET superseded_at = ?2 \+ WHERE page_id = ?1 AND superseded_at IS NULL",+ params![page.source_page_id.as_bytes(), now],+ )?;+ }++ let page_versions = tx.execute(+ "UPDATE pages SET project_id = ?1 WHERE project_id = ?2",+ params![dst, src],+ )? as u64;+ let sessions = tx.execute(+ "UPDATE sessions SET project_id = ?1 WHERE project_id = ?2",+ params![dst, src],+ )? as u64;+ let observations = tx.execute(+ "UPDATE observations SET project_id = ?1 WHERE project_id = ?2",+ params![dst, src],+ )? as u64;+ let handoffs = tx.execute(+ "UPDATE handoffs SET project_id = ?1 WHERE project_id = ?2",+ params![dst, src],+ )? as u64;++ // A pending proposal's target key is unique per project. Preserve both+ // proposals by making the source one an explicit conflict before moving.+ tx.execute(+ "UPDATE auto_improve_proposals SET status = 'conflict', decided_at = ?3, \+ decision_reason = 'source project merged into another project' \+ WHERE project_id = ?1 AND status = 'pending' AND EXISTS ( \+ SELECT 1 FROM auto_improve_proposals d \+ WHERE d.project_id = ?2 AND d.status = 'pending' \+ AND d.target_path = auto_improve_proposals.target_path)",+ params![src, dst, now],+ )?;+ for table in [+ "audit_log",+ "auto_improve_runs",+ "auto_improve_proposals",+ "auto_improve_rejections",+ "auto_improve_scheduler_claims",+ "session_consolidation_jobs",+ "page_feedback",+ "purged_sessions",+ ] {+ tx.execute(+ &format!("UPDATE {table} SET project_id = ?1 WHERE project_id = ?2"),+ params![dst, src],+ )?;+ }++ // Coalesce singleton/project-keyed state instead of discarding either+ // side. A later watermark wins; the earliest initialization remains the+ // provenance boundary.+ tx.execute(+ "INSERT INTO auto_improve_scheduler_state \+ (workspace_id, project_id, watermark_ended_at, initialized_at, updated_at) \+ SELECT workspace_id, ?1, watermark_ended_at, initialized_at, updated_at \+ FROM auto_improve_scheduler_state WHERE project_id = ?2 \+ ON CONFLICT(workspace_id, project_id) DO UPDATE SET \+ watermark_ended_at = max(watermark_ended_at, excluded.watermark_ended_at), \+ initialized_at = min(initialized_at, excluded.initialized_at), \+ updated_at = max(updated_at, excluded.updated_at)",+ params![dst, src],+ )?;+ tx.execute(+ "DELETE FROM auto_improve_scheduler_state WHERE project_id = ?1",+ params![src],+ )?;++ tx.execute(+ "INSERT INTO project_grants (workspace_id, project_id, user_id, level, granted_by, granted_at) \+ SELECT workspace_id, ?1, user_id, level, granted_by, granted_at \+ FROM project_grants WHERE project_id = ?2 \+ ON CONFLICT(workspace_id, project_id, user_id) DO UPDATE SET \+ level = CASE WHEN level = 'write' OR excluded.level = 'write' THEN 'write' ELSE 'read' END, \+ granted_at = min(granted_at, excluded.granted_at)",+ params![dst, src],+ )?;+ tx.execute(+ "DELETE FROM project_grants WHERE project_id = ?1",+ params![src],+ )?;++ // Same-name entities become one noun while every page edge survives.+ let duplicate_entities: Vec<(Vec<u8>, Vec<u8>)> = tx+ .prepare(+ "SELECT s.id, d.id FROM entities s JOIN entities d \+ ON d.workspace_id = s.workspace_id AND d.project_id = ?2 AND d.name = s.name \+ WHERE s.project_id = ?1",+ )?+ .query_map(params![src, dst], |row| Ok((row.get(0)?, row.get(1)?)))?+ .collect::<Result<_, _>>()?;+ for (source_entity, target_entity) in duplicate_entities {+ tx.execute(+ "INSERT OR IGNORE INTO entity_page_links (entity_id, page_id, valid_from, superseded_at) \+ SELECT ?1, page_id, valid_from, superseded_at FROM entity_page_links WHERE entity_id = ?2",+ params![target_entity, source_entity],+ )?;+ tx.execute("DELETE FROM entities WHERE id = ?1", params![source_entity])?;+ }+ tx.execute(+ "UPDATE entities SET project_id = ?1 WHERE project_id = ?2",+ params![dst, src],+ )?;++ // Keep every colliding workstream by giving only the source stream a+ // deterministic disambiguator before the coordinate update.+ tx.execute(+ "UPDATE workstreams SET name = name || '-from-' || lower(hex(?1)) \+ || '-' || lower(hex(id)) \+ WHERE project_id = ?1 AND EXISTS (SELECT 1 FROM workstreams d \+ WHERE d.project_id = ?2 \+ AND d.repo_fingerprint = workstreams.repo_fingerprint \+ AND d.worktree_fingerprint = workstreams.worktree_fingerprint \+ AND d.name = workstreams.name)",+ params![src, dst],+ )?;+ let workstreams = tx.execute(+ "UPDATE workstreams SET project_id = ?1 WHERE project_id = ?2",+ params![dst, src],+ )? as u64;++ // Candidate identity is evidence identity. Preserve a collision by+ // qualifying the source reference before moving it.+ tx.execute(+ "UPDATE profile_candidates SET source_ref = source_ref || '#merged-' || lower(substr(hex(id), 1, 8)) \+ WHERE project_id = ?1 AND EXISTS (SELECT 1 FROM profile_candidates d \+ WHERE d.project_id = ?2 \+ AND d.source_kind = profile_candidates.source_kind \+ AND d.source_ref = profile_candidates.source_ref \+ AND d.topic_key = profile_candidates.topic_key)",+ params![src, dst],+ )?;+ tx.execute(+ "UPDATE profile_candidates SET project_id = ?1 WHERE project_id = ?2",+ params![dst, src],+ )?;+ tx.execute(+ "INSERT INTO profile_entry_ledger (workspace_id, project_id, path, topic_key, written_at) \+ SELECT workspace_id, ?1, path, topic_key, written_at FROM profile_entry_ledger WHERE project_id = ?2 \+ ON CONFLICT(workspace_id, project_id, path) DO UPDATE SET \+ topic_key = CASE WHEN excluded.written_at > written_at THEN excluded.topic_key ELSE topic_key END, \+ written_at = max(written_at, excluded.written_at)",+ params![dst, src],+ )?;+ tx.execute(+ "DELETE FROM profile_entry_ledger WHERE project_id = ?1",+ params![src],+ )?;+ tx.execute(+ "INSERT INTO profile_harvest_marks (workspace_id, project_id, observations_until, pages_until) \+ SELECT workspace_id, ?1, observations_until, pages_until FROM profile_harvest_marks WHERE project_id = ?2 \+ ON CONFLICT(workspace_id, project_id) DO UPDATE SET \+ observations_until = max(observations_until, excluded.observations_until), \+ pages_until = max(pages_until, excluded.pages_until)",+ params![dst, src],+ )?;+ tx.execute(+ "DELETE FROM profile_harvest_marks WHERE project_id = ?1",+ params![src],+ )?;+ tx.execute(+ "INSERT INTO ingest_keys (project_id, key, seen_at, completed_at) \+ SELECT ?1, key, seen_at, completed_at FROM ingest_keys WHERE project_id = ?2 \+ ON CONFLICT(project_id, key) DO UPDATE SET \+ seen_at = max(seen_at, excluded.seen_at), \+ completed_at = CASE \+ WHEN completed_at IS NULL THEN excluded.completed_at \+ WHEN excluded.completed_at IS NULL THEN completed_at \+ ELSE max(completed_at, excluded.completed_at) END",+ params![dst, src],+ )?;+ tx.execute(+ "DELETE FROM ingest_keys WHERE project_id = ?1",+ params![src],+ )?;++ tx.execute(+ "UPDATE agent_messages SET from_project_id = ?1 WHERE from_project_id = ?2",+ params![dst, src],+ )?;+ tx.execute(+ "UPDATE agent_messages SET to_project_id = ?1 WHERE to_project_id = ?2",+ params![dst, src],+ )?;++ let mut page_conflicts = 0u64;+ for page in pages {+ if let Some(merged) = &page.merged_page {+ if merged.workspace_id != workspace_id || merged.project_id != target_project {+ return Err(StoreError::Duplicate(format!(+ "merged page '{}' targets the wrong scope",+ page.path.as_str()+ )));+ }+ let created_at: i64 = tx.query_row(+ "SELECT min(created_at) FROM pages WHERE project_id = ?1 AND path = ?2",+ params![dst, page.path.as_str()],+ |row| row.get(0),+ )?;+ let merged_id = upsert_page_in_tx(&tx, merged, now)?;+ tx.execute(+ "UPDATE pages SET created_at = ?2 WHERE id = ?1",+ params![merged_id.as_bytes(), created_at],+ )?;+ tx.execute(+ "INSERT INTO page_feedback \+ (id, page_id, workspace_id, project_id, kind, reason, salience_after, created_at) \+ VALUES (?1, ?2, ?3, ?4, 'stale', ?5, 1.0, ?6)",+ params![+ uuid::Uuid::now_v7().as_bytes(),+ merged_id.as_bytes(),+ ws,+ dst,+ format!("merged from source project {source_project}"),+ now,+ ],+ )?;+ page_conflicts += 1;+ }+ }++ audit_with_detail(+ &tx,+ "merge_project",+ Some(ws),+ Some(dst),+ None,+ None,+ now,+ &serde_json::json!({"source_project_id": source_project.to_string()}).to_string(),+ )?;++ let deleted = tx.execute(+ "DELETE FROM projects WHERE id = ?1 AND workspace_id = ?2",+ params![src, ws],+ )?;+ if deleted != 1 {+ return Err(StoreError::NotFound(+ "source project disappeared during merge".into(),+ ));+ }+ if commit {+ tx.commit()?;+ } else {+ tx.rollback()?;+ }+ Ok(MergeProjectSummary {+ page_versions,+ sessions,+ observations,+ handoffs,+ workstreams,+ page_conflicts,+ })+}+/// 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, Default, serde::Serialize, serde::Deserialize)]@@ -14912,6 +15374,241 @@ pub(crate) mod tests {assert_eq!(src_pages, 1, "rollback must preserve source pages");}+ #[test]+ fn merge_project_preserves_both_page_histories_and_dependent_rows() {+ let (_tmp, mut conn, ws, source) = fresh_db();+ let target = get_or_create_project(&mut conn, &ws, "target", None).unwrap();+ conn.execute(+ "UPDATE projects SET access_mode = 'restricted', profile_contribute = 0, \+ profile_consume = 0 WHERE id = ?1",+ params![source.as_bytes()],+ )+ .unwrap();+ let source_old = upsert_page(+ &mut conn,+ &page(ws, source, "notes/shared.md", "source old"),+ )+ .unwrap();+ let source_latest = upsert_page(+ &mut conn,+ &page(ws, source, "notes/shared.md", "source latest"),+ )+ .unwrap();+ let unique = upsert_page(+ &mut conn,+ &page(ws, source, "notes/source-only.md", "unique"),+ )+ .unwrap();+ let target_latest = upsert_page(+ &mut conn,+ &page(ws, target, "notes/shared.md", "target body"),+ )+ .unwrap();+ let earliest_created: i64 = conn+ .query_row(+ "SELECT min(created_at) FROM pages WHERE id IN (?1, ?2, ?3)",+ params![+ source_old.as_bytes(),+ source_latest.as_bytes(),+ target_latest.as_bytes()+ ],+ |row| row.get(0),+ )+ .unwrap();+ store_embedding(&mut conn, &source_latest, &[1, 2, 3, 4], "test", "m", 1).unwrap();++ let sid = SessionId::new();+ begin_session(&mut conn, &hook_session(sid, ws, source, None)).unwrap();+ insert_observation(+ &mut conn,+ &hook_observation(&hook_session(sid, ws, source, None)),+ )+ .unwrap();+ end_session(&mut conn, &sid, None).unwrap();++ let merged = page(+ ws,+ target,+ "notes/shared.md",+ "target body\n\n<!-- ai-memory:merged-from default/scratch -->\n\nsource latest",+ );+ let plan = vec![+ MergeProjectPage {+ path: PagePath::new("notes/shared.md").unwrap(),+ source_page_id: source_latest,+ target_page_id: Some(target_latest),+ merged_page: Some(merged),+ },+ MergeProjectPage {+ path: PagePath::new("notes/source-only.md").unwrap(),+ source_page_id: unique,+ target_page_id: None,+ merged_page: None,+ },+ ];++ let preview = merge_project(&mut conn, ws, source, target, &plan, false).unwrap();+ assert_eq!(preview.page_versions, 3);+ assert_eq!(preview.sessions, 1);+ assert_eq!(preview.observations, 1);+ assert_eq!(preview.page_conflicts, 1);+ assert_eq!(+ conn.query_row(+ "SELECT COUNT(*) FROM projects WHERE id = ?1",+ params![source.as_bytes()],+ |row| row.get::<_, i64>(0),+ )+ .unwrap(),+ 1,+ "preview must roll back"+ );++ let summary = merge_project(&mut conn, ws, source, target, &plan, true).unwrap();+ assert_eq!(summary.page_versions, 3);+ assert_eq!(summary.page_conflicts, 1);+ assert_eq!(summary.sessions, 1);+ assert_eq!(summary.observations, 1);+ assert_eq!(+ conn.query_row(+ "SELECT COUNT(*) FROM projects WHERE id = ?1",+ params![source.as_bytes()],+ |row| row.get::<_, i64>(0),+ )+ .unwrap(),+ 0+ );+ let policy: (String, i64, i64) = conn+ .query_row(+ "SELECT access_mode, profile_contribute, profile_consume FROM projects WHERE id = ?1",+ params![target.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .unwrap();+ assert_eq!(policy, ("restricted".into(), 0, 0));+ assert_eq!(+ conn.query_row(+ "SELECT COUNT(*) FROM pages WHERE project_id = ?1 AND path = 'notes/shared.md'",+ params![target.as_bytes()],+ |row| row.get::<_, i64>(0),+ )+ .unwrap(),+ 4,+ "target history, source history and combined head must survive"+ );+ let (body, latest, merged_created): (String, i64, i64) = conn+ .query_row(+ "SELECT body, is_latest, created_at FROM pages WHERE project_id = ?1 \+ AND path = 'notes/shared.md' ORDER BY updated_at DESC, rowid DESC LIMIT 1",+ params![target.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .unwrap();+ assert!(body.contains("target body"));+ assert!(body.contains("source latest"));+ assert_eq!(latest, 1);+ assert_eq!(merged_created, earliest_created);+ assert_eq!(+ conn.query_row(+ "SELECT COUNT(*) FROM page_embeddings WHERE page_id = ?1",+ params![source_latest.as_bytes()],+ |row| row.get::<_, i64>(0),+ )+ .unwrap(),+ 1,+ "embedding follows the unchanged source page id"+ );+ for id in [source_old, source_latest, target_latest] {+ let latest: i64 = conn+ .query_row(+ "SELECT is_latest FROM pages WHERE id = ?1",+ params![id.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(latest, 0, "prior versions remain reachable but superseded");+ }+ }++ #[test]+ fn merge_project_refuses_open_sessions_and_foreign_project_ids() {+ let (_tmp, mut conn, ws, source) = fresh_db();+ let target = get_or_create_project(&mut conn, &ws, "target", None).unwrap();+ let sid = SessionId::new();+ begin_session(&mut conn, &hook_session(sid, ws, source, None)).unwrap();+ assert!(matches!(+ merge_project(&mut conn, ws, source, target, &[], true),+ Err(StoreError::ProjectSessionsOpen { count: 1 })+ ));+ end_session(&mut conn, &sid, None).unwrap();++ let source_page =+ upsert_page(&mut conn, &page(ws, source, "notes/Case.md", "source")).unwrap();+ upsert_page(&mut conn, &page(ws, target, "notes/case.md", "target")).unwrap();+ let collision_plan = [MergeProjectPage {+ path: PagePath::new("notes/Case.md").unwrap(),+ source_page_id: source_page,+ target_page_id: None,+ merged_page: None,+ }];+ assert!(matches!(+ merge_project(&mut conn, ws, source, target, &collision_plan, true),+ Err(StoreError::PagePathCollides { .. })+ ));++ let foreign_ws = get_or_create_workspace(&mut conn, "foreign").unwrap();+ let foreign = get_or_create_project(&mut conn, &foreign_ws, "target", None).unwrap();+ assert!(matches!(+ merge_project(&mut conn, ws, source, foreign, &[], true),+ Err(StoreError::NotFound(_))+ ));+ assert_eq!(+ conn.query_row(+ "SELECT COUNT(*) FROM projects WHERE id = ?1",+ params![source.as_bytes()],+ |row| row.get::<_, i64>(0),+ )+ .unwrap(),+ 1,+ "a foreign target must move nothing"+ );+ }++ #[test]+ fn merge_project_preserves_colliding_workstreams() {+ let (_tmp, mut conn, ws, source) = fresh_db();+ let target = get_or_create_project(&mut conn, &ws, "target", None).unwrap();+ let now = Timestamp::now().as_microsecond();+ for (id, project) in [+ (uuid::Uuid::now_v7(), source),+ (uuid::Uuid::now_v7(), target),+ ] {+ conn.execute(+ "INSERT INTO workstreams (+ id, workspace_id, project_id, repo_fingerprint,+ worktree_fingerprint, name, cwd, created_at, selected_at, updated_at+ ) VALUES (?1, ?2, ?3, 'repo', 'tree', 'default', '/repo', ?4, ?4, ?4)",+ params![id.as_bytes(), ws.as_bytes(), project.as_bytes(), now],+ )+ .unwrap();+ }++ let summary = merge_project(&mut conn, ws, source, target, &[], true).unwrap();+ assert_eq!(summary.workstreams, 1);+ let names: Vec<String> = conn+ .prepare("SELECT name FROM workstreams WHERE project_id = ?1 ORDER BY name")+ .unwrap()+ .query_map(params![target.as_bytes()], |row| row.get(0))+ .unwrap()+ .collect::<Result<_, _>>()+ .unwrap();+ assert_eq!(names.len(), 2);+ assert_eq!(names[0], "default");+ assert!(+ names[1].starts_with("default-from-"),+ "source collision must receive a deterministic disambiguator: {names:?}"+ );+ }+/// Seed one session in `(ws, proj)` with everything `move_session`/// re-stamps: two observations, one handoff it produced, one completed/// consolidation job, one auto-improve run, one scheduler claim, and twodiff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex cb54982f..9b417193 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -1644,6 +1644,12 @@ pub struct PageVersionBody {pub title: String,/// Body stored on this version (markdown without frontmatter).pub body: String,+ /// Full frontmatter stored on this version.+ pub frontmatter: serde_json::Value,+ /// Memory tier stored on this version.+ pub tier: String,+ /// Whether this version was pinned.+ pub pinned: bool,/// ISO-8601 instant this version was written.pub created_at: String,}@@ -1788,24 +1794,31 @@ pub struct StatusCounts {/// The key two project names share when only their spelling differs/// (#1645).///-/// Case folds and decomposes first, so `Renato` and `Renato` written with a-/// combining accent are one key; then it keeps letters, digits, whitespace and-/// the separators a project name can legitimately use, which drops the-/// combining marks themselves and stray punctuation. It is a *finding*-/// heuristic, deliberately a little broad: a false positive costs a line in a-/// read-only report, while a split project costs a quarter of someone's memory.+/// Compatibility-decomposes and lowercases first, then drops only non-spacing+/// marks. Punctuation remains significant: `api` and `api!` are different+/// project names, while `Renato`, `RENATO`, and `Rénato` share a key.#[must_use]pub fn project_name_fold_key(name: &str) -> String {- let decomposed = icu_normalizer::DecomposingNormalizer::new_nfd().normalize(name);+ use unicode_categories::UnicodeCategories as _;++ let decomposed = icu_normalizer::DecomposingNormalizer::new_nfkd().normalize(name);decomposed.chars()- .filter(|c| c.is_alphanumeric() || c.is_whitespace() || matches!(c, '-' | '_' | '.'))+ .filter(|c| !c.is_mark_nonspacing()).collect::<String>().to_lowercase().trim().to_string()}+fn project_name_case_key(name: &str) -> String {+ icu_normalizer::DecomposingNormalizer::new_nfd()+ .normalize(name)+ .to_lowercase()+ .trim()+ .to_string()+}+/// One likely cross-project contamination finding from/// [`ReaderPool::audit_contamination`]. Advisory only — it flags STRUCTURAL/// mislandings (an entity whose identity disagrees with the bucket it landed@@ -1843,6 +1856,13 @@ pub struct ContaminationFinding {/// Session count of this project (CHECK B).#[serde(skip_serializing_if = "Option::is_none")]pub sessions: Option<u64>,+ /// Whether the peer names differ by case, accent, or both (CHECK B).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub collision_kind: Option<&'static str>,+ /// Latest page/session/observation activity timestamp in microseconds+ /// since the Unix epoch (CHECK B).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub last_activity_us: Option<i64>,}/// Per-check counts for an [`ReaderPool::audit_contamination`] run.@@ -11430,7 +11450,7 @@ impl ReaderPool {let row = conn.query_row(&format!(- "SELECT pg.title, pg.body, pg.created_at, \+ "SELECT pg.title, pg.body, pg.frontmatter_json, pg.tier, pg.pinned, pg.created_at, \(SELECT sp.id FROM pages sp \WHERE sp.id = pg.supersedes{prev_visible}) \FROM pages pg \@@ -11450,13 +11470,16 @@ impl ReaderPool {Ok((row.get::<_, String>(0)?,row.get::<_, String>(1)?,- row.get::<_, i64>(2)?,- row.get::<_, Option<Vec<u8>>>(3)?,+ row.get::<_, String>(2)?,+ row.get::<_, String>(3)?,+ row.get::<_, i64>(4)?,+ row.get::<_, i64>(5)?,+ row.get::<_, Option<Vec<u8>>>(6)?,))},).optional()?;- let Some((title, body, created_us, supersedes)) = row else {+ let Some((title, body, frontmatter, tier, pinned, created_us, supersedes)) = row else {return Ok(None);};Ok(Some(PageVersionBody {@@ -11464,6 +11487,9 @@ impl ReaderPool {supersedes: supersedes.as_deref().map(PageId::from_slice).transpose()?,title,body,+ frontmatter: serde_json::from_str(&frontmatter).unwrap_or_default(),+ tier,+ pinned: pinned != 0,created_at: jiff::Timestamp::from_microsecond(created_us).map(|ts| ts.to_string()).unwrap_or_default(),@@ -12499,7 +12525,7 @@ impl ReaderPool {// CHECK B's input: every project in scope's workspace with its counts.// A project-scoped audit still needs its peers to detect a collision;// only the emitted findings are restricted to the requested project.- type ProjectRow = (String, String, Vec<u8>, String, u64, u64);+ type ProjectRow = (String, String, Vec<u8>, String, u64, u64, i64);let (mut findings, candidates, prefixes, projects): (Vec<ContaminationFinding>,Vec<Candidate>,@@ -12629,7 +12655,11 @@ impl ReaderPool {"SELECT lower(hex(p.id)), wl.name, p.id, p.name, \(SELECT COUNT(*) FROM pages pg WHERE pg.project_id = p.id \AND pg.is_latest = 1), \- (SELECT COUNT(*) FROM sessions s WHERE s.project_id = p.id) \+ (SELECT COUNT(*) FROM sessions s WHERE s.project_id = p.id), \+ max(p.created_at, \+ COALESCE((SELECT MAX(pg.updated_at) FROM pages pg WHERE pg.project_id = p.id), 0), \+ COALESCE((SELECT MAX(COALESCE(s.ended_at, s.started_at)) FROM sessions s WHERE s.project_id = p.id), 0), \+ COALESCE((SELECT MAX(o.created_at) FROM observations o WHERE o.project_id = p.id), 0)) \FROM projects p JOIN workspaces wl ON wl.id = p.workspace_id",);if scoped {@@ -12651,6 +12681,7 @@ impl ReaderPool {row.get::<_, String>(3)?,u64::try_from(row.get::<_, i64>(4)?).unwrap_or(0),u64::try_from(row.get::<_, i64>(5)?).unwrap_or(0),+ row.get::<_, i64>(6)?,))})?;for r in rows {@@ -12687,6 +12718,8 @@ impl ReaderPool {peer_projects: None,pages: None,sessions: None,+ collision_kind: None,+ last_activity_us: None,});}}@@ -12714,6 +12747,19 @@ impl ReaderPool {.filter(|peer| peer.0 != project.0).map(|peer| peer.3.as_str()).collect();+ let case_key = project_name_case_key(&project.3);+ let case_differs = peers+ .iter()+ .any(|peer| peer.0 != project.0 && project_name_case_key(&peer.3) == case_key);+ let accent_differs = peers+ .iter()+ .any(|peer| peer.0 != project.0 && project_name_case_key(&peer.3) != case_key);+ let collision_kind = match (case_differs, accent_differs) {+ (true, true) => "case_and_accent",+ (true, false) => "case",+ (false, true) => "accent",+ (false, false) => "spelling",+ };findings.push(ContaminationFinding {check: "project_name_collision",confidence: "medium",@@ -12726,6 +12772,8 @@ impl ReaderPool {peer_projects: Some(others.join(", ")),pages: Some(project.4),sessions: Some(project.5),+ collision_kind: Some(collision_kind),+ last_activity_us: Some(project.6),});}}diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 0558d76a..dcaff775 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -30,8 +30,8 @@ use crate::error::{StoreError, StoreResult};use crate::ops::{self, AdmittedSession, DeleteWorkspaceSummary, EmbeddingWrite, HookSessionAdmission,IdleEndCandidate, IdleEndResult, IngestObservationOutcome, LifecycleOnlyEndOutcome,- MoveSessionSummary, MoveSummary, ObservationPruneOutcome, PagesMode, PurgeSummary,- ReorgSummary,+ MergeProjectPage, MergeProjectSummary, MoveSessionSummary, MoveSummary,+ ObservationPruneOutcome, PagesMode, PurgeSummary, ReorgSummary,};use crate::session_consolidation::SessionConsolidationJob;use crate::users::{self, TOKEN_HASH_LEN};@@ -572,6 +572,16 @@ pub(crate) enum WriteCmd {to_workspace: WorkspaceId,reply: oneshot::Sender<StoreResult<MoveSummary>>,},+ /// Merge one project id into another in the same workspace. The wiki+ /// layer supplies a compare-and-write plan for every latest source page.+ MergeProject {+ workspace_id: WorkspaceId,+ source_project: ProjectId,+ target_project: ProjectId,+ pages: Vec<MergeProjectPage>,+ commit: bool,+ reply: oneshot::Sender<StoreResult<MergeProjectSummary>>,+ },/// Re-stamp one session and its dependent rows (observations, handoffs,/// consolidation jobs, auto-improve runs and claim, session page) into/// another scope in one transaction. `commit = false` rolls back after@@ -2613,6 +2623,28 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Atomically merge one project id into another in the same workspace.+ pub async fn merge_project(+ &self,+ workspace_id: WorkspaceId,+ source_project: ProjectId,+ target_project: ProjectId,+ pages: Vec<MergeProjectPage>,+ commit: bool,+ ) -> StoreResult<MergeProjectSummary> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::MergeProject {+ workspace_id,+ source_project,+ target_project,+ pages,+ commit,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Re-stamp one session, its observations, the handoffs it produced, its/// consolidation jobs, auto-improve runs and scheduler claim, and its/// `sessions/<id>.md` page (per `pages`) into@@ -4579,6 +4611,24 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {);send_or_warn(reply, result, "move_project_workspace");}+ WriteCmd::MergeProject {+ workspace_id,+ source_project,+ target_project,+ pages,+ commit,+ reply,+ } => {+ let result = ops::merge_project(+ &mut conn,+ workspace_id,+ source_project,+ target_project,+ &pages,+ commit,+ );+ send_or_warn(reply, result, "merge_project");+ }WriteCmd::MoveSession {session_id,target_workspace,diff --git a/crates/ai-memory-store/tests/suite/audit_contamination.rs b/crates/ai-memory-store/tests/suite/audit_contamination.rsindex f39e25ae..d18d843e 100644--- a/crates/ai-memory-store/tests/suite/audit_contamination.rs+++ b/crates/ai-memory-store/tests/suite/audit_contamination.rs@@ -306,6 +306,7 @@ async fn audit_flags_projects_split_by_case_or_accents() {(4, "R\u{e9}nato"), // Rénato, composed(5, "renato-2"),(6, "widget"),+ (7, "renato!"),] {conn.execute("INSERT INTO projects (id, workspace_id, name, created_at) \@@ -333,7 +334,9 @@ async fn audit_flags_projects_split_by_case_or_accents() {"accent-only split is reported: {collisions:?}");assert!(- !collisions.contains(&"renato-2") && !collisions.contains(&"widget"),+ !collisions.contains(&"renato-2")+ && !collisions.contains(&"widget")+ && !collisions.contains(&"renato!"),"a different name is not a collision: {collisions:?}");assert_eq!(@@ -355,6 +358,14 @@ async fn audit_flags_projects_split_by_case_or_accents() {);assert_eq!(one.pages, Some(0));assert_eq!(one.sessions, Some(0));+ assert_eq!(one.collision_kind, Some("case_and_accent"));+ assert_eq!(one.last_activity_us, Some(now));+ let accented = report+ .findings+ .iter()+ .find(|f| f.landed_project == "R\u{e9}nato")+ .unwrap();+ assert_eq!(accented.collision_kind, Some("accent"));}/// The fold itself: what counts as the same name, and what does not.@@ -365,6 +376,7 @@ fn project_name_fold_key_matches_spelling_not_meaning() {assert_eq!(key("R\u{e9}nato"), key("Renato"));assert_eq!(key("felipe-nr-judoka"), key("Felipe-NR-Judoka"));assert_ne!(key("renato"), key("renato2"));+ assert_ne!(key("renato"), key("renato!"));assert_ne!(key("widget"), key("gadget"));assert_eq!(key(" api "), "api");}diff --git a/crates/ai-memory-wiki/src/lib.rs b/crates/ai-memory-wiki/src/lib.rsindex 04d54c45..cfaa1c5c 100644--- a/crates/ai-memory-wiki/src/lib.rs+++ b/crates/ai-memory-wiki/src/lib.rs@@ -36,7 +36,7 @@ pub use migrations::run_pending as run_wiki_migrations;pub use okf_index::okf_directory_listing;pub use watcher::{DEBOUNCE_WINDOW, RECONCILE_INTERVAL, WatcherHandle};pub use wiki::{- ConditionalBatchWrite, ConditionalWrite, EventLedgerFile, MoveSessionOutcome,+ ConditionalBatchWrite, ConditionalWrite, EventLedgerFile, MergeProjectFile, MoveSessionOutcome,PAGE_CHECKPOINT_WALK_LIMIT, PurgeSessionOutcome, SessionPageFile, Wiki, WritePageRequest,};diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex ffef04b9..70da9e1d 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -11,9 +11,9 @@ use ai_memory_core::{use ai_memory_llm::Embedder;use ai_memory_store::{ApproveAutoImproveProposal, ApproveAutoImproveProposalResult, AutoImproveProposalDetail,- ConditionalBatchUpsert, ConditionalUpsert, FailAutoImproveProposal, MoveSessionSummary,- MoveSummary, PagePrecondition, PagesMode, PurgeSessionSummary, ReaderPool, ScopeRow,- WriterHandle, artifact_path_for, f32_vec_to_bytes,+ ConditionalBatchUpsert, ConditionalUpsert, FailAutoImproveProposal, MergeProjectPage,+ MoveSessionSummary, MoveSummary, PagePrecondition, PagesMode, PurgeSessionSummary, ReaderPool,+ ScopeRow, WriterHandle, artifact_path_for, f32_vec_to_bytes,};use tokio::sync::RwLock;@@ -47,6 +47,72 @@ pub struct EventLedgerFile {pub bytes: u64,}+/// One source page prepared for [`Wiki::merge_project`].+#[derive(Debug, Clone)]+pub struct MergeProjectFile {+ /// Store-level compare-and-write and merged-version plan.+ pub store: MergeProjectPage,+ /// Fully emitted Markdown for a same-path collision. `None` means the+ /// source file is installed unchanged at the target path.+ pub merged_markdown: Option<String>,+}++fn copy_tree(git: &GitAdapter, source: &Path, target: &Path) -> WikiResult<()> {+ if !source.exists() {+ return Ok(());+ }+ std::fs::create_dir_all(target)?;+ for entry in std::fs::read_dir(source)? {+ let entry = entry?;+ let metadata = entry.file_type()?;+ if metadata.is_symlink() {+ return Err(WikiError::Io(std::io::Error::other(format!(+ "refusing symlink while copying project tree: {}",+ entry.path().display()+ ))));+ }+ let destination = target.join(entry.file_name());+ if metadata.is_dir() {+ copy_tree(git, &entry.path(), &destination)?;+ } else if metadata.is_file() {+ git.write_atomic(&destination, &std::fs::read(entry.path())?)?;+ }+ }+ Ok(())+}++fn copy_tree_missing(git: &GitAdapter, source: &Path, target: &Path) -> WikiResult<()> {+ if !source.exists() {+ return Ok(());+ }+ std::fs::create_dir_all(target)?;+ for entry in std::fs::read_dir(source)? {+ let entry = entry?;+ let metadata = entry.file_type()?;+ if metadata.is_symlink() {+ return Err(WikiError::Io(std::io::Error::other(format!(+ "refusing symlink while merging project tree: {}",+ entry.path().display()+ ))));+ }+ let destination = target.join(entry.file_name());+ if metadata.is_dir() {+ copy_tree_missing(git, &entry.path(), &destination)?;+ } else if metadata.is_file() && !destination.exists() {+ git.write_atomic(&destination, &std::fs::read(entry.path())?)?;+ } else if metadata.is_file()+ && entry+ .file_name()+ .to_str()+ .is_some_and(|name| name.starts_with("log-") && name.ends_with(".md"))+ {+ let bytes = std::fs::read(entry.path())?;+ git.append(&destination, &bytes)?;+ }+ }+ Ok(())+}+fn event_ledger_metadata(abs: &Path) -> WikiResult<Option<std::fs::Metadata>> {let metadata = match std::fs::symlink_metadata(abs) {Ok(metadata) => metadata,@@ -580,6 +646,182 @@ impl Wiki {}}+ /// Merge a source project tree into a target project in the same+ /// workspace while [`WriterHandle::merge_project`] atomically re-homes the+ /// indexed history. The target tree is snapshotted before files change and+ /// restored if the writer refuses, so disk never remains ahead of SQLite.+ ///+ /// # Errors+ /// Returns [`WikiError`] for an unsafe tree, I/O failure, admission+ /// rejection, or store precondition failure.+ pub async fn merge_project(+ &self,+ workspace_id: WorkspaceId,+ source_project: ProjectId,+ target_project: ProjectId,+ pages: Vec<MergeProjectFile>,+ admission_ctx: Option<AdmissionContext>,+ ) -> WikiResult<ai_memory_store::MergeProjectSummary> {+ self.inspect_project_tree(workspace_id, source_project)?;+ self.inspect_project_tree(workspace_id, target_project)?;+ let _guard = self.mutation_lock.write().await;+ self.inspect_project_tree(workspace_id, source_project)?;+ self.inspect_project_tree(workspace_id, target_project)?;+ let resolved_ctx = if let Some(chain) = &self.admission_chain {+ let mut ctx = admission_ctx.unwrap_or_default();+ ctx.op = AdmissionOp::MoveProject;+ self.resolve_admission_names(workspace_id, source_project, &mut ctx)+ .await;+ chain.notify(None, &ctx).await?;+ Some(ctx)+ } else {+ None+ };++ let source = self.confined_project_root(workspace_id, source_project, Prepare::Inspect)?;+ let target = self.confined_project_root(workspace_id, target_project, Prepare::Parents)?;+ let backup = target.with_file_name(format!(+ ".ai-memory-tmp.merge-{}-{}",+ target_project,+ PageId::new()+ ));+ let parked_source = source.with_file_name(format!(+ ".ai-memory-tmp.merge-source-{}-{}",+ source_project,+ PageId::new()+ ));+ if backup.exists() {+ return Err(WikiError::DestinationExists(backup.display().to_string()));+ }+ if parked_source.exists() {+ return Err(WikiError::DestinationExists(+ parked_source.display().to_string(),+ ));+ }+ if target.exists()+ && let Err(error) = copy_tree(&self.git, &target, &backup)+ {+ if backup.exists()+ && let Err(cleanup) = self.git.remove_dir_all(&backup)+ {+ tracing::warn!(+ %cleanup,+ path = %backup.display(),+ "merge-project target snapshot failed and partial backup cleanup failed"+ );+ }+ return Err(error);+ }+ if source.exists()+ && let Err(error) = self.git.rename(&source, &parked_source)+ {+ if backup.exists()+ && let Err(cleanup) = self.git.remove_dir_all(&backup)+ {+ tracing::warn!(+ %cleanup,+ path = %backup.display(),+ "merge-project source park failed and target backup cleanup failed"+ );+ }+ return Err(error.into());+ }++ let result = async {+ // Preserve non-page project artifacts too. Existing target files+ // win here; the explicit page plan below then installs every+ // source page or combined collision deterministically.+ if parked_source.exists() {+ copy_tree_missing(&self.git, &parked_source, &target)?;+ }+ for page in &pages {+ let destination = self.confined_page_path(+ workspace_id,+ target_project,+ &page.store.path,+ Prepare::Parents,+ )?;+ if let Some(rendered) = &page.merged_markdown {+ self.git.write_atomic(&destination, rendered.as_bytes())?;+ } else {+ let source_path = parked_source.join(page.store.path.as_str());+ let bytes = std::fs::read(source_path)?;+ self.git.write_atomic(&destination, &bytes)?;+ }+ }+ self.writer+ .merge_project(+ workspace_id,+ source_project,+ target_project,+ pages.iter().map(|page| page.store.clone()).collect(),+ true,+ )+ .await+ .map_err(WikiError::Store)+ }+ .await;++ match result {+ Ok(summary) => {+ if parked_source.exists()+ && let Err(error) = self.git.remove_dir_all(&parked_source)+ {+ tracing::warn!(+ %error,+ path = %parked_source.display(),+ "merge-project committed but watcher-ignored source cleanup failed"+ );+ }+ if backup.exists()+ && let Err(error) = self.git.remove_dir_all(&backup)+ {+ tracing::warn!(+ %error,+ path = %backup.display(),+ "merge-project committed but watcher-ignored target backup cleanup failed"+ );+ }+ if let (Some(chain), Some(ctx)) = (&self.admission_chain, &resolved_ctx) {+ chain.dispatch_async(None, &serde_json::Value::Null, "", ctx);+ }+ Ok(summary)+ }+ Err(error) => {+ let mut rollback_errors = Vec::new();+ if parked_source.exists()+ && let Err(rollback) = self.git.rename(&parked_source, &source)+ {+ rollback_errors+ .push(format!("restore source {}: {rollback}", source.display()));+ }+ if target.exists()+ && let Err(rollback) = self.git.remove_dir_all(&target)+ {+ rollback_errors.push(format!(+ "remove staged target {}: {rollback}",+ target.display()+ ));+ }+ if backup.exists()+ && !target.exists()+ && let Err(rollback) = self.git.rename(&backup, &target)+ {+ rollback_errors+ .push(format!("restore target {}: {rollback}", target.display()));+ }+ if rollback_errors.is_empty() {+ Err(error)+ } else {+ Err(WikiError::Io(std::io::Error::other(format!(+ "INCONSISTENT STATE: merge-project failed ({error}) and rollback was incomplete: {}",+ rollback_errors.join("; ")+ ))))+ }+ }+ }+ }+/// 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`]).@@ -833,6 +1075,65 @@ impl Wiki {parse(&raw)}+ /// Build one compare-and-write file plan for a same-workspace project+ /// merge from the Markdown source of truth.+ pub fn prepare_project_merge_file(+ &self,+ workspace_id: WorkspaceId,+ source_project: ProjectId,+ target_project: ProjectId,+ mut store: MergeProjectPage,+ source_label: &str,+ ) -> WikiResult<MergeProjectFile> {+ if store.target_page_id.is_none() {+ return Ok(MergeProjectFile {+ store,+ merged_markdown: None,+ });+ }+ let path = &store.path;+ let source = self.read_page(workspace_id, source_project, path)?;+ let target = self.read_page(workspace_id, target_project, path)?;+ let mut frontmatter = target.frontmatter;+ if (source.frontmatter.get("expires_at").is_none()+ || frontmatter.get("expires_at").is_none())+ && let Some(object) = frontmatter.as_object_mut()+ {+ object.remove("expires_at");+ object.remove("stale_after");+ }+ let body = format!(+ "{}\n\n<!-- ai-memory:merged-from {source_label} -->\n\n{}",+ target.body, source.body+ );+ let metadata = derive_index_metadata(path, &frontmatter)?;+ let title = derive_title(&frontmatter, &body, path);+ let markdown = Markdown {+ frontmatter: frontmatter.clone(),+ body: body.clone(),+ };+ let merged_page = NewPage {+ workspace_id,+ project_id: target_project,+ path: path.clone(),+ title,+ body,+ tier: metadata.tier,+ frontmatter_json: frontmatter,+ pinned: metadata.pinned,+ links: crate::markdown::extract_all_links(&markdown.frontmatter, &markdown.body, path),+ author_id: None,+ expires_at: metadata.expires_at,+ entities: metadata.entities,+ evidence: Vec::new(),+ };+ store.merged_page = Some(merged_page);+ Ok(MergeProjectFile {+ store,+ merged_markdown: Some(emit(&markdown)?),+ })+ }+/// Whether the calling agent wrote `sessions/<session_id>.md` itself,/// through `memory_write_page` with that session's id: the page carries/// `consolidated_by: agent`. The automatic session-page writers leave such@@ -974,7 +1275,64 @@ impl Wiki {path.as_str())))})?;- let mut md = parse(&raw)?;+ let md = parse(&raw)?;+ self.restore_page_markdown(workspace_id, project_id, path, md, true)+ .await+ }++ /// Restore one retained SQLite page version as the new latest version.+ /// This complements checkpoint restore for histories that moved from+ /// another project path during `merge-project`.+ pub async fn restore_page_from_version(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ path: PagePath,+ version_id: PageId,+ ) -> WikiResult<PageId> {+ let reader = self+ .store_reader+ .as_ref()+ .ok_or_else(|| ai_memory_wiki_error("page-version restore requires a store reader"))?;+ let version = reader+ .page_version_body(+ workspace_id,+ project_id,+ path.as_str().to_owned(),+ version_id,+ )+ .await?+ .ok_or_else(|| {+ WikiError::Store(ai_memory_store::StoreError::NotFound(+ "page version not found in the requested scope".into(),+ ))+ })?;+ let tier = version+ .tier+ .parse::<Tier>()+ .map_err(|error| ai_memory_wiki_error(&error.to_string()))?;+ let frontmatter = canonicalize_index_frontmatter(version.frontmatter, tier, version.pinned);+ self.restore_page_markdown(+ workspace_id,+ project_id,+ path,+ Markdown {+ frontmatter,+ body: version.body,+ },+ true,+ )+ .await+ }++ async fn restore_page_markdown(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ path: PagePath,+ mut md: Markdown,+ keep_own_generated_at: bool,+ ) -> WikiResult<PageId> {// Conform like the three sibling write paths (`write_page_inner`,// `apply_batch`, `approve_auto_improve_proposal`) do: the row this// upserts is conformed at the store's write choke point either way,@@ -994,7 +1352,7 @@ impl Wiki {&self.abs_path(workspace_id, project_id, &path),path.as_str(),&mut md,- true,+ keep_own_generated_at,);let raw = emit(&md)?;let title = derive_title(&md.frontmatter, &md.body, &path);diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex fea1c93f..d6c19ce4 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -966,14 +966,14 @@ recover pending-writes embedgenerate-auth-token setup-agent bootstrapinstall-instructions install-skills reorgpurge-project rename-project move-project-move-session uninstall upgrade-auth user completions-handoffs purge-session compact-api-key export-okf message-doctor backfill project-reclaim-ledger-versions repair-backfill-timestamps-server backup-agents restore-agents-profile setup+merge-project move-session uninstall+upgrade auth user+completions handoffs purge-session+compact api-key export-okf+message doctor backfill+project reclaim-ledger-versions+repair-backfill-timestamps server backup-agents+restore-agents profile setup```Run `ai-memory --help` for the full tree.diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 4726053d..f9c7677b 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -15,13 +15,14 @@ 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, **plus** any observation stamped into a different workspace by one of this workspace's sessions (cascades regardless of the observation's own `workspace_id`), and it nulls (does not delete) the session reference on any handoff in a different workspace that this workspace's sessions authored or accepted | 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. Logical delete by default; `"compact": true` additionally rebuilds the FTS indexes and `VACUUM`s (see below). `"dry_run": true` previews the same counts, including the cross-workspace ones, without deleting anything (see below). || `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. An existing same-named destination project makes this a **copy+purge merge**, which deletes the source's sessions, observations, handoffs and older page versions: it now needs `--allow-lossy-merge` as well, and without it the server answers `409` naming the counts it would discard (#1713). |+| `merge-project [--confirm]` | ✅ yes | no | no | Same-workspace, lossless identity repair. The default is a writer-transaction dry run. `--confirm` re-stamps every history-bearing row and removes the source only after the target files are installed; open sessions and live managed runs refuse. Same-path bodies are appended into a new stale-flagged target version while both histories remain reachable. || `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, profile prompt candidates, ingest keys 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`. || `repair-backfill-timestamps --project --confirm` | ✅ yes | no | yes, if the operator kept the audit row or the CLI's before/after report (nothing else) | Corrects `sessions.started_at`/`ended_at` for sessions an older `backfill` imported before it carried the transcript's own event time. The CLI reads the operator's local transcripts read-only and posts candidate `(session_id, started_at, ended_at)` tuples to `POST /admin/repair-session-times`, which validates each one against `(workspace, project)` (a candidate outside that scope is `not_found` and untouched), only rewrites a row whose `started_at` postdates the candidate's own end (`not_flattened` otherwise, so a correctly hook-captured session or a re-run is a no-op), refuses negative/inverted/future-dated times, and never assigns an end time to a session still open. Without `--confirm` the server validates and reports inside a rolled-back transaction, so it is a real dry run; a confirmed run writes one `audit_log` row per request with the before/after times. Touches only the two timestamp columns of rows already in scope; `observations` and pages (including the session's own page frontmatter) are untouched. || `backup --to` | ✅ yes | no | n/a | Streams a gzipped tarball from the server's online `sqlite3 .backup` plus the wiki tree. Safe alongside the live writer. || `forget-sweep` event-ledger pass (`[decay] ledger_retention_months`) | ✅ yes | old hook event ledger *files* (`log-YYYY-MM.md`) from disk, nothing in the database | no ai-memory command restores a ledger (`restore-page` restores pages only); the content stays in the wiki's git history when a checkpoint captured it, recoverable with plain git until the repository is compacted | **Off by default** (`0`). Runs inside the forget sweep, so `--dry-run` previews it: the report lists `ledgers_prunable` and `ledger_bytes_prunable`. Online through the admin API. Only a file whose name is `log-YYYY-MM.md` **and** whose content opens with a ledger hook entry qualifies; `log.md`, the current month and the previous month are never deleted, whatever the setting. Each removal consults the blocking admission chain (`delete_event_ledger` op); a `reject`-policy webhook keeps the file and the report counts it in `ledgers_undeleted`. || `reclaim-ledger-versions` | ✅ yes | superseded pre-#660 ledger page *versions* only | no (the latest page version stays) | Dry-run by default; needs `--confirm` to delete. Online through the writer actor, safe alongside the live writer. Content-gated: only non-latest, non-decay `log.md`/`log-YYYY-MM.md` versions whose body opens with a ledger hook entry are removed; a real page that merely shares the name is untouched. `--compact` additionally rebuilds FTS and `VACUUM`s to reclaim the freed bytes. || `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. |+| `restore-page --path (--from REV \| --page-id UUID)` | ✅ yes | overwrites one markdown page version | yes (restore another retained version) | Restores one page from wiki git history or a retained SQLite page version, reindexes it, and writes a post-restore checkpoint. `--page-id` reaches source history preserved by `merge-project`; it does not restore other DB state. || MCP `memory_restore_page` | ✅ yes | no (writes a new current version; the replaced one stays reachable) | yes (restore another checkpoint) | Lists a page's checkpoints, or writes one back through the `memory_write_page` path. Admin only, like `restore-page`. See [below](#mcp-memory_restore_page). || `backup-agents --to` / `restore-agents --from <tarball>` | ✅ yes (client-side; never touches the server or its data dir) | no | yes (`restore-agents --apply` keeps timestamped copies of overwritten files) | Agent-config assets, not wiki/db: MCP configs (redacted unless `--include-secrets`), hook configs, instructions, skills, plugins. `restore-agents` is a dry run by default; `--apply` writes to disk and `--force` overwrites existing or differing targets. Non-MCP assets are restored verbatim and may contain secrets, so only `--apply` an archive whose source you trust. || `restore --from <tarball>` | ❌ **stop the server first** | overwrites the data dir | no (without prior backup) | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). Stages and verifies the archive before swapping it in, so a failed restore leaves `wiki/` and `db/` as they were. Keeps an existing `config.toml` and saves the backup's as `config.toml.from-backup` unless `--with-config` is passed. |@@ -420,7 +421,7 @@ Failure modes:- **Manifest refresh/checkpoint failed after commit** → 200 with`manifest_warning`; the SQL rename remains committed and startup manifestbackfill can repair the disk metadata. The bootstrap, write-page,- move-project merge, move-session create, and managed-run responses surface+ move-project merge, `merge-project`, move-session create, and managed-run responses surfacethe same warning shape when their scope resolution performed the promotion.The warning is retained if the promoted operation later fails: MCP puts it at`error.data.manifest_warning`, while HTTP admin/managed-run errors keep the@@ -513,6 +514,43 @@ regard for the message's own `to_workspace_id`), and `from_session_id`/when they reference a session that lived in the deleted workspace (`ON DELETESET NULL`).+### `merge-project`++Use this only when two project rows in one workspace are the same logical+working copy, often after `audit-contamination` reports a case/accent spelling+collision:++```bash+# Exact dry run: no files or rows change.+ai-memory merge-project --workspace default --from Renato --into renato++# Apply after inspecting the counts.+ai-memory merge-project --workspace default --from Renato --into renato --confirm+```++The command is root-only on a multi-user server, like every `/admin/*`+operation. Names may be replaced independently with `--from-project-id` and+`--into-project-id`; each id is resolved inside `--workspace`, so an id from+another workspace returns 404 and reaches no mutation.++The writer verifies both latest-page sets under the transaction. It refuses if+the source has an open session or an unexpired active managed-run lease. A+same-path collision produces a new version whose body is the target body, a+`<!-- ai-memory:merged-from workspace/source -->` marker, and the source body.+The target frontmatter wins; `expires_at`/`stale_after` survive only when both+sides were expiring. The new page keeps the earlier creation time and receives+`stale` feedback naming the source, so `memory_lint` continues to report it+until a person or agent reconciles the combined prose. Every prior target and+source version remains under the target path and is available to history and+restore tooling.++SQLite commits the page histories, sessions, observations, handoffs,+embeddings, workstreams and auxiliary project indexes in one writer+transaction. The wiki mutation lock snapshots the target tree before installing+the merged files and restores it if the transaction refuses; after a commit it+removes the now-empty source tree, refreshes scope manifests and checkpoints+the result.+### `move-project````bash@@ -1015,6 +1053,10 @@ Fresh empty installs still have no commit until there is content to save.```bashai-memory restore-page --workspace default --project my-project \--path notes/foo.md --from <checkpoint>++# Restore a retained page version after merge-project moved its history+ai-memory restore-page --workspace default --project canonical \+ --path notes/foo.md --page-id <page-version-uuid>```Each omitted scope flag is resolved from the current directory; a non-empty@@ -1028,9 +1070,11 @@ What happens:2. Server validates the page path.3. Server checkpoints the current wiki tree first (`pre-restore-page ...`) whenthere are uncommitted changes.-4. Server reads the exact markdown blob for that project/page from git at- `--from`, parses it, writes it back to the live wiki tree, and upserts a new- latest page row in SQLite so search, links, and `/web` agree with disk.+4. Server reads either the exact markdown blob for that project/page from git+ at `--from`, or the retained SQLite version identified by `--page-id` after+ verifying that it now belongs to the requested project and path. It writes+ that content to the live wiki tree and upserts a new latest page row so+ search, links, and `/web` agree with disk.5. Server writes a post-restore checkpoint (`restore-page ...`) when the livetree changed.@@ -1040,6 +1084,8 @@ Failure modes:- **Invalid page path** → 422, no mutation.- **Checkpoint or file not found** → 500 with the git/libgit2 error; anypre-restore checkpoint remains as an audit breadcrumb.+- **Page-version UUID is malformed** → 400 before a checkpoint or mutation.+- **Page version is absent or belongs to another project/path** → 404.- **Historical markdown is malformed or non-UTF-8** → 500, live file is notreplaced.diff --git a/docs/programmatic-memory.md b/docs/programmatic-memory.mdindex 4af3324a..fe992af1 100644--- a/docs/programmatic-memory.md+++ b/docs/programmatic-memory.md@@ -150,7 +150,7 @@ any caller the server's auth lets in.| Operation | Call | Notes ||---|---|---|| Delete a page (there is no separate archive) | MCP `memory_delete_page` with `path` (plus `workspace` and `project`) | Checkpoints the wiki in git first, then removes the file and every indexed version of the page. Returns `{path, deleted, pre_checkpoint, checkpoint}`. Idempotent. |-| Restore a deleted or overwritten page | `POST /admin/restore-page` with `{workspace, project, path, rev}` | `rev` is any git revision that still holds the page: the delete's `pre_checkpoint`, or `<checkpoint>~1` when `pre_checkpoint` is `null` because the tree was already clean. Writes that version back as the latest page and reindexes it. After a delete, only that one version returns. |+| Restore a deleted or overwritten page | `POST /admin/restore-page` with `{workspace, project, path, rev}` or `{workspace, project, path, page_id}` | `rev` is any git revision that still holds the page: the delete's `pre_checkpoint`, or `<checkpoint>~1` when `pre_checkpoint` is `null` because the tree was already clean. `page_id` selects a retained SQLite version already belonging to that exact project/path, including source history preserved by `merge-project`. Exactly one source is required. Writes that version back as the latest page and reindexes it. || Find a revision | `GET /admin/checkpoints?limit=N` | Recent checkpoints (up to 100) with `oid` and `summary`. A delete's summary is `memory_delete_page: <path>`. || Purge one session | `POST /admin/purge-session` with `{workspace, project, session_id, confirm}` | Irreversible. Optional `dry_run` and `compact`. || Purge a whole project | `POST /admin/purge-project` with `{workspace, project, confirm}` | Irreversible. Optional `dry_run`, `compact`, and `force` (purge despite a live managed-workstream lease). |diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 4559b51c..1a4ca8db 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -92,8 +92,9 @@ the legitimate restricted-project control and the failed-query cases.| 8d | Messaging: an inferred scope never changes a queue; a read names it (#854) | `scope.rs` `ScopeSource::is_inferred`; `ai-memory-mcp/src/server.rs` `refuse_inferred_message_scope`, called by `memory_message_pop` and `memory_message_cancel` (mailbox scope) and `memory_message_send` (sender scope) before admission or any writer call, so a `shared_slot`/`startup_seed`/`default`/`default_after_mismatch` scope is refused with nothing claimed, cancelled, or delivered; `inferred_scope_hint` on every inferred `memory_message_list` (inbox and outbox, empty or not); the SessionStart notice (`ai-memory-hooks/src/router.rs` `render_inbox_notice`) and `memory_briefing` `scope` name the inbox from server-side names only | `agent_messages_scope.rs` `unscoped_pop_from_the_shared_slot_is_refused_and_claims_nothing`, `unscoped_cancel_from_the_shared_slot_is_refused_and_the_outbox_survives`, `unscoped_send_from_the_shared_slot_is_refused_and_explicit_sender_is_stamped` (each with the shared slot on another project; session-bound and explicit callers as controls; each fails with the guard removed), `unscoped_list_names_the_mailbox_it_read_even_when_not_empty`; `agent_messages_briefing.rs` `no_scope_pop_is_refused_and_the_briefing_names_the_inbox_to_pop`, `no_scope_inbox_list_that_misses_the_mail_names_the_inferred_scope`; router `session_start_notice_surfaces_pending_mail_without_consuming_it` (names the inbox, carries no message text) | STRONG || 8e | Messaging: admission is the same for MCP and admin sends (#756) | `ai-memory-mcp/src/admin.rs` `handle_send_message` runs `Wiki::authorize_operation(.., AdmissionOp::MessageSend, ..)` at the recipient scope before `insert_message` (a refusal is 403 and stores nothing) and calls `notify_operation_observers` only after a successful commit; skipping webhooks needs `Capability::SkipAdmissionChain` (`skip_webhooks_for_admin_request`); the MCP path is `server.rs` `memory_message_send` | `admin.rs` `admin_message_send_reject_leaves_inbox_empty` (a rejecting webhook gets 403 and an empty inbox; fails with the admission call removed), controls `admin_message_send_observer_sees_commit_without_blocking_response` and `admin_message_send_full_inbox_does_not_notify_observer` | STRONG || 8f | Messaging: the web mailbox shows a restricted sender's name and a card's count only to a reader of that repository; it never consumes mail | `ai-memory-store/src/reader.rs` `list_inbox_with_senders` (`readable_repository_predicate("sp.id", viewer)` on the sender join, so the name is `NULL` for an unreadable sender) and `pending_inbox_counts` (`readable_repository_predicate("p.id", viewer)`); `ai-memory-web/src/routes/project.rs` `mailbox` is `list`-only, no pop/cancel route exists, and `mailbox_scope` matches the URL's exact project name (as `list_pages` does), so an alias never shows another project's mail | `routes.rs` `web_mailbox_hides_restricted_sender_names_and_cards` (a granted reader of the recipient is shown "a project you cannot read", the restricted sender's name and card never reach the grid, alice as the control; fails with either predicate removed), `web_mailbox_lists_only_this_projects_inbox_and_never_consumes_it` (sender and bystander pages show nothing of the recipient's mail, a POST is 405 and the message is still pending, the body is HTML-escaped), `web_mailbox_does_not_follow_a_project_alias` (a legacy key that resolves to `acme-api` shows none of its mail on `/w/default/api`; `acme-api` itself is the control) | STRONG |-| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; identity-aware lookup accepts exact/canonical/v2-basename keys only when they deduplicate to one UUID; `ops.rs` `resolve_project_name_for_write` performs write authorization, optional name-only promotion, and audit in one writer transaction; create only via `create_explicit_scope`; `ops.rs` `get_or_create_project_as` — the capture and managed-run creator path — consults the same coordinate lookup before inserting, so a name a promoted project still answers to (its `legacy_name` or `canonical_name`) reuses that row, an ambiguous name is refused, and no twin is minted under a key the read path already resolves (the lookup is skipped only while the schema predates V76, via `project_coordinates::supports_coordinates`). The admin destructive project routes (`admin.rs` `resolve_target_for_admin`, used by `purge-project` / `rename-project` / `move-project`) accept a bare `project_id` as an alternative to the name: it is parsed to a UUID (400 on a malformed one), looked up **within the workspace the request named** via `ReaderPool::project_name_by_id` (404 when it names no row there, so a real id from another workspace is refused rather than resolved), and the two spellings are mutually exclusive (both or neither is a 400). `list-projects` carries the id in each row, and inherits the same row-level visibility filter as the name, so a restricted project leaks neither. `ProjectNameAmbiguous` refuses cross-forge/multi-candidate keys before mutation; its message names each holder and the key it matched by, but a restricted holder only as "a restricted project", because the lookup runs before any caller is authorized and the project list hides restricted names from callers without a grant; an audit failure after the name UPDATE rolls the transaction back. V76's derived-key indexes bound hot lookup to exact/canonical/legacy equality probes with at most four rows. Promoting public APIs return `ResolvedWriteScope` metadata (no untraced promotion API); MCP, admin, and managed-workstream write entry points make Wiki refresh/checkpoint the committed scope manifest after promotion and surface `manifest_warning` on success or any later operation failure; pure managed-run input validation precedes promotion. A managed run whose `project` is the name its checkout's git remote derives (`PrepareManagedRunRequest.repository_identity`, accepted only through `accept_wire_identity` and only when `path_style_name` equals the requested name) resolves through `resolve_project_by_identity_for_capture` — the identity holder, else the cwd-prefix project with `$HOME` excluded, claimed or renamed only for a writer — and then `authorize_scope_for(Write)` on the writer connection, so an identity can neither redirect a differently named run nor open, claim, or create a project the caller may not write; Project manifests persist the typed full identity/source and derived keys so clean reindex restores the same UUID and lookup behavior. Also `ai-memory-hooks/src/router.rs` `workspace_override_is_rescope` — the hook router's session-sticky gate resolves a marker's `workspace` override via this same no-create `lookup_existing_workspace` (never a hand-rolled lookup) and fails closed (treats it as a rescope, disqualifying sticky) on a different or unresolvable workspace; only an override that resolves to the session's OWN workspace is not a rescope (#976) | `scope.rs` `read_resolution_table_driven`, `multi_scope_resolution_deduplicates_and_validates`, `identity_resolution.rs` `a_capture_naming_a_promoted_projects_legacy_key_reuses_it` (a capture naming the promoted project's legacy key lands in it, creates nothing and leaves the name resolvable), `a_capture_of_an_existing_exact_name_still_lands_there`, `a_capture_of_a_new_name_still_creates_its_project` (controls: the fallback runs only after the exact-name miss and still records the creator), hooks `two_api_checkouts_with_different_remotes_get_two_projects` (an identity-less capture under a key two projects claim refuses and creates nothing; a fresh folder-named capture still creates its project as the control), `a_slashed_label_reaches_only_a_project_the_caller_may_use` (a `workspace/project` label passed as the project is authorized as the pair it names and creates nothing when refused; granted control), `a_slashed_write_resolves_its_own_pair_and_never_creates`, `an_existing_slashed_project_wins_over_the_split`, no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `dual_key_scope.rs` `page_write_failure_after_promotion_preserves_manifest_warning`, `handoff_failure_after_promotion_preserves_manifest_warning`; `workstream.rs` `managed_run_rejects_mutually_exclusive_selection_before_promotion`, `managed_run_downstream_failure_after_promotion_preserves_manifest_warning`; `identity_resolution.rs` `canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming`, `authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_lookup`, `read_only_user_cannot_promote_a_legacy_name`, `canonical_target_conflict_rolls_back_the_promotion`, `audit_failure_rolls_back_promotion_and_keeps_the_writer_alive`, `exact_name_that_is_another_forges_canonical_key_fails_closed`, `an_ambiguous_name_names_its_holders_but_not_a_restricted_one` (restricted holder unnamed; open holder named as the control), `concurrent_legacy_and_canonical_resolve_or_create_converge_on_one_uuid`; admin `admin_purge.rs` `purge_project_refuses_a_real_id_from_another_workspace` (a row that really exists in another workspace answers 404 from `default` and is left intact), admin_rename/admin_move `rename_project_refuses_a_real_id_from_another_workspace` / `move_project_refuses_a_real_id_from_another_workspace` (the same for rename and move, the foreign project keeps its name and workspace, with the same id accepted from its own workspace as the control), `purge_project_still_refuses_an_ambiguous_name_by_default` (a name held by two rows -- one via its `legacy_name` -- stays a 400 and purges nothing), `purge_project_by_id_reaches_the_twin_and_leaves_the_name_holder_intact` (legitimate control: the id reaches the row the name could not, and the name-holder survives with its name), and store `list_projects_with_stats_hides_a_restricted_projects_id_from_an_ungranted_viewer` (the id is absent exactly where the name is, for an ungranted viewer, and present for the operator -- bite-checked with the visibility filter removed); `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; wiki `promoted_identity_round_trips_through_manifest_and_clean_reindex`, `old_project_manifest_without_identity_still_reindexes`, `reindex_rejects_project_coordinate_fields_that_do_not_match_identity`; admin `write_page_surfaces_manifest_failure_after_promotion`, `bootstrap_surfaces_manifest_failure_after_promotion`, `move_project_merge_surfaces_destination_promotion_manifest_warning`, `move_session_create_surfaces_destination_promotion_manifest_warning`; `multi_session.rs` `two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_pointers`; MCP `dual_key_scope.rs`; hooks `workstream.rs` `managed_run_by_remote_identity_claims_the_folder_named_project`, `managed_run_by_remote_identity_routes_past_an_identityless_twin` (name-only control is ambiguous), `managed_run_identity_never_redirects_another_project_name`, `managed_run_by_remote_identity_refuses_a_viewer_without_write` (outsider refused with no project created; granted member admitted as the control), `managed_run_identity_never_claims_a_restricted_legacy_project` (an outsider whose cwd sits in a restricted identity-less project is refused, the identity stays unrecorded and no twin appears; fails with either the writer's claim check or the route's write check removed; a granted member claims it as the control), `managed_run_identity_routing_stays_inside_the_requested_workspace`, `concurrent_identity_runs_on_a_legacy_project_converge_on_it` (invariant #16), `managed_run_promotion_refreshes_the_scope_manifest`, `managed_run_discloses_manifest_failure_after_committed_promotion` static read/write/authz/cross-workspace/cross-forge cases; `router.rs` `workspace_override_is_rescope_only_on_a_genuine_workspace_change` (same/different/unresolvable workspace cases), `sticky_routing_keeps_the_session_project_across_a_sibling_checkout` (regression: same workspace forwarded on every event + `project_src=repo-root` from a nested checkout stays sticky), `sticky_routing_still_rescopes_when_marker_names_a_different_workspace_mid_session` (opposite direction: a genuinely different workspace still rescopes even under `sticky`) | STRONG |+| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; identity-aware lookup accepts exact/canonical/v2-basename keys only when they deduplicate to one UUID; `ops.rs` `resolve_project_name_for_write` performs write authorization, optional name-only promotion, and audit in one writer transaction; create only via `create_explicit_scope`; `ops.rs` `get_or_create_project_as` — the capture and managed-run creator path — consults the same coordinate lookup before inserting, so a name a promoted project still answers to (its `legacy_name` or `canonical_name`) reuses that row, an ambiguous name is refused, and no twin is minted under a key the read path already resolves (the lookup is skipped only while the schema predates V76, via `project_coordinates::supports_coordinates`). The admin destructive project routes (`admin.rs` `resolve_target_for_admin`, used by `purge-project` / `rename-project` / `move-project` / `merge-project`) accept a bare `project_id` as an alternative to the name: it is parsed to a UUID (400 on a malformed one), looked up **within the workspace the request named** via `ReaderPool::project_name_by_id` (404 when it names no row there, so a real id from another workspace is refused rather than resolved), and the two spellings are mutually exclusive (both or neither is a 400). `list-projects` carries the id in each row, and inherits the same row-level visibility filter as the name, so a restricted project leaks neither. `ProjectNameAmbiguous` refuses cross-forge/multi-candidate keys before mutation; its message names each holder and the key it matched by, but a restricted holder only as "a restricted project", because the lookup runs before any caller is authorized and the project list hides restricted names from callers without a grant; an audit failure after the name UPDATE rolls the transaction back. V76's derived-key indexes bound hot lookup to exact/canonical/legacy equality probes with at most four rows. Promoting public APIs return `ResolvedWriteScope` metadata (no untraced promotion API); MCP, admin, and managed-workstream write entry points make Wiki refresh/checkpoint the committed scope manifest after promotion and surface `manifest_warning` on success or any later operation failure; pure managed-run input validation precedes promotion. A managed run whose `project` is the name its checkout's git remote derives (`PrepareManagedRunRequest.repository_identity`, accepted only through `accept_wire_identity` and only when `path_style_name` equals the requested name) resolves through `resolve_project_by_identity_for_capture` — the identity holder, else the cwd-prefix project with `$HOME` excluded, claimed or renamed only for a writer — and then `authorize_scope_for(Write)` on the writer connection, so an identity can neither redirect a differently named run nor open, claim, or create a project the caller may not write; Project manifests persist the typed full identity/source and derived keys so clean reindex restores the same UUID and lookup behavior. Also `ai-memory-hooks/src/router.rs` `workspace_override_is_rescope` — the hook router's session-sticky gate resolves a marker's `workspace` override via this same no-create `lookup_existing_workspace` (never a hand-rolled lookup) and fails closed (treats it as a rescope, disqualifying sticky) on a different or unresolvable workspace; only an override that resolves to the session's OWN workspace is not a rescope (#976) | `scope.rs` `read_resolution_table_driven`, `multi_scope_resolution_deduplicates_and_validates`, `identity_resolution.rs` `a_capture_naming_a_promoted_projects_legacy_key_reuses_it` (a capture naming the promoted project's legacy key lands in it, creates nothing and leaves the name resolvable), `a_capture_of_an_existing_exact_name_still_lands_there`, `a_capture_of_a_new_name_still_creates_its_project` (controls: the fallback runs only after the exact-name miss and still records the creator), hooks `two_api_checkouts_with_different_remotes_get_two_projects` (an identity-less capture under a key two projects claim refuses and creates nothing; a fresh folder-named capture still creates its project as the control), `a_slashed_label_reaches_only_a_project_the_caller_may_use` (a `workspace/project` label passed as the project is authorized as the pair it names and creates nothing when refused; granted control), `a_slashed_write_resolves_its_own_pair_and_never_creates`, `an_existing_slashed_project_wins_over_the_split`, no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `dual_key_scope.rs` `page_write_failure_after_promotion_preserves_manifest_warning`, `handoff_failure_after_promotion_preserves_manifest_warning`; `workstream.rs` `managed_run_rejects_mutually_exclusive_selection_before_promotion`, `managed_run_downstream_failure_after_promotion_preserves_manifest_warning`; `identity_resolution.rs` `canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming`, `authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_lookup`, `read_only_user_cannot_promote_a_legacy_name`, `canonical_target_conflict_rolls_back_the_promotion`, `audit_failure_rolls_back_promotion_and_keeps_the_writer_alive`, `exact_name_that_is_another_forges_canonical_key_fails_closed`, `an_ambiguous_name_names_its_holders_but_not_a_restricted_one` (restricted holder unnamed; open holder named as the control), `concurrent_legacy_and_canonical_resolve_or_create_converge_on_one_uuid`; admin `admin_purge.rs` `purge_project_refuses_a_real_id_from_another_workspace` (a row that really exists in another workspace answers 404 from `default` and is left intact), admin_rename/admin_move `rename_project_refuses_a_real_id_from_another_workspace` / `move_project_refuses_a_real_id_from_another_workspace` (the same for rename and move, the foreign project keeps its name and workspace, with the same id accepted from its own workspace as the control), `purge_project_still_refuses_an_ambiguous_name_by_default` (a name held by two rows -- one via its `legacy_name` -- stays a 400 and purges nothing), `purge_project_by_id_reaches_the_twin_and_leaves_the_name_holder_intact` (legitimate control: the id reaches the row the name could not, and the name-holder survives with its name), and store `list_projects_with_stats_hides_a_restricted_projects_id_from_an_ungranted_viewer` (the id is absent exactly where the name is, for an ungranted viewer, and present for the operator -- bite-checked with the visibility filter removed); `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; wiki `promoted_identity_round_trips_through_manifest_and_clean_reindex`, `old_project_manifest_without_identity_still_reindexes`, `reindex_rejects_project_coordinate_fields_that_do_not_match_identity`; admin `write_page_surfaces_manifest_failure_after_promotion`, `bootstrap_surfaces_manifest_failure_after_promotion`, `move_project_merge_surfaces_destination_promotion_manifest_warning`, `move_session_create_surfaces_destination_promotion_manifest_warning`; `multi_session.rs` `two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_pointers`; MCP `dual_key_scope.rs`; hooks `workstream.rs` `managed_run_by_remote_identity_claims_the_folder_named_project`, `managed_run_by_remote_identity_routes_past_an_identityless_twin` (name-only control is ambiguous), `managed_run_identity_never_redirects_another_project_name`, `managed_run_by_remote_identity_refuses_a_viewer_without_write` (outsider refused with no project created; granted member admitted as the control), `managed_run_identity_never_claims_a_restricted_legacy_project` (an outsider whose cwd sits in a restricted identity-less project is refused, the identity stays unrecorded and no twin appears; fails with either the writer's claim check or the route's write check removed; a granted member claims it as the control), `managed_run_identity_routing_stays_inside_the_requested_workspace`, `concurrent_identity_runs_on_a_legacy_project_converge_on_it` (invariant #16), `managed_run_promotion_refreshes_the_scope_manifest`, `managed_run_discloses_manifest_failure_after_committed_promotion` static read/write/authz/cross-workspace/cross-forge cases; `router.rs` `workspace_override_is_rescope_only_on_a_genuine_workspace_change` (same/different/unresolvable workspace cases), `sticky_routing_keeps_the_session_project_across_a_sibling_checkout` (regression: same workspace forwarded on every event + `project_src=repo-root` from a nested checkout stays sticky), `sticky_routing_still_rescopes_when_marker_names_a_different_workspace_mid_session` (opposite direction: a genuinely different workspace still rescopes even under `sticky`) | STRONG || 10 | Destructive-op live-process refusal + confirm flags (invariant #9); `purge-project`'s `dry_run` always wins over `confirm` so a preview request can never become destructive; an explicitly empty restore-page scope cannot silently select the checkout | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project`; `admin.rs` `handle_purge_project` checks `req.dry_run` unconditionally, before `req.confirm`, mirroring `reclaim-ledger-versions`; `ai-memory-cli/src/commands/restore_page.rs` `run` calls `commands::refuse_empty_explicit` for both scope flags before resolution or HTTP | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir; `uninstall.rs` `purge_guard_refuses_a_live_sibling_before_stopping_the_service` — `uninstall --purge-data` checks for siblings (the `setup` service's own pid excepted) before it stops that service, and `purge_guard_rechecks_after_stopping_the_service` refuses when the stopped service is still alive; `admin_purge.rs` `purge_project_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing (the regression this row now also covers); `ops.rs` `purge_project_dry_run_changes_nothing` — every project-scoped row count, the `purged_scopes` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_project_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_project_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — a purge of project P collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project Q (via `sessions` cascading out of P), and both the preview and the confirmed report count it; CLI `tests/suite/marker_scope.rs` `restore_page_refuses_empty_scope_flags_without_sending_a_mutation` refuses empty and whitespace-only `--workspace`/`--project` with no POST; omitted, partially explicit and fully explicit scopes reach only the expected target as controls. Without the guard, the shipped binary sends the restore to the marker scope and the test fails | STRONG |+| 10a | Same-workspace project merge preserves both identities' data and fails closed on stale or live input | `ai-memory-store::merge_project` validates source and target ids against the named workspace, checks the complete source/target latest-page plan, refuses open sessions and unexpired managed leases, re-stamps/coalesces every project-keyed table in one writer transaction, creates a combined version for each page collision, and deletes the source row last. Page-id keyed embeddings/evidence/access/links follow unchanged. `Wiki::merge_project` holds the mutation lock, snapshots the target tree, parks the source, installs files before SQL and restores both trees on refusal. `/admin/merge-project` remains root-only and resolves optional ids inside the named workspace; retained version restore verifies the exact target scope/path before writing | store `merge_project_preserves_both_page_histories_and_dependent_rows`, `merge_project_refuses_open_sessions_and_foreign_project_ids`, `merge_project_preserves_colliding_workstreams`; admin `merge_project_dry_run_then_preserves_history_and_sessions` (also restores the retained source version), `merge_project_refuses_open_sessions_and_foreign_ids`, `concurrent_project_merges_have_one_winner_without_losing_the_page` | STRONG || 10b | Session purge is scope+owner-bound (no cross-session/project over-delete); `purge-session`'s `dry_run` always wins over `confirm`, same as `purge-project` | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; the session's prompt `profile_candidates` (`source_ref = 'session:<sid>'`, a globally unique id) are deleted in whichever project the harvest filed them, matching the `observations` cascade they were harvested from; whole op in one transaction, and the tombstone it leaves is checked by `begin_session_row` and by the new-session arm of `admit_hook_session_event`; `move_project_workspace` re-stamps the `purged_sessions` tombstone with the rest of the project so it still matches after a move; `admin.rs` `handle_purge_session` checks `req.dry_run` unconditionally, before `req.confirm` | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862); `admin_purge.rs` `purge_session_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing; `ops.rs` `purge_session_dry_run_changes_nothing` — every table a session purge touches, the `purged_sessions` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_session_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_session_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — purging session S collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project (via `S`'s own id cascading), and both the preview and the confirmed report count it; `admin_purge.rs` `purge_session_dry_run_refuses_a_session_outside_its_named_scope` — the same session previewed under a different real project (same workspace) or a different real workspace whose project shares the name both 404 with no counts in the body, with the session's own scope as the 200 control; the `purged_sessions` tombstone holds against live hook ingest as well as `begin_session`: `ops.rs` `a_purged_session_is_not_recreated_by_hook_admission` (`admit_hook_session_event` refuses a purged session and writes nothing, with a sibling session and the same id in another project admitted as controls) and `router.rs` `async_processing_drops_events_of_a_purged_session` (the late delivery is a terminal `dropped_invalid`, not a failure the client retries) and `batch_drops_a_purged_session_then_commits_next_item` (the batch endpoint acknowledges it as `dropped_invalid` and commits the next item instead of stopping fail-fast); the user's own sentences the profile harvested from the session's prompts go with it: `ops.rs` `purge_session_deletes_the_profile_candidates_harvested_from_it` (including the candidate harvested from a prompt the session recorded in another project, whose observation the purge deletes through the cascade; a sibling session's candidates in both projects and a page candidate survive); `ops.rs` `a_purged_session_stays_purged_after_its_project_moves` (after `move-project`, `begin_session` for the purged id in the destination is refused with `SessionPurged`; a fresh session there is admitted as the control) | STRONG || 10c | Ledger reclaim is content-gated, not filename-gated (invariant #16) | `ai-memory-store/src/ops.rs` `reclaim_ledger_versions` — a candidate row must pass `ai_memory_core::log_ledger::body_opens_with_log_ledger` on its own `body`, and only `is_latest=0 AND superseded_at IS NULL` rows are eligible, so decay-owned rows stay with `forget-sweep`; confirm gate in `admin.rs` `handle_reclaim_ledger_versions` | `reclaim_ledger_versions.rs` `a_prose_page_wearing_the_ledger_name_keeps_its_whole_version_chain`, `an_ordinary_page_chain_in_another_project_is_untouched`, `a_decay_tombstone_stays_with_the_sweep_that_owns_it`; `admin_reclaim_ledger_versions.rs` `deleting_without_confirm_is_refused_and_changes_nothing` (with dry-run and confirmed controls) | STRONG || 10d | Workspace delete's own row counts are scope-bound to `workspace_id` (a workspace's *own* rows are never over- or under-counted by a sibling workspace's), its cross-workspace observation/handoff cascade is reported by both preview and confirm rather than prevented (same as `purge-project` one level down), the non-empty guard fails closed without `force`, and `delete-workspace`'s `dry_run` always wins | `ai-memory-store/src/ops.rs` `delete_workspace` — every direct count and the `DELETE FROM workspaces` itself are scoped by `workspace_id = ?1`; the two `collateral_*` counts are scoped by `workspace_id != ?1` so a row is counted as one or the other but never both; `projects_deleted > 0 && !force → WorkspaceNotEmpty` fail-closed, and a missing workspace is `NotFound`, both checked identically under `PurgeMode::Preview` and `PurgeMode::Commit`; whole op in one transaction; `admin.rs` `handle_delete_workspace` checks `req.dry_run` unconditionally, before building the confirmed path, mirroring `reclaim-ledger-versions`/`purge-project`; root-only gate is the shared `/admin/*` multi-user auth ladder, not a separate check | `admin_move.rs` `delete_workspace_dry_run_never_counts_a_different_workspaces_rows` — previewing workspace A counts only its own project/page/session/observation/handoff rows, not workspace B's (which holds two like-named projects and its own full row set), and a session living in B that stamps an observation directly into A is counted in A's own `observations_deleted`, never in `collateral_observations_deleted` (the two counts are mutually exclusive by construction); `admin_move.rs` `delete_workspace_force_true_and_dry_run_true_still_only_previews` — `{"force": true, "dry_run": true}` deletes nothing; `ops.rs` `delete_workspace_dry_run_changes_nothing` — every table's row count, including `workspaces` itself and the `purged_scopes` tombstone (the two tables a confirmed delete's own transaction writes to), is identical before/after a `PurgeMode::Preview` run; `ops.rs` `delete_workspace_dry_run_and_confirmed_delete_both_report_collateral_damage_in_another_workspace` and `admin_move.rs` of the same name — deleting workspace W collaterally deletes an observation, and orphans a handoff's session reference, in a *different* workspace (via `sessions` cascading out of W), and both the preview and the confirmed response count it identically — the cascade itself is reported, not blocked, by either; `admin_move.rs` `delete_workspace_dry_run_refuses_non_empty_without_force` / `delete_workspace_dry_run_nonexistent_workspace_returns_404` — same `409`/`404` a confirmed delete would give; `admin.rs` `multiuser_delete_workspace_dry_run_rejects_db_user_and_anonymous` — root reaches the preview handler (404 control), DB user gets 403, anonymous gets 401 | STRONG |