From 449652b47b1b178d6aa2034b85a85337e06cf711 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 15:55:02 -0700 Subject: [PATCH 01/23] fix(config): reject duplicate projects and remove data dir test races Reject duplicate project keys with their file and key named. Exercise data directory helpers with explicit paths instead of mutating process environment. [[tasks/harmony-2793]] --- src/config.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++++++- src/data_dir.rs | 19 ++++++++------ 2 files changed, 77 insertions(+), 9 deletions(-) diff --git a/src/config.rs b/src/config.rs index 2c4c044..842834b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -199,9 +199,48 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, ) })?; + #[derive(Deserialize)] + struct CheckedConfig { + #[serde(default, deserialize_with = "unique_projects")] + projects: HashMap, + #[serde(flatten)] + config: MetaConfig, + } + + fn unique_projects<'de, D: serde::Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + struct ProjectsVisitor; + impl<'de> serde::de::Visitor<'de> for ProjectsVisitor { + type Value = HashMap; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a map of unique project keys") + } + + fn visit_map>( + self, + mut map: M, + ) -> Result { + let mut projects = HashMap::new(); + while let Some(key) = map.next_key::()? { + if projects.contains_key(&key) { + return Err(serde::de::Error::custom(format!( + "duplicate project key '{}'", + escape(&key) + ))); + } + projects.insert(key, map.next_value()?); + } + Ok(projects) + } + } + deserializer.deserialize_map(ProjectsVisitor) + } + // Determine format from file extension let path_str = meta_path.to_string_lossy(); - let config: MetaConfig = if path_str.ends_with(".yaml") || path_str.ends_with(".yml") { + let checked: CheckedConfig = if path_str.ends_with(".yaml") || path_str.ends_with(".yml") { serde_yaml_ng::from_str(&config_str).with_context(|| { format!( "Failed to parse YAML config file: {}", @@ -217,6 +256,9 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, })? }; + let mut config = checked.config; + config.projects = checked.projects; + // Convert project entries to normalized, validated ProjectInfo // in name order, so the first bad entry reported is always the same one let base_dir = meta_path @@ -2093,3 +2135,26 @@ mod tests { assert!(!tree[0].is_meta); } } + +#[cfg(test)] +mod duplicate_project_tests { + #[test] + fn duplicate_project_keys_name_file_and_key() { + let dir = tempfile::tempdir().unwrap(); + for (file, content) in [ + (".meta", r#"{"projects":{"dup":"first","dup":"second"}}"#), + ( + ".meta.json", + r#"{"projects":{"dup":"first","dup":"second"}}"#, + ), + (".meta.yaml", "projects:\n dup: first\n dup: second\n"), + (".meta.yml", "projects:\n dup: first\n dup: second\n"), + ] { + let path = dir.path().join(file); + std::fs::write(&path, content).unwrap(); + let err = format!("{:#}", super::parse_meta_config(&path).unwrap_err()); + assert!(err.contains(file), "{err}"); + assert!(err.contains("duplicate project key 'dup'"), "{err}"); + } + } +} diff --git a/src/data_dir.rs b/src/data_dir.rs index be002e4..25fea81 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -15,7 +15,10 @@ use std::path::{Path, PathBuf}; /// Ensure the meta data directory exists, creating it if needed. /// Returns the path to the directory. pub fn ensure_meta_dir() -> Result { - let dir = crate::meta_dir()?; + ensure_meta_dir_at(crate::meta_dir()?) +} + +fn ensure_meta_dir_at(dir: PathBuf) -> Result { create_private_dir(&dir)?; Ok(dir) } @@ -25,7 +28,11 @@ pub fn ensure_meta_dir() -> Result { /// The file may or may not exist. Use `store::read` to read with a default, /// or check existence manually. pub fn data_file(namespace: &str) -> Result { - Ok(crate::meta_dir()?.join(format!("{namespace}.json"))) + Ok(data_file_at(&crate::meta_dir()?, namespace)) +} + +fn data_file_at(dir: &Path, namespace: &str) -> PathBuf { + dir.join(format!("{namespace}.json")) } /// Get the path for a namespaced subdirectory: `~/.meta//`. @@ -57,17 +64,14 @@ mod tests { #[test] fn test_data_file_path() { let tmp = tempfile::tempdir().unwrap(); - std::env::set_var("META_DATA_DIR", tmp.path()); - let path = data_file("worktree").unwrap(); + let path = data_file_at(tmp.path(), "worktree"); assert_eq!(path, tmp.path().join("worktree.json")); - std::env::remove_var("META_DATA_DIR"); } #[test] fn test_ensure_meta_dir() { let tmp = tempfile::tempdir().unwrap(); - std::env::set_var("META_DATA_DIR", tmp.path().join("meta-test")); - let result = ensure_meta_dir().unwrap(); + let result = ensure_meta_dir_at(tmp.path().join("meta-test")).unwrap(); assert!(result.exists()); #[cfg(unix)] { @@ -75,6 +79,5 @@ mod tests { let mode = std::fs::metadata(&result).unwrap().permissions().mode(); assert_eq!(mode & 0o777, 0o700); } - std::env::remove_var("META_DATA_DIR"); } } From 7428ae051ad32391b6b13151c5e53227652ad244 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 15:55:40 -0700 Subject: [PATCH 02/23] fix(config): reject ambiguous configs and share workspace lookup Propagate discovery errors and retain the actual parent config for orphan hints. [[tasks/harmony-2793]] --- src/config.rs | 252 ++++++++++++++++++++++++++++++++++---------------- 1 file changed, 172 insertions(+), 80 deletions(-) diff --git a/src/config.rs b/src/config.rs index 842834b..de4a787 100644 --- a/src/config.rs +++ b/src/config.rs @@ -104,86 +104,99 @@ pub enum ConfigFormat { Yaml, } -/// The config file directly in directory `dir` (`.meta`, `.meta.json`, -/// `.meta.yaml`, `.meta.yml`, in that order). Only a missing directory or -/// file means there is none: one -/// that cannot be examined (no permission, a link whose target is out of -/// reach) is an error, since skipping it would silently drop its repos. -/// A `.meta` directory (the plugins folder) is not a config. +/// Supported config filenames. Exactly one may be a file in a directory. +pub const META_CONFIG_NAMES: [&str; 4] = [".meta", ".meta.json", ".meta.yaml", ".meta.yml"]; + +fn config_format(path: &Path) -> ConfigFormat { + match path.extension().and_then(|ext| ext.to_str()) { + Some("yaml" | "yml") => ConfigFormat::Yaml, + _ => ConfigFormat::Json, + } +} + +fn config_file_exists(path: &Path) -> anyhow::Result { + let unreadable = |e| anyhow::anyhow!("Cannot read {}: {e}", escape_path(path)); + match std::fs::symlink_metadata(path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(e) => return Err(unreadable(e)), + Ok(_) => {} + } + std::fs::metadata(path) + .map(|meta| meta.is_file()) + .map_err(unreadable) +} + +/// Find the config directly in `dir`, using [`META_CONFIG_NAMES`]. +/// Multiple config files or a candidate that cannot be examined are errors. +/// A `.meta` directory (for plugins and skills) is never a config. pub fn find_meta_config_in(dir: &Path) -> anyhow::Result> { - let unreadable = - |path: &Path, e: std::io::Error| anyhow::anyhow!("Cannot read {}: {e}", escape_path(path)); match std::fs::metadata(dir) { Ok(meta) if meta.is_dir() => {} Ok(_) => return Ok(None), Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(e) => return Err(unreadable(dir, e)), - } - for (name, format) in &[ - (".meta", ConfigFormat::Json), - (".meta.json", ConfigFormat::Json), - (".meta.yaml", ConfigFormat::Yaml), - (".meta.yml", ConfigFormat::Yaml), - ] { + Err(e) => return Err(e).with_context(|| format!("Cannot read {}", escape_path(dir))), + } + let mut found = Vec::new(); + for name in META_CONFIG_NAMES { let candidate = dir.join(name); - match std::fs::symlink_metadata(&candidate) { - Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, - Err(e) => return Err(unreadable(&candidate, e)), - Ok(_) => {} - } - match std::fs::metadata(&candidate) { - Ok(meta) if meta.is_file() => return Ok(Some((candidate, format.clone()))), - Ok(_) => continue, - Err(e) => return Err(unreadable(&candidate, e)), + if config_file_exists(&candidate)? { + found.push(candidate); } } - Ok(None) + if found.len() > 1 { + anyhow::bail!( + "Multiple meta config files in {}: {}. Keep exactly one config file.", + escape_path(dir), + found + .iter() + .map(|p| escape_path(p)) + .collect::>() + .join(", ") + ); + } + if let Some(path) = found.pop() { + std::fs::File::open(&path) + .with_context(|| format!("Cannot read {}", escape_path(&path)))?; + let format = config_format(&path); + Ok(Some((path, format))) + } else { + Ok(None) + } } -/// Find the meta config file, checking for .meta, .meta.yaml, and .meta.yml -/// -/// Walks up from `start_dir` to the filesystem root, looking for config files. -/// If `config_name` is provided, only looks for that specific filename. +/// Find the nearest config, walking from `start_dir` to the filesystem root. +/// Uses [`META_CONFIG_NAMES`], refusing ambiguous or unreadable configs. +/// An explicit `config_name` selects only that filename instead. pub fn find_meta_config( start_dir: &Path, config_name: Option<&PathBuf>, -) -> Option<(PathBuf, ConfigFormat)> { - let candidates: Vec<(String, ConfigFormat)> = if let Some(name) = config_name { - // User specified a config file name - let name_str = name.to_string_lossy().to_string(); - if name_str.ends_with(".yaml") || name_str.ends_with(".yml") { - vec![(name_str, ConfigFormat::Yaml)] - } else { - vec![(name_str, ConfigFormat::Json)] - } - } else { - // Default: check all supported names - vec![ - (".meta".to_string(), ConfigFormat::Json), - (".meta.json".to_string(), ConfigFormat::Json), - (".meta.yaml".to_string(), ConfigFormat::Yaml), - (".meta.yml".to_string(), ConfigFormat::Yaml), - ] - }; - - let mut current_dir = start_dir.to_path_buf(); - loop { - for (name, format) in &candidates { - let candidate = current_dir.join(name); - // A candidate that exists but can't be examined is returned, so - // reading it fails loudly, rather than skipped for a config - // further up (another workspace's) - let found = match std::fs::symlink_metadata(&candidate) { - Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, - Err(_) => true, - Ok(_) => !matches!(std::fs::metadata(&candidate), Ok(meta) if !meta.is_file()), - }; - if found { - return Some((candidate, format.clone())); +) -> anyhow::Result> { + for dir in start_dir.ancestors() { + let found = if let Some(name) = config_name { + let path = dir.join(name); + if config_file_exists(&path)? { + std::fs::File::open(&path) + .with_context(|| format!("Cannot read {}", escape_path(&path)))?; + let format = config_format(&path); + Some((path, format)) + } else { + None } + } else { + find_meta_config_in(dir)? + }; + if found.is_some() { + return Ok(found); } - current_dir = current_dir.parent()?.to_path_buf(); } + Ok(None) +} + +/// Nearest directory holding a config file, used for project-local plugins. +/// Plugin scope follows cwd, independently of a command's explicit `--config`. +pub fn find_workspace_root(start_dir: &Path) -> anyhow::Result> { + Ok(find_meta_config(start_dir, None)? + .and_then(|(path, _)| path.parent().map(Path::to_path_buf))) } /// Parse a meta config file (JSON or YAML) and return normalized project info and ignore list. @@ -720,7 +733,7 @@ pub fn walk_meta_tree( start_dir: &Path, max_depth: Option, ) -> anyhow::Result> { - let (config_path, _format) = find_meta_config(start_dir, None) + let (config_path, _format) = find_meta_config(start_dir, None)? .ok_or_else(|| anyhow::anyhow!("No .meta config found in {}", escape_path(start_dir)))?; let (projects, _ignore) = parse_meta_config(&config_path)?; @@ -800,6 +813,8 @@ pub struct OrphanWarning { pub current: PathBuf, /// Path to the parent meta directory pub parent: PathBuf, + /// Actual parent config path for the inclusion hint. + pub parent_config: PathBuf, /// Suggested key to add to parent's .meta file pub suggested_key: String, /// Format of the parent's config file (for showing appropriate syntax) @@ -810,9 +825,11 @@ pub struct OrphanWarning { /// /// Starts searching from the parent of `meta_dir` and walks up. /// Returns None if this is the root meta repo (no parent .meta found). -pub fn find_parent_meta_config(meta_dir: &Path) -> Option<(PathBuf, ConfigFormat)> { - let parent = meta_dir.parent()?; - find_meta_config(parent, None) +pub fn find_parent_meta_config(meta_dir: &Path) -> anyhow::Result> { + match meta_dir.parent() { + Some(parent) => find_meta_config(parent, None), + None => Ok(None), + } } /// Find the root (topmost) meta directory by walking up through parent .meta configs. @@ -820,17 +837,22 @@ pub fn find_parent_meta_config(meta_dir: &Path) -> Option<(PathBuf, ConfigFormat /// Starting from `meta_dir`, repeatedly calls `find_parent_meta_config` until /// no more parents are found. Returns the topmost meta directory in the hierarchy. /// If `meta_dir` is already the root, returns it unchanged. -pub fn find_root_meta_dir(meta_dir: &Path) -> PathBuf { +pub fn find_root_meta_dir(meta_dir: &Path) -> anyhow::Result { let mut current = meta_dir.to_path_buf(); loop { - match find_parent_meta_config(¤t) { + match find_parent_meta_config(¤t)? { Some((parent_config_path, _format)) => { current = parent_config_path .parent() - .expect("config file path should always have a parent directory") + .ok_or_else(|| { + anyhow::anyhow!( + "Config path has no parent: {}", + escape_path(&parent_config_path) + ) + })? .to_path_buf(); } - None => break current, + None => break Ok(current), } } } @@ -841,7 +863,7 @@ pub fn find_root_meta_dir(meta_dir: &Path) -> PathBuf { /// this directory in its project list (directly or transitively). /// Returns `None` if tracked or if there's no parent meta. pub fn check_orphan_status(meta_dir: &Path) -> Option { - let (parent_config, parent_format) = find_parent_meta_config(meta_dir)?; + let (parent_config, parent_format) = find_parent_meta_config(meta_dir).ok()??; let parent_meta_dir = parent_config.parent()?; // Walk the parent's project tree to see what's tracked @@ -871,6 +893,7 @@ pub fn check_orphan_status(meta_dir: &Path) -> Option { Some(OrphanWarning { current: meta_dir.to_path_buf(), parent: parent_meta_dir.to_path_buf(), + parent_config: parent_config.clone(), suggested_key, parent_format, }) @@ -1337,7 +1360,7 @@ mod tests { std::fs::write(dir.path().join(".meta"), r#"{"projects": {}}"#).unwrap(); // No parent above this directory - let result = find_parent_meta_config(dir.path()); + let result = find_parent_meta_config(dir.path()).unwrap(); assert!(result.is_none()); } @@ -1352,7 +1375,7 @@ mod tests { // Nested .meta std::fs::write(nested.join(".meta"), r#"{"projects": {}}"#).unwrap(); - let result = find_parent_meta_config(&nested); + let result = find_parent_meta_config(&nested).unwrap(); assert!(result.is_some()); let (path, _) = result.unwrap(); assert_eq!(path, dir.path().join(".meta")); @@ -2055,7 +2078,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); std::fs::write(dir.path().join(".meta"), r#"{"projects": {}}"#).unwrap(); - let root = find_root_meta_dir(dir.path()); + let root = find_root_meta_dir(dir.path()).unwrap(); assert_eq!(root, dir.path()); } @@ -2073,7 +2096,7 @@ mod tests { .unwrap(); std::fs::write(child.join(".meta"), r#"{"projects": {}}"#).unwrap(); - let root = find_root_meta_dir(&child); + let root = find_root_meta_dir(&child).unwrap(); assert_eq!(root, dir.path()); } @@ -2097,7 +2120,7 @@ mod tests { .unwrap(); std::fs::write(grandchild.join(".meta"), r#"{"projects": {}}"#).unwrap(); - let root = find_root_meta_dir(&grandchild); + let root = find_root_meta_dir(&grandchild).unwrap(); assert_eq!(root, dir.path()); } @@ -2105,6 +2128,72 @@ mod tests { // A `.meta/` directory (meta's local folder) is never config // ============================================================================ + #[test] + fn config_discovery_rejects_all_ambiguous_names() { + let dir = tempfile::tempdir().unwrap(); + let child = dir.path().join("child"); + std::fs::create_dir(&child).unwrap(); + for first in META_CONFIG_NAMES { + for second in META_CONFIG_NAMES { + if first >= second { + continue; + } + let a = dir.path().join(first); + let b = dir.path().join(second); + std::fs::write(&a, "{}").unwrap(); + std::fs::write(&b, "{}").unwrap(); + for err in [ + find_meta_config_in(dir.path()).unwrap_err(), + find_meta_config(&child, None).unwrap_err(), + ] { + let message = err.to_string(); + assert!(message.contains("Multiple meta config files")); + assert!(message.contains(&escape_path(&a)), "{message}"); + assert!(message.contains(&escape_path(&b)), "{message}"); + } + std::fs::remove_file(a).unwrap(); + std::fs::remove_file(b).unwrap(); + } + } + for name in META_CONFIG_NAMES { + std::fs::write(dir.path().join(name), "{}").unwrap(); + } + let message = find_meta_config_in(dir.path()).unwrap_err().to_string(); + for name in META_CONFIG_NAMES { + assert!(message.contains(&escape_path(&dir.path().join(name)))); + } + } + + #[test] + fn workspace_root_uses_nearest_config_not_bare_meta_directory() { + let dir = tempfile::tempdir().unwrap(); + let inner = dir.path().join("inner"); + let cwd = inner.join("child"); + std::fs::create_dir_all(cwd.join(".meta/plugins")).unwrap(); + std::fs::write(dir.path().join(".meta.yaml"), "projects: {}").unwrap(); + assert_eq!( + find_workspace_root(&cwd).unwrap(), + Some(dir.path().to_path_buf()) + ); + std::fs::write(inner.join(".meta.json"), "{}").unwrap(); + assert_eq!(find_workspace_root(&cwd).unwrap(), Some(inner)); + } + + #[cfg(unix)] + #[test] + fn unreadable_config_is_an_error_in_both_discovery_paths() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(".meta.yaml"); + std::fs::write(&path, "{}").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap(); + if std::fs::File::open(&path).is_err() { + assert!(find_meta_config_in(dir.path()).is_err()); + assert!(find_meta_config(dir.path(), None).is_err()); + } + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + #[test] fn test_meta_directory_is_not_config() { let dir = tempfile::tempdir().unwrap(); @@ -2117,7 +2206,10 @@ mod tests { find_meta_config_in(dir.path()).unwrap().unwrap().0, expected ); - assert_eq!(find_meta_config(dir.path(), None).unwrap().0, expected); + assert_eq!( + find_meta_config(dir.path(), None).unwrap().unwrap().0, + expected + ); } #[test] @@ -2128,7 +2220,7 @@ mod tests { // Legacy `.meta` config file in the parent std::fs::write(dir.path().join(".meta"), r#"{"projects": {"child": "x"}}"#).unwrap(); - let (path, _) = find_meta_config(&child, None).unwrap(); + let (path, _) = find_meta_config(&child, None).unwrap().unwrap(); assert_eq!(path, dir.path().join(".meta")); let tree = walk_meta_tree(dir.path(), None).unwrap(); From 187fde12a17d97b955fddc1401c4078c4dad9eb1 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 16:22:04 -0700 Subject: [PATCH 03/23] 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/config.rs | 65 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index de4a787..2aed336 100644 --- a/src/config.rs +++ b/src/config.rs @@ -192,9 +192,35 @@ pub fn find_meta_config( Ok(None) } -/// Nearest directory holding a config file, used for project-local plugins. +/// 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 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)) = (walk_meta_tree(parent, None), dir.canonicalize()) else { + return false; + }; + build_project_map(&tree, parent, "") + .into_values() + .any(|(path, _)| path.canonicalize().is_ok_and(|path| path == dir)) +} + +/// Nearest directory holding a config file: where `--local` plugins go. /// Plugin scope follows cwd, independently of a command's explicit `--config`. -pub fn find_workspace_root(start_dir: &Path) -> anyhow::Result> { +pub fn nearest_meta_dir(start_dir: &Path) -> anyhow::Result> { Ok(find_meta_config(start_dir, None)? .and_then(|(path, _)| path.parent().map(Path::to_path_buf))) } @@ -2164,19 +2190,48 @@ mod tests { } } + fn meta_json(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(); + meta_json(&top, r#""inner": {"repo": "x", "meta": true}"#); + meta_json(&top.join("inner"), r#""deep": {"repo": "x", "meta": true}"#); + meta_json(&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"); + meta_json(&unlisted, ""); + assert_eq!(workspace_root(&unlisted), unlisted); + // and so is one under a directory without a config + let below = top.join("plain/sub"); + meta_json(&below, ""); + assert_eq!(workspace_root(&below), below); + } + #[test] - fn workspace_root_uses_nearest_config_not_bare_meta_directory() { + fn nearest_meta_dir_uses_nearest_config_not_bare_meta_directory() { let dir = tempfile::tempdir().unwrap(); let inner = dir.path().join("inner"); let cwd = inner.join("child"); std::fs::create_dir_all(cwd.join(".meta/plugins")).unwrap(); std::fs::write(dir.path().join(".meta.yaml"), "projects: {}").unwrap(); assert_eq!( - find_workspace_root(&cwd).unwrap(), + nearest_meta_dir(&cwd).unwrap(), Some(dir.path().to_path_buf()) ); std::fs::write(inner.join(".meta.json"), "{}").unwrap(); - assert_eq!(find_workspace_root(&cwd).unwrap(), Some(inner)); + assert_eq!(nearest_meta_dir(&cwd).unwrap(), Some(inner)); } #[cfg(unix)] From 052e04fe28bffb3b41557846e4fad551b69eab8b Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 17:40:43 -0700 Subject: [PATCH 04/23] fix(config): a worktree checkout belongs to its main checkout's workspace workspace_meta_dirs returns the workspace's meta dirs nearest first, mapping a linked git worktree (a set's root checkout) to its main checkout, and asks each parent only for its own project list, so a broken sibling config no longer splits the workspace. Duplicate project keys are checked on MetaConfig itself. [[tasks/harmony-2793]] --- src/config.rs | 180 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 117 insertions(+), 63 deletions(-) diff --git a/src/config.rs b/src/config.rs index 2aed336..8fe672d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -86,7 +86,7 @@ pub struct MetaConfig { /// Projects in this meta repo. Values can be: /// - A git URL string: `"project": "git@github.com:org/repo.git"` /// - An extended object: `"project": { "repo": "...", "path": "...", "meta": true }` - #[serde(default)] + #[serde(default, deserialize_with = "unique_projects")] pub projects: HashMap, #[serde(default)] pub ignore: Vec, @@ -97,6 +97,38 @@ pub struct MetaConfig { pub worktrees_dir: Option, } +/// A project map in which no key appears twice: serde would keep the last. +fn unique_projects<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + struct ProjectsVisitor; + impl<'de> serde::de::Visitor<'de> for ProjectsVisitor { + type Value = HashMap; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a map of unique project keys") + } + + fn visit_map>( + self, + mut map: M, + ) -> Result { + let mut projects = HashMap::new(); + while let Some(key) = map.next_key::()? { + if projects.contains_key(&key) { + return Err(serde::de::Error::custom(format!( + "duplicate project key '{}'", + escape(&key) + ))); + } + projects.insert(key, map.next_value()?); + } + Ok(projects) + } + } + deserializer.deserialize_map(ProjectsVisitor) +} + /// Determines the format of a config file based on extension #[derive(Debug, Clone)] pub enum ConfigFormat { @@ -192,30 +224,65 @@ pub fn find_meta_config( Ok(None) } -/// 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) { +/// The meta directories of the workspace `meta_dir` belongs to, nearest +/// first and its root last: `meta_dir`, then each meta directory above it +/// whose own project list names the one before. A meta directory its parent +/// doesn't list (or whose parent's config can't be read) is a workspace of +/// its own. A linked git worktree, such as the root checkout of a worktree +/// set, belongs to the workspace of its main checkout. +pub fn workspace_meta_dirs(meta_dir: &Path) -> Vec { + let start = main_checkout(meta_dir) + .filter(|main| matches!(find_meta_config_in(main), Ok(Some(_)))) + .unwrap_or_else(|| meta_dir.to_path_buf()); + let mut dirs = vec![start.clone()]; + for parent in start.ancestors().skip(1) { match find_meta_config_in(parent) { Ok(None) => continue, - Ok(Some(_)) if lists(parent, &root) => root = parent.to_path_buf(), + Ok(Some((config, _))) if dirs.last().is_some_and(|dir| lists(&config, dir)) => { + dirs.push(parent.to_path_buf()) + } _ => break, } } - root + dirs } -/// Whether the project tree of the meta directory `parent` lists `dir`. -fn lists(parent: &Path, dir: &Path) -> bool { - let (Ok(tree), Ok(dir)) = (walk_meta_tree(parent, None), dir.canonicalize()) else { +/// The root of the workspace `meta_dir` belongs to (see [`workspace_meta_dirs`]). +pub fn workspace_root(meta_dir: &Path) -> PathBuf { + workspace_meta_dirs(meta_dir) + .pop() + .unwrap_or_else(|| meta_dir.to_path_buf()) +} + +/// Whether the project list in `config` names the directory `dir`. +fn lists(config: &Path, dir: &Path) -> bool { + let (Some(parent), Ok((projects, _)), Ok(dir)) = ( + config.parent(), + parse_meta_config(config), + dir.canonicalize(), + ) else { return false; }; - build_project_map(&tree, parent, "") - .into_values() - .any(|(path, _)| path.canonicalize().is_ok_and(|path| path == dir)) + projects.iter().any(|p| { + parent + .join(&p.path) + .canonicalize() + .is_ok_and(|path| path == dir) + }) +} + +/// The main checkout of the linked git worktree at `dir`, if it is one: its +/// `.git` file names `/.git/worktrees/`, whose `commondir` leads to +/// `/.git`. +fn main_checkout(dir: &Path) -> Option { + let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; + let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); + let common = std::fs::read_to_string(admin.join("commondir")).ok()?; + let common = admin.join(common.trim()).canonicalize().ok()?; + if common.file_name()? != ".git" { + return None; + } + common.parent().map(Path::to_path_buf) } /// Nearest directory holding a config file: where `--local` plugins go. @@ -238,48 +305,7 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, ) })?; - #[derive(Deserialize)] - struct CheckedConfig { - #[serde(default, deserialize_with = "unique_projects")] - projects: HashMap, - #[serde(flatten)] - config: MetaConfig, - } - - fn unique_projects<'de, D: serde::Deserializer<'de>>( - deserializer: D, - ) -> Result, D::Error> { - struct ProjectsVisitor; - impl<'de> serde::de::Visitor<'de> for ProjectsVisitor { - type Value = HashMap; - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("a map of unique project keys") - } - - fn visit_map>( - self, - mut map: M, - ) -> Result { - let mut projects = HashMap::new(); - while let Some(key) = map.next_key::()? { - if projects.contains_key(&key) { - return Err(serde::de::Error::custom(format!( - "duplicate project key '{}'", - escape(&key) - ))); - } - projects.insert(key, map.next_value()?); - } - Ok(projects) - } - } - deserializer.deserialize_map(ProjectsVisitor) - } - - // Determine format from file extension - let path_str = meta_path.to_string_lossy(); - let checked: CheckedConfig = if path_str.ends_with(".yaml") || path_str.ends_with(".yml") { + let config: MetaConfig = if let ConfigFormat::Yaml = config_format(meta_path) { serde_yaml_ng::from_str(&config_str).with_context(|| { format!( "Failed to parse YAML config file: {}", @@ -295,9 +321,6 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, })? }; - let mut config = checked.config; - config.projects = checked.projects; - // Convert project entries to normalized, validated ProjectInfo // in name order, so the first bad entry reported is always the same one let base_dir = meta_path @@ -724,8 +747,7 @@ pub fn load_meta_defaults(start_dir: &Path) -> MetaDefaults { Err(_) => return MetaDefaults::default(), }; - let path_str = config_path.to_string_lossy(); - let config: MetaConfig = if path_str.ends_with(".yaml") || path_str.ends_with(".yml") { + let config: MetaConfig = if let ConfigFormat::Yaml = config_format(&config_path) { serde_yaml_ng::from_str(&config_str).unwrap_or_default() } else { serde_json::from_str(&config_str).unwrap_or_default() @@ -2219,6 +2241,38 @@ mod tests { assert_eq!(workspace_root(&below), below); } + #[test] + fn a_linked_worktree_belongs_to_its_main_checkouts_workspace() { + let tmp = tempfile::tempdir().unwrap(); + let top = tmp.path().canonicalize().unwrap(); + meta_json(&top, r#""a": "x""#); + // A worktree set's root checkout, as git lays it out + let admin = top.join(".git/worktrees/s1"); + std::fs::create_dir_all(&admin).unwrap(); + std::fs::write(admin.join("commondir"), "../..\n").unwrap(); + let set = top.join(".worktrees/s1"); + meta_json(&set, r#""a": "x""#); + std::fs::write(set.join(".git"), format!("gitdir: {}\n", admin.display())).unwrap(); + assert_eq!(workspace_meta_dirs(&set), vec![top.clone()]); + } + + #[test] + fn a_broken_sibling_config_does_not_split_the_workspace() { + let tmp = tempfile::tempdir().unwrap(); + let top = tmp.path().canonicalize().unwrap(); + meta_json( + &top, + r#""inner": {"repo": "x", "meta": true}, "other": {"repo": "x", "meta": true}"#, + ); + meta_json(&top.join("inner"), ""); + std::fs::create_dir_all(top.join("other")).unwrap(); + std::fs::write(top.join("other/.meta.json"), "{not json").unwrap(); + assert_eq!( + workspace_meta_dirs(&top.join("inner")), + vec![top.join("inner"), top.clone()] + ); + } + #[test] fn nearest_meta_dir_uses_nearest_config_not_bare_meta_directory() { let dir = tempfile::tempdir().unwrap(); From a3f7b9b9051e734d0fee4ca9455c582acea8b0e5 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 18:14:15 -0700 Subject: [PATCH 05/23] fix(config): only a worktree meta made joins its main checkout's workspace A hand-made git worktree of the root is a workspace of its own. A set checkout's own meta dir stays first in workspace_meta_dirs, so its local plugins still load. The record file name lives here. [[tasks/harmony-2793]] --- src/config.rs | 42 +++++++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/src/config.rs b/src/config.rs index 8fe672d..2ab0aed 100644 --- a/src/config.rs +++ b/src/config.rs @@ -228,13 +228,19 @@ pub fn find_meta_config( /// first and its root last: `meta_dir`, then each meta directory above it /// whose own project list names the one before. A meta directory its parent /// doesn't list (or whose parent's config can't be read) is a workspace of -/// its own. A linked git worktree, such as the root checkout of a worktree -/// set, belongs to the workspace of its main checkout. +/// its own. A checkout in a worktree set meta made belongs to the workspace +/// of the main checkout it was made from, which follows it in the list. pub fn workspace_meta_dirs(meta_dir: &Path) -> Vec { - let start = main_checkout(meta_dir) + let mut dirs = vec![meta_dir.to_path_buf()]; + let start = match main_checkout(meta_dir) .filter(|main| matches!(find_meta_config_in(main), Ok(Some(_)))) - .unwrap_or_else(|| meta_dir.to_path_buf()); - let mut dirs = vec![start.clone()]; + { + Some(main) => { + dirs.push(main.clone()); + main + } + None => meta_dir.to_path_buf(), + }; for parent in start.ancestors().skip(1) { match find_meta_config_in(parent) { Ok(None) => continue, @@ -271,12 +277,22 @@ fn lists(config: &Path, dir: &Path) -> bool { }) } -/// The main checkout of the linked git worktree at `dir`, if it is one: its -/// `.git` file names `/.git/worktrees/`, whose `commondir` leads to -/// `/.git`. -fn main_checkout(dir: &Path) -> Option { +/// The file in a linked worktree's git admin directory +/// (`/.git/worktrees//`) where meta records the worktree set it +/// made the worktree for. +pub const WORKTREE_RECORD_FILE: &str = "meta-worktree.json"; + +/// The main checkout of the linked git worktree at `dir`, if meta made it +/// (its admin directory holds meta's record): its `.git` file names +/// `/.git/worktrees/`, whose `commondir` leads to `/.git`. +/// A worktree made by hand is a checkout of its own, as a second workspace +/// can be. +pub fn main_checkout(dir: &Path) -> Option { let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); + if !admin.join(WORKTREE_RECORD_FILE).is_file() { + return None; + } let common = std::fs::read_to_string(admin.join("commondir")).ok()?; let common = admin.join(common.trim()).canonicalize().ok()?; if common.file_name()? != ".git" { @@ -2242,7 +2258,7 @@ mod tests { } #[test] - fn a_linked_worktree_belongs_to_its_main_checkouts_workspace() { + fn a_worktree_meta_made_belongs_to_its_main_checkouts_workspace() { let tmp = tempfile::tempdir().unwrap(); let top = tmp.path().canonicalize().unwrap(); meta_json(&top, r#""a": "x""#); @@ -2253,7 +2269,11 @@ mod tests { let set = top.join(".worktrees/s1"); meta_json(&set, r#""a": "x""#); std::fs::write(set.join(".git"), format!("gitdir: {}\n", admin.display())).unwrap(); - assert_eq!(workspace_meta_dirs(&set), vec![top.clone()]); + // Made by hand: a workspace of its own + assert_eq!(workspace_meta_dirs(&set), vec![set.clone()]); + // Made by meta + std::fs::write(admin.join(WORKTREE_RECORD_FILE), "{}").unwrap(); + assert_eq!(workspace_meta_dirs(&set), vec![set.clone(), top.clone()]); } #[test] From 0cc453c6d0b8df3133ee13ab03db3a1be051b06d Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 18:44:47 -0700 Subject: [PATCH 06/23] fix(config): a set's origin is the project in meta's record Git's shared repository doesn't say which checkout made a set: a hand-made git worktree of the root is a second workspace sharing the root's git dir. set_origin reads the record's project instead. [[tasks/harmony-2793]] --- src/config.rs | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/config.rs b/src/config.rs index 2ab0aed..0f6be98 100644 --- a/src/config.rs +++ b/src/config.rs @@ -229,11 +229,11 @@ pub fn find_meta_config( /// whose own project list names the one before. A meta directory its parent /// doesn't list (or whose parent's config can't be read) is a workspace of /// its own. A checkout in a worktree set meta made belongs to the workspace -/// of the main checkout it was made from, which follows it in the list. +/// the set was made from ([`set_origin`]), which follows it in the list. pub fn workspace_meta_dirs(meta_dir: &Path) -> Vec { let mut dirs = vec![meta_dir.to_path_buf()]; - let start = match main_checkout(meta_dir) - .filter(|main| matches!(find_meta_config_in(main), Ok(Some(_)))) + let start = match set_origin(meta_dir) + .filter(|origin| matches!(find_meta_config_in(origin), Ok(Some(_)))) { Some(main) => { dirs.push(main.clone()); @@ -282,23 +282,18 @@ fn lists(config: &Path, dir: &Path) -> bool { /// made the worktree for. pub const WORKTREE_RECORD_FILE: &str = "meta-worktree.json"; -/// The main checkout of the linked git worktree at `dir`, if meta made it -/// (its admin directory holds meta's record): its `.git` file names -/// `/.git/worktrees/`, whose `commondir` leads to `/.git`. -/// A worktree made by hand is a checkout of its own, as a second workspace -/// can be. -pub fn main_checkout(dir: &Path) -> Option { +/// The meta directory a worktree set was made from, when `dir` is a checkout +/// in a set meta made: the `project` in meta's record in the checkout's git +/// admin directory (`/.git/worktrees//`, which its `.git` file +/// names). A worktree made by hand has no record and is a checkout of its own, +/// as a second workspace can be. Git's shared repository doesn't say which +/// checkout made the set, so only the record is used. +pub fn set_origin(dir: &Path) -> Option { let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); - if !admin.join(WORKTREE_RECORD_FILE).is_file() { - return None; - } - let common = std::fs::read_to_string(admin.join("commondir")).ok()?; - let common = admin.join(common.trim()).canonicalize().ok()?; - if common.file_name()? != ".git" { - return None; - } - common.parent().map(Path::to_path_buf) + let record = std::fs::read_to_string(admin.join(WORKTREE_RECORD_FILE)).ok()?; + let record: serde_json::Value = serde_json::from_str(&record).ok()?; + record.get("project")?.as_str().map(PathBuf::from) } /// Nearest directory holding a config file: where `--local` plugins go. @@ -2258,7 +2253,7 @@ mod tests { } #[test] - fn a_worktree_meta_made_belongs_to_its_main_checkouts_workspace() { + fn a_worktree_meta_made_belongs_to_its_origins_workspace() { let tmp = tempfile::tempdir().unwrap(); let top = tmp.path().canonicalize().unwrap(); meta_json(&top, r#""a": "x""#); @@ -2272,7 +2267,8 @@ mod tests { // Made by hand: a workspace of its own assert_eq!(workspace_meta_dirs(&set), vec![set.clone()]); // Made by meta - std::fs::write(admin.join(WORKTREE_RECORD_FILE), "{}").unwrap(); + let record = serde_json::json!({ "project": top }); + std::fs::write(admin.join(WORKTREE_RECORD_FILE), record.to_string()).unwrap(); assert_eq!(workspace_meta_dirs(&set), vec![set.clone(), top.clone()]); } From 1dd81ecfc8f168c96580889f66eea4e00c4d23d9 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 13:52:53 -0700 Subject: [PATCH 07/23] fix(config): a nested checkout in a set climbs the set, then its origin A set checkout's config accepts an absolute worktrees_dir inside the workspace the set was made from. [[tasks/harmony-2793]] --- src/config.rs | 74 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 56 insertions(+), 18 deletions(-) diff --git a/src/config.rs b/src/config.rs index 0f6be98..76ab464 100644 --- a/src/config.rs +++ b/src/config.rs @@ -232,21 +232,21 @@ pub fn find_meta_config( /// the set was made from ([`set_origin`]), which follows it in the list. pub fn workspace_meta_dirs(meta_dir: &Path) -> Vec { let mut dirs = vec![meta_dir.to_path_buf()]; - let start = match set_origin(meta_dir) - .filter(|origin| matches!(find_meta_config_in(origin), Ok(Some(_)))) - { - Some(main) => { - dirs.push(main.clone()); - main - } - None => meta_dir.to_path_buf(), - }; - for parent in start.ancestors().skip(1) { - match find_meta_config_in(parent) { - Ok(None) => continue, - Ok(Some((config, _))) if dirs.last().is_some_and(|dir| lists(&config, dir)) => { - dirs.push(parent.to_path_buf()) - } + while let Some(dir) = dirs.last().cloned() { + let parent = dir + .ancestors() + .skip(1) + .find_map(|parent| match find_meta_config_in(parent) { + Ok(None) => None, + Ok(Some((config, _))) => Some(lists(&config, &dir).then(|| parent.to_path_buf())), + Err(_) => Some(None), + }); + // Above the top of a set's checkouts, its origin's workspace goes on + let next = parent.flatten().or_else(|| { + set_origin(&dir).filter(|origin| matches!(find_meta_config_in(origin), Ok(Some(_)))) + }); + match next { + Some(next) if !dirs.contains(&next) => dirs.push(next), _ => break, } } @@ -341,9 +341,19 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, // Where worktrees live (as written, and where that really is); no // project may go there. A bad worktrees_dir is an error like a bad entry. let worktrees = match config.worktrees_dir.as_deref() { - Some(dir) => relative_dir(base_dir, dir).map_err(|why| { - anyhow::anyhow!("Invalid worktrees_dir in {}: {why}", escape_path(meta_path)) - })?, + Some(dir) => relative_dir(base_dir, dir) + .or_else(|why| { + // A set's checkout carries its workspace's config, whose + // absolute worktrees_dir is inside the workspace the set + // was made from + match set_origin(base_dir) { + Some(origin) if Path::new(dir).is_absolute() => relative_dir(&origin, dir), + _ => Err(why), + } + }) + .map_err(|why| { + anyhow::anyhow!("Invalid worktrees_dir in {}: {why}", escape_path(meta_path)) + })?, None => ".worktrees".to_string(), }; let worktrees_at = resolve_inside(base_dir, &worktrees) @@ -2272,6 +2282,34 @@ mod tests { assert_eq!(workspace_meta_dirs(&set), vec![set.clone(), top.clone()]); } + #[test] + fn a_nested_checkout_in_a_set_climbs_the_set_then_its_origin() { + let tmp = tempfile::tempdir().unwrap(); + let top = tmp.path().canonicalize().unwrap(); + let listing_child = r#""child": {"repo": "x", "meta": true}"#; + meta_json(&top, listing_child); + meta_json(&top.join("child"), ""); + // The set's root and nested checkouts, each with meta's record + let set = top.join(".worktrees/ctx"); + meta_json(&set, listing_child); + meta_json(&set.join("child"), ""); + let record = serde_json::json!({ "project": top }).to_string(); + for (checkout, id) in [(&set, "ctx"), (&set.join("child"), "child")] { + let admin = top.join(".git/worktrees").join(id); + std::fs::create_dir_all(&admin).unwrap(); + std::fs::write(admin.join(WORKTREE_RECORD_FILE), &record).unwrap(); + std::fs::write( + checkout.join(".git"), + format!("gitdir: {}\n", admin.display()), + ) + .unwrap(); + } + assert_eq!( + workspace_meta_dirs(&set.join("child")), + vec![set.join("child"), set.clone(), top.clone()] + ); + } + #[test] fn a_broken_sibling_config_does_not_split_the_workspace() { let tmp = tempfile::tempdir().unwrap(); From 548d4cd3c54aa526b7e09d12f048cbeb8de36629 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 14:24:16 -0700 Subject: [PATCH 08/23] fix(config): a set checkout stands for its source checkout set_source maps / to / from meta's record. workspace_meta_dirs walks the set's own meta dirs, then the source's chain. A set copy's absolute worktrees_dir is checked against the source. [[tasks/harmony-2793]] --- src/config.rs | 89 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 54 insertions(+), 35 deletions(-) diff --git a/src/config.rs b/src/config.rs index 76ab464..e19552b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -228,25 +228,33 @@ pub fn find_meta_config( /// first and its root last: `meta_dir`, then each meta directory above it /// whose own project list names the one before. A meta directory its parent /// doesn't list (or whose parent's config can't be read) is a workspace of -/// its own. A checkout in a worktree set meta made belongs to the workspace -/// the set was made from ([`set_origin`]), which follows it in the list. +/// its own. In a worktree set meta made, the set's own meta directories come +/// first, then those of the checkout it stands for ([`set_source`]) and its +/// workspace. pub fn workspace_meta_dirs(meta_dir: &Path) -> Vec { + let mut dirs = listed_chain(meta_dir); + // A checkout in a set meta made goes on with the checkout it stands for + let source = dirs.iter().find_map(|dir| { + set_source(dir).filter(|source| matches!(find_meta_config_in(source), Ok(Some(_)))) + }); + for dir in source.as_deref().map(listed_chain).unwrap_or_default() { + if !dirs.contains(&dir) { + dirs.push(dir); + } + } + dirs +} + +/// `meta_dir`, then each meta directory above it whose own project list +/// names the one before. +fn listed_chain(meta_dir: &Path) -> Vec { let mut dirs = vec![meta_dir.to_path_buf()]; - while let Some(dir) = dirs.last().cloned() { - let parent = dir - .ancestors() - .skip(1) - .find_map(|parent| match find_meta_config_in(parent) { - Ok(None) => None, - Ok(Some((config, _))) => Some(lists(&config, &dir).then(|| parent.to_path_buf())), - Err(_) => Some(None), - }); - // Above the top of a set's checkouts, its origin's workspace goes on - let next = parent.flatten().or_else(|| { - set_origin(&dir).filter(|origin| matches!(find_meta_config_in(origin), Ok(Some(_)))) - }); - match next { - Some(next) if !dirs.contains(&next) => dirs.push(next), + for parent in meta_dir.ancestors().skip(1) { + match find_meta_config_in(parent) { + Ok(None) => continue, + Ok(Some((config, _))) if dirs.last().is_some_and(|dir| lists(&config, dir)) => { + dirs.push(parent.to_path_buf()) + } _ => break, } } @@ -282,18 +290,24 @@ fn lists(config: &Path, dir: &Path) -> bool { /// made the worktree for. pub const WORKTREE_RECORD_FILE: &str = "meta-worktree.json"; -/// The meta directory a worktree set was made from, when `dir` is a checkout -/// in a set meta made: the `project` in meta's record in the checkout's git -/// admin directory (`/.git/worktrees//`, which its `.git` file -/// names). A worktree made by hand has no record and is a checkout of its own, -/// as a second workspace can be. Git's shared repository doesn't say which -/// checkout made the set, so only the record is used. -pub fn set_origin(dir: &Path) -> Option { +/// The checkout that `dir`, a checkout in a worktree set meta made, stands +/// for: the `project` the set was made from joined with `dir`'s place in +/// the set (`/child` for `/child`), from meta's record in the +/// checkout's git admin directory (`/.git/worktrees//`, which its +/// `.git` file names). A worktree made by hand has no record and stands for +/// itself, as a second workspace can. Git's shared repository doesn't say +/// which checkout made the set, so only the record is used. +pub fn set_source(dir: &Path) -> Option { let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); let record = std::fs::read_to_string(admin.join(WORKTREE_RECORD_FILE)).ok()?; let record: serde_json::Value = serde_json::from_str(&record).ok()?; - record.get("project")?.as_str().map(PathBuf::from) + let project = PathBuf::from(record.get("project")?.as_str()?); + let set = Path::new(record.get("set")?.as_str()?) + .canonicalize() + .ok()?; + let place = dir.canonicalize().ok()?; + Some(project.join(place.strip_prefix(set).ok()?)) } /// Nearest directory holding a config file: where `--local` plugins go. @@ -343,11 +357,10 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, let worktrees = match config.worktrees_dir.as_deref() { Some(dir) => relative_dir(base_dir, dir) .or_else(|why| { - // A set's checkout carries its workspace's config, whose - // absolute worktrees_dir is inside the workspace the set - // was made from - match set_origin(base_dir) { - Some(origin) if Path::new(dir).is_absolute() => relative_dir(&origin, dir), + // A set's checkout carries the config of the checkout it + // stands for, whose absolute worktrees_dir is inside that one + match set_source(base_dir) { + Some(source) if Path::new(dir).is_absolute() => relative_dir(&source, dir), _ => Err(why), } }) @@ -2263,7 +2276,7 @@ mod tests { } #[test] - fn a_worktree_meta_made_belongs_to_its_origins_workspace() { + fn a_worktree_meta_made_belongs_to_its_sources_workspace() { let tmp = tempfile::tempdir().unwrap(); let top = tmp.path().canonicalize().unwrap(); meta_json(&top, r#""a": "x""#); @@ -2277,13 +2290,13 @@ mod tests { // Made by hand: a workspace of its own assert_eq!(workspace_meta_dirs(&set), vec![set.clone()]); // Made by meta - let record = serde_json::json!({ "project": top }); + let record = serde_json::json!({ "project": top, "set": set }); std::fs::write(admin.join(WORKTREE_RECORD_FILE), record.to_string()).unwrap(); assert_eq!(workspace_meta_dirs(&set), vec![set.clone(), top.clone()]); } #[test] - fn a_nested_checkout_in_a_set_climbs_the_set_then_its_origin() { + fn a_nested_checkout_in_a_set_climbs_the_set_then_its_source() { let tmp = tempfile::tempdir().unwrap(); let top = tmp.path().canonicalize().unwrap(); let listing_child = r#""child": {"repo": "x", "meta": true}"#; @@ -2293,7 +2306,7 @@ mod tests { let set = top.join(".worktrees/ctx"); meta_json(&set, listing_child); meta_json(&set.join("child"), ""); - let record = serde_json::json!({ "project": top }).to_string(); + let record = serde_json::json!({ "project": top, "set": set }).to_string(); for (checkout, id) in [(&set, "ctx"), (&set.join("child"), "child")] { let admin = top.join(".git/worktrees").join(id); std::fs::create_dir_all(&admin).unwrap(); @@ -2304,9 +2317,15 @@ mod tests { ) .unwrap(); } + // The set's own meta dirs, then the checkout it stands for and up assert_eq!( workspace_meta_dirs(&set.join("child")), - vec![set.join("child"), set.clone(), top.clone()] + vec![ + set.join("child"), + set.clone(), + top.join("child"), + top.clone() + ] ); } From 97490f3ade2fd8ff89a97836557e0d10cff19a1d Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 14:52:23 -0700 Subject: [PATCH 09/23] fix(config): set_source follows aliases and set chains A member's alias is looked up by project name in the project's config (or used as the path for recursive sets), and a set made from inside another set leads on to that set's source. [[tasks/harmony-2793]] --- src/config.rs | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/src/config.rs b/src/config.rs index e19552b..0288733 100644 --- a/src/config.rs +++ b/src/config.rs @@ -291,13 +291,29 @@ fn lists(config: &Path, dir: &Path) -> bool { pub const WORKTREE_RECORD_FILE: &str = "meta-worktree.json"; /// The checkout that `dir`, a checkout in a worktree set meta made, stands -/// for: the `project` the set was made from joined with `dir`'s place in -/// the set (`/child` for `/child`), from meta's record in the -/// checkout's git admin directory (`/.git/worktrees//`, which its -/// `.git` file names). A worktree made by hand has no record and stands for -/// itself, as a second workspace can. Git's shared repository doesn't say -/// which checkout made the set, so only the record is used. +/// for. Meta's record in the checkout's git admin directory +/// (`/.git/worktrees//`, which its `.git` file names) gives the +/// `project` the set was made from; the checkout's place in the set is the +/// alias it was created under: a project name, whose path the project's +/// config gives, or (with --recursive) the path itself. A set +/// made from inside another set leads on to that set's source. A worktree +/// made by hand has no record and stands for itself, as a second workspace +/// can. Git's shared repository doesn't say which checkout made a set, so +/// only the record is used. pub fn set_source(dir: &Path) -> Option { + let mut source = recorded_source(dir)?; + let mut seen = vec![dir.to_path_buf()]; + while let Some(next) = recorded_source(&source) { + if seen.contains(&next) { + break; + } + seen.push(std::mem::replace(&mut source, next)); + } + Some(source) +} + +/// One step of [`set_source`]. +fn recorded_source(dir: &Path) -> Option { let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); let record = std::fs::read_to_string(admin.join(WORKTREE_RECORD_FILE)).ok()?; @@ -307,7 +323,20 @@ pub fn set_source(dir: &Path) -> Option { .canonicalize() .ok()?; let place = dir.canonicalize().ok()?; - Some(project.join(place.strip_prefix(set).ok()?)) + let place = place.strip_prefix(set).ok()?; + if place.as_os_str().is_empty() { + return Some(project); + } + // A set made without --recursive names a member by its project name; + // with it, by its path from the root, which is where it already is + let alias = place.to_string_lossy(); + let named = find_meta_config_in(&project) + .ok() + .flatten() + .and_then(|(config, _)| parse_meta_config(&config).ok()) + .and_then(|(projects, _)| projects.into_iter().find(|p| p.name == alias)) + .map(|p| project.join(p.path)); + Some(named.unwrap_or_else(|| project.join(place))) } /// Nearest directory holding a config file: where `--local` plugins go. From 8a90b2ef0363e758da15483831d8ecc61ad087be Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 15:10:21 -0700 Subject: [PATCH 10/23] fix(config): a set checkout stands for project + its place Sets lay their repos out as the workspace, so no alias guessing. [[tasks/harmony-2793]] --- src/config.rs | 57 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 35 insertions(+), 22 deletions(-) diff --git a/src/config.rs b/src/config.rs index 0288733..3fbb46f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -291,15 +291,14 @@ fn lists(config: &Path, dir: &Path) -> bool { pub const WORKTREE_RECORD_FILE: &str = "meta-worktree.json"; /// The checkout that `dir`, a checkout in a worktree set meta made, stands -/// for. Meta's record in the checkout's git admin directory -/// (`/.git/worktrees//`, which its `.git` file names) gives the -/// `project` the set was made from; the checkout's place in the set is the -/// alias it was created under: a project name, whose path the project's -/// config gives, or (with --recursive) the path itself. A set -/// made from inside another set leads on to that set's source. A worktree -/// made by hand has no record and stands for itself, as a second workspace -/// can. Git's shared repository doesn't say which checkout made a set, so -/// only the record is used. +/// for: the `project` the set was made from, joined with `dir`'s place in +/// the set (meta lays a set out as the workspace). The project comes from +/// meta's record in the checkout's git admin directory +/// (`/.git/worktrees//`, which its `.git` file names). A set made +/// from inside another set leads on to that set's source. A worktree made by +/// hand has no record and stands for itself, as a second workspace can. +/// Git's shared repository doesn't say which checkout made a set, so only +/// the record is used. pub fn set_source(dir: &Path) -> Option { let mut source = recorded_source(dir)?; let mut seen = vec![dir.to_path_buf()]; @@ -324,19 +323,8 @@ fn recorded_source(dir: &Path) -> Option { .ok()?; let place = dir.canonicalize().ok()?; let place = place.strip_prefix(set).ok()?; - if place.as_os_str().is_empty() { - return Some(project); - } - // A set made without --recursive names a member by its project name; - // with it, by its path from the root, which is where it already is - let alias = place.to_string_lossy(); - let named = find_meta_config_in(&project) - .ok() - .flatten() - .and_then(|(config, _)| parse_meta_config(&config).ok()) - .and_then(|(projects, _)| projects.into_iter().find(|p| p.name == alias)) - .map(|p| project.join(p.path)); - Some(named.unwrap_or_else(|| project.join(place))) + // meta puts each repo of a set where it is in the workspace + Some(project.join(place)) } /// Nearest directory holding a config file: where `--local` plugins go. @@ -2358,6 +2346,31 @@ mod tests { ); } + #[test] + fn a_set_checkout_stands_for_the_repo_at_its_place() { + // alpha lives at beta, and beta at gamma: a checkout at /beta is + // alpha's, not beta's + let tmp = tempfile::tempdir().unwrap(); + let top = tmp.path().canonicalize().unwrap(); + meta_json( + &top, + r#""alpha": {"repo": "x", "path": "beta"}, "beta": {"repo": "x", "path": "gamma"}"#, + ); + let set = top.join(".worktrees/s"); + let member = set.join("beta"); + std::fs::create_dir_all(&member).unwrap(); + let admin = top.join("beta/.git/worktrees/s"); + std::fs::create_dir_all(&admin).unwrap(); + let record = serde_json::json!({ "project": top, "set": set }).to_string(); + std::fs::write(admin.join(WORKTREE_RECORD_FILE), record).unwrap(); + std::fs::write( + member.join(".git"), + format!("gitdir: {}\n", admin.display()), + ) + .unwrap(); + assert_eq!(set_source(&member), Some(top.join("beta"))); + } + #[test] fn a_broken_sibling_config_does_not_split_the_workspace() { let tmp = tempfile::tempdir().unwrap(); From 5c6423907cc418c680da6719280683e71a83c6b2 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 15:29:55 -0700 Subject: [PATCH 11/23] docs(config): name rules exist so names don't overlap [[tasks/harmony-2793]] --- src/config.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/config.rs b/src/config.rs index 3fbb46f..f088870 100644 --- a/src/config.rs +++ b/src/config.rs @@ -461,7 +461,7 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, /// - No value (name, path, repo, tags, provides, depends_on) is empty or holds /// a control or bidirectional-control character ([`is_unsafe_char`]). /// - `name` is a relative path in normal form (usually one component; a -/// nested alias like `vendor/lib` is a worktree destination too), held to +/// nested alias like `vendor/lib` names a nested repo), held to /// the same rules as `path`. /// - The name and every path component pass [`component_problem`]: ASCII /// letters, digits, space and `._-+@` only, no trailing dot or space, no @@ -505,8 +505,8 @@ fn validate_project( } } // A name may be a relative path, such as `vendor/lib` for a nested - // repo: worktrees put the project at `/`. So it follows - // the path rules, and must already be in their normal form. + // repo, and names a project in commands. So it follows the path rules, + // and must already be in their normal form. let normal = normalize_project_path(&info.name).map_err(|why| format!("name: {why}"))?; if normal != info.name { return Err(format!( @@ -610,8 +610,8 @@ pub fn relative_dir(base_dir: &Path, raw: &str) -> Result { /// through existing symlinks, and without case, which some filesystems /// ignore. A repo inside another belongs in a nested `.meta` (`meta: true`). fn check_no_overlap(projects: &[(ProjectInfo, PathBuf)]) -> Result<(), String> { - // Paths, by where they resolve; and names, which worktrees use as - // destinations (`/`) + // Paths, by where they resolve; and names, which must name one project + // each in commands let by_location: Vec<_> = projects .iter() .map(|(info, location)| { @@ -637,8 +637,7 @@ fn check_no_overlap(projects: &[(ProjectInfo, PathBuf)]) -> Result<(), String> { .collect(); if let Some((outer, inner)) = nested(&by_name) { return Err(format!( - "project name '{}' is the same as or inside '{}', and names are worktree \ - destinations", + "project name '{}' is the same as or inside '{}'; names must not overlap", escape(&inner.name), escape(&outer.name) )); From 94d8ffbb85adab62b4097e09d48c1af602768f86 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 16:24:27 -0700 Subject: [PATCH 12/23] feat(config): read the set and project in meta's worktree record [[tasks/harmony-2793]] --- src/config.rs | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/config.rs b/src/config.rs index f088870..8321fc8 100644 --- a/src/config.rs +++ b/src/config.rs @@ -311,16 +311,32 @@ pub fn set_source(dir: &Path) -> Option { Some(source) } -/// One step of [`set_source`]. -fn recorded_source(dir: &Path) -> Option { +/// The meta directory meta's record says the set holding the checkout at +/// `dir` was made from. +pub fn recorded_project(dir: &Path) -> Option { + let record = worktree_record(dir)?; + Some(PathBuf::from(record.get("project")?.as_str()?)) +} + +/// The set meta's record says the checkout at `dir` was made for, resolved. +pub fn recorded_set(dir: &Path) -> Option { + let record = worktree_record(dir)?; + Path::new(record.get("set")?.as_str()?).canonicalize().ok() +} + +/// Meta's record of the linked worktree at `dir`, from git's admin directory +/// for it (which its `.git` file names). +fn worktree_record(dir: &Path) -> Option { let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); let record = std::fs::read_to_string(admin.join(WORKTREE_RECORD_FILE)).ok()?; - let record: serde_json::Value = serde_json::from_str(&record).ok()?; - let project = PathBuf::from(record.get("project")?.as_str()?); - let set = Path::new(record.get("set")?.as_str()?) - .canonicalize() - .ok()?; + serde_json::from_str(&record).ok() +} + +/// One step of [`set_source`]. +fn recorded_source(dir: &Path) -> Option { + let project = recorded_project(dir)?; + let set = recorded_set(dir)?; let place = dir.canonicalize().ok()?; let place = place.strip_prefix(set).ok()?; // meta puts each repo of a set where it is in the workspace From bd32cf1cc921f518cc0e7a6316ab522163f7b1b5 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 16:47:36 -0700 Subject: [PATCH 13/23] feat(config): follow a link to a missing target inside the base resolve_inside checks a dangling link as the path it names, so a link the root checkout copies into a set before its target exists leads to that target; a link out is still refused. meta_config_at reads one directory's config. Implements [[tasks/harmony-2793]] --- src/config.rs | 93 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 80 insertions(+), 13 deletions(-) diff --git a/src/config.rs b/src/config.rs index 8321fc8..c3536b9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -204,19 +204,7 @@ pub fn find_meta_config( config_name: Option<&PathBuf>, ) -> anyhow::Result> { for dir in start_dir.ancestors() { - let found = if let Some(name) = config_name { - let path = dir.join(name); - if config_file_exists(&path)? { - std::fs::File::open(&path) - .with_context(|| format!("Cannot read {}", escape_path(&path)))?; - let format = config_format(&path); - Some((path, format)) - } else { - None - } - } else { - find_meta_config_in(dir)? - }; + let found = meta_config_at(dir, config_name)?; if found.is_some() { return Ok(found); } @@ -224,6 +212,23 @@ pub fn find_meta_config( Ok(None) } +/// The config in `dir` itself: `config_name` if given, else the default. +pub fn meta_config_at( + dir: &Path, + config_name: Option<&PathBuf>, +) -> anyhow::Result> { + let Some(name) = config_name else { + return find_meta_config_in(dir); + }; + let path = dir.join(name); + if !config_file_exists(&path)? { + return Ok(None); + } + std::fs::File::open(&path).with_context(|| format!("Cannot read {}", escape_path(&path)))?; + let format = config_format(&path); + Ok(Some((path, format))) +} + /// The meta directories of the workspace `meta_dir` belongs to, nearest /// first and its root last: `meta_dir`, then each meta directory above it /// whose own project list names the one before. A meta directory its parent @@ -774,6 +779,12 @@ pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { } Ok(meta) if meta.file_type().is_symlink() => match current.canonicalize() { Ok(target) if target.starts_with(&base) => current = target, + // A link to what isn't there yet (a repo a checkout links + // to, before its own checkout): checked as the path it names + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + current = dangling_target(&base, ¤t, rel)?; + exists = false; + } Ok(_) => { return Err(format!( "path '{rel}' leads outside {} through the symlink '{}'", @@ -801,6 +812,43 @@ pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { Ok(current) } +/// Where the symlink `link` inside `base` leads when its target is missing: +/// the target's path, itself checked with [`resolve_inside`]. +fn dangling_target(base: &Path, link: &Path, rel: &str) -> Result { + let outside = || { + format!( + "path '{rel}' leads outside {} through the symlink '{}'", + escape_path(base), + escape_path(link) + ) + }; + let target = std::fs::read_link(link).map_err(|e| { + format!( + "path '{rel}' goes through the symlink '{}', which cannot be read: {e}", + escape_path(link) + ) + })?; + let mut path = PathBuf::new(); + for part in link.parent().unwrap_or(base).join(target).components() { + match part { + std::path::Component::ParentDir => { + path.pop(); + } + std::path::Component::CurDir => {} + other => path.push(other), + } + } + let place = path.strip_prefix(base).map_err(|_| outside())?; + let place: Vec<_> = place + .components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect(); + if place.is_empty() { + return Err(outside()); + } + resolve_inside(base, &place.join("/")) +} + /// Load defaults from a meta config file. /// Returns MetaDefaults::default() if no config found or on parse error. pub fn load_meta_defaults(start_dir: &Path) -> MetaDefaults { @@ -1728,6 +1776,25 @@ mod tests { } } + #[cfg(unix)] + #[test] + fn a_link_to_what_is_not_there_yet_leads_where_it_names() { + let dir = tempfile::tempdir().unwrap(); + let base = dir.path().canonicalize().unwrap(); + std::os::unix::fs::symlink("real", base.join("link")).unwrap(); + assert_eq!(resolve_inside(&base, "link"), Ok(base.join("real"))); + assert_eq!(resolve_inside(&base, "link/x"), Ok(base.join("real/x"))); + + std::os::unix::fs::symlink("../elsewhere", base.join("out")).unwrap(); + let err = resolve_inside(&base, "out").unwrap_err(); + assert!(err.contains("leads outside"), "{err}"); + // through a link that does exist, out of the base + std::os::unix::fs::symlink("/", base.join("root")).unwrap(); + std::os::unix::fs::symlink("root/nowhere-meta-test", base.join("via")).unwrap(); + let err = resolve_inside(&base, "via").unwrap_err(); + assert!(err.contains("leads outside"), "{err}"); + } + /// Whether a directory with mode 000 still can't be entered here (as /// root it can, and permission tests have nothing to check). #[cfg(unix)] From ace1b0a0fbbbe7a6316cd99542fc6a28cf963858 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 17:05:24 -0700 Subject: [PATCH 14/23] fix(config): follow a missing link target as the OS does Each link part of the target is followed before a later '..'; '..' out of a missing directory is refused; at most 40 links; the rest of the path is still checked after a followed link; resolver errors escape the path. Implements [[tasks/harmony-2793]] --- src/config.rs | 121 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 98 insertions(+), 23 deletions(-) diff --git a/src/config.rs b/src/config.rs index c3536b9..4e363c5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -754,11 +754,22 @@ fn normalize_project_path(raw: &str) -> Result { /// Returns the project's location: the real path of the part that exists, /// followed by the part not created yet. pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { + resolve_inside_after(base_dir, rel, 0) +} + +/// Links followed for a missing target before giving up, as the OS does. +const MAX_LINK_HOPS: usize = 40; + +/// [`resolve_inside`], `hops` links into following missing targets. +fn resolve_inside_after(base_dir: &Path, rel: &str, hops: usize) -> Result { let base = base_dir .canonicalize() .map_err(|e| format!("cannot resolve {}: {e}", escape_path(base_dir)))?; if rel.starts_with('/') || rel.split('/').any(|part| matches!(part, "" | "." | "..")) { - return Err(format!("path '{rel}' must be a plain relative path")); + return Err(format!( + "path '{}' must be a plain relative path", + escape(rel) + )); } let mut current = base.clone(); let mut exists = true; @@ -773,7 +784,8 @@ pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { // symlink out, so it is refused rather than taken as missing Err(e) => { return Err(format!( - "path '{rel}' cannot be checked at '{}': {e}", + "path '{}' cannot be checked at '{}': {e}", + escape(rel), escape_path(¤t) )) } @@ -782,12 +794,14 @@ pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { // A link to what isn't there yet (a repo a checkout links // to, before its own checkout): checked as the path it names Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - current = dangling_target(&base, ¤t, rel)?; - exists = false; + current = dangling_target(&base, ¤t, rel, hops + 1)?; + // the rest is checked too: part of it may exist + exists = current.symlink_metadata().is_ok(); } Ok(_) => { return Err(format!( - "path '{rel}' leads outside {} through the symlink '{}'", + "path '{}' leads outside {} through the symlink '{}'", + escape(rel), escape_path(&base), escape_path(¤t) )) @@ -796,7 +810,8 @@ pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { // cannot be checked, so it is refused Err(e) => { return Err(format!( - "path '{rel}' goes through the symlink '{}', which cannot be resolved: {e}", + "path '{}' goes through the symlink '{}', which cannot be resolved: {e}", + escape(rel), escape_path(¤t) )) } @@ -806,38 +821,70 @@ pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { } if current == base { return Err(format!( - "path '{rel}' leads to the directory of the .meta file itself" + "path '{}' leads to the directory of the .meta file itself", + escape(rel) )); } Ok(current) } /// Where the symlink `link` inside `base` leads when its target is missing: -/// the target's path, itself checked with [`resolve_inside`]. -fn dangling_target(base: &Path, link: &Path, rel: &str) -> Result { - let outside = || { +/// the target's path, with each link on the way followed before a `..` +/// after it, then checked with [`resolve_inside`]. +fn dangling_target(base: &Path, link: &Path, rel: &str, hops: usize) -> Result { + let unresolved = |at: &Path, e: std::io::Error| { format!( - "path '{rel}' leads outside {} through the symlink '{}'", - escape_path(base), - escape_path(link) + "path '{}' goes through the symlink '{}', which cannot be resolved: {e}", + escape(rel), + escape_path(at) ) }; - let target = std::fs::read_link(link).map_err(|e| { - format!( - "path '{rel}' goes through the symlink '{}', which cannot be read: {e}", - escape_path(link) - ) - })?; - let mut path = PathBuf::new(); - for part in link.parent().unwrap_or(base).join(target).components() { + if hops > MAX_LINK_HOPS { + return Err(unresolved( + link, + std::io::Error::other("too many levels of symbolic links"), + )); + } + let target = std::fs::read_link(link).map_err(|e| unresolved(link, e))?; + let mut path = link.parent().unwrap_or(base).to_path_buf(); + for part in target.components() { match part { + // `..` leaves a directory only if it is there, as the OS has it std::path::Component::ParentDir => { + if !path.is_dir() { + return Err(unresolved( + link, + std::io::Error::from(std::io::ErrorKind::NotFound), + )); + } path.pop(); } std::path::Component::CurDir => {} - other => path.push(other), + other => { + path.push(other); + if path + .symlink_metadata() + .is_ok_and(|meta| meta.file_type().is_symlink()) + { + path = match path.canonicalize() { + Ok(real) => real, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + dangling_target(base, &path, rel, hops + 1)? + } + Err(e) => return Err(unresolved(&path, e)), + }; + } + } } } + let outside = || { + format!( + "path '{}' leads outside {} through the symlink '{}'", + escape(rel), + escape_path(base), + escape_path(link) + ) + }; let place = path.strip_prefix(base).map_err(|_| outside())?; let place: Vec<_> = place .components() @@ -846,7 +893,7 @@ fn dangling_target(base: &Path, link: &Path, rel: &str) -> Result Date: Tue, 27 Oct 2026 17:40:06 -0700 Subject: [PATCH 15/23] fix(config): a set checkout a branch link put elsewhere stands for its own repo When the source rebuilt from a checkout's place is another git repository, the source is git's main checkout of the checkout's own. Implements [[tasks/harmony-2793]] --- src/config.rs | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/src/config.rs b/src/config.rs index 4e363c5..586550a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -345,7 +345,28 @@ fn recorded_source(dir: &Path) -> Option { let place = dir.canonicalize().ok()?; let place = place.strip_prefix(set).ok()?; // meta puts each repo of a set where it is in the workspace - Some(project.join(place)) + let source = project.join(place); + // unless a link that differs between the root's branches put it + // elsewhere: then that place holds another repository, and the source is + // git's main checkout of the checkout's own + match (common_git_dir(dir), common_git_dir(&source)) { + (Some(own), Some(there)) if own != there && own.file_name() == Some(".git".as_ref()) => { + own.parent().map(Path::to_path_buf) + } + _ => Some(source), + } +} + +/// The git directory the checkout at `dir` shares with its linked worktrees. +fn common_git_dir(dir: &Path) -> Option { + let dot_git = dir.join(".git"); + if dot_git.is_dir() { + return dot_git.canonicalize().ok(); + } + let gitfile = std::fs::read_to_string(&dot_git).ok()?; + let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); + let common = std::fs::read_to_string(admin.join("commondir")).ok()?; + admin.join(common.trim()).canonicalize().ok() } /// Nearest directory holding a config file: where `--local` plugins go. @@ -2528,6 +2549,29 @@ mod tests { assert_eq!(set_source(&member), Some(top.join("beta"))); } + #[test] + fn a_set_checkout_a_branch_link_put_elsewhere_stands_for_its_own_repo() { + // app is at `link`; the root's branch in the set links it to + // `alternate`, which in the workspace is another repository + let tmp = tempfile::tempdir().unwrap(); + let top = tmp.path().canonicalize().unwrap(); + let set = top.join(".worktrees/s"); + let member = set.join("alternate"); + std::fs::create_dir_all(&member).unwrap(); + std::fs::create_dir_all(top.join("alternate/.git")).unwrap(); + let admin = top.join("real/.git/worktrees/s"); + std::fs::create_dir_all(&admin).unwrap(); + std::fs::write(admin.join("commondir"), "../..\n").unwrap(); + let record = serde_json::json!({ "project": top, "set": set }).to_string(); + std::fs::write(admin.join(WORKTREE_RECORD_FILE), record).unwrap(); + std::fs::write( + member.join(".git"), + format!("gitdir: {}\n", admin.display()), + ) + .unwrap(); + assert_eq!(set_source(&member), Some(top.join("real"))); + } + #[test] fn a_broken_sibling_config_does_not_split_the_workspace() { let tmp = tempfile::tempdir().unwrap(); From d5401e9fb48e6fe2f86189cc2b90b610d9522597 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 17:57:58 -0700 Subject: [PATCH 16/23] fix(config): a set checkout's fallback source is a project of its workspace When the place-based source is another repository, the source is the recorded workspace's project that is the checkout's own repository; none means none. Implements [[tasks/harmony-2793]] --- src/config.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/config.rs b/src/config.rs index 586550a..9138c9b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -348,10 +348,14 @@ fn recorded_source(dir: &Path) -> Option { let source = project.join(place); // unless a link that differs between the root's branches put it // elsewhere: then that place holds another repository, and the source is - // git's main checkout of the checkout's own + // the project of the same workspace that is the checkout's own repository match (common_git_dir(dir), common_git_dir(&source)) { - (Some(own), Some(there)) if own != there && own.file_name() == Some(".git".as_ref()) => { - own.parent().map(Path::to_path_buf) + (Some(own), Some(there)) if own != there => { + let tree = walk_meta_tree(&project, None).ok()?; + build_project_map(&tree, &project, "") + .into_values() + .map(|(path, _)| path) + .find(|path| common_git_dir(path).as_ref() == Some(&own)) } _ => Some(source), } @@ -2555,6 +2559,10 @@ mod tests { // `alternate`, which in the workspace is another repository let tmp = tempfile::tempdir().unwrap(); let top = tmp.path().canonicalize().unwrap(); + meta_json( + &top, + r#""app": {"repo": "x", "path": "real"}, "alt": {"repo": "x", "path": "alternate"}"#, + ); let set = top.join(".worktrees/s"); let member = set.join("alternate"); std::fs::create_dir_all(&member).unwrap(); @@ -2570,6 +2578,10 @@ mod tests { ) .unwrap(); assert_eq!(set_source(&member), Some(top.join("real"))); + + // a repository that is no project of the workspace stands for nothing + meta_json(&top, r#""alt": {"repo": "x", "path": "alternate"}"#); + assert_eq!(set_source(&member), None); } #[test] From 396c155df8db06ed9df5e2814f35f37578f78c10 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 18:15:33 -0700 Subject: [PATCH 17/23] fix(config): look a set checkout's source up whenever its place isn't its repo A place that holds no repository (missing, or a plain directory) is looked up by identity too. Implements [[tasks/harmony-2793]] --- src/config.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/config.rs b/src/config.rs index 9138c9b..eaafec8 100644 --- a/src/config.rs +++ b/src/config.rs @@ -347,10 +347,11 @@ fn recorded_source(dir: &Path) -> Option { // meta puts each repo of a set where it is in the workspace let source = project.join(place); // unless a link that differs between the root's branches put it - // elsewhere: then that place holds another repository, and the source is - // the project of the same workspace that is the checkout's own repository - match (common_git_dir(dir), common_git_dir(&source)) { - (Some(own), Some(there)) if own != there => { + // elsewhere: then that place holds another repository (or none), and the + // source is the project of the same workspace that is the checkout's own + // repository + match common_git_dir(dir) { + Some(own) if common_git_dir(&source).as_ref() != Some(&own) => { let tree = walk_meta_tree(&project, None).ok()?; build_project_map(&tree, &project, "") .into_values() @@ -2579,6 +2580,12 @@ mod tests { .unwrap(); assert_eq!(set_source(&member), Some(top.join("real"))); + // so does a place that holds no repository, or nothing, in the workspace + std::fs::remove_dir_all(top.join("alternate/.git")).unwrap(); + assert_eq!(set_source(&member), Some(top.join("real"))); + std::fs::remove_dir_all(top.join("alternate")).unwrap(); + assert_eq!(set_source(&member), Some(top.join("real"))); + // a repository that is no project of the workspace stands for nothing meta_json(&top, r#""alt": {"repo": "x", "path": "alternate"}"#); assert_eq!(set_source(&member), None); From bb352f77848de8b386196d9aa69991a09f39fab9 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 18:32:17 -0700 Subject: [PATCH 18/23] fix(config): a --separate-git-dir checkout's .git names its git dir With no commondir behind a .git file, its target is the common git dir, as repo_git_dir has it. Unit fixtures now write the commondir real linked worktrees have. Implements [[tasks/harmony-2793]] --- src/config.rs | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index eaafec8..aaeb457 100644 --- a/src/config.rs +++ b/src/config.rs @@ -369,9 +369,14 @@ fn common_git_dir(dir: &Path) -> Option { return dot_git.canonicalize().ok(); } let gitfile = std::fs::read_to_string(&dot_git).ok()?; - let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); - let common = std::fs::read_to_string(admin.join("commondir")).ok()?; - admin.join(common.trim()).canonicalize().ok() + let target = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); + // A linked worktree's admin directory names the git directory in + // `commondir`; a `--separate-git-dir` checkout's `.git` names it itself + match std::fs::read_to_string(target.join("commondir")) { + Ok(common) => target.join(common.trim()).canonicalize().ok(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => target.canonicalize().ok(), + Err(_) => None, + } } /// Nearest directory holding a config file: where `--local` plugins go. @@ -2507,9 +2512,10 @@ mod tests { meta_json(&set, listing_child); meta_json(&set.join("child"), ""); let record = serde_json::json!({ "project": top, "set": set }).to_string(); - for (checkout, id) in [(&set, "ctx"), (&set.join("child"), "child")] { - let admin = top.join(".git/worktrees").join(id); + for (checkout, repo) in [(&set, top.clone()), (&set.join("child"), top.join("child"))] { + let admin = repo.join(".git/worktrees/ctx"); std::fs::create_dir_all(&admin).unwrap(); + std::fs::write(admin.join("commondir"), "../..\n").unwrap(); std::fs::write(admin.join(WORKTREE_RECORD_FILE), &record).unwrap(); std::fs::write( checkout.join(".git"), @@ -2544,6 +2550,7 @@ mod tests { std::fs::create_dir_all(&member).unwrap(); let admin = top.join("beta/.git/worktrees/s"); std::fs::create_dir_all(&admin).unwrap(); + std::fs::write(admin.join("commondir"), "../..\n").unwrap(); let record = serde_json::json!({ "project": top, "set": set }).to_string(); std::fs::write(admin.join(WORKTREE_RECORD_FILE), record).unwrap(); std::fs::write( @@ -2591,6 +2598,24 @@ mod tests { assert_eq!(set_source(&member), None); } + #[test] + fn a_separate_git_dir_workspace_is_its_set_roots_source() { + let tmp = tempfile::tempdir().unwrap(); + let base = tmp.path().canonicalize().unwrap(); + let (top, git) = (base.join("ws"), base.join("git")); + meta_json(&top, ""); + std::fs::write(top.join(".git"), format!("gitdir: {}\n", git.display())).unwrap(); + let set = top.join(".worktrees/s"); + std::fs::create_dir_all(&set).unwrap(); + let admin = git.join("worktrees/s"); + std::fs::create_dir_all(&admin).unwrap(); + std::fs::write(admin.join("commondir"), "../..\n").unwrap(); + let record = serde_json::json!({ "project": top, "set": set }).to_string(); + std::fs::write(admin.join(WORKTREE_RECORD_FILE), record).unwrap(); + std::fs::write(set.join(".git"), format!("gitdir: {}\n", admin.display())).unwrap(); + assert_eq!(set_source(&set), Some(top)); + } + #[test] fn a_broken_sibling_config_does_not_split_the_workspace() { let tmp = tempfile::tempdir().unwrap(); From 18b41a64e179c395fe1c15f6f25f1abed1f8d136 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 19:21:37 -0700 Subject: [PATCH 19/23] feat(config): has_worktree_record, readable or not A record meta can no longer parse still marks a checkout as meta's. Implements [[tasks/harmony-2793]] --- src/config.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index aaeb457..ab9757f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -332,10 +332,21 @@ pub fn recorded_set(dir: &Path) -> Option { /// Meta's record of the linked worktree at `dir`, from git's admin directory /// for it (which its `.git` file names). fn worktree_record(dir: &Path) -> Option { + let record = std::fs::read_to_string(record_path(dir)?).ok()?; + serde_json::from_str(&record).ok() +} + +/// Whether meta left its record for the checkout at `dir`, readable or not. +pub fn has_worktree_record(dir: &Path) -> bool { + record_path(dir).is_some_and(|path| path.symlink_metadata().is_ok()) +} + +/// Where meta's record of the linked worktree at `dir` goes: in git's admin +/// directory for it, which its `.git` file names. +fn record_path(dir: &Path) -> Option { let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); - let record = std::fs::read_to_string(admin.join(WORKTREE_RECORD_FILE)).ok()?; - serde_json::from_str(&record).ok() + Some(admin.join(WORKTREE_RECORD_FILE)) } /// One step of [`set_source`]. From 8cdfb4f2f14b2537713736d87f9bf5dcc02a7046 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 19:40:40 -0700 Subject: [PATCH 20/23] fix(config): resolve existing parts of a missing link target as the OS does canonicalize each existing part, so an absolute target meets the base in its \\?\ form on Windows and links are followed before a later '..'. Implements [[tasks/harmony-2793]] --- src/config.rs | 47 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/src/config.rs b/src/config.rs index ab9757f..a5f03de 100644 --- a/src/config.rs +++ b/src/config.rs @@ -902,21 +902,26 @@ fn dangling_target(base: &Path, link: &Path, rel: &str, hops: usize) -> Result

