From bc0b0ce050897596b7ee50f54eb8c7ebd55663c9 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:27:51 -0700 Subject: [PATCH 01/28] fix: escape untrusted values in meta context and warnings meta context escapes control characters and '|' in names, branches, tags and dependencies, so the markdown that agents read cannot be broken or carry terminal escapes. Worktree and orphan warnings escape directory names and paths. A refused ~/.meta/plugins is reported instead of silently skipped. Re-exports meta_core::display. Implements [[tasks/harmony-2749]] --- src/context.rs | 72 ++++++++++++++++++++++++++++++++------- src/lib.rs | 1 + src/main.rs | 21 ++++++------ src/registry.rs | 2 +- src/subprocess_plugins.rs | 12 ++++--- 5 files changed, 81 insertions(+), 27 deletions(-) diff --git a/src/context.rs b/src/context.rs index 8a55d0a..8041aaa 100644 --- a/src/context.rs +++ b/src/context.rs @@ -14,6 +14,7 @@ use std::time::{Duration, SystemTime}; use crate::dependency_graph::DependencyGraph; use crate::git_utils; use meta_core::config::{self, ProjectInfo}; +use meta_core::display::escape; // ── Cache ─────────────────────────────────────────────── @@ -26,18 +27,20 @@ struct CachedContext { workspace_root: PathBuf, } -fn cache_path() -> PathBuf { +fn cache_path() -> anyhow::Result { meta_core::data_dir::data_file("context_cache") } fn load_cache() -> Option { - let path = cache_path(); + let path = cache_path().ok()?; let content = std::fs::read(&path).ok()?; serde_json::from_slice(&content).ok() } fn save_cache(cached: &CachedContext, verbose: bool) { - let path = cache_path(); + let Ok(path) = cache_path() else { + return; + }; match serde_json::to_vec(cached) { Ok(json) => { if let Err(e) = std::fs::write(&path, json) { @@ -315,13 +318,25 @@ fn build_dependency_map(projects: &[ProjectInfo]) -> Option String { + escape(s).replace('|', "\\|") +} + +fn md_list(items: &[String]) -> String { + items.iter().map(|s| md(s)).collect::>().join(", ") +} + pub fn format_markdown(ctx: &WorkspaceContext) -> String { let mut out = String::new(); // Header out.push_str(&format!( "# Meta Workspace: {} ({} repos)\n\n", - ctx.name, ctx.repo_count + md(&ctx.name), + ctx.repo_count )); out.push_str(&ctx.description); out.push_str("\n\n"); @@ -337,10 +352,10 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { for r in &ctx.repos { out.push_str(&format!( "| {} | {} | {} | {} |\n", - r.name, - r.branch.as_deref().unwrap_or("-"), + md(&r.name), + md(r.branch.as_deref().unwrap_or("-")), format_status(r), - r.tags.join(", "), + md_list(&r.tags), )); } } else if has_status { @@ -350,8 +365,8 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { for r in &ctx.repos { out.push_str(&format!( "| {} | {} | {} |\n", - r.name, - r.branch.as_deref().unwrap_or("-"), + md(&r.name), + md(r.branch.as_deref().unwrap_or("-")), format_status(r), )); } @@ -361,11 +376,11 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { out.push_str("| Repo | Tags |\n"); out.push_str("|------|------|\n"); for r in &ctx.repos { - out.push_str(&format!("| {} | {} |\n", r.name, r.tags.join(", "))); + out.push_str(&format!("| {} | {} |\n", md(&r.name), md_list(&r.tags))); } } else { for r in &ctx.repos { - out.push_str(&format!("- {}\n", r.name)); + out.push_str(&format!("- {}\n", md(&r.name))); } } } @@ -383,7 +398,7 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { sorted_keys.sort(); for key in sorted_keys { let targets = &deps[key]; - out.push_str(&format!("{} → {}\n", key, targets.join(", "))); + out.push_str(&format!("{} → {}\n", md(key), md_list(targets))); } } @@ -447,6 +462,39 @@ mod tests { } } + #[test] + fn markdown_escapes_untrusted_values() { + // Values from git, the filesystem or an old context cache can carry + // terminal escapes or break the table that agents read. + let mut ctx = make_ctx( + vec![make_repo( + "z\u{1b}[2J", + Some("evil|branch\u{1b}]52;c;cm0K\u{7}"), + Some(false), + Some(0), + vec!["n\nfake"], + )], + Some(HashMap::from([( + "a\u{1b}[1A".to_string(), + vec!["b\nc".to_string()], + )])), + ); + ctx.name = "ws\u{1b}]0;TITLE\u{7}".to_string(); + let md = format_markdown(&ctx); + assert!(!md.contains('\u{1b}') && !md.contains('\u{7}'), "{md}"); + assert!( + md.contains( + "| z\\u{1b}[2J | evil\\|branch\\u{1b}]52;c;cm0K\\u{7} | clean | n\\nfake |" + ), + "{md}" + ); + assert!( + md.contains("# Meta Workspace: ws\\u{1b}]0;TITLE\\u{7} (1 repos)"), + "{md}" + ); + assert!(md.contains("a\\u{1b}[1A → b\\nc"), "{md}"); + } + // ── format_status ────────────────────────────────── #[test] diff --git a/src/lib.rs b/src/lib.rs index 17dbba7..7889f5a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ pub mod config; +pub use meta_core::display; pub mod context; pub mod dependency_graph; pub mod git_utils; diff --git a/src/main.rs b/src/main.rs index 1ae0557..2c2298e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ use loop_lib::run; use meta_core::config::{ self, find_meta_config, parse_meta_config, ConfigFormat, MetaTreeNode, ProjectInfo, }; +use meta_core::display::{escape, escape_path}; use std::io::Write; use std::path::PathBuf; @@ -700,7 +701,7 @@ fn handle_command_dispatch( if cli.verbose { eprintln!( "Detected worktree context: '{}' ({} repos)", - task_name, + escape(&task_name), wt_paths.len() ); } @@ -743,7 +744,7 @@ fn handle_command_dispatch( "{}: no projects match tag filter '{}' in worktree '{}'", "warning".yellow().bold(), cli.tag.as_deref().unwrap_or(""), - task_name + escape(&task_name) ); return Ok(()); } @@ -811,7 +812,7 @@ fn handle_command_dispatch( eprintln!( "{} No .meta config found for worktree '{}'. Tags, plugins, and dependency features unavailable.", "warning:".yellow().bold(), - task_name + escape(&task_name) ); } @@ -1385,8 +1386,8 @@ fn check_and_warn_orphan() { "{}: This meta repo is not tracked by its parent.", "warning".yellow().bold() ); - eprintln!(" Current: {}", warning.current.display()); - eprintln!(" Parent: {}", warning.parent.display()); + eprintln!(" Current: {}", escape_path(&warning.current)); + eprintln!(" Parent: {}", escape_path(&warning.parent)); eprintln!(); // Show format-appropriate syntax @@ -1396,18 +1397,18 @@ fn check_and_warn_orphan() { }; eprintln!( " To include it, add to {}/{}:", - warning.parent.display(), + escape_path(&warning.parent), config_file ); match warning.parent_format { ConfigFormat::Json => { eprintln!( " \"{}\": {{ \"repo\": \"\", \"meta\": true }}", - warning.suggested_key + escape(&warning.suggested_key) ); } ConfigFormat::Yaml => { - eprintln!(" {}:", warning.suggested_key); + eprintln!(" {}:", escape(&warning.suggested_key)); eprintln!(" repo: "); eprintln!(" meta: true"); } @@ -1559,7 +1560,7 @@ mod tests { let api = &projects[0]; assert_eq!(api.name, "api"); - assert_eq!(api.path, "./services/api"); + assert_eq!(api.path, "services/api"); // normalized assert_eq!(api.repo.as_ref().unwrap(), "git@github.com:org/api.git"); assert_eq!(api.tags, vec!["backend", "rust"]); } @@ -1622,7 +1623,7 @@ ignore: ); let api = projects.iter().find(|p| p.name == "api").unwrap(); - assert_eq!(api.path, "./backend/api"); + assert_eq!(api.path, "backend/api"); // normalized assert_eq!(api.tags, vec!["backend", "python"]); assert_eq!(ignore, vec!["node_modules", "__pycache__"]); diff --git a/src/registry.rs b/src/registry.rs index adfaea6..54b2f42 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -225,7 +225,7 @@ impl RegistryConfig { /// Get the config file path fn config_path() -> Result { - Ok(meta_core::meta_dir().join("config.yaml")) + Ok(meta_core::meta_dir()?.join("config.yaml")) } /// Get list of registries (defaults to the public registry) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 85c4eab..ffc8af1 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -65,11 +65,15 @@ impl SubprocessPluginManager { } } - // Search in ~/.meta/plugins/ (global installed) - if let Ok(global_plugins) = meta_core::data_dir::data_subdir("plugins") { - if global_plugins.exists() && visited.insert(global_plugins.clone()) { - self.scan_directory(&global_plugins)?; + // Search in ~/.meta/plugins/ (global installed), which is refused when + // another user could write to it + match meta_core::data_dir::data_subdir("plugins") { + Ok(global_plugins) => { + if visited.insert(global_plugins.clone()) { + self.scan_directory(&global_plugins)?; + } } + Err(e) => eprintln!("warning: skipping global plugins: {e:#}"), } // Search in PATH for meta-* executables (bundled/system) From 80426ec30bad9fbe3f669bf3af4653d5cccae915 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:27:51 -0700 Subject: [PATCH 02/28] fix: keep refused global plugins out of discovery; escape errors A refused ~/.meta/plugins is also skipped by the walk up from cwd. The registry config is read only from a private data dir. Errors from main and verbose paths are escaped. Implements [[tasks/harmony-2749]] --- src/context.rs | 6 +++--- src/main.rs | 16 ++++++++++++++-- src/registry.rs | 2 +- src/subprocess_plugins.rs | 32 +++++++++++++++++++++++--------- 4 files changed, 41 insertions(+), 15 deletions(-) diff --git a/src/context.rs b/src/context.rs index 8041aaa..3935aaa 100644 --- a/src/context.rs +++ b/src/context.rs @@ -14,7 +14,7 @@ use std::time::{Duration, SystemTime}; use crate::dependency_graph::DependencyGraph; use crate::git_utils; use meta_core::config::{self, ProjectInfo}; -use meta_core::display::escape; +use meta_core::display::{escape, escape_path}; // ── Cache ─────────────────────────────────────────────── @@ -48,7 +48,7 @@ fn save_cache(cached: &CachedContext, verbose: bool) { eprintln!("Failed to write context cache: {e}"); } } else if verbose { - eprintln!("Saved context cache to {}", path.display()); + eprintln!("Saved context cache to {}", escape_path(&path)); } } Err(e) => { @@ -150,7 +150,7 @@ pub fn handle_context(json: bool, no_status: bool, no_cache: bool, verbose: bool eprintln!( "Found {} projects in {}", projects.len(), - config_path.display() + escape_path(&config_path) ); } diff --git a/src/main.rs b/src/main.rs index 2c2298e..aa6daef 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ use loop_lib::run; use meta_core::config::{ self, find_meta_config, parse_meta_config, ConfigFormat, MetaTreeNode, ProjectInfo, }; -use meta_core::display::{escape, escape_path}; +use meta_core::display::{escape, escape_lines, escape_path}; use std::io::Write; use std::path::PathBuf; @@ -456,7 +456,19 @@ fn print_plugin_update_help() { // === Main Entry Point === -fn main() -> Result<()> { +fn main() -> std::process::ExitCode { + match run_cli() { + Ok(()) => std::process::ExitCode::SUCCESS, + Err(e) => { + // as Rust prints an error returned from main, but escaped: it can + // carry paths and names from git and the filesystem + eprintln!("Error: {}", escape_lines(&format!("{e:?}"))); + std::process::ExitCode::FAILURE + } + } +} + +fn run_cli() -> Result<()> { env_logger::init(); let mut cli = Cli::parse(); diff --git a/src/registry.rs b/src/registry.rs index 54b2f42..b6d1c25 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -225,7 +225,7 @@ impl RegistryConfig { /// Get the config file path fn config_path() -> Result { - Ok(meta_core::meta_dir()?.join("config.yaml")) + Ok(meta_core::data_dir::private_meta_dir()?.join("config.yaml")) } /// Get list of registries (defaults to the public registry) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index ffc8af1..26726e8 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -51,11 +51,25 @@ impl SubprocessPluginManager { self.verbose = verbose; let mut visited = std::collections::HashSet::new(); + // ~/.meta/plugins/ is refused when another user could write to it. The + // walk up from cwd passes through it from anywhere under $HOME, so + // mark it visited to keep that walk from running what it holds. + let global_plugins = meta_core::data_dir::data_subdir("plugins"); + if let Err(e) = &global_plugins { + eprintln!("warning: skipping global plugins: {e:#}"); + if let Ok(dir) = meta_core::meta_dir() { + let refused = dir.join("plugins"); + visited.insert(refused.canonicalize().unwrap_or(refused)); + } + } + // Search in .meta/plugins/ directories walking up from cwd (project-local) let mut current_dir = std::env::current_dir()?; loop { let plugin_dir = current_dir.join(".meta").join("plugins"); - if plugin_dir.exists() && plugin_dir.is_dir() && visited.insert(plugin_dir.clone()) { + if plugin_dir.is_dir() + && visited.insert(plugin_dir.canonicalize().unwrap_or(plugin_dir.clone())) + { self.scan_directory(&plugin_dir)?; } if let Some(parent) = current_dir.parent() { @@ -65,15 +79,15 @@ impl SubprocessPluginManager { } } - // Search in ~/.meta/plugins/ (global installed), which is refused when - // another user could write to it - match meta_core::data_dir::data_subdir("plugins") { - Ok(global_plugins) => { - if visited.insert(global_plugins.clone()) { - self.scan_directory(&global_plugins)?; - } + // Search in ~/.meta/plugins/ (global installed) + if let Ok(global_plugins) = global_plugins { + if visited.insert( + global_plugins + .canonicalize() + .unwrap_or(global_plugins.clone()), + ) { + self.scan_directory(&global_plugins)?; } - Err(e) => eprintln!("warning: skipping global plugins: {e:#}"), } // Search in PATH for meta-* executables (bundled/system) From 95f3bb2afd556618ca67b5a51cb1b11efdd6b633 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:27:51 -0700 Subject: [PATCH 03/28] fix: escape plugin discovery and verbose paths The skipped-global-plugins warning, plugin discovery and verbose config paths are escaped. Implements [[tasks/harmony-2749]] --- src/main.rs | 4 ++-- src/subprocess_plugins.rs | 14 +++++++++----- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index aa6daef..978f673 100644 --- a/src/main.rs +++ b/src/main.rs @@ -862,7 +862,7 @@ fn handle_command_dispatch( .map(|p| p.to_string_lossy().to_string()) .unwrap_or_else(|| ".meta / .meta.yaml / .meta.yml".to_string()); eprintln!("Error: Could not find meta config file '{config_name}'"); - eprintln!("Searched from {} up to root", current_dir.display()); + eprintln!("Searched from {} up to root", escape_path(¤t_dir)); std::process::exit(1); } }; @@ -871,7 +871,7 @@ fn handle_command_dispatch( if cli.verbose { println!("{}", "Verbose mode enabled".green()); - println!("Resolved config file path: {}", absolute_path.display()); + println!("Resolved config file path: {}", escape_path(&absolute_path)); println!("Executing command: {command_str}"); } diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 26726e8..1950440 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -4,6 +4,7 @@ //! This approach provides better isolation, language flexibility, and simpler debugging. use anyhow::{Context, Result}; +use meta_core::display::{escape, escape_lines, escape_path}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; @@ -56,7 +57,10 @@ impl SubprocessPluginManager { // mark it visited to keep that walk from running what it holds. let global_plugins = meta_core::data_dir::data_subdir("plugins"); if let Err(e) = &global_plugins { - eprintln!("warning: skipping global plugins: {e:#}"); + eprintln!( + "warning: skipping global plugins: {}", + escape_lines(&format!("{e:#}")) + ); if let Ok(dir) = meta_core::meta_dir() { let refused = dir.join("plugins"); visited.insert(refused.canonicalize().unwrap_or(refused)); @@ -105,7 +109,7 @@ impl SubprocessPluginManager { /// Scan a .meta-plugins directory for plugin executables fn scan_directory(&mut self, dir: &Path) -> Result<()> { if self.verbose { - println!("Scanning for subprocess plugins in: {}", dir.display()); + println!("Scanning for subprocess plugins in: {}", escape_path(dir)); } for entry in std::fs::read_dir(dir)? { @@ -166,9 +170,9 @@ impl SubprocessPluginManager { if self.verbose { println!( " Found plugin: {} v{} ({})", - info.name, - info.version, - path.display() + escape(&info.name), + escape(&info.version), + escape_path(path) ); } From ba8f81daba44de48d54c262ea399ed783b1cbcd6 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:27:51 -0700 Subject: [PATCH 04/28] fix: skip plugin directories other users could write to Plugin directories found walking up from cwd get the same check as ~/.meta/plugins and are skipped with a warning when another user owns or can write to them. Implements [[tasks/harmony-2749]] --- src/subprocess_plugins.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 1950440..6bdd1bf 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -46,6 +46,9 @@ impl SubprocessPluginManager { /// /// Discovery order (first match wins): /// 1. `.meta/plugins/` directories walking up from cwd (project-local) + /// + /// A plugin directory that another user owns or could write to is + /// skipped with a warning (see `meta_core::data_dir::check_private_dir`). /// 2. `~/.meta/plugins/` (global installed) /// 3. PATH (bundled/system plugins) pub fn discover_plugins(&mut self, verbose: bool) -> Result<()> { @@ -74,7 +77,16 @@ impl SubprocessPluginManager { if plugin_dir.is_dir() && visited.insert(plugin_dir.canonicalize().unwrap_or(plugin_dir.clone())) { - self.scan_directory(&plugin_dir)?; + // Plugins are run, so one that another user could have put + // there is skipped + match meta_core::data_dir::check_private_dir(&plugin_dir) { + Ok(()) => self.scan_directory(&plugin_dir)?, + Err(e) => eprintln!( + "warning: skipping plugins in {}: {}", + escape_path(&plugin_dir), + escape_lines(&format!("{e:#}")) + ), + } } if let Some(parent) = current_dir.parent() { current_dir = parent.to_path_buf(); From 6eb68b8152cb1bc4f954b59e63df08b409be51eb 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:27:51 -0700 Subject: [PATCH 05/28] fix: escape plugin list; don't create or warn about a missing global plugin dir Implements [[tasks/harmony-2749]] --- src/main.rs | 14 ++++++++++++-- src/subprocess_plugins.rs | 36 +++++++++++++++++++++--------------- 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/src/main.rs b/src/main.rs index 978f673..4431bef 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1141,7 +1141,12 @@ fn handle_plugin_command( // For local plugins, show the path in the local plugins dir let cwd = std::env::current_dir()?; let path = cwd.join(".meta/plugins").join(&plugin.name); - println!("{:<12} {:<12} {}", name, version, path.display()); + println!( + "{:<12} {:<12} {}", + escape(name), + escape(version), + escape_path(&path) + ); } } } else { @@ -1169,7 +1174,12 @@ fn handle_plugin_command( println!("{:<12} {:<12} PATH", "NAME", "VERSION"); println!("{}", "-".repeat(70)); for (name, version, _, path) in &plugins { - println!("{:<12} {:<12} {}", name, version, path.display()); + println!( + "{:<12} {:<12} {}", + escape(name), + escape(version), + escape_path(path) + ); } } } diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 6bdd1bf..98c6eb8 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -55,20 +55,26 @@ impl SubprocessPluginManager { self.verbose = verbose; let mut visited = std::collections::HashSet::new(); - // ~/.meta/plugins/ is refused when another user could write to it. The - // walk up from cwd passes through it from anywhere under $HOME, so - // mark it visited to keep that walk from running what it holds. - let global_plugins = meta_core::data_dir::data_subdir("plugins"); - if let Err(e) = &global_plugins { - eprintln!( - "warning: skipping global plugins: {}", - escape_lines(&format!("{e:#}")) - ); - if let Ok(dir) = meta_core::meta_dir() { - let refused = dir.join("plugins"); - visited.insert(refused.canonicalize().unwrap_or(refused)); - } - } + // ~/.meta/plugins/, when it exists, is refused if another user could + // write to it. The walk up from cwd passes through it from anywhere + // under $HOME, so a refused one is marked visited to keep that walk + // from running what it holds. No home, or no plugins dir, just means + // no global plugins. + let global_plugins = meta_core::meta_dir() + .ok() + .map(|dir| dir.join("plugins")) + .filter(|dir| dir.is_dir()) + .filter(|dir| match meta_core::data_dir::check_private_dir(dir) { + Ok(()) => true, + Err(e) => { + eprintln!( + "warning: skipping global plugins: {}", + escape_lines(&format!("{e:#}")) + ); + visited.insert(dir.canonicalize().unwrap_or(dir.clone())); + false + } + }); // Search in .meta/plugins/ directories walking up from cwd (project-local) let mut current_dir = std::env::current_dir()?; @@ -96,7 +102,7 @@ impl SubprocessPluginManager { } // Search in ~/.meta/plugins/ (global installed) - if let Ok(global_plugins) = global_plugins { + if let Some(global_plugins) = global_plugins { if visited.insert( global_plugins .canonicalize() From 3a4f60e24ec497887aafc7636efccbde89e6ffcb 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:27:51 -0700 Subject: [PATCH 06/28] fix: escape backslashes in meta context cells A backslash before | could otherwise turn an escaped pipe into a cell break. Implements [[tasks/harmony-2749]] --- src/context.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/context.rs b/src/context.rs index 3935aaa..5d1f94b 100644 --- a/src/context.rs +++ b/src/context.rs @@ -319,10 +319,10 @@ fn build_dependency_map(projects: &[ProjectInfo]) -> Option String { - escape(s).replace('|', "\\|") + escape(s).replace('\\', "\\\\").replace('|', "\\|") } fn md_list(items: &[String]) -> String { @@ -469,7 +469,7 @@ mod tests { let mut ctx = make_ctx( vec![make_repo( "z\u{1b}[2J", - Some("evil|branch\u{1b}]52;c;cm0K\u{7}"), + Some("evil|branch\\|x\u{1b}]52;c;cm0K\u{7}"), Some(false), Some(0), vec!["n\nfake"], @@ -484,15 +484,15 @@ mod tests { assert!(!md.contains('\u{1b}') && !md.contains('\u{7}'), "{md}"); assert!( md.contains( - "| z\\u{1b}[2J | evil\\|branch\\u{1b}]52;c;cm0K\\u{7} | clean | n\\nfake |" + "| z\\\\u{1b}[2J | evil\\|branch\\\\\\|x\\\\u{1b}]52;c;cm0K\\\\u{7} | clean | n\\\\nfake |" ), "{md}" ); assert!( - md.contains("# Meta Workspace: ws\\u{1b}]0;TITLE\\u{7} (1 repos)"), + md.contains("# Meta Workspace: ws\\\\u{1b}]0;TITLE\\\\u{7} (1 repos)"), "{md}" ); - assert!(md.contains("a\\u{1b}[1A → b\\nc"), "{md}"); + assert!(md.contains("a\\\\u{1b}[1A → b\\\\nc"), "{md}"); } // ── format_status ────────────────────────────────── From 41302e8dafa4e1cb79b7041f01a461ac02139262 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:27:51 -0700 Subject: [PATCH 07/28] fix: read and write the context cache as a private store; escape a verbose config path Implements [[tasks/harmony-2749]] --- src/context.rs | 27 +++++++++------------------ src/main.rs | 2 +- 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/src/context.rs b/src/context.rs index 5d1f94b..a358043 100644 --- a/src/context.rs +++ b/src/context.rs @@ -32,30 +32,21 @@ fn cache_path() -> anyhow::Result { } fn load_cache() -> Option { - let path = cache_path().ok()?; - let content = std::fs::read(&path).ok()?; - serde_json::from_slice(&content).ok() + // checked like any store: it is rendered into what agents read + meta_core::store::read::>(&cache_path().ok()?) + .ok() + .flatten() } fn save_cache(cached: &CachedContext, verbose: bool) { let Ok(path) = cache_path() else { return; }; - match serde_json::to_vec(cached) { - Ok(json) => { - if let Err(e) = std::fs::write(&path, json) { - if verbose { - eprintln!("Failed to write context cache: {e}"); - } - } else if verbose { - eprintln!("Saved context cache to {}", escape_path(&path)); - } - } - Err(e) => { - if verbose { - eprintln!("Failed to serialize context cache: {e}"); - } - } + match meta_core::store::write_atomic(&path, cached) { + Ok(()) if verbose => eprintln!("Saved context cache to {}", escape_path(&path)), + Ok(()) => {} + Err(e) if verbose => eprintln!("Failed to write context cache: {e:#}"), + Err(_) => {} } } diff --git a/src/main.rs b/src/main.rs index 4431bef..6294909 100644 --- a/src/main.rs +++ b/src/main.rs @@ -766,7 +766,7 @@ fn handle_command_dispatch( if cli.verbose && !config_in_worktree { eprintln!( "Using config from primary checkout: {}", - config_path.display() + escape_path(&config_path) ); } From 29f4aa3d1bf536206fa3272960e7c33ba1c2a5e7 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:27:51 -0700 Subject: [PATCH 08/28] fix: check the registry config and plugin files before trusting them Implements [[tasks/harmony-2749]] --- src/registry.rs | 12 +++++++++--- src/subprocess_plugins.rs | 10 +++++++++- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/registry.rs b/src/registry.rs index b6d1c25..55fc1ec 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -212,9 +212,15 @@ impl RegistryConfig { /// Load registry config from ~/.meta/config.yaml pub fn load() -> Result { let config_path = Self::config_path()?; - if config_path.exists() { - let content = std::fs::read_to_string(&config_path) - .with_context(|| format!("Failed to read {}", config_path.display()))?; + if std::fs::symlink_metadata(&config_path).is_ok() { + // It names where plugins are downloaded from + meta_core::store::check_private_file(&config_path)?; + let content = std::fs::read_to_string(&config_path).with_context(|| { + format!( + "Failed to read {}", + meta_core::display::escape_path(&config_path) + ) + })?; let config: RegistryConfig = serde_yaml::from_str(&content) .with_context(|| "Failed to parse registry config")?; Ok(config) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 98c6eb8..04179db 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -141,7 +141,15 @@ impl SubprocessPluginManager { && !name.ends_with(".so") && !name.ends_with(".dll") { - self.try_load_plugin(&path)?; + // It is run: skip it if another user could have changed it + match meta_core::data_dir::check_trusted_file(&path) { + Ok(()) => self.try_load_plugin(&path)?, + Err(e) => eprintln!( + "warning: skipping plugin {}: {}", + escape_path(&path), + escape_lines(&format!("{e:#}")) + ), + } } } } From 7360740f853d75030416f9c20e370c599204c35b 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:27:51 -0700 Subject: [PATCH 09/28] fix: allow a registry config reached through the user's own symlinks Implements [[tasks/harmony-2749]] --- src/registry.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/registry.rs b/src/registry.rs index 55fc1ec..534868b 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -213,8 +213,10 @@ impl RegistryConfig { pub fn load() -> Result { let config_path = Self::config_path()?; if std::fs::symlink_metadata(&config_path).is_ok() { - // It names where plugins are downloaded from - meta_core::store::check_private_file(&config_path)?; + // It names where plugins are downloaded from. (A symlink, as + // dotfile managers make, is fine if nothing on the way is + // another user's.) + meta_core::data_dir::check_trusted_file(&config_path)?; let content = std::fs::read_to_string(&config_path).with_context(|| { format!( "Failed to read {}", From 81ba778682617eb896849a5cd654aaf41a6ab935 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:27:51 -0700 Subject: [PATCH 10/28] fix: escape paths in meta init output Implements [[tasks/harmony-2749]] --- src/init.rs | 78 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 31 deletions(-) diff --git a/src/init.rs b/src/init.rs index 74621f8..3d47f75 100644 --- a/src/init.rs +++ b/src/init.rs @@ -7,6 +7,7 @@ use crate::config; use anyhow::{Context, Result}; use colored::*; +use meta_core::display::escape_path; use serde_json::{json, Map, Value}; use std::fs; use std::path::{Path, PathBuf}; @@ -206,7 +207,7 @@ fn install_claude_integration_to( let rules_link = symlink_in(target_dir, Path::new(".claude/rules")); if rules_link.is_none() { fs::create_dir_all(&rules_dir) - .with_context(|| format!("Failed to create {}", rules_dir.display()))?; + .with_context(|| format!("Failed to create {}", escape_path(&rules_dir)))?; } // Older releases wrote flat `.md` files, which Claude Code does not load. @@ -229,14 +230,14 @@ fn install_claude_integration_to( println!( "{} {} (not created by meta, left alone)", "Skipped".yellow(), - flat_path.display() + escape_path(&flat_path) ); skipped += 1; } else if overwrite_content && shipped { fs::remove_file(&flat_path) - .with_context(|| format!("Failed to remove {}", flat_path.display()))?; + .with_context(|| format!("Failed to remove {}", escape_path(&flat_path)))?; if verbose { - println!("{} {}", "Removed".yellow(), flat_path.display()); + println!("{} {}", "Removed".yellow(), escape_path(&flat_path)); } } } @@ -250,8 +251,8 @@ fn install_claude_integration_to( println!( "{} {} (reached through the symlink {}, not followed)", "Skipped".yellow(), - rel.display(), - link.display() + escape_path(&rel), + escape_path(&link) ); skipped += 1; continue; @@ -286,7 +287,7 @@ fn install_claude_integration_to( println!( "{} .claude/settings.json (reached through the symlink {}, not followed)", "Skipped".yellow(), - link.display() + escape_path(&link) ); skipped += 1; } else { @@ -448,19 +449,26 @@ fn install_skills_with( for (name, content) in skills { let rel = tool_dir.join(name).join("SKILL.md"); if let Some(link) = symlink_in(root, &rel) { - anyhow::bail!("Refusing to write through the symlink {}", link.display()); + anyhow::bail!( + "Refusing to write through the symlink {}", + escape_path(&link) + ); } let path = root.join(&rel); if path.exists() && !overwrite { if verbose { - println!("{} {} (already exists)", "Skipped".yellow(), path.display()); + println!( + "{} {} (already exists)", + "Skipped".yellow(), + escape_path(&path) + ); } report.skipped += 1; continue; } let skill_dir = root.join(tool_dir.join(name)); fs::create_dir_all(&skill_dir) - .with_context(|| format!("Failed to create {}", skill_dir.display()))?; + .with_context(|| format!("Failed to create {}", escape_path(&skill_dir)))?; write_file(&path, content, verbose)?; report.written += 1; } @@ -475,15 +483,15 @@ fn install_skills_with( println!( "{} {} (reached through the symlink {}, not followed)", "Skipped".yellow(), - agent_dir.display(), - link.display() + escape_path(agent_dir), + escape_path(&link) ); report.skipped += 1; continue; } let skills_dir = root.join(agent_dir); fs::create_dir_all(&skills_dir) - .with_context(|| format!("Failed to create {}", skills_dir.display()))?; + .with_context(|| format!("Failed to create {}", escape_path(&skills_dir)))?; report.agent_dirs.push(agent_dir.display().to_string()); // One `..` per folder in `agent_dir` @@ -498,7 +506,11 @@ fn install_skills_with( SkillEntry::Owned if overwrite => remove_owned(&link, &marker)?, SkillEntry::Owned => { if verbose { - println!("{} {} (already exists)", "Skipped".yellow(), link.display()); + println!( + "{} {} (already exists)", + "Skipped".yellow(), + escape_path(&link) + ); } report.skipped += 1; continue; @@ -507,7 +519,7 @@ fn install_skills_with( println!( "{} {} (not created by {tool}, left alone)", "Skipped".yellow(), - link.display() + escape_path(&link) ); report.skipped += 1; continue; @@ -519,8 +531,8 @@ fn install_skills_with( println!( "{} {} -> {}", "Linked".green(), - link.display(), - target.display() + escape_path(&link), + escape_path(&target) ); } } @@ -532,7 +544,7 @@ fn install_skills_with( println!( "{} {} (symlink failed: {err})", "Copied".yellow(), - link.display() + escape_path(&link) ); report.copied += 1; } @@ -602,30 +614,30 @@ fn skill_entry(link: &Path, target: &Path, marker: &str, legacy: Option<&str>) - fn remove_owned(link: &Path, marker: &str) -> Result<()> { if fs::symlink_metadata(link).is_ok_and(|m| m.is_file()) { return fs::remove_file(link) - .with_context(|| format!("Failed to remove {}", link.display())); + .with_context(|| format!("Failed to remove {}", escape_path(link))); } for file in ["SKILL.md", marker] { let path = link.join(file); if path.exists() { fs::remove_file(&path) - .with_context(|| format!("Failed to remove {}", path.display()))?; + .with_context(|| format!("Failed to remove {}", escape_path(&path)))?; } } - fs::remove_dir(link).with_context(|| format!("Failed to remove {}", link.display())) + fs::remove_dir(link).with_context(|| format!("Failed to remove {}", escape_path(link))) } /// Copy the skill folder of `source` (a `SKILL.md`) to `dir` where it can't be linked, /// marking the copy as the tool's own. fn copy_skill(source: &Path, dir: &Path, marker: &str) -> Result<()> { - fs::create_dir(dir).with_context(|| format!("Failed to create {}", dir.display()))?; + fs::create_dir(dir).with_context(|| format!("Failed to create {}", escape_path(dir)))?; fs::copy(source, dir.join("SKILL.md")) - .with_context(|| format!("Failed to copy {}", source.display()))?; + .with_context(|| format!("Failed to copy {}", escape_path(source)))?; fs::write( dir.join(marker), "Copied by `meta init claude` because a symlink could not be created here.\n\ `meta init claude --update` refreshes it.\n", ) - .with_context(|| format!("Failed to write {}", dir.display()))?; + .with_context(|| format!("Failed to write {}", escape_path(dir)))?; Ok(()) } @@ -658,18 +670,22 @@ fn install_settings(settings_path: &Path, force: bool, verbose: bool) -> Result< // Merge: read existing, deep-merge hooks, write back let existing_content = fs::read_to_string(settings_path) - .with_context(|| format!("Failed to read {}", settings_path.display()))?; + .with_context(|| format!("Failed to read {}", escape_path(settings_path)))?; let existing: Value = serde_json::from_str(&existing_content) - .with_context(|| format!("Failed to parse {}", settings_path.display()))?; + .with_context(|| format!("Failed to parse {}", escape_path(settings_path)))?; let merged = merge_hooks_into_settings(existing, meta_hooks); let content = serde_json::to_string_pretty(&merged)?; fs::write(settings_path, &content) - .with_context(|| format!("Failed to write {}", settings_path.display()))?; + .with_context(|| format!("Failed to write {}", escape_path(settings_path)))?; if verbose { - println!("{} {} (merged)", "Wrote".green(), settings_path.display()); + println!( + "{} {} (merged)", + "Wrote".green(), + escape_path(settings_path) + ); } else { println!(" {} settings.json (merged)", "✓".green()); } @@ -852,15 +868,15 @@ fn register_marketplace(verbose: bool) { } fn write_file(path: &Path, content: &str, verbose: bool) -> Result<()> { - fs::write(path, content).with_context(|| format!("Failed to write {}", path.display()))?; + fs::write(path, content).with_context(|| format!("Failed to write {}", escape_path(path)))?; if verbose { - println!("{} {}", "Wrote".green(), path.display()); + println!("{} {}", "Wrote".green(), escape_path(path)); } else { // Show the parent too: every skill file is named SKILL.md. let name = |p: &Path| p.file_name().unwrap_or_default().to_owned(); let shown = Path::new(&path.parent().map(name).unwrap_or_default()).join(name(path)); - println!(" {} {}", "✓".green(), shown.display()); + println!(" {} {}", "✓".green(), escape_path(&shown)); } Ok(()) From a1deefdd4e902e2cd1102d1279ffa3b6b4d4b5dd 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:27:51 -0700 Subject: [PATCH 11/28] fix: escape the cwd in a debug line Implements [[tasks/harmony-2749]] --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 6294909..caccc64 100644 --- a/src/main.rs +++ b/src/main.rs @@ -654,7 +654,7 @@ fn handle_command_dispatch( log::debug!( "parallel={} (from config defaults, cwd={})", defaults.parallel, - cwd.display() + escape_path(&cwd) ); defaults.parallel }; From acf16dfdce4bf968cad088f4360c89053392dd33 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:27:51 -0700 Subject: [PATCH 12/28] fix: escape paths and errors in worktree discovery debug logs Implements [[tasks/harmony-2749]] --- src/worktree.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/worktree.rs b/src/worktree.rs index cd81704..398e512 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -6,6 +6,7 @@ //! for worktree management commands. use anyhow::{Context, Result}; +use meta_core::display::{escape_lines, escape_path}; use serde::Serialize; use std::path::{Path, PathBuf}; @@ -132,7 +133,11 @@ fn discover_repos_recursive( let entries = match std::fs::read_dir(dir) { Ok(entries) => entries, Err(e) => { - log::debug!("Skipping unreadable directory {}: {e}", dir.display()); + log::debug!( + "Skipping unreadable directory {}: {}", + escape_path(dir), + escape_lines(&format!("{e:#}")) + ); return Ok(()); } }; @@ -162,7 +167,11 @@ fn discover_repos_recursive( let source = match source_repo_from_gitfile(&sub_git) { Ok(s) => s, Err(e) => { - log::debug!("Skipping {}: {e}", sub_path.display()); + log::debug!( + "Skipping {}: {}", + escape_path(&sub_path), + escape_lines(&format!("{e:#}")) + ); continue; } }; @@ -179,7 +188,11 @@ fn discover_repos_recursive( } else { // Not a repo — recurse into intermediate directory if let Err(e) = discover_repos_recursive(root, &sub_path, repos) { - log::debug!("Skipping subtree {}: {e}", sub_path.display()); + log::debug!( + "Skipping subtree {}: {}", + escape_path(&sub_path), + escape_lines(&format!("{e:#}")) + ); } } } From 681de7440a983d1075773831b77b728d02c6e463 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:27:51 -0700 Subject: [PATCH 13/28] fix: escape paths in worktree, registry and plugin errors Implements [[tasks/harmony-2749]] --- src/registry.rs | 20 +++++++++++++------- src/subprocess_plugins.rs | 2 +- src/worktree.rs | 23 ++++++++++++----------- 3 files changed, 26 insertions(+), 19 deletions(-) diff --git a/src/registry.rs b/src/registry.rs index 534868b..ed65289 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -6,6 +6,7 @@ use anyhow::{Context, Result}; use log::{debug, info}; +use meta_core::display::escape_path; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::io::Read; @@ -121,8 +122,12 @@ impl PluginManifest { return Ok(Self::default()); } - let content = std::fs::read_to_string(manifest_path) - .with_context(|| format!("Failed to read manifest from {}", manifest_path.display()))?; + let content = std::fs::read_to_string(manifest_path).with_context(|| { + format!( + "Failed to read manifest from {}", + escape_path(manifest_path) + ) + })?; let manifest: Self = serde_json::from_str(&content).with_context(|| "Failed to parse plugin manifest")?; @@ -135,8 +140,9 @@ impl PluginManifest { let json = serde_json::to_string_pretty(self).with_context(|| "Failed to serialize manifest")?; - std::fs::write(manifest_path, json) - .with_context(|| format!("Failed to write manifest to {}", manifest_path.display()))?; + std::fs::write(manifest_path, json).with_context(|| { + format!("Failed to write manifest to {}", escape_path(manifest_path)) + })?; Ok(()) } @@ -674,7 +680,7 @@ impl PluginInstaller { std::fs::create_dir_all(&self.plugins_dir).with_context(|| { format!( "Failed to create plugins directory: {}", - self.plugins_dir.display() + escape_path(&self.plugins_dir) ) }) } @@ -1068,7 +1074,7 @@ impl PluginInstaller { let output = Command::new(plugin_path) .arg("--meta-plugin-info") .output() - .with_context(|| format!("Failed to execute {}", plugin_path.display()))?; + .with_context(|| format!("Failed to execute {}", escape_path(plugin_path)))?; if !output.status.success() { anyhow::bail!( @@ -1134,7 +1140,7 @@ impl PluginInstaller { let plugin_path = self.plugins_dir.join(&plugin_name); if plugin_path.exists() { std::fs::remove_file(&plugin_path) - .with_context(|| format!("Failed to remove {}", plugin_path.display()))?; + .with_context(|| format!("Failed to remove {}", escape_path(&plugin_path)))?; // Remove from manifest let mut manifest = self.load_manifest()?; diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 04179db..cb5a250 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -307,7 +307,7 @@ impl SubprocessPluginManager { .stdout(Stdio::piped()) // Capture stdout to parse response .stderr(Stdio::inherit()) // Let stderr pass through for error messages .spawn() - .with_context(|| format!("Failed to execute plugin {}", plugin.path.display()))?; + .with_context(|| format!("Failed to execute plugin {}", escape_path(&plugin.path)))?; // Send request to plugin's stdin if let Some(mut stdin) = child.stdin.take() { diff --git a/src/worktree.rs b/src/worktree.rs index 398e512..db6b3d6 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -234,7 +234,7 @@ pub fn discover_worktree_members_recursive(task_dir: &Path) -> Result Result metadata, Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, Err(error) => { - return Err(error).with_context(|| format!("Cannot inspect {}", git_file.display())) + return Err(error) + .with_context(|| format!("Cannot inspect {}", escape_path(&git_file))) } }; if !metadata.is_file() { @@ -274,30 +275,30 @@ fn validate_worktree_gitfile(git_file: &Path) -> Result<()> { let target = content .trim() .strip_prefix("gitdir: ") - .ok_or_else(|| anyhow::anyhow!("Invalid .git file format at {}", git_file.display()))?; + .ok_or_else(|| anyhow::anyhow!("Invalid .git file format at {}", escape_path(git_file)))?; let admin = git_file .parent() .unwrap_or(Path::new(".")) .join(target) .canonicalize() - .with_context(|| format!("Missing worktree metadata for {}", git_file.display()))?; + .with_context(|| format!("Missing worktree metadata for {}", escape_path(git_file)))?; anyhow::ensure!( admin.join("HEAD").is_file(), "Missing worktree HEAD at {}", - admin.display() + escape_path(&admin) ); let common = std::fs::read_to_string(admin.join("commondir"))?; let common = admin.join(common.trim()).canonicalize()?; anyhow::ensure!( common.join("HEAD").is_file() && common.join("objects").is_dir(), "Incomplete common Git metadata at {}", - common.display() + escape_path(&common) ); let backlink = std::fs::read_to_string(admin.join("gitdir"))?; anyhow::ensure!( admin.join(backlink.trim()).canonicalize()? == git_file.canonicalize()?, "Worktree metadata backlink does not match {}", - git_file.display() + escape_path(git_file) ); Ok(()) } @@ -306,12 +307,12 @@ fn validate_worktree_gitfile(git_file: &Path) -> Result<()> { /// .git file contains: "gitdir: /path/to/primary/.git/worktrees/" fn source_repo_from_gitfile(git_file: &Path) -> Result { let content = std::fs::read_to_string(git_file) - .with_context(|| format!("Failed to read .git file at {}", git_file.display()))?; + .with_context(|| format!("Failed to read .git file at {}", escape_path(git_file)))?; let gitdir = content .trim() .strip_prefix("gitdir: ") - .ok_or_else(|| anyhow::anyhow!("Invalid .git file format at {}", git_file.display()))?; + .ok_or_else(|| anyhow::anyhow!("Invalid .git file format at {}", escape_path(git_file)))?; // gitdir points to: /path/to/primary/.git/worktrees/ // We need: /path/to/primary/ @@ -324,7 +325,7 @@ fn source_repo_from_gitfile(git_file: &Path) -> Result { .unwrap_or(Path::new(".")) .join(gitdir_path) .canonicalize() - .with_context(|| format!("Cannot resolve gitdir from {}", git_file.display()))? + .with_context(|| format!("Cannot resolve gitdir from {}", escape_path(git_file)))? }; // Walk up: worktrees/ -> .git -> repo root let dot_git_dir = gitdir_path @@ -336,7 +337,7 @@ fn source_repo_from_gitfile(git_file: &Path) -> Result { let repo_root = dot_git_dir.parent().ok_or_else(|| { anyhow::anyhow!( "Cannot find repo root from .git dir: {}", - dot_git_dir.display() + escape_path(dot_git_dir) ) })?; From 6e34eee4f15b69906d074796f947e252d1685fc5 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:27:51 -0700 Subject: [PATCH 14/28] fix: --config --recursive fails on a refused nested .meta; escape cached context and update errors walk_from parsed nested configs with unwrap_or_default, so a nested config that fails validation silently dropped its subtree with --config. It now uses meta_core's walk_projects, which returns the error. Context cache text goes through md(), plugin update lines through escape, and a meta-* entry that is not a program is skipped before the trust check instead of warned about. Implements [[tasks/harmony-2749]] --- src/context.rs | 8 +++-- src/main.rs | 62 ++++++++------------------------------- src/subprocess_plugins.rs | 1 + 3 files changed, 19 insertions(+), 52 deletions(-) diff --git a/src/context.rs b/src/context.rs index a358043..12d82a8 100644 --- a/src/context.rs +++ b/src/context.rs @@ -329,7 +329,7 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { md(&ctx.name), ctx.repo_count )); - out.push_str(&ctx.description); + out.push_str(&md(&ctx.description)); out.push_str("\n\n"); // Repo table @@ -379,7 +379,11 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { // Key commands out.push_str("\n## Key Commands\n"); for cmd in &ctx.commands { - out.push_str(&format!("- `{}` — {}\n", cmd.command, cmd.description)); + out.push_str(&format!( + "- `{}` — {}\n", + md(&cmd.command), + md(&cmd.description) + )); } // Dependencies diff --git a/src/main.rs b/src/main.rs index caccc64..dfa2a1e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -911,7 +911,7 @@ fn handle_command_dispatch( // The walk reads the default config file; with --config, start from // the chosen one and walk only the nested meta repos tree = match cli.config { - Some(_) => walk_from(meta_dir, &meta_projects, depth), + Some(_) => config::walk_projects(meta_dir, &meta_projects, depth)?, None => config::walk_meta_tree(meta_dir, depth)?, }; project_paths = vec![meta_dir_str.clone()]; @@ -1267,13 +1267,22 @@ fn handle_plugin_command( match installer.update_plugin(name) { Ok(_) => { if !json { - println!("Updated {} from {} to {}", name, current, latest); + println!( + "Updated {} from {} to {}", + escape(name), + escape(current), + escape(latest) + ); } updated_count += 1; } Err(e) => { if !json { - eprintln!("Failed to update {}: {}", name, e); + eprintln!( + "Failed to update {}: {}", + escape(name), + escape_lines(&format!("{e:#}")) + ); } } } @@ -1439,53 +1448,6 @@ fn check_and_warn_orphan() { } } -/// The meta tree whose top level is `projects` (from the config the user -/// chose), walked the way `walk_meta_tree` walks the default config: nested -/// meta repos `depth` levels down, each directory expanded at most once. -fn walk_from( - meta_dir: &std::path::Path, - projects: &[ProjectInfo], - depth: Option, -) -> Vec { - fn walk( - dir: &std::path::Path, - projects: &[ProjectInfo], - depth: Option, - visited: &mut std::collections::HashSet, - ) -> Vec { - let mut nodes: Vec = projects - .iter() - .map(|project| { - let project_dir = dir.join(&project.path); - let config = find_meta_config(&project_dir, None).filter(|(path, _)| { - project_dir.is_dir() && path.parent() == Some(&project_dir) - }); - let canonical = project_dir.canonicalize().unwrap_or(project_dir.clone()); - let children = match &config { - Some((path, _)) if depth != Some(0) && visited.insert(canonical) => { - parse_meta_config(path) - .map(|(nested, _)| { - let depth = depth.map(|d| d.saturating_sub(1)); - walk(&project_dir, &nested, depth, visited) - }) - .unwrap_or_default() - } - _ => vec![], - }; - MetaTreeNode { - info: project.clone(), - is_meta: config.is_some(), - children, - } - }) - .collect(); - nodes.sort_by(|a, b| a.info.name.cmp(&b.info.name)); - nodes - } - let root = meta_dir.canonicalize().unwrap_or(meta_dir.to_path_buf()); - walk(meta_dir, projects, depth, &mut [root].into_iter().collect()) -} - /// Flatten a meta tree into path strings, optionally filtering by tag. /// If tag_filter is Some, only includes nodes whose tags match (and recurses into them). fn flatten_with_tag_filter(nodes: &[MetaTreeNode], tag_filter: &Option) -> Vec { diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index cb5a250..a6a7dd4 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -140,6 +140,7 @@ impl SubprocessPluginManager { && !name.ends_with(".dylib") && !name.ends_with(".so") && !name.ends_with(".dll") + && is_executable(&path) { // It is run: skip it if another user could have changed it match meta_core::data_dir::check_trusted_file(&path) { From 4d0005e77f592189d6c8a50c89aeb8399ec2e30f 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:44:42 -0700 Subject: [PATCH 15/28] fix: escape plugin names, versions and sources in install and update output Implements [[tasks/harmony-2749]] --- src/main.rs | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/src/main.rs b/src/main.rs index dfa2a1e..d56efc8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1062,13 +1062,19 @@ fn handle_plugin_command( // Direct URL install let plugin_name = installer.install_from_url(&name)?; if !json { - println!("Successfully installed {plugin_name} to {location}"); + println!( + "Successfully installed {} to {location}", + escape(&plugin_name) + ); } } else if let Some(shorthand) = GitHubShorthand::parse(&name) { // GitHub shorthand install (user/repo[@version]) let plugin_name = installer.install_from_github(&shorthand)?; if !json { - println!("Successfully installed {plugin_name} to {location}"); + println!( + "Successfully installed {} to {location}", + escape(&plugin_name) + ); } } else { // Registry-based install @@ -1082,11 +1088,13 @@ fn handle_plugin_command( let plugin_name = installer.install_from_github(&shorthand)?; if !json { println!( - "Successfully installed {plugin_name} from {source} to {location}" + "Successfully installed {} from {} to {location}", + escape(&plugin_name), + escape(&source) ); } } else { - anyhow::bail!("Invalid plugin source in registry: {}", source); + anyhow::bail!("Invalid plugin source in registry: {}", escape(&source)); } } Err(_) => { @@ -1097,9 +1105,9 @@ fn handle_plugin_command( if !json { println!( "Successfully installed {} v{} ({}) to {location}", - metadata.name, - metadata.version, - installed.join(", ") + escape(&metadata.name), + escape(&metadata.version), + escape(&installed.join(", ")) ); } } @@ -1216,7 +1224,9 @@ fn handle_plugin_command( if !json { println!( "Update available for {}: {} → {}", - plugin_name, current, latest + escape(&plugin_name), + escape(¤t), + escape(&latest) ); } } else { @@ -1224,14 +1234,17 @@ fn handle_plugin_command( if !json { println!( "Successfully updated {} from {} to {} in {}", - updated, current, latest, location + escape(&updated), + escape(¤t), + escape(&latest), + escape(location) ); } } } None => { if !json { - println!("{} is already up to date", plugin_name); + println!("{} is already up to date", escape(&plugin_name)); } } } @@ -1259,7 +1272,12 @@ fn handle_plugin_command( if !json { println!("Updates available:"); for (name, current, latest) in &updates_available { - println!(" {} {} → {}", name, current, latest); + println!( + " {} {} → {}", + escape(name), + escape(current), + escape(latest) + ); } } } else { @@ -1288,7 +1306,11 @@ fn handle_plugin_command( } } if !json { - println!("\nUpdated {} plugin(s) in {}", updated_count, location); + println!( + "\nUpdated {} plugin(s) in {}", + updated_count, + escape(location) + ); } } } From a227b816d18859341f0b4774623b5c63bd17a3c6 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 16/28] docs: repo selection spells a repo as name, ./name or name/; '..' paths are refused Implements [[tasks/harmony-2749]] --- src/repo_filter.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/repo_filter.rs b/src/repo_filter.rs index a245d17..760efc2 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -33,7 +33,7 @@ pub fn repo_names( /// [`repo_names`]) or by its whole path from `root` (`.` for the root; a /// trailing `/` is ignored), never by a part of either. A value starting with /// `./` is a path only. Repos are compared as directories, so excluding one -/// excludes every spelling of it (`api` and `libs/../api`). A value that names +/// excludes every spelling of it (`api`, `./api` and `api/`). A value that names /// none of `dirs` is an error, so a typo never runs a command in a repo it was /// meant to leave out; so is a value that names several repos, and a selection /// that leaves no repo. From 1c204132abb8787f06185c99c789af88172d5b3e 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:15:22 -0700 Subject: [PATCH 17/28] fix: escape control characters in log records Registry and plugin logs carry names, versions, file names and URLs from manifests and the network. meta's logger now writes every record through escape_lines. Implements [[tasks/harmony-2749]] --- src/main.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index d56efc8..9ca598b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -469,7 +469,21 @@ fn main() -> std::process::ExitCode { } fn run_cli() -> Result<()> { - env_logger::init(); + // Log records carry names, versions, paths and URLs from config, the + // filesystem and plugin registries: escape them like other output + env_logger::Builder::from_default_env() + .format(|buf, record| { + use std::io::Write; + writeln!( + buf, + "[{} {} {}] {}", + buf.timestamp(), + record.level(), + record.target(), + escape_lines(&record.args().to_string()) + ) + }) + .init(); let mut cli = Cli::parse(); From ceee3cef4399f0db6012b8fcfe95041c07118c62 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 18/28] fix: a refused registry config is an error, not the default registry; escape plugin search results Implements [[tasks/harmony-2749]] --- src/main.rs | 8 +++++--- src/registry.rs | 4 +++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index 9ca598b..f46b753 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1047,15 +1047,17 @@ fn handle_plugin_command( if json { println!("{}", serde_json::to_string_pretty(&results)?); } else if results.is_empty() { - println!("No plugins found matching '{query}'"); + println!("No plugins found matching '{}'", escape(&query)); } else { println!("Found {} plugin(s):", results.len()); for plugin in results { println!( " {} v{} - {}", - plugin.name, plugin.version, plugin.description + escape(&plugin.name), + escape(&plugin.version), + escape(&plugin.description) ); - println!(" by {}", plugin.author); + println!(" by {}", escape(&plugin.author)); } } } diff --git a/src/registry.rs b/src/registry.rs index ed65289..4475a71 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -262,7 +262,9 @@ pub struct RegistryClient { impl RegistryClient { /// Create a new registry client pub fn new(verbose: bool) -> Result { - let config = RegistryConfig::load().unwrap_or_default(); + // A config that is refused must not fall back to the default + // registry: it may list a private one with the same plugin names + let config = RegistryConfig::load()?; Ok(Self { registries: config.get_registries(), verbose, From 1de0c89dd131e93d86dab5f171afc37a5d8635b7 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:05:13 -0700 Subject: [PATCH 19/28] fix: only a missing registry config means the default registry A config.yaml that cannot be examined (an unsearchable ~/.meta, say) was taken as absent, so a private registry silently became the public one. Implements [[tasks/harmony-2749]] --- src/registry.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/registry.rs b/src/registry.rs index 4475a71..49e0145 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -218,7 +218,21 @@ impl RegistryConfig { /// Load registry config from ~/.meta/config.yaml pub fn load() -> Result { let config_path = Self::config_path()?; - if std::fs::symlink_metadata(&config_path).is_ok() { + // Only a missing file means "use the default registry": one that + // can't be examined may list a private registry + let present = match std::fs::symlink_metadata(&config_path) { + Ok(_) => true, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(e) => { + return Err(e).with_context(|| { + format!( + "Cannot read {}", + meta_core::display::escape_path(&config_path) + ) + }) + } + }; + if present { // It names where plugins are downloaded from. (A symlink, as // dotfile managers make, is fine if nothing on the way is // another user's.) From b51f5145a5c82ef4e9f6da646033bf329fe8b082 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:30:23 -0700 Subject: [PATCH 20/28] fix: show what a failing plugin printed; escape newlines in log records The host exited on a plugin's non-zero status without printing the stdout it captured, so remove/prune's report of what they deleted was lost behind a store error. Log records now escape newlines too, so data cannot forge a log line. Implements [[tasks/harmony-2749]] --- src/main.rs | 3 ++- src/subprocess_plugins.rs | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index f46b753..8b69175 100644 --- a/src/main.rs +++ b/src/main.rs @@ -480,7 +480,8 @@ fn run_cli() -> Result<()> { buf.timestamp(), record.level(), record.target(), - escape_lines(&record.args().to_string()) + // Newlines too: one from data could forge a log line + escape(&record.args().to_string()) ) }) .init(); diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index a6a7dd4..78111b6 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -319,7 +319,10 @@ impl SubprocessPluginManager { let output = child.wait_with_output()?; if !output.status.success() { - // Plugin already printed its error to stderr, just propagate the exit code + // Plugin already printed its error to stderr. What it printed + // before failing (say the worktrees it removed before a store + // error) is shown too; then its exit code is propagated. + print!("{}", String::from_utf8_lossy(&output.stdout)); std::process::exit(output.status.code().unwrap_or(1)); } From fd46a529b7117cfdc76e4292405c085a699e3c05 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:39 -0700 Subject: [PATCH 21/28] fix: follow the fallible config lookup Implements [[tasks/harmony-2749]] --- src/init.rs | 2 +- src/registry.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/init.rs b/src/init.rs index 3d47f75..471ff86 100644 --- a/src/init.rs +++ b/src/init.rs @@ -179,7 +179,7 @@ fn install_claude_integration_to( let skills_dir = claude_dir.join("skills"); let rules_dir = claude_dir.join("rules"); - if config::find_meta_config_in(target_dir).is_none() { + if !matches!(config::find_meta_config_in(target_dir), Ok(Some(_))) { println!( "{}", "Warning: No .meta config found in current directory.".yellow() diff --git a/src/registry.rs b/src/registry.rs index 49e0145..76ac657 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -668,7 +668,7 @@ impl PluginInstaller { } // Check for legacy config files in current directory - if let Some((_config_path, _)) = find_meta_config_in(current) { + if let Some((_config_path, _)) = find_meta_config_in(current)? { return Ok(current.to_path_buf()); } From 419b15dca4c286cf8c1d35d88344e28ec4b5362d Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:12:22 -0700 Subject: [PATCH 22/28] fix: plugin install and update check the plugins dir, its manifest and a new binary like discovery does The manifest says where each plugin is updated from, and install runs the downloaded binary. Another user who could change the plugins directory or the manifest could point an update at their own release. Implements [[tasks/harmony-2749]] --- src/registry.rs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/registry.rs b/src/registry.rs index 76ac657..d62f382 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -118,8 +118,16 @@ pub enum InstallScope { impl PluginManifest { /// Load manifest from file, or return empty manifest if not found pub fn load(manifest_path: &Path) -> Result { - if !manifest_path.exists() { - return Ok(Self::default()); + match std::fs::symlink_metadata(manifest_path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()), + Err(e) => { + return Err(e).with_context(|| { + format!("Cannot read manifest {}", escape_path(manifest_path)) + }) + } + // It names where each plugin is updated from, so another user + // must not be able to change it + Ok(_) => meta_core::data_dir::check_trusted_file(manifest_path)?, } let content = std::fs::read_to_string(manifest_path).with_context(|| { @@ -698,7 +706,18 @@ impl PluginInstaller { "Failed to create plugins directory: {}", escape_path(&self.plugins_dir) ) - }) + })?; + self.check_plugins_dir() + } + + /// Plugins are run from this directory and its manifest says where they + /// are updated from: like plugin discovery, refuse it when another user + /// owns it or can change it (or a directory on the way to it). + fn check_plugins_dir(&self) -> Result<()> { + match std::fs::symlink_metadata(&self.plugins_dir) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + _ => meta_core::data_dir::check_private_dir(&self.plugins_dir), + } } /// Get the manifest file path @@ -708,6 +727,7 @@ impl PluginInstaller { /// Load the plugin manifest fn load_manifest(&self) -> Result { + self.check_plugins_dir()?; PluginManifest::load(&self.manifest_path()) } @@ -1087,6 +1107,8 @@ impl PluginInstaller { fn validate_plugin(&self, plugin_path: &Path) -> Result<()> { use std::process::Command; + // It is run: the same check as for any plugin meta runs + meta_core::data_dir::check_trusted_file(plugin_path)?; let output = Command::new(plugin_path) .arg("--meta-plugin-info") .output() From b5af016a3ef49deeb6f09c91791beb370389fcd0 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:29:10 -0700 Subject: [PATCH 23/28] fix: write the plugin manifest 0600 and the plugins dir 0700; a PATH link to a refused plugin dir stays refused Under umask 002 meta wrote a group-writable manifest and then refused it. PATH entries are compared resolved, like the plugin dirs, so one that links to a refused dir does not run what it holds. uninstall checks the dir before deleting; init reports a config it cannot read. Implements [[tasks/harmony-2749]] --- src/init.rs | 3 ++- src/registry.rs | 42 +++++++++++++++++++++++++-------------- src/subprocess_plugins.rs | 6 +++++- 3 files changed, 34 insertions(+), 17 deletions(-) diff --git a/src/init.rs b/src/init.rs index 471ff86..e2d66cf 100644 --- a/src/init.rs +++ b/src/init.rs @@ -179,7 +179,8 @@ fn install_claude_integration_to( let skills_dir = claude_dir.join("skills"); let rules_dir = claude_dir.join("rules"); - if !matches!(config::find_meta_config_in(target_dir), Ok(Some(_))) { + // A config that can't be read is an error, not "no config" + if config::find_meta_config_in(target_dir)?.is_none() { println!( "{}", "Warning: No .meta config found in current directory.".yellow() diff --git a/src/registry.rs b/src/registry.rs index d62f382..c1e1e52 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -145,14 +145,10 @@ impl PluginManifest { /// Save manifest to file pub fn save(&self, manifest_path: &Path) -> Result<()> { - let json = - serde_json::to_string_pretty(self).with_context(|| "Failed to serialize manifest")?; - - std::fs::write(manifest_path, json).with_context(|| { - format!("Failed to write manifest to {}", escape_path(manifest_path)) - })?; - - Ok(()) + // Private (0600), like meta's other stores: load refuses a manifest + // others could change, so one written under umask 002 would refuse itself + meta_core::store::write_atomic(manifest_path, self) + .with_context(|| format!("Failed to write manifest to {}", escape_path(manifest_path))) } /// Add or update a plugin entry @@ -701,13 +697,8 @@ impl PluginInstaller { /// Ensure the plugins directory exists fn ensure_plugins_dir(&self) -> Result<()> { - std::fs::create_dir_all(&self.plugins_dir).with_context(|| { - format!( - "Failed to create plugins directory: {}", - escape_path(&self.plugins_dir) - ) - })?; - self.check_plugins_dir() + // Made 0700 (whatever the umask), then held to the private-dir rules + meta_core::data_dir::create_private_dir(&self.plugins_dir) } /// Plugins are run from this directory and its manifest says where they @@ -1175,6 +1166,8 @@ impl PluginInstaller { pub fn uninstall(&self, name: &str) -> Result<()> { let plugin_name = ensure_plugin_prefix(name); + // Refuse an untrusted dir before deleting anything in it + self.check_plugins_dir()?; let plugin_path = self.plugins_dir.join(&plugin_name); if plugin_path.exists() { std::fs::remove_file(&plugin_path) @@ -1361,6 +1354,25 @@ mod tests { assert_eq!(registries[1], "https://another.registry.com"); } + #[cfg(unix)] + #[test] + fn test_plugins_dir_and_manifest_are_private_whatever_the_umask() { + // Load refuses a manifest or dir others could change, so meta must + // not create them group- or world-writable (umask 002) itself + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let installer = PluginInstaller { + plugins_dir: dir.path().join("plugins"), + verbose: false, + scope: InstallScope::Local, + }; + installer.save_manifest(&PluginManifest::default()).unwrap(); + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&installer.plugins_dir), 0o700); + assert_eq!(mode(&installer.manifest_path()), 0o600); + assert!(installer.load_manifest().is_ok()); + } + #[test] fn test_plugin_installer_uninstall() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 78111b6..564a843 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -115,7 +115,11 @@ impl SubprocessPluginManager { // Search in PATH for meta-* executables (bundled/system) if let Ok(path_var) = std::env::var("PATH") { for path_dir in std::env::split_paths(&path_var) { - if path_dir.exists() && visited.insert(path_dir.clone()) { + // Compared resolved, like the plugin dirs above: a PATH entry + // that links to a refused plugin dir must not bring it back + if path_dir.exists() + && visited.insert(path_dir.canonicalize().unwrap_or(path_dir.clone())) + { self.scan_path_directory(&path_dir)?; } } From f88836b24ec5e00e21eb71eb7d05ff8018dcea4b Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:43:26 -0700 Subject: [PATCH 24/28] fix: a meta-* program on PATH gets the same trust check as one in a plugin dir A PATH entry could be a link into a plugin dir that was refused, and discovery ran it with --meta-plugin-info. Implements [[tasks/harmony-2749]] --- src/subprocess_plugins.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 564a843..00d6f0f 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -168,7 +168,16 @@ impl SubprocessPluginManager { let path = entry.path(); if let Some(name) = path.file_name().and_then(|n| n.to_str()) { if name.starts_with("meta-") && is_executable(&path) { - self.try_load_plugin(&path)?; + // It is run: a link into a dir another user can change + // (a refused plugin dir, say) is skipped like one there + match meta_core::data_dir::check_trusted_file(&path) { + Ok(()) => self.try_load_plugin(&path)?, + Err(e) => eprintln!( + "warning: skipping plugin {}: {}", + escape_path(&path), + escape_lines(&format!("{e:#}")) + ), + } } } } From f85414f841995663464efb96cd7c548e06e2a998 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 25/28] fix: skip only PATH programs that lead into a refused plugin dir; uninstall checks the manifest first The file trust check on every PATH program refused plugins that Homebrew or a umask 002 install leave in group-writable dirs, so meta git stopped working, while anyone able to write a PATH dir could plant git there anyway. PATH stays the user's choice; a program that resolves into a plugin dir refused this run is still skipped. Implements [[tasks/harmony-2749]] --- src/registry.rs | 3 ++- src/subprocess_plugins.rs | 51 +++++++++++++++++++++++++-------------- 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/src/registry.rs b/src/registry.rs index c1e1e52..7d5a605 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -1170,11 +1170,12 @@ impl PluginInstaller { self.check_plugins_dir()?; let plugin_path = self.plugins_dir.join(&plugin_name); if plugin_path.exists() { + // The manifest is checked before anything is deleted + let mut manifest = self.load_manifest()?; std::fs::remove_file(&plugin_path) .with_context(|| format!("Failed to remove {}", escape_path(&plugin_path)))?; // Remove from manifest - let mut manifest = self.load_manifest()?; manifest.remove_plugin(&plugin_name); self.save_manifest(&manifest)?; diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 00d6f0f..68fae76 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -54,6 +54,8 @@ impl SubprocessPluginManager { pub fn discover_plugins(&mut self, verbose: bool) -> Result<()> { self.verbose = verbose; let mut visited = std::collections::HashSet::new(); + // Plugin dirs refused below, resolved: a PATH entry may lead into one + let mut refused = std::collections::HashSet::new(); // ~/.meta/plugins/, when it exists, is refused if another user could // write to it. The walk up from cwd passes through it from anywhere @@ -71,7 +73,9 @@ impl SubprocessPluginManager { "warning: skipping global plugins: {}", escape_lines(&format!("{e:#}")) ); - visited.insert(dir.canonicalize().unwrap_or(dir.clone())); + let resolved = dir.canonicalize().unwrap_or(dir.clone()); + visited.insert(resolved.clone()); + refused.insert(resolved); false } }); @@ -87,11 +91,14 @@ impl SubprocessPluginManager { // there is skipped match meta_core::data_dir::check_private_dir(&plugin_dir) { Ok(()) => self.scan_directory(&plugin_dir)?, - Err(e) => eprintln!( - "warning: skipping plugins in {}: {}", - escape_path(&plugin_dir), - escape_lines(&format!("{e:#}")) - ), + Err(e) => { + eprintln!( + "warning: skipping plugins in {}: {}", + escape_path(&plugin_dir), + escape_lines(&format!("{e:#}")) + ); + refused.insert(plugin_dir.canonicalize().unwrap_or(plugin_dir.clone())); + } } } if let Some(parent) = current_dir.parent() { @@ -120,7 +127,7 @@ impl SubprocessPluginManager { if path_dir.exists() && visited.insert(path_dir.canonicalize().unwrap_or(path_dir.clone())) { - self.scan_path_directory(&path_dir)?; + self.scan_path_directory(&path_dir, &refused)?; } } } @@ -161,22 +168,30 @@ impl SubprocessPluginManager { Ok(()) } - /// Scan a PATH directory for meta-* executables - fn scan_path_directory(&mut self, dir: &Path) -> Result<()> { + /// Scan a PATH directory for meta-* executables. PATH is the user's own + /// choice (it is where meta and git come from too), so only a program + /// that resolves into a plugin dir refused above is skipped. + fn scan_path_directory( + &mut self, + dir: &Path, + refused: &std::collections::HashSet, + ) -> Result<()> { if let Ok(entries) = std::fs::read_dir(dir) { for entry in entries.flatten() { let path = entry.path(); if let Some(name) = path.file_name().and_then(|n| n.to_str()) { if name.starts_with("meta-") && is_executable(&path) { - // It is run: a link into a dir another user can change - // (a refused plugin dir, say) is skipped like one there - match meta_core::data_dir::check_trusted_file(&path) { - Ok(()) => self.try_load_plugin(&path)?, - Err(e) => eprintln!( - "warning: skipping plugin {}: {}", - escape_path(&path), - escape_lines(&format!("{e:#}")) - ), + let home = path + .canonicalize() + .ok() + .and_then(|target| target.parent().map(Path::to_path_buf)); + if home.is_some_and(|dir| refused.contains(&dir)) { + eprintln!( + "warning: skipping plugin {}: it links into a refused plugin directory", + escape_path(&path) + ); + } else { + self.try_load_plugin(&path)?; } } } From 891b714f2229a1223445e86393733548c19a9f2e 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:34:50 -0700 Subject: [PATCH 26/28] fix: a PATH program is skipped if any link on its way leads into a refused plugin dir or file Comparing only the final target's parent missed a program below a refused dir and a second link that leaves it; a single plugin file refused inside an accepted dir is recorded too. Implements [[tasks/harmony-2749]] --- src/subprocess_plugins.rs | 62 ++++++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 14 deletions(-) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 68fae76..58e5eeb 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -90,7 +90,7 @@ impl SubprocessPluginManager { // Plugins are run, so one that another user could have put // there is skipped match meta_core::data_dir::check_private_dir(&plugin_dir) { - Ok(()) => self.scan_directory(&plugin_dir)?, + Ok(()) => self.scan_directory(&plugin_dir, &mut refused)?, Err(e) => { eprintln!( "warning: skipping plugins in {}: {}", @@ -115,7 +115,7 @@ impl SubprocessPluginManager { .canonicalize() .unwrap_or(global_plugins.clone()), ) { - self.scan_directory(&global_plugins)?; + self.scan_directory(&global_plugins, &mut refused)?; } } @@ -136,7 +136,11 @@ impl SubprocessPluginManager { } /// Scan a .meta-plugins directory for plugin executables - fn scan_directory(&mut self, dir: &Path) -> Result<()> { + fn scan_directory( + &mut self, + dir: &Path, + refused: &mut std::collections::HashSet, + ) -> Result<()> { if self.verbose { println!("Scanning for subprocess plugins in: {}", escape_path(dir)); } @@ -156,11 +160,14 @@ impl SubprocessPluginManager { // It is run: skip it if another user could have changed it match meta_core::data_dir::check_trusted_file(&path) { Ok(()) => self.try_load_plugin(&path)?, - Err(e) => eprintln!( - "warning: skipping plugin {}: {}", - escape_path(&path), - escape_lines(&format!("{e:#}")) - ), + Err(e) => { + eprintln!( + "warning: skipping plugin {}: {}", + escape_path(&path), + escape_lines(&format!("{e:#}")) + ); + refused.insert(path.canonicalize().unwrap_or(path.clone())); + } } } } @@ -170,7 +177,8 @@ impl SubprocessPluginManager { /// Scan a PATH directory for meta-* executables. PATH is the user's own /// choice (it is where meta and git come from too), so only a program - /// that resolves into a plugin dir refused above is skipped. + /// that leads into a plugin dir or file refused above, through any of + /// its links, is skipped. fn scan_path_directory( &mut self, dir: &Path, @@ -181,11 +189,7 @@ impl SubprocessPluginManager { let path = entry.path(); if let Some(name) = path.file_name().and_then(|n| n.to_str()) { if name.starts_with("meta-") && is_executable(&path) { - let home = path - .canonicalize() - .ok() - .and_then(|target| target.parent().map(Path::to_path_buf)); - if home.is_some_and(|dir| refused.contains(&dir)) { + if leads_into_refused(&path, refused) { eprintln!( "warning: skipping plugin {}: it links into a refused plugin directory", escape_path(&path) @@ -722,6 +726,36 @@ impl SubprocessPluginManager { } /// Check if a file is executable +/// Whether running `path` would run something a refused plugin dir or file +/// holds: the link chain is followed one hop at a time, and a hop in a +/// directory at or below a refused one, or at a refused file, counts. Too +/// many hops count as well. +fn leads_into_refused(path: &Path, refused: &std::collections::HashSet) -> bool { + let held = |hop: &Path| { + let dir = hop.parent().and_then(|d| d.canonicalize().ok()); + let file = hop.canonicalize().ok(); + refused.iter().any(|r| { + dir.as_deref().is_some_and(|d| d.starts_with(r)) || file.as_deref() == Some(r.as_path()) + }) + }; + let mut hop = path.to_path_buf(); + for _ in 0..40 { + if held(&hop) { + return true; + } + match std::fs::read_link(&hop) { + Ok(target) => { + hop = match hop.parent() { + Some(dir) => dir.join(target), + None => target, + } + } + Err(_) => return false, + } + } + true +} + #[cfg(unix)] fn is_executable(path: &Path) -> bool { use std::os::unix::fs::PermissionsExt; From 799386b4932c57ce525c382c12f7523c9b09c268 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:54:02 -0700 Subject: [PATCH 27/28] fix: walk PATH programs component by component to catch directory links into a refused plugin dir; --local plugin commands work where .meta is the config file Canonicalizing whole directories hid a directory symlink inside a refused plugin dir. A workspace whose .meta is the config file has no .meta/plugins (it is 'not a directory'), which now means no plugins. Implements [[tasks/harmony-2749]] --- src/registry.rs | 15 ++++++-- src/subprocess_plugins.rs | 74 +++++++++++++++++++++++++++------------ 2 files changed, 65 insertions(+), 24 deletions(-) diff --git a/src/registry.rs b/src/registry.rs index 7d5a605..347a8b5 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -115,11 +115,20 @@ pub enum InstallScope { // Future: Custom(PathBuf) for --path flag in M5 } +/// Whether `e` means the path does not exist: not found, or a part of it +/// that is a file (`.meta/plugins` where `.meta` is the config file). +fn missing(e: &std::io::Error) -> bool { + matches!( + e.kind(), + std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory + ) +} + impl PluginManifest { /// Load manifest from file, or return empty manifest if not found pub fn load(manifest_path: &Path) -> Result { match std::fs::symlink_metadata(manifest_path) { - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()), + Err(e) if missing(&e) => return Ok(Self::default()), Err(e) => { return Err(e).with_context(|| { format!("Cannot read manifest {}", escape_path(manifest_path)) @@ -706,7 +715,9 @@ impl PluginInstaller { /// owns it or can change it (or a directory on the way to it). fn check_plugins_dir(&self) -> Result<()> { match std::fs::symlink_metadata(&self.plugins_dir) { - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + // None there (in a workspace whose .meta is the config file, + // .meta/plugins is "not a directory"): no plugins + Err(e) if missing(&e) => Ok(()), _ => meta_core::data_dir::check_private_dir(&self.plugins_dir), } } diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 58e5eeb..788cb1d 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -726,34 +726,64 @@ impl SubprocessPluginManager { } /// Check if a file is executable -/// Whether running `path` would run something a refused plugin dir or file -/// holds: the link chain is followed one hop at a time, and a hop in a -/// directory at or below a refused one, or at a refused file, counts. Too -/// many hops count as well. +/// Whether running `path` would pass through a refused plugin dir or file. +/// The path is resolved one component at a time, following each symlink +/// where it is met (a directory link as well as the program's own), and +/// every location on the way is checked: one at or below a refused dir, or +/// a refused file, counts. More than 40 links count as well. fn leads_into_refused(path: &Path, refused: &std::collections::HashSet) -> bool { - let held = |hop: &Path| { - let dir = hop.parent().and_then(|d| d.canonicalize().ok()); - let file = hop.canonicalize().ok(); - refused.iter().any(|r| { - dir.as_deref().is_some_and(|d| d.starts_with(r)) || file.as_deref() == Some(r.as_path()) - }) + use std::path::Component; + // A location as canonicalize writes it (refused entries are written so), + // without resolving a link at its last component + let located = |at: &Path| match (at.parent(), at.file_name()) { + (Some(dir), Some(name)) => dir.canonicalize().ok().map(|dir| dir.join(name)), + _ => at.canonicalize().ok(), }; - let mut hop = path.to_path_buf(); - for _ in 0..40 { - if held(&hop) { - return true; - } - match std::fs::read_link(&hop) { - Ok(target) => { - hop = match hop.parent() { - Some(dir) => dir.join(target), - None => target, + let held = |at: &Path| located(at).is_some_and(|at| refused.iter().any(|r| at.starts_with(r))); + let mut pending: std::collections::VecDeque = path + .components() + .map(|c| PathBuf::from(c.as_os_str())) + .collect(); + let mut current = PathBuf::new(); + let mut links = 0; + while let Some(part) = pending.pop_front() { + match part.components().next() { + Some(Component::Prefix(_)) | Some(Component::RootDir) => current.push(&part), + Some(Component::CurDir) | None => {} + Some(Component::ParentDir) => { + current.pop(); + } + Some(Component::Normal(name)) => { + let next = current.join(name); + if held(&next) { + return true; + } + match std::fs::symlink_metadata(&next) { + Ok(meta) if meta.file_type().is_symlink() => { + links += 1; + let Ok(target) = std::fs::read_link(&next) else { + return true; + }; + if links > 40 { + return true; + } + // The target's parts go first; an absolute one + // starts again from its root + if target.has_root() { + current = PathBuf::new(); + } + for (k, c) in target.components().enumerate() { + pending.insert(k, PathBuf::from(c.as_os_str())); + } + } + Ok(_) => current = next, + // Not there: nothing to run through it + Err(_) => return false, } } - Err(_) => return false, } } - true + false } #[cfg(unix)] From 24a93af894fe72f70593bd5e794d5cd34dd0e1fe Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:09:52 -0700 Subject: [PATCH 28/28] fix: resolve a PATH program from its absolute path, so a relative entry's .. is followed Implements [[tasks/harmony-2749]] --- src/subprocess_plugins.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 788cb1d..17754b3 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -740,7 +740,13 @@ fn leads_into_refused(path: &Path, refused: &std::collections::HashSet) _ => at.canonicalize().ok(), }; let held = |at: &Path| located(at).is_some_and(|at| refused.iter().any(|r| at.starts_with(r))); - let mut pending: std::collections::VecDeque = path + // From the absolute path, so a relative PATH entry's `..` is resolved + // against where it really leads + let absolute = match std::env::current_dir() { + Ok(cwd) => cwd.join(path), + Err(_) => return true, + }; + let mut pending: std::collections::VecDeque = absolute .components() .map(|c| PathBuf::from(c.as_os_str())) .collect();