From d374c8b23a5bd3cccaf3dc8c4ddd90307ed4683c Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 15:47:37 -0700 Subject: [PATCH 01/34] docs(skills): config names, plugin locations, --local, worktree scope Teach .meta.yaml/.meta.json, with .meta as the legacy file; one config per directory. Plugin discovery reads the workspace root's .meta/plugins only; --local documented. Worktree remove/prune act on the current workspace's sets only. Drop the store line from meta-safety. [[tasks/harmony-2793]] --- .claude/skills/meta-plugins/SKILL.md | 19 +++++++++++--- .claude/skills/meta-safety/SKILL.md | 2 +- .claude/skills/meta-workspace/SKILL.md | 34 +++++++++++++------------- .claude/skills/meta-worktree/SKILL.md | 18 ++++++++------ 4 files changed, 45 insertions(+), 28 deletions(-) diff --git a/.claude/skills/meta-plugins/SKILL.md b/.claude/skills/meta-plugins/SKILL.md index 4711bad..f0182ff 100644 --- a/.claude/skills/meta-plugins/SKILL.md +++ b/.claude/skills/meta-plugins/SKILL.md @@ -55,11 +55,18 @@ meta --include api cargo clippy --all-targets -- -D warnings ## Plugin Discovery Plugins are discovered from: -1. `.meta/plugins/` in the current directory and each parent -2. `~/.meta/plugins/` (moved by `META_DATA_DIR`) +1. `.meta/plugins/` at the workspace root (the nearest directory at or above + the current one that holds a meta config); `meta plugin install --local` + installs there +2. `~/.meta/plugins/` (moved by `META_DATA_DIR`), where `meta plugin install` installs 3. Executables named `meta-*` in PATH -The first plugin found with a given name wins. +The first plugin found with a given name wins. A plugins folder meta can't read, +and a plugin that doesn't answer `--meta-plugin-info` within 5 seconds, are +skipped with a warning naming them. + +Project-local plugins are binaries: `--local` writes `.meta/plugins/.gitignore` +(`*`) so they stay out of git as untracked files. ## Plugin Management @@ -75,8 +82,14 @@ meta plugin install # Uninstall meta plugin uninstall + +# The same for this workspace only (.meta/plugins/ at the workspace root) +meta plugin install --local +meta plugin list --local ``` +`--local` outside a meta workspace fails with "not in a meta workspace". + ## Understanding Command Flow ``` diff --git a/.claude/skills/meta-safety/SKILL.md b/.claude/skills/meta-safety/SKILL.md index d584efb..e873d63 100644 --- a/.claude/skills/meta-safety/SKILL.md +++ b/.claude/skills/meta-safety/SKILL.md @@ -78,7 +78,7 @@ meta --strict git worktree prune - The root repo skipped because a commit-ish is missing there (worktree create) - Invalid `--meta` format values (worktree create) - Failed directory removal (worktree prune) -- Store update failures (worktree create, add, remove, prune) +- Worktree sets prune can't check or whose records it can't read (worktree prune) **When to use --strict:** - CI pipelines testing a specific release tag across all repos diff --git a/.claude/skills/meta-workspace/SKILL.md b/.claude/skills/meta-workspace/SKILL.md index 859ca35..f2c78e1 100644 --- a/.claude/skills/meta-workspace/SKILL.md +++ b/.claude/skills/meta-workspace/SKILL.md @@ -29,27 +29,27 @@ In a meta repo, changes often span multiple repositories. Using `meta` commands - **Maintain consistency** - same commit message, same branch across repos - **Never miss a repo** - meta tracks them all -## The .meta File - -The `.meta` file defines child repositories: - -```json -{ - "projects": { - "api": "git@github.com:org/api.git", - "web": { - "repo": "git@github.com:org/web.git", - "path": "./frontend/web", - "tags": ["frontend", "typescript"] - } - } -} +## The Meta Config + +One config file in the workspace root defines the child repositories: +`.meta.yaml` (or `.meta.yml`), or `.meta.json`. + +```yaml +projects: + api: git@github.com:org/api.git + web: + repo: git@github.com:org/web.git + path: frontend/web + tags: [frontend, typescript] ``` -**Simple format**: `"name": "git-url"` - clones to `./name` +**Simple format**: `name: git-url` - clones to `./name` **Extended format**: Object with `repo`, optional `path`, optional `tags` -`.meta.json`, `.meta.yaml` and `.meta.yml` are also supported. +An older repo may use the legacy `.meta` file (JSON, no extension). It still +works, but it takes the name of meta's `.meta/` folder (skills and +project-local plugins): rename it with `git mv .meta .meta.json` (same content). +Two config files in one directory are an error that names both; keep one. ## Discovering What's Here diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index 2cceb6a..8ffd832 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -163,14 +163,15 @@ meta git worktree prune # remove expired (TTL) and orphaned s `remove` and `prune` delete only sets meta created, and check every repo in the set first, nested ones included: uncommitted or untracked changes, commits on no branch, and files outside every repo count as work. `remove` refuses such a -set unless `--force`; `prune` keeps it. `prune` sees the sets recorded in the -current workspace's repositories (including sets made from other checkouts of -them), not every set on the machine. `--force` and `exec --ephemeral` discard that work: commit and -push first. +set unless `--force`; `prune` keeps it. Both act only on sets of the current +workspace: sets whose every worktree is recorded in one of the workspace's +repositories. Another workspace's set is never touched, even when both share a +`META_WORKTREES` directory; `remove` refuses it and names its workspace. +`--force` and `exec --ephemeral` discard that work: commit and push first. ## Lifecycle Hooks -Configure hooks in the meta config (`.meta`, `.meta.json`, `.meta.yaml` or `.meta.yml`): +Configure hooks in the meta config (`.meta.yaml`, `.meta.yml`, `.meta.json` or the legacy `.meta`): ```yaml worktree: @@ -190,14 +191,17 @@ into git's own directory for that worktree, `/.git/worktrees//meta-wor with the set's path, its project, when it was created, and its TTL, ephemeral flag and custom metadata. Git deletes the record with the worktree. The record is how `remove` and `prune` know meta made a set: a set made by hand, or by a -meta from before records, is refused; remove it with `git worktree remove`. +meta from before records, is refused, and so is a set holding a worktree meta +has no record of (one added by hand with `git worktree add`); remove those with +`git worktree remove`. `list` scans this project's `.worktrees/` and shows each set's record. ## Strict Mode `--strict` on `create` (or global `meta --strict`) turns warnings such as a missing commit-ish in one repo into errors. A create that fails is rolled back: -the worktrees and branches it made are deleted again. +the worktrees and branches it made are deleted again. If the rollback itself +can't delete something, the error says what was left behind. ## Command Reference From f897278edffd01050336e8cedb027a59c0a9e9a8 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 15:55:03 -0700 Subject: [PATCH 02/34] fix(cli): preserve init settings and handle command edge cases Validate and merge settings before installing content, write settings atomically, and report kept skills and actual hooks. Replace marketplace registration with a hint. Escape command and filter names, handle stdout EPIPE, show claimed plugin commands, and refuse project-list filters. [[tasks/harmony-2793]] --- Cargo.toml | 3 +- src/init.rs | 439 ++++++++++++++++++++++----------------------- src/main.rs | 28 ++- src/repo_filter.rs | 3 +- 4 files changed, 246 insertions(+), 227 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6670c04..43542db 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,9 +31,10 @@ flate2 = "1.0" tar = "0.4" zip = { version = "9.0.4", default-features = false, features = ["aes-crypto", "bzip2", "deflate", "time", "zstd"] } +tempfile = "3.3" + [dev-dependencies] assert_cmd = "2.0" -tempfile = "3.3" predicates = "2.1" indexmap = "2" diff --git a/src/init.rs b/src/init.rs index e2d66cf..9ced2fc 100644 --- a/src/init.rs +++ b/src/init.rs @@ -115,7 +115,7 @@ pub enum InitCommand { None, /// Install Claude Code skills, rules, and hooks Claude { - /// Overwrite all existing files including settings + /// Refresh skills and rules, merge meta hooks into settings force: bool, /// Update skills and rules only, skip settings (preserves user customizations) update: bool, @@ -143,13 +143,13 @@ fn print_init_help() { println!(" claude Install Claude Code skills, rules, and hooks for this meta repo"); println!(); println!("OPTIONS:"); - println!(" -f, --force Overwrite all existing files including settings"); + println!(" -f, --force Refresh skills and rules, merge meta hooks into settings"); println!(" -u, --update Update skills and rules only, preserve settings"); println!(); println!("EXAMPLES:"); println!(" meta init claude Install Claude integration"); println!(" meta init claude --update Update skills/rules, keep settings"); - println!(" meta init claude --force Overwrite everything"); + println!(" meta init claude --force Refresh skills/rules and merge settings"); } /// Install Claude Code skills and hook configuration @@ -189,7 +189,14 @@ fn install_claude_integration_to( println!(); } - let mut merged = false; + // Build and validate settings before writing any skills or rules. + let settings_path = claude_dir.join("settings.json"); + let settings_link = symlink_in(target_dir, Path::new(".claude/settings.json")); + let settings_plan = if update || settings_link.is_some() { + None + } else { + Some(prepare_settings(&settings_path)?) + }; // --force or --update: overwrite; default: skip existing let overwrite_content = force || update; @@ -227,19 +234,19 @@ fn install_claude_integration_to( .next() .is_some_and(|l| FLAT_SKILL_HEADINGS.contains(&l)) }); - if overwrite_content && is_file && !shipped { - println!( - "{} {} (not created by meta, left alone)", - "Skipped".yellow(), - escape_path(&flat_path) - ); - skipped += 1; - } else if overwrite_content && shipped { + if overwrite_content && shipped { fs::remove_file(&flat_path) .with_context(|| format!("Failed to remove {}", escape_path(&flat_path)))?; if verbose { println!("{} {}", "Removed".yellow(), escape_path(&flat_path)); } + } else if fs::symlink_metadata(&flat_path).is_ok() { + println!( + "{} {} (left alone)", + "Skipped".yellow(), + escape_path(&flat_path) + ); + skipped += 1; } } @@ -271,37 +278,28 @@ fn install_claude_integration_to( installed += 1; } - // Install/merge settings.json with hook configuration - // --update: skip entirely (preserve user settings) - // --force: overwrite completely - // default: merge meta hooks into existing settings - let settings_path = claude_dir.join("settings.json"); + // --update leaves settings untouched; --force uses the same merge as default. if update { - if verbose { - println!( - "{} settings.json (--update preserves settings)", - "Skipped".yellow() - ); - } + println!("Skipped .claude/settings.json (--update preserves settings)"); skipped += 1; - } else if let Some(link) = symlink_in(target_dir, Path::new(".claude/settings.json")) { + } else if let Some(link) = settings_link { println!( - "{} .claude/settings.json (reached through the symlink {}, not followed)", - "Skipped".yellow(), + "Skipped .claude/settings.json (reached through the symlink {}, not followed)", escape_path(&link) ); skipped += 1; - } else { - let result = install_settings(&settings_path, force, verbose)?; - match result { - SettingsResult::Created => installed += 1, - SettingsResult::Overwritten => installed += 1, - SettingsResult::Merged => { - merged = true; - installed += 1; - } + } else if let Some(plan) = settings_plan { + if let Some(content) = plan.content { + write_settings_atomic(&settings_path, &content)?; + installed += 1; } + println!("{} {}", plan.message, escape_path(&settings_path)); } + let present_hooks = fs::read_to_string(&settings_path) + .ok() + .and_then(|content| serde_json::from_str::(&content).ok()) + .map(|settings| installed_hooks(&settings)) + .unwrap_or_default(); // Print summary println!(); @@ -324,17 +322,11 @@ fn install_claude_integration_to( skills.copied ); } - if merged { - println!( - "{} Merged meta hooks into existing settings.json", - "✓".green() - ); - } if skipped > 0 { let hint = if update { "(--update preserves settings)" } else { - "(use --force to overwrite, --update to refresh content)" + "(use --force or --update to refresh skills and rules)" }; println!( "{} Skipped {} existing file(s) {}", @@ -344,7 +336,7 @@ fn install_claude_integration_to( ); } - if installed > 0 || merged { + if installed > 0 { println!(); println!("Claude Code is now configured for this meta repository:"); println!( @@ -353,12 +345,17 @@ fn install_claude_integration_to( skills.agent_dirs.join(", ") ); println!(" Rules: .claude/rules/ ({} rule files)", RULES.len()); - println!(" Hooks: .claude/settings.json (SessionStart, PreToolUse, PreCompact)"); + if !present_hooks.is_empty() { + println!( + " Hooks: .claude/settings.json ({})", + present_hooks.join(", ") + ); + } println!(" Note: PreToolUse hooks require the standalone agent CLI (`agent guard`)."); } #[cfg(not(test))] - if (installed > 0 || merged) && !agent_cli_available() { + if (installed > 0) && !agent_cli_available() { println!( "{}", "Warning: 'agent' CLI not found. PreToolUse hooks require the standalone agent tool." @@ -367,10 +364,10 @@ fn install_claude_integration_to( println!("Install from: https://github.com/gitkb/agent"); } - // Try to register GitKB marketplace if claude CLI is available - // Skip in tests to avoid external CLI calls that slow down test execution - #[cfg(not(test))] - register_marketplace(verbose); + println!(); + println!("For global Claude plugin access, run:"); + println!(" claude plugin marketplace add gitkb/claude-plugins"); + println!(" claude plugin install meta@gitkb"); Ok(()) } @@ -457,13 +454,11 @@ fn install_skills_with( } let path = root.join(&rel); if path.exists() && !overwrite { - if verbose { - println!( - "{} {} (already exists)", - "Skipped".yellow(), - escape_path(&path) - ); - } + println!( + "{} {} (already exists)", + "Skipped".yellow(), + escape_path(&path) + ); report.skipped += 1; continue; } @@ -503,16 +498,13 @@ fn install_skills_with( let legacy = agent.legacy.then_some(*content); match skill_entry(&link, &target, &marker, legacy) { SkillEntry::Missing => {} - SkillEntry::Linked => continue, + SkillEntry::Linked => { + println!("Skipped {} (already linked)", escape_path(&link)); + continue; + } SkillEntry::Owned if overwrite => remove_owned(&link, &marker)?, SkillEntry::Owned => { - if verbose { - println!( - "{} {} (already exists)", - "Skipped".yellow(), - escape_path(&link) - ); - } + println!("Skipped {} (already exists)", escape_path(&link)); report.skipped += 1; continue; } @@ -642,56 +634,70 @@ fn copy_skill(source: &Path, dir: &Path, marker: &str) -> Result<()> { Ok(()) } -/// Result of settings installation -enum SettingsResult { - Created, - Overwritten, - Merged, +struct SettingsPlan { + content: Option, + message: String, } -/// Install or merge settings.json -fn install_settings(settings_path: &Path, force: bool, verbose: bool) -> Result { - let meta_hooks = build_meta_hooks(); - - if !settings_path.exists() { - // Fresh install: create new settings with meta hooks - let settings = json!({ "hooks": meta_hooks }); - let content = serde_json::to_string_pretty(&settings)?; - write_file(settings_path, &content, verbose)?; - return Ok(SettingsResult::Created); - } - - if force { - // Force: overwrite completely - let settings = json!({ "hooks": meta_hooks }); - let content = serde_json::to_string_pretty(&settings)?; - write_file(settings_path, &content, verbose)?; - return Ok(SettingsResult::Overwritten); - } - - // Merge: read existing, deep-merge hooks, write back - let existing_content = fs::read_to_string(settings_path) - .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 {}", 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 {}", escape_path(settings_path)))?; - - if verbose { - println!( - "{} {} (merged)", - "Wrote".green(), - escape_path(settings_path) - ); +fn prepare_settings(path: &Path) -> Result { + let existing = match fs::read_to_string(path) { + Ok(content) => Some( + serde_json::from_str::(&content) + .with_context(|| format!("Invalid JSON in {} at key '$'", escape_path(path)))?, + ), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(e).with_context(|| format!("Failed to read {}", escape_path(path))), + }; + let created = existing.is_none(); + let existing = existing.unwrap_or_else(|| json!({})); + let before = installed_hooks(&existing); + let merged = merge_hooks_into_settings(existing, build_meta_hooks(), path)?; + let added: Vec<_> = installed_hooks(&merged) + .into_iter() + .filter(|key| !before.contains(key)) + .collect(); + let message = if created { + "Created".to_string() + } else if added.is_empty() { + "Already has meta's hooks (no write):".to_string() } else { - println!(" {} settings.json (merged)", "✓".green()); - } + format!("Added {} hooks to", added.join(", ")) + }; + let content = if created || !added.is_empty() { + Some(serde_json::to_string_pretty(&merged)?) + } else { + None + }; + Ok(SettingsPlan { content, message }) +} - Ok(SettingsResult::Merged) +fn write_settings_atomic(path: &Path, content: &str) -> Result<()> { + use std::io::Write; + let parent = path.parent().context("Settings path has no parent")?; + let mut temp = tempfile::NamedTempFile::new_in(parent).with_context(|| { + format!( + "Failed to create temporary settings in {}", + escape_path(parent) + ) + })?; + temp.write_all(content.as_bytes())?; + temp.persist(path) + .with_context(|| format!("Failed to write {}", escape_path(path)))?; + Ok(()) +} + +fn installed_hooks(settings: &Value) -> Vec { + build_meta_hooks() + .into_iter() + .filter_map(|(key, groups)| { + let existing = settings.get("hooks")?.get(&key)?.as_array()?; + groups + .as_array()? + .iter() + .all(|group| existing.contains(group)) + .then_some(key) + }) + .collect() } /// Build the meta hooks configuration as a JSON object @@ -739,68 +745,42 @@ fn build_meta_hooks() -> Map { } /// Merge meta hooks into existing settings, preserving other settings -fn merge_hooks_into_settings(mut existing: Value, meta_hooks: Map) -> Value { - // Ensure existing has a hooks object - if !existing.is_object() { - return json!({ "hooks": meta_hooks }); - } - - let obj = existing.as_object_mut().unwrap(); - - // Get or create the hooks object +fn merge_hooks_into_settings( + mut existing: Value, + meta_hooks: Map, + path: &Path, +) -> Result { + let invalid = |key: &str, shape: &str| { + anyhow::anyhow!( + "Cannot merge {}: key '{}' must be {}", + escape_path(path), + key, + shape + ) + }; + let obj = existing + .as_object_mut() + .ok_or_else(|| invalid("$", "an object"))?; let hooks = obj .entry("hooks") .or_insert_with(|| json!({})) - .as_object_mut(); - - if let Some(hooks) = hooks { - // For each lifecycle key in meta_hooks, append to existing array - for (lifecycle, meta_hook_array) in meta_hooks { - if let Some(existing_array) = hooks.get_mut(&lifecycle) { - // Existing array: append meta hooks - if let Some(arr) = existing_array.as_array_mut() { - if let Some(meta_arr) = meta_hook_array.as_array() { - for hook in meta_arr { - // Avoid duplicates by checking if hook already exists - if !arr.iter().any(|h| hooks_equal(h, hook)) { - arr.push(hook.clone()); - } - } - } + .as_object_mut() + .ok_or_else(|| invalid("hooks", "an object"))?; + for (key, groups) in meta_hooks { + let arr = hooks + .entry(&key) + .or_insert_with(|| json!([])) + .as_array_mut() + .ok_or_else(|| invalid(&format!("hooks.{key}"), "an array"))?; + if let Some(groups) = groups.as_array() { + for group in groups { + if !arr.contains(group) { + arr.push(group.clone()); } - } else { - // No existing array: add meta hooks - hooks.insert(lifecycle, meta_hook_array); } } - } else { - // hooks is not an object, replace it - obj.insert("hooks".to_string(), json!(meta_hooks)); - } - - existing -} - -/// Check if two hook entries are effectively equal (same type and command/prompt) -fn hooks_equal(a: &Value, b: &Value) -> bool { - // Compare the hooks array within each group - let a_hooks = a.get("hooks").and_then(|h| h.as_array()); - let b_hooks = b.get("hooks").and_then(|h| h.as_array()); - - match (a_hooks, b_hooks) { - (Some(a_arr), Some(b_arr)) => { - if a_arr.len() != b_arr.len() { - return false; - } - a_arr.iter().zip(b_arr.iter()).all(|(a_hook, b_hook)| { - let same_type = a_hook.get("type") == b_hook.get("type"); - let same_command = a_hook.get("command") == b_hook.get("command"); - let same_prompt = a_hook.get("prompt") == b_hook.get("prompt"); - same_type && same_command && same_prompt - }) - } - _ => false, } + Ok(existing) } #[cfg(not(test))] @@ -816,58 +796,6 @@ fn agent_cli_available() -> bool { .unwrap_or(false) } -/// Register the GitKB marketplace with Claude Code (if available). -/// This is best-effort — if `claude` is not on PATH, skip silently. -#[cfg(not(test))] -fn register_marketplace(verbose: bool) { - use std::process::Command; - - // Check if claude CLI is available - let claude_available = Command::new("claude") - .arg("--version") - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .status() - .map(|s| s.success()) - .unwrap_or(false); - - if !claude_available { - if verbose { - println!( - "{} Claude CLI not found, skipping marketplace registration", - "•".yellow() - ); - } - return; - } - - // Register the marketplace (idempotent) - let result = Command::new("claude") - .args(["plugin", "marketplace", "add", "gitkb/claude-plugins"]) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .status(); - - match result { - Ok(status) if status.success() => { - println!(); - println!("{} Registered GitKB plugin marketplace", "✓".green()); - println!( - " Run {} for global plugin access", - "claude plugin install meta@gitkb".cyan() - ); - } - _ => { - if verbose { - println!( - "{} Failed to register marketplace (non-fatal)", - "•".yellow() - ); - } - } - } -} - fn write_file(path: &Path, content: &str, verbose: bool) -> Result<()> { fs::write(path, content).with_context(|| format!("Failed to write {}", escape_path(path)))?; @@ -888,6 +816,71 @@ mod tests { use super::*; use tempfile::tempdir; + #[test] + fn invalid_settings_leave_every_file_unchanged_even_with_force() { + fn snapshot(root: &Path) -> Vec<(PathBuf, Option>)> { + let mut entries = Vec::new(); + for entry in fs::read_dir(root).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + entries.push((path.clone(), None)); + entries.extend(snapshot(&path)); + } else { + entries.push((path.clone(), Some(fs::read(&path).unwrap()))); + } + } + entries.sort(); + entries + } + for (content, key) in [ + (r#"[{"user":"data"}]"#, "$"), + (r#"{"hooks":[],"theme":"dark"}"#, "hooks"), + (r#"{"hooks":{"PreToolUse":{}}}"#, "hooks.PreToolUse"), + ("{invalid json", "$"), + ] { + let dir = tempdir().unwrap(); + fs::create_dir_all(dir.path().join(".claude/rules")).unwrap(); + fs::write( + dir.path() + .join(".claude/rules/meta-workspace-discipline.md"), + "keep this rule", + ) + .unwrap(); + let settings = dir.path().join(".claude/settings.json"); + fs::write(&settings, content).unwrap(); + let before = snapshot(dir.path()); + for force in [false, true] { + let err = + install_claude_integration_to(dir.path(), force, false, false).unwrap_err(); + let message = format!("{err:#}"); + assert!(message.contains(&escape_path(&settings)), "{message}"); + assert!(message.contains(&format!("key '{key}'")), "{message}"); + assert_eq!(snapshot(dir.path()), before); + } + } + } + + #[test] + fn settings_plan_compares_matchers_and_reports_no_write() { + let dir = tempdir().unwrap(); + let path = dir.path().join("settings.json"); + let mut settings = json!({"hooks": build_meta_hooks(), "theme": "dark"}); + settings["hooks"]["PreToolUse"][0]["matcher"] = json!("Read"); + fs::write(&path, serde_json::to_string(&settings).unwrap()).unwrap(); + let plan = prepare_settings(&path).unwrap(); + assert_eq!(plan.message, "Added PreToolUse hooks to"); + let content = plan.content.unwrap(); + let merged: Value = serde_json::from_str(&content).unwrap(); + assert_eq!(merged["theme"], "dark"); + assert_eq!(merged["hooks"]["PreToolUse"].as_array().unwrap().len(), 2); + assert_eq!(merged["hooks"]["PreToolUse"][1]["matcher"], "Bash"); + write_settings_atomic(&path, &content).unwrap(); + let plan = prepare_settings(&path).unwrap(); + assert_eq!(plan.message, "Already has meta's hooks (no write):"); + assert!(plan.content.is_none()); + assert_eq!(fs::read_to_string(path).unwrap(), content); + } + #[test] fn test_install_creates_skills_rules_and_settings() { let dir = tempdir().unwrap(); @@ -1002,12 +995,12 @@ mod tests { let rule_content = fs::read_to_string(&existing_rule).unwrap(); assert!(rule_content.contains("Meta Workspace Discipline")); - // Settings should be overwritten (not merged) + // --force still merges settings. let settings_content = fs::read_to_string(&existing_settings).unwrap(); let settings: Value = serde_json::from_str(&settings_content).unwrap(); assert!( - settings.get("custom").is_none(), - "should not preserve custom key with --force" + settings.get("custom").is_some(), + "should preserve custom key with --force" ); assert!(settings.get("hooks").is_some(), "should have hooks"); } @@ -1466,7 +1459,8 @@ mod tests { }); let meta_hooks = build_meta_hooks(); - let merged = merge_hooks_into_settings(existing, meta_hooks); + let merged = + merge_hooks_into_settings(existing, meta_hooks, Path::new("settings.json")).unwrap(); // Should preserve existing Stop hook assert!(merged["hooks"]["Stop"].is_array()); @@ -1500,7 +1494,8 @@ mod tests { }); let meta_hooks = build_meta_hooks(); - let merged = merge_hooks_into_settings(existing, meta_hooks); + let merged = + merge_hooks_into_settings(existing, meta_hooks, Path::new("settings.json")).unwrap(); // Should NOT duplicate SessionStart hook let session_hooks = merged["hooks"]["SessionStart"].as_array().unwrap(); diff --git a/src/main.rs b/src/main.rs index 8b69175..7500364 100644 --- a/src/main.rs +++ b/src/main.rs @@ -177,7 +177,7 @@ struct InitArgs { enum InitCommands { /// Install Claude Code skills, rules, and hooks for this meta repo Claude { - /// Overwrite all existing files including settings + /// Refresh skills and rules, merge meta hooks into settings #[arg(short, long)] force: bool, @@ -287,10 +287,15 @@ fn write_help_with_plugin_commands( commands.push((name, desc, Some(plugin))); } - // Plugin commands (e.g., "git", "project", "rust") + // Plugin namespaces must be claimed commands, not merely plugin names. // These are invoked as `meta ` // Mark them with plugin name and version suffix for (name, version, description) in plugins.list_plugins() { + if !plugins.available_commands().iter().any(|(command, owner)| { + *owner == name && command.split_whitespace().next() == Some(name) + }) { + continue; + } commands.push(( name.to_string(), description.to_string(), @@ -459,6 +464,12 @@ fn print_plugin_update_help() { fn main() -> std::process::ExitCode { match run_cli() { Ok(()) => std::process::ExitCode::SUCCESS, + Err(e) + if e.downcast_ref::() + .is_some_and(|e| e.0.kind() == std::io::ErrorKind::BrokenPipe) => + { + 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 @@ -674,6 +685,16 @@ fn handle_command_dispatch( defaults.parallel }; + if !is_explicit_exec + && command_args.first().is_some_and(|s| s == "project") + && command_args + .get(1) + .is_some_and(|s| s == "list" || s == "ls") + && (cli.include.is_some() || cli.exclude.is_some()) + { + anyhow::bail!("meta project list does not take --include/--exclude"); + } + let command_str = loop_lib::display_command(&command_args); // Check if this is `git clone` - it doesn't require a .meta file because @@ -1416,8 +1437,9 @@ fn unrecognized_command_error( eprintln!( "{}: unrecognized command '{}'", "error".red().bold(), - first_cmd + escape(first_cmd) ); + let command_str = escape(command_str); eprintln!(); eprintln!("To run '{command_str}' across all repos:"); eprintln!(" meta exec -- {command_str}"); diff --git a/src/repo_filter.rs b/src/repo_filter.rs index 760efc2..b0747a3 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -74,10 +74,11 @@ pub fn select( let listed = |repos: &[&Repo]| -> String { repos .iter() - .map(|r| r.path.as_str()) + .map(|r| meta_core::display::escape(&r.path)) .collect::>() .join(", ") }; + let value = meta_core::display::escape(value); if by_name.len() > 1 { bail!( "{flag} '{value}' is the .meta name of the repos at {}; name one by its path, \ From 570f2e64154a43ebe8a703663576019ce54cfa06 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 15:56:07 -0700 Subject: [PATCH 03/34] fix(plugins): scope discovery to workspaces and bound metadata probes Use the nearest config for local plugins, skip unreadable plugin directories, and kill timed-out probe process groups. Report local binary versions and paths, ignore untracked local plugin files, and escape config errors. [[tasks/harmony-2793]] --- Cargo.toml | 3 + src/context.rs | 2 +- src/main.rs | 64 +++--- src/registry.rs | 139 +++++++------ src/subprocess_plugins.rs | 192 +++++++++++++----- tests/plugin_discovery.rs | 405 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 654 insertions(+), 151 deletions(-) create mode 100644 tests/plugin_discovery.rs diff --git a/Cargo.toml b/Cargo.toml index 43542db..7d8828f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,9 @@ zip = { version = "9.0.4", default-features = false, features = ["aes-crypto", " tempfile = "3.3" +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [dev-dependencies] assert_cmd = "2.0" predicates = "2.1" diff --git a/src/context.rs b/src/context.rs index 12d82a8..a8114ef 100644 --- a/src/context.rs +++ b/src/context.rs @@ -103,7 +103,7 @@ fn is_cache_valid(cached: &CachedContext, current_root: &PathBuf) -> bool { pub fn handle_context(json: bool, no_status: bool, no_cache: bool, verbose: bool) -> Result<()> { let cwd = std::env::current_dir().context("Failed to get current directory")?; - let (config_path, _format) = config::find_meta_config(&cwd, None) + let (config_path, _format) = config::find_meta_config(&cwd, None)? .ok_or_else(|| anyhow::anyhow!("Not a meta workspace (no .meta config found)"))?; let meta_dir = config_path diff --git a/src/main.rs b/src/main.rs index 7500364..f629534 100644 --- a/src/main.rs +++ b/src/main.rs @@ -755,7 +755,8 @@ fn handle_command_dispatch( } // Try to find .meta config for full feature support - if let Some((config_path, _format)) = find_meta_config(&task_dir, cli.config.as_ref()) { + if let Some((config_path, _format)) = find_meta_config(&task_dir, cli.config.as_ref())? + { let (meta_projects, ignore_list) = parse_meta_config(&config_path)?; // Build name→info lookup for tag filtering @@ -889,14 +890,14 @@ fn handle_command_dispatch( } } - let absolute_path = match find_meta_config(¤t_dir, cli.config.as_ref()) { + let absolute_path = match find_meta_config(¤t_dir, cli.config.as_ref())? { Some((path, _format)) => path, None => { let config_name = cli .config .as_ref() - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_else(|| ".meta / .meta.yaml / .meta.yml".to_string()); + .map(|p| escape_path(p)) + .unwrap_or_else(|| config::META_CONFIG_NAMES.join(" / ")); eprintln!("Error: Could not find meta config file '{config_name}'"); eprintln!("Searched from {} up to root", escape_path(¤t_dir)); std::process::exit(1); @@ -1158,17 +1159,15 @@ fn handle_plugin_command( return Ok(()); } if local { - // For --local, use the registry-based listing for plugin management - let plugins = match PluginInstaller::new_local(verbose) { - Ok(installer) => installer.list_plugins_detailed()?, - Err(_) => { - if !json { - println!("Not in a meta workspace"); - } - return Ok(()); + let cwd = std::env::current_dir()?; + if config::find_workspace_root(&cwd)?.is_none() { + if !json { + println!("Not in a meta workspace"); } - }; - + return Ok(()); + } + let installer = PluginInstaller::new_local(verbose)?; + let plugins = installer.list_plugins_detailed()?; if json { println!("{}", serde_json::to_string_pretty(&plugins)?); } else if plugins.is_empty() { @@ -1184,9 +1183,7 @@ fn handle_plugin_command( .strip_prefix(PLUGIN_PREFIX) .unwrap_or(&plugin.name); let version = plugin.version.as_deref().unwrap_or("-"); - // 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); + let path = installer.plugins_dir().join(&plugin.name); println!( "{:<12} {:<12} {}", escape(name), @@ -1463,7 +1460,7 @@ fn check_and_warn_orphan() { } // Find the nearest .meta config - let Some((config_path, _)) = find_meta_config(¤t_dir, None) else { + let Ok(Some((config_path, _))) = find_meta_config(¤t_dir, None) else { return; }; @@ -1483,14 +1480,9 @@ fn check_and_warn_orphan() { eprintln!(); // Show format-appropriate syntax - let config_file = match warning.parent_format { - ConfigFormat::Json => ".meta", - ConfigFormat::Yaml => ".meta.yaml", - }; eprintln!( - " To include it, add to {}/{}:", - escape_path(&warning.parent), - config_file + " To include it, add to {}:", + escape_path(&warning.parent_config) ); match warning.parent_format { ConfigFormat::Json => { @@ -1680,23 +1672,21 @@ ignore: let meta_path = dir.path().join(".meta"); std::fs::write(&meta_path, r#"{"projects": {}}"#).unwrap(); - let result = find_meta_config(dir.path(), None); + let result = find_meta_config(dir.path(), None).unwrap(); assert!(result.is_some()); let (path, _format) = result.unwrap(); assert_eq!(path, meta_path); } #[test] - fn test_find_meta_config_yaml_priority() { + fn test_find_meta_config_rejects_ambiguity() { let dir = tempfile::tempdir().unwrap(); - // Create .meta first (JSON), then .meta.yaml std::fs::write(dir.path().join(".meta"), r#"{"projects": {}}"#).unwrap(); - - // .meta should be found first (it's checked before .meta.yaml) - let result = find_meta_config(dir.path(), None); - assert!(result.is_some()); - let (path, _format) = result.unwrap(); - assert!(path.ends_with(".meta")); + std::fs::write(dir.path().join(".meta.yaml"), "projects: {}").unwrap(); + let err = find_meta_config(dir.path(), None).unwrap_err().to_string(); + assert!(err.contains("Multiple meta config files")); + assert!(err.contains(".meta.yaml")); + assert!(err.contains(&escape_path(&dir.path().join(".meta")))); } #[test] @@ -1939,7 +1929,7 @@ projects: std::fs::write(&meta_path, r#"{"projects": {}}"#).unwrap(); // Search from nested directory should find root .meta - let result = find_meta_config(&nested, None); + let result = find_meta_config(&nested, None).unwrap(); assert!(result.is_some()); let (found_path, _) = result.unwrap(); assert_eq!(found_path, meta_path); @@ -1953,7 +1943,7 @@ projects: let yaml_path = dir.path().join(".meta.yaml"); std::fs::write(&yaml_path, "projects:\n p1: git@test.git\n").unwrap(); - let result = find_meta_config(dir.path(), None); + let result = find_meta_config(dir.path(), None).unwrap(); assert!(result.is_some()); // Clean up and test .yml extension @@ -1961,7 +1951,7 @@ projects: let yml_path = dir.path().join(".meta.yml"); std::fs::write(&yml_path, "projects:\n p2: git@test.git\n").unwrap(); - let result = find_meta_config(dir.path(), None); + let result = find_meta_config(dir.path(), None).unwrap(); assert!(result.is_some()); } } diff --git a/src/registry.rs b/src/registry.rs index d00b749..b19132b 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -625,46 +625,16 @@ impl PluginInstaller { &self.scope } - /// Find the workspace root directory by walking up from the current directory - /// - /// Searches for: - /// 1. `.meta/` directory (new format, preferred) - /// 2. `.meta.yaml`, `.meta.yml`, or `.meta` config file (legacy formats) - /// - /// Walks up the directory tree until one is found or filesystem root is reached. - /// - /// # Errors - /// Find the workspace root starting from the given directory. - /// Walks up the directory tree looking for .meta/ directory or legacy config files. + /// Find the nearest directory holding a config file (not a bare `.meta/`). fn find_workspace_root_from(start_dir: &Path) -> Result { - use crate::config::find_meta_config_in; - - // Walk up the directory tree once, checking both .meta/ and config files - let mut current = start_dir; - loop { - // Check for .meta/ directory (new format) - let meta_dir = current.join(".meta"); - if meta_dir.is_dir() { - return Ok(current.to_path_buf()); - } - - // Check for legacy config files in current directory - if let Some((_config_path, _)) = find_meta_config_in(current)? { - return Ok(current.to_path_buf()); - } - - // Move to parent directory - match current.parent() { - Some(parent) => current = parent, - None => break, - } - } + meta_core::config::find_workspace_root(start_dir)?.ok_or_else(|| anyhow::anyhow!( + "Not in a meta workspace.\nExpected to find a config file: {}.\nRun 'meta init' to create a new workspace, or cd to an existing workspace.", + meta_core::config::META_CONFIG_NAMES.join(", ") + )) + } - anyhow::bail!( - "Not in a meta workspace.\n\ - Expected to find .meta/ directory or .meta.yaml config file.\n\ - Run 'meta init' to create a new workspace, or cd to an existing workspace." - ) + pub fn plugins_dir(&self) -> &Path { + &self.plugins_dir } /// Get the default plugins directory (~/.meta/plugins/) @@ -675,7 +645,28 @@ impl PluginInstaller { /// Ensure the plugins directory exists fn ensure_plugins_dir(&self) -> Result<()> { // Made 0700, whatever the umask - meta_core::data_dir::create_private_dir(&self.plugins_dir) + meta_core::data_dir::create_private_dir(&self.plugins_dir)?; + if self.scope == InstallScope::Local { + let ignore_path = self.plugins_dir.join(".gitignore"); + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&ignore_path) + { + Ok(mut file) => { + use std::io::Write; + file.write_all(b"*\n").with_context(|| { + format!("Failed to write {}", escape_path(&ignore_path)) + })?; + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => { + return Err(e) + .with_context(|| format!("Failed to create {}", escape_path(&ignore_path))) + } + } + } + Ok(()) } /// Get the manifest file path @@ -1113,9 +1104,19 @@ impl PluginInstaller { plugins.push(PluginInfo { name: name.to_string(), - version: manifest_entry.and_then(|e| e.version.clone()), + version: match crate::subprocess_plugins::probe_plugin_info(&path) { + Ok(info) => info.map(|info| info.version), + Err(e) => { + eprintln!("Warning: {e}"); + None + } + }, source: manifest_entry.map(|e| e.source.clone()), - location: PluginLocation::Installed, + location: if self.scope == InstallScope::Local { + PluginLocation::ProjectLocal + } else { + PluginLocation::Installed + }, installed: manifest_entry.map(|e| e.installed.clone()), }); } @@ -2019,8 +2020,9 @@ mod tests { assert!(plugins.is_empty()); } + #[cfg(unix)] #[test] - fn test_list_plugins_detailed_with_manifest() { + fn test_list_plugins_detailed_uses_binary_version_and_manifest_provenance() { let dir = tempfile::tempdir().unwrap(); let installer = PluginInstaller { plugins_dir: dir.path().to_path_buf(), @@ -2030,7 +2032,13 @@ mod tests { // Create plugin file std::fs::create_dir_all(dir.path()).unwrap(); - std::fs::write(dir.path().join("meta-test"), b"fake plugin").unwrap(); + let plugin_path = dir.path().join("meta-test"); + std::fs::write( + &plugin_path, + b"#!/bin/sh\necho '{\"name\":\"test\",\"version\":\"2.0.0\",\"commands\":[]}'\n", + ) + .unwrap(); + make_executable(&plugin_path).unwrap(); // Create manifest let mut manifest = PluginManifest::default(); @@ -2049,14 +2057,14 @@ mod tests { let plugins = installer.list_plugins_detailed().unwrap(); assert_eq!(plugins.len(), 1); assert_eq!(plugins[0].name, "meta-test"); - assert_eq!(plugins[0].version.as_deref(), Some("v1.0.0")); + assert_eq!(plugins[0].version.as_deref(), Some("2.0.0")); assert_eq!(plugins[0].source.as_deref(), Some("test-user/meta-test")); } // === M4: Project-local plugin installation tests === #[test] - fn test_find_workspace_root_with_meta_directory() { + fn test_find_workspace_root_rejects_bare_meta_directory() { let temp = tempfile::tempdir().unwrap(); let meta_dir = temp.path().join(".meta"); std::fs::create_dir(&meta_dir).unwrap(); @@ -2065,19 +2073,15 @@ mod tests { let subdir = temp.path().join("sub").join("dir"); std::fs::create_dir_all(&subdir).unwrap(); - // Test from subdirectory - should walk up and find .meta/ let result = PluginInstaller::find_workspace_root_from(&subdir); - - assert!(result.is_ok()); - // Canonicalize paths for comparison (handles /var vs /private/var on macOS) - assert_eq!( - result.unwrap().canonicalize().unwrap(), - temp.path().canonicalize().unwrap() - ); + assert!(result + .unwrap_err() + .to_string() + .contains("Not in a meta workspace")); } #[test] - fn test_find_workspace_root_with_legacy_yaml() { + fn test_find_workspace_root_with_yaml() { let temp = tempfile::tempdir().unwrap(); std::fs::write(temp.path().join(".meta.yaml"), "projects: {}").unwrap(); @@ -2092,7 +2096,7 @@ mod tests { } #[test] - fn test_find_workspace_root_with_legacy_json() { + fn test_find_workspace_root_with_legacy_meta_file() { let temp = tempfile::tempdir().unwrap(); std::fs::write(temp.path().join(".meta"), r#"{"projects":{}}"#).unwrap(); @@ -2110,7 +2114,8 @@ mod tests { fn test_find_workspace_root_fails_outside_workspace() { let temp = tempfile::tempdir().unwrap(); - let result = PluginInstaller::find_workspace_root_from(temp.path()); + let result = + PluginInstaller::find_workspace_root_from(temp.path().ancestors().last().unwrap()); assert!(result.is_err()); let err_msg = result.unwrap_err().to_string(); @@ -2119,10 +2124,10 @@ mod tests { } #[test] - fn test_find_workspace_root_prefers_meta_dir_over_legacy() { + fn test_find_workspace_root_with_config_and_meta_directory() { let temp = tempfile::tempdir().unwrap(); - // Create both .meta/ directory and legacy .meta.yaml + // A config file establishes a workspace alongside its .meta/ directory. let meta_dir = temp.path().join(".meta"); std::fs::create_dir(&meta_dir).unwrap(); std::fs::write(temp.path().join(".meta.yaml"), "projects: {}").unwrap(); @@ -2144,6 +2149,8 @@ mod tests { let meta_dir = temp.path().join(".meta"); std::fs::create_dir(&meta_dir).unwrap(); + std::fs::write(temp.path().join(".meta.yaml"), "projects: {}").unwrap(); + // Create plugins dir so we can canonicalize it let plugins_dir = temp.path().join(LOCAL_PLUGINS_DIR); std::fs::create_dir_all(&plugins_dir).unwrap(); @@ -2164,7 +2171,8 @@ mod tests { fn test_new_local_fails_outside_workspace() { let temp = tempfile::tempdir().unwrap(); - let result = PluginInstaller::new_local_from(temp.path(), false); + let result = + PluginInstaller::new_local_from(temp.path().ancestors().last().unwrap(), false); assert!(result.is_err()); assert!(result @@ -2173,6 +2181,19 @@ mod tests { .contains("Not in a meta workspace")); } + #[test] + fn local_plugins_gitignore_is_created_and_existing_file_is_kept() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join(".meta.yaml"), "projects: {}").unwrap(); + let installer = PluginInstaller::new_local_from(temp.path(), false).unwrap(); + installer.ensure_plugins_dir().unwrap(); + let path = installer.plugins_dir.join(".gitignore"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "*\n"); + std::fs::write(&path, "custom\n").unwrap(); + installer.ensure_plugins_dir().unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "custom\n"); + } + #[test] fn test_constants_defined() { // Verify constants are accessible and have expected values diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 3472536..30575a9 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -6,8 +6,10 @@ use anyhow::{Context, Result}; use meta_core::display::{escape, escape_path}; use std::collections::HashMap; +use std::io::Read; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; #[allow(unused_imports)] pub use meta_plugin_protocol::{ @@ -15,6 +17,88 @@ pub use meta_plugin_protocol::{ PluginRequest, PluginRequestOptions, }; +/// Query metadata with one deadline for both process exit and stdout EOF. +pub(crate) fn probe_plugin_info(path: &Path) -> Result> { + let deadline = Instant::now() + Duration::from_secs(5); + let mut command = Command::new(path); + command + .arg("--meta-plugin-info") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + command.process_group(0); + } + let mut child = match command.spawn() { + Ok(child) => child, + Err(_) => return Ok(None), + }; + let Some(mut stdout) = child.stdout.take() else { + let _ = child.kill(); + let _ = child.wait(); + return Ok(None); + }; + let (sender, receiver) = std::sync::mpsc::channel(); + let reader = std::thread::spawn(move || { + let mut bytes = Vec::new(); + let result = stdout.read_to_end(&mut bytes).map(|_| bytes); + let _ = sender.send(result); + }); + let mut status = None; + let mut output = None; + loop { + if status.is_none() { + status = match child.try_wait() { + Ok(status) => status, + Err(_) => break, + }; + } + if output.is_none() { + match receiver.try_recv() { + Ok(result) => output = Some(result), + Err(std::sync::mpsc::TryRecvError::Empty) => {} + Err(std::sync::mpsc::TryRecvError::Disconnected) => break, + } + } + if let (Some(status), Some(output)) = (status.as_ref(), output.as_ref()) { + let _ = reader.join(); + return Ok(if status.success() { + output + .as_ref() + .ok() + .and_then(|bytes| serde_json::from_slice(bytes).ok()) + } else { + None + }); + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + break; + } + std::thread::sleep(remaining.min(Duration::from_millis(10))); + } + // A wrapper may already have exited while its descendants hold stdout open. + // Kill its process group even when try_wait has reaped the wrapper. + #[cfg(unix)] + if let Ok(pid) = i32::try_from(child.id()) { + // SAFETY: the child was started as leader of its own process group. + unsafe { + libc::kill(-pid, libc::SIGKILL); + } + } + let _ = child.kill(); + let _ = child.wait(); + if reader.is_finished() { + let _ = reader.join(); + } + anyhow::bail!( + "Plugin {} did not answer --meta-plugin-info within 5 seconds; skipping", + escape_path(path) + ) +} + /// A discovered subprocess plugin #[derive(Debug, Clone)] pub struct SubprocessPlugin { @@ -45,32 +129,27 @@ impl SubprocessPluginManager { /// Discover and load all subprocess plugins /// /// Discovery order (first match wins): - /// 1. `.meta/plugins/` directories walking up from cwd (project-local) - /// 2. `~/.meta/plugins/` (global installed) + /// 1. The nearest workspace's `.meta/plugins/` (project-local) + /// 2. `meta_core::meta_dir()/plugins/` (global installed) /// 3. PATH (bundled/system plugins) pub fn discover_plugins(&mut self, verbose: bool) -> Result<()> { self.verbose = verbose; let mut visited = std::collections::HashSet::new(); - // 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.is_dir() && visited.insert(resolved(&plugin_dir)) { + // Local plugins belong only to the nearest workspace, independently of --config. + let cwd = std::env::current_dir()?; + if let Some(root) = meta_core::config::find_workspace_root(&cwd)? { + let plugin_dir = root.join(".meta/plugins"); + if visited.insert(resolved(&plugin_dir)) { self.scan_directory(&plugin_dir)?; } - if let Some(parent) = current_dir.parent() { - current_dir = parent.to_path_buf(); - } else { - break; - } } // Search in ~/.meta/plugins/ (global installed). No home just means // no global plugins. if let Ok(meta_dir) = meta_core::meta_dir() { let global_plugins = meta_dir.join("plugins"); - if global_plugins.is_dir() && visited.insert(resolved(&global_plugins)) { + if visited.insert(resolved(&global_plugins)) { self.scan_directory(&global_plugins)?; } } @@ -87,14 +166,36 @@ impl SubprocessPluginManager { Ok(()) } - /// Scan a .meta-plugins directory for plugin executables + /// 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: {}", escape_path(dir)); } - for entry in std::fs::read_dir(dir)? { - let entry = entry?; + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => { + eprintln!( + "Warning: Cannot read plugins directory {}: {}; skipping", + escape_path(dir), + escape(&e.to_string()) + ); + return Ok(()); + } + }; + for entry in entries { + let entry = match entry { + Ok(entry) => entry, + Err(e) => { + eprintln!( + "Warning: Cannot read plugins directory {}: {}; skipping entry", + escape_path(dir), + escape(&e.to_string()) + ); + continue; + } + }; let path = entry.path(); // Look for executables named meta-* @@ -133,46 +234,29 @@ impl SubprocessPluginManager { return Ok(()); } - // Query plugin info - let output = Command::new(path) - .arg("--meta-plugin-info") - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .output(); - - match output { - Ok(output) if output.status.success() => { - // Try to parse as plugin info - silently skip if invalid JSON - // (e.g., meta-mcp is an MCP server, not a meta plugin) - let info: PluginInfo = match serde_json::from_slice(&output.stdout) { - Ok(info) => info, - Err(_) => return Ok(()), // Not a valid plugin, skip silently - }; - - if self.verbose { - println!( - " Found plugin: {} v{} ({})", - escape(&info.name), - escape(&info.version), - escape_path(path) - ); - } - - // Don't override if already loaded (first one wins) - if !self.plugins.contains_key(&info.name) { - self.plugins.insert( - info.name.clone(), - SubprocessPlugin { - path: path.to_path_buf(), - info, - }, - ); - } - } - _ => { - // Not a valid plugin, ignore silently + let info = match probe_plugin_info(path) { + Ok(Some(info)) => info, + Ok(None) => return Ok(()), + Err(e) => { + eprintln!("Warning: {e}"); + return Ok(()); } + }; + if self.verbose { + println!( + " Found plugin: {} v{} ({})", + escape(&info.name), + escape(&info.version), + escape_path(path) + ); } + // Don't override if already loaded (first one wins). + self.plugins + .entry(info.name.clone()) + .or_insert_with(|| SubprocessPlugin { + path: path.to_path_buf(), + info, + }); Ok(()) } diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs new file mode 100644 index 0000000..67484a9 --- /dev/null +++ b/tests/plugin_discovery.rs @@ -0,0 +1,405 @@ +//! Plugin scope and metadata probing must not break unrelated commands. +#![cfg(unix)] + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +struct Fixture { + _temp: tempfile::TempDir, + home: PathBuf, + cwd: PathBuf, + data: PathBuf, + bin: PathBuf, +} + +impl Fixture { + fn new(workspace: bool) -> Self { + let temp = tempfile::tempdir().unwrap(); + let home = temp.path().join("home"); + let cwd = home.join("workspace"); + let data = temp.path().join("data"); + let bin = temp.path().join("bin"); + for dir in [&cwd, &data, &bin] { + fs::create_dir_all(dir).unwrap(); + } + if workspace { + fs::write(cwd.join(".meta.yaml"), "projects: {}\n").unwrap(); + } + Self { + _temp: temp, + home, + cwd, + data, + bin, + } + } + + fn command(&self, args: &[&str]) -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_meta")); + cmd.args(args) + .current_dir(&self.cwd) + .env("HOME", &self.home) + .env("XDG_CONFIG_HOME", self.home.join("xdg")) + .env("XDG_DATA_HOME", self.home.join("xdg/data")) + .env("GIT_CONFIG_GLOBAL", self.home.join("gitconfig")) + .env("META_DATA_DIR", &self.data) + .env("PATH", format!("{}:/usr/bin:/bin", self.bin.display())); + cmd + } + + fn run(&self, args: &[&str]) -> Output { + self.command(args).output().unwrap() + } +} + +fn script(path: &Path, body: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, format!("#!/bin/sh\n{body}\n")).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); +} + +fn plugin(path: &Path, name: &str, version: &str) { + script( + path, + &format!( + "echo '{{\"name\":\"{name}\",\"version\":\"{version}\",\"commands\":[\"{name}\"]}}'" + ), + ); +} + +#[test] +fn bare_home_meta_directory_is_neither_workspace_nor_project_plugin_source() { + let f = Fixture::new(false); + plugin(&f.home.join(".meta/plugins/meta-fake"), "fake", "1.0"); + let help = f.run(&["--help"]); + assert!(help.status.success()); + assert!(!String::from_utf8_lossy(&help.stdout).contains("fake")); + for args in [ + vec!["plugin", "list", "--local"], + vec!["plugin", "install", "--local", "missing/repo"], + vec!["plugin", "uninstall", "--local", "missing"], + vec!["plugin", "update", "--local", "missing"], + ] { + let output = f.run(&args); + let text = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(text.contains("Not in a meta workspace"), "{args:?}: {text}"); + } +} + +#[test] +fn discovery_stops_at_nearest_workspace_and_uses_global_data_dir() { + let f = Fixture::new(true); + plugin(&f.home.join(".meta/plugins/meta-ancestor"), "ancestor", "1"); + plugin(&f.cwd.join(".meta/plugins/meta-local"), "local", "2"); + plugin(&f.data.join("plugins/meta-global"), "global", "3"); + plugin(&f.bin.join("meta-system"), "system", "4"); + // All three sources provide the same name: the local one wins. + plugin(&f.data.join("plugins/meta-local"), "local", "wrong-global"); + plugin(&f.bin.join("meta-local"), "local", "wrong-path"); + plugin(&f.bin.join("meta-global"), "global", "wrong-path"); + let output = f.run(&["plugin", "list", "--json"]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8_lossy(&output.stdout); + assert!(!text.contains("ancestor"), "{text}"); + assert!(!text.contains("wrong-"), "{text}"); + for name in ["local", "global", "system"] { + assert!(text.contains(name), "{text}"); + } +} + +#[test] +fn explicit_config_does_not_redirect_plugin_scope() { + let f = Fixture::new(true); + let other = f.home.join("other"); + fs::create_dir(&other).unwrap(); + fs::write(other.join(".meta.yaml"), "projects: {}").unwrap(); + plugin(&other.join(".meta/plugins/meta-foreign"), "foreign", "1"); + plugin(&f.cwd.join(".meta/plugins/meta-local"), "local", "2"); + let output = f.run(&[ + "--config", + other.join(".meta.yaml").to_str().unwrap(), + "plugin", + "list", + "--json", + ]); + assert!(output.status.success()); + let text = String::from_utf8_lossy(&output.stdout); + assert!(text.contains("local")); + assert!(!text.contains("foreign")); +} + +#[test] +fn local_list_from_subdirectory_uses_real_path_and_binary_version() { + let mut f = Fixture::new(true); + let plugin_path = f.cwd.join(".meta/plugins/meta-real"); + plugin(&plugin_path, "real", "2.5.0"); + fs::write(f.cwd.join(".meta/plugins/.manifest.json"), r#"{"plugins":{"meta-real":{"source":"example/repo","version":"stale","installed":"2024-01-01","platform":"test"}}}"#).unwrap(); + f.cwd = f.cwd.join("nested/deep"); + fs::create_dir_all(&f.cwd).unwrap(); + let output = f.run(&["plugin", "list", "--local"]); + assert!(output.status.success()); + let text = String::from_utf8_lossy(&output.stdout); + assert!(text.contains(plugin_path.to_str().unwrap()), "{text}"); + assert!(text.contains("2.5.0"), "{text}"); + assert!(!text.contains("stale"), "{text}"); +} + +#[test] +fn ambiguous_configs_and_explicit_config_errors_are_escaped() { + let f = Fixture::new(true); + fs::write(f.cwd.join(".meta.json"), "{}").unwrap(); + for args in [vec!["--help"], vec!["plugin", "list", "--local"]] { + let output = f.run(&args); + assert!(!output.status.success()); + let err = String::from_utf8_lossy(&output.stderr); + assert!(err.contains("Multiple meta config files"), "{err}"); + assert!( + err.contains(".meta.json") && err.contains(".meta.yaml"), + "{err}" + ); + } + fs::remove_file(f.cwd.join(".meta.json")).unwrap(); + let output = f.run(&["--config", "absent\u{1b}\nFORGED", "exec", "--", "true"]); + let err = String::from_utf8_lossy(&output.stderr); + assert!( + err.contains("Could not find meta config file 'absent\\u{1b}\\nFORGED'"), + "{err}" + ); + assert!(!err.contains('\u{1b}'), "{err}"); + fs::remove_file(f.cwd.join(".meta.yaml")).unwrap(); + let output = f.run(&["exec", "--", "true"]); + let err = String::from_utf8_lossy(&output.stderr); + assert!( + err.contains("'.meta / .meta.json / .meta.yaml / .meta.yml'"), + "{err}" + ); +} + +#[test] +fn local_install_gitignores_untracked_plugin_files() { + use std::io::{Read, Write}; + use std::net::TcpListener; + let f = Fixture::new(true); + let body = + b"#!/bin/sh\necho '{\"name\":\"installed\",\"version\":\"1.2.3\",\"commands\":[]}'\n"; + let mut archive = tar::Builder::new(flate2::write::GzEncoder::new( + Vec::new(), + flate2::Compression::default(), + )); + let mut header = tar::Header::new_gnu(); + header.set_path("meta-installed").unwrap(); + header.set_size(body.len() as u64); + header.set_mode(0o755); + header.set_cksum(); + archive.append(&header, body.as_slice()).unwrap(); + let bytes = archive.into_inner().unwrap().finish().unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/plugin.tar.gz", listener.local_addr().unwrap()); + listener.set_nonblocking(true).unwrap(); + let server = std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + match listener.accept() { + Ok((mut stream, _)) => { + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(2))) + .unwrap(); + let mut request = [0; 4096]; + assert!(stream.read(&mut request).unwrap() > 0); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + bytes.len() + ) + .unwrap(); + stream.write_all(&bytes).unwrap(); + return; + } + Err(e) + if e.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline => + { + std::thread::sleep(Duration::from_millis(10)); + } + Err(e) => panic!("download request did not arrive: {e}"), + } + } + }); + let output = f.run(&["plugin", "install", "--local", &url]); + server.join().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(f.cwd.join(".meta/plugins/meta-installed").is_file()); + assert_eq!( + fs::read_to_string(f.cwd.join(".meta/plugins/.gitignore")).unwrap(), + "*\n" + ); +} + +#[test] +fn orphan_hint_names_actual_parent_config() { + for name in [".meta.json", ".meta.yml"] { + let f = Fixture::new(true); + let parent_config = f.home.join(name); + fs::write( + &parent_config, + if name.ends_with("json") { + "{\"projects\":{}}" + } else { + "projects: {}" + }, + ) + .unwrap(); + let output = f.run(&["--help"]); + assert!(output.status.success()); + let err = String::from_utf8_lossy(&output.stderr); + assert!( + err.contains(&format!( + "To include it, add to {}:", + parent_config.display() + )), + "{err}" + ); + } +} + +#[test] +fn unreadable_plugin_directory_warns_and_help_still_runs() { + // Root can read mode-000 directories, so this case cannot be exercised there. + if unsafe { libc::geteuid() } == 0 { + return; + } + let f = Fixture::new(true); + let global_data = f.home.join("global\nFORGED\u{1b}"); + let global_plugins = global_data.join("plugins"); + fs::create_dir_all(&global_plugins).unwrap(); + fs::set_permissions(&global_plugins, fs::Permissions::from_mode(0o000)).unwrap(); + let output = f + .command(&["--help"]) + .env("META_DATA_DIR", &global_data) + .output() + .unwrap(); + fs::set_permissions(&global_plugins, fs::Permissions::from_mode(0o700)).unwrap(); + assert!(output.status.success()); + let err = String::from_utf8_lossy(&output.stderr); + assert!(err.contains("global\\nFORGED\\u{1b}/plugins"), "{err}"); + assert!(err.contains("Cannot read plugins directory"), "{err}"); + assert!(!err.contains('\u{1b}')); + // Also exercise the actual workspace plugins directory. + let path = f.cwd.join(".meta/plugins"); + fs::create_dir_all(&path).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o000)).unwrap(); + let output_local = f.run(&["--help"]); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + assert!(output.status.success()); + assert!(output_local.status.success()); + let err = String::from_utf8_lossy(&output_local.stderr); + assert!( + err.contains("Warning: Cannot read plugins directory"), + "{err}" + ); + assert!(err.contains(path.to_str().unwrap()), "{err}"); +} + +fn running(pid: i32) -> bool { + // On Linux an orphan may briefly be a zombie until init reaps it. + if let Ok(stat) = fs::read_to_string(format!("/proc/{pid}/stat")) { + return !stat.rsplit_once(") ").unwrap().1.starts_with('Z'); + } + unsafe { libc::kill(pid, 0) == 0 } +} + +fn timeout_case(background: bool) { + let f = Fixture::new(true); + let pidfile = f.cwd.join("pids"); + let path = f.cwd.join(".meta/plugins/meta-hung\nFORGED\u{1b}"); + let body = if background { + "echo $$ > pids\nsleep 60 &\necho $! >> pids\nexit 0" + } else { + "echo $$ > pids\nexec sleep 60" + }; + script(&path, body); + // Redirect to files so a regression cannot block this test on inherited pipes. + let stdout = fs::File::create(f.cwd.join("stdout")).unwrap(); + let stderr = fs::File::create(f.cwd.join("stderr")).unwrap(); + let started = Instant::now(); + let mut child = f + .command(&["--help"]) + .stdout(Stdio::from(stdout)) + .stderr(Stdio::from(stderr)) + .spawn() + .unwrap(); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break Some(status); + } + if started.elapsed() > Duration::from_secs(8) { + let _ = child.kill(); + let _ = child.wait(); + break None; + } + std::thread::sleep(Duration::from_millis(20)); + }; + let pids: Vec = fs::read_to_string(&pidfile) + .unwrap() + .lines() + .map(|s| s.parse().unwrap()) + .collect(); + let mut survivors = Vec::new(); + for pid in pids { + for _ in 0..50 { + if !running(pid) { + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + if running(pid) { + survivors.push(pid); + unsafe { + libc::kill(pid, libc::SIGKILL); + } + } + } + assert!( + status.is_some_and(|s| s.success()), + "command did not finish within deadline" + ); + assert!(started.elapsed() < Duration::from_secs(8)); + assert!( + survivors.is_empty(), + "plugin processes left running: {survivors:?}" + ); + let err = fs::read_to_string(f.cwd.join("stderr")).unwrap(); + assert!(err.contains("meta-hung\\nFORGED\\u{1b}"), "{err}"); + assert!( + err.contains("did not answer --meta-plugin-info within 5 seconds; skipping"), + "{err}" + ); + assert!(!err.contains('\u{1b}')); +} + +#[test] +fn sleeping_probe_times_out_and_reaps_plugin() { + timeout_case(false); +} + +#[test] +fn exited_wrapper_with_background_stdout_times_out_and_kills_descendant() { + timeout_case(true); +} From 44eecc04bd6b45078077ccd912193eb73ef91aa8 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 16:08:36 -0700 Subject: [PATCH 04/34] docs(skills): prune keeps to this workspace's sets [[tasks/harmony-2793]] --- .claude/skills/meta-worktree/SKILL.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index 8ffd832..01f7d0e 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -96,9 +96,10 @@ meta git worktree create ci-check --all --ephemeral --meta agent=review-bot --me meta git worktree exec --ephemeral lint-check --all -- make lint ``` -`prune` removes sets whose TTL has expired and sets it considers orphaned (none -of its repos are in the project any more); for a set whose directory is gone it -only forgets meta's record. `--ephemeral` alone only records metadata. A TTL is a backstop for a session that +`prune` removes sets whose TTL has expired and sets whose project directory is +gone; for a set whose directory is gone it only forgets meta's record. Once its +repos are taken out of the meta config, a set is no longer the workspace's: +remove it with `git worktree remove`. `--ephemeral` alone only records metadata. A TTL is a backstop for a session that dies before removing its sets. ## Inspecting Worktrees @@ -157,7 +158,7 @@ run it from the primary checkout to be sure it uses the primary repos. meta git worktree remove auth-fix # refuses a set with work it would lose meta git worktree remove auth-fix --force # discards that work meta git worktree prune --dry-run # preview -meta git worktree prune # remove expired (TTL) and orphaned sets +meta git worktree prune # remove expired (TTL) and orphaned sets of this workspace ``` `remove` and `prune` delete only sets meta created, and check every repo in the From 8f3d861b263625c8286aaccfb83010e66fc511f3 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 16:22:04 -0700 Subject: [PATCH 05/34] fix(plugins): nested meta repos share their workspace's plugins Plugin discovery reads .meta/plugins next to the nearest meta config and next to each parent config that lists it (one workspace), and no further. A legacy .meta config file means no project plugins, without a warning. workspace_root moves to meta_core so worktree scope and plugin scope share one definition; the nearest-config lookup is now nearest_meta_dir. [[tasks/harmony-2793]] --- .claude/skills/meta-plugins/SKILL.md | 9 +++++---- src/main.rs | 2 +- src/registry.rs | 2 +- src/subprocess_plugins.rs | 30 +++++++++++++++++++++------- tests/plugin_discovery.rs | 25 +++++++++++++++++++++++ 5 files changed, 55 insertions(+), 13 deletions(-) diff --git a/.claude/skills/meta-plugins/SKILL.md b/.claude/skills/meta-plugins/SKILL.md index f0182ff..2c2862f 100644 --- a/.claude/skills/meta-plugins/SKILL.md +++ b/.claude/skills/meta-plugins/SKILL.md @@ -55,9 +55,10 @@ meta --include api cargo clippy --all-targets -- -D warnings ## Plugin Discovery Plugins are discovered from: -1. `.meta/plugins/` at the workspace root (the nearest directory at or above - the current one that holds a meta config); `meta plugin install --local` - installs there +1. `.meta/plugins/` next to the nearest meta config, then next to each parent + meta config that lists it as a project (one workspace), nearest first; a + parent that doesn't list it is not read. `meta plugin install --local` + installs into the nearest one 2. `~/.meta/plugins/` (moved by `META_DATA_DIR`), where `meta plugin install` installs 3. Executables named `meta-*` in PATH @@ -83,7 +84,7 @@ meta plugin install # Uninstall meta plugin uninstall -# The same for this workspace only (.meta/plugins/ at the workspace root) +# The same for this meta repo only (.meta/plugins/ next to the nearest meta config) meta plugin install --local meta plugin list --local ``` diff --git a/src/main.rs b/src/main.rs index f629534..74f41d1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1160,7 +1160,7 @@ fn handle_plugin_command( } if local { let cwd = std::env::current_dir()?; - if config::find_workspace_root(&cwd)?.is_none() { + if config::nearest_meta_dir(&cwd)?.is_none() { if !json { println!("Not in a meta workspace"); } diff --git a/src/registry.rs b/src/registry.rs index b19132b..69c14f1 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -627,7 +627,7 @@ impl PluginInstaller { /// Find the nearest directory holding a config file (not a bare `.meta/`). fn find_workspace_root_from(start_dir: &Path) -> Result { - meta_core::config::find_workspace_root(start_dir)?.ok_or_else(|| anyhow::anyhow!( + meta_core::config::nearest_meta_dir(start_dir)?.ok_or_else(|| anyhow::anyhow!( "Not in a meta workspace.\nExpected to find a config file: {}.\nRun 'meta init' to create a new workspace, or cd to an existing workspace.", meta_core::config::META_CONFIG_NAMES.join(", ") )) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 30575a9..e0a6914 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -129,19 +129,27 @@ impl SubprocessPluginManager { /// Discover and load all subprocess plugins /// /// Discovery order (first match wins): - /// 1. The nearest workspace's `.meta/plugins/` (project-local) + /// 1. `.meta/plugins/` of each meta directory from the nearest one up to + /// its workspace's root (`meta_core::config::workspace_root`) /// 2. `meta_core::meta_dir()/plugins/` (global installed) /// 3. PATH (bundled/system plugins) pub fn discover_plugins(&mut self, verbose: bool) -> Result<()> { self.verbose = verbose; let mut visited = std::collections::HashSet::new(); - // Local plugins belong only to the nearest workspace, independently of --config. + // Project plugins: those of each meta directory from the nearest one + // up to its workspace's root, nearest first, independently of --config let cwd = std::env::current_dir()?; - if let Some(root) = meta_core::config::find_workspace_root(&cwd)? { - let plugin_dir = root.join(".meta/plugins"); - if visited.insert(resolved(&plugin_dir)) { - self.scan_directory(&plugin_dir)?; + if let Some(nearest) = meta_core::config::nearest_meta_dir(&cwd)? { + let root = meta_core::config::workspace_root(&nearest); + for dir in nearest.ancestors().take_while(|dir| dir.starts_with(&root)) { + if meta_core::config::find_meta_config_in(dir)?.is_none() { + continue; + } + let plugin_dir = dir.join(".meta/plugins"); + if visited.insert(resolved(&plugin_dir)) { + self.scan_directory(&plugin_dir)?; + } } } @@ -174,7 +182,15 @@ impl SubprocessPluginManager { let entries = match std::fs::read_dir(dir) { Ok(entries) => entries, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + // A legacy `.meta` config file in place of the `.meta/` folder means no plugins + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory + ) => + { + return Ok(()) + } Err(e) => { eprintln!( "Warning: Cannot read plugins directory {}: {}; skipping", diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs index 67484a9..c14a7b4 100644 --- a/tests/plugin_discovery.rs +++ b/tests/plugin_discovery.rs @@ -118,6 +118,22 @@ fn discovery_stops_at_nearest_workspace_and_uses_global_data_dir() { } } +#[test] +fn nested_meta_dir_reads_its_workspace_plugins_but_not_an_unlisting_parent() { + let f = Fixture::new(true); + plugin(&f.home.join(".meta/plugins/meta-parent"), "parent", "1"); + let listed = |yaml: &str| { + fs::write(f.home.join(".meta.yaml"), yaml).unwrap(); + let output = f.run(&["plugin", "list", "--json"]); + assert!(output.status.success()); + String::from_utf8_lossy(&output.stdout).contains("parent") + }; + // The parent lists this meta dir: one workspace, its plugins load here + assert!(listed("projects:\n workspace:\n repo: x\n meta: true\n")); + // A parent that doesn't list it is another workspace + assert!(!listed("projects: {}\n")); +} + #[test] fn explicit_config_does_not_redirect_plugin_scope() { let f = Fixture::new(true); @@ -279,6 +295,15 @@ fn orphan_hint_names_actual_parent_config() { } } +#[test] +fn legacy_meta_config_file_means_no_project_plugins_without_a_warning() { + let f = Fixture::new(false); + fs::write(f.cwd.join(".meta"), "{\"projects\": {}}\n").unwrap(); + let out = f.run(&["exec", "--", "true"]); + assert!(out.status.success()); + assert_eq!(String::from_utf8_lossy(&out.stderr), ""); +} + #[test] fn unreadable_plugin_directory_warns_and_help_still_runs() { // Root can read mode-000 directories, so this case cannot be exercised there. From f54a05b5601433d87a0acc2034ac95ae57b0b4c9 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Mon, 26 Oct 2026 23:23:46 +0000 Subject: [PATCH 06/34] style: auto-format code --- tests/plugin_discovery.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs index c14a7b4..ccc56b7 100644 --- a/tests/plugin_discovery.rs +++ b/tests/plugin_discovery.rs @@ -129,7 +129,9 @@ fn nested_meta_dir_reads_its_workspace_plugins_but_not_an_unlisting_parent() { String::from_utf8_lossy(&output.stdout).contains("parent") }; // The parent lists this meta dir: one workspace, its plugins load here - assert!(listed("projects:\n workspace:\n repo: x\n meta: true\n")); + assert!(listed( + "projects:\n workspace:\n repo: x\n meta: true\n" + )); // A parent that doesn't list it is another workspace assert!(!listed("projects: {}\n")); } From 3c45b92461a35081a4622449bfc783a405988bf6 Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 17:05:25 -0700 Subject: [PATCH 07/34] test: platform-independent paths in init and orphan-hint tests Windows joins with a backslash; macOS resolves /var to /private/var. [[tasks/harmony-2793]] --- src/init.rs | 2 +- tests/plugin_discovery.rs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/init.rs b/src/init.rs index 9ced2fc..c1ded26 100644 --- a/src/init.rs +++ b/src/init.rs @@ -846,7 +846,7 @@ mod tests { "keep this rule", ) .unwrap(); - let settings = dir.path().join(".claude/settings.json"); + let settings = dir.path().join(".claude").join("settings.json"); fs::write(&settings, content).unwrap(); let before = snapshot(dir.path()); for force in [false, true] { diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs index ccc56b7..d3aabab 100644 --- a/tests/plugin_discovery.rs +++ b/tests/plugin_discovery.rs @@ -287,6 +287,8 @@ fn orphan_hint_names_actual_parent_config() { let output = f.run(&["--help"]); assert!(output.status.success()); let err = String::from_utf8_lossy(&output.stderr); + // meta names the parent by its resolved path (/private/var on macOS) + let parent_config = f.home.canonicalize().unwrap().join(name); assert!( err.contains(&format!( "To include it, add to {}:", From abcfbe4d1196ab9a42d6f3a6156ab747cfe7178c Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 17:40:43 -0700 Subject: [PATCH 08/34] fix: review round 1 (plugin scope in sets, output EPIPE, init merge) Plugin discovery uses workspace_meta_dirs, so worktree sets see the workspace's plugins. Plugin output and help go through a fallible writer. plugin list --local fails outside a workspace, JSON too. The probe waits on stdout then exit, without a sleep loop. init compares hook groups by matcher and hooks (not timeout) and keeps settings.json's mode. The project list filter refusal moves to the project plugin. [[tasks/harmony-2793]] --- .claude/skills/meta-plugins/SKILL.md | 3 +- .claude/skills/meta-worktree/SKILL.md | 3 +- src/init.rs | 50 ++++++++++++++- src/main.rs | 19 +----- src/subprocess_plugins.rs | 89 +++++++++++++-------------- tests/plugin_discovery.rs | 2 + 6 files changed, 97 insertions(+), 69 deletions(-) diff --git a/.claude/skills/meta-plugins/SKILL.md b/.claude/skills/meta-plugins/SKILL.md index 2c2862f..126077e 100644 --- a/.claude/skills/meta-plugins/SKILL.md +++ b/.claude/skills/meta-plugins/SKILL.md @@ -57,7 +57,8 @@ meta --include api cargo clippy --all-targets -- -D warnings Plugins are discovered from: 1. `.meta/plugins/` next to the nearest meta config, then next to each parent meta config that lists it as a project (one workspace), nearest first; a - parent that doesn't list it is not read. `meta plugin install --local` + parent that doesn't list it is not read. Inside a worktree set, a checkout + counts as the main checkout it was made from. `meta plugin install --local` installs into the nearest one 2. `~/.meta/plugins/` (moved by `META_DATA_DIR`), where `meta plugin install` installs 3. Executables named `meta-*` in PATH diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index 01f7d0e..b15979b 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -167,7 +167,8 @@ no branch, and files outside every repo count as work. `remove` refuses such a set unless `--force`; `prune` keeps it. Both act only on sets of the current workspace: sets whose every worktree is recorded in one of the workspace's repositories. Another workspace's set is never touched, even when both share a -`META_WORKTREES` directory; `remove` refuses it and names its workspace. +`META_WORKTREES` directory; `remove` refuses it and names its workspace. Run +from inside a set, they act on the workspace the set was made from. `--force` and `exec --ephemeral` discard that work: commit and push first. ## Lifecycle Hooks diff --git a/src/init.rs b/src/init.rs index c1ded26..5efb736 100644 --- a/src/init.rs +++ b/src/init.rs @@ -681,6 +681,10 @@ fn write_settings_atomic(path: &Path, content: &str) -> Result<()> { ) })?; temp.write_all(content.as_bytes())?; + // The temporary file is private; keep the mode settings.json had + if let Ok(meta) = fs::metadata(path) { + temp.as_file().set_permissions(meta.permissions())?; + } temp.persist(path) .with_context(|| format!("Failed to write {}", escape_path(path)))?; Ok(()) @@ -694,12 +698,29 @@ fn installed_hooks(settings: &Value) -> Vec { groups .as_array()? .iter() - .all(|group| existing.contains(group)) + .all(|group| existing.iter().any(|found| same_group(found, group))) .then_some(key) }) .collect() } +/// Whether two hook groups run the same hooks for the same tool calls: the +/// same matcher and the same hook types, commands and prompts. Other fields, +/// such as a timeout the user changed, don't make a group another one. +fn same_group(a: &Value, b: &Value) -> bool { + type Hook<'a> = (Option<&'a Value>, Option<&'a Value>, Option<&'a Value>); + fn hooks(group: &Value) -> Option>> { + let hooks = group.get("hooks")?.as_array()?; + Some( + hooks + .iter() + .map(|h| (h.get("type"), h.get("command"), h.get("prompt"))) + .collect(), + ) + } + a.get("matcher") == b.get("matcher") && hooks(a) == hooks(b) +} + /// Build the meta hooks configuration as a JSON object fn build_meta_hooks() -> Map { let mut hooks = Map::new(); @@ -774,7 +795,7 @@ fn merge_hooks_into_settings( .ok_or_else(|| invalid(&format!("hooks.{key}"), "an array"))?; if let Some(groups) = groups.as_array() { for group in groups { - if !arr.contains(group) { + if !arr.iter().any(|found| same_group(found, group)) { arr.push(group.clone()); } } @@ -860,6 +881,31 @@ mod tests { } } + #[test] + fn a_changed_hook_timeout_is_still_metas_hook() { + let dir = tempdir().unwrap(); + let settings = dir.path().join("settings.json"); + let mut hooks = build_meta_hooks(); + hooks["SessionStart"][0]["hooks"][0]["timeout"] = json!(30); + fs::write(&settings, json!({ "hooks": hooks }).to_string()).unwrap(); + let plan = prepare_settings(&settings).unwrap(); + assert!(plan.content.is_none(), "{}", plan.message); + } + + #[cfg(unix)] + #[test] + fn merged_settings_keep_their_file_mode() { + use std::os::unix::fs::PermissionsExt; + let dir = tempdir().unwrap(); + let settings = dir.path().join("settings.json"); + fs::write(&settings, r#"{"theme":"dark"}"#).unwrap(); + fs::set_permissions(&settings, fs::Permissions::from_mode(0o644)).unwrap(); + let plan = prepare_settings(&settings).unwrap(); + write_settings_atomic(&settings, &plan.content.unwrap()).unwrap(); + let mode = fs::metadata(&settings).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o644); + } + #[test] fn settings_plan_compares_matchers_and_reports_no_write() { let dir = tempdir().unwrap(); diff --git a/src/main.rs b/src/main.rs index 74f41d1..e509a1e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -607,7 +607,7 @@ fn run_cli() -> Result<()> { if is_root_help || (is_bare && !is_promoted) { if let Some(help_text) = subprocess_plugins.get_plugin_help(first) { - println!("{help_text}"); + subprocess_plugins::print_output(&format!("{help_text}\n"))?; return Ok(()); } } @@ -685,16 +685,6 @@ fn handle_command_dispatch( defaults.parallel }; - if !is_explicit_exec - && command_args.first().is_some_and(|s| s == "project") - && command_args - .get(1) - .is_some_and(|s| s == "list" || s == "ls") - && (cli.include.is_some() || cli.exclude.is_some()) - { - anyhow::bail!("meta project list does not take --include/--exclude"); - } - let command_str = loop_lib::display_command(&command_args); // Check if this is `git clone` - it doesn't require a .meta file because @@ -1159,13 +1149,6 @@ fn handle_plugin_command( return Ok(()); } if local { - let cwd = std::env::current_dir()?; - if config::nearest_meta_dir(&cwd)?.is_none() { - if !json { - println!("Not in a meta workspace"); - } - return Ok(()); - } let installer = PluginInstaller::new_local(verbose)?; let plugins = installer.list_plugins_detailed()?; if json { diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index e0a6914..dde038c 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -41,46 +41,35 @@ pub(crate) fn probe_plugin_info(path: &Path) -> Result> { return Ok(None); }; let (sender, receiver) = std::sync::mpsc::channel(); - let reader = std::thread::spawn(move || { + std::thread::spawn(move || { let mut bytes = Vec::new(); - let result = stdout.read_to_end(&mut bytes).map(|_| bytes); - let _ = sender.send(result); + let _ = sender.send(stdout.read_to_end(&mut bytes).map(|_| bytes)); }); - let mut status = None; - let mut output = None; - loop { - if status.is_none() { - status = match child.try_wait() { - Ok(status) => status, - Err(_) => break, - }; - } - if output.is_none() { - match receiver.try_recv() { - Ok(result) => output = Some(result), - Err(std::sync::mpsc::TryRecvError::Empty) => {} - Err(std::sync::mpsc::TryRecvError::Disconnected) => break, + // stdout ends once the plugin, and anything it started that holds it, is done + let remaining = deadline.saturating_duration_since(Instant::now()); + if let Ok(output) = receiver.recv_timeout(remaining) { + loop { + match child.try_wait() { + Ok(Some(status)) => { + return Ok(output + .ok() + .filter(|_| status.success()) + .and_then(|bytes| serde_json::from_slice(&bytes).ok())) + } + Ok(None) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(1)) + } + Ok(None) => break, + Err(e) => { + return Err(e).with_context(|| { + format!("Cannot wait for plugin {}; skipping", escape_path(path)) + }) + } } } - if let (Some(status), Some(output)) = (status.as_ref(), output.as_ref()) { - let _ = reader.join(); - return Ok(if status.success() { - output - .as_ref() - .ok() - .and_then(|bytes| serde_json::from_slice(bytes).ok()) - } else { - None - }); - } - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - break; - } - std::thread::sleep(remaining.min(Duration::from_millis(10))); } // A wrapper may already have exited while its descendants hold stdout open. - // Kill its process group even when try_wait has reaped the wrapper. + // Kill its process group even when the wrapper itself has exited. #[cfg(unix)] if let Ok(pid) = i32::try_from(child.id()) { // SAFETY: the child was started as leader of its own process group. @@ -88,17 +77,27 @@ pub(crate) fn probe_plugin_info(path: &Path) -> Result> { libc::kill(-pid, libc::SIGKILL); } } + // Elsewhere only the plugin itself is killed: a process it started that + // still holds stdout outlives it, but meta doesn't wait for that reader let _ = child.kill(); let _ = child.wait(); - if reader.is_finished() { - let _ = reader.join(); - } anyhow::bail!( "Plugin {} did not answer --meta-plugin-info within 5 seconds; skipping", escape_path(path) ) } +/// Print a plugin's output. A closed stdout (`meta ... | head`) ends meta +/// quietly, as it does for command output. +pub(crate) fn print_output(text: &str) -> Result<()> { + use std::io::Write; + std::io::stdout() + .lock() + .write_all(text.as_bytes()) + .map_err(loop_lib::StdoutError)?; + Ok(()) +} + /// A discovered subprocess plugin #[derive(Debug, Clone)] pub struct SubprocessPlugin { @@ -129,8 +128,8 @@ impl SubprocessPluginManager { /// Discover and load all subprocess plugins /// /// Discovery order (first match wins): - /// 1. `.meta/plugins/` of each meta directory from the nearest one up to - /// its workspace's root (`meta_core::config::workspace_root`) + /// 1. `.meta/plugins/` of each of the workspace's meta directories, from + /// the nearest one up (`meta_core::config::workspace_meta_dirs`) /// 2. `meta_core::meta_dir()/plugins/` (global installed) /// 3. PATH (bundled/system plugins) pub fn discover_plugins(&mut self, verbose: bool) -> Result<()> { @@ -141,11 +140,7 @@ impl SubprocessPluginManager { // up to its workspace's root, nearest first, independently of --config let cwd = std::env::current_dir()?; if let Some(nearest) = meta_core::config::nearest_meta_dir(&cwd)? { - let root = meta_core::config::workspace_root(&nearest); - for dir in nearest.ancestors().take_while(|dir| dir.starts_with(&root)) { - if meta_core::config::find_meta_config_in(dir)?.is_none() { - continue; - } + for dir in meta_core::config::workspace_meta_dirs(&nearest) { let plugin_dir = dir.join(".meta/plugins"); if visited.insert(resolved(&plugin_dir)) { self.scan_directory(&plugin_dir)?; @@ -377,7 +372,7 @@ impl SubprocessPluginManager { // 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)); + let _ = std::io::Write::write_all(&mut std::io::stdout(), &output.stdout); std::process::exit(output.status.code().unwrap_or(1)); } @@ -391,7 +386,7 @@ impl SubprocessPluginManager { // If stdout doesn't look like JSON, print it (legacy plugin output) if !stdout_str.trim().starts_with('{') { - print!("{stdout_str}"); + print_output(&stdout_str)?; return Ok(true); } @@ -411,7 +406,7 @@ impl SubprocessPluginManager { ), Err(_) => { // Not a plan - print output as-is - print!("{stdout_str}"); + print_output(&stdout_str)?; Ok(true) } } diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs index d3aabab..72022ed 100644 --- a/tests/plugin_discovery.rs +++ b/tests/plugin_discovery.rs @@ -79,6 +79,7 @@ fn bare_home_meta_directory_is_neither_workspace_nor_project_plugin_source() { assert!(!String::from_utf8_lossy(&help.stdout).contains("fake")); for args in [ vec!["plugin", "list", "--local"], + vec!["plugin", "list", "--local", "--json"], vec!["plugin", "install", "--local", "missing/repo"], vec!["plugin", "uninstall", "--local", "missing"], vec!["plugin", "update", "--local", "missing"], @@ -89,6 +90,7 @@ fn bare_home_meta_directory_is_neither_workspace_nor_project_plugin_source() { String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr) ); + assert!(!output.status.success(), "{args:?}"); assert!(text.contains("Not in a meta workspace"), "{args:?}: {text}"); } } From b4f580d541cbdb7e848c97a98020af9af26e524f Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 18:14:15 -0700 Subject: [PATCH 09/34] fix(cli): escape argument errors; discover a set checkout's own plugins meta_cli::args renders clap errors from the escaped arguments, for the host and the worktree plugin. [[tasks/harmony-2793]] --- .claude/skills/meta-plugins/SKILL.md | 5 ++-- src/args.rs | 36 ++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 2 +- tests/plugin_discovery.rs | 27 +++++++++++++++++++++ 5 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 src/args.rs diff --git a/.claude/skills/meta-plugins/SKILL.md b/.claude/skills/meta-plugins/SKILL.md index 126077e..704a49e 100644 --- a/.claude/skills/meta-plugins/SKILL.md +++ b/.claude/skills/meta-plugins/SKILL.md @@ -57,8 +57,9 @@ meta --include api cargo clippy --all-targets -- -D warnings Plugins are discovered from: 1. `.meta/plugins/` next to the nearest meta config, then next to each parent meta config that lists it as a project (one workspace), nearest first; a - parent that doesn't list it is not read. Inside a worktree set, a checkout - counts as the main checkout it was made from. `meta plugin install --local` + parent that doesn't list it is not read. Inside a worktree set, a checkout's + own plugins come first, then those of the main checkout it was made from + and its workspace. `meta plugin install --local` installs into the nearest one 2. `~/.meta/plugins/` (moved by `META_DATA_DIR`), where `meta plugin install` installs 3. Executables named `meta-*` in PATH diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..5da5676 --- /dev/null +++ b/src/args.rs @@ -0,0 +1,36 @@ +//! Command-line errors that never echo control characters. + +use meta_core::display::escape; +use std::ffi::OsStr; + +/// The error to show for `args` that `P` rejected. Clap quotes rejected +/// values as given, so the error comes from parsing the escaped arguments: +/// the same error, with values that can't move the cursor or forge a line. +/// If the escaped arguments parse, a plain error stands in. +pub fn escaped_error( + args: impl IntoIterator>, +) -> clap::Error { + let shown = args + .into_iter() + .map(|arg| escape(&arg.as_ref().to_string_lossy()).into_owned()) + .collect::>(); + match P::try_parse_from(shown) { + Err(e) => e, + Ok(_) => P::command().error( + clap::error::ErrorKind::InvalidValue, + "an argument contains a control character", + ), + } +} + +/// Parse `P` from this process's arguments, exiting on an error with +/// [`escaped_error`] (help and version print as usual). +pub fn parse() -> P { + use clap::error::ErrorKind; + P::try_parse().unwrap_or_else(|e| match e.kind() { + ErrorKind::DisplayHelp + | ErrorKind::DisplayVersion + | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand => e.exit(), + _ => escaped_error::