{} - other => { - path.push(other); - if path - .symlink_metadata() - .is_ok_and(|meta| meta.file_type().is_symlink()) - { - path = match path.canonicalize() { - Ok(real) => real, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - dangling_target(base, &path, rel, hops + 1)? + // What exists is taken as the OS resolves it (links followed, + // and in the base's form: `\\?\` on Windows, which an absolute + // target doesn't carry); a link to what is missing is followed here + std::path::Component::Normal(_) => { + path.push(part); + match path.canonicalize() { + Ok(real) => path = real, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + if path + .symlink_metadata() + .is_ok_and(|meta| meta.file_type().is_symlink()) + { + path = dangling_target(base, &path, rel, hops + 1)?; } - Err(e) => return Err(unresolved(&path, e)), - }; + } + Err(e) => return Err(unresolved(&path, e)), } } + // The root of an absolute target + std::path::Component::Prefix(_) | std::path::Component::RootDir => path.push(part), } } let outside = || { @@ -1865,6 +1870,24 @@ mod tests { } } + #[cfg(windows)] + #[test] + fn an_absolute_link_to_what_is_not_there_yet_stays_inside() { + let dir = tempfile::tempdir().unwrap(); + let base = dir.path().canonicalize().unwrap(); + // the target as a user writes it, without `\\?\` + let plain = dir.path().join("real"); + // creating links needs a privilege or developer mode + if std::os::windows::fs::symlink_dir(&plain, base.join("link")).is_err() { + return; + } + assert_eq!(resolve_inside(&base, "link"), Ok(base.join("real"))); + let outside = tempfile::tempdir().unwrap(); + std::os::windows::fs::symlink_dir(outside.path().join("x"), base.join("out")).unwrap(); + let err = resolve_inside(&base, "out").unwrap_err(); + assert!(err.contains("leads outside"), "{err}"); + } + #[cfg(unix)] #[test] fn a_link_to_what_is_not_there_yet_leads_where_it_names() { From 3bda7601b4beeab91feb7b20a354e4c3516e055c Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 19:57:24 -0700 Subject: [PATCH 21/23] feat(config): gitfile_target; note when the Windows link test skips Implements [[tasks/harmony-2793]] --- src/config.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/config.rs b/src/config.rs index a5f03de..eb849af 100644 --- a/src/config.rs +++ b/src/config.rs @@ -341,12 +341,18 @@ pub fn has_worktree_record(dir: &Path) -> bool { record_path(dir).is_some_and(|path| path.symlink_metadata().is_ok()) } +/// The git directory the `.git` file of the checkout at `dir` names: for a +/// linked worktree, git's admin directory for it. `None` when there is no +/// such file or it names nothing. +pub fn gitfile_target(dir: &Path) -> Option { + let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; + Some(dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim())) +} + /// Where meta's record of the linked worktree at `dir` goes: in git's admin /// directory for it, which its `.git` file names. fn record_path(dir: &Path) -> Option { - let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; - let admin = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); - Some(admin.join(WORKTREE_RECORD_FILE)) + Some(gitfile_target(dir)?.join(WORKTREE_RECORD_FILE)) } /// One step of [`set_source`]. @@ -1879,6 +1885,7 @@ mod tests { let plain = dir.path().join("real"); // creating links needs a privilege or developer mode if std::os::windows::fs::symlink_dir(&plain, base.join("link")).is_err() { + eprintln!("skipped: this runner can't create symbolic links"); return; } assert_eq!(resolve_inside(&base, "link"), Ok(base.join("real"))); From 2bb309eb4511e715436db57269e40290ab623256 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 20:18:28 -0700 Subject: [PATCH 22/23] fix(config): find a checkout's project past broken sibling configs; an empty gitdir names nothing project_with_git_dir passes over configs it can't read. gitfile_target returns nothing for 'gitdir:' with no target; common_git_dir uses it. has_worktree_record is folded into its one caller. Implements [[tasks/harmony-2793]] --- src/config.rs | 56 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 14 deletions(-) diff --git a/src/config.rs b/src/config.rs index eb849af..110287b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -336,17 +336,13 @@ fn worktree_record(dir: &Path) -> Option { serde_json::from_str(&record).ok() } -/// Whether meta left its record for the checkout at `dir`, readable or not. -pub fn has_worktree_record(dir: &Path) -> bool { - record_path(dir).is_some_and(|path| path.symlink_metadata().is_ok()) -} - /// The git directory the `.git` file of the checkout at `dir` names: for a /// linked worktree, git's admin directory for it. `None` when there is no -/// such file or it names nothing. +/// such file or it names nothing (git rejects an empty `gitdir:` too). pub fn gitfile_target(dir: &Path) -> Option { let gitfile = std::fs::read_to_string(dir.join(".git")).ok()?; - Some(dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim())) + let target = gitfile.trim().strip_prefix("gitdir:")?.trim(); + (!target.is_empty()).then(|| dir.join(target)) } /// Where meta's record of the linked worktree at `dir` goes: in git's admin @@ -369,24 +365,38 @@ fn recorded_source(dir: &Path) -> Option { // repository match common_git_dir(dir) { Some(own) if common_git_dir(&source).as_ref() != Some(&own) => { - let tree = walk_meta_tree(&project, None).ok()?; - build_project_map(&tree, &project, "") - .into_values() - .map(|(path, _)| path) - .find(|path| common_git_dir(path).as_ref() == Some(&own)) + project_with_git_dir(&project, &own, 0) } _ => Some(source), } } +/// The project of the meta repo at `meta_dir`, or of the meta repos nested +/// in it, whose repository's git directory is `git_dir`. A config that can't +/// be read is passed over: one broken sibling doesn't hide the project. +fn project_with_git_dir(meta_dir: &Path, git_dir: &Path, depth: usize) -> Option { + if depth > MAX_LINK_HOPS { + return None; + } + let (config, _) = find_meta_config_in(meta_dir).ok()??; + let (projects, _) = parse_meta_config(&config).ok()?; + projects.iter().find_map(|project| { + let path = meta_dir.join(&project.path); + if common_git_dir(&path).as_deref() == Some(git_dir) { + Some(path) + } else { + project_with_git_dir(&path, git_dir, depth + 1) + } + }) +} + /// The git directory the checkout at `dir` shares with its linked worktrees. fn common_git_dir(dir: &Path) -> Option { let dot_git = dir.join(".git"); if dot_git.is_dir() { return dot_git.canonicalize().ok(); } - let gitfile = std::fs::read_to_string(&dot_git).ok()?; - let target = dir.join(gitfile.trim().strip_prefix("gitdir:")?.trim()); + let target = gitfile_target(dir)?; // A linked worktree's admin directory names the git directory in // `commondir`; a `--separate-git-dir` checkout's `.git` names it itself match std::fs::read_to_string(target.join("commondir")) { @@ -2634,6 +2644,15 @@ mod tests { std::fs::remove_dir_all(top.join("alternate")).unwrap(); assert_eq!(set_source(&member), Some(top.join("real"))); + // a broken config of another nested repo doesn't hide it + meta_json( + &top, + r#""app": {"repo": "x", "path": "real"}, "alt": {"repo": "x", "path": "alternate"}, "other": {"repo": "x", "meta": true}"#, + ); + std::fs::create_dir_all(top.join("other")).unwrap(); + std::fs::write(top.join("other/.meta.json"), "{broken").unwrap(); + assert_eq!(set_source(&member), Some(top.join("real"))); + // a repository that is no project of the workspace stands for nothing meta_json(&top, r#""alt": {"repo": "x", "path": "alternate"}"#); assert_eq!(set_source(&member), None); @@ -2657,6 +2676,15 @@ mod tests { assert_eq!(set_source(&set), Some(top)); } + #[test] + fn an_empty_gitdir_names_nothing() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join(".git"), "gitdir:\n").unwrap(); + assert_eq!(gitfile_target(tmp.path()), None); + std::fs::write(tmp.path().join(".git"), "gitdir: x\n").unwrap(); + assert_eq!(gitfile_target(tmp.path()), Some(tmp.path().join("x"))); + } + #[test] fn a_broken_sibling_config_does_not_split_the_workspace() { let tmp = tempfile::tempdir().unwrap(); From 39fff062369d82b4b20c005e92301d817ed5f154 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 21:26:11 -0700 Subject: [PATCH 23/23] fix(config): a set checkout stands for a project of its workspace, not just its repository A non-root checkout stands for the recorded workspace's project with the same repository: the one at its place, else the only one; a second workspace's checkout of that repository is no project. Implements [[tasks/harmony-2793]] --- src/config.rs | 88 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 68 insertions(+), 20 deletions(-) diff --git a/src/config.rs b/src/config.rs index 110287b..ad3d261 100644 --- a/src/config.rs +++ b/src/config.rs @@ -359,35 +359,54 @@ fn recorded_source(dir: &Path) -> Option { let place = place.strip_prefix(set).ok()?; // meta puts each repo of a set where it is in the workspace let source = project.join(place); - // unless a link that differs between the root's branches put it - // elsewhere: then that place holds another repository (or none), and the - // source is the project of the same workspace that is the checkout's own - // repository - match common_git_dir(dir) { - Some(own) if common_git_dir(&source).as_ref() != Some(&own) => { - project_with_git_dir(&project, &own, 0) - } - _ => Some(source), + // The set's root stands for the workspace itself. Another checkout + // stands for a project of that workspace with the same repository: the + // one at its place, else (a link that differs between the root's + // branches put it elsewhere) the only one there is. Its place alone + // doesn't say: a second workspace's `git worktree add` shares the + // repository but is no project. + let Some(own) = common_git_dir(dir) else { + return Some(source); + }; + if place.as_os_str().is_empty() { + return Some(source); + } + let mut matches = Vec::new(); + projects_with_git_dir(&project, &own, 0, &mut matches); + let at_place = source.canonicalize().ok(); + match matches.as_slice() { + [only] => Some(only.clone()), + // no project says (one no longer listed, say): its place, if that + // is its repository + [] => (common_git_dir(&source).as_ref() == Some(&own)).then_some(source), + _ => matches.into_iter().find(|path| { + path.canonicalize() + .ok() + .is_some_and(|real| Some(real) == at_place) + }), } } -/// The project of the meta repo at `meta_dir`, or of the meta repos nested +/// The projects of the meta repo at `meta_dir`, and of the meta repos nested /// in it, whose repository's git directory is `git_dir`. A config that can't -/// be read is passed over: one broken sibling doesn't hide the project. -fn project_with_git_dir(meta_dir: &Path, git_dir: &Path, depth: usize) -> Option { +/// be read is passed over: one broken sibling doesn't hide a project. +fn projects_with_git_dir(meta_dir: &Path, git_dir: &Path, depth: usize, found: &mut Vec) { if depth > MAX_LINK_HOPS { - return None; + return; } - let (config, _) = find_meta_config_in(meta_dir).ok()??; - let (projects, _) = parse_meta_config(&config).ok()?; - projects.iter().find_map(|project| { + let Some((config, _)) = find_meta_config_in(meta_dir).ok().flatten() else { + return; + }; + let Ok((projects, _)) = parse_meta_config(&config) else { + return; + }; + for project in &projects { let path = meta_dir.join(&project.path); if common_git_dir(&path).as_deref() == Some(git_dir) { - Some(path) - } else { - project_with_git_dir(&path, git_dir, depth + 1) + found.push(path.clone()); } - }) + projects_with_git_dir(&path, git_dir, depth + 1, found); + } } /// The git directory the checkout at `dir` shares with its linked worktrees. @@ -2658,6 +2677,35 @@ mod tests { assert_eq!(set_source(&member), None); } + #[test] + fn a_second_checkout_of_a_projects_repo_is_not_its_source() { + // app is at `real`; `alternate` is a hand-made `git worktree add` of + // the same repository, no project; a branch link put the set's + // checkout of app at `/alternate` + let tmp = tempfile::tempdir().unwrap(); + let top = tmp.path().canonicalize().unwrap(); + meta_json(&top, r#""app": {"repo": "x", "path": "real"}"#); + let linked = |checkout: &Path, id: &str| { + let admin = top.join("real/.git/worktrees").join(id); + std::fs::create_dir_all(&admin).unwrap(); + std::fs::write(admin.join("commondir"), "../..\n").unwrap(); + std::fs::create_dir_all(checkout).unwrap(); + std::fs::write( + checkout.join(".git"), + format!("gitdir: {}\n", admin.display()), + ) + .unwrap(); + admin + }; + linked(&top.join("alternate"), "alternate"); + let set = top.join(".worktrees/s"); + let member = set.join("alternate"); + let admin = linked(&member, "s"); + let record = serde_json::json!({ "project": top, "set": set }).to_string(); + std::fs::write(admin.join(WORKTREE_RECORD_FILE), record).unwrap(); + assert_eq!(set_source(&member), Some(top.join("real"))); + } + #[test] fn a_separate_git_dir_workspace_is_its_set_roots_source() { let tmp = tempfile::tempdir().unwrap();