diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 8066f4f121..a86735a06f 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -212,6 +212,18 @@ pub struct UnregisteredRemovalHold { pub release: tokio::sync::Notify, } +/// Feature `testing`: a hold on one managed worktree creation at a point a test +/// picked: after it registered the directory it chose and before it builds +/// there, after it found the directory free and before it registers it, or in a +/// failed creation before its rollback removes the worktree. It notifies +/// `reached` once held and returns once `release` is notified. +#[cfg(feature = "testing")] +#[derive(Default)] +pub struct WorktreeCreationHold { + pub reached: tokio::sync::Notify, + pub release: tokio::sync::Notify, +} + /// Feature `testing`: a hold on one subscription's `follow` task. It notifies /// `waiting` once it is held, `cancelled` once retirement cancels it, and /// returns once `release` is notified. @@ -364,6 +376,46 @@ impl RunningServer { .get::() .map(|managed| managed.hold_next_unregistered_removal()) } + /// Names the task id the next managed worktree creation tries first, so a + /// test can make it meet a path a removal registered. Answers whether the + /// part is present. Feature `testing` only. + #[cfg(feature = "testing")] + pub fn prefer_next_worktree_task_id(&self, task_id: &str) -> bool { + match self.root.get::() { + Some(managed) => { + managed.prefer_next_task_id(task_id); + true + } + None => false, + } + } + /// Holds the next managed worktree creation after it checked its directory + /// and before it builds there, so a test can remove that path in between. + /// Feature `testing` only. + #[cfg(feature = "testing")] + pub fn hold_next_worktree_creation(&self) -> Option> { + self.root + .get::() + .map(|managed| managed.hold_next_creation()) + } + /// Holds the next managed worktree creation after it found its directory + /// free and before it registers that path, so a test can let a rollback of + /// that path run in between. Feature `testing` only. + #[cfg(feature = "testing")] + pub fn hold_next_worktree_creation_check(&self) -> Option> { + self.root + .get::() + .map(|managed| managed.hold_next_creation_check()) + } + /// Holds the next failed managed worktree creation before its rollback + /// removes the worktree it built, so a test can register that path first. + /// Feature `testing` only. + #[cfg(feature = "testing")] + pub fn hold_next_worktree_rollback(&self) -> Option> { + self.root + .get::() + .map(|managed| managed.hold_next_rollback()) + } /// Holds the next subscription's `follow` task open until `release`, so a /// test can keep an attach or detach in flight at a known point. Feature /// `testing` only. diff --git a/crates/dim-app-server/src/storage/face.rs b/crates/dim-app-server/src/storage/face.rs index 6d2908f638..729b3a5a7b 100644 --- a/crates/dim-app-server/src/storage/face.rs +++ b/crates/dim-app-server/src/storage/face.rs @@ -1,4 +1,4 @@ -use super::{PreparedWorktree, SessionStore, WorktreeDirectory}; +use super::{PreparedWorktree, SessionStore, WorktreeCreation, WorktreeDirectory}; use crate::protocol::SessionOrigin; use dim_agent_runtime::{AgentError, ReplyLanguage, SessionConfig}; use dim_agent_types::grant::{GrantKind, GrantMode}; @@ -150,10 +150,21 @@ impl Store { pub fn remove_worktree( &self, directory: WorktreeDirectory, - remove: impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>>, + remove: impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>> + Send + 'static, ) -> impl Future> { self.0.remove_worktree(directory, remove) } + /// Removes the worktree a failed creation built, taking the creation's own + /// registration over as the path's deletion registration. The rollback of + /// a managed creation is the only caller, so this stays off the face. + pub(crate) fn remove_created_worktree( + &self, + directory: WorktreeDirectory, + creation: WorktreeCreation, + remove: impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>> + Send + 'static, + ) -> impl Future> { + self.0.remove_created_worktree(directory, creation, remove) + } pub fn remove_unregistered_directory( &self, path: PathBuf, @@ -161,6 +172,15 @@ impl Store { ) -> impl Future> { self.0.remove_unregistered_directory(path, remove) } + /// Registers a worktree directory a creation selected until the returned + /// guard drops; the registration takes the ownership lock a removal + /// registers under. + pub(crate) fn begin_worktree_creation( + &self, + path: &std::path::Path, + ) -> impl Future> { + self.0.begin_worktree_creation(path) + } } #[derive(Deserialize)] diff --git a/crates/dim-app-server/src/storage/mod.rs b/crates/dim-app-server/src/storage/mod.rs index b61eacf01b..2729362f6a 100644 --- a/crates/dim-app-server/src/storage/mod.rs +++ b/crates/dim-app-server/src/storage/mod.rs @@ -53,6 +53,7 @@ pub use timeline::testing as timeline_testing; pub fn rebuild_text_index(connection: &rusqlite::Connection) -> dim_agent_runtime::Result<()> { text::backfill(connection) } +pub(crate) use timeline::WorktreeCreation; pub use timeline::{ PreparedWorktree, SessionStore, SessionStorePlugin, SqliteTimelineStore, TurnWindow, WorktreeDirectoryRecord, WorktreeUsage, diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index 68ffff982b..dee6c94f74 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -30,7 +30,7 @@ use rutis::host::{CtxHost, DynPlugin, Effect, Key, TypeKey}; use rutis_bridge::session::{HostDispatch, host_key}; use serde::{Deserialize, Serialize}; use std::{ - collections::{BTreeMap, BTreeSet, HashMap, VecDeque}, + collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}, ops::RangeInclusive, panic::{AssertUnwindSafe, catch_unwind}, path::{Component, Path, PathBuf}, @@ -1276,7 +1276,76 @@ pub struct SessionStore { /// Serializes output ownership across Sessions: a delete's shared-owner /// check, removal and row deletion, and a fork's copy of the output rows, /// so a fork either copies before the removal or sees no rows (ADR 013 D4). + /// A worktree removal holds it for its checks and the registration of its + /// path, not for the deletion itself. ownership: Arc>, + /// The normalized directories a worktree removal is deleting now. A + /// removal registers its path under the ownership lock and clears it when + /// the deletion returns, so the path stays refused for the whole deletion + /// while unrelated work proceeds. Only memory holds it: a process that dies + /// mid-removal leaves a partly deleted directory, which the same removal + /// removes again. + deleting: Arc>>, + /// The normalized directories a worktree creation is building now. A + /// creation registers its chosen directory under the ownership lock before + /// it builds there and holds it until its Session row is written or its + /// rollback hands the path over to a deletion, so a removal of the same + /// path meets this registration instead of deleting a worktree that is + /// still being created. + creating: Arc>>, +} + +/// A path a removal registered as being deleted. The removal's own task owns +/// this: dropping it is what clears the path, so dropping a caller that waits +/// for the removal does not clear it early. +struct Deleting { + store: SessionStore, + path: PathBuf, +} + +impl Drop for Deleting { + fn drop(&mut self) { + self.store + .deleting + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&self.path); + } +} + +/// A directory a creation registered as being built. The creation's own task +/// owns this: dropping it is what clears the path, so a caller that stops +/// waiting for the creation does not clear it before the creation is over. +pub(crate) struct WorktreeCreation { + store: SessionStore, + path: PathBuf, + /// Whether the rollback's removal took this registration over as the + /// path's deletion registration. A registration ends once, so the drop + /// that follows the hand-over cannot clear a registration another + /// creation made for the same path. + handed_over: bool, +} + +impl std::fmt::Debug for WorktreeCreation { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("WorktreeCreation") + .field("path", &self.path) + .finish() + } +} + +impl Drop for WorktreeCreation { + fn drop(&mut self) { + if self.handed_over { + return; + } + self.store + .creating + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&self.path); + } } /// A Session's verified subtree in one recorded worktree. The association @@ -1320,6 +1389,8 @@ impl SessionStore { files, titles, ownership: Arc::new(tokio::sync::Mutex::new(())), + deleting: Arc::new(Mutex::new(HashSet::new())), + creating: Arc::new(Mutex::new(HashSet::new())), } } pub fn timeline_store(&self) -> Arc { @@ -1588,7 +1659,8 @@ impl SessionStore { /// The prepare step of `session.fork`; the ownership lock keeps this copy /// and a delete's output removal apart. [`SqliteTimelineStore::fork_session`] /// copies the rows and writes `config`, the source record's text the - /// caller read, into the fork's record unchanged. + /// caller read, into the fork's record unchanged. A workspace the text + /// names that is being removed refuses the fork. pub async fn fork_session( &self, source: &str, @@ -1599,6 +1671,9 @@ impl SessionStore { crate::protocol::check_session_id(source)?; crate::protocol::check_session_id(fork)?; let _ownership = self.ownership.lock().await; + if let Some(cwd) = config_cwd(config) { + self.reject_deletion(&cwd).await?; + } self.timeline.fork_session(source, fork, at, config).await } /// The source record's configuration text, for a caller that copies it @@ -1626,6 +1701,7 @@ impl SessionStore { let agent = agent_id.to_owned(); let leader = leader.map(str::to_owned); let _ownership = self.ownership.lock().await; + self.reject_deletion(Path::new(&config.cwd)).await?; if !tokio::fs::metadata(&config.cwd) .await .map(|metadata| metadata.is_dir()) @@ -1703,6 +1779,7 @@ impl SessionStore { )); } let _ownership = self.ownership.lock().await; + self.reject_deletion(&directory.root).await?; if !tokio::fs::metadata(&directory.root) .await .map(|metadata| metadata.is_dir()) @@ -1805,13 +1882,15 @@ impl SessionStore { /// Deletes a directory record after its worktree was removed, or after /// its root was verified missing. Refuses while any Session association - /// remains, so the non-cascading foreign key stays satisfied; the caller - /// re-checks under the same ownership lock before its Git removal. - /// Returns whether this database had the record. + /// remains, so the non-cascading foreign key stays satisfied, and while a + /// removal is deleting the same path; the caller re-checks under the same + /// ownership lock before its Git removal. Returns whether this database + /// had the record. pub async fn remove_worktree_directory(&self, directory: WorktreeDirectory) -> Result { let repository = stored_worktree_path(&directory.repository)?.to_owned(); let root = stored_worktree_path(&directory.root)?.to_owned(); let _ownership = self.ownership.lock().await; + self.reject_deletion(Path::new(&root)).await?; self.timeline .db .run(move |connection| { @@ -1843,73 +1922,114 @@ impl SessionStore { .await } - /// Removes one worktree under the store's exclusion: the ownership lock - /// is held from the re-check through `remove` and the record deletion, so - /// a late association or Session row fails this call instead of slipping - /// in. The directory must have no association and no stored Session - /// workspace at or under it; `remove` performs the Git removal and - /// succeeds for a root already verified missing. Returns whether the - /// record was removed. + /// Removes one worktree: the ownership lock is held for the association + /// and Session-workspace checks and for registering `directory.root` as + /// being deleted, then released for `remove` and reacquired to delete the + /// record. A late association or Session creation fails the checks or + /// meets the registered path instead of slipping in, and an unrelated + /// operation proceeds while `remove` runs. The directory must have no + /// association and no stored Session workspace at or under it; `remove` + /// performs the Git removal and succeeds for a root already verified + /// missing. Returns whether the record was removed. pub async fn remove_worktree( &self, directory: WorktreeDirectory, - remove: impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>>, + remove: impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>> + Send + 'static, + ) -> Result { + self.remove_registered_worktree(directory, None, remove) + .await + } + + /// Removes the worktree a failed creation built, as its rollback: inside + /// the ownership lock this removal takes the creation's own registration + /// over as the path's deletion registration, so neither a creation nor a + /// removal registers that path in between. Otherwise the same as + /// [`Self::remove_worktree`]. + pub(crate) async fn remove_created_worktree( + &self, + directory: WorktreeDirectory, + creation: WorktreeCreation, + remove: impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>> + Send + 'static, + ) -> Result { + self.remove_registered_worktree(directory, Some(creation), remove) + .await + } + + async fn remove_registered_worktree( + &self, + directory: WorktreeDirectory, + creation: Option, + remove: impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>> + Send + 'static, ) -> Result { let repository = stored_worktree_path(&directory.repository)?.to_owned(); let root = stored_worktree_path(&directory.root)?.to_owned(); let checked = (repository.clone(), root.clone()); - let _ownership = self.ownership.lock().await; - let used: bool = self - .timeline - .db - .run_read(move |connection| { - connection - .query_row( - "SELECT EXISTS(SELECT 1 FROM session_worktrees \ - WHERE repository=?1 AND root=?2)", - params![checked.0, checked.1], - |row| row.get(0), - ) - .map_err(error) - }) - .await?; - if used { - return Err(AgentError::InvalidInput( - "the worktree directory still has Session associations".into(), - )); - } - let sessions = self.sessions_under_workspace(&directory.root).await?; - if let Some(session) = sessions.first() { - return Err(AgentError::InvalidInput(format!( - "Session {session} uses this worktree" - ))); - } - remove(directory.root.clone()).await?; - let removed = self - .timeline - .db - .run(move |connection| { - connection - .execute( - "DELETE FROM worktree_directories WHERE repository=?1 AND root=?2", - params![repository, root], - ) - .map_err(error) - }) - .await?; - Ok(removed > 0) - } - - /// Removes an unregistered directory under the store's exclusion: the - /// ownership lock is held from the final record and workspace checks - /// through `remove`, so a Session created or a directory recorded after - /// the check fails this call and a creation after the removal re-checks - /// its missing workspace. The checks and the removal run in their own - /// task, so dropping the caller does not release the lock while the - /// removal is still running. The path is a store path, absolute without - /// relative components, and neither a recorded worktree directory nor a - /// stored Session workspace may be at or under it; `remove` re-checks the - /// unregistered facts and performs the deletion. Returns whether the + let path = PathBuf::from(&root); + let store = self.clone(); + tokio::spawn(async move { + let deleting = { + let _ownership = store.ownership.lock().await; + let used: bool = store + .timeline + .db + .run_read(move |connection| { + connection + .query_row( + "SELECT EXISTS(SELECT 1 FROM session_worktrees \ + WHERE repository=?1 AND root=?2)", + params![checked.0, checked.1], + |row| row.get(0), + ) + .map_err(error) + }) + .await?; + if used { + return Err(AgentError::InvalidInput( + "the worktree directory still has Session associations".into(), + )); + } + let sessions = store.sessions_under_workspace(&path).await?; + if let Some(session) = sessions.first() { + return Err(AgentError::InvalidInput(format!( + "Session {session} uses this worktree" + ))); + } + match creation { + Some(creation) => store.begin_deletion_of_creation(creation), + None => store.begin_deletion(&path).await?, + } + }; + remove(path).await?; + let _ownership = store.ownership.lock().await; + let removed = store + .timeline + .db + .run(move |connection| { + connection + .execute( + "DELETE FROM worktree_directories WHERE repository=?1 AND root=?2", + params![repository, root], + ) + .map_err(error) + }) + .await?; + drop(deleting); + Ok(removed > 0) + }) + .await + .map_err(|error| AgentError::Storage(format!("the removal task failed: {error}")))? + } + + /// Removes an unregistered directory: the ownership lock is held for the + /// final record and workspace checks and for registering `path` as being + /// deleted, then released for `remove`. A Session created or a directory + /// recorded after the check fails the checks or meets the registered path, + /// and a creation after the removal re-checks its missing workspace. The + /// work runs in its own task, so dropping the caller neither releases the + /// registration nor stops the deletion. The path is a store path, absolute + /// without relative components, and neither a recorded worktree directory + /// nor a stored Session workspace may be at or under it; `remove` re-checks + /// the unregistered facts and performs the deletion. Returns whether the /// directory was still present when the lock was acquired; `false` means /// another removal already finished. pub async fn remove_unregistered_directory( @@ -1920,36 +2040,147 @@ impl SessionStore { stored_worktree_path(&path)?; let store = self.clone(); tokio::spawn(async move { - let _ownership = store.ownership.lock().await; - match tokio::fs::symlink_metadata(&path).await { - Ok(_) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), - Err(_) => {} - } - let directories = store.worktree_directories().await?; - if let Some(record) = directories - .iter() - .find(|record| record.directory.root.starts_with(&path)) - { - return Err(AgentError::InvalidInput(format!( - "{} is a recorded worktree directory; remove it by task id", - record.directory.root.display() - ))); - } - let sessions = store.sessions_under_workspace(&path).await?; - if let Some(session) = sessions.first() { - return Err(AgentError::InvalidInput(format!( - "Session {session} uses {}", - path.display() - ))); - } + let deleting = { + let _ownership = store.ownership.lock().await; + match tokio::fs::symlink_metadata(&path).await { + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(_) => {} + } + let directories = store.worktree_directories().await?; + if let Some(record) = directories + .iter() + .find(|record| record.directory.root.starts_with(&path)) + { + return Err(AgentError::InvalidInput(format!( + "{} is a recorded worktree directory; remove it by task id", + record.directory.root.display() + ))); + } + let sessions = store.sessions_under_workspace(&path).await?; + if let Some(session) = sessions.first() { + return Err(AgentError::InvalidInput(format!( + "Session {session} uses {}", + path.display() + ))); + } + store.begin_deletion(&path).await? + }; remove(path).await?; + drop(deleting); Ok(true) }) .await .map_err(|error| AgentError::Storage(format!("the removal task failed: {error}")))? } + /// Registers `path` as being deleted until the returned guard drops. The + /// caller holds the ownership lock, so the checks that precede it and this + /// registration are one step for every operation that looks at the same + /// lock. A path that is itself, above or below a path already being + /// removed is refused, which also refuses a second removal of the same + /// worktree, and so is one a creation registered as being built. + async fn begin_deletion(&self, path: &Path) -> Result { + let path = normalized(path).await; + let mut deleting = self + .deleting + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let creating = self + .creating + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(other) = creating.iter().find(|other| overlaps(other, &path)) { + return Err(AgentError::InvalidInput(format!( + "{} is being created", + other.display() + ))); + } + if let Some(other) = deleting.iter().find(|other| overlaps(other, &path)) { + return Err(AgentError::InvalidInput(format!( + "{} is being removed", + other.display() + ))); + } + deleting.insert(path.clone()); + Ok(Deleting { + store: self.clone(), + path, + }) + } + + /// Registers `creation`'s path as being deleted in the same lock hold that + /// ends the creation's own registration. The caller holds the ownership + /// lock, so no creation or removal registers this path in between: it is + /// registered as being created until this call and as being deleted from + /// before the creation's registration ends until the returned guard drops. + fn begin_deletion_of_creation(&self, mut creation: WorktreeCreation) -> Deleting { + let path = creation.path.clone(); + let mut deleting = self + .deleting + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut creating = self + .creating + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + creation.handed_over = true; + creating.remove(&path); + deleting.insert(path.clone()); + Deleting { + store: self.clone(), + path, + } + } + + /// Refuses a workspace or root that a removal is deleting now. The caller + /// holds the ownership lock, which is the same lock a removal registers + /// under, so a path seen as free cannot be registered before this + /// operation records what it does with it. Call it before the caller's own + /// existence check: the end of a deletion clears the registration, and a + /// workspace that deletion removed then fails that check instead. + async fn reject_deletion(&self, path: &Path) -> Result<()> { + let path = normalized(path).await; + let deleting = self + .deleting + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + match deleting.iter().find(|other| overlaps(other, &path)) { + Some(other) => Err(AgentError::InvalidInput(format!( + "{} is being removed", + other.display() + ))), + None => Ok(()), + } + } + + /// Registers the worktree directory a creation selected, until the returned + /// guard drops. This call takes the ownership lock, the same lock a removal + /// registers under, so a path seen as free cannot be registered by a + /// removal before this creation records what it does with it. A path a + /// removal is deleting, or one another creation registered, is refused. + pub(crate) async fn begin_worktree_creation(&self, path: &Path) -> Result { + let path = normalized(path).await; + let _ownership = self.ownership.lock().await; + self.reject_deletion(&path).await?; + let mut creating = self + .creating + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(other) = creating.iter().find(|other| overlaps(other, &path)) { + return Err(AgentError::InvalidInput(format!( + "{} is being created", + other.display() + ))); + } + creating.insert(path.clone()); + Ok(WorktreeCreation { + store: self.clone(), + path, + handed_over: false, + }) + } + /// Lists the Session associations of a recorded directory. An unknown /// directory or a candidate without remaining associations has no usages. pub async fn worktree_usages( @@ -1995,6 +2226,35 @@ fn stored_worktree_path(path: &Path) -> Result<&str> { .ok_or_else(|| error("a worktree path must be UTF-8")) } +/// A path in the form every deletion check compares: the resolved directory, so +/// a route through a symlink and the directory it names overlap. A path that +/// cannot be resolved, such as one already deleted, keeps its own form. +async fn normalized(path: &Path) -> PathBuf { + tokio::fs::canonicalize(path) + .await + .unwrap_or_else(|_| path.to_path_buf()) +} + +/// Whether one path is at or under the other. +fn overlaps(one: &Path, other: &Path) -> bool { + one.starts_with(other) || other.starts_with(one) +} + +/// The workspace a stored Session configuration names, read from the same text +/// `session_catalog` records it from. Text that does not carry one, or carries +/// an empty one, has no workspace to check. +fn config_cwd(config: &str) -> Option { + let cwd = serde_json::from_str::(config) + .ok()? + .get("cwd")? + .as_str()? + .to_owned(); + if cwd.is_empty() { + return None; + } + Some(PathBuf::from(cwd)) +} + /// The Session directory, the `sessionFiles` service and the /// `sessionMetadata` service. Session files live below the FileStorage root /// `files_root`, which is the database directory. diff --git a/crates/dim-app-server/src/worktrees.rs b/crates/dim-app-server/src/worktrees.rs index f4556a11de..b49deacb22 100644 --- a/crates/dim-app-server/src/worktrees.rs +++ b/crates/dim-app-server/src/worktrees.rs @@ -2,11 +2,18 @@ //! //! One Process part owns the root, the task id, the Git calls and the //! list/remove/prune selection. The records stay with SessionStore: creation -//! writes them in the Session's own transaction, and a removal runs under the -//! store's ownership lock so a late association cannot slip in between the -//! re-check and the record deletion. Git is the fact; a record is a candidate. +//! writes them in the Session's own transaction, and a removal re-checks its +//! path and registers it as being deleted under the store's ownership lock +//! before it runs its deletion outside that lock, so a late association or +//! creation meets the registration instead of slipping in. A creation compares +//! its directory with that registration and moves to another task id, and it +//! registers its own directory under the same lock until its Session row is +//! written or its failed creation hands that registration to the removal, so a +//! removal meets the creation too. Git is the fact; a record is a candidate. use crate::methods::ManagementMethods; -use crate::storage::{PreparedWorktree, Store, WorktreeDirectory, WorktreeDirectoryRecord}; +use crate::storage::{ + PreparedWorktree, Store, WorktreeCreation, WorktreeDirectory, WorktreeDirectoryRecord, +}; use dim_agent_capabilities::methods::{ Interruption, MethodCall, MethodDecl, RpcError, params, reply, }; @@ -34,16 +41,29 @@ pub struct ManagedWorktrees { sessions: Arc, #[cfg(feature = "testing")] removal_hold: std::sync::Mutex>>, + #[cfg(feature = "testing")] + creation_hold: std::sync::Mutex>>, + #[cfg(feature = "testing")] + creation_check_hold: std::sync::Mutex>>, + #[cfg(feature = "testing")] + rollback_hold: std::sync::Mutex>>, + #[cfg(feature = "testing")] + task_id_hold: std::sync::Mutex>, } /// A worktree this call created, with what it needs to be reported or /// discarded: the directory, the Session's subtree, the branch and the base. -#[derive(Debug, Clone)] +#[derive(Debug)] pub struct CreatedWorktree { pub task_id: String, pub prepared: PreparedWorktree, pub branch: String, pub base: String, + /// The creation's registration of `prepared.directory.root`: a removal of + /// that path is refused until this value drops, which is after the Session + /// row is written or after the failed creation's rollback took the + /// registration over as the path's deletion registration. + creating: std::sync::Mutex>, } /// One row of `worktree.list`: a recorded directory under the managed root, @@ -147,6 +167,14 @@ impl ManagedWorktrees { sessions, #[cfg(feature = "testing")] removal_hold: std::sync::Mutex::new(None), + #[cfg(feature = "testing")] + creation_hold: std::sync::Mutex::new(None), + #[cfg(feature = "testing")] + creation_check_hold: std::sync::Mutex::new(None), + #[cfg(feature = "testing")] + rollback_hold: std::sync::Mutex::new(None), + #[cfg(feature = "testing")] + task_id_hold: std::sync::Mutex::new(None), } } @@ -168,6 +196,39 @@ impl ManagedWorktrees { } } + /// Names the task id the next allocation tries first, so a test can make a + /// creation meet a path a removal registered. Feature `testing` only. + #[cfg(feature = "testing")] + pub(crate) fn prefer_next_task_id(&self, task_id: &str) { + *self.task_id_hold.lock().expect("task id hold") = Some(task_id.to_owned()); + } + + /// Holds the next creation after its directory check and before it builds + /// there. Feature `testing` only. + #[cfg(feature = "testing")] + pub(crate) fn hold_next_creation(&self) -> Arc { + hold_creation(&self.creation_hold) + } + + /// Holds the next creation after it found its directory free and before it + /// registers that path. Feature `testing` only. + #[cfg(feature = "testing")] + pub(crate) fn hold_next_creation_check(&self) -> Arc { + hold_creation(&self.creation_check_hold) + } + + /// Holds the next failed creation before its rollback removes the worktree + /// it built. Feature `testing` only. + #[cfg(feature = "testing")] + pub(crate) fn hold_next_rollback(&self) -> Arc { + hold_creation(&self.rollback_hold) + } + + #[cfg(feature = "testing")] + fn preferred_task_id(&self) -> Option { + self.task_id_hold.lock().expect("task id hold").take() + } + /// Creates one worktree for `source` at `$HOME/worktrees//` /// and returns the directory and the subtree the new Session starts in. /// The caller records them in the Session creation transaction and calls @@ -232,6 +293,9 @@ impl ManagedWorktrees { let mut last = None; for _ in 0..ALLOCATION_ATTEMPTS { + #[cfg(feature = "testing")] + let task_id = self.preferred_task_id().unwrap_or_else(task_id); + #[cfg(not(feature = "testing"))] let task_id = task_id(); let directory = root.join(&task_id).join(&repo_name); if tokio::fs::try_exists(&directory) @@ -243,6 +307,22 @@ impl ManagedWorktrees { )); continue; } + // A removal registers a path under the ownership lock and clears + // it only when the deletion returns; a directory that registration + // still covers is not built in, even if its files are already gone. + // Registering this directory in the same call keeps a removal that + // starts while it is built away from it. + #[cfg(feature = "testing")] + wait_creation_hold(&self.creation_check_hold).await; + let creating = match self.sessions.begin_worktree_creation(&directory).await { + Ok(creating) => creating, + Err(error) => { + last = Some(error.into()); + continue; + } + }; + #[cfg(feature = "testing")] + wait_creation_hold(&self.creation_hold).await; let branch_name = match branch { Some(branch) => branch.to_owned(), None => format!("dim/{task_id}"), @@ -292,7 +372,7 @@ impl ManagedWorktrees { let root_dir = match canonical(directory.clone()).await { Ok(root_dir) => root_dir, Err(error) => { - self.rollback_add(&repository, &directory, &branch_name) + self.rollback_add(&repository, &directory, &branch_name, Some(creating)) .await; return Err(error); } @@ -300,7 +380,7 @@ impl ManagedWorktrees { let subtree = match checked_subtree(&root_dir, &relative).await { Ok(subtree) => subtree, Err(error) => { - self.rollback_add(&repository, &root_dir, &branch_name) + self.rollback_add(&repository, &root_dir, &branch_name, Some(creating)) .await; return Err(error); } @@ -316,6 +396,7 @@ impl ManagedWorktrees { }, branch: branch_name, base, + creating: std::sync::Mutex::new(Some(creating)), }); } Err(last.unwrap_or_else(|| WorktreeError::Invalid("no task id was free".into()))) @@ -324,44 +405,61 @@ impl ManagedWorktrees { /// Removes a worktree this call just added under the store's ownership /// exclusion, without `--force` and with a token that cannot be cancelled. /// The branch goes only after Git accepted the removal. A Session or - /// content that appeared since the checkout keeps both. - async fn rollback_add(&self, repository: &Path, root: &Path, branch: &str) { + /// content that appeared since the checkout keeps both. The creation's own + /// `registration`, if it has not ended yet, becomes the path's deletion + /// registration in the same lock hold that re-checks the removal, so no + /// creation registers the path in between and the rollback still deletes + /// what it built. + async fn rollback_add( + &self, + repository: &Path, + root: &Path, + branch: &str, + registration: Option, + ) { + #[cfg(feature = "testing")] + wait_creation_hold(&self.rollback_hold).await; let directory = WorktreeDirectory { repository: repository.to_owned(), root: root.to_owned(), }; let repository = directory.repository.clone(); let branch = branch.to_owned(); - let _ = self - .sessions - .remove_worktree(directory, move |root| { - Box::pin(async move { - let text = root.to_str().ok_or_else(|| { - AgentError::InvalidInput("the worktree path is not UTF-8".into()) - })?; - let cancel = CancellationToken::new(); - git( - &repository, - &["worktree", "remove", text], - &cancel, - GIT_WRITE_TIMEOUT, - ) - .await - .map_err(|error| AgentError::Storage(error.message().to_owned()))?; - if let Some(parent) = root.parent() { - let _ = tokio::fs::remove_dir(parent).await; - } - let _ = git( - &repository, - &["branch", "-D", &branch], - &cancel, - GIT_WRITE_TIMEOUT, - ) - .await; - Ok(()) - }) + let remove = move |root: PathBuf| -> BoxFuture<'static, Result<(), AgentError>> { + Box::pin(async move { + let text = root.to_str().ok_or_else(|| { + AgentError::InvalidInput("the worktree path is not UTF-8".into()) + })?; + let cancel = CancellationToken::new(); + git( + &repository, + &["worktree", "remove", text], + &cancel, + GIT_WRITE_TIMEOUT, + ) + .await + .map_err(|error| AgentError::Storage(error.message().to_owned()))?; + if let Some(parent) = root.parent() { + let _ = tokio::fs::remove_dir(parent).await; + } + let _ = git( + &repository, + &["branch", "-D", &branch], + &cancel, + GIT_WRITE_TIMEOUT, + ) + .await; + Ok(()) }) - .await; + }; + let _ = match registration { + Some(registration) => { + self.sessions + .remove_created_worktree(directory, registration, remove) + .await + } + None => self.sessions.remove_worktree(directory, remove).await, + }; } /// Removes what a failed creation made: the worktree and the branch this @@ -373,6 +471,7 @@ impl ManagedWorktrees { &created.prepared.directory.repository, &created.prepared.directory.root, &created.branch, + created.take_creation(), ) .await; } @@ -911,6 +1010,27 @@ async fn git( .map_err(|_| WorktreeError::Git("Git returned non-UTF-8 output".into())) } +/// Feature `testing`: arms one hold slot and answers the hold the next creation +/// or rollback at that slot waits on. +#[cfg(feature = "testing")] +fn hold_creation( + slot: &std::sync::Mutex>>, +) -> Arc { + let hold = Arc::new(crate::WorktreeCreationHold::default()); + *slot.lock().expect("creation hold") = Some(hold.clone()); + hold +} + +/// Feature `testing`: waits at the slot if it is armed. Feature `testing` only. +#[cfg(feature = "testing")] +async fn wait_creation_hold(slot: &std::sync::Mutex>>) { + let hold = slot.lock().expect("creation hold").take(); + if let Some(hold) = hold { + hold.reached.notify_one(); + hold.release.notified().await; + } +} + /// Whether Git definitively answers that `root` is not a worktree of its own. /// A timeout, spawn failure, cancellation or any other Git error is not an /// answer: the caller must not fall back to deleting the directory. @@ -1078,7 +1198,8 @@ async fn checked_subtree(root: &Path, relative: &Path) -> Result Result<(), WorktreeError> { match tokio::fs::symlink_metadata(entry).await { Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {} @@ -1104,7 +1225,7 @@ async fn check_unregistered_entry(entry: &Path) -> Result<(), WorktreeError> { /// managed root without a `.git` entry, and without `force` none has content. /// Returns the empty children a non-force removal deletes. The unregistered /// condition is the absence of `.git`, so these are filesystem checks only and -/// no Git subprocess runs under the ownership lock. +/// the removal runs them without the ownership lock. async fn check_unregistered_children( entry: &Path, root: &Path, @@ -1200,9 +1321,12 @@ async fn check_unregistered_tree(entry: &Path) -> Result<(), WorktreeError> { } /// A task directory whose checks passed. `force` removes everything; otherwise -/// only the plain empty subdirectories the check recorded are removed, each -/// without recursion, so content that appears after the check fails the -/// removal with `worktree_in_use` instead of being deleted. +/// only the plain empty subdirectories the check recorded are removed, each by +/// name from an open directory handle on Unix, so content that appears after +/// the check fails the removal with `worktree_in_use` instead of being deleted +/// and a task directory or child swapped for a symlink cannot redirect the +/// removal. A platform without that handle-relative deletion refuses the +/// non-force removal instead of deleting by path. async fn remove_checked_entry( entry: &Path, empty_children: &[PathBuf], @@ -1213,24 +1337,93 @@ async fn remove_checked_entry( .await .map_err(|error| WorktreeError::Store(error.to_string())); } + let entry = entry.to_path_buf(); + let children = empty_children.to_vec(); + tokio::task::spawn_blocking(move || remove_empty_directories(&entry, &children)) + .await + .map_err(|error| WorktreeError::Store(format!("the removal task failed: {error}")))? +} + +/// Removes the recorded empty children and then the task directory, each by +/// name from an open directory handle. A name this removes is never resolved +/// through a symlink, so replacing the task directory or one of its children +/// with a symlink after the check refuses the removal instead of deleting a +/// same-named directory outside the managed root. +#[cfg(unix)] +fn remove_empty_directories(entry: &Path, empty_children: &[PathBuf]) -> Result<(), WorktreeError> { + let directory = open_plain_directory(entry)?; for child in empty_children { - remove_empty_dir(child).await?; + let name = child.file_name().ok_or_else(|| { + WorktreeError::InUse(format!("{} is not a directory entry", child.display())) + })?; + remove_entry(&directory, name, child)?; } - remove_empty_dir(entry).await + let parent = entry + .parent() + .ok_or_else(|| WorktreeError::InUse(format!("{} has no parent", entry.display())))?; + let parent = open_plain_directory(parent)?; + let name = entry.file_name().ok_or_else(|| { + WorktreeError::InUse(format!("{} is not a directory entry", entry.display())) + })?; + remove_entry(&parent, name, entry) } -/// Remove one directory only while it is still empty. -async fn remove_empty_dir(path: &Path) -> Result<(), WorktreeError> { - match tokio::fs::remove_dir(path).await { - Ok(()) => Ok(()), - Err(error) if error.kind() == std::io::ErrorKind::DirectoryNotEmpty => { - Err(WorktreeError::InUse(format!( - "{} is not empty; --force removes it", - path.display() - ))) - } - Err(error) => Err(WorktreeError::Store(error.to_string())), +/// Opens `path` as a directory without following a symlink at it. +#[cfg(unix)] +fn open_plain_directory(path: &Path) -> Result { + use std::os::unix::fs::OpenOptionsExt; + std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(path) + .map_err(|error| match error.raw_os_error() { + Some(libc::ELOOP | libc::ENOTDIR) => { + WorktreeError::InUse(format!("{} is not a plain directory", path.display())) + } + _ => WorktreeError::Store(format!("{}: {error}", path.display())), + }) +} + +/// Removes the directory `name` in `directory`, only while it is empty. +#[cfg(unix)] +fn remove_entry(directory: &std::fs::File, name: &OsStr, path: &Path) -> Result<(), WorktreeError> { + use std::os::fd::AsRawFd; + use std::os::unix::ffi::OsStrExt; + let name = std::ffi::CString::new(name.as_bytes()) + .map_err(|_| WorktreeError::InUse(format!("{} is not a directory name", path.display())))?; + // SAFETY: `directory` is an open handle for the call and `name` is a live + // NUL-terminated string. + if unsafe { libc::unlinkat(directory.as_raw_fd(), name.as_ptr(), libc::AT_REMOVEDIR) } == 0 { + return Ok(()); } + let error = std::io::Error::last_os_error(); + Err(match error.raw_os_error() { + Some(libc::ENOTEMPTY | libc::EEXIST) => WorktreeError::InUse(format!( + "{} is not empty; --force removes it", + path.display() + )), + Some(libc::ENOTDIR | libc::ELOOP) => { + WorktreeError::InUse(format!("{} is not a plain directory", path.display())) + } + _ => WorktreeError::Store(format!("{}: {error}", path.display())), + }) +} + +/// Refuses the non-force removal. A non-Unix target deletes a directory by +/// path and offers no ready-made deletion of only an empty directory relative +/// to an open directory handle, so a reparse point swapped into a path +/// component after the check could redirect the deletion outside the managed +/// root. `--force` removes the tree with `std::fs::remove_dir_all`, which walks +/// it through directory handles and does not follow a reparse point inside it. +#[cfg(not(unix))] +fn remove_empty_directories( + entry: &Path, + _empty_children: &[PathBuf], +) -> Result<(), WorktreeError> { + Err(WorktreeError::InUse(format!( + "{} is an unregistered directory; --force removes it on this platform", + entry.display() + ))) } /// A recorded root that exists but Git no longer names: there is no working @@ -1349,6 +1542,15 @@ impl CreatedWorktree { branch: self.branch.clone(), } } + + /// Takes this creation's registration, if the creation still holds it, so + /// its rollback can hand it over to the deletion of the path. + fn take_creation(&self) -> Option { + self.creating + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + } } /// The `worktree` management namespace: host commands that never take part in @@ -1569,6 +1771,7 @@ mod tests { /// Content that appears in the task directory after the check must refuse /// the non-force removal instead of being deleted with the directory. + #[cfg(unix)] #[tokio::test] async fn content_that_appears_after_the_check_is_not_deleted() { let entry = scratch("late-content"); @@ -1587,8 +1790,57 @@ mod tests { std::fs::remove_dir_all(&entry).unwrap(); } + /// A task directory swapped for a symlink after the check must not + /// redirect the recorded empty child removal outside the managed root. + #[cfg(unix)] + #[tokio::test] + async fn a_swapped_task_directory_does_not_redirect_the_removal() { + let base = scratch("swapped-entry"); + let entry = base.join("aaaaaa"); + let victim = base.join("victim"); + std::fs::create_dir_all(entry.join("repo")).unwrap(); + std::fs::create_dir_all(victim.join("repo")).unwrap(); + let children = vec![entry.join("repo")]; + std::fs::rename(&entry, base.join("moved")).unwrap(); + std::os::unix::fs::symlink(&victim, &entry).unwrap(); + let error = remove_checked_entry(&entry, &children, false) + .await + .expect_err("a redirected task directory must refuse the removal"); + assert!( + matches!(&error, WorktreeError::InUse(message) if message.contains("not a plain directory")), + "{error:?}" + ); + assert!(victim.join("repo").is_dir()); + std::fs::remove_dir_all(&base).unwrap(); + } + + /// A child swapped for a symlink after the check is not followed: the + /// directory it names is left alone. + #[cfg(unix)] + #[tokio::test] + async fn a_swapped_child_does_not_redirect_the_removal() { + let base = scratch("swapped-child"); + let entry = base.join("aaaaaa"); + let victim = base.join("victim"); + std::fs::create_dir_all(&entry).unwrap(); + std::fs::create_dir_all(victim.join("repo")).unwrap(); + let children = vec![entry.join("repo")]; + std::os::unix::fs::symlink(victim.join("repo"), entry.join("repo")).unwrap(); + let error = remove_checked_entry(&entry, &children, false) + .await + .expect_err("a redirected child must refuse the removal"); + assert!( + matches!(&error, WorktreeError::InUse(message) if message.contains("not a plain directory")), + "{error:?}" + ); + assert!(victim.join("repo").is_dir()); + assert!(entry.is_dir()); + std::fs::remove_dir_all(&base).unwrap(); + } + /// Content that appears in a subdirectory the check recorded as empty must /// refuse the removal before that subdirectory is deleted. + #[cfg(unix)] #[tokio::test] async fn content_that_appears_in_a_checked_child_is_not_deleted() { let entry = scratch("late-child"); @@ -1606,4 +1858,26 @@ mod tests { assert!(child.is_dir()); std::fs::remove_dir_all(&entry).unwrap(); } + + /// A non-Unix target deletes a directory by path, so a reparse point + /// swapped in after the check could redirect the non-force removal; this + /// path refuses and `--force` removes the tree instead. + #[cfg(not(unix))] + #[tokio::test] + async fn a_path_based_removal_refuses_an_unregistered_directory() { + let entry = scratch("path-based-removal"); + let child = entry.join("repo"); + std::fs::create_dir_all(&child).unwrap(); + let error = remove_checked_entry(&entry, std::slice::from_ref(&child), false) + .await + .expect_err("a path-based removal must refuse the non-force removal"); + assert_eq!(error.code(), "worktree_in_use"); + assert!( + matches!(&error, WorktreeError::InUse(message) if message.contains("--force")), + "{error:?}" + ); + assert!(child.is_dir()); + remove_checked_entry(&entry, &[], true).await.unwrap(); + assert!(!entry.exists()); + } } diff --git a/crates/dim-app-server/tests/transport_flow/process_typescript.rs b/crates/dim-app-server/tests/transport_flow/process_typescript.rs index 8f506fc17d..e4276e57b1 100644 --- a/crates/dim-app-server/tests/transport_flow/process_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/process_typescript.rs @@ -1806,7 +1806,7 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( cwd: held.to_string_lossy().into_owned(), ..Default::default() }; - let mut concurrent_creation = { + let concurrent_creation = { let store = store.clone(); let agent_id = agent_id.clone(); tokio::spawn(async move { @@ -1823,20 +1823,19 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( .await }) }; + let refused = tokio::time::timeout(Duration::from_secs(10), concurrent_creation) + .await + .expect("the path being removed is refused without waiting") + .unwrap() + .expect_err("the path being removed is refused"); assert!( - tokio::time::timeout(Duration::from_millis(50), &mut concurrent_creation) - .await - .is_err(), - "creation must remain excluded until the unregistered removal settles" + matches!(&refused, AgentError::InvalidInput(message) if message.contains("is being removed")), + "{refused:?}" ); assert_ok(&client.rpc("storefixture.release", json!({})).await); let removed = client.response(removal).await; assert_ok(&removed); assert_eq!(removed["result"], json!({"removed":true})); - assert!(matches!( - concurrent_creation.await.unwrap(), - Err(AgentError::InvalidInput(_)) - )); assert!(!held.exists()); let refused = client .rpc( @@ -1862,7 +1861,7 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( std::fs::read_to_string(&ready).unwrap(), workspace.to_string_lossy() ); - let mut concurrent_creation = { + let concurrent_creation = { let store = store.clone(); tokio::spawn(async move { store @@ -1878,20 +1877,19 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( .await }) }; + let refused = tokio::time::timeout(Duration::from_secs(10), concurrent_creation) + .await + .expect("the path being removed is refused without waiting") + .unwrap() + .expect_err("the path being removed is refused"); assert!( - tokio::time::timeout(Duration::from_millis(50), &mut concurrent_creation) - .await - .is_err(), - "creation must remain excluded until the foreign removal settles" + matches!(&refused, AgentError::InvalidInput(message) if message.contains("is being removed")), + "{refused:?}" ); assert_ok(&client.rpc("storefixture.release", json!({})).await); let removed = client.response(removal).await; assert_ok(&removed); assert_eq!(removed["result"], json!({"removed":true})); - assert!(matches!( - concurrent_creation.await.unwrap(), - Err(AgentError::InvalidInput(_)) - )); assert!(!workspace.exists()); assert!(store.worktree_directories().await.unwrap().is_empty()); assert!(!store.has_records("late").await.unwrap()); diff --git a/crates/dim-app-server/tests/transport_flow/worktrees.rs b/crates/dim-app-server/tests/transport_flow/worktrees.rs index dfd67d8634..25265139a9 100644 --- a/crates/dim-app-server/tests/transport_flow/worktrees.rs +++ b/crates/dim-app-server/tests/transport_flow/worktrees.rs @@ -1354,8 +1354,8 @@ async fn unregistered_removal_refuses_a_recorded_directory_before_the_callback() } /// A `.git` entry that appears after the content check refuses the removal: -/// the store re-checks the unregistered facts under the ownership lock before -/// it deletes anything. +/// the removal re-checks the unregistered facts in its own task, after its +/// path is registered as being deleted, before it deletes anything. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn unregistered_remove_refuses_a_git_entry_added_after_the_content_check() { let work = Work::new(); @@ -1393,9 +1393,9 @@ async fn unregistered_remove_refuses_a_git_entry_added_after_the_content_check() server.join().await.unwrap(); } -/// A removal that holds the ownership lock first deletes the directory, so a -/// creation queued behind it fails its own cwd check instead of leaving a -/// Session that points at a deleted workspace. +/// A removal registers its path under the ownership lock before it deletes +/// the directory, so a creation on that path is refused without waiting; +/// after the removal the deleted workspace fails the creation's own check. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn session_creation_after_an_unregistered_removal_fails_its_workspace_check() { let work = Work::new(); @@ -1426,7 +1426,7 @@ async fn session_creation_after_an_unregistered_removal_fails_its_workspace_chec }); tokio::time::timeout(Duration::from_secs(30), reached.notified()) .await - .expect("the removal holds the ownership lock"); + .expect("the removal reaches its deletion step"); let config = SessionConfig { cwd: task.to_string_lossy().into_owned(), ..Default::default() @@ -1447,13 +1447,33 @@ async fn session_creation_after_an_unregistered_removal_fails_its_workspace_chec .await } }); - release.notify_one(); - let error = creation + let refused = tokio::time::timeout(Duration::from_secs(10), creation) .await + .expect("the path being removed is refused without waiting") .unwrap() - .expect_err("the removed workspace fails the creation check"); - assert!(error.to_string().contains("no longer exists"), "{error}"); + .expect_err("the path being removed is refused"); + assert!( + matches!(&refused, AgentError::InvalidInput(message) if message.contains("is being removed")), + "{refused:?}" + ); + release.notify_one(); removal.await.unwrap().unwrap(); + let after = store + .create_owned_session( + "fixture-session-after", + &SessionConfig { + cwd: task.to_string_lossy().into_owned(), + ..Default::default() + }, + "fixture-agent", + 4, + None, + SessionOrigin::Client, + None, + ) + .await + .expect_err("the removed workspace fails the creation check"); + assert!(after.to_string().contains("no longer exists"), "{after}"); assert!(!task.exists()); assert!(!store.has_records("fixture-session").await.unwrap()); server.shutdown(); @@ -1534,10 +1554,10 @@ async fn unregistered_remove_reports_not_found_when_another_removal_won() { server.join().await.unwrap(); } -/// Dropping the caller of an unregistered removal must not release the -/// ownership lock while the deletion is still running. +/// Dropping the caller of an unregistered removal stops neither the deletion +/// nor the path's registration, which ends only when the deletion returns. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn dropping_the_caller_keeps_the_removal_lock_until_the_deletion_finishes() { +async fn dropping_the_caller_keeps_the_removal_until_the_deletion_finishes() { let work = Work::new(); let server = host(&work).await; let store = server.service::().unwrap(); @@ -1549,11 +1569,13 @@ async fn dropping_the_caller_keeps_the_removal_lock_until_the_deletion_finishes( let agent_id = listed["result"][0]["agentId"].as_str().unwrap().to_owned(); let reached = Arc::new(tokio::sync::Notify::new()); let release = Arc::new(tokio::sync::Notify::new()); + let finished = Arc::new(tokio::sync::Notify::new()); let removal = tokio::spawn({ let store = store.clone(); let task = task.clone(); let reached = reached.clone(); let release = release.clone(); + let finished = finished.clone(); async move { store .remove_unregistered_directory(task, move |path| { @@ -1562,7 +1584,9 @@ async fn dropping_the_caller_keeps_the_removal_lock_until_the_deletion_finishes( release.notified().await; tokio::fs::remove_dir_all(&path) .await - .map_err(|error| AgentError::Storage(error.to_string())) + .map_err(|error| AgentError::Storage(error.to_string()))?; + finished.notify_one(); + Ok(()) }) }) .await @@ -1570,7 +1594,7 @@ async fn dropping_the_caller_keeps_the_removal_lock_until_the_deletion_finishes( }); tokio::time::timeout(Duration::from_secs(30), reached.notified()) .await - .expect("the removal holds the ownership lock"); + .expect("the removal reaches its deletion step"); removal.abort(); assert!(removal.await.unwrap_err().is_cancelled()); let config = SessionConfig { @@ -1593,12 +1617,19 @@ async fn dropping_the_caller_keeps_the_removal_lock_until_the_deletion_finishes( .await } }); - release.notify_one(); - let error = creation + let refused = tokio::time::timeout(Duration::from_secs(10), creation) .await + .expect("the path being removed is refused after its caller is dropped") .unwrap() - .expect_err("the removed workspace fails the creation check"); - assert!(error.to_string().contains("no longer exists"), "{error}"); + .expect_err("the path being removed is refused"); + assert!( + matches!(&refused, AgentError::InvalidInput(message) if message.contains("is being removed")), + "{refused:?}" + ); + release.notify_one(); + tokio::time::timeout(Duration::from_secs(10), finished.notified()) + .await + .expect("the deletion finishes after its caller is gone"); assert!(!task.exists()); server.shutdown(); server.join().await.unwrap(); @@ -1800,3 +1831,790 @@ async fn committed_shell_completion_recovers_after_notice_failure_and_host_loss( server.join().await.unwrap(); } } + +/// An unregistered removal refuses its own path, its parent and its children +/// for the whole deletion and does not hold the ownership lock while it +/// deletes, so an unrelated creation completes while the deletion runs. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_unregistered_removal_refuses_its_path_without_holding_the_lock() { + let work = Work::new(); + let server = host(&work).await; + let store = server.service::().unwrap(); + let task = unregistered_task(&work, "aaaaaa"); + std::fs::create_dir_all(task.join("repo")).unwrap(); + let reached = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let removal = tokio::spawn({ + let store = store.clone(); + let task = task.clone(); + let reached = reached.clone(); + let release = release.clone(); + async move { + store + .remove_unregistered_directory(task, move |path| { + Box::pin(async move { + reached.notify_one(); + release.notified().await; + tokio::fs::remove_dir_all(&path) + .await + .map_err(|error| AgentError::Storage(error.to_string())) + }) + }) + .await + } + }); + tokio::time::timeout(Duration::from_secs(30), reached.notified()) + .await + .expect("the removal reaches its deletion step"); + + let mut client = Client::new_version(&server, false, 3).await; + let unrelated = tokio::time::timeout( + Duration::from_secs(10), + client.rpc("session.create", json!({"cwd": work.repo})), + ) + .await + .expect("an unrelated creation does not wait for the removal"); + assert_ok(&unrelated); + for path in [task.clone(), task.join("repo"), work.home.join("worktrees")] { + let refused = tokio::time::timeout( + Duration::from_secs(10), + client.rpc("session.create", json!({"cwd": path})), + ) + .await + .unwrap_or_else(|_| panic!("a creation on {} waits for the removal", path.display())); + assert!( + refused["error"]["message"] + .as_str() + .is_some_and(|message| message.contains("is being removed")), + "{refused}" + ); + } + let repeated = tokio::time::timeout( + Duration::from_secs(10), + client.rpc("worktree.remove", json!({"taskId": "aaaaaa"})), + ) + .await + .expect("a repeated removal does not wait for the first"); + assert_eq!(repeated["error"]["data"]["appError"], "worktree_in_use"); + + let created = client + .rpc( + "session.create", + json!({"cwd": work.repo.join("packages/a")}), + ) + .await; + assert_ok(&created); + let session_id = created["result"]["sessionId"].as_str().unwrap().to_owned(); + let associated = tokio::time::timeout( + Duration::from_secs(10), + store.associate_worktree( + &session_id, + WorktreeDirectory { + repository: work.repo.clone(), + root: task.clone(), + }, + task.clone(), + ), + ) + .await + .expect("an association does not wait for the removal") + .expect_err("the path being removed cannot be associated"); + assert!( + matches!(&associated, AgentError::InvalidInput(message) if message.contains("is being removed")), + "{associated:?}" + ); + + release.notify_one(); + assert!(removal.await.unwrap().unwrap()); + assert!(!task.exists()); + server.shutdown(); + server.join().await.unwrap(); +} + +/// A recorded removal runs its Git removal outside the ownership lock: the +/// recorded root and its task directory stay refused while it runs, and an +/// unrelated creation completes. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_recorded_removal_refuses_its_path_without_holding_the_lock() { + let work = Work::new(); + let server = host(&work).await; + let store = server.service::().unwrap(); + let mut client = Client::new_version(&server, false, 3).await; + let created = client + .rpc("session.create", json!({"cwd": work.repo, "worktree": {}})) + .await; + assert_ok(&created); + let session_id = created["result"]["sessionId"].as_str().unwrap().to_owned(); + let task_id = created["result"]["worktree"]["taskId"] + .as_str() + .unwrap() + .to_owned(); + let root = PathBuf::from(created["result"]["worktree"]["root"].as_str().unwrap()); + let repository = PathBuf::from( + created["result"]["worktree"]["repository"] + .as_str() + .unwrap(), + ); + assert_ok( + &client + .rpc("session.delete", json!({"sessionId": session_id})) + .await, + ); + let reached = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let removal = tokio::spawn({ + let store = store.clone(); + let root = root.clone(); + let reached = reached.clone(); + let release = release.clone(); + async move { + store + .remove_worktree(WorktreeDirectory { repository, root }, move |path| { + Box::pin(async move { + reached.notify_one(); + release.notified().await; + tokio::fs::remove_dir_all(&path) + .await + .map_err(|error| AgentError::Storage(error.to_string())) + }) + }) + .await + } + }); + tokio::time::timeout(Duration::from_secs(30), reached.notified()) + .await + .expect("the removal reaches its Git removal"); + + let unrelated = tokio::time::timeout( + Duration::from_secs(10), + client.rpc( + "session.create", + json!({"cwd": work.repo.join("packages/a")}), + ), + ) + .await + .expect("an unrelated creation does not wait for the removal"); + assert_ok(&unrelated); + let parent = root.parent().unwrap().to_path_buf(); + for path in [root.clone(), parent] { + let refused = tokio::time::timeout( + Duration::from_secs(10), + client.rpc("session.create", json!({"cwd": path})), + ) + .await + .unwrap_or_else(|_| panic!("a creation on {} waits for the removal", path.display())); + assert!( + refused["error"]["message"] + .as_str() + .is_some_and(|message| message.contains("is being removed")), + "{refused}" + ); + } + let repeated = client + .rpc("worktree.remove", json!({"taskId": task_id, "force": true})) + .await; + assert_eq!(repeated["error"]["data"]["appError"], "worktree_in_use"); + + release.notify_one(); + assert!(removal.await.unwrap().unwrap()); + assert!(!root.exists()); + server.shutdown(); + server.join().await.unwrap(); +} + +/// A removal that fails reports the error to its caller and keeps no +/// registration: the workspace is usable again as soon as the failure returns. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_failed_removal_reports_the_error_and_keeps_no_registration() { + let work = Work::new(); + let server = host(&work).await; + let store = server.service::().unwrap(); + let task = unregistered_task(&work, "aaaaaa"); + std::fs::create_dir_all(task.join("repo")).unwrap(); + let reached = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let removal = tokio::spawn({ + let store = store.clone(); + let task = task.clone(); + let reached = reached.clone(); + let release = release.clone(); + async move { + store + .remove_unregistered_directory(task, move |_| { + Box::pin(async move { + reached.notify_one(); + release.notified().await; + Err(AgentError::Storage("the deletion failed".into())) + }) + }) + .await + } + }); + tokio::time::timeout(Duration::from_secs(30), reached.notified()) + .await + .expect("the removal reaches its deletion step"); + let mut client = Client::new_version(&server, false, 3).await; + let refused = tokio::time::timeout( + Duration::from_secs(10), + client.rpc("session.create", json!({"cwd": task})), + ) + .await + .expect("the path being removed is refused without waiting"); + assert!( + refused["error"]["message"] + .as_str() + .is_some_and(|message| message.contains("is being removed")), + "{refused}" + ); + release.notify_one(); + let error = removal + .await + .unwrap() + .expect_err("the failed deletion reports its error"); + assert!(error.to_string().contains("the deletion failed"), "{error}"); + let created = client.rpc("session.create", json!({"cwd": task})).await; + assert_ok(&created); + assert!(task.join("repo").is_dir()); + server.shutdown(); + server.join().await.unwrap(); +} + +/// A stored configuration that names no workspace has nothing to compare, so +/// a removal elsewhere does not refuse its fork. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_fork_without_a_workspace_is_not_refused_by_an_unrelated_removal() { + let work = Work::new(); + let server = host(&work).await; + let store = server.service::().unwrap(); + let mut client = Client::new_version(&server, false, 3).await; + let listed = client.rpc("agent.list", json!({})).await; + assert_ok(&listed); + let agent_id = listed["result"][0]["agentId"].as_str().unwrap().to_owned(); + let config = SessionConfig { + cwd: work.repo.to_string_lossy().into_owned(), + ..Default::default() + }; + store + .create_owned_session( + "fork-source", + &config, + &agent_id, + 4, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap(); + let task = unregistered_task(&work, "aaaaaa"); + std::fs::create_dir_all(task.join("repo")).unwrap(); + let reached = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let removal = tokio::spawn({ + let store = store.clone(); + let task = task.clone(); + let reached = reached.clone(); + let release = release.clone(); + async move { + store + .remove_unregistered_directory(task, move |path| { + Box::pin(async move { + reached.notify_one(); + release.notified().await; + tokio::fs::remove_dir_all(&path) + .await + .map_err(|error| AgentError::Storage(error.to_string())) + }) + }) + .await + } + }); + tokio::time::timeout(Duration::from_secs(30), reached.notified()) + .await + .expect("the removal reaches its deletion step"); + store + .fork_session("fork-source", "fork-no-workspace", 0, r#"{"cwd":""}"#) + .await + .expect("a stored configuration without a workspace is not refused"); + release.notify_one(); + assert!(removal.await.unwrap().unwrap()); + assert!(store.has_records("fork-no-workspace").await.unwrap()); + server.shutdown(); + server.join().await.unwrap(); +} + +/// A creation that would pick the task id of a directory a removal registered +/// moves to another id instead: it never builds at, under or above the path +/// being deleted, so the removed path keeps no directory. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_creation_does_not_build_at_a_path_a_removal_is_deleting() { + let work = Work::new(); + let server = host(&work).await; + let store = server.service::().unwrap(); + let mut client = Client::new_version(&server, false, 3).await; + let created = client + .rpc("session.create", json!({"cwd": work.repo, "worktree": {}})) + .await; + assert_ok(&created); + let session_id = created["result"]["sessionId"].as_str().unwrap().to_owned(); + let task_id = created["result"]["worktree"]["taskId"] + .as_str() + .unwrap() + .to_owned(); + let root = PathBuf::from(created["result"]["worktree"]["root"].as_str().unwrap()); + let repository = PathBuf::from( + created["result"]["worktree"]["repository"] + .as_str() + .unwrap(), + ); + assert_ok( + &client + .rpc("session.delete", json!({"sessionId": session_id})) + .await, + ); + let removed = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let removal = tokio::spawn({ + let store = store.clone(); + let root = root.clone(); + let removed = removed.clone(); + let release = release.clone(); + let removal_repository = repository.clone(); + async move { + store + .remove_worktree(WorktreeDirectory { repository, root }, move |path| { + Box::pin(async move { + tokio::task::spawn_blocking(move || { + git( + &removal_repository, + &["worktree", "remove", path.to_str().unwrap()], + ); + }) + .await + .map_err(|error| AgentError::Storage(error.to_string()))?; + removed.notify_one(); + release.notified().await; + Ok(()) + }) + }) + .await + } + }); + tokio::time::timeout(Duration::from_secs(30), removed.notified()) + .await + .expect("the removal deletes the directory"); + assert!( + server.prefer_next_worktree_task_id(&task_id), + "the ManagedWorktrees part exists" + ); + + let created = tokio::time::timeout( + Duration::from_secs(10), + client.rpc( + "session.create", + json!({"cwd": work.repo, "worktree": {"branch": "reused"}}), + ), + ) + .await + .expect("a creation does not wait for the removal"); + assert_ok(&created); + let replacement = PathBuf::from(created["result"]["worktree"]["root"].as_str().unwrap()); + assert_ne!( + replacement, root, + "a creation must not build at the path a removal is deleting" + ); + assert!(!root.exists(), "the removed path keeps no directory"); + + release.notify_one(); + assert!(removal.await.unwrap().unwrap()); + assert!(!root.exists()); + server.shutdown(); + server.join().await.unwrap(); +} + +/// A removal of the task directory a creation is building in is refused: the +/// creation registers the directory it chose under the ownership lock before it +/// builds there and holds the registration until its Session row is written, so +/// the removal cannot delete the worktree in between. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_removal_does_not_delete_a_path_a_creation_is_building() { + let work = Work::new(); + let server = host(&work).await; + let task = unregistered_task(&work, "aaaaaa"); + let hold = server + .hold_next_worktree_creation() + .expect("the ManagedWorktrees part exists"); + assert!( + server.prefer_next_worktree_task_id("aaaaaa"), + "the ManagedWorktrees part exists" + ); + let mut creator = Client::new_version(&server, false, 3).await; + let repo = work.repo.clone(); + let creation = tokio::spawn(async move { + creator + .rpc("session.create", json!({"cwd": repo, "worktree": {}})) + .await + }); + tokio::time::timeout(Duration::from_secs(30), hold.reached.notified()) + .await + .expect("the creation checks its directory before it builds"); + let mut remover = Client::new_version(&server, false, 3).await; + let refused = tokio::time::timeout( + Duration::from_secs(10), + remover.rpc("worktree.remove", json!({"taskId": "aaaaaa"})), + ) + .await + .expect("a removal of a path being created does not wait"); + assert_eq!(refused["error"]["data"]["appError"], "worktree_in_use"); + assert!( + refused["error"]["message"] + .as_str() + .is_some_and(|message| message.contains("is being created")), + "{refused}" + ); + hold.release.notify_one(); + let created = creation.await.unwrap(); + assert_ok(&created); + let root = PathBuf::from(created["result"]["worktree"]["root"].as_str().unwrap()); + assert_eq!( + root, + task.join("repo"), + "the creation builds where it registered" + ); + assert!( + root.is_dir(), + "the creation keeps the directory it registered" + ); + let session_id = created["result"]["sessionId"].as_str().unwrap().to_owned(); + assert_ok( + &remover + .rpc("session.delete", json!({"sessionId": session_id})) + .await, + ); + let removed = tokio::time::timeout( + Duration::from_secs(10), + remover.rpc("worktree.remove", json!({"taskId": "aaaaaa"})), + ) + .await + .expect("the path is removable after its creation finishes"); + assert_ok(&removed); + assert_eq!(removed["result"], json!({"removed": true})); + assert!(!root.exists()); + server.shutdown(); + server.join().await.unwrap(); +} + +/// A creation that fails after it built its worktree still removes it: the +/// rollback ends the creation's own registration first, so the path it holds +/// does not refuse the removal the rollback needs. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_failed_creation_removes_the_worktree_it_registered() { + let work = Work::new(); + let server = host(&work).await; + let repo = work.repo.clone(); + git(&repo, &["rm", "--cached", "-r", "-q", "packages/b"]); + git( + &repo, + &[ + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "commit", + "-qm", + "drop the subtree", + ], + ); + assert!( + server.prefer_next_worktree_task_id("aaaaaa"), + "the ManagedWorktrees part exists" + ); + let mut client = Client::new_version(&server, false, 3).await; + let failed = tokio::time::timeout( + Duration::from_secs(30), + client.rpc( + "session.create", + json!({"cwd": repo.join("packages/b"), "worktree": {}}), + ), + ) + .await + .expect("a creation that cannot map its subtree does not hang"); + assert!( + failed["error"]["message"] + .as_str() + .is_some_and(|message| message.contains("packages/b")), + "{failed}" + ); + let task = work.home.join("worktrees/aaaaaa"); + assert!(!task.exists(), "the failed creation keeps no directory"); + assert!( + server.prefer_next_worktree_task_id("aaaaaa"), + "the ManagedWorktrees part exists" + ); + let created = client + .rpc("session.create", json!({"cwd": repo, "worktree": {}})) + .await; + assert_ok(&created); + assert_eq!( + created["result"]["worktree"]["taskId"], "aaaaaa", + "the failed creation kept neither its directory nor its branch" + ); + server.shutdown(); + server.join().await.unwrap(); +} + +/// Dropping the caller of a recorded removal keeps the spawned deletion +/// running, the path refused and its record undeletable until it ends. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn dropping_the_caller_keeps_the_removal_and_its_path_refused() { + let work = Work::new(); + let server = host(&work).await; + let store = server.service::().unwrap(); + let task = unregistered_task(&work, "aaaaaa"); + std::fs::create_dir_all(task.join("repo")).unwrap(); + let directory = WorktreeDirectory { + repository: work.repo.clone(), + root: task.clone(), + }; + let reached = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let finished = Arc::new(tokio::sync::Notify::new()); + let removal = tokio::spawn({ + let store = store.clone(); + let directory = directory.clone(); + let reached = reached.clone(); + let release = release.clone(); + let finished = finished.clone(); + async move { + store + .remove_worktree(directory, move |path| { + Box::pin(async move { + reached.notify_one(); + release.notified().await; + tokio::fs::remove_dir_all(&path) + .await + .map_err(|error| AgentError::Storage(error.to_string()))?; + finished.notify_one(); + Ok(()) + }) + }) + .await + } + }); + tokio::time::timeout(Duration::from_secs(30), reached.notified()) + .await + .expect("the removal reaches its deletion step"); + removal.abort(); + assert!(removal.await.unwrap_err().is_cancelled()); + let record = store + .remove_worktree_directory(directory) + .await + .expect_err("the record of a path being removed cannot be deleted"); + assert!( + matches!(&record, AgentError::InvalidInput(message) if message.contains("is being removed")), + "{record:?}" + ); + let mut client = Client::new_version(&server, false, 3).await; + let refused = tokio::time::timeout( + Duration::from_secs(10), + client.rpc("session.create", json!({"cwd": task})), + ) + .await + .expect("the path being removed is refused after its caller is dropped"); + assert!( + refused["error"]["message"] + .as_str() + .is_some_and(|message| message.contains("is being removed")), + "{refused}" + ); + release.notify_one(); + tokio::time::timeout(Duration::from_secs(10), finished.notified()) + .await + .expect("the deletion finishes after its caller is gone"); + assert!(!task.exists()); + server.shutdown(); + server.join().await.unwrap(); +} + +/// Two creations that reach the same task id do not share it: the one that +/// meets the other's registration of the path moves to another id, and the one +/// that registered it still builds there. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_second_creation_moves_off_the_path_a_creation_registered() { + let work = Work::new(); + let server = host(&work).await; + let hold = server + .hold_next_worktree_creation() + .expect("the ManagedWorktrees part exists"); + assert!( + server.prefer_next_worktree_task_id("aaaaaa"), + "the ManagedWorktrees part exists" + ); + let mut first_client = Client::new_version(&server, false, 3).await; + let repo = work.repo.clone(); + let first = tokio::spawn(async move { + first_client + .rpc("session.create", json!({"cwd": repo, "worktree": {}})) + .await + }); + tokio::time::timeout(Duration::from_secs(30), hold.reached.notified()) + .await + .expect("the first creation registers its directory before it builds"); + assert!( + server.prefer_next_worktree_task_id("aaaaaa"), + "the ManagedWorktrees part exists" + ); + let mut second_client = Client::new_version(&server, false, 3).await; + let second_repo = work.repo.clone(); + let second = tokio::spawn(async move { + second_client + .rpc( + "session.create", + json!({"cwd": second_repo, "worktree": {}}), + ) + .await + }); + let built = tokio::time::timeout(Duration::from_secs(30), second) + .await + .expect("the second creation does not wait for the first") + .unwrap(); + assert_ok(&built); + assert_ne!( + built["result"]["worktree"]["taskId"], "aaaaaa", + "the second creation does not build at the path the first registered" + ); + hold.release.notify_one(); + let created = tokio::time::timeout(Duration::from_secs(30), first) + .await + .expect("the first creation builds where it registered") + .unwrap(); + assert_ok(&created); + let root = work.home.join("worktrees/aaaaaa/repo"); + assert_eq!(created["result"]["worktree"]["taskId"], "aaaaaa"); + assert_eq!( + PathBuf::from(created["result"]["worktree"]["root"].as_str().unwrap()), + root + ); + assert!(root.is_dir()); + server.shutdown(); + server.join().await.unwrap(); +} + +/// A failed creation's rollback removes the worktree and the branch it built +/// even though a creation that found the path free before the failure meets it: +/// the rollback's registration of the path keeps the second creation off it +/// until the removal ends. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_creation_cannot_take_the_path_a_failed_creation_rolls_back() { + let work = Work::new(); + let server = host(&work).await; + let repo = work.repo.clone(); + git(&repo, &["rm", "--cached", "-r", "-q", "packages/b"]); + git( + &repo, + &[ + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "commit", + "-qm", + "drop the subtree", + ], + ); + let building = server + .hold_next_worktree_creation() + .expect("the ManagedWorktrees part exists"); + assert!( + server.prefer_next_worktree_task_id("aaaaaa"), + "the ManagedWorktrees part exists" + ); + let mut failing_client = Client::new_version(&server, false, 3).await; + let failing_cwd = repo.join("packages/b"); + let failed = tokio::spawn(async move { + failing_client + .rpc( + "session.create", + json!({"cwd": failing_cwd, "worktree": {}}), + ) + .await + }); + tokio::time::timeout(Duration::from_secs(30), building.reached.notified()) + .await + .expect("the failed creation registers its directory before it builds"); + let checking = server + .hold_next_worktree_creation_check() + .expect("the ManagedWorktrees part exists"); + assert!( + server.prefer_next_worktree_task_id("aaaaaa"), + "the ManagedWorktrees part exists" + ); + let mut second_client = Client::new_version(&server, false, 3).await; + let second_repo = repo.clone(); + let second = tokio::spawn(async move { + second_client + .rpc( + "session.create", + json!({"cwd": second_repo, "worktree": {}}), + ) + .await + }); + tokio::time::timeout(Duration::from_secs(30), checking.reached.notified()) + .await + .expect("the second creation finds the path free before it registers it"); + let rollback = server + .hold_next_worktree_rollback() + .expect("the ManagedWorktrees part exists"); + let registered = server + .hold_next_worktree_creation() + .expect("the ManagedWorktrees part exists"); + building.release.notify_one(); + tokio::time::timeout(Duration::from_secs(30), rollback.reached.notified()) + .await + .expect("the failed creation reaches its rollback"); + checking.release.notify_one(); + tokio::time::timeout(Duration::from_secs(30), registered.reached.notified()) + .await + .expect("the second creation registers a directory of its own"); + rollback.release.notify_one(); + let failed = tokio::time::timeout(Duration::from_secs(30), failed) + .await + .expect("the rollback finishes") + .unwrap(); + assert!( + failed["error"]["message"] + .as_str() + .is_some_and(|message| message.contains("packages/b")), + "{failed}" + ); + let path = work.home.join("worktrees/aaaaaa/repo"); + assert!( + !path.exists(), + "the failed creation removes the worktree the rollback holds" + ); + registered.release.notify_one(); + let built = tokio::time::timeout(Duration::from_secs(30), second) + .await + .expect("the second creation does not wait for the rollback") + .unwrap(); + assert_ok(&built); + assert_ne!( + built["result"]["worktree"]["taskId"], "aaaaaa", + "the second creation does not build at the path the rollback holds" + ); + assert!( + server.prefer_next_worktree_task_id("aaaaaa"), + "the ManagedWorktrees part exists" + ); + let mut client = Client::new_version(&server, false, 3).await; + let reused = client + .rpc("session.create", json!({"cwd": repo, "worktree": {}})) + .await; + assert_ok(&reused); + assert_eq!( + reused["result"]["worktree"]["taskId"], "aaaaaa", + "the failed creation kept neither its directory nor its branch" + ); + server.shutdown(); + server.join().await.unwrap(); +} diff --git a/docs/architecture/rust-agent/timeline-storage.md b/docs/architecture/rust-agent/timeline-storage.md index eab069b0fe..87c705ae3e 100644 --- a/docs/architecture/rust-agent/timeline-storage.md +++ b/docs/architecture/rust-agent/timeline-storage.md @@ -18,8 +18,8 @@ worktree 清理都调用原实现。AgentBuilder 使用的 TimelineStore 端口 分叉前由生命周期 owner 验证来源角色、已发布的 main 切点、批次/上下文边界和静止点,传入去掉 `initialTitle` 的来源存储配置文本;仓储保持文本字节,不追加运行时配置限制。 创建、分叉、删除共用 native 边界的 Session id 单个正常路径分量校验,拒绝绝对路径、父目录与多级路径,在碰触存储和输出目录前返回 `invalid`。 -`removeWorktree` 延续 native 回调的所有权互斥:回调不得等待同锁操作,即创建、分叉、删除 Session、删除 worktree 目录记录、再次删除 worktree、删除未登记目录,以及 `worktreeAssociations.associate`;不取此锁的读取仍可使用。回调失败不删除目录记录,不改为锁外删除。 -`removeUnregisteredDirectory` 在同一把锁内复核目录记录中没有根在该目录或其下的条目、存储中没有 Session 的 cwd 在该目录或其下,再运行调用方的删除(删除前只用文件系统检查复核未登记条件),锁一直持有到删除结束,调用方放弃这次调用不会提前放锁;回调同样不得等待上述同锁操作。 +`removeWorktree` 在所有权锁内复核并把要删的规范化根登记进内存的正在删除集合,随后放锁、等待回调,回调返回后再取锁删除目录记录;登记与删除在同一个任务里结束,调用方放弃这次调用既不停止删除,也不提前清除登记。回调不在锁内,删除期间落在登记路径上、其下或其中的 Session 创建、分叉、关联、目录记录删除与再次删除都被拒绝,worktree 创建不选这样的路径,不相关路径照常放行;worktree 创建在锁内把选中的目录登记进对称的正在创建集合,删除碰到它也拒绝,创建自己的失败清除在同一把锁内把这条登记交接成正在删除;不取此锁的读取不受影响。回调失败不删除目录记录,也不留下登记。 +`removeUnregisteredDirectory` 在同一把锁内复核目录记录中没有根在该目录或其下的条目、存储中没有 Session 的 cwd 在该目录或其下,再把规范化路径登记进同一集合,放锁后运行调用方的删除(删除前只用文件系统检查复核未登记条件);调用方放弃这次调用既不停止删除,也不提前清除登记。 `store.catalog` 返回数据库页(数据库 sequence,行内 `closed=false`),客户端需要的 live sequence 与关闭状态仍由生命周期 owner 用 AgentIndex 补齐。原生错误分类不变:未知 Session 的 addGrant 为外键 `storage`,removeGrant 幂等成功,语言更新为 `closed`;未知协议版本仍由数据库返回 `storage`,调用方须先检查。 ```text diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 8eca878f61..ce4052095c 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -53,7 +53,7 @@ draining its admitted work before unloading. | Caller → owner | API | Transaction owner and boundary | | --- | --- | --- | | Agents, Session catalog, grants and worktree clients → store → sqliteStorage | Reuse the store request/reply shapes for `createOwnedSession, fork, owner, creationRecord, hasRecords, sessionConfig, sessionConfigText, catalog, addGrant, removeGrant, grants, setSessionLanguage, associateWorktree, worktreeDirectories, worktreeUsages, sessionsUnderWorkspace, removeWorktreeDirectory`. | SQLite creates the Session, main branch, ownership and optional worktree association in one transaction. Fork uses bounded copy transactions on its own connection; only the final transaction inserts the Session row and makes the fork visible. Association commits the directory and Session link together. | -| Session deletion and worktree removal → store | `store.delete` uses `sqliteStorage.hasRecords, removableOutputDirectories, touchWorktreeDirectories, rollbackSession`. `store.removeWorktree` uses the existing association/workspace checks and directory deletion; `store.removeUnregisteredDirectory` uses the existing directory-record and workspace checks and the caller's deletion. | SessionStore holds its ownership lock across the checks and the filesystem removal, including a recursive `--force` deletion with no time limit, so Session creation, fork, deletion and worktree association or removal wait for it. Dropping the caller does not release the lock while the removal runs. SQLite owns each database step. File deletion and Git removal run outside SQL transactions. | +| Session deletion and worktree removal → store | `store.delete` uses `sqliteStorage.hasRecords, removableOutputDirectories, touchWorktreeDirectories, rollbackSession`. `store.removeWorktree` uses the existing association/workspace checks and directory deletion; `store.removeUnregisteredDirectory` uses the existing directory-record and workspace checks and the caller's deletion. | SessionStore holds its ownership lock across the checks and the registration of the resolved path in an in-memory set, then releases it for the caller's deletion, including a recursive `--force` deletion with no time limit. Until the same removal task clears the registration, Session creation, fork, worktree association, directory-record deletion or another removal at, under or above that path are refused instead of waiting for it; dropping the caller stops neither the deletion nor the registration. SQLite owns each database step. File deletion and Git removal run outside SQL transactions and outside the ownership lock. | | SessionTitle and Session rename → store → sqliteStorage | `readMetadata(sessionId)`, `setTitle(existing title request)`; existing metadata replies. FileAccess → `store.associateWorktree` with the existing association record. | SQLite checks the title revision and commits the write. SessionStore serializes title writes and publishes the committed notice before admitting the next one. | | Timeline clients → timelineStore; SessionStore → sqliteStorage | Bind existing `createSession, rollbackSession, releaseSession, sessionConfig, branches, head, batchEnd, batchEndAt, readPage, readSegments, query, trace, saveSnapshot, latestSnapshot` requests at the native boundary. `commitTimelineRound({batches: Append[]}) → {sessions: [{sessionId, result}]}` accepts ordered batches grouped by Session. | SessionStore admits appends synchronously, groups the existing writer round, and serves commit subscriptions and release/drain. SQLite owns encoding, the grouped transaction, per-Session fallback on failure and writer memo settlement. One accepted round produces the existing ordered batch outcomes after commit. Release or unload drops generation-local reader/writer state after drain. | | Session file put/import and read → sessionFiles → sqliteStorage | `reserveFile(sessionId,fileId,generation)`, `commitFile(sessionId,fileId,generation)`, `abandonFile(fileId,generation)`; ownership and path reads via `ownsFile, ownsOutput, ownedPaths`; `registerOutput(sessionId,path)`. | SessionStore reserves, writes or imports bytes through the file owner, then finalizes. SQLite verifies the Session and writer generation, clears the reservation and inserts ownership atomically. Bytes, path validation and fileId transfer stay with the file owner. | diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 9fd3844b36..e5dd257f13 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -765,31 +765,32 @@ is null or `{repository,root,subtree}`. Session creation retains the atomic owner/configuration/worktree publication. `lastUsedAtMs` is null for legacy directory records without an association timestamp. -`removeWorktree` keeps the owner exclusion from its usage checks through the physical -removal and directory-row deletion. Its callback receives the checked root path and -is awaited; no SQL or Timeline commit lock is held while awaiting it. A callback failure -leaves the directory row in place. As with the native callback, it must not await operations -that acquire this same ownership mutex: `createOwnedSession`, `fork`, `delete`, -`removeWorktreeDirectory`, `removeWorktree`, `removeUnregisteredDirectory`, or -`store.associateWorktree`. Reads and -other operations that do not acquire that mutex remain available. The callback may refuse with `invalid`, `cancelled` -or `storage`; unexpected callback or transport failures are `storage`. There is no -separate check/remove lease and no window for a concurrent Session creation to use -a directory being removed. `removeWorktreeDirectory` is the existing database-only -candidate cleanup, with its existing association checks. +`removeWorktree` holds the owner exclusion for its usage checks and for registering the +resolved root as being removed, then releases it and awaits the callback, which receives +the checked root path; the exclusion is taken again only to delete the directory row after +the callback returns. No SQL or Timeline commit lock is held while awaiting it. The +registration ends in the removal's own task, so dropping the caller stops neither the +deletion nor the registration. While it runs, `createOwnedSession`, `fork`, +`store.associateWorktree`, `removeWorktreeDirectory`, `removeWorktree` and +`removeUnregisteredDirectory` are refused with `invalid` for a path at, under or above the +registered one, and proceed for unrelated paths. The callback may refuse with `invalid`, +`cancelled` or `storage`; unexpected callback or transport failures are `storage`. A +callback failure leaves the directory row in place and no registration. The registration +is the only record of the removal: there is no separate check/remove lease, and a Session +creation on a directory being removed is refused instead of waiting for it. +`removeWorktreeDirectory` is the existing database-only candidate cleanup, with its +existing association checks and the same refusal for a path being removed. `removeUnregisteredDirectory` takes `{root}` and the same asynchronous removal callback. It is the unregistered removal of [worktree management §5](worktree-management.md#5-列出删除与清理): the root is absolute -without relative components, and the operation holds the owner exclusion from its -directory-record and workspace checks through the callback, so a Session created or -a directory recorded after the check fails the call and a creation after the removal -re-checks its missing workspace. The callback receives the checked root and is awaited; -it re-checks the unregistered filesystem facts before it deletes anything. A callback -failure is `invalid`, `cancelled` or `storage` as above, and it must not await any -operation in the list above. Dropping the caller does not release the lock while the callback runs. The lock has no time -limit: it covers a recursive `--force` deletion of any size, and Session creation, -fork, deletion and worktree association or removal wait for it. +without relative components, and the operation holds the owner exclusion for its +directory-record and workspace checks and for registering the resolved root, then awaits +the callback, which re-checks the unregistered filesystem facts before it deletes +anything. A callback failure is `invalid`, `cancelled` or `storage` as above. The +registration keeps the root refused to the operations above until the same removal task +clears it, and the deletion itself has no time limit: it covers a recursive `--force` +deletion of any size. Dropping the caller stops neither the deletion nor the registration. `catalog` takes the existing Session catalog request and the calling Agent owner's loaded/closed snapshots. Its result is the stored catalog page: sequence comes from the diff --git a/docs/design/worktree-management.md b/docs/design/worktree-management.md index 572c96ad2e..ef639049bc 100644 --- a/docs/design/worktree-management.md +++ b/docs/design/worktree-management.md @@ -49,17 +49,18 @@ Git 创建;调用方停止等待不会撤回该任务,Session 与 worktree 映射路径必须留在新根内。 2. ManagedWorktrees 分配 `` 并执行 `git worktree add -b `。`base` 先经 `git rev-parse --verify` 解析为 commit,`branch` 由 `-b` 消费且只新建,因此以 `-` 开头的值不会变成 - Git 选项;默认分支或目标路径已存在时换一个 `` 重试(最多三次),显式 `branch` 冲突直接返回 - `worktree_branch_exists`,不重试。add 失败只删除本次创建的空任务目录:路径与分支可能是并发赢家创建的, - 本调用不碰它们。 + Git 选项;默认分支或目标路径已存在、或目标路径与正在删除的路径重叠时换一个 `` 重试(最多三次);选中的目录 + 在锁内登记为“正在创建”,保留到目录记录与使用关联写入、或失败清除把它交接成“正在删除”为止(见 §5)。 + 显式 `branch` 冲突直接返回 `worktree_branch_exists`,不重试。add 失败只删除本次创建的空任务目录:路径与分支 + 可能是并发赢家创建的,本调用不碰它们。 3. 以根下的映射子树作为新 Session 的 `cwd`(源工作区就是仓库根时即根本身),使 [worktree-access §2.2](worktree-access.md#22-仓库身份与目录范围) 的范围映射成为实际工作区。映射前缀逐 组件拒绝符号链接,解析后的路径必须仍在根内。目录记录与使用关联由 SessionStore 在新 Session 的同一事务 里写入,记录的 subtree 等于这个 cwd;这一步失败即视为 Session 未创建。 4. 第 2 步之后的任何失败,ManagedWorktrees 用未取消的清理路径删除本次创建的目录与分支;已准备目录的撤回 - 复用 SessionStore 的删除操作,在 ownership 排他区内重查关联与根/子树下的 Session cwd,持锁完成 Git 撤回 - 后才删除目录记录。其他 Session 已使用该根或子树、Git 拒绝删除或目录写入他人内容时保留它们(不带 `-f`); - 没有目录记录的残留由 `list` 列为未登记,入口始终返回原错误。 + 复用 SessionStore 的删除操作,在 ownership 排他区内重查关联与根/子树下的 Session cwd,并把创建自己的“正在创建”登记 + 在同一把锁内交接成“正在删除”,放锁后完成 Git 撤回,删除成功后才删目录记录。其他 Session 已使用该根或子树、Git 拒绝删除或目录写入他人内容时 + 保留它们(不带 `-f`);没有目录记录的残留由 `list` 列为未登记,入口始终返回原错误。 创建成功后不写 Timeline 事件:worktree 是进程级事实,不是分支状态。映射子树进入本 Session 的工作区范围, 根的其余部分按 worktree-access §2.2 仍需审批;文件工具与显式 `exec` cwd 不再对映射子树逐文件审批 @@ -96,24 +97,44 @@ agent 工具,不经过 Permission 批准,也从不服务给配对设备的 同一次存储操作里完成,分支保留,已提交内容不随目录消失。根已核验缺失,或存在但 Git 已不再登记时,只删 记录并 `git worktree prune`;后者在目录非空时需要 `--force`。未登记目录按 task-id 显式删除,要求内容干净、 目录记录中没有根在其下的条目、没有 Session 的 cwd 在根下且要删除的整棵树不含 `.git` 条目(目录、gitdir 文件或 - 符号链接,含悬空链接);带 `.git` 的残留由用户用 `git worktree remove` 处理,错误信息给出路径。 + 符号链接,含悬空链接);非 Unix 平台上不带 `--force` 的未登记删除以 `worktree_in_use` 拒绝并要求 `--force`; + 带 `.git` 的残留由用户用 `git worktree remove` 处理,错误信息给出路径。 记录只有 repository 与 root,同一路径被手工重建的 worktree 视为同一条记录,这是已知限制。 - **prune**:候选只包括根在 `$DIMCODE_HOME/worktrees` 下、没有剩余使用关联的目录记录,再按最后使用时间 应用 `--older-than` 或 `--keep`;未知时间按 §4 处理,仍有关联、Session 的 cwd 在根下、无法检查、Git 已不再登记(除显式 `--force`)或未登记的目录一律不选。删除前逐项复核 Git 登记、根未变与内容干净,先预览再按确认删除;apply 携带预览的 task id,只删除用户看到的集合,单个候选失败时保留其记录并继续其余候选。保留项逐条给出原因。 选择语义与交互沿用 [session cleanup](cli-commands.md#session-deletion-and-cleanup),不新增第二套。 -- **排斥**:已登记的 remove 与 prune 经由 SessionStore 的 `store.removeWorktree` 操作完成:它持有会话存储 - 所有权锁,先复核关联与存储中的 Session cwd,再调用调用方传入的 Git 删除步骤,最后删除记录。未登记的 remove - 经由 `store.removeUnregisteredDirectory`:它在同一把锁内复核目录记录中没有根在该目录或其下的条目、存储中没有 - Session 的 cwd 在该目录或其下,再运行调用方传入的删除步骤;该步骤在删除前用文件系统检查复核目录仍是管理根下的 - 普通目录、它的直接子目录仍是管理根内的普通目录,以及删除范围内每个目录都没有 `.git` 条目(目录、gitdir 文件或 - 符号链接,含悬空链接;遍历不跟随符号链接,不起 Git 子进程),不满足就拒绝。 - `Session` 创建与 `associate_worktree` 在同一把锁内重新核验 cwd 与根是否仍是目录,所以复核之后不会出现指向已删根的 - 新 Session 或关联;分叉、删除 Session 与关联移除也取同一把锁,会等这次删除结束。 - 锁跨越的步骤没有时间上限:一次 `git worktree remove`(30 秒超时)、Git 不再登记时的 `cleanup_unregistered_root` - 递归删除,以及未登记目录删除前对整棵树 `.git` 条目的遍历和带 `--force` 的递归删除都在锁内;未登记目录的内容有多少,锁就持有多久。 - 这期间 `session.create`、`session.fork`、`session.delete` 以及 worktree 关联与删除都要等这把锁。 +- **排斥**:删除分两步。已登记的 remove 与 prune 经由 SessionStore 的 `store.removeWorktree` 操作:它在会话存储 + 所有权锁内复核关联与存储中的 Session cwd;未登记的 remove 经由 `store.removeUnregisteredDirectory`:它在同一把锁内 + 复核目录记录中没有根在该目录或其下的条目、存储中没有 Session 的 cwd 在该目录或其下。两个操作随后把要删的规范化路径 + 登记进内存的“正在删除”集合,放锁。调用方传入的删除步骤(`git worktree remove`、`cleanup_unregistered_root`、未登记目录 + 的检查与递归删除)在本次请求自己的任务里前台完成,失败照样返回给调用方,记录只在删除成功后删除。删除结束时同一个任务把路径 + 移出集合;外层请求被取消也不会提前移出,集合只在内存里,进程崩溃后半删的目录仍可按 task id 再删一次。 +- **正在删除**:集合只拦与登记路径相同、在其上或在其下的操作:`session.create` 与 `sessions.launch` 的 cwd、 + `store.fork` 配置里的 cwd、`associate_worktree` 的根、同一路径的再次删除,以及同一目录的记录删除 + (`store.removeWorktreeDirectory`)都被拒绝(`worktree.remove` 报 `worktree_in_use`);`worktree.create` 在 + 同一把锁内拿选中的目录与集合比对,命中就换一个 ``,所以登记期间不会在同一路径建出目录。 + 父路径方向也拒绝,因为它的内容正在被删(例如任务目录下的仓库),这期间不在其上新建 Session。删除结束后被删的目录 + 自然通不过创建与关联的目录检查。不相关路径的创建、分叉、删除与关联不再等删除;复核之后也不会出现指向已删根的 + 新 Session 或关联。 +- **正在创建**:`worktree.create` 选中目录之后、建目录之前,在同一把锁内把选中的规范化路径登记进“正在创建”集合, + 与“正在删除”对称。登记由创建自己的任务持有,只随创建结束而释放(目录记录与使用关联写入之后,或失败清除把它交接成“正在删除”之后), + 删除方移不掉它;集合同样只在内存里。`store.removeWorktree` 与 `store.removeUnregisteredDirectory` 在锁内 + 登记“正在删除”时与这个集合双向比对,命中(路径相同、在其上或在其下)即以 `worktree_in_use` 拒绝,所以创建通过 + 目录检查之后、把 worktree 交给 Session 之前落进来的删除不会删到正在创建的 worktree。创建自己的失败清除(撤回目录与分支) + 在同一把锁内把这条登记直接交接成“正在删除”,中间没有空档,所以撤回既不会被自己的登记挡住,也不会被另一条在同一路径上 + 通过检查的创建插进去。创建成功时登记在目录记录写入后释放,同一路径随后可正常删除;两条创建撞上同一路径时 + 后一条换一个 ``。 +- **未登记目录的复核**:由 ManagedWorktrees 提供的删除步骤在删除前用文件系统检查复核目录仍是管理根下的普通目录、 + 它的直接子目录仍是管理根内的普通目录,以及删除范围内每个目录都没有 `.git` 条目(目录、gitdir 文件或符号链接,含悬空链接; + 遍历不跟随符号链接,不起 Git 子进程),不满足就拒绝。 +- **非 force 的删除**:只删检查记录下来的空直接子目录和任务目录本身,逐个按名字从已打开的目录句柄删除(Unix 的 `unlinkat`); + 任务目录或子目录在检查后被换成符号链接时删除以 `worktree_in_use` 失败,不会删到管理根外。Windows 没有既能只删空目录、 + 又能守住管理根边界的现成原语,所以非 Unix 平台上未登记目录的非 force 删除直接以 `worktree_in_use` 拒绝并提示 `--force`; + `--force` 用标准库的 `remove_dir_all`,它按目录句柄遍历、不跟随树内的 reparse point。 +- **时间上限**:锁只跨越复核与登记,没有慢步骤。删除本身没有时间上限:`git worktree remove` 有 30 秒超时, + 递归删除按目录内容多少决定,这是已知限制。 可证明的使用只有记录与存储中的 cwd;其余使用不可证明,由预览、确认和 worktree-access §4 的删除授权承担。 - Session 删除和 `session cleanup` 不删除也不报告遗留的 worktree;`worktree list` 是查看它们的唯一入口。 @@ -121,7 +142,7 @@ agent 工具,不经过 Permission 批准,也从不服务给配对设备的 | Owner | 现有机制为何不够 | 需要的合同 | 顺序与失败 | | --- | --- | --- | --- | -| SessionStore | `associate_worktree` 要求 Session 已存在,不能补写创建期记录;目录记录没有时间;删除目录记录会撞上未级联的关联外键 | 创建 Session 时同一事务写入目录记录、使用关联与最后使用时间;关联写入/解除更新时间;按根查询任何存储中 Session 的 cwd;Session 创建、分叉、删除、关联写入与移除共用所有权锁,创建与关联在锁内重新核验 cwd/根;`store.removeWorktree` 与 `store.removeUnregisteredDirectory` 操作在锁内复核并运行调用方传入的删除(前者还删除记录),锁一直持有到删除结束且没有时间上限;删除目录记录的类型化操作(含核验缺失/Git 不登记的记录清理)。列变更遵守 native-storage-format.md | 创建失败不留记录;删除成功才删记录,失败保留供重试 | +| SessionStore | `associate_worktree` 要求 Session 已存在,不能补写创建期记录;目录记录没有时间;删除目录记录会撞上未级联的关联外键 | 创建 Session 时同一事务写入目录记录、使用关联与最后使用时间;关联写入/解除更新时间;按根查询任何存储中 Session 的 cwd;Session 创建、分叉、删除、关联写入与移除共用所有权锁,创建与关联在锁内重新核验 cwd/根;`store.removeWorktree` 与 `store.removeUnregisteredDirectory` 在锁内复核并把正在删除的路径登记到内存集合,放锁后运行调用方传入的删除(前者还在删除成功后删记录),同一路径及其上下路径的创建、关联、分叉与再次删除在删除期间被拒,创建在锁内把选中的目录登记进对称的“正在创建”集合、删除遇到它同样拒绝;删除目录记录的类型化操作(含核验缺失/Git 不登记的记录清理)。列变更遵守 native-storage-format.md | 创建失败不留记录;删除成功才删记录,失败保留供重试,且不留下删除登记 | | Agents | 现有 `cwd` 只能指向已存在目录,不能把创建目录和创建 Session 合成一次请求 | `session.create` 与 `sessions.launch` 共用可选 `worktree`、嵌套回复、创建关联与失败清除;launch 保持既有策略上限与非交互语义 | 入口只校验格式与权限;Git、失败清除由 ManagedWorktrees 执行,创建失败时入口调用它清除 | | App Server 协议 | 客户端各自 `git worktree add` 会重新引入路径分歧;新成员会被旧 daemon 当作未知字段拒绝 | `hello.features` 宣告 `session.create.worktree` 与 `sessions.launch.worktree`(仅在产品 home 与原生存储都存在时宣告)、`worktree.list`、`worktree.remove`、`worktree.prune`;`cwd` 声明为源工作区;三个操作注册为 `managementMethods` 的 `worktree` 命名空间,不服务配对设备 | 客户端只在宣告存在时发送;失败不留半成品,重试创建新的 `` | | CLI 与 Desktop | 没有可调用的创建入口,只能让模型跑 Git | 各自的入口与展示(`--worktree`、`dimcode worktree ...`;TUI 的 `/worktree` 面板留待后续),只消费类型化结果与拒绝原因 | 由各自 owner 更新 cli-commands.md 与 clients.md;不拼路径、不读存储、不直接调用 Git | diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 51f54434a6..18fafd15be 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -700,9 +700,9 @@ export interface Store { sessionsUnderWorkspace(request: { root: string }): Promise<{ sessionIds: string[] }>; removeWorktreeDirectory(request: WorktreeDirectory): Promise<{ removed: boolean }>; worktreeUsages(request: WorktreeDirectory): Promise<{ usages: { sessionId: string; subtree: string }[] }>; - /** Callback runs under the native ownership mutex: do not await createOwnedSession, fork, delete, removeWorktreeDirectory, removeWorktree, removeUnregisteredDirectory or worktreeAssociations.associate from it. */ + /** The root is checked and registered under the native ownership mutex, then the callback runs outside it; creation, fork, association, directory-record deletion and removal at, under or above the root stay refused until it returns. */ removeWorktree(request: WorktreeDirectory, remove: (path: string) => Promise): Promise<{ removed: boolean }>; - /** Removes an unregistered directory after the final workspace check; the callback runs under the native ownership mutex, which the removal holds until the callback finishes. */ + /** Removes an unregistered directory after the final workspace check; the callback runs outside the native ownership mutex and the path stays refused as above until it returns. */ removeUnregisteredDirectory(request: { root: string }, remove: (path: string) => Promise): Promise<{ removed: boolean }>; }