(std::env::args_os()).exit(), + }) +} diff --git a/src/lib.rs b/src/lib.rs index 7889f5a..23819db 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +pub mod args; pub mod config; pub use meta_core::display; pub mod context; diff --git a/src/main.rs b/src/main.rs index e509a1e..1921118 100644 --- a/src/main.rs +++ b/src/main.rs @@ -497,7 +497,7 @@ fn run_cli() -> Result<()> { }) .init(); - let mut cli = Cli::parse(); + let mut cli: Cli = meta_cli::args::parse(); log::debug!("cli.json = {}", cli.json); diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs index 72022ed..1f38667 100644 --- a/tests/plugin_discovery.rs +++ b/tests/plugin_discovery.rs @@ -138,6 +138,33 @@ fn nested_meta_dir_reads_its_workspace_plugins_but_not_an_unlisting_parent() { assert!(!listed("projects: {}\n")); } +#[test] +fn a_worktree_set_checkout_reads_its_own_and_its_main_checkouts_plugins() { + let f = Fixture::new(true); + // A set's root checkout, laid out as git and meta leave it + let admin = f.cwd.join(".git/worktrees/s1"); + fs::create_dir_all(&admin).unwrap(); + fs::write(admin.join("commondir"), "../..\n").unwrap(); + fs::write(admin.join("meta-worktree.json"), "{}").unwrap(); + let set = f.cwd.join(".worktrees/s1"); + fs::create_dir_all(&set).unwrap(); + fs::write(set.join(".meta.yaml"), "projects: {}\n").unwrap(); + fs::write(set.join(".git"), format!("gitdir: {}\n", admin.display())).unwrap(); + plugin(&f.cwd.join(".meta/plugins/meta-main"), "main", "1"); + plugin(&set.join(".meta/plugins/meta-setlocal"), "setlocal", "1"); + let output = f + .command(&["plugin", "list", "--json"]) + .current_dir(&set) + .output() + .unwrap(); + assert!(output.status.success()); + let text = String::from_utf8_lossy(&output.stdout); + assert!( + text.contains("setlocal") && text.contains("\"main\""), + "{text}" + ); +} + #[test] fn explicit_config_does_not_redirect_plugin_scope() { let f = Fixture::new(true); From 2381680932e0bfce942c7d4c917156d109f307de Mon Sep 17 00:00:00 2001 From: gsc Date: Mon, 26 Oct 2026 18:44:47 -0700 Subject: [PATCH 10/34] fix(cli): review round 3 (plugins with an unusable config, init text) An unusable config skips project plugins with a warning, so --help still prints. A new settings.json follows the umask. The "already linked" lines show only with --verbose. The not-in-a-workspace hint no longer points at meta init. [[tasks/harmony-2793]] --- .claude/skills/meta-safety/SKILL.md | 2 +- .claude/skills/meta-worktree/SKILL.md | 3 ++- src/init.rs | 14 ++++++++++---- src/registry.rs | 4 ++-- src/subprocess_plugins.rs | 11 ++++++++++- tests/plugin_discovery.rs | 13 +++++++++---- 6 files changed, 34 insertions(+), 13 deletions(-) diff --git a/.claude/skills/meta-safety/SKILL.md b/.claude/skills/meta-safety/SKILL.md index e873d63..51c03b7 100644 --- a/.claude/skills/meta-safety/SKILL.md +++ b/.claude/skills/meta-safety/SKILL.md @@ -78,7 +78,7 @@ meta --strict git worktree prune - The root repo skipped because a commit-ish is missing there (worktree create) - Invalid `--meta` format values (worktree create) - Failed directory removal (worktree prune) -- Worktree sets prune can't check or whose records it can't read (worktree prune) +- Any set prune keeps: one holding work, a worktree meta has no record of, a worktree from another workspace, or a record it can't read (worktree prune) **When to use --strict:** - CI pipelines testing a specific release tag across all repos diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index b15979b..dff6f86 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -28,7 +28,8 @@ primary checkout. Create one set per task, with only the repos it touches, and remove it once the work is pushed. Before a session ends, remove every set it created. Run `meta git worktree` commands from the primary checkout: inside a set they look -for sets under that set (only `list` understands the current set). +for sets under that set (only `list`, `remove` and `prune` understand the +current set). ## Creating Worktrees diff --git a/src/init.rs b/src/init.rs index 5efb736..ef50ece 100644 --- a/src/init.rs +++ b/src/init.rs @@ -499,7 +499,9 @@ fn install_skills_with( match skill_entry(&link, &target, &marker, legacy) { SkillEntry::Missing => {} SkillEntry::Linked => { - println!("Skipped {} (already linked)", escape_path(&link)); + if verbose { + println!("Skipped {} (already linked)", escape_path(&link)); + } continue; } SkillEntry::Owned if overwrite => remove_owned(&link, &marker)?, @@ -673,6 +675,11 @@ fn prepare_settings(path: &Path) -> Result { fn write_settings_atomic(path: &Path, content: &str) -> Result<()> { use std::io::Write; + // A new file has nothing to lose, and gets the umask's mode + if !path.exists() { + return fs::write(path, content) + .with_context(|| format!("Failed to write {}", escape_path(path))); + } let parent = path.parent().context("Settings path has no parent")?; let mut temp = tempfile::NamedTempFile::new_in(parent).with_context(|| { format!( @@ -682,9 +689,8 @@ fn write_settings_atomic(path: &Path, content: &str) -> Result<()> { })?; temp.write_all(content.as_bytes())?; // The temporary file is private; keep the mode settings.json had - if let Ok(meta) = fs::metadata(path) { - temp.as_file().set_permissions(meta.permissions())?; - } + temp.as_file() + .set_permissions(fs::metadata(path)?.permissions())?; temp.persist(path) .with_context(|| format!("Failed to write {}", escape_path(path)))?; Ok(()) diff --git a/src/registry.rs b/src/registry.rs index 69c14f1..4afbe9a 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -628,7 +628,7 @@ impl PluginInstaller { /// Find the nearest directory holding a config file (not a bare `.meta/`). fn find_workspace_root_from(start_dir: &Path) -> Result { meta_core::config::nearest_meta_dir(start_dir)?.ok_or_else(|| anyhow::anyhow!( - "Not in a meta workspace.\nExpected to find a config file: {}.\nRun 'meta init' to create a new workspace, or cd to an existing workspace.", + "Not in a meta workspace.\nExpected to find a config file: {}.\nCreate one here (e.g. .meta.yaml), or cd into a workspace.", meta_core::config::META_CONFIG_NAMES.join(", ") )) } @@ -2120,7 +2120,7 @@ mod tests { assert!(result.is_err()); let err_msg = result.unwrap_err().to_string(); assert!(err_msg.contains("Not in a meta workspace")); - assert!(err_msg.contains("meta init")); + assert!(err_msg.contains("Create one here")); } #[test] diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index dde038c..720e53e 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -139,7 +139,16 @@ impl SubprocessPluginManager { // Project plugins: those of each meta directory from the nearest one // up to its workspace's root, nearest first, independently of --config let cwd = std::env::current_dir()?; - if let Some(nearest) = meta_core::config::nearest_meta_dir(&cwd)? { + // A config meta can't use leaves no project plugins; the command + // itself reports it, and `--help` still prints + let nearest = meta_core::config::nearest_meta_dir(&cwd).unwrap_or_else(|e| { + eprintln!( + "Warning: {}; skipping project plugins", + escape(&format!("{e:#}")) + ); + None + }); + if let Some(nearest) = nearest { for dir in meta_core::config::workspace_meta_dirs(&nearest) { let plugin_dir = dir.join(".meta/plugins"); if visited.insert(resolved(&plugin_dir)) { diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs index 1f38667..8e5beba 100644 --- a/tests/plugin_discovery.rs +++ b/tests/plugin_discovery.rs @@ -139,13 +139,14 @@ fn nested_meta_dir_reads_its_workspace_plugins_but_not_an_unlisting_parent() { } #[test] -fn a_worktree_set_checkout_reads_its_own_and_its_main_checkouts_plugins() { +fn a_worktree_set_checkout_reads_its_own_and_its_origins_plugins() { let f = Fixture::new(true); // A set's root checkout, laid out as git and meta leave it let admin = f.cwd.join(".git/worktrees/s1"); fs::create_dir_all(&admin).unwrap(); fs::write(admin.join("commondir"), "../..\n").unwrap(); - fs::write(admin.join("meta-worktree.json"), "{}").unwrap(); + let record = format!("{{\"project\": {:?}}}", f.cwd.display().to_string()); + fs::write(admin.join("meta-worktree.json"), record).unwrap(); let set = f.cwd.join(".worktrees/s1"); fs::create_dir_all(&set).unwrap(); fs::write(set.join(".meta.yaml"), "projects: {}\n").unwrap(); @@ -206,9 +207,13 @@ fn local_list_from_subdirectory_uses_real_path_and_binary_version() { fn ambiguous_configs_and_explicit_config_errors_are_escaped() { let f = Fixture::new(true); fs::write(f.cwd.join(".meta.json"), "{}").unwrap(); - for args in [vec!["--help"], vec!["plugin", "list", "--local"]] { + // Help still prints, with a warning; a command that needs the config fails + for (args, works) in [ + (vec!["--help"], true), + (vec!["plugin", "list", "--local"], false), + ] { let output = f.run(&args); - assert!(!output.status.success()); + assert_eq!(output.status.success(), works, "{args:?}"); let err = String::from_utf8_lossy(&output.stderr); assert!(err.contains("Multiple meta config files"), "{err}"); assert!( From 0549fb3ee90b9cbe65d19716c75ba316cde693f4 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 13:24:38 -0700 Subject: [PATCH 11/34] fix(cli): a closed stdout exits 141, not 0 As a shell reports a command a closed pipe stopped, so a failure it cut off isn't reported as success. [[tasks/harmony-2793]] --- src/main.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 1921118..1b163c7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -468,7 +468,9 @@ fn main() -> std::process::ExitCode { if e.downcast_ref::() .is_some_and(|e| e.0.kind() == std::io::ErrorKind::BrokenPipe) => { - std::process::ExitCode::SUCCESS + // As a shell reports a command a closed pipe stopped (128 + SIGPIPE), + // so a failure it hid isn't reported as success + std::process::ExitCode::from(141) } Err(e) => { // as Rust prints an error returned from main, but escaped: it can From 4a1b9b3eb8fc5b82de1208980b29ac05abfaa1e4 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 13:52:53 -0700 Subject: [PATCH 12/34] fix(cli): any print to a closed stdout exits 141 quietly A panic hook turns std's broken-pipe print panic into the same quiet exit as fallible writes, for every built-in command. [[tasks/harmony-2793]] --- src/main.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1b163c7..8e48b0f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -461,16 +461,41 @@ fn print_plugin_update_help() { // === Main Entry Point === +/// Exit status for output cut off by a closed stdout, as a shell reports a +/// command SIGPIPE stopped (128 + 13): a failure it hid isn't success. +const CLOSED_STDOUT: u8 = 141; + +/// `println!` panics when stdout is a closed pipe (`meta … | head`). End +/// quietly instead, as a fallible write to stdout does; other panics are +/// reported as usual. +fn exit_quietly_on_closed_stdout() { + let report = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let payload = info.payload(); + let message = payload + .downcast_ref::() + .map(String::as_str) + .or_else(|| payload.downcast_ref::<&str>().copied()) + .unwrap_or(""); + // std's wording; "os error 232" is Windows' closed pipe + if message.starts_with("failed printing to stdout") + && (message.contains("Broken pipe") || message.contains("os error 232")) + { + std::process::exit(CLOSED_STDOUT.into()); + } + report(info) + })); +} + fn main() -> std::process::ExitCode { + exit_quietly_on_closed_stdout(); match run_cli() { Ok(()) => std::process::ExitCode::SUCCESS, Err(e) if e.downcast_ref::() .is_some_and(|e| e.0.kind() == std::io::ErrorKind::BrokenPipe) => { - // As a shell reports a command a closed pipe stopped (128 + SIGPIPE), - // so a failure it hid isn't reported as success - std::process::ExitCode::from(141) + std::process::ExitCode::from(CLOSED_STDOUT) } Err(e) => { // as Rust prints an error returned from main, but escaped: it can From 188b9f0eafd72c0abdf95ec0476f8d4046e62140 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 14:24:17 -0700 Subject: [PATCH 13/34] fix(cli): review round 6 (escaping, init wording, test isolation) Plugin names in install/uninstall errors and the verbose command echo are escaped. A user's own file at a skill name says it isn't meta's. Discovery tests use canonical temp paths; HOME-faking tests also set XDG_CONFIG_HOME and GIT_CONFIG_GLOBAL. [[tasks/harmony-2793]] --- .claude/skills/meta-plugins/SKILL.md | 4 ++-- .claude/skills/meta-worktree/SKILL.md | 15 +++++++-------- src/init.rs | 9 +++++++-- src/main.rs | 4 ++-- src/registry.rs | 10 +++++----- tests/plugin_discovery.rs | 16 +++++++++++----- tests/plugin_git.rs | 2 ++ tests/plugin_routing.rs | 2 ++ 8 files changed, 38 insertions(+), 24 deletions(-) diff --git a/.claude/skills/meta-plugins/SKILL.md b/.claude/skills/meta-plugins/SKILL.md index 704a49e..dec16fe 100644 --- a/.claude/skills/meta-plugins/SKILL.md +++ b/.claude/skills/meta-plugins/SKILL.md @@ -58,8 +58,8 @@ Plugins are discovered from: 1. `.meta/plugins/` next to the nearest meta config, then next to each parent meta config that lists it as a project (one workspace), nearest first; a parent that doesn't list it is not read. Inside a worktree set, a checkout's - own plugins come first, then those of the main checkout it was made from - and its workspace. `meta plugin install --local` + own plugins come first, then those of the checkout it stands for (the one + it was made from) and its workspace. `meta plugin install --local` installs into the nearest one 2. `~/.meta/plugins/` (moved by `META_DATA_DIR`), where `meta plugin install` installs 3. Executables named `meta-*` in PATH diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index dff6f86..d672ef6 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -26,10 +26,9 @@ Read-only work (reading code, searching, answering questions) may stay in the primary checkout. Create one set per task, with only the repos it touches, and remove it once the -work is pushed. Before a session ends, remove every set it created. Run -`meta git worktree` commands from the primary checkout: inside a set they look -for sets under that set (only `list`, `remove` and `prune` understand the -current set). +work is pushed. Before a session ends, remove every set it created. Inside a +set, `meta git worktree` commands find sets where the checkout the set was +made from keeps them, so running them there acts on the workspace's sets. ## Creating Worktrees @@ -97,10 +96,10 @@ meta git worktree create ci-check --all --ephemeral --meta agent=review-bot --me meta git worktree exec --ephemeral lint-check --all -- make lint ``` -`prune` removes sets whose TTL has expired and sets whose project directory is -gone; for a set whose directory is gone it only forgets meta's record. Once its -repos are taken out of the meta config, a set is no longer the workspace's: -remove it with `git worktree remove`. `--ephemeral` alone only records metadata. A TTL is a backstop for a session that +`prune` removes sets whose TTL has expired; for a set whose directory is gone +it only forgets meta's record. Once its repos are taken out of the meta config, +or the checkout it was made from is moved or deleted, a set is no longer the +workspace's: remove it with `git worktree remove`. `--ephemeral` alone only records metadata. A TTL is a backstop for a session that dies before removing its sets. ## Inspecting Worktrees diff --git a/src/init.rs b/src/init.rs index ef50ece..89057d4 100644 --- a/src/init.rs +++ b/src/init.rs @@ -242,9 +242,14 @@ fn install_claude_integration_to( } } else if fs::symlink_metadata(&flat_path).is_ok() { println!( - "{} {} (left alone)", + "{} {} ({})", "Skipped".yellow(), - escape_path(&flat_path) + escape_path(&flat_path), + if shipped { + "an older meta's file; --force or --update removes it" + } else { + "not created by meta, left alone" + } ); skipped += 1; } diff --git a/src/main.rs b/src/main.rs index 8e48b0f..b97af7e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -926,7 +926,7 @@ fn handle_command_dispatch( if cli.verbose { println!("{}", "Verbose mode enabled".green()); println!("Resolved config file path: {}", escape_path(&absolute_path)); - println!("Executing command: {command_str}"); + println!("Executing command: {}", escape(&command_str)); } let (meta_projects, ignore_list) = parse_meta_config(&absolute_path)?; @@ -1250,7 +1250,7 @@ fn handle_plugin_command( installer.uninstall(&name)?; if !json { - println!("Successfully uninstalled {name} from {location}"); + println!("Successfully uninstalled {} from {location}", escape(&name)); } } PluginCommands::Update { name, local, check } => { diff --git a/src/registry.rs b/src/registry.rs index 4afbe9a..8b2db51 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -6,7 +6,7 @@ use anyhow::{Context, Result}; use log::{debug, info}; -use meta_core::display::escape_path; +use meta_core::display::{escape, escape_path}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::io::Read; @@ -327,7 +327,7 @@ impl RegistryClient { } } - anyhow::bail!("Plugin '{name}' not found in any registry") + anyhow::bail!("Plugin '{}' not found in any registry", escape(name)) } /// Fetch plugin metadata (complex registry format) @@ -347,7 +347,7 @@ impl RegistryClient { } } - anyhow::bail!("Plugin '{name}' not found in any registry") + anyhow::bail!("Plugin '{}' not found in any registry", escape(name)) } /// Search for plugins matching a query @@ -971,7 +971,7 @@ impl PluginInstaller { self.validate_plugin(&plugin_path).with_context(|| { // Remove invalid plugin on failure let _ = std::fs::remove_file(&plugin_path); - format!("Plugin validation failed for {plugin_name}") + format!("Plugin validation failed for {}", escape(plugin_name)) })?; } @@ -1145,7 +1145,7 @@ impl PluginInstaller { info!("Uninstalled {}", plugin_name); Ok(()) } else { - anyhow::bail!("Plugin {plugin_name} is not installed") + anyhow::bail!("Plugin {} is not installed", escape(&plugin_name)) } } diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs index 8e5beba..49211cb 100644 --- a/tests/plugin_discovery.rs +++ b/tests/plugin_discovery.rs @@ -18,10 +18,12 @@ struct Fixture { impl Fixture { fn new(workspace: bool) -> Self { let temp = tempfile::tempdir().unwrap(); - let home = temp.path().join("home"); + // meta reports resolved paths (macOS's temp dir is behind a link) + let base = temp.path().canonicalize().unwrap(); + let home = base.join("home"); let cwd = home.join("workspace"); - let data = temp.path().join("data"); - let bin = temp.path().join("bin"); + let data = base.join("data"); + let bin = base.join("bin"); for dir in [&cwd, &data, &bin] { fs::create_dir_all(dir).unwrap(); } @@ -142,12 +144,16 @@ fn nested_meta_dir_reads_its_workspace_plugins_but_not_an_unlisting_parent() { fn a_worktree_set_checkout_reads_its_own_and_its_origins_plugins() { let f = Fixture::new(true); // A set's root checkout, laid out as git and meta leave it + let set = f.cwd.join(".worktrees/s1"); let admin = f.cwd.join(".git/worktrees/s1"); fs::create_dir_all(&admin).unwrap(); fs::write(admin.join("commondir"), "../..\n").unwrap(); - let record = format!("{{\"project\": {:?}}}", f.cwd.display().to_string()); + let record = format!( + "{{\"project\": {:?}, \"set\": {:?}}}", + f.cwd.display().to_string(), + set.display().to_string() + ); fs::write(admin.join("meta-worktree.json"), record).unwrap(); - let set = f.cwd.join(".worktrees/s1"); fs::create_dir_all(&set).unwrap(); fs::write(set.join(".meta.yaml"), "projects: {}\n").unwrap(); fs::write(set.join(".git"), format!("gitdir: {}\n", admin.display())).unwrap(); diff --git a/tests/plugin_git.rs b/tests/plugin_git.rs index a2d2aef..4c7936b 100644 --- a/tests/plugin_git.rs +++ b/tests/plugin_git.rs @@ -352,6 +352,8 @@ fn malformed_worktree_membership_is_reported_before_dispatch() { .args(["exec", "--", "/usr/bin/touch", marker.to_str().unwrap()]) .current_dir(&worktree) .env("HOME", &root) + .env("XDG_CONFIG_HOME", root.join("xdg")) + .env("GIT_CONFIG_GLOBAL", root.join("gitconfig")) .env("META_DATA_DIR", root.join("data")) .env("PATH", "/usr/bin:/bin") .output() diff --git a/tests/plugin_routing.rs b/tests/plugin_routing.rs index 50ed27f..166f4dd 100644 --- a/tests/plugin_routing.rs +++ b/tests/plugin_routing.rs @@ -49,6 +49,8 @@ fn run_meta(root: &Path, args: &[&str]) -> std::process::Output { .args(args) .current_dir(root) .env("HOME", root) + .env("XDG_CONFIG_HOME", root.join("xdg")) + .env("GIT_CONFIG_GLOBAL", root.join("gitconfig")) .env("META_DATA_DIR", root.join("data")) .env( "PATH", From d812301096403e3542797d1ae0c1112ffe7f9bdc Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 14:52:23 -0700 Subject: [PATCH 14/34] fix(cli): Windows closed pipes; cap the plugin probe's output The closed-stdout check also knows os errors 109 and 232, unit-tested. A plugin can't fill memory while it is probed. [[tasks/harmony-2793]] --- .claude/skills/meta-safety/SKILL.md | 1 - .claude/skills/meta-worktree/SKILL.md | 10 ++++----- src/main.rs | 29 +++++++++++++++++++++++---- src/subprocess_plugins.rs | 5 +++-- 4 files changed, 32 insertions(+), 13 deletions(-) diff --git a/.claude/skills/meta-safety/SKILL.md b/.claude/skills/meta-safety/SKILL.md index 51c03b7..cf789c6 100644 --- a/.claude/skills/meta-safety/SKILL.md +++ b/.claude/skills/meta-safety/SKILL.md @@ -74,7 +74,6 @@ meta --strict git worktree prune **What becomes an error in strict mode:** - Missing refs when using a commit-ish (worktree create) -- Failed PR branch fetches, or no repo matching `--from-pr` (worktree create) - The root repo skipped because a commit-ish is missing there (worktree create) - Invalid `--meta` format values (worktree create) - Failed directory removal (worktree prune) diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index d672ef6..2d1e069 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -65,10 +65,9 @@ Add a repo to an existing set with `meta git worktree add auth-fix --repo anothe `--from-pr` uses the PR's head branch name and fetches it from the child repo whose `origin` matches; it does not check out a fork's branch or pin the head -SHA. It never applies to the root repo. When no repo matches it only warns and -keeps the set's own branch; when the fetch fails it warns and still uses a branch -named after the PR, without the PR's commits (add `--strict` to make either an -error). To continue a PR on the root repo, check out its branch directly: +SHA. It never applies to the root repo. When no selected repo matches, or the +fetch fails, create fails and makes nothing. To continue a PR on the root repo, +check out its branch directly: ```bash git fetch origin my-feature:my-feature # create or fast-forward the local branch @@ -76,8 +75,7 @@ meta git worktree create review --repo .:my-feature --repo backend --strict ``` Don't pass `origin/my-feature` as the commit-ish here: with a commit-ish, create -always makes a new branch, which fails when `my-feature` already exists locally -(and without `--strict` that failure is only a warning). +always makes a new branch, which fails when `my-feature` already exists locally. With `--from-pr` on a child repo whose PR branch already exists locally, `create` checks that branch out as it is (the fetch only updates `origin/`), so diff --git a/src/main.rs b/src/main.rs index b97af7e..df3025c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -477,16 +477,22 @@ fn exit_quietly_on_closed_stdout() { .map(String::as_str) .or_else(|| payload.downcast_ref::<&str>().copied()) .unwrap_or(""); - // std's wording; "os error 232" is Windows' closed pipe - if message.starts_with("failed printing to stdout") - && (message.contains("Broken pipe") || message.contains("os error 232")) - { + if is_closed_stdout_panic(message) { std::process::exit(CLOSED_STDOUT.into()); } report(info) })); } +/// Whether `message` is std's panic for printing to a closed stdout: a +/// broken pipe, which Windows reports as os error 109 or 232. +fn is_closed_stdout_panic(message: &str) -> bool { + message.starts_with("failed printing to stdout") + && ["Broken pipe", "(os error 109)", "(os error 232)"] + .iter() + .any(|closed| message.contains(closed)) +} + fn main() -> std::process::ExitCode { exit_quietly_on_closed_stdout(); match run_cli() { @@ -1548,6 +1554,21 @@ fn flatten_filtered_inner( #[cfg(test)] mod tests { use super::*; + + #[test] + fn closed_stdout_panics_are_recognised_on_every_platform() { + for message in [ + "failed printing to stdout: Broken pipe (os error 32)", + "failed printing to stdout: The pipe has been ended. (os error 109)", + "failed printing to stdout: The pipe is being closed. (os error 232)", + ] { + assert!(is_closed_stdout_panic(message), "{message}"); + } + assert!(!is_closed_stdout_panic( + "failed printing to stdout: No space left on device (os error 28)" + )); + assert!(!is_closed_stdout_panic("index out of bounds: Broken pipe")); + } use std::io::Write; use tempfile::NamedTempFile; diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 720e53e..121403f 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -35,7 +35,7 @@ pub(crate) fn probe_plugin_info(path: &Path) -> Result> { Ok(child) => child, Err(_) => return Ok(None), }; - let Some(mut stdout) = child.stdout.take() else { + let Some(stdout) = child.stdout.take() else { let _ = child.kill(); let _ = child.wait(); return Ok(None); @@ -43,7 +43,8 @@ pub(crate) fn probe_plugin_info(path: &Path) -> Result> { let (sender, receiver) = std::sync::mpsc::channel(); std::thread::spawn(move || { let mut bytes = Vec::new(); - let _ = sender.send(stdout.read_to_end(&mut bytes).map(|_| bytes)); + // Plugin info is small; a plugin flooding stdout can't fill memory + let _ = sender.send(stdout.take(1 << 20).read_to_end(&mut bytes).map(|_| bytes)); }); // stdout ends once the plugin, and anything it started that holds it, is done let remaining = deadline.saturating_duration_since(Instant::now()); From 935727c3c2f829e0a920f6910c24ad7d77bd8eb6 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 15:10:21 -0700 Subject: [PATCH 15/34] fix(cli): clearer init settings errors and plugin warning [[tasks/harmony-2793]] --- .claude/skills/meta-worktree/SKILL.md | 3 +++ src/init.rs | 21 ++++++++++++--------- src/subprocess_plugins.rs | 2 +- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index 2d1e069..d45f4f0 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -63,6 +63,9 @@ meta git worktree create auth-fix --repo backend --dry-run Add a repo to an existing set with `meta git worktree add auth-fix --repo another-service`. +A set lays its repos out as the workspace does: each repo sits at its `path` +from the meta config, so relative references between repos keep working. + `--from-pr` uses the PR's head branch name and fetches it from the child repo whose `origin` matches; it does not check out a fork's branch or pin the head SHA. It never applies to the root repo. When no selected repo matches, or the diff --git a/src/init.rs b/src/init.rs index 89057d4..c66338d 100644 --- a/src/init.rs +++ b/src/init.rs @@ -650,7 +650,7 @@ fn prepare_settings(path: &Path) -> Result { let existing = match fs::read_to_string(path) { Ok(content) => Some( serde_json::from_str::(&content) - .with_context(|| format!("Invalid JSON in {} at key '$'", escape_path(path)))?, + .with_context(|| format!("Invalid JSON in {}", escape_path(path)))?, ), Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, Err(e) => return Err(e).with_context(|| format!("Failed to read {}", escape_path(path))), @@ -790,9 +790,12 @@ fn merge_hooks_into_settings( shape ) }; - let obj = existing - .as_object_mut() - .ok_or_else(|| invalid("$", "an object"))?; + let obj = existing.as_object_mut().ok_or_else(|| { + anyhow::anyhow!( + "Cannot merge {}: it must hold a JSON object", + escape_path(path) + ) + })?; let hooks = obj .entry("hooks") .or_insert_with(|| json!({})) @@ -865,10 +868,10 @@ mod tests { entries } for (content, key) in [ - (r#"[{"user":"data"}]"#, "$"), - (r#"{"hooks":[],"theme":"dark"}"#, "hooks"), - (r#"{"hooks":{"PreToolUse":{}}}"#, "hooks.PreToolUse"), - ("{invalid json", "$"), + (r#"[{"user":"data"}]"#, "must hold a JSON object"), + (r#"{"hooks":[],"theme":"dark"}"#, "key 'hooks'"), + (r#"{"hooks":{"PreToolUse":{}}}"#, "key 'hooks.PreToolUse'"), + ("{invalid json", "Invalid JSON"), ] { let dir = tempdir().unwrap(); fs::create_dir_all(dir.path().join(".claude/rules")).unwrap(); @@ -886,7 +889,7 @@ mod tests { install_claude_integration_to(dir.path(), force, false, false).unwrap_err(); let message = format!("{err:#}"); assert!(message.contains(&escape_path(&settings)), "{message}"); - assert!(message.contains(&format!("key '{key}'")), "{message}"); + assert!(message.contains(key), "{message}"); assert_eq!(snapshot(dir.path()), before); } } diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 121403f..063386d 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -144,7 +144,7 @@ impl SubprocessPluginManager { // itself reports it, and `--help` still prints let nearest = meta_core::config::nearest_meta_dir(&cwd).unwrap_or_else(|e| { eprintln!( - "Warning: {}; skipping project plugins", + "Warning: {} Skipping project plugins.", escape(&format!("{e:#}")) ); None From 785c5eab9dc5810842c4215e2a033b342813d8ae Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 15:29:55 -0700 Subject: [PATCH 16/34] fix(cli): inside a set, tags and filters go by project path and name A set lays its repos out as the workspace, so --tag matches a checkout's path against project paths and --include/--exclude take project names too. Discovery finds repos at hidden paths, skipping only .git and nested .worktrees. [[tasks/harmony-2793]] --- .claude/skills/meta-worktree/SKILL.md | 8 +++---- src/main.rs | 33 ++++++++++++++++++--------- src/repo_filter.rs | 2 +- src/worktree.rs | 29 ++++++++++++++--------- 4 files changed, 45 insertions(+), 27 deletions(-) diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index d45f4f0..521c47c 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -126,8 +126,8 @@ meta git worktree exec auth-fix --exclude legacy -- npm test meta git worktree exec auth-fix --parallel -- cargo build ``` -`--include`/`--exclude` name whole repos by alias, their path in the set -(`.` for the root repo), never part of a path. A value that names no repo in +`--include`/`--exclude` name whole repos as in the workspace: a project's name +or its path in the set (`.` for the root repo), never part of a path. A value that names no repo in the set is an error. They go after the set name: `meta --include x git worktree ...` is refused. The command's arguments reach it as typed, with no shell; use `-- sh -c '...'` when you want one. @@ -240,7 +240,7 @@ can't delete something, the error says what was left behind. | Option | Description | |--------|-------------| -| `--include ` | Only these repos, by alias (comma-separated) | -| `--exclude ` | Skip these repos, by alias (comma-separated) | +| `--include ` | Only these repos, by name or path (comma-separated) | +| `--exclude ` | Skip these repos, by name or path (comma-separated) | | `--parallel` | Run concurrently | | `--ephemeral` | Create, run, then remove (takes `--repo`/`--all`, `--branch`, `--from-pr`, `--meta`, a commit-ish) | diff --git a/src/main.rs b/src/main.rs index df3025c..b4f0dd6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -782,20 +782,27 @@ fn handle_command_dispatch( { let (meta_projects, ignore_list) = parse_meta_config(&config_path)?; - // Build name→info lookup for tag filtering + // A set lays its repos out as the workspace: a checkout's path + // in the set is its project's path let project_map: std::collections::HashMap<&str, &ProjectInfo> = - meta_projects.iter().map(|p| (p.name.as_str(), p)).collect(); + meta_projects.iter().map(|p| (p.path.as_str(), p)).collect(); - // Derive aliases from worktree paths and filter by tags + // Filter the checkouts by their projects' tags let wt_directories: Vec = wt_paths .iter() .filter(|path| { if let Some(ref tag_filter) = cli.tag { - let alias = path - .file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_else(|| ".".to_string()); - if let Some(info) = project_map.get(alias.as_str()) { + let place = path + .strip_prefix(&task_dir) + .ok() + .map(|p| { + p.components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect::>() + .join("/") + }) + .unwrap_or_default(); + if let Some(info) = project_map.get(place.as_str()) { matches_tag_filter(&info.tags, tag_filter) } else { true // Unknown projects pass through @@ -807,9 +814,13 @@ fn handle_command_dispatch( .map(|p| p.display().to_string()) .collect(); - // A worktree member sits at its alias, so its path in the set - // is the name to select it by - let wt_directories = select_repos(cli, wt_directories, &task_dir, Vec::new)?; + // Selected by project name or by its path in the set + let wt_directories = select_repos(cli, wt_directories, &task_dir, || { + meta_projects + .iter() + .map(|p| (p.name.clone(), p.path.clone())) + .collect() + })?; if wt_directories.is_empty() { eprintln!( diff --git a/src/repo_filter.rs b/src/repo_filter.rs index b0747a3..553acfd 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -101,7 +101,7 @@ pub fn select( bail!( "{flag} '{value}' names none of the repos this command runs in. Use a repo's \ name from .meta or its path from the workspace root (`.` for the root), as \ - `meta project list` shows it; in a worktree set, its alias. --tag and \ + `meta project list` shows it; in a worktree set, the same, from the set's root. --tag and \ --recursive change which repos the command runs in." ); } diff --git a/src/worktree.rs b/src/worktree.rs index db6b3d6..90cbbe7 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -151,9 +151,9 @@ fn discover_repos_recursive( continue; } - // Skip hidden directories - let name = entry.file_name(); - if name.to_string_lossy().starts_with('.') { + // A repo may live at a hidden path (`.deps/x`); git's own directory + // and a nested worktree directory hold no members of this set + if is_not_a_member_dir(&entry.file_name()) { continue; } @@ -200,8 +200,9 @@ fn discover_repos_recursive( } /// Discover all realized worktrees, including repos nested beneath other repos. -/// Unlike legacy discovery, traversal errors are fatal. Hidden directories and -/// directory symlinks are excluded; traversal never follows links outside the set. +/// Unlike legacy discovery, traversal errors are fatal. `.git`, nested +/// `.worktrees` and directory symlinks are excluded; traversal never follows +/// links outside the set. /// A finite entry budget prevents unbounded scans of generated directory trees. pub fn discover_worktree_repos_recursive(task_dir: &Path) -> Result> { Ok(discover_worktree_members_recursive(task_dir)? @@ -220,14 +221,18 @@ pub struct WorktreeMemberInfo { pub source_path: PathBuf, } +/// Git's own directory and a nested worktree directory, which hold no +/// members of the set being scanned. +fn is_not_a_member_dir(name: &std::ffi::OsStr) -> bool { + name == ".git" || name == ".worktrees" +} + pub fn discover_worktree_members_recursive(task_dir: &Path) -> Result> { let mut repos = Vec::new(); let entries = walkdir::WalkDir::new(task_dir) .follow_links(false) .into_iter() - .filter_entry(|entry| { - entry.depth() == 0 || !entry.file_name().to_string_lossy().starts_with('.') - }); + .filter_entry(|entry| entry.depth() == 0 || !is_not_a_member_dir(entry.file_name())); for (count, entry) in entries.enumerate() { anyhow::ensure!( count < 2_000_000, @@ -474,15 +479,17 @@ mod recursive_tests { #[cfg(unix)] #[test] - /// Hidden directories and symlink cycles are excluded from traversal. - fn recursive_skips_hidden_directories_and_symlink_cycles() { + /// A repo at a hidden path is a member; a nested set and symlink cycles + /// are excluded from traversal. + fn recursive_finds_hidden_paths_but_skips_nested_sets_and_cycles() { let temp = tempfile::tempdir().unwrap(); member(temp.path(), "visible"); member(temp.path(), ".hidden/child"); + member(temp.path(), ".worktrees/other"); std::os::unix::fs::symlink(temp.path(), temp.path().join("visible/cycle")).unwrap(); assert_eq!( aliases(discover_worktree_repos_recursive(temp.path()).unwrap()), - ["visible"] + [".hidden/child", "visible"] ); } /// Relative Git links resolve against the checkout, independently of cwd. From 0da1b7ea273d7d2177cdaef3ae7515c368fafd03 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 16:04:37 -0700 Subject: [PATCH 17/34] fix(cli): scan hidden dirs of a set only on configured project paths An agent's own worktree (.claude/worktrees/x) in a set is not a member. Inside a set, tags and names cover nested meta repos too. [[tasks/harmony-2793]] --- src/main.rs | 15 +++++---- src/worktree.rs | 85 ++++++++++++++++++++++++++++++++++++------------- 2 files changed, 71 insertions(+), 29 deletions(-) diff --git a/src/main.rs b/src/main.rs index b4f0dd6..188ad7d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -783,9 +783,13 @@ fn handle_command_dispatch( let (meta_projects, ignore_list) = parse_meta_config(&config_path)?; // A set lays its repos out as the workspace: a checkout's path - // in the set is its project's path - let project_map: std::collections::HashMap<&str, &ProjectInfo> = - meta_projects.iter().map(|p| (p.path.as_str(), p)).collect(); + // in the set is its project's path, nested meta repos included + let tree = config::walk_meta_tree(&task_dir, None).unwrap_or_default(); + let project_map: std::collections::HashMap = + config::build_project_map(&tree, &task_dir, "") + .into_iter() + .map(|(place, (_, info))| (place, info)) + .collect(); // Filter the checkouts by their projects' tags let wt_directories: Vec = wt_paths @@ -816,10 +820,7 @@ fn handle_command_dispatch( // Selected by project name or by its path in the set let wt_directories = select_repos(cli, wt_directories, &task_dir, || { - meta_projects - .iter() - .map(|p| (p.name.clone(), p.path.clone())) - .collect() + repo_filter::repo_names(&task_dir, &meta_projects, &tree) })?; if wt_directories.is_empty() { diff --git a/src/worktree.rs b/src/worktree.rs index 90cbbe7..f7bc55b 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -110,7 +110,8 @@ pub fn discover_worktree_members(task_dir: &Path) -> Result Result, ) -> Result<()> { let entries = match std::fs::read_dir(dir) { @@ -151,9 +153,7 @@ fn discover_repos_recursive( continue; } - // A repo may live at a hidden path (`.deps/x`); git's own directory - // and a nested worktree directory hold no members of this set - if is_not_a_member_dir(&entry.file_name()) { + if !scanned.holds_members(root, &sub_path) { continue; } @@ -187,7 +187,7 @@ fn discover_repos_recursive( }); } else { // Not a repo — recurse into intermediate directory - if let Err(e) = discover_repos_recursive(root, &sub_path, repos) { + if let Err(e) = discover_repos_recursive(root, &sub_path, scanned, repos) { log::debug!( "Skipping subtree {}: {}", escape_path(&sub_path), @@ -200,9 +200,9 @@ fn discover_repos_recursive( } /// Discover all realized worktrees, including repos nested beneath other repos. -/// Unlike legacy discovery, traversal errors are fatal. `.git`, nested -/// `.worktrees` and directory symlinks are excluded; traversal never follows -/// links outside the set. +/// Unlike legacy discovery, traversal errors are fatal. Hidden directories +/// (see `ScannedDirs`) and directory symlinks are excluded; traversal never +/// follows links outside the set. /// A finite entry budget prevents unbounded scans of generated directory trees. pub fn discover_worktree_repos_recursive(task_dir: &Path) -> Result> { Ok(discover_worktree_members_recursive(task_dir)? @@ -221,18 +221,51 @@ pub struct WorktreeMemberInfo { pub source_path: PathBuf, } -/// Git's own directory and a nested worktree directory, which hold no -/// members of the set being scanned. -fn is_not_a_member_dir(name: &std::ffi::OsStr) -> bool { - name == ".git" || name == ".worktrees" +/// Which directories of a set may hold its members. Hidden directories +/// (`.git`, a nested `.worktrees`, `.claude/worktrees` of an agent) don't, +/// except on the way to a project the set's config puts at a hidden path +/// (`.deps/x`). +struct ScannedDirs { + hidden_project_dirs: std::collections::HashSet, +} + +impl ScannedDirs { + fn of(task_dir: &Path) -> Self { + let paths = meta_core::config::walk_meta_tree(task_dir, None) + .map(|tree| meta_core::config::build_project_map(&tree, task_dir, "")) + .unwrap_or_default(); + let hidden_project_dirs = paths + .into_values() + .filter_map(|(path, _)| path.strip_prefix(task_dir).ok().map(Path::to_path_buf)) + .flat_map(|path| path.ancestors().map(Path::to_path_buf).collect::>()) + .collect(); + ScannedDirs { + hidden_project_dirs, + } + } + + /// Whether `dir`, inside the set at `root`, may hold members. + fn holds_members(&self, root: &Path, dir: &Path) -> bool { + let Some(name) = dir.file_name() else { + return true; + }; + if name == ".git" || name == ".worktrees" { + return false; + } + !name.to_string_lossy().starts_with('.') + || dir + .strip_prefix(root) + .is_ok_and(|place| self.hidden_project_dirs.contains(place)) + } } pub fn discover_worktree_members_recursive(task_dir: &Path) -> Result> { let mut repos = Vec::new(); + let scanned = ScannedDirs::of(task_dir); let entries = walkdir::WalkDir::new(task_dir) .follow_links(false) .into_iter() - .filter_entry(|entry| entry.depth() == 0 || !is_not_a_member_dir(entry.file_name())); + .filter_entry(|entry| entry.depth() == 0 || scanned.holds_members(task_dir, entry.path())); for (count, entry) in entries.enumerate() { anyhow::ensure!( count < 2_000_000, @@ -479,17 +512,25 @@ mod recursive_tests { #[cfg(unix)] #[test] - /// A repo at a hidden path is a member; a nested set and symlink cycles - /// are excluded from traversal. - fn recursive_finds_hidden_paths_but_skips_nested_sets_and_cycles() { + /// A repo the set's config puts at a hidden path is a member; other + /// hidden directories (a nested set, an agent's own worktrees) and + /// symlink cycles are excluded from traversal. + fn recursive_finds_configured_hidden_paths_only() { let temp = tempfile::tempdir().unwrap(); - member(temp.path(), "visible"); - member(temp.path(), ".hidden/child"); - member(temp.path(), ".worktrees/other"); - std::os::unix::fs::symlink(temp.path(), temp.path().join("visible/cycle")).unwrap(); + let root = temp.path().canonicalize().unwrap(); + std::fs::write( + root.join(".meta.json"), + r#"{"projects": {"child": {"repo": "x", "path": ".deps/child"}}}"#, + ) + .unwrap(); + member(&root, "visible"); + member(&root, ".deps/child"); + member(&root, ".claude/worktrees/agent"); + member(&root, ".worktrees/other"); + std::os::unix::fs::symlink(&root, root.join("visible/cycle")).unwrap(); assert_eq!( - aliases(discover_worktree_repos_recursive(temp.path()).unwrap()), - [".hidden/child", "visible"] + aliases(discover_worktree_repos_recursive(&root).unwrap()), + [".deps/child", "visible"] ); } /// Relative Git links resolve against the checkout, independently of cwd. From f763c0685d6f7e8af5da6e6f5e5e2b6bc6f224c4 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 16:24:27 -0700 Subject: [PATCH 18/34] fix(cli): hidden members by record; tags from the chosen config Under a hidden directory, a checkout is a set member only if meta's record names the set. Inside a set the tag tree comes from the chosen config and its errors stop the command; the no-match warning escapes the tag. [[tasks/harmony-2793]] --- src/main.rs | 4 +-- src/worktree.rs | 76 +++++++++++++++++++++++++------------------------ 2 files changed, 41 insertions(+), 39 deletions(-) diff --git a/src/main.rs b/src/main.rs index 188ad7d..942ae86 100644 --- a/src/main.rs +++ b/src/main.rs @@ -784,7 +784,7 @@ fn handle_command_dispatch( // A set lays its repos out as the workspace: a checkout's path // in the set is its project's path, nested meta repos included - let tree = config::walk_meta_tree(&task_dir, None).unwrap_or_default(); + let tree = config::walk_projects(&task_dir, &meta_projects, None)?; let project_map: std::collections::HashMap = config::build_project_map(&tree, &task_dir, "") .into_iter() @@ -827,7 +827,7 @@ fn handle_command_dispatch( eprintln!( "{}: no projects match tag filter '{}' in worktree '{}'", "warning".yellow().bold(), - cli.tag.as_deref().unwrap_or(""), + escape(cli.tag.as_deref().unwrap_or("")), escape(&task_name) ); return Ok(()); diff --git a/src/worktree.rs b/src/worktree.rs index f7bc55b..60af3e6 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -153,7 +153,7 @@ fn discover_repos_recursive( continue; } - if !scanned.holds_members(root, &sub_path) { + if !ScannedDirs::searched(&sub_path) { continue; } @@ -163,6 +163,9 @@ fn discover_repos_recursive( .map(|m| m.is_file()) .unwrap_or(false) { + if !scanned.member(root, &sub_path) { + continue; + } // This is a worktree repo — use relative path from root as alias let source = match source_repo_from_gitfile(&sub_git) { Ok(s) => s, @@ -221,41 +224,38 @@ pub struct WorktreeMemberInfo { pub source_path: PathBuf, } -/// Which directories of a set may hold its members. Hidden directories -/// (`.git`, a nested `.worktrees`, `.claude/worktrees` of an agent) don't, -/// except on the way to a project the set's config puts at a hidden path -/// (`.deps/x`). +/// Which checkouts in a set are its members. `.git` and a nested +/// `.worktrees` hold none. Under another hidden directory, only a checkout +/// meta's record says it made for this set counts: a project may live at +/// `.deps/x`, but a tool's own worktrees (`.claude/worktrees/x`) are not the +/// set's. struct ScannedDirs { - hidden_project_dirs: std::collections::HashSet, + set: PathBuf, } impl ScannedDirs { fn of(task_dir: &Path) -> Self { - let paths = meta_core::config::walk_meta_tree(task_dir, None) - .map(|tree| meta_core::config::build_project_map(&tree, task_dir, "")) - .unwrap_or_default(); - let hidden_project_dirs = paths - .into_values() - .filter_map(|(path, _)| path.strip_prefix(task_dir).ok().map(Path::to_path_buf)) - .flat_map(|path| path.ancestors().map(Path::to_path_buf).collect::>()) - .collect(); ScannedDirs { - hidden_project_dirs, + set: task_dir + .canonicalize() + .unwrap_or_else(|_| task_dir.to_path_buf()), } } - /// Whether `dir`, inside the set at `root`, may hold members. - fn holds_members(&self, root: &Path, dir: &Path) -> bool { - let Some(name) = dir.file_name() else { - return true; - }; - if name == ".git" || name == ".worktrees" { - return false; - } - !name.to_string_lossy().starts_with('.') - || dir - .strip_prefix(root) - .is_ok_and(|place| self.hidden_project_dirs.contains(place)) + /// Whether to look for members inside `dir`. + fn searched(dir: &Path) -> bool { + dir.file_name() + .is_none_or(|name| name != ".git" && name != ".worktrees") + } + + /// Whether the checkout at `dir`, inside the set at `root`, is a member. + fn member(&self, root: &Path, dir: &Path) -> bool { + let hidden = dir.strip_prefix(root).is_ok_and(|place| { + place + .components() + .any(|c| c.as_os_str().to_string_lossy().starts_with('.')) + }); + !hidden || meta_core::config::recorded_set(dir).as_ref() == Some(&self.set) } } @@ -265,7 +265,7 @@ pub fn discover_worktree_members_recursive(task_dir: &Path) -> Result Result

