From 72e6a88a5b1d56a884964a25f0dc0e481f2931af Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 16:05:14 -0700 Subject: [PATCH 01/19] fix(worktree): scope set removal to the workspace's repos Add worktree::workspace: the workspace a meta dir belongs to climbs only through parents whose project tree lists the child (an unlisted nested workspace is its own), and its repos are the root plus every repo in its .meta tree, as git dirs. Workspace::foreign_members names each worktree of a set whose repository is not one of them, with the workspace its record names, so prune and remove can keep to this workspace's sets. In a set that has a record, a worktree without one is now a blocker of its own kind (RemovalCheck::missing_records): meta didn't create it, so it doesn't delete it. Only create's rollback exempts that kind. [[tasks/harmony-2793]] --- src/worktree/mod.rs | 1 + src/worktree/safety.rs | 36 ++++++- src/worktree/workspace.rs | 201 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 234 insertions(+), 4 deletions(-) create mode 100644 src/worktree/workspace.rs diff --git a/src/worktree/mod.rs b/src/worktree/mod.rs index ec02b17..93afceb 100644 --- a/src/worktree/mod.rs +++ b/src/worktree/mod.rs @@ -9,6 +9,7 @@ pub mod hooks; pub mod record; pub mod safety; pub mod types; +pub mod workspace; // Re-export commonly-used types pub use types::RepoSpec; diff --git a/src/worktree/safety.rs b/src/worktree/safety.rs index 876f44c..7291f7a 100644 --- a/src/worktree/safety.rs +++ b/src/worktree/safety.rs @@ -37,6 +37,12 @@ pub struct RemovalCheck { /// as a proof of ownership; a create rolling back the set it just /// claimed needs no such proof. pub unusable_records: Vec, + /// Worktrees without a record in a set whose other worktrees have one + /// (part of `blockers`): meta didn't make them, so it doesn't delete + /// them. A create rolling back may not have recorded every worktree yet. + pub missing_records: Vec, + /// The members whose record can't be used. + unusable_members: Vec, /// Each checkout's complete git status, stranded commit ids, and the size /// and modification time of every file `unsaved` lists, so a re-check /// sees changes the abbreviated lines would hide, rewrites included. @@ -64,8 +70,9 @@ impl RemovalCheck { /// as unsaved: uncommitted or untracked changes, commits that no branch, tag /// or remote ref holds, and files that no repository holds. Ignored files count as disposable, as /// they do for `git worktree remove`. Blocks on a worktree whose record -/// (see [`record`]) names another set, such as a set nested in this one, or -/// whose record can't be read. +/// (see [`record`]) names another set, such as a set nested in this one, +/// whose record can't be read, or that has no record while another worktree +/// of the set has one. pub fn check_worktree_removal(wt_dir: &Path) -> Result { let mut check = RemovalCheck::default(); if wt_dir.symlink_metadata().is_ok_and(|m| m.is_symlink()) { @@ -95,7 +102,6 @@ pub fn check_worktree_removal(wt_dir: &Path) -> Result { scan(&set, wt_dir, root_owned, &mut loose, &mut check)?; // A stable order, so two checks of an unchanged set compare equal. check.members.sort_by(|a, b| a.path.cmp(&b.path)); - check.blockers.sort(); loose.sort(); // Another set's records are blockers already @@ -110,7 +116,22 @@ pub fn check_worktree_removal(wt_dir: &Path) -> Result { escape_path(wt_dir) )); } + let missing: Vec = check + .members + .iter() + .filter(|m| m.record.is_none() && !check.unusable_members.contains(&m.path)) + .map(|m| { + format!( + "{}: meta has no record of creating it (made by hand, or its record was \ + deleted); run 'git worktree remove' on it first", + relative_label(wt_dir, &m.path) + ) + }) + .collect(); + check.blockers.extend(missing.iter().cloned()); + check.missing_records = missing; } + check.blockers.sort(); let paths: Vec = check.members.iter().map(|m| m.path.clone()).collect(); for member in &paths { @@ -246,6 +267,7 @@ fn add_member( ); check.unusable_records.push(why.clone()); check.blockers.push(why); + check.unusable_members.push(path.to_path_buf()); None } }; @@ -625,7 +647,7 @@ fn operation_in_progress(repo: &Path) -> Result> { .map(|(_, name)| name)) } -fn relative_label(root: &Path, path: &Path) -> String { +pub(super) fn relative_label(root: &Path, path: &Path) -> String { match path.strip_prefix(root) { Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(), Ok(rel) => escape_path(rel).to_string(), @@ -738,6 +760,12 @@ mod tests { let record = set_record(&set); mark(&set, &record); + // In a set meta made, a worktree without a record is not meta's + let check = check_worktree_removal(&set).unwrap(); + assert_eq!(check.missing_records.len(), 1, "{check:?}"); + assert!(check.missing_records[0].starts_with("leaf: meta has no record")); + assert_eq!(check.blockers, check.missing_records); + mark(&set.join("leaf"), &record); let check = check_worktree_removal(&set).unwrap(); assert!(check.is_clear(), "{check:?}"); assert_eq!(check.record(), Some(&record)); diff --git a/src/worktree/workspace.rs b/src/worktree/workspace.rs new file mode 100644 index 0000000..e01fa0d --- /dev/null +++ b/src/worktree/workspace.rs @@ -0,0 +1,201 @@ +//! The workspace a command runs in, and the repositories that make it up. +//! +//! Commands that delete worktree sets keep to this workspace's sets: those +//! whose every worktree belongs to one of its repositories. Where the sets +//! are kept (`META_WORKTREES` may be shared, or point into another +//! workspace) doesn't change that. + +use anyhow::{Context, Result}; +use meta_core::display::escape_path; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +use super::safety::{relative_label, RemovalCheck}; + +/// A workspace's root meta directory and its repositories. +pub struct Workspace { + pub root: PathBuf, + /// Each repository (the root's own, then every one in its `.meta` + /// tree, nested ones included) with its git directory: where the + /// records of the worktrees made from it are. + pub repos: Vec<(PathBuf, PathBuf)>, + /// What couldn't be read (the project tree, a repository), with why: + /// worktrees from there count as another workspace's. + pub unreadable: Vec<(PathBuf, anyhow::Error)>, + git_dirs: HashSet, +} + +impl Workspace { + /// The workspace `meta_dir` belongs to (see [`workspace_root`]). + pub fn of(meta_dir: &Path) -> Workspace { + let root = workspace_root(meta_dir); + let mut paths = vec![root.clone()]; + let mut unreadable = Vec::new(); + match meta_core::config::walk_meta_tree(&root, None) { + Ok(tree) => paths.extend( + meta_core::config::build_project_map(&tree, &root, "") + .into_values() + .map(|(path, _)| path), + ), + Err(e) => unreadable.push((root.clone(), e)), + } + let mut repos = Vec::new(); + for path in paths { + match repo_git_dir(&path) { + Ok(Some(git_dir)) => repos.push((path, git_dir)), + Ok(None) => {} + Err(e) => unreadable.push((path, e)), + } + } + let git_dirs = repos + .iter() + .filter_map(|(_, git_dir)| git_dir.canonicalize().ok()) + .collect(); + Workspace { + root, + repos, + unreadable, + git_dirs, + } + } + + /// Whether `git_dir` is the git directory of one of this workspace's + /// repositories. + pub fn holds(&self, git_dir: &Path) -> bool { + git_dir + .canonicalize() + .is_ok_and(|git_dir| self.git_dirs.contains(&git_dir)) + } + + /// The worktrees of the set at `wt_dir` (checked as `check`) that come + /// from repositories outside this workspace, each with the workspace + /// its record names. A set with any is another workspace's. + pub fn foreign_members(&self, wt_dir: &Path, check: &RemovalCheck) -> Vec { + check + .members + .iter() + .filter(|m| !self.holds(&m.repo_git_dir)) + .map(|m| { + let label = relative_label(wt_dir, &m.path); + let repo = m.repo_git_dir.canonicalize(); + let repo = escape_path(repo.as_deref().unwrap_or(&m.repo_git_dir)); + match &m.record { + Some(record) => format!( + "{label}: its repository {repo} is not one of this workspace's; its \ + record names the workspace at {}", + escape_path(&record.project) + ), + None => { + format!("{label}: its repository {repo} is not one of this workspace's") + } + } + }) + .collect() + } +} + +/// The root of the workspace `meta_dir` belongs to: `meta_dir`, or the +/// nearest meta directory above it whose project tree lists it, and so on +/// upward. A meta directory its parent doesn't list (or whose parent's tree +/// can't be read) is a workspace of its own. +pub fn workspace_root(meta_dir: &Path) -> PathBuf { + let mut root = meta_dir.to_path_buf(); + for parent in meta_dir.ancestors().skip(1) { + match meta_core::config::find_meta_config_in(parent) { + Ok(None) => continue, + Ok(Some(_)) if lists(parent, &root) => root = parent.to_path_buf(), + _ => break, + } + } + root +} + +/// Whether the project tree of the meta directory `parent` lists `dir`. +fn lists(parent: &Path, dir: &Path) -> bool { + let (Ok(tree), Ok(dir)) = ( + meta_core::config::walk_meta_tree(parent, None), + dir.canonicalize(), + ) else { + return false; + }; + meta_core::config::build_project_map(&tree, parent, "") + .into_values() + .any(|(path, _)| path.canonicalize().is_ok_and(|path| path == dir)) +} + +/// The git directory holding the worktrees of the repository at `repo`: +/// `None` if there is no repository there (not cloned). +pub fn repo_git_dir(repo: &Path) -> Result> { + let dot_git = repo.join(".git"); + // Links are followed: a `.git` linked to the real git directory is one + let meta = match std::fs::metadata(&dot_git) { + Ok(meta) => meta, + // A bare repository is its own git directory + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + let bare = repo.join("HEAD").is_file() + && repo.join("objects").is_dir() + && repo.join("refs").is_dir(); + return Ok(bare.then(|| repo.to_path_buf())); + } + Err(e) => { + return Err( + anyhow::Error::from(e).context(format!("Cannot inspect {}", escape_path(&dot_git))) + ) + } + }; + if meta.is_dir() { + return Ok(Some(dot_git)); + } + // A `.git` file: a linked worktree's (its admin directory names the + // repository's git directory in `commondir`) or a `--separate-git-dir` + // checkout's (it names the git directory itself, with no `commondir`) + let content = std::fs::read_to_string(&dot_git) + .with_context(|| format!("Cannot read {}", escape_path(&dot_git)))?; + let target = content + .trim() + .strip_prefix("gitdir:") + .map(|target| repo.join(target.trim())) + .with_context(|| format!("{} has no gitdir line", escape_path(&dot_git)))?; + let commondir = target.join("commondir"); + match std::fs::read_to_string(&commondir) { + Ok(common) => Ok(Some(target.join(common.trim()))), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Some(target)), + Err(e) => { + Err(anyhow::Error::from(e).context(format!("Cannot read {}", escape_path(&commondir)))) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(dir: &Path, projects: &str) { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write( + dir.join(".meta.json"), + format!(r#"{{"projects": {{{projects}}}}}"#), + ) + .unwrap(); + } + + #[test] + fn the_root_climbs_only_through_parents_that_list_the_child() { + let tmp = tempfile::tempdir().unwrap(); + let top = tmp.path().canonicalize().unwrap(); + config(&top, r#""inner": {"repo": "x", "meta": true}"#); + config(&top.join("inner"), r#""deep": {"repo": "x", "meta": true}"#); + config(&top.join("inner/deep"), ""); + assert_eq!(workspace_root(&top.join("inner/deep")), top); + assert_eq!(workspace_root(&top.join("inner")), top); + + // A workspace inside another that doesn't list it is its own + let unlisted = top.join("inner/elsewhere"); + config(&unlisted, ""); + assert_eq!(workspace_root(&unlisted), unlisted); + // and so is one under a directory without a config + let below = top.join("plain/sub"); + config(&below, ""); + assert_eq!(workspace_root(&below), below); + } +} From 71151cfe89e310fcc48e3500585ee7b13b49be4e Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 16:05:14 -0700 Subject: [PATCH 02/19] fix(worktree): escape names in errors, read config via the shared resolver validate_worktree_name, lookup_project and lookup_nested_project show user-given names (and the valid list) escaped, so a name with a newline or ESC gives a one-line error with no raw control bytes. The nested lookup's valid paths are listed on that one line. read_meta_config_value goes through meta_core::config::find_meta_config_in and returns errors instead of skipping a config it can't read or parse; resolve_worktree_root propagates them and hooks warn and don't run. A duration that isn't a number names the whole value. [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 126 ++++++++++++++++++++++++++-------------- src/worktree/hooks.rs | 8 ++- 2 files changed, 88 insertions(+), 46 deletions(-) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 2b40b3f..9355511 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -1,7 +1,8 @@ //! Utility functions for worktree management. use anyhow::{Context, Result}; -use meta_core::display::escape_path; +use meta_core::config::ConfigFormat; +use meta_core::display::{escape, escape_path}; use std::path::{Path, PathBuf}; use super::types::WorktreeContext; @@ -10,17 +11,18 @@ pub fn validate_worktree_name(name: &str) -> Result<()> { if name.is_empty() { anyhow::bail!("Worktree name cannot be empty"); } + let shown = escape(name); if name.starts_with('.') { - anyhow::bail!("Invalid worktree name '{name}': cannot start with '.'"); + anyhow::bail!("Invalid worktree name '{shown}': cannot start with '.'"); } if name.contains('/') || name.contains('\\') { - anyhow::bail!("Invalid worktree name '{name}': cannot contain path separators"); + anyhow::bail!("Invalid worktree name '{shown}': cannot contain path separators"); } if !name .chars() .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { - anyhow::bail!("Invalid worktree name '{name}': only ASCII alphanumeric characters, hyphens, and underscores allowed"); + anyhow::bail!("Invalid worktree name '{shown}': only ASCII alphanumeric characters, hyphens, and underscores allowed"); } Ok(()) } @@ -38,7 +40,7 @@ pub fn resolve_worktree_root(meta_dir: Option<&Path>) -> Result { if let Some((config, _)) = meta_core::config::find_meta_config_in(dir)? { meta_core::config::parse_meta_config(&config)?; } - if let Some(configured) = read_worktrees_dir_from_config(dir) { + if let Some(configured) = read_worktrees_dir_from_config(dir)? { // Worktrees are created and removed there, so a committed config // may not point it outside the workspace let relative = meta_core::config::relative_dir(dir, &configured).map_err(|why| { @@ -67,38 +69,29 @@ pub fn resolve_worktree_root(meta_dir: Option<&Path>) -> Result { Ok(cwd.join(".worktrees")) } -/// Read and parse the .meta config as a JSON Value. -/// Tries .meta, .meta.json, .meta.yaml, .meta.yml in order, parsing JSON or YAML as appropriate. -pub fn read_meta_config_value(meta_dir: &Path) -> Option { - for name in &[".meta", ".meta.json", ".meta.yaml", ".meta.yml"] { - let path = meta_dir.join(name); - if !path.exists() || !path.is_file() { - continue; - } - let content = match std::fs::read_to_string(&path) { - Ok(c) => c, - Err(_) => continue, - }; - // Try JSON first - if let Ok(v) = serde_json::from_str::(&content) { - return Some(v); - } - // Try YAML - if let Ok(v) = serde_yaml_ng::from_str::(&content) { - // Convert YAML Value to JSON Value for uniform access - if let Ok(json_val) = serde_json::to_value(v) { - return Some(json_val); - } - } - } - None +/// The config file in `meta_dir` (see +/// [`meta_core::config::find_meta_config_in`]) as a JSON value, if there is +/// one. One that can't be read or parsed is an error. +pub fn read_meta_config_value(meta_dir: &Path) -> Result> { + let Some((path, format)) = meta_core::config::find_meta_config_in(meta_dir)? else { + return Ok(None); + }; + let content = std::fs::read_to_string(&path) + .with_context(|| format!("Cannot read {}", escape_path(&path)))?; + let value = match format { + ConfigFormat::Json => serde_json::from_str(&content).map_err(anyhow::Error::from), + ConfigFormat::Yaml => serde_yaml_ng::from_str::(&content) + .map_err(anyhow::Error::from) + .and_then(|v| serde_json::to_value(v).map_err(anyhow::Error::from)), + }; + value + .map(Some) + .with_context(|| format!("Cannot parse {}", escape_path(&path))) } -pub fn read_worktrees_dir_from_config(meta_dir: &Path) -> Option { - read_meta_config_value(meta_dir)? - .get("worktrees_dir") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()) +pub fn read_worktrees_dir_from_config(meta_dir: &Path) -> Result> { + Ok(read_meta_config_value(meta_dir)? + .and_then(|config| config.get("worktrees_dir")?.as_str().map(str::to_string))) } pub fn find_meta_dir() -> Option { @@ -232,8 +225,8 @@ pub fn lookup_project<'a>( let valid: Vec<&str> = projects.iter().map(|p| p.name.as_str()).collect(); anyhow::anyhow!( "Unknown repo alias: '{}'. Valid aliases: {}", - alias, - valid.join(", ") + escape(alias), + escape(&valid.join(", ")) ) }) } @@ -260,13 +253,13 @@ pub fn lookup_nested_project( let mut valid_paths: Vec<_> = project_map.keys().collect(); valid_paths.sort(); anyhow::anyhow!( - "Unknown nested repo: '{}'. Valid nested paths:\n {}", - alias, + "Unknown nested repo: '{}'. Valid nested paths: {}", + escape(alias), valid_paths .into_iter() - .cloned() + .map(|path| escape(path)) .collect::>() - .join("\n ") + .join(", ") ) }) } else { @@ -315,9 +308,12 @@ pub fn parse_duration(s: &str) -> Result { }; (num_str, multiplier) }; - let num: u64 = num_str - .parse() - .with_context(|| format!("Invalid duration number: '{num_str}'"))?; + let num: u64 = num_str.parse().with_context(|| { + format!( + "Invalid duration '{}': use a number with an optional s, m, h, d or w suffix", + escape(s) + ) + })?; num.checked_mul(multiplier) .filter(|secs| i64::try_from(*secs).is_ok()) @@ -513,6 +509,48 @@ mod tests { assert!(err.to_string().contains("only ASCII alphanumeric")); } + /// A user-given name in an error is shown escaped, so the error stays + /// one line with no control characters. + fn assert_escaped(err: anyhow::Error) { + let err = err.to_string(); + assert!(!err.contains('\n') && !err.contains('\x1b'), "{err:?}"); + } + + #[test] + fn errors_escape_the_names_they_show() { + for name in [ + "bad\nFORGED", + ".bad\nFORGED", + "a/\x1b]0;x\x07", + "bad\x1b[2J", + ] { + assert_escaped(validate_worktree_name(name).unwrap_err()); + } + + let projects = [meta_core::config::ProjectInfo { + name: "odd\x1b[2J".to_string(), + path: "odd".to_string(), + repo: None, + tags: vec![], + provides: vec![], + depends_on: vec![], + meta: false, + }]; + let err = lookup_project(&projects, "a\nFORGED").unwrap_err(); + assert!(err.to_string().contains("'a\\nFORGED'"), "{err}"); + assert_escaped(err); + + let tmp = tempfile::tempdir().unwrap(); + std::fs::write( + tmp.path().join(".meta"), + r#"{"projects": {"vendor": {"repo": "git@github.com:org/vendor.git", "meta": true}}}"#, + ) + .unwrap(); + for alias in ["a\nFORGED", "vendor/\nFORGED", "vendor/\x1b[2J"] { + assert_escaped(lookup_nested_project(tmp.path(), alias).unwrap_err()); + } + } + // ── parse_duration ────────────────────────────────────── #[test] diff --git a/src/worktree/hooks.rs b/src/worktree/hooks.rs index 23b6cf8..15efbd8 100644 --- a/src/worktree/hooks.rs +++ b/src/worktree/hooks.rs @@ -21,8 +21,12 @@ pub fn fire_worktree_hook(hook_name: &str, payload: &serde_json::Value, meta_dir }; let config = match read_meta_config_value(dir) { - Some(c) => c, - None => return, + Ok(Some(c)) => c, + Ok(None) => return, + Err(e) => { + log::warn!("Hook '{hook_name}' not run: {e:#}"); + return; + } }; let hook_cmd = config From d771180d569b2788a544f5d35ffc4e48257bbc5d Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 16:07:04 -0700 Subject: [PATCH 03/19] fix(config): propagate config lookup errors in worktree and git commands Adapt to meta_core's Result-returning config lookups: a config that can't be read, or two configs in one directory, is an error instead of "no config". [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 9355511..91e4991 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -97,12 +97,16 @@ pub fn read_worktrees_dir_from_config(meta_dir: &Path) -> Result> pub fn find_meta_dir() -> Option { let cwd = std::env::current_dir().ok()?; meta_core::config::find_meta_config(&cwd, None) + .ok() + .flatten() .map(|(path, _)| path.parent().unwrap_or(Path::new(".")).to_path_buf()) } /// Like `find_meta_dir()` but returns an error if not found. pub fn require_meta_dir() -> Result { - find_meta_dir().ok_or_else(|| anyhow::anyhow!("Not inside a meta project (no .meta found)")) + let cwd = std::env::current_dir()?; + meta_core::config::find_workspace_root(&cwd)? + .ok_or_else(|| anyhow::anyhow!("Not inside a meta project (no .meta found)")) } /// The directory of the worktree set `name` under `worktree_root`. A symlink @@ -175,7 +179,7 @@ pub fn discover_and_validate_worktree( /// Load and parse the .meta config, returning the project list. pub fn load_projects(meta_dir: &Path) -> Result> { - let (config_path, _) = meta_core::config::find_meta_config(meta_dir, None) + let (config_path, _) = meta_core::config::find_meta_config(meta_dir, None)? .ok_or_else(|| anyhow::anyhow!("No .meta config found in {}", escape_path(meta_dir)))?; let (projects, _) = meta_core::config::parse_meta_config(&config_path)?; Ok(projects) From bdcfa7cc97f195f08b92f198ec404a4d8e26b917 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 16:22:05 -0700 Subject: [PATCH 04/19] fix(plugins): nested meta repos share their workspace's plugins Plugin discovery reads .meta/plugins next to the nearest meta config and next to each parent config that lists it (one workspace), and no further. A legacy .meta config file means no project plugins, without a warning. workspace_root moves to meta_core so worktree scope and plugin scope share one definition; the nearest-config lookup is now nearest_meta_dir. [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 2 +- src/worktree/workspace.rs | 67 ++------------------------------------- 2 files changed, 3 insertions(+), 66 deletions(-) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 91e4991..57fee92 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -105,7 +105,7 @@ pub fn find_meta_dir() -> Option { /// Like `find_meta_dir()` but returns an error if not found. pub fn require_meta_dir() -> Result { let cwd = std::env::current_dir()?; - meta_core::config::find_workspace_root(&cwd)? + meta_core::config::nearest_meta_dir(&cwd)? .ok_or_else(|| anyhow::anyhow!("Not inside a meta project (no .meta found)")) } diff --git a/src/worktree/workspace.rs b/src/worktree/workspace.rs index e01fa0d..d73ac10 100644 --- a/src/worktree/workspace.rs +++ b/src/worktree/workspace.rs @@ -26,9 +26,9 @@ pub struct Workspace { } impl Workspace { - /// The workspace `meta_dir` belongs to (see [`workspace_root`]). + /// The workspace `meta_dir` belongs to (see [`meta_core::config::workspace_root`]). pub fn of(meta_dir: &Path) -> Workspace { - let root = workspace_root(meta_dir); + let root = meta_core::config::workspace_root(meta_dir); let mut paths = vec![root.clone()]; let mut unreadable = Vec::new(); match meta_core::config::walk_meta_tree(&root, None) { @@ -94,35 +94,6 @@ impl Workspace { } } -/// The root of the workspace `meta_dir` belongs to: `meta_dir`, or the -/// nearest meta directory above it whose project tree lists it, and so on -/// upward. A meta directory its parent doesn't list (or whose parent's tree -/// can't be read) is a workspace of its own. -pub fn workspace_root(meta_dir: &Path) -> PathBuf { - let mut root = meta_dir.to_path_buf(); - for parent in meta_dir.ancestors().skip(1) { - match meta_core::config::find_meta_config_in(parent) { - Ok(None) => continue, - Ok(Some(_)) if lists(parent, &root) => root = parent.to_path_buf(), - _ => break, - } - } - root -} - -/// Whether the project tree of the meta directory `parent` lists `dir`. -fn lists(parent: &Path, dir: &Path) -> bool { - let (Ok(tree), Ok(dir)) = ( - meta_core::config::walk_meta_tree(parent, None), - dir.canonicalize(), - ) else { - return false; - }; - meta_core::config::build_project_map(&tree, parent, "") - .into_values() - .any(|(path, _)| path.canonicalize().is_ok_and(|path| path == dir)) -} - /// The git directory holding the worktrees of the repository at `repo`: /// `None` if there is no repository there (not cloned). pub fn repo_git_dir(repo: &Path) -> Result> { @@ -165,37 +136,3 @@ pub fn repo_git_dir(repo: &Path) -> Result> { } } } - -#[cfg(test)] -mod tests { - use super::*; - - fn config(dir: &Path, projects: &str) { - std::fs::create_dir_all(dir).unwrap(); - std::fs::write( - dir.join(".meta.json"), - format!(r#"{{"projects": {{{projects}}}}}"#), - ) - .unwrap(); - } - - #[test] - fn the_root_climbs_only_through_parents_that_list_the_child() { - let tmp = tempfile::tempdir().unwrap(); - let top = tmp.path().canonicalize().unwrap(); - config(&top, r#""inner": {"repo": "x", "meta": true}"#); - config(&top.join("inner"), r#""deep": {"repo": "x", "meta": true}"#); - config(&top.join("inner/deep"), ""); - assert_eq!(workspace_root(&top.join("inner/deep")), top); - assert_eq!(workspace_root(&top.join("inner")), top); - - // A workspace inside another that doesn't list it is its own - let unlisted = top.join("inner/elsewhere"); - config(&unlisted, ""); - assert_eq!(workspace_root(&unlisted), unlisted); - // and so is one under a directory without a config - let below = top.join("plain/sub"); - config(&below, ""); - assert_eq!(workspace_root(&below), below); - } -} From ac7b0d0e321d9986caf2a64be2a4a21b14a28fd6 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 17:40:43 -0700 Subject: [PATCH 05/19] refactor(worktree): use meta_core's workspace and meta dir lookups [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 57fee92..a47ef08 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -96,10 +96,7 @@ pub fn read_worktrees_dir_from_config(meta_dir: &Path) -> Result> pub fn find_meta_dir() -> Option { let cwd = std::env::current_dir().ok()?; - meta_core::config::find_meta_config(&cwd, None) - .ok() - .flatten() - .map(|(path, _)| path.parent().unwrap_or(Path::new(".")).to_path_buf()) + meta_core::config::nearest_meta_dir(&cwd).ok().flatten() } /// Like `find_meta_dir()` but returns an error if not found. From 0b8e04f0af6de3a0041809d73069cf6a3f1e4a6a Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 18:14:15 -0700 Subject: [PATCH 06/19] refactor(worktree): record file name from meta_core [[tasks/harmony-2793]] --- src/worktree/record.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/worktree/record.rs b/src/worktree/record.rs index 738e710..3c83e7d 100644 --- a/src/worktree/record.rs +++ b/src/worktree/record.rs @@ -14,7 +14,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; /// The record's file name inside a worktree's admin directory. -pub const RECORD_FILE: &str = "meta-worktree.json"; +pub const RECORD_FILE: &str = meta_core::config::WORKTREE_RECORD_FILE; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SetRecord { From e5e3bed9823a10d232dcf9754488791f2f125df5 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 18:44:47 -0700 Subject: [PATCH 07/19] fix(worktree): a set another workspace made is foreign, even in a shared repo A worktree whose record names a project in another workspace counts as that workspace's, so a hand-made second workspace sharing the root's git dir can't prune or remove the first one's root-only sets. [[tasks/harmony-2793]] --- src/worktree/workspace.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/src/worktree/workspace.rs b/src/worktree/workspace.rs index d73ac10..d1dd7fc 100644 --- a/src/worktree/workspace.rs +++ b/src/worktree/workspace.rs @@ -67,19 +67,42 @@ impl Workspace { .is_ok_and(|git_dir| self.git_dirs.contains(&git_dir)) } + /// Whether `project`, the meta directory a record names, is in this + /// workspace. Two workspaces can share a repository (one checked out + /// with `git worktree add` from the other), so the repository alone + /// doesn't say whose a set is. A project that is gone leaves only the + /// repository to go by (prune treats such a set as orphaned). + fn made_here(&self, project: &Path) -> bool { + let root = |dir: &Path| { + let root = meta_core::config::workspace_root(dir); + root.canonicalize().unwrap_or(root) + }; + !project.exists() || root(project) == root(&self.root) + } + /// The worktrees of the set at `wt_dir` (checked as `check`) that come - /// from repositories outside this workspace, each with the workspace - /// its record names. A set with any is another workspace's. + /// from repositories outside this workspace, or that another workspace + /// made, each with the workspace its record names. A set with any is + /// another workspace's. pub fn foreign_members(&self, wt_dir: &Path, check: &RemovalCheck) -> Vec { check .members .iter() - .filter(|m| !self.holds(&m.repo_git_dir)) + .filter(|m| { + !self.holds(&m.repo_git_dir) + || m.record + .as_ref() + .is_some_and(|r| !self.made_here(&r.project)) + }) .map(|m| { let label = relative_label(wt_dir, &m.path); let repo = m.repo_git_dir.canonicalize(); let repo = escape_path(repo.as_deref().unwrap_or(&m.repo_git_dir)); match &m.record { + Some(record) if self.holds(&m.repo_git_dir) => format!( + "{label}: the workspace at {} made it", + escape_path(&record.project) + ), Some(record) => format!( "{label}: its repository {repo} is not one of this workspace's; its \ record names the workspace at {}", From ce4445a8817c6a885b142ac79abcb1437196f4c7 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 13:24:38 -0700 Subject: [PATCH 08/19] refactor(worktree): Workspace::made_here is public for prune [[tasks/harmony-2793]] --- src/worktree/workspace.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/worktree/workspace.rs b/src/worktree/workspace.rs index d1dd7fc..d57139b 100644 --- a/src/worktree/workspace.rs +++ b/src/worktree/workspace.rs @@ -72,7 +72,7 @@ impl Workspace { /// with `git worktree add` from the other), so the repository alone /// doesn't say whose a set is. A project that is gone leaves only the /// repository to go by (prune treats such a set as orphaned). - fn made_here(&self, project: &Path) -> bool { + pub fn made_here(&self, project: &Path) -> bool { let root = |dir: &Path| { let root = meta_core::config::workspace_root(dir); root.canonicalize().unwrap_or(root) From 4e1a3a1cf336e604dba306a82a4e4527680e8bd3 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 13:52:53 -0700 Subject: [PATCH 09/19] fix(worktree): escape durations, --from-pr specs and branch names in errors Workspace keeps only git dirs and resolves its root once. [[tasks/harmony-2793]] --- src/worktree/git_ops.rs | 14 ++++++++------ src/worktree/helpers.rs | 15 +++++++++++---- src/worktree/workspace.rs | 22 +++++++++++----------- 3 files changed, 30 insertions(+), 21 deletions(-) diff --git a/src/worktree/git_ops.rs b/src/worktree/git_ops.rs index aec863b..5aa37d2 100644 --- a/src/worktree/git_ops.rs +++ b/src/worktree/git_ops.rs @@ -352,7 +352,7 @@ pub fn git_rev_parse(repo_path: &Path, rev: &str) -> Result> { /// can't read is an error, not "free". pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { let full = format!("refs/heads/{branch}"); - let in_use = |by: &str| anyhow::anyhow!("'{branch}' is {by}"); + let in_use = |by: &str| anyhow::anyhow!("'{}' is {by}", escape(branch)); // A symbolic branch would carry a ref transaction to the branch it points // at, which this check never looked at. @@ -363,8 +363,9 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { Some(1) => {} Some(0) => return Err(in_use("a symbolic ref; meta only moves plain branches")), _ => anyhow::bail!( - "Cannot inspect '{branch}': {}", - String::from_utf8_lossy(&symbolic.stderr).trim() + "Cannot inspect '{}': {}", + escape(branch), + escape(String::from_utf8_lossy(&symbolic.stderr).trim()) ), } @@ -453,7 +454,7 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { /// through git's ref transaction. pub fn git_delete_branch_at(repo_path: &Path, branch: &str, expected: &str) -> Result<()> { git_branch_is_free(repo_path, branch) - .map_err(|e| anyhow::anyhow!("Branch '{branch}' is in use; kept ({e})"))?; + .map_err(|e| anyhow::anyhow!("Branch '{}' is in use; kept ({e})", escape(branch)))?; let output = git_command(repo_path) .args([ "update-ref", @@ -466,8 +467,9 @@ pub fn git_delete_branch_at(repo_path: &Path, branch: &str, expected: &str) -> R if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); anyhow::bail!( - "Branch '{branch}' no longer points where it was created; kept ({})", - stderr.trim() + "Branch '{}' no longer points where it was created; kept ({})", + escape(branch), + escape(stderr.trim()) ); } // Upstream settings of a deleted branch; there may be none. diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index a47ef08..fec2670 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -304,7 +304,8 @@ pub fn parse_duration(s: &str) -> Result { "d" => 86400, "w" => 604800, _ => anyhow::bail!( - "Invalid duration suffix '{suffix}'. Use s (seconds), m (minutes), h (hours), d (days), or w (weeks)" + "Invalid duration suffix '{}'. Use s (seconds), m (minutes), h (hours), d (days), or w (weeks)", + escape(suffix) ), }; (num_str, multiplier) @@ -318,7 +319,7 @@ pub fn parse_duration(s: &str) -> Result { num.checked_mul(multiplier) .filter(|secs| i64::try_from(*secs).is_ok()) - .ok_or_else(|| anyhow::anyhow!("Duration '{s}' is too large")) + .ok_or_else(|| anyhow::anyhow!("Duration '{}' is too large", escape(s))) } /// Format seconds into a human-friendly duration string. @@ -351,13 +352,19 @@ pub fn resolve_from_pr(from_pr: &str) -> Result<(String, u32, String)> { // Parse format: owner/repo#N let hash_pos = from_pr.rfind('#').ok_or_else(|| { - anyhow::anyhow!("Invalid --from-pr format: '{from_pr}'. Expected: owner/repo#N") + anyhow::anyhow!( + "Invalid --from-pr format: '{}'. Expected: owner/repo#N", + escape(from_pr) + ) })?; let repo_spec = &from_pr[..hash_pos]; // Validate repo spec format: must be owner/repo if !repo_spec.contains('/') || repo_spec.starts_with('/') || repo_spec.ends_with('/') { - anyhow::bail!("Invalid repo spec '{repo_spec}' in --from-pr. Expected: owner/repo#N"); + anyhow::bail!( + "Invalid repo spec '{}' in --from-pr. Expected: owner/repo#N", + escape(repo_spec) + ); } let pr_num: u32 = from_pr[hash_pos + 1..] .parse() diff --git a/src/worktree/workspace.rs b/src/worktree/workspace.rs index d57139b..f13df51 100644 --- a/src/worktree/workspace.rs +++ b/src/worktree/workspace.rs @@ -15,14 +15,16 @@ use super::safety::{relative_label, RemovalCheck}; /// A workspace's root meta directory and its repositories. pub struct Workspace { pub root: PathBuf, - /// Each repository (the root's own, then every one in its `.meta` - /// tree, nested ones included) with its git directory: where the - /// records of the worktrees made from it are. - pub repos: Vec<(PathBuf, PathBuf)>, + /// The git directory of each repository (the root's own, then every one + /// in its `.meta` tree, nested ones included): where the records of the + /// worktrees made from it are. + pub repos: Vec, /// What couldn't be read (the project tree, a repository), with why: /// worktrees from there count as another workspace's. pub unreadable: Vec<(PathBuf, anyhow::Error)>, git_dirs: HashSet, + /// `root`, resolved, to compare other workspaces' roots with. + canonical_root: PathBuf, } impl Workspace { @@ -42,16 +44,17 @@ impl Workspace { let mut repos = Vec::new(); for path in paths { match repo_git_dir(&path) { - Ok(Some(git_dir)) => repos.push((path, git_dir)), + Ok(Some(git_dir)) => repos.push(git_dir), Ok(None) => {} Err(e) => unreadable.push((path, e)), } } let git_dirs = repos .iter() - .filter_map(|(_, git_dir)| git_dir.canonicalize().ok()) + .filter_map(|git_dir| git_dir.canonicalize().ok()) .collect(); Workspace { + canonical_root: root.canonicalize().unwrap_or_else(|_| root.clone()), root, repos, unreadable, @@ -73,11 +76,8 @@ impl Workspace { /// doesn't say whose a set is. A project that is gone leaves only the /// repository to go by (prune treats such a set as orphaned). pub fn made_here(&self, project: &Path) -> bool { - let root = |dir: &Path| { - let root = meta_core::config::workspace_root(dir); - root.canonicalize().unwrap_or(root) - }; - !project.exists() || root(project) == root(&self.root) + let root = meta_core::config::workspace_root(project); + !project.exists() || root.canonicalize().unwrap_or(root) == self.canonical_root } /// The worktrees of the set at `wt_dir` (checked as `check`) that come From b7d7ae76f95504fe4d8641932893822095ae7bdd Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 14:24:17 -0700 Subject: [PATCH 10/19] fix(worktree): unknown ownership is not ours; escape the rest A record whose project is gone or moved is not this workspace's. resolve_worktree_root resolves from the checkout a set checkout stands for. Worktree names are validated for exec/status/diff; --from-pr, branch and git error text are escaped. [[tasks/harmony-2793]] --- src/worktree/git_ops.rs | 15 ++++++++------- src/worktree/helpers.rs | 29 +++++++++++++++++++++++------ src/worktree/workspace.rs | 6 +++--- 3 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/worktree/git_ops.rs b/src/worktree/git_ops.rs index 5aa37d2..b8e7f8f 100644 --- a/src/worktree/git_ops.rs +++ b/src/worktree/git_ops.rs @@ -106,9 +106,9 @@ pub fn git_worktree_add( anyhow::bail!( "git worktree add failed for '{}' (branch: {}, ref: {}): {}", escape_path(repo_path), - branch, - ref_name, - stderr.trim() + escape(branch), + escape(ref_name), + escape(stderr.trim()) ); } return Ok(Some(start)); // Always creates a new branch from ref @@ -155,8 +155,8 @@ pub fn git_worktree_add( anyhow::bail!( "git worktree add failed for '{}' (branch: {}): {}", escape_path(repo_path), - branch, - stderr.trim() + escape(branch), + escape(stderr.trim()) ); } @@ -337,9 +337,10 @@ pub fn git_rev_parse(repo_path: &Path, rev: &str) -> Result> { return Ok(None); } anyhow::bail!( - "git rev-parse {rev} failed in {}: {}", + "git rev-parse {} failed in {}: {}", + escape(rev), escape_path(repo_path), - stderr.trim() + escape(stderr.trim()) ) } diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index fec2670..47ea604 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -32,8 +32,10 @@ pub fn resolve_worktree_root(meta_dir: Option<&Path>) -> Result { if let Ok(env_path) = std::env::var("META_WORKTREES") { return Ok(PathBuf::from(env_path)); } - // 2. Check worktrees_dir in .meta config - if let Some(dir) = meta_dir { + // 2. Check worktrees_dir in .meta config. In a worktree set, of the + // checkout it stands for: its sets live where that one's do + let source = meta_dir.and_then(meta_core::config::set_source); + if let Some(dir) = source.as_deref().filter(|s| s.is_dir()).or(meta_dir) { // The config's rules for the worktree directory (inside the // workspace, not inside a project, not into .git) hold here too, // whoever ran this plugin @@ -149,6 +151,7 @@ pub fn resolve_worktree_context(name: &str) -> Result { /// Resolve worktree context and verify the worktree exists. pub fn resolve_existing_worktree(name: &str) -> Result { + validate_worktree_name(name)?; let ctx = resolve_worktree_context(name)?; if !ctx.wt_dir.exists() { anyhow::bail!( @@ -368,7 +371,7 @@ pub fn resolve_from_pr(from_pr: &str) -> Result<(String, u32, String)> { } let pr_num: u32 = from_pr[hash_pos + 1..] .parse() - .with_context(|| format!("Invalid PR number in '{from_pr}'"))?; + .with_context(|| format!("Invalid PR number in '{}'", escape(from_pr)))?; // Resolve head branch via gh CLI let output = Command::new("gh") @@ -391,14 +394,17 @@ pub fn resolve_from_pr(from_pr: &str) -> Result<(String, u32, String)> { anyhow::bail!( "Failed to resolve PR #{} in {}: {}", pr_num, - repo_spec, - stderr.trim() + escape(repo_spec), + escape(stderr.trim()) ); } let branch = String::from_utf8_lossy(&output.stdout).trim().to_string(); if branch.is_empty() { - anyhow::bail!("Empty head branch for PR #{pr_num} in {repo_spec}"); + anyhow::bail!( + "Empty head branch for PR #{pr_num} in {}", + escape(repo_spec) + ); } Ok((repo_spec.to_string(), pr_num, branch)) @@ -524,6 +530,17 @@ mod tests { assert!(!err.contains('\n') && !err.contains('\x1b'), "{err:?}"); } + #[test] + fn from_pr_errors_escape_the_spec() { + for spec in ["o/r#1\u{1b}[2J\nFORGED", "bad\u{1b}[2J\nFORGED"] { + let message = format!("{:#}", resolve_from_pr(spec).unwrap_err()); + assert!( + !message.contains('\n') && !message.contains('\u{1b}'), + "{message}" + ); + } + } + #[test] fn errors_escape_the_names_they_show() { for name in [ diff --git a/src/worktree/workspace.rs b/src/worktree/workspace.rs index f13df51..cabe6fa 100644 --- a/src/worktree/workspace.rs +++ b/src/worktree/workspace.rs @@ -73,11 +73,11 @@ impl Workspace { /// Whether `project`, the meta directory a record names, is in this /// workspace. Two workspaces can share a repository (one checked out /// with `git worktree add` from the other), so the repository alone - /// doesn't say whose a set is. A project that is gone leaves only the - /// repository to go by (prune treats such a set as orphaned). + /// doesn't say whose a set is. A project that is gone (or moved) leaves + /// its sets of unknown ownership: not this workspace's. pub fn made_here(&self, project: &Path) -> bool { let root = meta_core::config::workspace_root(project); - !project.exists() || root.canonicalize().unwrap_or(root) == self.canonical_root + project.exists() && root.canonicalize().unwrap_or(root) == self.canonical_root } /// The worktrees of the set at `wt_dir` (checked as `check`) that come From 4c2482d401ccaf5446c36a1e6a3214c8d1aa077b Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 15:10:21 -0700 Subject: [PATCH 11/19] fix(worktree): place set members at their path; name a gone workspace place_in_set puts each repo where it is in the workspace. A refusal for a set whose workspace is gone points to git worktree remove. [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 20 ++++++++++++++++++++ src/worktree/workspace.rs | 5 +++++ 2 files changed, 25 insertions(+) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 47ea604..3e21ff3 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -235,6 +235,26 @@ pub fn lookup_project<'a>( }) } +/// Where the repo at `source`, found from `meta_dir` under `alias`, goes in +/// a worktree set: its path from the meta dir, so a set lays its repos out +/// as the workspace does (its copied config stays right, and relative +/// references between repos, such as Cargo workspace members, hold). The +/// alias stands in for a source outside the meta dir. +pub fn place_in_set(meta_dir: &Path, alias: &str, source: &Path) -> String { + source + .strip_prefix(meta_dir) + .ok() + .filter(|place| !place.as_os_str().is_empty()) + .map(|place| { + place + .components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect::>() + .join("/") + }) + .unwrap_or_else(|| alias.to_string()) +} + /// Look up a project by alias, supporting nested paths like "vendor/tree-sitter-markdown". /// /// For simple aliases (no `/`), uses flat lookup from the current .meta. diff --git a/src/worktree/workspace.rs b/src/worktree/workspace.rs index cabe6fa..422509a 100644 --- a/src/worktree/workspace.rs +++ b/src/worktree/workspace.rs @@ -99,6 +99,11 @@ impl Workspace { let repo = m.repo_git_dir.canonicalize(); let repo = escape_path(repo.as_deref().unwrap_or(&m.repo_git_dir)); match &m.record { + Some(record) if !record.project.exists() => format!( + "{label}: the workspace at {} made it, and it is gone or was moved; \ + remove this worktree with 'git worktree remove'", + escape_path(&record.project) + ), Some(record) if self.holds(&m.repo_git_dir) => format!( "{label}: the workspace at {} made it", escape_path(&record.project) From 7be1de3daba8d11be6c68d3cf807919c3d347c49 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 15:29:55 -0700 Subject: [PATCH 12/19] fix(worktree): place_in_set compares resolved paths [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 3e21ff3..6452ee1 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -241,8 +241,9 @@ pub fn lookup_project<'a>( /// references between repos, such as Cargo workspace members, hold). The /// alias stands in for a source outside the meta dir. pub fn place_in_set(meta_dir: &Path, alias: &str, source: &Path) -> String { - source - .strip_prefix(meta_dir) + let resolve = |path: &Path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); + resolve(source) + .strip_prefix(resolve(meta_dir)) .ok() .filter(|place| !place.as_os_str().is_empty()) .map(|place| { From 6ac876f4242a04114984e6e0a7294d7e92fa9b2e Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 16:04:37 -0700 Subject: [PATCH 13/19] fix(worktree): a set keeps a project's configured path, links included [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 6452ee1..15927a5 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -241,9 +241,17 @@ pub fn lookup_project<'a>( /// references between repos, such as Cargo workspace members, hold). The /// alias stands in for a source outside the meta dir. pub fn place_in_set(meta_dir: &Path, alias: &str, source: &Path) -> String { + // The configured path, as written (a link inside the workspace stays the + // link); resolved only when the two are spelled differently let resolve = |path: &Path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); - resolve(source) - .strip_prefix(resolve(meta_dir)) + source + .strip_prefix(meta_dir) + .map(Path::to_path_buf) + .or_else(|_| { + resolve(source) + .strip_prefix(resolve(meta_dir)) + .map(Path::to_path_buf) + }) .ok() .filter(|place| !place.as_os_str().is_empty()) .map(|place| { From 76016da2f95416d46e2cb2c57241b8c665ca327a Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 16:24:27 -0700 Subject: [PATCH 14/19] fix(worktree): escape git's error text in worktree messages [[tasks/harmony-2793]] --- src/worktree/git_ops.rs | 31 +++++++++++++++++++++++++------ src/worktree/safety.rs | 10 +++++----- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/src/worktree/git_ops.rs b/src/worktree/git_ops.rs index b8e7f8f..aa8a5e6 100644 --- a/src/worktree/git_ops.rs +++ b/src/worktree/git_ops.rs @@ -68,7 +68,7 @@ fn ensure_checkout_config_is_not_bare(repo_path: &Path) -> Result<()> { anyhow::bail!( "Failed to inspect core.bare for '{}': {}", escape_path(repo_path), - stderr.trim() + escape(stderr.trim()) ); } @@ -177,7 +177,7 @@ pub fn git_worktree_remove(repo_path: &Path, worktree_path: &Path, force: bool) if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); - anyhow::bail!("git worktree remove failed: {}", stderr.trim()); + anyhow::bail!("git worktree remove failed: {}", escape(stderr.trim())); } Ok(()) } @@ -194,7 +194,7 @@ pub fn git_status_summary(repo_path: &Path) -> Result { anyhow::bail!( "git status failed for '{}': {}", escape_path(repo_path), - stderr.trim() + escape(stderr.trim()) ); } @@ -377,7 +377,7 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { list.status.success(), "Cannot list the worktrees of {}: {}", escape_path(repo_path), - String::from_utf8_lossy(&list.stderr).trim() + escape(String::from_utf8_lossy(&list.stderr).trim()) ); let wanted = format!("branch {full}"); if String::from_utf8_lossy(&list.stdout) @@ -394,7 +394,7 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { output.status.success(), "Cannot find the git directory of {}: {}", escape_path(repo_path), - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); // Relative output is relative to the repository, where git ran. let common = @@ -489,7 +489,11 @@ pub fn git_fetch_branch(repo_path: &Path, branch: &str) -> Result<()> { if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); - anyhow::bail!("Failed to fetch branch '{}': {}", branch, stderr.trim()); + anyhow::bail!( + "Failed to fetch branch '{}': {}", + escape(branch), + escape(stderr.trim()) + ); } Ok(()) } @@ -499,6 +503,21 @@ mod tests { use super::*; use std::collections::BTreeSet; + #[test] + fn a_failed_fetch_is_reported_on_one_line() { + let tmp = init_git_repo(); + git_command(tmp.path()) + .args(["remote", "add", "origin", "/nonexistent/r\u{1b}[2J\nFORGED"]) + .status() + .unwrap(); + let err = git_fetch_branch(tmp.path(), "b\u{1b}[2J\nFORGED").unwrap_err(); + let message = format!("{err:#}"); + assert!( + !message.contains('\n') && !message.contains('\u{1b}'), + "{message}" + ); + } + /// Create a minimal git repo in a tempdir and return the tempdir handle. fn init_git_repo() -> tempfile::TempDir { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/worktree/safety.rs b/src/worktree/safety.rs index 7291f7a..bfac413 100644 --- a/src/worktree/safety.rs +++ b/src/worktree/safety.rs @@ -468,7 +468,7 @@ fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String anyhow::ensure!( output.status.success(), "git status failed: {}", - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); // Exact, for the re-check: raw bytes, not a lossy decoding. let text = format!("{:?}", output.stdout); @@ -532,7 +532,7 @@ fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String anyhow::ensure!( output.status.success(), "git rev-list failed: {}", - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); let commits = String::from_utf8_lossy(&output.stdout).into_owned(); let stranded = commits.lines().count(); @@ -550,7 +550,7 @@ fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String anyhow::ensure!( staged.status.success(), "git diff --cached failed: {}", - String::from_utf8_lossy(&staged.stderr).trim() + escape(String::from_utf8_lossy(&staged.stderr).trim()) ); let staged = String::from_utf8_lossy(&staged.stdout).into_owned(); let files: Vec = modified @@ -581,7 +581,7 @@ fn hidden_files(repo: &Path) -> Result> { anyhow::ensure!( output.status.success(), "git ls-files failed: {}", - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); // Entries are " "; a lowercase tag means assume-unchanged, // "S" skip-worktree. @@ -629,7 +629,7 @@ fn operation_in_progress(repo: &Path) -> Result> { anyhow::ensure!( output.status.success(), "git rev-parse --git-dir failed: {}", - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); let git_dir = repo.join(String::from_utf8_lossy(&output.stdout).trim_end_matches(['\n', '\r'])); let markers = [ From b82517996406c44c3dc66ab09239a23ea24c3ff2 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 16:47:36 -0700 Subject: [PATCH 15/19] feat(worktree): check a repo out where a link at its place leads dest_in_set: the repo placed at a link a checkout already holds goes where the link leads, inside the set. Implements [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 15927a5..399d4d9 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -264,6 +264,19 @@ pub fn place_in_set(meta_dir: &Path, alias: &str, source: &Path) -> String { .unwrap_or_else(|| alias.to_string()) } +/// Where the repo placed at `place` is checked out in the set at `wt_dir`: +/// there, or where a link a checkout already put there leads, as in the +/// workspace. Refused when a link leads outside the set. +pub fn dest_in_set(wt_dir: &Path, place: &str) -> Result { + let resolved = meta_core::config::resolve_inside(wt_dir, place)?; + let plain = wt_dir.canonicalize().map(|dir| dir.join(place)).ok(); + Ok(if plain.as_ref() == Some(&resolved) { + wt_dir.join(place) + } else { + resolved + }) +} + /// Look up a project by alias, supporting nested paths like "vendor/tree-sitter-markdown". /// /// For simple aliases (no `/`), uses flat lookup from the current .meta. From 81443587494592eb3bee8d8c554864617a3b4b51 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 18:15:33 -0700 Subject: [PATCH 16/19] fix(worktree): escape the set name in 'No repos found' Implements [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 399d4d9..0aae2fc 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -172,7 +172,7 @@ pub fn discover_and_validate_worktree( let ctx = resolve_existing_worktree(name)?; let repos = meta_cli::worktree::discover_worktree_repos(&ctx.wt_dir)?; if repos.is_empty() { - anyhow::bail!("No repos found in worktree '{name}'"); + anyhow::bail!("No repos found in worktree '{}'", escape(name)); } Ok(repos) } From 856d5fbd35aac60b672e695b1bc3e4df8ac210b1 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 19:21:37 -0700 Subject: [PATCH 17/19] feat(worktree): owner_dir, the meta dir whose settings a set's are Inside a set, the checkout it stands for, which outlives the set. Implements [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 0aae2fc..18e89e6 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -235,6 +235,14 @@ pub fn lookup_project<'a>( }) } +/// The meta directory whose sets and settings (such as hooks) `meta_dir`'s +/// are: inside a set, the checkout the set stands for, which outlives it. +pub fn owner_dir(meta_dir: &Path) -> PathBuf { + meta_core::config::set_source(meta_dir) + .filter(|source| source.is_dir()) + .unwrap_or_else(|| meta_dir.to_path_buf()) +} + /// Where the repo at `source`, found from `meta_dir` under `alias`, goes in /// a worktree set: its path from the meta dir, so a set lays its repos out /// as the workspace does (its copied config stays right, and relative From 192c086c699f9109068776c9e7325bb571c3f928 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 19:40:40 -0700 Subject: [PATCH 18/19] fix(worktree): hooks run in the directory of their config; escape the hook warning Implements [[tasks/harmony-2793]] --- src/worktree/hooks.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/worktree/hooks.rs b/src/worktree/hooks.rs index 15efbd8..da1465f 100644 --- a/src/worktree/hooks.rs +++ b/src/worktree/hooks.rs @@ -24,7 +24,10 @@ pub fn fire_worktree_hook(hook_name: &str, payload: &serde_json::Value, meta_dir Ok(Some(c)) => c, Ok(None) => return, Err(e) => { - log::warn!("Hook '{hook_name}' not run: {e:#}"); + log::warn!( + "Hook '{hook_name}' not run: {}", + meta_core::display::escape_lines(&format!("{e:#}")) + ); return; } }; @@ -45,8 +48,11 @@ pub fn fire_worktree_hook(hook_name: &str, payload: &serde_json::Value, meta_dir Err(_) => return, }; + // From the directory whose config names the hook: a set removed from + // inside it takes the caller's directory with it let result = Command::new("sh") .args(["-c", cmd_str]) + .current_dir(dir) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::inherit()) From 88b5d8fb78edbe209a0da9b28733fe7b1cc98cb6 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 20:18:28 -0700 Subject: [PATCH 19/19] refactor(worktree): resolve_worktree_root uses owner_dir Implements [[tasks/harmony-2793]] --- src/worktree/helpers.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 18e89e6..a67321b 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -34,8 +34,8 @@ pub fn resolve_worktree_root(meta_dir: Option<&Path>) -> Result { } // 2. Check worktrees_dir in .meta config. In a worktree set, of the // checkout it stands for: its sets live where that one's do - let source = meta_dir.and_then(meta_core::config::set_source); - if let Some(dir) = source.as_deref().filter(|s| s.is_dir()).or(meta_dir) { + if let Some(dir) = meta_dir.map(owner_dir) { + let dir = dir.as_path(); // The config's rules for the worktree directory (inside the // workspace, not inside a project, not into .git) hold here too, // whoever ran this plugin