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): reconcile native path aliases before removal
Linuxdazhaob55628bf4415
diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rsindex c700c38b7..23f36360b 100644--- a/crates/host-core/src/db.rs+++ b/crates/host-core/src/db.rs@@ -7,7 +7,7 @@ pub(crate) use serde_json::Value;pub(crate) use std::path::{Path, PathBuf};/// Current SQLite schema version.-pub const SCHEMA_VERSION: i64 = 27;+pub const SCHEMA_VERSION: i64 = 28;/// Absolute approval deadline for a newly submitted Plan or Goal proposal.pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;@@ -20,6 +20,7 @@ mod model;mod model_discovery_migration;mod plugin_providers_migration;mod project_groups;+mod project_path_migration;mod repositories;mod schema;mod session_collaboration_migration;@@ -70,3 +71,7 @@ pub fn ms_to_ts(ms: i64) -> String {#[cfg(test)]mod tests;++#[cfg(test)]+#[path = "db/project_path_tests.rs"]+mod project_path_tests;diff --git a/crates/host-core/src/db/project_groups.rs b/crates/host-core/src/db/project_groups.rsindex 5de81f6f2..643b6d749 100644--- a/crates/host-core/src/db/project_groups.rs+++ b/crates/host-core/src/db/project_groups.rs@@ -209,12 +209,14 @@ impl Database {let mut used_paths = std::collections::HashSet::new();let mut groups = Vec::with_capacity(stored.len() + projects.len());- for group in stored {- for root in &group.roots {+ for mut group in stored {+ for root in &mut group.roots {let path = canonical_project_path(&root.path).ok_or_else(|| anyhow!("project group root path must not be blank"))?;+ root.path = path.clone();used_paths.insert(path);}+ group.primary_path = group.roots[0].path.clone();for path in &group.detached_paths {if let Some(path) = canonical_project_path(path) {used_paths.insert(path);diff --git a/crates/host-core/src/db/project_path_migration.rs b/crates/host-core/src/db/project_path_migration.rsnew file mode 100644index 000000000..26391eeeb--- /dev/null+++ b/crates/host-core/src/db/project_path_migration.rs@@ -0,0 +1,144 @@+use super::*;+use std::collections::BTreeMap;++pub(super) fn migrate(conn: &Connection, path: &Path, from: i64) -> Result<()> {+ let backup = create_migration_backup(conn, path, from)?;+ let tx = conn.unchecked_transaction()?;+ reconcile_project_paths(conn, None)?;+ tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;+ tx.commit().with_context(|| {+ format!(+ "commit project path migration; backup {} remains",+ backup.display()+ )+ })+}++/// Resolve actual filesystem identities, not a platform-wide lowercase guess:+/// Windows directories and macOS volumes can both be case-sensitive.+pub(super) fn reconcile_project_paths(conn: &Connection, target: Option<&str>) -> Result<()> {+ let rows = conn+ .prepare(+ "SELECT id, path FROM projects+ ORDER BY EXISTS(SELECT 1 FROM sessions s WHERE s.project_id=projects.id) DESC,+ last_opened_at DESC, id ASC",+ )?+ .query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ // Most lists contain no aliases. Avoid filesystem probes of unrelated or+ // unavailable roots on every project-group/tool-context read.+ let mut spellings = BTreeMap::<String, usize>::new();+ for (_, path) in &rows {+ if let Some(path) = normalize_project_path(path) {+ *spellings.entry(path.to_uppercase()).or_default() += 1;+ }+ }+ let mut groups = BTreeMap::<String, Vec<(i64, String)>>::new();+ for (id, path) in rows {+ if path.starts_with(REMOTE_PROJECT_PREFIX) {+ continue;+ }+ let Some(normalized) = normalize_project_path(&path) else {+ continue;+ };+ if target.is_none()+ && normalized == path+ && spellings.get(&normalized.to_uppercase()) == Some(&1)+ {+ continue;+ }+ if target.is_some_and(|target| normalized.to_uppercase() != target.to_uppercase()) {+ continue;+ }+ if let Some(canonical) = canonical_project_path(&path) {+ // A retargeted symlink must not redirect an old project's ownership.+ if normalized.to_uppercase() != canonical.to_uppercase() {+ continue;+ }+ if target.is_none_or(|target| target == canonical) {+ groups.entry(canonical).or_default().push((id, path));+ }+ }+ }+ let groups: Vec<_> = groups+ .into_iter()+ .filter(|(path, rows)| rows.len() > 1 || rows[0].1 != *path)+ .collect();+ if groups.is_empty() {+ return Ok(());+ }+ // Session import can already own a transaction on this connection.+ conn.execute_batch("SAVEPOINT reconcile_project_paths")?;+ let result = (|| -> Result<()> {+ for (canonical, rows) in groups {+ let keep = rows[0].0;+ for (id, old_path) in &rows {+ // Keep both original memory records if they conflict. A missing+ // canonical record inherits the survivor's memory without loss.+ conn.execute(+ "INSERT OR IGNORE INTO kv(ns,key,value_json,updated_at)+ SELECT ns,?1,value_json,updated_at FROM kv WHERE ns='projectMemory' AND key=?2",+ params![canonical, old_path],+ )?;+ if *id == keep {+ continue;+ }+ conn.execute(+ "UPDATE sessions SET project_id=?1 WHERE project_id=?2",+ params![keep, id],+ )?;+ conn.execute(+ "UPDATE scheduled_tasks SET project_id=?1 WHERE project_id=?2",+ params![keep, id],+ )?;+ conn.execute(+ "UPDATE projects SET pinned=MAX(pinned,(SELECT pinned FROM projects WHERE id=?2)),+ created_at=MIN(created_at,(SELECT created_at FROM projects WHERE id=?2)),+ last_opened_at=MAX(last_opened_at,(SELECT last_opened_at FROM projects WHERE id=?2)),+ worktree_setup_command=COALESCE(worktree_setup_command,(SELECT worktree_setup_command FROM projects WHERE id=?2))+ WHERE id=?1", params![keep, id],+ )?;+ conn.execute(+ "UPDATE kv SET value_json=?1 WHERE ns='app' AND key='currentProjectId' AND value_json=?2",+ params![keep.to_string(), id.to_string()],+ )?;+ conn.execute("DELETE FROM projects WHERE id=?1", params![id])?;+ }+ conn.execute(+ "UPDATE projects SET path=?1 WHERE id=?2",+ params![canonical, keep],+ )?;+ }+ conn.execute_batch("RELEASE reconcile_project_paths")?;+ Ok(())+ })();+ if let Err(error) = result {+ conn.execute_batch("ROLLBACK TO reconcile_project_paths; RELEASE reconcile_project_paths")+ .context("roll back project path repair")?;+ return Err(error);+ }+ Ok(())+}++impl Database {+ /// A destructive operation must prefer the selected stored row. Resolving+ /// symlinks/case first can silently select a different historical row.+ pub(crate) fn stored_project_path(&self, raw: &str) -> Result<Option<String>> {+ let Some(path) = normalize_project_path(raw) else {+ return Ok(None);+ };+ let target = canonical_project_path(raw);+ if let Some(target) = target.as_deref() {+ reconcile_project_paths(&self.conn, Some(target))?;+ }+ let exact = self+ .conn+ .query_row(+ "SELECT path FROM projects WHERE path=?1",+ params![path],+ |r| r.get::<_, String>(0),+ )+ .optional()?;+ Ok(exact.or_else(|| canonical_project_path(raw)))+ }+}diff --git a/crates/host-core/src/db/project_path_tests.rs b/crates/host-core/src/db/project_path_tests.rsnew file mode 100644index 000000000..951ee8e84--- /dev/null+++ b/crates/host-core/src/db/project_path_tests.rs@@ -0,0 +1,239 @@+use super::*;++#[test]+fn unicode_case_aliases_use_the_same_native_project_identity() {+ for (name, alias) in [("Älpha", "älpha"), ("Σ", "ς")] {+ let root = tempfile::tempdir().unwrap();+ let root = root.path().canonicalize().unwrap();+ let folder = root.join(name);+ let alias = root.join(alias);+ let db = Database::open(&root.join("pi.sqlite")).unwrap();+ let first = db.ensure_project(alias.to_str().unwrap(), false).unwrap();+ std::fs::create_dir(&folder).unwrap();+ if !alias.exists() {+ continue;+ }+ assert_eq!(+ db.ensure_project(folder.to_str().unwrap(), false).unwrap(),+ first+ );+ assert_eq!(db.list_projects().unwrap().len(), 1);+ }+}++#[test]+fn project_path_upgrade_preserves_every_owner_and_reuses_the_project() {+ let root = tempfile::tempdir().unwrap();+ let root = root.path().canonicalize().unwrap();+ let folder = root.join("Alpha");+ let alias = root.join("alpha").to_string_lossy().replace('\\', "/");+ std::fs::create_dir(&folder).unwrap();+ if !std::path::Path::new(&alias).exists() {+ return; // Distinct directories on a case-sensitive filesystem.+ }+ let canonical = canonical_project_path(folder.to_str().unwrap()).unwrap();+ let file = root.join("pi.sqlite");+ let (first, second);+ {+ let db = Database::open(&file).unwrap();+ first = db.ensure_project(&canonical, false).unwrap();+ db.conn().execute(+ "INSERT INTO projects(path,name,pinned,created_at,last_opened_at) VALUES(?1,'Keep this name',1,1,2)",+ params![alias],+ ).unwrap();+ second = db.conn().last_insert_rowid();+ for (id, project) in [("canonical", first), ("alias", second)] {+ db.conn()+ .execute(+ "INSERT INTO sessions(id,project_id,created_at,updated_at) VALUES(?1,?2,1,1)",+ params![id, project],+ )+ .unwrap();+ db.conn().execute("INSERT INTO scheduled_tasks(id,title,prompt,project_id,created_at,updated_at) VALUES(?1,'Task','Prompt',?2,1,1)", params![id, project]).unwrap();+ }+ db.kv_set("app", "currentProjectId", &serde_json::json!(second))+ .unwrap();+ db.conn().pragma_update(None, "user_version", 27).unwrap();+ }+ let db = Database::open(&file).unwrap();+ assert_eq!(db.list_projects().unwrap().len(), 1);+ let keep = db.ensure_project(&alias, false).unwrap();+ assert_eq!(db.ensure_project(&canonical, false).unwrap(), keep);+ let owners: Vec<i64> = db+ .conn()+ .prepare("SELECT project_id FROM sessions ORDER BY id")+ .unwrap()+ .query_map([], |r| r.get(0))+ .unwrap()+ .collect::<rusqlite::Result<_>>()+ .unwrap();+ assert_eq!(owners, vec![keep, keep]);+ let tasks: i64 = db+ .conn()+ .query_row(+ "SELECT count(*) FROM scheduled_tasks WHERE project_id=?1",+ params![keep],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(tasks, 2);+ assert!(db.get_project(keep).unwrap().unwrap().pinned);+ assert_eq!(+ db.kv_get("app", "currentProjectId").unwrap(),+ Some(serde_json::json!(keep))+ );+ assert!(migration_backup_path(&file, 27).exists());+}++#[test]+fn project_created_before_directory_exists_is_not_duplicated_when_it_appears() {+ let root = tempfile::tempdir().unwrap();+ let root = root.path().canonicalize().unwrap();+ let folder = root.join("Alpha");+ let alias = root.join("alpha");+ let db = Database::open(&root.join("pi.sqlite")).unwrap();+ let first = db.ensure_project(alias.to_str().unwrap(), false).unwrap();+ std::fs::create_dir(&folder).unwrap();+ if !alias.exists() {+ return;+ }+ let second = db.ensure_project(folder.to_str().unwrap(), false).unwrap();+ assert_eq!(first, second);+ assert_eq!(db.list_projects().unwrap().len(), 1);+}++#[test]+fn case_sensitive_project_identities_stay_distinct() {+ let root = tempfile::tempdir().unwrap();+ let upper = root.path().join("Alpha");+ let lower = root.path().join("alpha");+ std::fs::create_dir(&upper).unwrap();+ if lower.exists() {+ return;+ }+ std::fs::create_dir(&lower).unwrap();+ let db = Database::open(&root.path().join("pi.sqlite")).unwrap();+ assert_ne!(+ db.ensure_project(upper.to_str().unwrap(), false).unwrap(),+ db.ensure_project(lower.to_str().unwrap(), false).unwrap()+ );+ assert_eq!(db.list_projects().unwrap().len(), 2);+}++#[test]+fn opaque_remote_project_identities_are_not_case_folded() {+ let root = tempfile::tempdir().unwrap();+ let db = Database::open(&root.path().join("pi.sqlite")).unwrap();+ for path in ["remote-project:Alpha", "remote-project:alpha"] {+ db.conn()+ .execute(+ "INSERT INTO projects(path,name,created_at,last_opened_at) VALUES(?1,'Remote',1,1)",+ params![path],+ )+ .unwrap();+ }+ assert_eq!(db.list_projects().unwrap().len(), 2);+}++#[test]+fn historical_group_case_alias_keeps_its_context_and_remains_addressable() {+ let root = tempfile::tempdir().unwrap();+ let root = root.path().canonicalize().unwrap();+ let folder = root.join("Alpha");+ let alias = root.join("alpha");+ std::fs::create_dir(&folder).unwrap();+ if !alias.exists() {+ return;+ }+ let db = Database::open(&root.join("pi.sqlite")).unwrap();+ let mut group = db+ .create_project_group("Kept group", &[folder.to_string_lossy().into_owned()])+ .unwrap();+ group.primary_path = alias.to_string_lossy().replace('\\', "/");+ group.roots[0].path = group.primary_path.clone();+ db.kv_set(+ "projectGroups",+ &group.id,+ &serde_json::to_value(&group).unwrap(),+ )+ .unwrap();+ db.set_project_group_instructions(&group.id, "Preserve group instructions")+ .unwrap();+ let canonical = canonical_project_path(folder.to_str().unwrap()).unwrap();+ let restored = db+ .stored_project_group_for_path(&canonical)+ .unwrap()+ .unwrap();+ assert_eq!(restored.id, group.id);+ assert_eq!(restored.primary_path, canonical);+ assert_eq!(+ db.get_project_group_instructions(&group.id).unwrap(),+ "Preserve group instructions"+ );+}++#[cfg(unix)]+#[test]+fn deleting_a_stored_symlink_path_does_not_retarget_to_another_project() {+ let root = tempfile::tempdir().unwrap();+ let target = root.path().join("unrelated");+ let link = root.path().join("old-link");+ std::fs::create_dir(&target).unwrap();+ std::os::unix::fs::symlink(&target, &link).unwrap();+ let db = Database::open(&root.path().join("pi.sqlite")).unwrap();+ let unrelated = db.ensure_project(target.to_str().unwrap(), false).unwrap();+ db.conn()+ .execute(+ "INSERT INTO projects(path,name,created_at,last_opened_at) VALUES(?1,'Stored',1,1)",+ params![link.to_str()],+ )+ .unwrap();+ assert!(db.delete_project(link.to_str().unwrap()).unwrap());+ assert!(db.get_project(unrelated).unwrap().is_some());+}++#[test]+fn path_repair_is_atomic_and_can_run_inside_an_import_transaction() {+ let root = tempfile::tempdir().unwrap();+ let root = root.path().canonicalize().unwrap();+ let folder = root.join("Alpha");+ let alias = root.join("alpha");+ let db = Database::open(&root.join("pi.sqlite")).unwrap();+ let first = db.ensure_project(alias.to_str().unwrap(), false).unwrap();+ std::fs::create_dir(&folder).unwrap();+ if !alias.exists() {+ return;+ }+ let tx = db.conn().unchecked_transaction().unwrap();+ assert_eq!(+ db.ensure_project(folder.to_str().unwrap(), false).unwrap(),+ first+ );+ tx.rollback().unwrap();+ assert_eq!(+ db.project_path(first).unwrap().unwrap(),+ alias.to_string_lossy().replace('\\', "/")+ );+ let canonical = canonical_project_path(folder.to_str().unwrap()).unwrap();+ db.conn()+ .execute(+ "INSERT INTO projects(path,name,created_at,last_opened_at) VALUES(?1,'Duplicate',1,1)",+ params![canonical],+ )+ .unwrap();+ db.conn().execute_batch("CREATE TRIGGER reject_merge BEFORE DELETE ON projects BEGIN SELECT RAISE(ABORT,'blocked'); END;").unwrap();+ assert!(db.list_projects().is_err());+ let count: i64 = db+ .conn()+ .query_row("SELECT count(*) FROM projects", [], |r| r.get(0))+ .unwrap();+ assert_eq!(count, 2);+ assert_eq!(+ db.project_path(first).unwrap().unwrap(),+ alias.to_string_lossy().replace('\\', "/")+ );+ db.conn()+ .execute_batch("DROP TRIGGER reject_merge")+ .unwrap();+ assert_eq!(db.list_projects().unwrap().len(), 1);+}diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rsindex 0791856dc..9fff1042f 100644--- a/crates/host-core/src/db/repositories.rs+++ b/crates/host-core/src/db/repositories.rs@@ -216,6 +216,7 @@ impl Database {26 => {migrate_v26_to_v27(&conn, path)?;}+ 27 => {}legacy @ 1..=6 => {let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");drop(conn);@@ -279,6 +280,10 @@ impl Database {if migrated_version == 26 {migrate_v26_to_v27(&conn, path)?;}+ let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;+ if version == 27 {+ super::project_path_migration::migrate(&conn, path, 27)?;+ }let db = Self { conn, data_dir };db.boot_maintenance()?;crate::session_collaboration::recover(&db)?;@@ -370,7 +375,10 @@ impl Database {}return Ok(id);}- upsert_project_row(&self.conn, path, touch)?+ let target = canonical_project_path(path)+ .ok_or_else(|| anyhow!("project path must not be blank"))?;+ super::project_path_migration::reconcile_project_paths(&self.conn, Some(&target))?;+ upsert_project_row(&self.conn, &target, touch)?.ok_or_else(|| anyhow!("project path must not be blank"))}@@ -403,6 +411,7 @@ impl Database {}pub fn list_projects(&self) -> Result<Vec<ProjectRecord>> {+ super::project_path_migration::reconcile_project_paths(&self.conn, None)?;let mut stmt = self.conn.prepare_cached("SELECT id, path, name, pinned, created_at, last_opened_atFROM projects@@ -424,7 +433,8 @@ impl Database {/// Session ids attached to a project row, including sessions already/// marked deleted. Callers delete each session so its transcript files follow.pub fn project_session_ids(&self, path: &str) -> Result<Vec<String>> {- let path = canonical_project_path(path)+ let path = self+ .stored_project_path(path)?.ok_or_else(|| anyhow!("project path must not be blank"))?;let mut stmt = self.conn.prepare_cached("SELECT s.id FROM sessions s@@ -438,7 +448,8 @@ impl Database {/// Delete a project row by canonical path. Returns whether a row existed so/// callers can report an idempotent removal.pub fn delete_project(&self, path: &str) -> Result<bool> {- let path = canonical_project_path(path)+ let path = self+ .stored_project_path(path)?.ok_or_else(|| anyhow!("project path must not be blank"))?;let deleted = self.conndiff --git a/crates/host-core/src/db/tool_image_storage_migration.rs b/crates/host-core/src/db/tool_image_storage_migration.rsindex 641812459..30c7f1df8 100644--- a/crates/host-core/src/db/tool_image_storage_migration.rs+++ b/crates/host-core/src/db/tool_image_storage_migration.rs@@ -80,7 +80,7 @@ mod tests {std::fs::write(file, b"legacy bytes are not rewritten on database open\n").unwrap();}let db = Database::open(&path).unwrap();- assert_eq!(version(db.conn()), 27);+ assert_eq!(version(db.conn()), SCHEMA_VERSION);let backup_path = migration_backup_path(&path, 25);let backup = Connection::open(&backup_path).unwrap();assert_eq!(version(&backup), 25);@@ -98,7 +98,7 @@ mod tests {drop(db);let original_backup = std::fs::read(&backup_path).unwrap();let db = Database::open(&path).unwrap();- assert_eq!(version(db.conn()), 27);+ assert_eq!(version(db.conn()), SCHEMA_VERSION);assert_eq!(std::fs::read(backup_path).unwrap(),original_backup,@@ -107,18 +107,27 @@ mod tests {}#[test]- fn fresh_database_uses_27_and_future_28_is_refused() {+ fn fresh_database_uses_latest_schema_and_future_schema_is_refused() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("pi.sqlite");let db = Database::open(&path).unwrap();- assert_eq!(version(db.conn()), 27);- db.conn().pragma_update(None, "user_version", 28).unwrap();+ assert_eq!(version(db.conn()), SCHEMA_VERSION);+ db.conn()+ .pragma_update(None, "user_version", SCHEMA_VERSION + 1)+ .unwrap();drop(db);let error = Database::open(&path).err().expect("future schema must be refused");- assert!(error.to_string().contains("28 is newer than supported 27"));- assert_eq!(version(&Connection::open(path).unwrap()), 28);+ assert!(error.to_string().contains(&format!(+ "{} is newer than supported {}",+ SCHEMA_VERSION + 1,+ SCHEMA_VERSION+ )));+ assert_eq!(+ version(&Connection::open(path).unwrap()),+ SCHEMA_VERSION + 1+ );}#[test]@@ -146,7 +155,7 @@ mod tests {.unwrap();drop(conn);let db = Database::open(&path).unwrap();- assert_eq!(version(db.conn()), 27);+ assert_eq!(version(db.conn()), SCHEMA_VERSION);for schema in [24, 25] {let backup = Connection::open(migration_backup_path(&path, schema)).unwrap();assert_eq!(version(&backup), schema);diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rsindex bb8aa55a1..993e58975 100644--- a/crates/host-core/src/plugins/providers/tests.rs+++ b/crates/host-core/src/plugins/providers/tests.rs@@ -101,10 +101,10 @@ fn a_new_database_carries_the_owner_column_at_the_current_schema_version() {// v19 session omit, v21 the session Todo checklist, and v22 the// session-list index, v23 the session title source, v24 the worktree// registry, v25 model discovery state, v26 lossless image storage, and v27- // the session Fast mode switch. A fresh database is stamped with the+ // the session Fast mode switch; v28 repairs project path aliases.+ // A fresh database is stamped with the// newest version, so the// column set is the current one.- assert_eq!(SCHEMA_VERSION, 27);let version: i64 = db.conn().query_row("PRAGMA user_version", [], |row| row.get(0))diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 7ecac98cd..ffed7ed65 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -2253,9 +2253,12 @@ async fn handle_request(.get("path").and_then(|v| v.as_str()).ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;- let path = crate::db::canonical_project_path(path)- .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;let st = state.lock().await;+ let path = st+ .db+ .stored_project_path(path)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?+ .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;if crate::scheduled::project::has_running_tasks(&st.db, &path).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?{diff --git a/crates/host-core/src/turn_queue.rs b/crates/host-core/src/turn_queue.rsindex adbbd0f77..9ad2a8012 100644--- a/crates/host-core/src/turn_queue.rs+++ b/crates/host-core/src/turn_queue.rs@@ -532,7 +532,11 @@ mod tests {assert_eq!(entries[0].content, "existing");assert!(entries[0].user_message_id.is_none());assert!(entries[0].voice_origin.is_none());- assert_eq!(crate::db::SCHEMA_VERSION, 27);+ let version: i64 = db+ .conn()+ .query_row("PRAGMA user_version", [], |row| row.get(0))+ .unwrap();+ assert_eq!(version, crate::db::SCHEMA_VERSION);}#[test]diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 2f2c01b4a..71a4ba965 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1,4 +1,24 @@-# 04. Data Storage (Schema v27)+# 04. Data Storage (Schema v28)++### Project path aliases (#2148)++The v27-to-v28 upgrade creates a verified database backup and atomically merges+case/separator spellings that native filesystem resolution identifies as the+same local directory. Prefer a row with sessions, then the latest last-opened+time and lowest id. Rebind every session and schedule before deleting duplicate+rows; retain pinned state, the earliest creation and latest opening timestamps,+and update the current project id. Transcript files are never rewritten or+deleted by this repair. Original path-keyed memory records remain intact; a+missing canonical memory record inherits the preferred row's value.++Upsert, listing and removal repeat this reconciliation for directories that+become available after startup. Missing directories retain their normalized+spelling until resolution proves an alias. Do not lowercase all Windows/macOS+paths: case-sensitive directories/volumes remain distinct, remote project ids+are opaque, and a retargeted symlink must not redirect stored ownership.+After reconciliation, removal prefers an exact stored path before filesystem+canonicalization. Existing busy checks and permanent-deletion confirmation apply+to the resulting unified project and all of its sessions.### Lossless tool-image storage (#1868)diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex b481c4c70..122e13892 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -244,6 +244,12 @@ type ToolBudgetHealth = {`rolledBack`, `alreadyRolledBack`, `conflict`, or `unavailable`.### Projects+- Before upsert, list or removal, reconcile local case/separator aliases proven+ by filesystem resolution, preserving all session/schedule ownership. Removal+ prefers the stored selected path; it must not delete another stored project+ merely because a symlink now resolves there. Missing paths, distinct+ case-sensitive directories and opaque remote ids are preserved. See storage+ schema v28 and `E2E-PROJECT-case-alias-upgrade-and-delete`.- `projects.list` — returns durable project records ordered pinned-first, thenby last-opened time; includes records materialized by session imports- `projects.create({ path })` — upserts a durable project record withoutdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex f7041b3ad..c1d012691 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1,5 +1,23 @@# 04. E2E Test Plan+## E2E-PROJECT-case-alias-upgrade-and-delete++- Entry: `python scripts/e2e-project-path-case.py <candidate-host>` on native+ Windows or a case-insensitive macOS volume. `--expect-bug` verifies the old+ failure against an unpatched Host.+- Create a temporary profile, real `Alpha` directory, two conversations with+ transcript bytes, and an unrelated project/conversation. Seed the historical+ lowercase project row and move one conversation to it while the Host is stopped.+- Restart: require one project, both conversations owned by it, and both+ transcripts preserved. Delete by the lowercase spelling: require both owned+ conversations/files removed, no reappearing alias row, and the unrelated+ conversation and physical project directory preserved.+- Repository regressions also cover a directory appearing after its first+ registration, schedule/current-selection retention, opaque remote ids,+ distinct case-sensitive directories, retargeted symlinks, nested import+ transactions and failure rollback. Use synthetic data only; no installed+ user profile, provider request or interactive Electron instance is used.+## E2E-COMPOSER-DIRECTORY-PASTE: Native folder cards and lazy context- **Preconditions**: Synthetic folders/files with spaces, Unicode and XML-significant names.diff --git a/scripts/e2e-project-path-case.py b/scripts/e2e-project-path-case.pynew file mode 100644index 000000000..6e5045ee7--- /dev/null+++ b/scripts/e2e-project-path-case.py@@ -0,0 +1,131 @@+"""Exercise project case-alias upgrade and deletion against a real native Host.++Usage: python scripts/e2e-project-path-case.py HOST [--aie] [--expect-bug]+Only a temporary profile and synthetic conversations are used.+"""+import argparse+from contextlib import closing+import json+import os+from pathlib import Path+import queue+import sqlite3+import subprocess+import tempfile+import threading+++class Host:+ def __init__(self, binary, profile):+ env = dict(os.environ, PI_DESKTOP_DATA_DIR=str(profile), AIE_DATA_DIR=str(profile))+ self.process = subprocess.Popen(+ [binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, text=True, encoding="utf-8", env=env,+ )+ self.lines = queue.Queue()+ threading.Thread(target=self.read, daemon=True).start()+ try:+ self.call("app.handshake", protocolVersion=11)+ except BaseException:+ self.close()+ raise++ def read(self):+ for line in self.process.stdout:+ self.lines.put(json.loads(line))+ self.lines.put(None)++ def call(self, method, **params):+ self.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1,+ "method": method, "params": params}) + "\n")+ self.process.stdin.flush()+ while True:+ message = self.lines.get(timeout=45)+ if message is None:+ self.process.wait(timeout=10)+ raise AssertionError(f"Host exited: {self.process.returncode}: {self.process.stderr.read()[-1500:]}")+ if message.get("id") == 1:+ assert "error" not in message, message+ return message["result"]++ def close(self):+ self.process.terminate()+ self.process.wait(timeout=10)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("host")+ parser.add_argument("--aie", action="store_true")+ parser.add_argument("--expect-bug", action="store_true")+ args = parser.parse_args()+ with tempfile.TemporaryDirectory(prefix="project-case-2148-") as temporary:+ root = Path(temporary).resolve()+ folder = root / "Alpha"+ folder.mkdir()+ alias = str(root / "alpha").replace("\\", "/")+ assert (root / "alpha").is_dir(), "Run on a case-insensitive filesystem"+ profile = root / "profile"+ host = Host(args.host, profile)+ try:+ first = host.call("session.create", title="Alias conversation", projectPath=str(folder))["session"]["id"]+ second = host.call("session.create", title="Canonical conversation", projectPath=str(folder))["session"]["id"]+ other = root / "Other"+ other.mkdir()+ unrelated = host.call("session.create", title="Unrelated", projectPath=str(other))["session"]["id"]+ for session_id in (first, second, unrelated):+ host.call("session.appendMessage", sessionId=session_id,+ message={"id": session_id + "-message", "role": "user", "content": "Synthetic fixture", "createdAt": "2026-11-06T00:00:00Z"})+ finally:+ host.close()+ transcripts = {sid: (profile / "sessions" / (sid + ".jsonl")).read_bytes()+ for sid in (first, second, unrelated)}+ database = profile / "pi.sqlite"+ with closing(sqlite3.connect(database)) as conn:+ canonical_id, canonical = conn.execute("SELECT id,path FROM projects WHERE id=(SELECT project_id FROM sessions WHERE id=?)", (second,)).fetchone()+ assert canonical != alias, (canonical, alias)+ conn.execute("INSERT INTO projects(path,name,created_at,last_opened_at) VALUES(?,?,1,1)", (alias, "Alias"))+ alias_id = conn.execute("SELECT id FROM projects WHERE path=?", (alias,)).fetchone()[0]+ conn.execute("UPDATE sessions SET project_id=? WHERE id=?", (alias_id, first))+ if not args.expect_bug:+ conn.execute("PRAGMA user_version=" + str(33 if args.aie else 27))+ conn.commit()+ host = Host(args.host, profile)+ try:+ projects = host.call("projects.list")["projects"]+ matching = [p for p in projects if p["path"].lower() == canonical.lower()]+ print("Rows after reopen:", [(p["id"], p["path"]) for p in matching], flush=True)+ with closing(sqlite3.connect(database)) as conn:+ owners = dict(conn.execute("SELECT id,project_id FROM sessions WHERE id IN (?,?)", (first, second)))+ if args.expect_bug:+ assert len(matching) == 2, matching+ else:+ assert len(matching) == 1, "Duplicate logical projects survived upgrade"+ assert len(owners) == 2 and len(set(owners.values())) == 1, owners+ for sid in (first, second):+ assert (profile / "sessions" / (sid + ".jsonl")).read_bytes() == transcripts[sid]+ result = host.call("projects.delete" if args.aie else "projects.remove", path=alias)+ with closing(sqlite3.connect(database)) as conn:+ remaining = dict(conn.execute("SELECT id,project_id FROM sessions"))+ rows = list(conn.execute("SELECT id,path FROM projects"))+ print("Delete result:", result, flush=True)+ print("Alias survived:", first in remaining, "canonical survived:", second in remaining, flush=True)+ assert unrelated in remaining, "An unrelated conversation was deleted"+ assert (profile / "sessions" / (unrelated + ".jsonl")).read_bytes() == transcripts[unrelated]+ assert folder.is_dir(), "Physical project directory was deleted"+ if args.expect_bug:+ assert first in remaining and second not in remaining, remaining+ assert any(p == alias for _, p in rows), rows+ print("CONFIRMED #2148: alias row survived; canonical conversation was deleted", flush=True)+ else:+ assert first not in remaining and second not in remaining, remaining+ assert not any(p.lower() == canonical.lower() for _, p in rows), rows+ for sid in (first, second):+ assert not (profile / "sessions" / (sid + ".jsonl")).exists()+ print("PASS #2148: upgrade preserved both conversations; explicit deletion removed the unified project", flush=True)+ finally:+ host.close()+++if __name__ == "__main__":+ main()