(std::env::args_os()).exit(), }) } diff --git a/src/worktree.rs b/src/worktree.rs index 4f73077..82ebdb0 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -128,7 +128,8 @@ fn not_held( } /// Whether a checkout meta made for a set (a linked worktree with meta's -/// record, readable or not) is under `dir`, as in a set moved by hand. Other tools' worktrees +/// record, readable or not, or one whose git directory can't be found) is +/// under `dir`, as in a set moved by hand. Other tools' worktrees /// have no record; plain clones (a `.git` directory, or a link to one) are /// not looked inside. pub fn holds_meta_checkout(dir: &Path) -> bool { @@ -145,8 +146,16 @@ pub fn holds_meta_checkout(dir: &Path) -> bool { } match std::fs::metadata(entry.path().join(".git")) { Ok(meta) if meta.is_dir() => walk.skip_current_dir(), - // even one meta can no longer read: it was meta's - Ok(_) if meta_core::config::has_worktree_record(entry.path()) => return true, + // even one meta can no longer read: it was meta's. A checkout + // whose git directory can't be found (moved, with relative paths) + // may be meta's too: it is not taken for a plain clone + Ok(_) => { + let reachable = meta_core::config::gitfile_target(entry.path()) + .is_some_and(|target| target.is_dir()); + if !reachable || meta_core::config::has_worktree_record(entry.path()) { + return true; + } + } _ => {} } } From e71251b49cd6e30168d620b6fc1c1d5b4c0b2964 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 20:18:29 -0700 Subject: [PATCH 30/34] fix(cli): escape the plugin path in plan errors; the guard checks the record beside its target Implements [[tasks/harmony-2793]] --- src/subprocess_plugins.rs | 2 +- src/worktree.rs | 12 +++++++++--- tests/plugin_discovery.rs | 25 +++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 3aa5eba..a241714 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -413,7 +413,7 @@ impl SubprocessPluginManager { Err(e) if is_plan => anyhow::bail!( "plugin {} sent an execution plan this meta cannot read ({e}); \ upgrade the plugin to match this meta", - plugin.path.display() + escape_path(&plugin.path) ), Err(_) => { // Not a plan - print output as-is diff --git a/src/worktree.rs b/src/worktree.rs index 82ebdb0..7b22640 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -150,9 +150,15 @@ pub fn holds_meta_checkout(dir: &Path) -> bool { // whose git directory can't be found (moved, with relative paths) // may be meta's too: it is not taken for a plain clone Ok(_) => { - let reachable = meta_core::config::gitfile_target(entry.path()) - .is_some_and(|target| target.is_dir()); - if !reachable || meta_core::config::has_worktree_record(entry.path()) { + let meta_made = + meta_core::config::gitfile_target(entry.path()).is_none_or(|admin| { + !admin.is_dir() + || admin + .join(meta_core::config::WORKTREE_RECORD_FILE) + .symlink_metadata() + .is_ok() + }); + if meta_made { return true; } } diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs index ba9b649..3874f00 100644 --- a/tests/plugin_discovery.rs +++ b/tests/plugin_discovery.rs @@ -516,3 +516,28 @@ esac"#, "{text}" ); } + +#[test] +fn an_unreadable_plan_names_the_plugin_on_one_line() { + let f = Fixture::new(false); + // a workspace whose path holds a newline: the plugin's path does too + let cwd = f.cwd.join("ws\nFORGED"); + fs::create_dir_all(&cwd).unwrap(); + fs::write(cwd.join(".meta.yaml"), "projects: {}\n").unwrap(); + script( + &cwd.join(".meta/plugins/meta-demo"), + r#"case "$1" in +--meta-plugin-info) printf '%s\n' '{"name":"demo","version":"1","commands":["demo run"]}' ;; +*) printf '%s\n' '{"plan":{"commands":[{"cmd":"true"}]}}' ;; +esac"#, + ); + let out = f + .command(&["demo", "run"]) + .current_dir(&cwd) + .output() + .unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("ws\\nFORGED"), "{err}"); + assert!(!err.lines().any(|line| line.starts_with("FORGED")), "{err}"); +} From b78ba7b47be2b9b6bc33b959dc3814c90be899e0 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 20:50:53 -0700 Subject: [PATCH 31/34] fix(cli): the moved-set guard refuses what it can't read; readable fallback tree A traversal or .git error means meta can't tell, so it refuses. Checkouts of sets kept inside the directory (any worktrees_dir) are no sign of a moved set. The source-workspace fallback tree passes over each config it can't read. Implements [[tasks/harmony-2793]] --- src/worktree.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/src/worktree.rs b/src/worktree.rs index 7b22640..f4b9a6d 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -101,13 +101,41 @@ pub fn set_tree( let mut tree: Vec<_> = members .iter() .find_map(|member| config::recorded_project(member)) - .and_then(|dir| config::walk_projects(&dir, projects, None).ok()) - .map(|tree| not_held(tree, set_dir)) + .map(|dir| not_held(readable_tree(&dir, projects, 0), set_dir)) .unwrap_or_default(); tree.extend(own); Ok(tree) } +/// The meta tree of `projects` in `dir`, passing over each nested config +/// that can't be read: one broken config loses only its own projects. +fn readable_tree( + dir: &Path, + projects: &[meta_core::config::ProjectInfo], + depth: usize, +) -> Vec { + use meta_core::config; + projects + .iter() + .map(|project| { + let path = dir.join(&project.path); + let nested = (depth < 32) + .then(|| config::find_meta_config_in(&path).ok().flatten()) + .flatten(); + let children = nested + .as_ref() + .and_then(|(config, _)| config::parse_meta_config(config).ok()) + .map(|(projects, _)| readable_tree(&path, &projects, depth + 1)) + .unwrap_or_default(); + config::MetaTreeNode { + info: project.clone(), + is_meta: nested.is_some(), + children, + } + }) + .collect() +} + /// `nodes` without the projects of the nested meta repos whose config the /// set at `dir` holds: those the set's own tree describes. fn not_held( @@ -128,11 +156,13 @@ fn not_held( } /// Whether a checkout meta made for a set (a linked worktree with meta's -/// record, readable or not, or one whose git directory can't be found) is -/// under `dir`, as in a set moved by hand. Other tools' worktrees +/// record, readable or not, or one whose git directory can't be found) may +/// be under `dir`, as in a set moved by hand; a part of `dir` that can't be +/// read may hold one too. Other tools' worktrees /// have no record; plain clones (a `.git` directory, or a link to one) are /// not looked inside. pub fn holds_meta_checkout(dir: &Path) -> bool { + let canonical_dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()); // Where discovery looks: not in `.git`, nor in the sets of a workspace // that is itself under `.worktrees` (its own nested `.worktrees`) let mut walk = walkdir::WalkDir::new(dir) @@ -140,12 +170,21 @@ pub fn holds_meta_checkout(dir: &Path) -> bool { .into_iter() .filter_entry(|entry| entry.depth() == 0 || ScannedDirs::searched(entry.path())); while let Some(entry) = walk.next() { - let Ok(entry) = entry else { continue }; + // What can't be read may hold one: can't tell is no plain clone + let Ok(entry) = entry else { return true }; if !entry.file_type().is_dir() { continue; } match std::fs::metadata(entry.path().join(".git")) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return true, Ok(meta) if meta.is_dir() => walk.skip_current_dir(), + // a checkout of a set kept inside `dir` (a workspace there with + // sets of its own, wherever its worktrees_dir puts them) is no + // sign that `dir` is a set + Ok(_) + if meta_core::config::recorded_set(entry.path()) + .is_some_and(|set| set.starts_with(&canonical_dir) && set != canonical_dir) => { + } // even one meta can no longer read: it was meta's. A checkout // whose git directory can't be found (moved, with relative paths) // may be meta's too: it is not taken for a plain clone From 81e734420843adc7f3685d6ac27b84950aeac0cc Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 21:08:24 -0700 Subject: [PATCH 32/34] fix(cli): a plugin may answer without reading its request; the guard needs the workspace inside too A broken pipe while sending the request no longer fails the command: the plugin's output and status decide. The moved-set guard passes over a checkout only when both its set and its workspace lie inside the directory. readable_tree visits each meta repo once. Test plugins read their request. Implements [[tasks/harmony-2793]] --- src/subprocess_plugins.rs | 13 +++++++++++-- src/worktree.rs | 28 +++++++++++++++++----------- tests/plugin_discovery.rs | 24 ++++++++++++++++++++++-- 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index a241714..d4b703e 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -371,10 +371,19 @@ impl SubprocessPluginManager { .spawn() .with_context(|| format!("Failed to execute plugin {}", escape_path(&plugin.path)))?; - // Send request to plugin's stdin + // Send request to plugin's stdin. A plugin may answer without + // reading it; then its output and exit status decide, not the pipe. if let Some(mut stdin) = child.stdin.take() { use std::io::Write; - stdin.write_all(request_json.as_bytes())?; + match stdin.write_all(request_json.as_bytes()) { + Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {} + result => result.with_context(|| { + format!( + "Cannot send the request to plugin {}", + escape_path(&plugin.path) + ) + })?, + } } let output = child.wait_with_output()?; diff --git a/src/worktree.rs b/src/worktree.rs index f4b9a6d..85fb828 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -101,7 +101,10 @@ pub fn set_tree( let mut tree: Vec<_> = members .iter() .find_map(|member| config::recorded_project(member)) - .map(|dir| not_held(readable_tree(&dir, projects, 0), set_dir)) + .map(|dir| { + let mut visited = std::collections::HashSet::new(); + not_held(readable_tree(&dir, projects, &mut visited), set_dir) + }) .unwrap_or_default(); tree.extend(own); Ok(tree) @@ -112,20 +115,21 @@ pub fn set_tree( fn readable_tree( dir: &Path, projects: &[meta_core::config::ProjectInfo], - depth: usize, + visited: &mut std::collections::HashSet, ) -> Vec { use meta_core::config; projects .iter() .map(|project| { let path = dir.join(&project.path); - let nested = (depth < 32) - .then(|| config::find_meta_config_in(&path).ok().flatten()) - .flatten(); + let nested = config::find_meta_config_in(&path).ok().flatten(); + // each meta repo once, as `walk_projects` does: links can loop + let first_visit = visited.insert(path.canonicalize().unwrap_or_else(|_| path.clone())); let children = nested .as_ref() + .filter(|_| first_visit) .and_then(|(config, _)| config::parse_meta_config(config).ok()) - .map(|(projects, _)| readable_tree(&path, &projects, depth + 1)) + .map(|(projects, _)| readable_tree(&path, &projects, visited)) .unwrap_or_default(); config::MetaTreeNode { info: project.clone(), @@ -178,13 +182,15 @@ pub fn holds_meta_checkout(dir: &Path) -> bool { match std::fs::metadata(entry.path().join(".git")) { Err(e) if e.kind() != std::io::ErrorKind::NotFound => return true, Ok(meta) if meta.is_dir() => walk.skip_current_dir(), - // a checkout of a set kept inside `dir` (a workspace there with - // sets of its own, wherever its worktrees_dir puts them) is no - // sign that `dir` is a set + // a checkout of a set kept inside `dir` by a workspace inside + // `dir` (one there with sets of its own, wherever its + // worktrees_dir puts them) is no sign that `dir` is a set Ok(_) if meta_core::config::recorded_set(entry.path()) - .is_some_and(|set| set.starts_with(&canonical_dir) && set != canonical_dir) => { - } + .is_some_and(|set| set.starts_with(&canonical_dir) && set != canonical_dir) + && meta_core::config::recorded_project(entry.path()) + .and_then(|project| project.canonicalize().ok()) + .is_some_and(|project| project.starts_with(&canonical_dir)) => {} // even one meta can no longer read: it was meta's. A checkout // whose git directory can't be found (moved, with relative paths) // may be meta's too: it is not taken for a plain clone diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs index 3874f00..c6be992 100644 --- a/tests/plugin_discovery.rs +++ b/tests/plugin_discovery.rs @@ -503,7 +503,7 @@ fn verbose_dispatch_keeps_a_plugins_name_on_its_line() { &f.data.join("plugins/meta-demo"), r#"case "$1" in --meta-plugin-info) printf '%s\n' '{"name":"bad\u001b[2J\nFORGED","version":"1","commands":["demo run"]}' ;; -*) exit 0 ;; +*) cat >/dev/null ;; esac"#, ); let out = f.run(&["--verbose", "demo", "run"]); @@ -528,7 +528,7 @@ fn an_unreadable_plan_names_the_plugin_on_one_line() { &cwd.join(".meta/plugins/meta-demo"), r#"case "$1" in --meta-plugin-info) printf '%s\n' '{"name":"demo","version":"1","commands":["demo run"]}' ;; -*) printf '%s\n' '{"plan":{"commands":[{"cmd":"true"}]}}' ;; +*) cat >/dev/null; printf '%s\n' '{"plan":{"commands":[{"cmd":"true"}]}}' ;; esac"#, ); let out = f @@ -541,3 +541,23 @@ esac"#, assert!(err.contains("ws\\nFORGED"), "{err}"); assert!(!err.lines().any(|line| line.starts_with("FORGED")), "{err}"); } + +#[test] +fn a_plugin_that_answers_without_reading_its_request_still_answers() { + let f = Fixture::new(true); + script( + &f.data.join("plugins/meta-quick"), + r#"case "$1" in +--meta-plugin-info) printf '%s\n' '{"name":"quick","version":"1","commands":["quick go"]}' ;; +*) echo answered ;; +esac"#, + ); + // the plugin may exit before meta has written its request + for _ in 0..20 { + let out = f.run(&["quick", "go"]); + let text = String::from_utf8_lossy(&out.stdout).to_string() + + &String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{text}"); + assert!(text.contains("answered"), "{text}"); + } +} From ad73d56a390acdf6d12612a27eb8867a213be434 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 21:26:11 -0700 Subject: [PATCH 33/34] fix(cli): a set's config comes only from members recorded for that set set_origin skips checkouts of other sets moved in, and refuses members that name different workspaces. readable_tree records only meta repos as visited. Implements [[tasks/harmony-2793]] --- src/worktree.rs | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/src/worktree.rs b/src/worktree.rs index 85fb828..efff9da 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -79,12 +79,42 @@ pub fn set_config( if let Some(found) = config::meta_config_at(set_dir, config_name)? { return Ok(Some(found)); } - match members.iter().find_map(|m| config::recorded_project(m)) { + match set_origin(set_dir, members)? { Some(source) => config::meta_config_at(&source, config_name), None => config::find_meta_config(set_dir, config_name), } } +/// The workspace meta recorded the set at `set_dir` was made from, by the +/// members whose record names this set (another set's checkout moved in +/// doesn't count). Members that name different workspaces are an error. +fn set_origin(set_dir: &Path, members: &[PathBuf]) -> Result> { + use meta_core::config; + let set = set_dir + .canonicalize() + .unwrap_or_else(|_| set_dir.to_path_buf()); + let mut origin: Option = None; + for member in members { + if config::recorded_set(member).as_ref() != Some(&set) { + continue; + } + let Some(project) = config::recorded_project(member) else { + continue; + }; + match &origin { + Some(first) if *first != project => anyhow::bail!( + "The checkouts of worktree set {} name different workspaces ({} and {}); \ + meta can't tell which config describes them", + escape_path(set_dir), + escape_path(first), + escape_path(&project) + ), + _ => origin = Some(project), + } + } + Ok(origin) +} + /// The meta tree that describes the checkouts of the set at `set_dir`, whose /// config lists `projects`: the nested configs of the workspace the set was /// made from, for nested meta repos the set doesn't hold (one skipped, say), @@ -98,9 +128,7 @@ pub fn set_tree( ) -> Result> { use meta_core::config; let own = config::walk_projects(set_dir, projects, None)?; - let mut tree: Vec<_> = members - .iter() - .find_map(|member| config::recorded_project(member)) + let mut tree: Vec<_> = set_origin(set_dir, members)? .map(|dir| { let mut visited = std::collections::HashSet::new(); not_held(readable_tree(&dir, projects, &mut visited), set_dir) @@ -124,10 +152,9 @@ fn readable_tree( let path = dir.join(&project.path); let nested = config::find_meta_config_in(&path).ok().flatten(); // each meta repo once, as `walk_projects` does: links can loop - let first_visit = visited.insert(path.canonicalize().unwrap_or_else(|_| path.clone())); let children = nested .as_ref() - .filter(|_| first_visit) + .filter(|_| visited.insert(path.canonicalize().unwrap_or_else(|_| path.clone()))) .and_then(|(config, _)| config::parse_meta_config(config).ok()) .map(|(projects, _)| readable_tree(&path, &projects, visited)) .unwrap_or_default(); From 81b32cc102ff6e10d7f7ada55b0e2d9fbc182619 Mon Sep 17 00:00:00 2001 From: gsc Date: Tue, 27 Oct 2026 21:53:53 -0700 Subject: [PATCH 34/34] fix(cli): a record that can't be looked up may be meta's; no orphan advice in a set Only a NotFound record means not meta's; other errors refuse with --primary. The not-tracked hint stays quiet inside a recorded set. The set_origin error names --primary. Implements [[tasks/harmony-2793]] --- src/main.rs | 4 ++++ src/worktree.rs | 13 ++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 09bb4f0..4de3e53 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1523,6 +1523,10 @@ fn check_and_warn_orphan() { }; // Check if this meta repo is orphaned (not tracked by parent) + // A set's checkout is meta's own, not a repo its parent forgot to list + if config::set_source(&meta_dir).is_some() { + return; + } if let Some(warning) = config::check_orphan_status(&meta_dir) { eprintln!( "{}: This meta repo is not tracked by its parent.", diff --git a/src/worktree.rs b/src/worktree.rs index efff9da..617c8c2 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -104,7 +104,7 @@ fn set_origin(set_dir: &Path, members: &[PathBuf]) -> Result> { match &origin { Some(first) if *first != project => anyhow::bail!( "The checkouts of worktree set {} name different workspaces ({} and {}); \ - meta can't tell which config describes them", + meta can't tell which config describes them. Pass --primary to run in the workspace.", escape_path(set_dir), escape_path(first), escape_path(&project) @@ -224,11 +224,14 @@ pub fn holds_meta_checkout(dir: &Path) -> bool { Ok(_) => { let meta_made = meta_core::config::gitfile_target(entry.path()).is_none_or(|admin| { + // only a record that is surely absent says "not meta's" !admin.is_dir() - || admin - .join(meta_core::config::WORKTREE_RECORD_FILE) - .symlink_metadata() - .is_ok() + || !matches!( + admin + .join(meta_core::config::WORKTREE_RECORD_FILE) + .symlink_metadata(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound + ) }); if meta_made { return true;