Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(projects): relocate only missing folders and cover two-step repair
vastsacbd0e0c80659
diff --git a/crates/host-core/src/db/project_groups.rs b/crates/host-core/src/db/project_groups.rsindex 514e56463..8410b810d 100644--- a/crates/host-core/src/db/project_groups.rs+++ b/crates/host-core/src/db/project_groups.rs@@ -401,37 +401,62 @@ impl Database {let mut ordered = vec![primary.clone()];ordered.extend(selected.into_iter().filter(|path| path != &primary));- let relocating_single_root =- current.roots.len() == 1 && ordered.len() == 1 && primary != current_primary;let removed = current.roots.iter().map(|root| root.path.as_str()).filter(|path| !ordered.iter().any(|candidate| candidate == path)).collect::<Vec<_>>();- let mut removed_without_sessions = Vec::new();- if !relocating_single_root {+ // An edit that leaves one root is an explicit relocation only when the+ // project being replaced no longer exists on disk; replacing a folder+ // that still exists keeps the detach semantics below (#2469).+ let relocation_source = if ordered.len() != 1 {+ None+ } else if current.roots.len() == 1 {+ // One-save repair: the sole root is swapped for its replacement.+ (primary != current_primary && !Path::new(¤t_primary).is_dir())+ .then(|| current_primary.clone())+ } else {+ // Two-step repair (#1869): the replacement was saved next to the+ // stale root first and the stale root is dropped now. Relocate only+ // one unambiguous stale project with data onto an empty target;+ // otherwise the stale root detaches as before.+ let mut stale = Vec::new();for path in &removed {- let has_sessions: bool = self.conn.query_row(- "SELECT EXISTS(- SELECT 1 FROM sessions s- JOIN projects p ON p.id = s.project_id- WHERE p.path = ?1- )",- params![path],- |row| row.get(0),- )?;- if !has_sessions {- removed_without_sessions.push(*path);+ if !Path::new(path).is_dir()+ && super::project_path_migration::project_path_owns_data(&self.conn, path)?+ {+ stale.push(path.to_string());}}- }- if relocating_single_root {- super::project_path_migration::relocate_project_path(- &self.conn,- ¤t_primary,- &primary,+ if stale.len() == 1+ && !super::project_path_migration::project_path_owns_data(&self.conn, &primary)?+ {+ stale.pop()+ } else {+ None+ }+ };+ let mut removed_without_sessions = Vec::new();+ for path in &removed {+ if relocation_source.as_deref() == Some(*path) {+ continue;+ }+ let has_sessions: bool = self.conn.query_row(+ "SELECT EXISTS(+ SELECT 1 FROM sessions s+ JOIN projects p ON p.id = s.project_id+ WHERE p.path = ?1+ )",+ params![path],+ |row| row.get(0),)?;+ if !has_sessions {+ removed_without_sessions.push(*path);+ }+ }+ if let Some(source) = relocation_source.as_deref() {+ super::project_path_migration::relocate_project_path(&self.conn, source, &primary)?;} else {for path in &ordered {self.ensure_project(path, false)?;@@ -444,7 +469,7 @@ impl Database {.execute(params![name, primary])?;let mut legacy = current;legacy.name = name.to_string();- if relocating_single_root {+ if relocation_source.is_some() {legacy.id = format!("legacy:{primary}");legacy.primary_path = primary.clone();legacy.roots[0].path = primary.clone();diff --git a/crates/host-core/src/db/project_path_migration.rs b/crates/host-core/src/db/project_path_migration.rsindex d22192b00..4004b5279 100644--- a/crates/host-core/src/db/project_path_migration.rs+++ b/crates/host-core/src/db/project_path_migration.rs@@ -121,6 +121,41 @@ pub(super) fn reconcile_project_paths(conn: &Connection, target: Option<&str>) -Ok(())}+fn scheduled_task_workspace_paths(conn: &Connection) -> Result<Vec<(String, Option<String>)>> {+ let mut statement = conn.prepare(+ "SELECT id,json_extract(config_json,'$.workspacePath') FROM scheduled_tasks+ WHERE json_extract(config_json,'$.workspacePath') IS NOT NULL",+ )?;+ let rows = statement+ .query_map([], |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))+ })?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ Ok(rows)+}++/// Whether the canonical `path` owns chats, scheduled tasks (by project id or+/// bound `workspacePath`), or path-scoped memory. Relocation moves such data+/// only onto a path that owns none of it.+pub(super) fn project_path_owns_data(conn: &Connection, path: &str) -> Result<bool> {+ let project = conn+ .query_row("SELECT id FROM projects WHERE path=?1", [path], |row| {+ row.get::<_, i64>(0)+ })+ .optional()?;+ let bound_task = scheduled_task_workspace_paths(conn)?+ .iter()+ .any(|(_, task)| task.as_deref().and_then(canonical_project_path).as_deref() == Some(path));+ Ok(bound_task+ || conn.query_row(+ "SELECT EXISTS(SELECT 1 FROM kv WHERE ns='projectMemory' AND key=?1)+ OR EXISTS(SELECT 1 FROM sessions WHERE project_id=?2)+ OR EXISTS(SELECT 1 FROM scheduled_tasks WHERE project_id=?2)",+ params![path, project],+ |row| row.get(0),+ )?)+}+/// Move one explicitly selected project to its replacement directory while/// retaining the project id used by sessions and scheduled tasks. The target/// may be an empty shadow row created by opening the replacement path first;@@ -137,30 +172,8 @@ pub(super) fn relocate_project_path(conn: &Connection, old: &str, new: &str) ->row.get::<_, i64>(0)}).optional()?;- let task_paths = {- let mut statement = conn.prepare(- "SELECT id,json_extract(config_json,'$.workspacePath') FROM scheduled_tasks- WHERE json_extract(config_json,'$.workspacePath') IS NOT NULL",- )?;- let rows = statement- .query_map([], |row| {- Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))- })?- .collect::<rusqlite::Result<Vec<_>>>()?;- rows- };- let target_task = task_paths- .iter()- .any(|(_, path)| path.as_deref().and_then(canonical_project_path).as_deref() == Some(new));- let occupied: bool = target_task- || conn.query_row(- "SELECT EXISTS(SELECT 1 FROM kv WHERE ns='projectMemory' AND key=?1)- OR EXISTS(SELECT 1 FROM sessions WHERE project_id=?2)- OR EXISTS(SELECT 1 FROM scheduled_tasks WHERE project_id=?2)",- params![new, target],- |row| row.get(0),- )?;- if occupied {+ let task_paths = scheduled_task_workspace_paths(conn)?;+ if project_path_owns_data(conn, new)? {return Err(anyhow!("replacement folder belongs to a non-empty project: {new}"));@@ -233,4 +246,24 @@ impl Database {.optional()?;Ok(exact.or_else(|| canonical_project_path(raw)))}++ /// Id of the project row stored at the given spelling or its canonical+ /// form, without creating one. Lets callers notice an explicit relocation.+ pub(crate) fn project_id_at_path(&self, raw: &str) -> Result<Option<i64>> {+ for path in [normalize_project_path(raw), canonical_project_path(raw)]+ .into_iter()+ .flatten()+ {+ let id = self+ .conn+ .query_row("SELECT id FROM projects WHERE path=?1", [&path], |r| {+ r.get::<_, i64>(0)+ })+ .optional()?;+ if id.is_some() {+ return Ok(id);+ }+ }+ Ok(None)+ }}diff --git a/crates/host-core/src/db/tests.rs b/crates/host-core/src/db/tests.rsindex 39002987a..67d1564d4 100644--- a/crates/host-core/src/db/tests.rs+++ b/crates/host-core/src/db/tests.rs@@ -2094,6 +2094,300 @@ fn single_root_replacement_rolls_back_an_empty_target_delete_on_failure() {assert_eq!(db.project_path(source).unwrap(), Some(group.primary_path));}+fn create_project_chat(db: &Database, path: &std::path::Path) -> String {+ crate::sessions::create_session(+ db,+ Some("Existing chat".into()),+ Some("agent".into()),+ None,+ None,+ Some(path.to_string_lossy().into_owned()),+ )+ .unwrap()+ .id+}++fn session_project_path(db: &Database, id: &str) -> Option<String> {+ crate::sessions::session_summary(db, id)+ .unwrap()+ .unwrap()+ .project_path+}++#[test]+fn single_root_replacement_keeps_sessions_when_the_old_folder_still_exists() {+ // Swapping an existing folder for an unrelated one is not a relocation:+ // the old project keeps its chats and stays reachable on its own.+ let dir = tempfile::tempdir().unwrap();+ let old = dir.path().join("old");+ let other = dir.path().join("other");+ std::fs::create_dir(&old).unwrap();+ std::fs::create_dir(&other).unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let group = db+ .create_project_group("Swap", &[old.to_string_lossy().into_owned()])+ .unwrap();+ let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();+ let session = create_project_chat(&db, &old);+ db.set_project_memory(&old.to_string_lossy(), "Old context")+ .unwrap();+ let canonical_old = group.primary_path.clone();+ let canonical_other = crate::db::canonical_project_path(&other.to_string_lossy()).unwrap();++ let updated = db+ .update_project_group(+ &group.id,+ "Swap",+ &[other.to_string_lossy().into_owned()],+ Some(&other.to_string_lossy()),+ )+ .unwrap();++ assert_eq!(updated.primary_path, canonical_other);+ assert_eq!(+ db.project_path(source).unwrap().as_deref(),+ Some(canonical_old.as_str())+ );+ assert_eq!(+ session_project_path(&db, &session).as_deref(),+ Some(canonical_old.as_str())+ );+ assert_eq!(db.project_session_ids(&canonical_old).unwrap(), [session]);+ assert!(db.project_session_ids(&canonical_other).unwrap().is_empty());+ assert_eq!(+ db.get_project_memory(&old.to_string_lossy())+ .unwrap()+ .content,+ "Old context"+ );+ assert_eq!(db.list_projects().unwrap().len(), 2);+ assert!(db+ .list_project_groups()+ .unwrap()+ .iter()+ .any(|candidate| candidate.legacy && candidate.primary_path == canonical_old));+}++#[test]+fn legacy_single_root_replacement_keeps_sessions_when_the_old_folder_still_exists() {+ let dir = tempfile::tempdir().unwrap();+ let old = dir.path().join("old");+ let other = dir.path().join("other");+ std::fs::create_dir(&old).unwrap();+ std::fs::create_dir(&other).unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();+ let session = create_project_chat(&db, &old);+ let group = db+ .list_project_groups()+ .unwrap()+ .into_iter()+ .find(|group| group.legacy)+ .unwrap();+ let canonical_old = group.primary_path.clone();++ let updated = db+ .update_project_group(+ &group.id,+ "Swap",+ &[other.to_string_lossy().into_owned()],+ Some(&other.to_string_lossy()),+ )+ .unwrap();++ // Pre-relocation behavior: the legacy record is returned unchanged.+ assert_eq!(updated.primary_path, canonical_old);+ assert_eq!(+ db.project_path(source).unwrap().as_deref(),+ Some(canonical_old.as_str())+ );+ assert_eq!(+ session_project_path(&db, &session).as_deref(),+ Some(canonical_old.as_str())+ );+ assert_eq!(db.list_projects().unwrap().len(), 2);+}++#[test]+fn two_step_stale_root_repair_relocates_the_stale_project() {+ // #1869 + #2469: the user first saves the replacement next to the stale+ // root, then saves again with only the replacement.+ let dir = tempfile::tempdir().unwrap();+ let old = dir.path().join("old");+ let new = dir.path().join("new");+ std::fs::create_dir(&old).unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let group = db+ .create_project_group("Moved", &[old.to_string_lossy().into_owned()])+ .unwrap();+ let canonical_old = group.primary_path.clone();+ let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();+ let session = create_project_chat(&db, &old);+ db.conn()+ .execute(+ "INSERT INTO scheduled_tasks(id,title,prompt,project_id,config_json,created_at,updated_at)+ VALUES('task','Task','Prompt',?1,json_object('workspacePath',?2),1,1)",+ params![source, canonical_old],+ )+ .unwrap();+ db.set_project_memory(&old.to_string_lossy(), "Keep this context")+ .unwrap();++ std::fs::rename(&old, &new).unwrap();+ let canonical_new = crate::db::canonical_project_path(&new.to_string_lossy()).unwrap();+ let first = db+ .update_project_group(+ &group.id,+ "Moved",+ &[canonical_old.clone(), new.to_string_lossy().into_owned()],+ Some(&canonical_new),+ )+ .unwrap();+ assert_eq!(first.roots.len(), 2);+ let shadow = db.ensure_project(&canonical_new, false).unwrap();+ assert_ne!(shadow, source);++ let healed = db+ .update_project_group(+ &group.id,+ "Moved",+ &[new.to_string_lossy().into_owned()],+ Some(&canonical_new),+ )+ .unwrap();++ assert_eq!(healed.id, group.id);+ assert_eq!(healed.primary_path, canonical_new);+ assert_eq!(healed.roots.len(), 1);+ assert!(!healed.detached_paths.contains(&canonical_old));+ assert_eq!(+ db.project_path(source).unwrap().as_deref(),+ Some(canonical_new.as_str())+ );+ assert!(db.get_project(shadow).unwrap().is_none());+ assert_eq!(db.list_projects().unwrap().len(), 1);+ assert_eq!(+ session_project_path(&db, &session).as_deref(),+ Some(canonical_new.as_str())+ );+ let task_workspace: String = db+ .conn()+ .query_row(+ "SELECT json_extract(config_json,'$.workspacePath') FROM scheduled_tasks WHERE id='task'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(task_workspace, canonical_new);+ assert_eq!(+ db.get_project_memory(&canonical_new).unwrap().content,+ "Keep this context"+ );+ let groups = db.list_project_groups().unwrap();+ assert_eq!(groups.len(), 1);+ assert_eq!(groups[0].id, group.id);+}++#[test]+fn two_step_stale_root_repair_keeps_detach_when_the_replacement_has_chats() {+ // A replacement that already owns chats is never merged implicitly; the+ // stale root is detached exactly as before relocation existed.+ let dir = tempfile::tempdir().unwrap();+ let old = dir.path().join("old");+ let new = dir.path().join("new");+ std::fs::create_dir(&old).unwrap();+ std::fs::create_dir(&new).unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let group = db+ .create_project_group(+ "Pair",+ &[+ new.to_string_lossy().into_owned(),+ old.to_string_lossy().into_owned(),+ ],+ )+ .unwrap();+ let canonical_new = group.primary_path.clone();+ let canonical_old = crate::db::canonical_project_path(&old.to_string_lossy()).unwrap();+ let source = db.ensure_project(&old.to_string_lossy(), false).unwrap();+ let old_session = create_project_chat(&db, &old);+ let new_session = create_project_chat(&db, &new);+ std::fs::remove_dir(&old).unwrap();++ let updated = db+ .update_project_group(+ &group.id,+ "Pair",+ &[new.to_string_lossy().into_owned()],+ Some(&canonical_new),+ )+ .unwrap();+ assert_eq!(updated.roots.len(), 1);+ assert_eq!(+ db.project_path(source).unwrap().as_deref(),+ Some(canonical_old.as_str())+ );+ assert_eq!(+ session_project_path(&db, &old_session).as_deref(),+ Some(canonical_old.as_str())+ );+ assert_eq!(+ session_project_path(&db, &new_session).as_deref(),+ Some(canonical_new.as_str())+ );+ assert_eq!(db.list_projects().unwrap().len(), 2);+}++#[test]+fn removing_an_existing_root_with_chats_still_detaches_it() {+ let dir = tempfile::tempdir().unwrap();+ let kept = dir.path().join("kept");+ let removed = dir.path().join("removed");+ std::fs::create_dir(&kept).unwrap();+ std::fs::create_dir(&removed).unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let group = db+ .create_project_group(+ "Pair",+ &[+ kept.to_string_lossy().into_owned(),+ removed.to_string_lossy().into_owned(),+ ],+ )+ .unwrap();+ let canonical_kept = group.primary_path.clone();+ let canonical_removed = crate::db::canonical_project_path(&removed.to_string_lossy()).unwrap();+ let source = db+ .ensure_project(&removed.to_string_lossy(), false)+ .unwrap();+ let session = create_project_chat(&db, &removed);++ let updated = db+ .update_project_group(+ &group.id,+ "Pair",+ &[kept.to_string_lossy().into_owned()],+ None,+ )+ .unwrap();+ assert_eq!(updated.roots.len(), 1);+ assert_eq!(updated.primary_path, canonical_kept);+ assert!(!updated.detached_paths.contains(&canonical_removed));+ assert_eq!(+ db.project_path(source).unwrap().as_deref(),+ Some(canonical_removed.as_str())+ );+ assert_eq!(+ session_project_path(&db, &session).as_deref(),+ Some(canonical_removed.as_str())+ );+ assert!(db+ .list_project_groups()+ .unwrap()+ .iter()+ .any(|candidate| candidate.legacy && candidate.primary_path == canonical_removed));+}+#[test]fn project_group_update_allows_a_root_renamed_away_externally() {// #1869: when a group folder is renamed (or unmounted) outside the app,diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex bb41be500..eba538616 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -2174,10 +2174,16 @@ async fn handle_request(.collect::<Vec<_>>();let primary = params.get("primary").and_then(Value::as_str);let mut st = state.lock().await;- let active_group = match st.workspace.path.as_deref() {+ // The active project's id survives an explicit relocation while its+ // stored path changes; detect that to follow it with the workspace.+ let active_project = match st.workspace.path.as_deref() {Some(path) => st.db- .project_group_for_path(path)+ .project_id_at_path(path)+ .and_then(|id| match id {+ Some(id) => Ok(st.db.project_path(id)?.map(|path| (id, path))),+ None => Ok(None),+ }).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,None => None,};@@ -2185,12 +2191,27 @@ async fn handle_request(.db.update_project_group(group_id, name, &folders, primary).map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;- if active_group.is_some_and(|current| {- current.id == group_id- && current.roots.len() == 1- && current.primary_path != group.primary_path- }) {- st.workspace.set(PathBuf::from(&group.primary_path));+ if let Some((id, before)) = active_project {+ let relocated = st+ .db+ .project_path(id)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?+ .filter(|after| {+ after != &before && group.roots.iter().any(|root| &root.path == after)+ });+ if let Some(path) = relocated {+ // Mirror `workspace.set`: hashline anchors belong to the old+ // root, and the current project id follows the new path.+ st.hashline.drop_all();+ let ws = st.workspace.set(PathBuf::from(&path));+ let pid = st+ .db+ .ensure_project(&ws.path, true)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ st.db+ .kv_set("app", "currentProjectId", &json!(pid))+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ }}Ok(json!({ "group": group }))}@@ -6603,6 +6624,119 @@ mod tests {);}+ #[tokio::test]+ async fn project_group_update_rpc_follows_a_two_step_relocation() {+ let data_dir = tempfile::tempdir().unwrap();+ let old = data_dir.path().join("old");+ let new = data_dir.path().join("new");+ fs::create_dir(&old).unwrap();+ let mut app_state = AppState::open(data_dir.path()).unwrap();+ app_state.handshook = true;+ app_state.workspace.set(&old);+ let state = Arc::new(Mutex::new(app_state));+ let send = |method: &'static str, params: Value| {+ let state = state.clone();+ async move {+ handle_request(state, method, params, mpsc::unbounded_channel().0)+ .await+ .unwrap()+ }+ };+ let created = send(+ "project.group.create",+ json!({ "name": "Movable", "folders": [old] }),+ )+ .await;+ let group_id = created["group"]["id"].as_str().unwrap().to_string();+ let old_path = created["group"]["primaryPath"]+ .as_str()+ .unwrap()+ .to_string();+ {+ let st = state.lock().await;+ crate::sessions::create_session(+ &st.db,+ Some("Existing chat".into()),+ Some("agent".into()),+ None,+ None,+ Some(old_path.clone()),+ )+ .unwrap();+ }+ fs::rename(&old, &new).unwrap();+ let new_path = crate::db::canonical_project_path(&new.to_string_lossy()).unwrap();++ send(+ "project.group.update",+ json!({+ "groupId": group_id,+ "name": "Movable",+ "folders": [old_path, new],+ "primary": new,+ }),+ )+ .await;+ let workspace = send("workspace.get", json!({})).await;+ assert_eq!(workspace["workspace"]["path"], json!(old_path));++ send(+ "project.group.update",+ json!({+ "groupId": group_id,+ "name": "Movable",+ "folders": [new],+ "primary": new,+ }),+ )+ .await;+ let workspace = send("workspace.get", json!({})).await;+ assert_eq!(workspace["workspace"]["path"], json!(new_path));+ }++ #[tokio::test]+ async fn project_group_update_rpc_keeps_workspace_when_the_old_folder_exists() {+ let data_dir = tempfile::tempdir().unwrap();+ let old = data_dir.path().join("old");+ let other = data_dir.path().join("other");+ fs::create_dir(&old).unwrap();+ fs::create_dir(&other).unwrap();+ let mut app_state = AppState::open(data_dir.path()).unwrap();+ app_state.handshook = true;+ let before = app_state.workspace.set(&old).path;+ let state = Arc::new(Mutex::new(app_state));+ let created = handle_request(+ state.clone(),+ "project.group.create",+ json!({ "name": "Swap", "folders": [old] }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ handle_request(+ state.clone(),+ "project.group.update",+ json!({+ "groupId": created["group"]["id"],+ "name": "Swap",+ "folders": [other],+ "primary": other,+ }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ let workspace = handle_request(+ state,+ "workspace.get",+ json!({}),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ assert_eq!(workspace["workspace"]["path"], json!(before));+ }+#[tokio::test]async fn project_group_update_rpc_switches_the_primary_folder() {let data_dir = tempfile::tempdir().unwrap();diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 440de6c31..e5054f7c3 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -92,13 +92,21 @@ legacy group; removing a root from group membership never deletes sessions or fiExisting path projects are projected as legacy single-root groups at read time;their path-scoped memory and filesystem instructions remain readable.Replacing the sole root of a legacy or stored single-root group is an explicit-project relocation, not a detach. The host retains the original project id and-updates its canonical path in the same transaction as the group edit, moves the-old path's `projectMemory` key and bound scheduled-task `workspacePath`, and-absorbs only an empty target project row. Existing chats and scheduled tasks-therefore retain their owner. A target that already owns chats, tasks, or memory-blocks the edit without changing either project. Multi-root detachment keeps the-existing standalone-project behavior.+project relocation, not a detach, only when the old root no longer exists on+disk. The host retains the original project id and updates its canonical path+in the same transaction as the group edit, moves the old path's+`projectMemory` key and bound scheduled-task `workspacePath`, and absorbs only+an empty target project row. Existing chats and scheduled tasks therefore+retain their owner. A target that already owns chats, tasks, or memory blocks+the edit without changing either project. When the old root still exists, the+edit is an ordinary swap: the old project keeps its chats, tasks, and memory+and stays readable as a standalone project. The two-step repair (#1869) is+covered too: after the replacement was first saved next to the missing root,+an edit that leaves only the replacement relocates the missing root's project+onto it when exactly one removed root is missing on disk and owns chats, tasks,+or memory and the replacement's project owns none; the stored group id is kept.+Otherwise, and for removed roots that still exist, multi-root detachment keeps+the existing standalone-project behavior.5. **Plan/Goal checkpoints are immutable host artifacts** with recorded path,hash, and size; the existing approval row also carries execution fields.Startup interruption is the process-epoch fence and no work is replayed.diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex f79725544..cb4cb21ca 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -286,12 +286,21 @@ type ToolBudgetHealth = {are removed, a `primary` outside `folders` is rejected, roots owned byanother non-legacy group are rejected, and a root with existing chats cannotbe detached. Removed roots are retained as suppressed historical paths rather- than reappearing as standalone legacy groups. Replacing the only root of a- legacy or stored single-root group instead relocates its existing project row:- the canonical path and path-scoped memory move while the project id, chats,- scheduled tasks, and group id remain stable. An empty shadow row at the new- path is absorbed; a target with its own chats, tasks, or memory is rejected,- and every database change rolls back together on failure.+ than reappearing as standalone legacy groups. When the old root no longer+ exists on disk, replacing the only root of a legacy or stored single-root+ group instead relocates its existing project row: the canonical path and+ path-scoped memory move while the project id, chats, scheduled tasks, and+ group id remain stable. An empty shadow row at the new path is absorbed; a+ target with its own chats, tasks, or memory is rejected, and every database+ change rolls back together on failure. If the old root still exists, the+ replacement is an ordinary swap and nothing is relocated. The two-step repair+ (first save the replacement next to the missing root, then save with only+ the replacement) relocates the same way when exactly one removed root is+ missing on disk and owns chats, tasks, or memory and the remaining root's+ project owns none; otherwise removed roots detach as described above. When+ the active workspace's project is relocated, the host moves the workspace to+ the new path exactly as `workspace.set` does (hashline anchors are dropped+ and `currentProjectId` follows).- `project.group.memory.get/set({ groupId, entries })` — reads or normalizesshared group memory using the existing 32 KiB entry limit.- `project.group.instructions.get/set({ groupId, content })` — reads or storesdiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 72afab34e..c4aec268c 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -658,12 +658,17 @@ visually distinct from list content.removal of a folder that still owns chats. Every other folder row carries aSet as Primary action that promotes it: the row moves to the top, the Primarytag moves with it, and the host stores the promoted folder as the group's- primary root on save. When a single-root project was moved externally, adding- its replacement, promoting it, and removing the stale row in one save- relocates the existing project instead of creating a replacement with- orphaned chats. A non-empty independent project at the replacement path- rejects the save unchanged. A remote project keeps its host-owned binding and- shows no promotion action.+ primary root on save. When a single-root project's folder was moved+ externally and the old folder no longer exists, adding its replacement,+ promoting it, and removing the stale row in one save relocates the existing+ project instead of creating a replacement with orphaned chats. Saving the+ replacement next to the stale row first and removing the stale row in a+ later save relocates the same way. If the old folder still exists, the save+ is an ordinary swap and the old project keeps its chats. A non-empty+ independent project at the replacement path rejects the one-save repair+ unchanged and leaves the two-step repair on the ordinary detach. A remote+ project keeps its host-owned binding and shows no promotion action.+ Background session or run-status updatesmust preserve unsaved name, folder, and primary edits in the open editor.Git repository as equal filled tiles without strokes (D297); the active sourceuses a deeper tile, not a selected border. A repository URL reuses the clonediff --git a/docs/spec/06-delivery/e2e/tools-and-workspace.md b/docs/spec/06-delivery/e2e/tools-and-workspace.mdindex e34837722..22fa6d89f 100644--- a/docs/spec/06-delivery/e2e/tools-and-workspace.md+++ b/docs/spec/06-delivery/e2e/tools-and-workspace.md@@ -572,24 +572,37 @@ journeys cover successful reads, saves and directory browsing.Read or Bash call. 4) Inspect project memory, the scheduled task, the projectlist, and the binding after restart. 5) Repeat with an empty shadow projectpreviously opened at the replacement path. 6) Repeat with a non-empty- independent target project and verify that saving is rejected.+ independent target project and verify that saving is rejected. 7) Repeat the+ two-step repair: save the replacement next to the stale row first, then save+ again with only the replacement. 8) Repeat step 2 while the old folder still+ exists (an ordinary swap to an unrelated folder).- **Expected**: The original project id and stored group id survive, its pathbecomes the canonical replacement, and the existing chat, scheduled task, andpath-scoped memory remain available without recreating the session. The oldworkspace call succeeds at the replacement path. An empty shadow row isabsorbed, leaving one project. A target with its own chats, tasks, or memoryblocks the operation with both projects and the original group unchanged.- Multi-root detachment still preserves a removed root's chats as a standalone- project; no automatic directory-move detection or implicit project merge is- introduced.+ The two-step repair ends in the same relocated state; if the replacement+ already owns chats, tasks, or memory, the stale root detaches unchanged+ instead. Relocation applies only when the old folder no longer exists: when+ it still exists, its project keeps its chats, tasks, and memory and remains+ a standalone project. Multi-root detachment still preserves a removed+ existing root's chats as a standalone project; no automatic directory-move+ detection or implicit merge of non-empty projects is introduced.- **Specs linked**: `03-runtime/04-data-storage.md`,`03-runtime/06-host-rpc-protocol.md` (Projects),`04-ux/08-component-spec.md` (project editor).- **Acceptance**: C (project and chat interaction), D (workspace identity),F (persistence), Quality.- **Milestone**: M5-- **Status**: Host integration-covered by the four- `single_root_replacement_*` regressions and the active-workspace RPC regression; full UI scenario Draft+- **Status**: Host integration-covered by the `single_root_replacement_*`,+ `legacy_single_root_replacement_keeps_sessions_when_the_old_folder_still_exists`,+ `two_step_stale_root_repair_*`, and+ `removing_an_existing_root_with_chats_still_detaches_it` regressions and the+ `project_group_update_rpc_relocates_the_active_single_root_workspace`,+ `project_group_update_rpc_follows_a_two_step_relocation`, and+ `project_group_update_rpc_keeps_workspace_when_the_old_folder_exists` RPC+ regressions; full UI scenario Draft## E2E-048c: Detach a project folder with chats and delete it