From d8e498d4d8a30f4cbeccbeb4a7dd8d3f2fe37799 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:59:58 -0700 Subject: [PATCH 1/5] fix: escape untrusted text in worktree and clone output; store errors fail; config-checked worktree root Rebased onto meta-git-safety as one commit (both changed the same worktree code). Keeps that PR's create, remove and prune safety code, and adds this PR's part: - worktrees_dir and the default .worktrees are checked by the .meta path rules wherever the plugin resolves them; a symlinked set directory is refused. - Paths, names and file names in worktree and clone messages, including the new safety checks, go through meta_core::display::escape. - The store path is fallible (a refused data dir is an error), and only a missing store file means there is nothing to remove. Implements [[tasks/harmony-2749]] --- src/clone_queue.rs | 5 +-- src/lib.rs | 17 +++++----- src/worktree/git_ops.rs | 37 +++++++++++----------- src/worktree/helpers.rs | 69 +++++++++++++++++++++++++++++++++++++---- src/worktree/safety.rs | 47 +++++++++++++++------------- src/worktree/store.rs | 33 +++++++++++++------- 6 files changed, 142 insertions(+), 66 deletions(-) diff --git a/src/clone_queue.rs b/src/clone_queue.rs index 2983ff8..afe0d3b 100644 --- a/src/clone_queue.rs +++ b/src/clone_queue.rs @@ -1,5 +1,6 @@ use log::{debug, warn}; use meta_core::config; +use meta_core::display::escape_path; use std::collections::{BTreeSet, HashSet}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -95,7 +96,7 @@ impl CloneQueue { } let Some((meta_path, _format)) = config::find_meta_config_in(base_dir) else { - debug!("No .meta config found in {}", base_dir.display()); + debug!("No .meta config found in {}", escape_path(base_dir)); return Ok(0); }; @@ -103,7 +104,7 @@ impl CloneQueue { debug!( "Discovered {} projects in {} at depth {}", projects.len(), - base_dir.display(), + escape_path(base_dir), depth_level ); diff --git a/src/lib.rs b/src/lib.rs index b5fba76..823a57a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ use anyhow::Result; use indicatif::ProgressBar; +use meta_core::display::escape_path; use std::path::Path; use std::process::{Command, Stdio}; pub mod clone_queue; @@ -23,17 +24,17 @@ pub fn clone_repo_with_progress( if let Some(pb) = pb { pb.finish_with_message(format!( "{}: already exists, skipping", - target_dir.display() + escape_path(target_dir) )); } else { - println!("{}: already exists, skipping", target_dir.display()); + println!("{}: already exists, skipping", escape_path(target_dir)); } return Ok(()); } if let Some(pb) = pb { pb.set_message(format!("Cloning {url}")); } else { - println!("Cloning {} into {}", url, target_dir.display()); + println!("Cloning {} into {}", url, escape_path(target_dir)); } let mut child = Command::new("git") .arg("clone") @@ -45,22 +46,22 @@ pub fn clone_repo_with_progress( let status = child.wait()?; if let Some(pb) = pb { if status.success() { - pb.finish_with_message(format!("{} ✓", style(target_dir.display()).green())); + pb.finish_with_message(format!("{} ✓", style(escape_path(target_dir)).green())); } else { pb.finish_with_message(format!( "Failed to clone {} into {}", url, - target_dir.display() + escape_path(target_dir) )); } } else if status.success() { - println!("{} ✓", style(target_dir.display()).green()); + println!("{} ✓", style(escape_path(target_dir)).green()); } else { - println!("Failed to clone {} into {}", url, target_dir.display()); + println!("Failed to clone {} into {}", url, escape_path(target_dir)); } if status.success() { Ok(()) } else { - anyhow::bail!("Failed to clone {} into {}", url, target_dir.display()) + anyhow::bail!("Failed to clone {} into {}", url, escape_path(target_dir)) } } diff --git a/src/worktree/git_ops.rs b/src/worktree/git_ops.rs index a34a913..aec863b 100644 --- a/src/worktree/git_ops.rs +++ b/src/worktree/git_ops.rs @@ -1,6 +1,7 @@ //! Git operations for worktree management. use anyhow::Result; +use meta_core::display::{escape, escape_path}; use std::path::Path; use std::process::{Command, Stdio}; @@ -58,15 +59,15 @@ fn ensure_checkout_config_is_not_bare(repo_path: &Path) -> Result<()> { anyhow::bail!( "Repository '{}' is a checked-out work tree but its shared Git config has \ core.bare=true.\nRepair it with:\n git -C {} config --local core.bare false", - repo_path.display(), - shell_quote_path(repo_path) + escape_path(repo_path), + escape(&shell_quote_path(repo_path)) ); } } else if output.status.code() != Some(1) { let stderr = String::from_utf8_lossy(&output.stderr); anyhow::bail!( "Failed to inspect core.bare for '{}': {}", - repo_path.display(), + escape_path(repo_path), stderr.trim() ); } @@ -90,7 +91,7 @@ pub fn git_worktree_add( anyhow::anyhow!( "Ref '{}' not found in repo '{}'", ref_name, - repo_path.display() + escape_path(repo_path) ) })?; // Pass the name, not the commit: a remote-tracking ref still sets the @@ -104,7 +105,7 @@ pub fn git_worktree_add( let stderr = String::from_utf8_lossy(&output.stderr); anyhow::bail!( "git worktree add failed for '{}' (branch: {}, ref: {}): {}", - repo_path.display(), + escape_path(repo_path), branch, ref_name, stderr.trim() @@ -139,7 +140,7 @@ pub fn git_worktree_add( } else { // Create new branch from HEAD let start = git_rev_parse(repo_path, "HEAD")?.ok_or_else(|| { - anyhow::anyhow!("{} has no commit to branch from", repo_path.display()) + anyhow::anyhow!("{} has no commit to branch from", escape_path(repo_path)) })?; ( vec!["worktree", "add", "-b", branch, &dest_str], @@ -153,7 +154,7 @@ pub fn git_worktree_add( let stderr = String::from_utf8_lossy(&output.stderr); anyhow::bail!( "git worktree add failed for '{}' (branch: {}): {}", - repo_path.display(), + escape_path(repo_path), branch, stderr.trim() ); @@ -192,7 +193,7 @@ pub fn git_status_summary(repo_path: &Path) -> Result { let stderr = String::from_utf8_lossy(&output.stderr); anyhow::bail!( "git status failed for '{}': {}", - repo_path.display(), + escape_path(repo_path), stderr.trim() ); } @@ -311,10 +312,10 @@ pub fn remove_worktree_repos( for m in ordered { if verbose { - eprintln!("Removing worktree at {}", m.path.display()); + eprintln!("Removing worktree at {}", escape_path(&m.path)); } git_worktree_remove(&m.repo_git_dir, &m.path, force) - .map_err(|e| e.context(format!("Cannot remove {}", m.path.display())))?; + .map_err(|e| e.context(format!("Cannot remove {}", escape_path(&m.path))))?; } Ok(()) } @@ -337,7 +338,7 @@ pub fn git_rev_parse(repo_path: &Path, rev: &str) -> Result> { } anyhow::bail!( "git rev-parse {rev} failed in {}: {}", - repo_path.display(), + escape_path(repo_path), stderr.trim() ) } @@ -373,7 +374,7 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { anyhow::ensure!( list.status.success(), "Cannot list the worktrees of {}: {}", - repo_path.display(), + escape_path(repo_path), String::from_utf8_lossy(&list.stderr).trim() ); let wanted = format!("branch {full}"); @@ -390,7 +391,7 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { anyhow::ensure!( output.status.success(), "Cannot find the git directory of {}: {}", - repo_path.display(), + escape_path(repo_path), String::from_utf8_lossy(&output.stderr).trim() ); // Relative output is relative to the repository, where git ran. @@ -399,8 +400,8 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { anyhow::ensure!( common.is_dir(), "Cannot find the git directory of {} (got {})", - repo_path.display(), - common.display() + escape_path(repo_path), + escape_path(&common) ); let mut admin_dirs = vec![common.clone()]; match std::fs::read_dir(common.join("worktrees")) { @@ -418,7 +419,7 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { Ok(text) => Ok(text), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()), Err(e) => { - Err(anyhow::Error::from(e).context(format!("Cannot read {}", path.display()))) + Err(anyhow::Error::from(e).context(format!("Cannot read {}", escape_path(&path)))) } } }; @@ -433,14 +434,14 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { { return Err(in_use(&format!( "being rebased by the worktree whose git dir is {}", - dir.display() + escape_path(&dir) ))); } let bisect = read(dir.join("BISECT_START"))?; if [branch, full.as_str()].contains(&bisect.trim()) { return Err(in_use(&format!( "being bisected by the worktree whose git dir is {}", - dir.display() + escape_path(&dir) ))); } } diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 97ed98c..0b8b311 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -1,6 +1,7 @@ //! Utility functions for worktree management. use anyhow::{Context, Result}; +use meta_core::display::escape_path; use std::path::{Path, PathBuf}; use super::types::WorktreeContext; @@ -31,11 +32,35 @@ pub fn resolve_worktree_root(meta_dir: Option<&Path>) -> Result { } // 2. Check worktrees_dir in .meta config if let Some(dir) = meta_dir { + // The config's rules for the worktree directory (inside the + // workspace, not inside a project, not into .git) hold here too, + // whoever ran this plugin + if let Some((config, _)) = meta_core::config::find_meta_config_in(dir) { + meta_core::config::parse_meta_config(&config)?; + } if let Some(configured) = read_worktrees_dir_from_config(dir) { - return Ok(dir.join(configured)); + // Worktrees are created and removed there, so a committed config + // may not point it outside the workspace + let relative = meta_core::config::relative_dir(dir, &configured).map_err(|why| { + anyhow::anyhow!( + "Invalid worktrees_dir in the .meta of {}: {why} (use META_WORKTREES \ + for a directory elsewhere)", + escape_path(dir) + ) + })?; + return Ok(dir.join(relative)); } - // 3. Default: .worktrees/ relative to meta root - return Ok(dir.join(".worktrees")); + // 3. Default: .worktrees/ relative to meta root, held to the same + // rules: a committed symlink there must not send worktrees (and their + // removal) outside the workspace or into .git + let root = dir.join(".worktrees"); + meta_core::config::relative_dir(dir, ".worktrees").map_err(|why| { + anyhow::anyhow!( + "Refusing to keep worktrees in {}: {why}", + escape_path(&root) + ) + })?; + return Ok(root); } // Fallback if no meta dir found let cwd = std::env::current_dir()?; @@ -87,12 +112,40 @@ pub fn require_meta_dir() -> Result { find_meta_dir().ok_or_else(|| anyhow::anyhow!("Not inside a meta project (no .meta found)")) } +/// The directory of the worktree set `name` under `worktree_root`. A symlink +/// there (say one tracked in a repo that holds `worktrees_dir`) must not +/// lead commands, or a removal, outside the worktree root. +pub fn worktree_set_dir(worktree_root: &Path, name: &str) -> Result { + let wt_dir = worktree_root.join(name); + // meta makes set directories itself; one that is a link (even to another + // set) is someone else's doing + if wt_dir + .symlink_metadata() + .is_ok_and(|meta| meta.file_type().is_symlink()) + { + anyhow::bail!( + "Refusing to use worktree '{}': {} is a symlink", + meta_core::display::escape(name), + escape_path(&wt_dir) + ); + } + if worktree_root.exists() { + meta_core::config::resolve_inside(worktree_root, name).map_err(|why| { + anyhow::anyhow!( + "Refusing to use worktree '{}': {why}", + meta_core::display::escape(name) + ) + })?; + } + Ok(worktree_root.join(name)) +} + /// Resolve worktree context for a named worktree. /// Returns meta_dir (for hooks), worktree_root, and the specific worktree directory. pub fn resolve_worktree_context(name: &str) -> Result { let meta_dir = find_meta_dir(); let worktree_root = resolve_worktree_root(meta_dir.as_deref())?; - let wt_dir = worktree_root.join(name); + let wt_dir = worktree_set_dir(&worktree_root, name)?; Ok(WorktreeContext { meta_dir, worktree_root, @@ -104,7 +157,11 @@ pub fn resolve_worktree_context(name: &str) -> Result { pub fn resolve_existing_worktree(name: &str) -> Result { let ctx = resolve_worktree_context(name)?; if !ctx.wt_dir.exists() { - anyhow::bail!("Worktree '{}' not found at {}", name, ctx.wt_dir.display()); + anyhow::bail!( + "Worktree '{}' not found at {}", + name, + escape_path(&ctx.wt_dir) + ); } Ok(ctx) } @@ -126,7 +183,7 @@ pub fn discover_and_validate_worktree( /// Load and parse the .meta config, returning the project list. pub fn load_projects(meta_dir: &Path) -> Result> { let (config_path, _) = meta_core::config::find_meta_config(meta_dir, None) - .ok_or_else(|| anyhow::anyhow!("No .meta config found in {}", meta_dir.display()))?; + .ok_or_else(|| anyhow::anyhow!("No .meta config found in {}", escape_path(meta_dir)))?; let (projects, _) = meta_core::config::parse_meta_config(&config_path)?; Ok(projects) } diff --git a/src/worktree/safety.rs b/src/worktree/safety.rs index 7116627..5b6354a 100644 --- a/src/worktree/safety.rs +++ b/src/worktree/safety.rs @@ -4,6 +4,7 @@ //! inspected, nested ones included, and so is anything outside a repository. use anyhow::{Context, Result}; +use meta_core::display::{escape, escape_path}; use std::path::{Path, PathBuf}; use super::git_ops::{git_command, remove_worktree_repos}; @@ -53,7 +54,7 @@ pub fn check_worktree_removal(wt_dir: &Path) -> Result { if wt_dir.symlink_metadata().is_ok_and(|m| m.is_symlink()) { check.blockers.push(format!( "{} is a symbolic link; meta doesn't delete through links", - wt_dir.display() + escape_path(wt_dir) )); return Ok(check); } @@ -66,7 +67,9 @@ pub fn check_worktree_removal(wt_dir: &Path) -> Result { true } GitEntry::Repository(why) => { - check.blockers.push(format!("{}: {why}", wt_dir.display())); + check + .blockers + .push(format!("{}: {why}", escape_path(wt_dir))); return Ok(check); } GitEntry::None => false, @@ -139,13 +142,13 @@ pub fn delete_checked_set( if check_worktree_removal(wt_dir)? != *check { anyhow::bail!( "{} changed after it was checked; left in place, check it again", - wt_dir.display() + escape_path(wt_dir) ); } remove_worktree_repos(&check.members, force, verbose)?; if force { for path in &check.loose { - remove_entry(path).with_context(|| format!("Cannot delete {}", path.display()))?; + remove_entry(path).with_context(|| format!("Cannot delete {}", escape_path(path)))?; } } remove_empty_dirs(wt_dir)?; @@ -156,7 +159,7 @@ pub fn delete_checked_set( anyhow::bail!( "{} could not be deleted completely (left in place: {}); new files may have \ appeared in it, or some couldn't be removed", - wt_dir.display(), + escape_path(wt_dir), sample(&left, |p| relative_label(wt_dir, p)) ); } @@ -179,10 +182,10 @@ fn remove_empty_dirs(dir: &Path) -> Result<()> { let entries = match std::fs::read_dir(dir) { Ok(entries) => entries, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(e) => return Err(e).with_context(|| format!("Cannot read {}", dir.display())), + Err(e) => return Err(e).with_context(|| format!("Cannot read {}", escape_path(dir))), }; for entry in entries { - let entry = entry.with_context(|| format!("Cannot read {}", dir.display()))?; + let entry = entry.with_context(|| format!("Cannot read {}", escape_path(dir)))?; if entry.file_type().is_ok_and(|t| t.is_dir()) { remove_empty_dirs(&entry.path())?; } @@ -220,7 +223,7 @@ fn git_entry(dir: &Path) -> Result { GitEntry::None }) } - Err(e) => Err(e).with_context(|| format!("Cannot inspect {}", git.display())), + Err(e) => Err(e).with_context(|| format!("Cannot inspect {}", escape_path(&git))), } } @@ -239,20 +242,20 @@ fn linked_worktree_git_dir(checkout: &Path) -> Result { anyhow::ensure!( admin.exists(), "its git metadata {} is missing; was the repository moved or deleted?", - admin.display() + escape_path(&admin) ); let common = std::fs::read_to_string(admin.join("commondir")).with_context(|| { if admin.components().any(|c| c.as_os_str() == "modules") { format!( "{} looks like a submodule; meta can't remove sets that contain submodules", - admin.display() + escape_path(&admin) ) } else { - format!("{} has no commondir", admin.display()) + format!("{} has no commondir", escape_path(&admin)) } })?; let backlink = std::fs::read_to_string(admin.join("gitdir")) - .with_context(|| format!("{} has no gitdir", admin.display()))?; + .with_context(|| format!("{} has no gitdir", escape_path(&admin)))?; let points_back = admin .join(backlink.trim()) .canonicalize() @@ -262,7 +265,7 @@ fn linked_worktree_git_dir(checkout: &Path) -> Result { points_back, "{} belongs to another checkout (if this set was moved, run \ 'git worktree repair' in its repository)", - admin.display() + escape_path(&admin) ); Ok(admin.join(common.trim())) } @@ -271,16 +274,16 @@ fn linked_worktree_git_dir(checkout: &Path) -> Result { /// `dir` accounts for its files. fn scan(dir: &Path, owned: bool, loose: &mut Vec, check: &mut RemovalCheck) -> Result<()> { let entries = - std::fs::read_dir(dir).with_context(|| format!("Cannot read {}", dir.display()))?; + std::fs::read_dir(dir).with_context(|| format!("Cannot read {}", escape_path(dir)))?; for entry in entries { - let entry = entry.with_context(|| format!("Cannot read {}", dir.display()))?; + let entry = entry.with_context(|| format!("Cannot read {}", escape_path(dir)))?; let path = entry.path(); if entry.file_name() == ".git" { continue; } let file_type = entry .file_type() - .with_context(|| format!("Cannot inspect {}", path.display()))?; + .with_context(|| format!("Cannot inspect {}", escape_path(&path)))?; if !file_type.is_dir() { if !owned { loose.push(path); @@ -288,7 +291,9 @@ fn scan(dir: &Path, owned: bool, loose: &mut Vec, check: &mut RemovalCh continue; } match git_entry(&path)? { - GitEntry::Repository(why) => check.blockers.push(format!("{}: {why}", path.display())), + GitEntry::Repository(why) => check + .blockers + .push(format!("{}: {why}", escape_path(&path))), GitEntry::Worktree(repo_git_dir) => { check.members.push(Member { path: path.clone(), @@ -351,7 +356,7 @@ fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String found.push(format!( "{} {what}: {}", plural(files.len(), "file"), - sample(files, |(shown, _)| shown.clone()) + sample(files, |(shown, _)| escape(shown).into_owned()) )); } } @@ -407,7 +412,7 @@ fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String found, format!( "{}\0{text}\0{commits}\0{staged}\0{}\0{operation:?}", - repo.display(), + escape_path(repo), files.join("\n") ), )) @@ -494,8 +499,8 @@ fn operation_in_progress(repo: &Path) -> Result> { fn relative_label(root: &Path, path: &Path) -> String { match path.strip_prefix(root) { Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(), - Ok(rel) => rel.display().to_string(), - Err(_) => path.display().to_string(), + Ok(rel) => escape_path(rel).to_string(), + Err(_) => escape_path(path).to_string(), } } diff --git a/src/worktree/store.rs b/src/worktree/store.rs index e14c822..b51dac9 100644 --- a/src/worktree/store.rs +++ b/src/worktree/store.rs @@ -3,6 +3,7 @@ //! Manages `~/.meta/worktree.json` — the persistent record of all worktrees. use anyhow::Result; +use meta_core::display::escape_path; use std::path::{Path, PathBuf}; use super::types::{StoreRepoEntry, WorktreeStoreData, WorktreeStoreEntry}; @@ -21,7 +22,7 @@ fn store_key(worktree_path: &Path) -> String { Err(e) => { log::debug!( "Failed to canonicalize path '{}': {}. Using original path.", - worktree_path.display(), + escape_path(worktree_path), e ); worktree_path.to_string_lossy().into_owned() @@ -29,7 +30,7 @@ fn store_key(worktree_path: &Path) -> String { } } -fn store_path() -> PathBuf { +fn store_path() -> Result { meta_core::data_dir::data_file("worktree") } @@ -38,16 +39,26 @@ fn store_lock_path(data_path: &Path) -> PathBuf { } /// Return (data_path, lock_path) for the worktree store. -fn store_paths() -> (PathBuf, PathBuf) { - let data_path = store_path(); +fn store_paths() -> Result<(PathBuf, PathBuf)> { + let data_path = store_path()?; let lock_path = store_lock_path(&data_path); - (data_path, lock_path) + Ok((data_path, lock_path)) +} + +/// Whether the store file does not exist, so there is nothing to remove. +/// Any other error (an unreadable data dir, say) is left to the update, +/// which reports it, instead of being taken as an empty store. +fn store_missing(data_path: &Path) -> bool { + matches!( + std::fs::symlink_metadata(data_path), + Err(e) if e.kind() == std::io::ErrorKind::NotFound + ) } /// Add a worktree entry to the centralized store. pub fn store_add(worktree_path: &Path, entry: WorktreeStoreEntry) -> Result<()> { meta_core::data_dir::ensure_meta_dir()?; - let (data_path, lock_path) = store_paths(); + let (data_path, lock_path) = store_paths()?; let key = store_key(worktree_path); meta_core::store::update::(&data_path, &lock_path, |store| { @@ -57,7 +68,7 @@ pub fn store_add(worktree_path: &Path, entry: WorktreeStoreEntry) -> Result<()> /// Get all entries from the store. pub fn store_list() -> Result { - meta_core::store::read(&store_path()) + meta_core::store::read(&store_path()?) } /// Get the store key and entry for an existing worktree path, if meta @@ -85,7 +96,7 @@ pub fn store_sets_inside(worktree_path: &Path) -> Result> { /// Add repos to an existing worktree entry in the store. pub fn store_extend_repos(worktree_path: &Path, repos: Vec) -> Result<()> { - let (data_path, lock_path) = store_paths(); + let (data_path, lock_path) = store_paths()?; let key = store_key(worktree_path); meta_core::store::update::(&data_path, &lock_path, move |store| { @@ -99,8 +110,8 @@ pub fn store_extend_repos(worktree_path: &Path, repos: Vec) -> R /// Each `(key, created_at)` pair removes the entry only if it is still the /// one that was read, so a worktree recreated at the same path keeps its record. pub fn store_remove_batch(entries: &[(String, String)]) -> Result<()> { - let (data_path, lock_path) = store_paths(); - if !data_path.exists() { + let (data_path, lock_path) = store_paths()?; + if store_missing(&data_path) { return Ok(()); } @@ -559,7 +570,7 @@ mod tests { std::fs::create_dir_all(&store_dir).unwrap(); std::env::set_var("META_DATA_DIR", &store_dir); - let store = store_path(); + let store = store_path().unwrap(); // Clean up by ensuring a fresh empty store meta_core::data_dir::ensure_meta_dir().unwrap(); From 35a7fccc2ebb3cca6565c5143aa42fb79f175ac2 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:32:03 -0700 Subject: [PATCH 2/5] fix: escape store entries and the .gitignore pattern in plugin log records The plugin's logger writes records as they are; a malformed timestamp or name in worktree.json, or a META_WORKTREES name, reached the terminal raw. Implements [[tasks/harmony-2749]] --- src/worktree/helpers.rs | 5 ++++- src/worktree/store.rs | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 0b8b311..c14f0cc 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -453,7 +453,10 @@ pub fn ensure_worktrees_in_gitignore( std::fs::write(&gitignore_path, format!("{pattern}\n"))?; } if !quiet { - log::info!("Added '{pattern}' to .gitignore"); + log::info!( + "Added '{}' to .gitignore", + meta_core::display::escape(&pattern) + ); } Ok(()) } diff --git a/src/worktree/store.rs b/src/worktree/store.rs index b51dac9..7033231 100644 --- a/src/worktree/store.rs +++ b/src/worktree/store.rs @@ -138,8 +138,8 @@ pub fn entry_ttl_remaining(entry: &WorktreeStoreEntry, now_epoch: i64) -> Option Err(e) => { log::warn!( "Malformed created_at '{}' in store entry '{}': {}", - entry.created_at, - entry.name, + meta_core::display::escape(&entry.created_at), + meta_core::display::escape(&entry.name), e ); return i64::MAX; From 10010b7d7cfb6efde2bd945ec74d85fcb53dd331 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:48:00 -0700 Subject: [PATCH 3/5] fix: keep the safety fingerprint unescaped; it is compared, not printed Implements [[tasks/harmony-2749]] --- src/worktree/safety.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/worktree/safety.rs b/src/worktree/safety.rs index 5b6354a..0f1c577 100644 --- a/src/worktree/safety.rs +++ b/src/worktree/safety.rs @@ -412,7 +412,7 @@ fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String found, format!( "{}\0{text}\0{commits}\0{staged}\0{}\0{operation:?}", - escape_path(repo), + repo.display(), files.join("\n") ), )) From 1a1bd032b2b18ff0ad9794fca6407cff74920c38 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:56:38 -0700 Subject: [PATCH 4/5] fix: clone discovery fails on a nested config it cannot read Implements [[tasks/harmony-2749]] --- src/clone_queue.rs | 22 ++++++++++++++++++++-- src/worktree/helpers.rs | 2 +- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/clone_queue.rs b/src/clone_queue.rs index afe0d3b..b1c14e9 100644 --- a/src/clone_queue.rs +++ b/src/clone_queue.rs @@ -95,7 +95,7 @@ impl CloneQueue { } } - let Some((meta_path, _format)) = config::find_meta_config_in(base_dir) else { + let Some((meta_path, _format)) = config::find_meta_config_in(base_dir)? else { debug!("No .meta config found in {}", escape_path(base_dir)); return Ok(0); }; @@ -115,7 +115,7 @@ impl CloneQueue { // Skip if already exists if target_path.exists() { // But still check if it has a config file for nested discovery - if config::find_meta_config_in(&target_path).is_some() { + if config::find_meta_config_in(&target_path)?.is_some() { // Queue it for discovery even though it's already cloned added += self.push_from_meta(&target_path, depth_level + 1)?; } @@ -262,6 +262,24 @@ mod tests { // ── push / dedup ────────────────────────────────────────── + #[cfg(unix)] + #[test] + fn push_from_meta_fails_on_a_nested_config_it_cannot_read() { + // child/.meta is a link to nowhere: its repos are unknown, which is + // an error, not "no nested repos" + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("child")).unwrap(); + std::fs::write( + dir.path().join(".meta"), + r#"{"projects": {"child": {"repo": "u", "meta": true}}}"#, + ) + .unwrap(); + std::os::unix::fs::symlink("missing.json", dir.path().join("child/.meta")).unwrap(); + let queue = CloneQueue::new(None, None); + let err = queue.push_from_meta(dir.path(), 0).unwrap_err(); + assert!(format!("{err:#}").contains("Cannot read"), "{err:#}"); + } + #[test] fn push_adds_task_and_increments_count() { let queue = CloneQueue::new(None, None); diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index c14f0cc..2b40b3f 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -35,7 +35,7 @@ pub fn resolve_worktree_root(meta_dir: Option<&Path>) -> Result { // The config's rules for the worktree directory (inside the // workspace, not inside a project, not into .git) hold here too, // whoever ran this plugin - if let Some((config, _)) = meta_core::config::find_meta_config_in(dir) { + if let Some((config, _)) = meta_core::config::find_meta_config_in(dir)? { meta_core::config::parse_meta_config(&config)?; } if let Some(configured) = read_worktrees_dir_from_config(dir) { From df263a710f0e82691783f4d77c38d5832cd94018 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:02:02 -0700 Subject: [PATCH 5/5] fix: clone discovery checks the depth limit before looking at an existing child's config Implements [[tasks/harmony-2749]] --- src/clone_queue.rs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/clone_queue.rs b/src/clone_queue.rs index b1c14e9..90cefe1 100644 --- a/src/clone_queue.rs +++ b/src/clone_queue.rs @@ -114,11 +114,9 @@ impl CloneQueue { // Skip if already exists if target_path.exists() { - // But still check if it has a config file for nested discovery - if config::find_meta_config_in(&target_path)?.is_some() { - // Queue it for discovery even though it's already cloned - added += self.push_from_meta(&target_path, depth_level + 1)?; - } + // But still look in it for nested discovery (push_from_meta + // checks the depth limit before it looks for a config) + added += self.push_from_meta(&target_path, depth_level + 1)?; continue; } @@ -262,6 +260,23 @@ mod tests { // ── push / dedup ────────────────────────────────────────── + #[cfg(unix)] + #[test] + fn push_from_meta_does_not_look_past_the_depth_limit() { + // child exists with a dangling .meta; at depth limit 0 it is never + // read, so seeding still queues the missing sibling + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("child")).unwrap(); + std::fs::write( + dir.path().join(".meta"), + r#"{"projects": {"child": {"repo": "u", "meta": true}, "sib": "u2"}}"#, + ) + .unwrap(); + std::os::unix::fs::symlink("missing.json", dir.path().join("child/.meta")).unwrap(); + let queue = CloneQueue::new(None, Some(0)); + assert_eq!(queue.push_from_meta(dir.path(), 0).unwrap(), 1); + } + #[cfg(unix)] #[test] fn push_from_meta_fails_on_a_nested_config_it_cannot_read() {