Skip to content

mission control for agent skills

fix: revalidate shared scope mutations

Alvin Unreal1914b59e210d
diff --git a/internal/agents/agents.go b/internal/agents/agents.go
index 9e89e93..d033df3 100644
--- a/internal/agents/agents.go
+++ b/internal/agents/agents.go
@@ -1,6 +1,7 @@
package agents
import (
+ "fmt"
"os"
"path/filepath"
"sort"
@@ -343,55 +344,151 @@ type sharedRootResult struct {
}
// sharedRootInfo reports whether root is reached through a symlinked path
-// component below anchor. anchor is cwd for project-scope locations and the
-// user's home directory for global-scope locations.
+// component. anchor is cwd for project-scope locations and the user's home
+// directory for global-scope locations.
//
// When root sits under anchor, each path component of root strictly below
// anchor is Lstat-ed in turn; the first symlinked component means everything
// under it (including root) is shared with wherever the link resolves to.
-// A missing component means nothing below it exists either, so the walk
-// stops there and reports not-shared rather than continuing.
//
-// When root is NOT under anchor (e.g. CODEX_HOME pointing outside the home
-// directory), only root itself is Lstat-ed and reported if it is a symlink.
-// The walk deliberately does not continue up to the filesystem root in that
-// case — doing so would false-positive on system-level symlinks such as
-// macOS's /var -> /private/var.
+// When root is NOT under anchor (e.g. CODEX_HOME=/alias pointing outside the
+// home directory), every path component needed to reach root is walked from
+// the volume root so ancestor symlinks such as /alias -> ~/.claude are
+// detected even when /alias/skills itself is an ordinary directory. A normal
+// non-symlink external root remains usable.
+//
+// A missing component after an earlier symlink is never reached: the walk
+// returns shared at the first symlink. A missing component with no prior
+// symlink means the path does not exist yet and is reported not-shared.
+// Does not use EvalSymlinks.
func sharedRootInfo(root, anchor string) (link, target string, shared bool) {
root = filepath.Clean(root)
anchor = filepath.Clean(anchor)
+ if root == "" || root == "." {
+ return "", "", false
+ }
if root == anchor {
return "", "", false
}
- prefix := anchor + string(filepath.Separator)
- if !strings.HasPrefix(root, prefix) {
+
+ start := pathWalkStart(root)
+ if pathInside(root, anchor) && anchor != "" && anchor != "." {
+ // Restrict the walk to components strictly below anchor so system
+ // symlinks above the scope boundary (e.g. macOS /var -> /private/var
+ // when home lives under /var/...) are not false-positives.
+ start = anchor
+ }
+ if root == start {
+ return symlinkAt(root)
+ }
+
+ rel, err := filepath.Rel(start, root)
+ if err != nil || rel == "." || !pathInside(root, start) {
+ // Fall back to walking every absolute component of root.
+ return walkSymlinkComponents(root, pathWalkStart(root))
+ }
+ return walkSymlinkComponents(root, start)
+}
+
+// walkSymlinkComponents Lstats each path component from start down to root
+// (exclusive of start, inclusive of root). Returns at the first symlink.
+// Missing components (ErrNotExist) with no earlier symlink mean the path is
+// not a live shared root. Any other inspection error fails closed as shared.
+func walkSymlinkComponents(root, start string) (link, target string, shared bool) {
+ root = filepath.Clean(root)
+ start = filepath.Clean(start)
+ if root == start {
return symlinkAt(root)
}
- rel := strings.TrimPrefix(root, prefix)
- current := anchor
+ rel, err := filepath.Rel(start, root)
+ if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ return "", "", false
+ }
+ current := start
for _, part := range strings.Split(rel, string(filepath.Separator)) {
+ if part == "" || part == "." {
+ continue
+ }
current = filepath.Join(current, part)
info, err := os.Lstat(current)
if err != nil {
- return "", "", false
+ if os.IsNotExist(err) {
+ // Missing component with no earlier symlink: not a live shared root.
+ return "", "", false
+ }
+ // Inspection error: fail closed.
+ return current, "", true
}
if info.Mode()&os.ModeSymlink != 0 {
- return symlinkAt(current)
+ // Reuse the Lstat result; only Readlink is needed for the target.
+ return readlinkDetails(current)
}
}
return "", "", false
}
+// pathWalkStart returns the volume root used when walking absolute path
+// components of an external custom root (e.g. "/" on Unix, "C:\\" on Windows).
+func pathWalkStart(path string) string {
+ path = filepath.Clean(path)
+ vol := filepath.VolumeName(path)
+ if vol != "" {
+ // Windows volume root: "C:" + separator
+ return vol + string(filepath.Separator)
+ }
+ if filepath.IsAbs(path) {
+ return string(filepath.Separator)
+ }
+ // Relative path: walk from "." is not meaningful for shared-root
+ // detection; callers typically pass absolute roots.
+ return ""
+}
+
+// pathInside reports whether path is equal to root or a descendant of root
+// using filepath-aware containment (not raw string-prefix matching), so
+// siblings like root+"-foo" are not treated as inside root.
+func pathInside(path, root string) bool {
+ path = filepath.Clean(path)
+ root = filepath.Clean(root)
+ if path == "" || root == "" {
+ return false
+ }
+ if path == root {
+ return true
+ }
+ rel, err := filepath.Rel(root, path)
+ if err != nil {
+ return false
+ }
+ if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ return false
+ }
+ return true
+}
+
// symlinkAt reports whether path itself is a symlink, returning path as the
-// link and its resolved, cleaned target when so.
+// link and its resolved, cleaned target when so. Lstat/Readlink inspection
+// errors on a path that appears to be a symlink fail closed as shared.
func symlinkAt(path string) (link, target string, shared bool) {
info, err := os.Lstat(path)
- if err != nil || info.Mode()&os.ModeSymlink == 0 {
+ if err != nil {
+ if os.IsNotExist(err) {
+ return "", "", false
+ }
+ return path, "", true
+ }
+ if info.Mode()&os.ModeSymlink == 0 {
return "", "", false
}
+ return readlinkDetails(path)
+}
+
+// readlinkDetails resolves a path already known (via Lstat) to be a symlink.
+// Avoids a second Lstat; Readlink failures fail closed as shared.
+func readlinkDetails(path string) (link, target string, shared bool) {
raw, err := os.Readlink(path)
if err != nil {
- return "", "", false
+ return path, "", true
}
if !filepath.IsAbs(raw) {
raw = filepath.Join(filepath.Dir(path), raw)
@@ -399,16 +496,154 @@ func symlinkAt(path string) (link, target string, shared bool) {
return path, filepath.Clean(raw), true
}
+// CheckDestructivePath reports whether path is currently safe to mutate.
+// Path must sit under a known agent location root. Live checks cover:
+// 1. symlink ancestry of the matched scope root (below its anchor), and
+// 2. every path component from that root through filepath.Dir(path)
+// (nested/shelf parents such as .lazyskills-disabled).
+//
+// The final skill entry leaf may itself be a symlink and is not rejected for
+// that alone. Fail closed when the path's location is unknown or inspection
+// errors. Do not use scan-time ObservedPath.SharedRoot alone at execution time.
+func CheckDestructivePath(path, cwd string) error {
+ return CheckDestructivePathWithEnv(path, cwd, DefaultEnv())
+}
+
+// CheckDestructivePathWithEnv is CheckDestructivePath with an explicit Env
+// (for tests and callers that already have one).
+func CheckDestructivePathWithEnv(path, cwd string, e Env) error {
+ path = filepath.Clean(path)
+ if path == "" || path == "." {
+ return fmt.Errorf("path is empty or invalid")
+ }
+ locs := LocationsWithEnv(cwd, e)
+ loc, ok := locationContainingPath(path, locs)
+ if !ok {
+ return fmt.Errorf("path is outside known skill locations; refusing mutation: %s", path)
+ }
+ root := filepath.Clean(loc.Root)
+ anchor := e.Home
+ if loc.Scope == model.ScopeProject {
+ anchor = cwd
+ }
+ // Live, uncached ancestry walk for the matched scope root.
+ _, _, shared := sharedRootInfo(root, anchor)
+ if shared {
+ return fmt.Errorf("path is reached through a symlinked skills root; refusing mutation: %s", path)
+ }
+ // Live-validate nested parents below the scope root through Dir(path),
+ // excluding only the final skill entry. Catches a .lazyskills-disabled
+ // (or other intermediate) component replaced by a symlink after scan.
+ if err := checkNestedParentsSafe(path, root); err != nil {
+ return err
+ }
+ return nil
+}
+
+// checkNestedParentsSafe walks symlink components strictly below scopeRoot
+// through filepath.Dir(path). path itself (the skill entry) is not checked.
+func checkNestedParentsSafe(path, scopeRoot string) error {
+ path = filepath.Clean(path)
+ scopeRoot = filepath.Clean(scopeRoot)
+ if path == scopeRoot {
+ return nil
+ }
+ if !pathInside(path, scopeRoot) {
+ return fmt.Errorf("path is outside known skill locations; refusing mutation: %s", path)
+ }
+ parent := filepath.Dir(path)
+ if parent == path || parent == scopeRoot {
+ // Direct child of the scope root: no nested parent components.
+ return nil
+ }
+ _, _, shared := walkSymlinkComponents(parent, scopeRoot)
+ if shared {
+ return fmt.Errorf("path is reached through a symlinked skills root; refusing mutation: %s", path)
+ }
+ return nil
+}
+
+// DestructiveSkillInstallPaths returns every install path a skills CLI
+// remove/add for skillName would touch under current agent locations at the
+// given scope. Includes empty/unobserved roots. agentFilter, when non-empty,
+// restricts to those agent names; otherwise all agents at scope are included
+// (matching skills remove without --agent, which targets every known agent).
+// Fail closed when skillName is empty or no locations match.
+func DestructiveSkillInstallPaths(cwd, skillName string, scope model.Scope, agentFilter []string) ([]string, error) {
+ return DestructiveSkillInstallPathsWithEnv(cwd, skillName, scope, agentFilter, DefaultEnv())
+}
+
+// DestructiveSkillInstallPathsWithEnv is DestructiveSkillInstallPaths with an
+// explicit Env.
+func DestructiveSkillInstallPathsWithEnv(cwd, skillName string, scope model.Scope, agentFilter []string, e Env) ([]string, error) {
+ skillName = strings.TrimSpace(skillName)
+ if skillName == "" || skillName == "." || skillName == ".." {
+ return nil, fmt.Errorf("skill identity is empty or invalid")
+ }
+ // Install identity is a single path base (skills CLI sanitizeName / basename).
+ if filepath.Base(skillName) != skillName || strings.Contains(skillName, string(filepath.Separator)) {
+ return nil, fmt.Errorf("skill identity must be a single path base")
+ }
+
+ filter := map[string]bool{}
+ for _, a := range agentFilter {
+ if a != "" {
+ filter[a] = true
+ }
+ }
+ locs := LocationsWithEnv(cwd, e)
+ seen := map[string]bool{}
+ var paths []string
+ matchedLocs := 0
+ for _, loc := range locs {
+ if loc.Scope != scope {
+ continue
+ }
+ if len(filter) > 0 && !filter[loc.AgentName] {
+ continue
+ }
+ matchedLocs++
+ p := filepath.Join(filepath.Clean(loc.Root), skillName)
+ if seen[p] {
+ continue
+ }
+ seen[p] = true
+ paths = append(paths, p)
+ }
+ if matchedLocs == 0 {
+ return nil, fmt.Errorf("no agent locations match scope %s for live shared-root validation", scope)
+ }
+ if len(paths) == 0 {
+ return nil, fmt.Errorf("unable to resolve skill install paths for live shared-root validation")
+ }
+ return paths, nil
+}
+
+// locationContainingPath returns the most specific (longest root) known
+// location that contains path, if any.
+func locationContainingPath(path string, locs []Location) (Location, bool) {
+ path = filepath.Clean(path)
+ var best Location
+ found := false
+ for _, loc := range locs {
+ root := filepath.Clean(loc.Root)
+ if !pathInside(path, root) {
+ continue
+ }
+ if !found || len(root) > len(filepath.Clean(best.Root)) {
+ best = loc
+ found = true
+ }
+ }
+ return best, found
+}
+
// isUnderAnyGlobalRoot reports whether path is equal to, or nested inside, any
// of the global skills roots. Matching is path-boundary aware so that
// ~/.agents/skills-foo is not treated as inside ~/.agents/skills.
func isUnderAnyGlobalRoot(path string, roots map[string]bool) bool {
for r := range roots {
- r = filepath.Clean(r)
- if path == r {
- return true
- }
- if strings.HasPrefix(path, r+string(filepath.Separator)) {
+ if pathInside(path, r) {
return true
}
}
diff --git a/internal/agents/shared_root_test.go b/internal/agents/shared_root_test.go
index 249191a..92dfea0 100644
--- a/internal/agents/shared_root_test.go
+++ b/internal/agents/shared_root_test.go
@@ -75,7 +75,7 @@ func TestSharedRootInfoIgnoresPlainRealDirectories(t *testing.T) {
}
}
-func TestSharedRootInfoOutsideAnchorOnlyChecksRootItself(t *testing.T) {
+func TestSharedRootInfoOutsideAnchorRealDirectoryNotShared(t *testing.T) {
home := t.TempDir()
external := t.TempDir()
@@ -88,6 +88,11 @@ func TestSharedRootInfoOutsideAnchorOnlyChecksRootItself(t *testing.T) {
if _, _, shared := sharedRootInfo(realRoot, home); shared {
t.Fatalf("expected real directory outside anchor to not be flagged as shared")
}
+}
+
+func TestSharedRootInfoOutsideAnchorDetectsRootSymlink(t *testing.T) {
+ home := t.TempDir()
+ external := t.TempDir()
// A symlinked root outside anchor (e.g. CODEX_HOME pointing elsewhere):
// flagged because the root itself is a symlink.
@@ -111,6 +116,282 @@ func TestSharedRootInfoOutsideAnchorOnlyChecksRootItself(t *testing.T) {
}
}
+// TestSharedRootInfoOutsideAnchorDetectsAncestorSymlink covers the P1 case:
+// CODEX_HOME=/alias with /alias -> ~/.claude and /alias/skills an ordinary
+// directory must still be flagged shared via the ancestor symlink.
+func TestSharedRootInfoOutsideAnchorDetectsAncestorSymlink(t *testing.T) {
+ home := t.TempDir()
+ external := t.TempDir()
+
+ claudeHome := filepath.Join(external, "claude-home")
+ claudeSkills := filepath.Join(claudeHome, "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // Write a marker so we can prove canonical content is the link target.
+ if err := os.WriteFile(filepath.Join(claudeSkills, ".marker"), []byte("canonical"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ alias := filepath.Join(external, "alias")
+ if err := os.Symlink(claudeHome, alias); err != nil {
+ t.Fatal(err)
+ }
+ root := filepath.Join(alias, "skills")
+ // root itself is a real directory (reached through the alias symlink).
+ info, err := os.Lstat(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ t.Fatalf("precondition failed: %s should be a real directory, not a symlink", root)
+ }
+
+ link, target, shared := sharedRootInfo(root, home)
+ if !shared {
+ t.Fatalf("expected ancestor symlink /alias to mark %s as shared", root)
+ }
+ if link != alias {
+ t.Fatalf("expected link %q, got %q", alias, link)
+ }
+ if target != claudeHome {
+ t.Fatalf("expected target %q, got %q", claudeHome, target)
+ }
+}
+
+// TestSharedRootInfoOutsideAnchorMissingDescendantUnderSymlink still flags
+// shared when a descendant beneath an earlier symlink does not exist yet
+// (e.g. /alias -> target but /alias/skills has not been created).
+func TestSharedRootInfoOutsideAnchorMissingDescendantUnderSymlink(t *testing.T) {
+ home := t.TempDir()
+ external := t.TempDir()
+
+ targetHome := filepath.Join(external, "target-home")
+ if err := os.MkdirAll(targetHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // Deliberately do NOT create target-home/skills.
+ alias := filepath.Join(external, "alias")
+ if err := os.Symlink(targetHome, alias); err != nil {
+ t.Fatal(err)
+ }
+ root := filepath.Join(alias, "skills")
+ if _, err := os.Lstat(root); !os.IsNotExist(err) {
+ t.Fatalf("precondition: skills descendant should be missing, lstat err=%v", err)
+ }
+
+ link, gotTarget, shared := sharedRootInfo(root, home)
+ if !shared {
+ t.Fatalf("expected missing descendant beneath symlink ancestor to still be shared")
+ }
+ if link != alias {
+ t.Fatalf("expected link %q, got %q", alias, link)
+ }
+ if gotTarget != targetHome {
+ t.Fatalf("expected target %q, got %q", targetHome, gotTarget)
+ }
+}
+
+func TestPathInsideIsBoundaryAware(t *testing.T) {
+ root := filepath.Join(string(filepath.Separator), "home", "user", ".agents", "skills")
+ sibling := root + "-foo"
+ child := filepath.Join(root, "my-skill")
+ if pathInside(sibling, root) {
+ t.Fatalf("expected sibling %q not inside %q", sibling, root)
+ }
+ if !pathInside(child, root) {
+ t.Fatalf("expected child %q inside %q", child, root)
+ }
+ if !pathInside(root, root) {
+ t.Fatalf("expected path inside itself")
+ }
+}
+
+func TestCheckDestructivePathLiveSharedRoot(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ codexHome := filepath.Join(home, ".codex")
+ if err := os.MkdirAll(codexHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(claudeSkills, filepath.Join(codexHome, "skills")); err != nil {
+ t.Fatal(err)
+ }
+ skillPath := filepath.Join(codexHome, "skills", "demo")
+ if err := os.MkdirAll(skillPath, 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ e := Env{Home: home, Vars: map[string]string{}, ExistsFunc: pathExists}
+ if err := CheckDestructivePathWithEnv(skillPath, cwd, e); err == nil {
+ t.Fatal("expected shared-root skill path to be refused")
+ }
+
+ // Owned claude path remains usable.
+ owned := filepath.Join(claudeSkills, "owned")
+ if err := os.MkdirAll(owned, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := CheckDestructivePathWithEnv(owned, cwd, e); err != nil {
+ t.Fatalf("expected owned path to be allowed, got %v", err)
+ }
+}
+
+func TestCheckDestructivePathAllowsSkillEntrySymlink(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ realSkill := filepath.Join(home, "elsewhere", "real-skill")
+ if err := os.MkdirAll(realSkill, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ entry := filepath.Join(claudeSkills, "linked-skill")
+ if err := os.Symlink(realSkill, entry); err != nil {
+ t.Fatal(err)
+ }
+
+ e := Env{Home: home, Vars: map[string]string{}, ExistsFunc: pathExists}
+ // Final skill entry may be a symlink; nested parents + root ancestry are gated.
+ if err := CheckDestructivePathWithEnv(entry, cwd, e); err != nil {
+ t.Fatalf("expected skill-entry symlink under owned root to be allowed, got %v", err)
+ }
+}
+
+// TestCheckDestructivePathRejectsSymlinkedNestedParent covers a shelf/nested
+// parent (e.g. .lazyskills-disabled) that is itself a symlink while the scope
+// root remains a plain directory.
+func TestCheckDestructivePathRejectsSymlinkedNestedParent(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // Canonical shelf content elsewhere.
+ canonicalShelf := filepath.Join(home, "canonical-disabled")
+ if err := os.MkdirAll(filepath.Join(canonicalShelf, "shelved"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(canonicalShelf, "shelved", "MARKER"), []byte("canonical"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ // Scope root is real; nested .lazyskills-disabled is a symlink.
+ if err := os.Symlink(canonicalShelf, filepath.Join(claudeSkills, ".lazyskills-disabled")); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(claudeSkills, ".lazyskills-disabled", "shelved")
+ e := Env{Home: home, Vars: map[string]string{}, ExistsFunc: pathExists}
+ if err := CheckDestructivePathWithEnv(path, cwd, e); err == nil {
+ t.Fatal("expected symlinked nested shelf parent to be refused")
+ }
+ // Canonical marker must still be readable (validator is read-only).
+ if data, err := os.ReadFile(filepath.Join(canonicalShelf, "shelved", "MARKER")); err != nil || string(data) != "canonical" {
+ t.Fatalf("canonical shelf content must remain untouched, data=%q err=%v", data, err)
+ }
+}
+
+// TestLocationsWithEnvExternalCodexHomeParentAlias is the integration case:
+// CODEX_HOME points at an external alias whose parent is a symlink into
+// another agent's home; LocationsWithEnv must flag the skills root shared.
+func TestLocationsWithEnvExternalCodexHomeParentAlias(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ external := t.TempDir()
+
+ claudeHome := filepath.Join(external, "claude-home")
+ claudeSkills := filepath.Join(claudeHome, "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ alias := filepath.Join(external, "alias")
+ if err := os.Symlink(claudeHome, alias); err != nil {
+ t.Fatal(err)
+ }
+ // CODEX_HOME=/alias → skills at /alias/skills (ordinary dir via parent link).
+ codexSkills := filepath.Join(alias, "skills")
+ info, err := os.Lstat(codexSkills)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ t.Fatal("precondition: skills dir itself must not be a symlink")
+ }
+
+ e := Env{
+ Home: home,
+ Vars: map[string]string{"CODEX_HOME": alias},
+ ExistsFunc: pathExists,
+ }
+ locations := LocationsWithEnv(cwd, e)
+ found := false
+ for _, loc := range locations {
+ if loc.AgentName == "codex" && loc.Root == codexSkills && loc.Scope == model.ScopeGlobal && !loc.Canonical {
+ found = true
+ if !loc.SharedRoot {
+ t.Fatalf("expected external CODEX_HOME parent alias to mark shared, got %#v", loc)
+ }
+ if loc.SharedRootLink != alias {
+ t.Fatalf("expected shared link %q, got %#v", alias, loc)
+ }
+ }
+ }
+ if !found {
+ t.Fatalf("expected codex location at %s, got %#v", codexSkills, locations)
+ }
+
+ // Live destructive check on an install path under that root must refuse.
+ skillPath := filepath.Join(codexSkills, "demo")
+ if err := CheckDestructivePathWithEnv(skillPath, cwd, e); err == nil {
+ t.Fatal("expected destructive check to refuse path under aliased external CODEX_HOME")
+ }
+}
+
+func TestDestructiveSkillInstallPathsIncludesUnobservedRoots(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ e := Env{Home: home, Vars: map[string]string{}, ExistsFunc: pathExists}
+ // No skills installed anywhere — paths still enumerate every global root.
+ paths, err := DestructiveSkillInstallPathsWithEnv(cwd, "demo", model.ScopeGlobal, nil, e)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(paths) < 2 {
+ t.Fatalf("expected multiple global install paths including unobserved roots, got %#v", paths)
+ }
+ seenClaude, seenCodex := false, false
+ for _, p := range paths {
+ if p == filepath.Join(home, ".claude", "skills", "demo") {
+ seenClaude = true
+ }
+ if p == filepath.Join(home, ".codex", "skills", "demo") {
+ seenCodex = true
+ }
+ }
+ if !seenClaude || !seenCodex {
+ t.Fatalf("expected claude and codex install paths among %#v", paths)
+ }
+}
+
+func TestCheckDestructivePathUnknownLocationFailsClosed(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ e := Env{Home: home, Vars: map[string]string{}, ExistsFunc: pathExists}
+ orphan := filepath.Join(t.TempDir(), "orphan-skill")
+ if err := os.MkdirAll(orphan, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := CheckDestructivePathWithEnv(orphan, cwd, e); err == nil {
+ t.Fatal("expected unknown location to fail closed")
+ }
+}
+
func TestSharedRootInfoSiblingNotConfusedWithRoot(t *testing.T) {
home := t.TempDir()
anchor := filepath.Join(home, ".agents", "skills")
diff --git a/internal/scan/scan.go b/internal/scan/scan.go
index 97bee75..b6d96c3 100644
--- a/internal/scan/scan.go
+++ b/internal/scan/scan.go
@@ -260,6 +260,7 @@ func scanDisabledLocation(loc agents.Location, skills map[string]*model.Skill) {
if st, err := os.Stat(target); err != nil || !st.IsDir() {
sk := ensureSkill(skills, loc.Scope, entry.Name(), entry.Name(), "")
addObservedPath(sk, observed)
+ addSharedScopeRootIssue(sk, loc, observed.Path)
continue
}
parseDir = target
@@ -272,6 +273,7 @@ func scanDisabledLocation(loc agents.Location, skills map[string]*model.Skill) {
if err != nil {
sk := ensureSkill(skills, loc.Scope, entry.Name(), entry.Name(), "")
addObservedPath(sk, observed)
+ addSharedScopeRootIssue(sk, loc, observed.Path)
issueType := "invalid_frontmatter"
if errors.Is(err, os.ErrNotExist) {
issueType = "missing_skill_md"
@@ -288,9 +290,24 @@ func scanDisabledLocation(loc agents.Location, skills map[string]*model.Skill) {
sk.Preview = doc.Raw
}
addObservedPath(sk, observed)
+ addSharedScopeRootIssue(sk, loc, observed.Path)
}
}
+// addSharedScopeRootIssue records the shared_scope_root warning for an
+// observation reached through a symlinked scope root (active or disabled).
+func addSharedScopeRootIssue(sk *model.Skill, loc agents.Location, path string) {
+ if sk == nil || !loc.SharedRoot {
+ return
+ }
+ sk.AddHealthIssue(model.HealthIssue{
+ Type: "shared_scope_root",
+ Severity: "warning",
+ Message: sharedScopeRootMessage(loc),
+ Path: path,
+ })
+}
+
type locationScanCacheKey struct {
root string
scope model.Scope
@@ -602,14 +619,7 @@ func applyScannedLocationRecords(loc agents.Location, skills map[string]*model.S
for _, issue := range record.healthIssues {
sk.AddHealthIssue(issue)
}
- if loc.SharedRoot {
- sk.AddHealthIssue(model.HealthIssue{
- Type: "shared_scope_root",
- Severity: "warning",
- Message: sharedScopeRootMessage(loc),
- Path: observed.Path,
- })
- }
+ addSharedScopeRootIssue(sk, loc, observed.Path)
}
}
diff --git a/internal/scan/scan_test.go b/internal/scan/scan_test.go
index 688feeb..82f500a 100644
--- a/internal/scan/scan_test.go
+++ b/internal/scan/scan_test.go
@@ -847,3 +847,66 @@ func TestSharedScopeRootSymlinkFlagsOnlyTheSymlinkedAgent(t *testing.T) {
}
}
}
+
+// TestSharedScopeRootDisabledObservationGetsHealthWarning ensures disabled
+// shelf observations under a shared scope root receive the same
+// shared_scope_root health warning as active observations.
+func TestSharedScopeRootDisabledObservationGetsHealthWarning(t *testing.T) {
+ home := withHome(t)
+ cwd := t.TempDir()
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // Put the skill only on the disabled shelf under the shared codex root.
+ codexHome := filepath.Join(home, ".codex")
+ if err := os.MkdirAll(codexHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(claudeSkills, filepath.Join(codexHome, "skills")); err != nil {
+ t.Fatal(err)
+ }
+ disabled := filepath.Join(claudeSkills, ".lazyskills-disabled", "parked")
+ writeSkill(t, disabled, "Parked", "disabled shared skill")
+
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var sk *model.Skill
+ for _, s := range res.Skills {
+ if s.Name == "Parked" {
+ sk = s
+ break
+ }
+ }
+ if sk == nil {
+ t.Fatalf("expected Parked skill, got %#v", res.Skills)
+ }
+ var codexDisabled *model.ObservedPath
+ for i := range sk.ObservedPaths {
+ op := &sk.ObservedPaths[i]
+ if op.Agent == "codex" && op.Status == model.StatusDisabled {
+ codexDisabled = op
+ }
+ }
+ if codexDisabled == nil {
+ t.Fatalf("expected codex disabled observation, got %#v", sk.ObservedPaths)
+ }
+ if !codexDisabled.SharedRoot {
+ t.Fatalf("expected disabled codex observation SharedRoot, got %#v", codexDisabled)
+ }
+ found := false
+ for _, issue := range sk.HealthIssues {
+ if issue.Type == "shared_scope_root" && issue.Path == codexDisabled.Path {
+ found = true
+ if issue.Severity != "warning" {
+ t.Fatalf("expected warning severity, got %#v", issue)
+ }
+ }
+ }
+ if !found {
+ t.Fatalf("expected shared_scope_root health issue on disabled path, got %#v", sk.HealthIssues)
+ }
+}
diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go
index 76b4298..b08ea83 100644
--- a/internal/tui/tui_test.go
+++ b/internal/tui/tui_test.go
@@ -541,7 +541,7 @@ func TestBulkActionStopsOnFirstFailure(t *testing.T) {
for _, skill := range m.result.Skills {
m.selectedKeys[skillKey(skill)] = true
}
- result, partialSuccess := m.runBatch(m.currentActions()[0].Exec.Batch)
+ result, partialSuccess := m.runBatch(m.currentActions()[0].ID, m.currentActions()[0].Exec.Batch)
if calls != 1 || result.ExitCode != 2 {
t.Fatalf("expected stop on first failure, calls=%d result=%#v", calls, result)
}
@@ -591,11 +591,15 @@ func TestDeleteBrokenSymlinkPartialFailureRescans(t *testing.T) {
t.Skip("permission-denied symlink removal path is not meaningful as root")
}
cwd := t.TempDir()
- goodLink := filepath.Join(cwd, "good-broken")
+ skillsRoot := filepath.Join(cwd, ".agents", "skills")
+ if err := os.MkdirAll(skillsRoot, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ goodLink := filepath.Join(skillsRoot, "good-broken")
if err := os.Symlink(filepath.Join(cwd, "missing-good"), goodLink); err != nil {
t.Fatal(err)
}
- lockedDir := filepath.Join(cwd, "locked")
+ lockedDir := filepath.Join(skillsRoot, "locked")
if err := os.Mkdir(lockedDir, 0o755); err != nil {
t.Fatal(err)
}
@@ -644,7 +648,11 @@ func TestDeleteBrokenSymlinkFailureRescans(t *testing.T) {
t.Skip("permission-denied symlink removal path is not meaningful as root")
}
cwd := t.TempDir()
- lockedDir := filepath.Join(cwd, "locked")
+ skillsRoot := filepath.Join(cwd, ".agents", "skills")
+ if err := os.MkdirAll(skillsRoot, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ lockedDir := filepath.Join(skillsRoot, "locked")
if err := os.Mkdir(lockedDir, 0o755); err != nil {
t.Fatal(err)
}
@@ -684,8 +692,12 @@ func TestDeleteBrokenSymlinkFailureRescans(t *testing.T) {
func TestDeleteBrokenSymlinkRequiresScopedIdentity(t *testing.T) {
cwd := t.TempDir()
- projectLink := filepath.Join(cwd, "project-broken")
- globalLink := filepath.Join(cwd, "global-broken")
+ projectRoot := filepath.Join(cwd, ".agents", "skills")
+ if err := os.MkdirAll(projectRoot, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ projectLink := filepath.Join(projectRoot, "project-broken")
+ globalLink := filepath.Join(projectRoot, "global-broken")
if err := os.Symlink(filepath.Join(cwd, "missing-project"), projectLink); err != nil {
t.Fatal(err)
}
@@ -732,8 +744,12 @@ func TestDeleteBrokenSymlinkRequiresScopedIdentity(t *testing.T) {
func TestDeleteBrokenSymlinkTargetsMatchingScope(t *testing.T) {
cwd := t.TempDir()
- projectLink := filepath.Join(cwd, "project-broken")
- globalLink := filepath.Join(cwd, "global-broken")
+ projectRoot := filepath.Join(cwd, ".agents", "skills")
+ if err := os.MkdirAll(projectRoot, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ projectLink := filepath.Join(projectRoot, "project-broken")
+ globalLink := filepath.Join(projectRoot, "global-broken")
if err := os.Symlink(filepath.Join(cwd, "missing-project"), projectLink); err != nil {
t.Fatal(err)
}
@@ -767,7 +783,11 @@ func TestDeleteBrokenSymlinkTargetsMatchingScope(t *testing.T) {
func TestDeleteBrokenSymlinkRechecksPathBeforeRemove(t *testing.T) {
cwd := t.TempDir()
- restoredFile := filepath.Join(cwd, "restored-file")
+ skillsRoot := filepath.Join(cwd, ".agents", "skills")
+ if err := os.MkdirAll(skillsRoot, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ restoredFile := filepath.Join(skillsRoot, "restored-file")
if err := os.WriteFile(restoredFile, []byte("do not delete"), 0o644); err != nil {
t.Fatal(err)
}
@@ -775,11 +795,11 @@ func TestDeleteBrokenSymlinkRechecksPathBeforeRemove(t *testing.T) {
if err := os.WriteFile(restoredTarget, []byte("target"), 0o644); err != nil {
t.Fatal(err)
}
- restoredLink := filepath.Join(cwd, "restored-link")
+ restoredLink := filepath.Join(skillsRoot, "restored-link")
if err := os.Symlink(restoredTarget, restoredLink); err != nil {
t.Fatal(err)
}
- brokenLink := filepath.Join(cwd, "still-broken")
+ brokenLink := filepath.Join(skillsRoot, "still-broken")
if err := os.Symlink(filepath.Join(cwd, "missing"), brokenLink); err != nil {
t.Fatal(err)
}
@@ -818,7 +838,7 @@ func TestDeleteBrokenSymlinkRechecksPathBeforeRemove(t *testing.T) {
func TestDeleteBrokenSymlinkNoopReportsAndRescans(t *testing.T) {
cwd := t.TempDir()
- missingLink := filepath.Join(cwd, "already-gone")
+ missingLink := filepath.Join(cwd, ".agents", "skills", "already-gone")
m := appModel{cwd: cwd, width: 120, height: 32, selected: 1, result: model.ScanResult{Skills: []*model.Skill{{
Name: "Broken",
Scope: model.ScopeProject,
@@ -1118,6 +1138,10 @@ func TestExecuteRemovePrunesProjectLockEntry(t *testing.T) {
if err := os.WriteFile(lockPath, []byte(`{"version":1,"skills":{"ghost":{"source":"o/r"},"keep":{"source":"o/r"}}}`), 0o644); err != nil {
t.Fatal(err)
}
+ ghostPath := filepath.Join(dir, ".agents", "skills", "ghost")
+ if err := os.MkdirAll(ghostPath, 0o755); err != nil {
+ t.Fatal(err)
+ }
originalRunExec := runExec
runExec = func(spec runner.ExecSpec) runner.Result {
@@ -1125,7 +1149,16 @@ func TestExecuteRemovePrunesProjectLockEntry(t *testing.T) {
}
t.Cleanup(func() { runExec = originalRunExec })
- m := appModel{cwd: dir, width: 120, height: 32}
+ m := appModel{
+ cwd: dir, width: 120, height: 32,
+ result: model.ScanResult{Skills: []*model.Skill{{
+ Name: "ghost",
+ Scope: model.ScopeProject,
+ ObservedPaths: []model.ObservedPath{{
+ Path: ghostPath, Scope: model.ScopeProject, Agent: "opencode", Status: model.StatusCopy,
+ }},
+ }}},
+ }
action := actions.CommandPreview{
ID: "remove",
ConfirmValue: "ghost",
@@ -1480,19 +1513,36 @@ func TestConfirmationOverlayCopyMatchesRisk(t *testing.T) {
}
func actionTestModel(cwd string) appModel {
+ skillPath := filepath.Join(cwd, ".agents", "skills", "deploy-skill")
return appModel{cwd: cwd, width: 120, height: 32, selected: 1, result: model.ScanResult{Skills: []*model.Skill{{
Name: "Deploy Skill",
Description: "desc",
Scope: model.ScopeProject,
- CanonicalPath: "/tmp/deploy-skill",
+ CanonicalPath: skillPath,
LocalLock: &model.LocalLockEntry{Source: "owner/repo"},
+ ObservedPaths: []model.ObservedPath{{
+ Path: skillPath,
+ Scope: model.ScopeProject,
+ Agent: "opencode",
+ Status: model.StatusCopy,
+ }},
}}}}
}
func bulkActionTestModel(cwd string) appModel {
+ one := filepath.Join(cwd, ".agents", "skills", "one")
+ two := filepath.Join(cwd, ".agents", "skills", "two")
return appModel{cwd: cwd, width: 120, height: 32, selected: 1, result: model.ScanResult{Skills: []*model.Skill{
- {Name: "One", Description: "desc", Scope: model.ScopeProject, CanonicalPath: "/tmp/one", LocalLock: &model.LocalLockEntry{Source: "owner/repo"}},
- {Name: "Two", Description: "desc", Scope: model.ScopeProject, CanonicalPath: "/tmp/two", LocalLock: &model.LocalLockEntry{Source: "owner/repo"}},
+ {
+ Name: "One", Description: "desc", Scope: model.ScopeProject, CanonicalPath: one,
+ LocalLock: &model.LocalLockEntry{Source: "owner/repo"},
+ ObservedPaths: []model.ObservedPath{{Path: one, Scope: model.ScopeProject, Agent: "opencode", Status: model.StatusCopy}},
+ },
+ {
+ Name: "Two", Description: "desc", Scope: model.ScopeProject, CanonicalPath: two,
+ LocalLock: &model.LocalLockEntry{Source: "owner/repo"},
+ ObservedPaths: []model.ObservedPath{{Path: two, Scope: model.ScopeProject, Agent: "opencode", Status: model.StatusCopy}},
+ },
}}}
}
@@ -3364,7 +3414,7 @@ func TestModalCommandPickerUXWithBulkSelection(t *testing.T) {
func TestTuiEnableDisableActions(t *testing.T) {
tempDir := t.TempDir()
- skillDir := filepath.Join(tempDir, "my-skill")
+ skillDir := filepath.Join(tempDir, ".aider-desk", "skills", "my-skill")
if err := os.MkdirAll(skillDir, 0755); err != nil {
t.Fatal(err)
}
@@ -3402,7 +3452,7 @@ func TestTuiEnableDisableActions(t *testing.T) {
t.Fatal("expected loadSnapshot cmd to be returned on success")
}
- disabledPath := filepath.Join(tempDir, ".lazyskills-disabled", "my-skill")
+ disabledPath := filepath.Join(tempDir, ".aider-desk", "skills", ".lazyskills-disabled", "my-skill")
if _, err := os.Stat(disabledPath); err != nil {
t.Fatalf("expected disabled folder to exist at %s, got error: %v", disabledPath, err)
}
@@ -3435,7 +3485,7 @@ func TestTuiEnableDisableActions(t *testing.T) {
func TestTuiEnableDisableEdgeCases(t *testing.T) {
tempDir := t.TempDir()
- skillDir := filepath.Join(tempDir, "my-skill")
+ skillDir := filepath.Join(tempDir, ".aider-desk", "skills", "my-skill")
if err := os.MkdirAll(skillDir, 0755); err != nil {
t.Fatal(err)
}
@@ -3473,7 +3523,7 @@ func TestTuiEnableDisableEdgeCases(t *testing.T) {
}
// 2. Guard check: per-agent enable blocked when disabled path is shared by multiple agents
- disabledPath := filepath.Join(tempDir, ".lazyskills-disabled", "my-skill")
+ disabledPath := filepath.Join(tempDir, ".aider-desk", "skills", ".lazyskills-disabled", "my-skill")
skDisabled := &model.Skill{
Name: "my-skill",
Scope: model.ScopeProject,
@@ -3515,7 +3565,7 @@ func TestTuiEnableDisableEdgeCases(t *testing.T) {
}
// 4. Preflight validate dest already exists
- destDir := filepath.Join(tempDir, ".lazyskills-disabled", "my-skill")
+ destDir := filepath.Join(tempDir, ".aider-desk", "skills", ".lazyskills-disabled", "my-skill")
if err := os.MkdirAll(destDir, 0755); err != nil {
t.Fatal(err)
}
@@ -3680,24 +3730,44 @@ func TestSharedRootGatesSourceEnableDisableActions(t *testing.T) {
// TestSharedRootMoveHandlerRefusesRename is the defense-in-depth check on the
// exec handler itself: even if a stale or forged action offers a move whose
-// src is a shared-root path, the handler must re-check m.result.Skills and
-// abort the whole plan without renaming anything.
+// src is currently reached through a shared scope root, the handler must
+// re-check live ancestry and abort the whole plan without renaming anything.
func TestSharedRootMoveHandlerRefusesRename(t *testing.T) {
- tempDir := t.TempDir()
- skillDir := filepath.Join(tempDir, "shared-skill")
- if err := os.MkdirAll(skillDir, 0755); err != nil {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ t.Setenv("HOME", home)
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ codexHome := filepath.Join(home, ".codex")
+ if err := os.MkdirAll(codexHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(claudeSkills, filepath.Join(codexHome, "skills")); err != nil {
+ t.Fatal(err)
+ }
+ skillDir := filepath.Join(codexHome, "skills", "shared-skill")
+ if err := os.MkdirAll(skillDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ marker := filepath.Join(skillDir, "SKILL.md")
+ if err := os.WriteFile(marker, []byte("canonical"), 0o644); err != nil {
t.Fatal(err)
}
m := appModel{
- cwd: tempDir,
+ cwd: cwd,
result: model.ScanResult{
Skills: []*model.Skill{
{
Name: "shared-skill",
Scope: model.ScopeGlobal,
+ // Scan-time flag deliberately false: execution must not
+ // trust cached SharedRoot alone.
ObservedPaths: []model.ObservedPath{
- {Path: skillDir, Scope: model.ScopeGlobal, Agent: "codex", Status: model.StatusCopy, SharedRoot: true},
+ {Path: skillDir, Scope: model.ScopeGlobal, Agent: "codex", Status: model.StatusCopy, SharedRoot: false},
},
},
},
@@ -3717,14 +3787,264 @@ func TestSharedRootMoveHandlerRefusesRename(t *testing.T) {
if resAppModel.actionResult == nil || !strings.Contains(resAppModel.actionResult.Err, "symlinked") {
t.Fatalf("expected actionResult to carry a shared-root refusal, got: %+v", resAppModel.actionResult)
}
- if _, err := os.Stat(skillDir); err != nil {
- t.Fatalf("expected the shared-root directory to remain untouched, got error: %v", err)
+ if data, err := os.ReadFile(marker); err != nil || string(data) != "canonical" {
+ t.Fatalf("expected canonical content untouched, data=%q err=%v", data, err)
}
- if _, err := os.Stat(filepath.Join(tempDir, ".lazyskills-disabled", "shared-skill")); !os.IsNotExist(err) {
+ if _, err := os.Stat(filepath.Join(codexHome, "skills", ".lazyskills-disabled", "shared-skill")); !os.IsNotExist(err) {
t.Fatal("expected no disabled shelf entry to be created for the shared-root path")
}
}
+// TestLiveTopologyChangeRefusesStaleSourceAndDestMove covers the P1 case where
+// an owned scope root is replaced by a symlink after scan/preview but before
+// execution: both source and destination parent chains must be refused without
+// mutating canonical content.
+func TestLiveTopologyChangeRefusesStaleSourceAndDestMove(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ t.Setenv("HOME", home)
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // Canonical content that must not be moved.
+ canonicalSkill := filepath.Join(claudeSkills, "owned-skill")
+ if err := os.MkdirAll(canonicalSkill, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ marker := filepath.Join(canonicalSkill, "MARKER")
+ if err := os.WriteFile(marker, []byte("do-not-move"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ // At scan time codex skills is a real owned directory with its own copy.
+ codexSkills := filepath.Join(home, ".codex", "skills")
+ if err := os.MkdirAll(codexSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ skillDir := filepath.Join(codexSkills, "owned-skill")
+ if err := os.MkdirAll(skillDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(skillDir, "MARKER"), []byte("codex-copy"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ // After scan: replace the owned codex skills root with a symlink into
+ // claude's canonical skills. The skill path string is unchanged.
+ if err := os.RemoveAll(codexSkills); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(claudeSkills, codexSkills); err != nil {
+ t.Fatal(err)
+ }
+ // Through the new symlink, skillDir now resolves to canonical content.
+ if data, err := os.ReadFile(filepath.Join(skillDir, "MARKER")); err != nil || string(data) != "do-not-move" {
+ t.Fatalf("precondition: skillDir should now read canonical content, data=%q err=%v", data, err)
+ }
+
+ m := appModel{
+ cwd: cwd,
+ result: model.ScanResult{
+ Skills: []*model.Skill{{
+ Name: "owned-skill",
+ Scope: model.ScopeGlobal,
+ ObservedPaths: []model.ObservedPath{{
+ Path: skillDir, Scope: model.ScopeGlobal, Agent: "codex", Status: model.StatusCopy, SharedRoot: false,
+ }},
+ }},
+ },
+ }
+ action := actions.CommandPreview{
+ ID: "disable_skill",
+ Exec: actions.ExecSpec{Internal: "disable_skill", Args: []string{skillDir}},
+ }
+ resModel, cmd := m.executeAction(action)
+ if cmd != nil {
+ t.Fatal("expected live topology guard to refuse the move")
+ }
+ res := resModel.(appModel)
+ if res.actionResult == nil || !strings.Contains(res.actionResult.Err, "symlinked") {
+ t.Fatalf("expected symlinked-root refusal, got %#v", res.actionResult)
+ }
+ if data, err := os.ReadFile(marker); err != nil || string(data) != "do-not-move" {
+ t.Fatalf("canonical content must remain unmoved, data=%q err=%v", data, err)
+ }
+ if _, err := os.Stat(filepath.Join(claudeSkills, ".lazyskills-disabled", "owned-skill")); !os.IsNotExist(err) {
+ t.Fatal("expected no disabled shelf under the canonical root")
+ }
+}
+
+// TestLiveTopologyAllowsNormalSkillEntrySymlink ensures the final skill entry
+// may itself be a symlink under an owned root without being rejected.
+func TestLiveTopologyAllowsNormalSkillEntrySymlink(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ t.Setenv("HOME", home)
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ realSkill := filepath.Join(home, "real-skill-body")
+ if err := os.MkdirAll(realSkill, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(realSkill, "SKILL.md"), []byte("body"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ entry := filepath.Join(claudeSkills, "linked-skill")
+ if err := os.Symlink(realSkill, entry); err != nil {
+ t.Fatal(err)
+ }
+
+ m := appModel{
+ cwd: cwd,
+ result: model.ScanResult{Skills: []*model.Skill{{
+ Name: "linked-skill",
+ Scope: model.ScopeGlobal,
+ ObservedPaths: []model.ObservedPath{{
+ Path: entry, Scope: model.ScopeGlobal, Agent: "claude-code", Status: model.StatusSymlink,
+ }},
+ }}},
+ }
+ action := actions.CommandPreview{
+ ID: "disable_skill",
+ Exec: actions.ExecSpec{Internal: "disable_skill", Args: []string{entry}},
+ }
+ _, cmd := m.executeAction(action)
+ if cmd == nil {
+ t.Fatal("expected skill-entry symlink under owned root to be movable")
+ }
+ disabled := filepath.Join(claudeSkills, ".lazyskills-disabled", "linked-skill")
+ if _, err := os.Lstat(disabled); err != nil {
+ t.Fatalf("expected disabled shelf entry for skill-entry symlink, err=%v", err)
+ }
+ if _, err := os.Lstat(entry); !os.IsNotExist(err) {
+ t.Fatalf("expected active entry to be gone after disable, err=%v", err)
+ }
+ // Canonical body remains reachable via the moved symlink.
+ if _, err := os.Stat(filepath.Join(realSkill, "SKILL.md")); err != nil {
+ t.Fatalf("expected real skill body preserved, err=%v", err)
+ }
+}
+
+// TestLiveUnsafePathBlocksExternalRemoveClosure ensures remove execution does
+// not invoke runExec after a live shared-root path is detected.
+func TestLiveUnsafePathBlocksExternalRemoveClosure(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ t.Setenv("HOME", home)
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ codexHome := filepath.Join(home, ".codex")
+ if err := os.MkdirAll(codexHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(claudeSkills, filepath.Join(codexHome, "skills")); err != nil {
+ t.Fatal(err)
+ }
+ skillDir := filepath.Join(codexHome, "skills", "shared")
+ if err := os.MkdirAll(skillDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ called := false
+ old := runExec
+ runExec = func(spec runner.ExecSpec) runner.Result {
+ called = true
+ return runner.Result{Program: spec.Program, Args: spec.Args, Cwd: spec.Cwd, ExitCode: 0}
+ }
+ t.Cleanup(func() { runExec = old })
+
+ m := appModel{
+ cwd: cwd,
+ result: model.ScanResult{Skills: []*model.Skill{{
+ Name: "shared",
+ Scope: model.ScopeGlobal,
+ ObservedPaths: []model.ObservedPath{{
+ Path: skillDir, Scope: model.ScopeGlobal, Agent: "codex", Status: model.StatusCopy, SharedRoot: false,
+ }},
+ }}},
+ }
+ action := actions.CommandPreview{
+ ID: "remove",
+ ConfirmValue: "shared",
+ Mutates: true,
+ Exec: actions.ExecSpec{Program: "skills", Args: []string{"remove", "shared", "--yes", "-g"}},
+ }
+ resModel, cmd := m.executeAction(action)
+ if cmd != nil {
+ // Synchronous refusal should not schedule a command.
+ t.Fatal("expected external remove to be refused before scheduling runExec")
+ }
+ res := resModel.(appModel)
+ if res.actionResult == nil || !strings.Contains(res.actionResult.Err, "symlinked") {
+ t.Fatalf("expected shared-root refusal, got %#v", res.actionResult)
+ }
+ if called {
+ t.Fatal("runExec must not run after live unsafe path detection")
+ }
+}
+
+// TestLiveUnsafePathBlocksBulkExecutionClosure ensures bulk execution validates
+// upfront and does not run any batch command when a live unsafe path is found.
+func TestLiveUnsafePathBlocksBulkExecutionClosure(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ t.Setenv("HOME", home)
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ codexHome := filepath.Join(home, ".codex")
+ if err := os.MkdirAll(codexHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(claudeSkills, filepath.Join(codexHome, "skills")); err != nil {
+ t.Fatal(err)
+ }
+ skillDir := filepath.Join(codexHome, "skills", "shared")
+ if err := os.MkdirAll(skillDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ calls := 0
+ old := runExec
+ runExec = func(spec runner.ExecSpec) runner.Result {
+ calls++
+ return runner.Result{Program: spec.Program, Args: spec.Args, Cwd: spec.Cwd, ExitCode: 0}
+ }
+ t.Cleanup(func() { runExec = old })
+
+ m := appModel{
+ cwd: cwd,
+ result: model.ScanResult{Skills: []*model.Skill{{
+ Name: "shared",
+ Scope: model.ScopeGlobal,
+ ObservedPaths: []model.ObservedPath{{
+ Path: skillDir, Scope: model.ScopeGlobal, Agent: "codex", Status: model.StatusCopy,
+ }},
+ }}},
+ }
+ batch := []actions.ExecSpec{{Program: "skills", Args: []string{"remove", "shared", "--yes", "-g"}}}
+ result, partial := m.runBatch("bulk_remove", batch)
+ if result.ExitCode == 0 || !strings.Contains(result.Err, "symlinked") {
+ t.Fatalf("expected bulk upfront refusal, got %#v", result)
+ }
+ if partial {
+ t.Fatal("upfront refusal must not count as partial success")
+ }
+ if calls != 0 {
+ t.Fatalf("expected no batch commands to run, calls=%d", calls)
+ }
+}
+
func TestTUIPreviewRenderInFlightSuppression(t *testing.T) {
m := appModel{
width: 120,
@@ -4047,3 +4367,268 @@ func TestTUIPreviewRenderIgnoresCompletionWhenNewerRenderInFlight(t *testing.T)
t.Fatalf("expected no duplicate dispatch while newer render remains in flight, got %v", cmd)
}
}
+
+// TestMoveRejectsSymlinkedNestedShelfParent ensures a .lazyskills-disabled
+// parent that is a symlink is refused and canonical shelf content is untouched.
+func TestMoveRejectsSymlinkedNestedShelfParent(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ t.Setenv("HOME", home)
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ skillDir := filepath.Join(claudeSkills, "shelved-skill")
+ if err := os.MkdirAll(skillDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(skillDir, "MARKER"), []byte("src"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ // Destination parent chain: scope root is real, but .lazyskills-disabled
+ // is a symlink into a canonical shelf elsewhere.
+ canonicalShelf := filepath.Join(home, "other-agent-disabled")
+ if err := os.MkdirAll(canonicalShelf, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(canonicalShelf, "KEEP"), []byte("canonical"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(canonicalShelf, filepath.Join(claudeSkills, ".lazyskills-disabled")); err != nil {
+ t.Fatal(err)
+ }
+
+ m := appModel{cwd: cwd}
+ action := actions.CommandPreview{
+ ID: "disable_skill",
+ Exec: actions.ExecSpec{Internal: "disable_skill", Args: []string{skillDir}},
+ }
+ resModel, cmd := m.executeAction(action)
+ if cmd != nil {
+ t.Fatal("expected move to refuse symlinked nested shelf parent")
+ }
+ res := resModel.(appModel)
+ if res.actionResult == nil || !strings.Contains(res.actionResult.Err, "symlinked") {
+ t.Fatalf("expected symlinked refusal, got %#v", res.actionResult)
+ }
+ if data, err := os.ReadFile(filepath.Join(skillDir, "MARKER")); err != nil || string(data) != "src" {
+ t.Fatalf("source must remain, data=%q err=%v", data, err)
+ }
+ if data, err := os.ReadFile(filepath.Join(canonicalShelf, "KEEP")); err != nil || string(data) != "canonical" {
+ t.Fatalf("canonical shelf must remain untouched, data=%q err=%v", data, err)
+ }
+ // No skill entry should have been created under the aliased shelf.
+ if _, err := os.Stat(filepath.Join(canonicalShelf, "shelved-skill")); !os.IsNotExist(err) {
+ t.Fatal("expected no skill entry under canonical aliased shelf")
+ }
+}
+
+// TestMoveRejectsTopologySwapBeforeMkdirAll swaps the destination scope root
+// to a symlink after preflight has passed, on the first execution-time check
+// (before MkdirAll). MkdirAll must not create directories under the canonical
+// target, and the rename must not run.
+func TestMoveRejectsTopologySwapBeforeMkdirAll(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ t.Setenv("HOME", home)
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // Canonical tree that must not receive mkdir/rename side effects.
+ if err := os.WriteFile(filepath.Join(claudeSkills, "CANONICAL"), []byte("keep"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ codexSkills := filepath.Join(home, ".codex", "skills")
+ if err := os.MkdirAll(codexSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ skillDir := filepath.Join(codexSkills, "move-me")
+ if err := os.MkdirAll(skillDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(skillDir, "MARKER"), []byte("codex"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ // Preflight sees a safe owned root. On the first execution-time
+ // checkDestructivePath call (before MkdirAll), replace codex skills with
+ // a symlink into claude's canonical skills.
+ calls := 0
+ old := checkDestructivePath
+ checkDestructivePath = func(path, checkCwd string) error {
+ calls++
+ // Preflight: src + dest = 2 calls. Third call is first execution check.
+ if calls == 3 {
+ if err := os.RemoveAll(codexSkills); err != nil {
+ t.Fatalf("swap remove: %v", err)
+ }
+ if err := os.Symlink(claudeSkills, codexSkills); err != nil {
+ t.Fatalf("swap symlink: %v", err)
+ }
+ }
+ return old(path, checkCwd)
+ }
+ t.Cleanup(func() { checkDestructivePath = old })
+
+ m := appModel{cwd: cwd}
+ action := actions.CommandPreview{
+ ID: "disable_skill",
+ Exec: actions.ExecSpec{Internal: "disable_skill", Args: []string{skillDir}},
+ }
+ resModel, cmd := m.executeAction(action)
+ if cmd != nil {
+ t.Fatal("expected topology-swap guard to refuse before/without successful move")
+ }
+ res := resModel.(appModel)
+ if res.actionResult == nil || !strings.Contains(res.actionResult.Err, "symlinked") {
+ t.Fatalf("expected symlinked refusal after topology swap, got %#v", res.actionResult)
+ }
+ // Canonical tree must not have gained a disabled shelf from MkdirAll.
+ if _, err := os.Stat(filepath.Join(claudeSkills, ".lazyskills-disabled")); !os.IsNotExist(err) {
+ t.Fatal("MkdirAll must not create .lazyskills-disabled under the canonical target after topology swap")
+ }
+ if data, err := os.ReadFile(filepath.Join(claudeSkills, "CANONICAL")); err != nil || string(data) != "keep" {
+ t.Fatalf("canonical marker must remain, data=%q err=%v", data, err)
+ }
+}
+
+// TestExternalRemoveValidatesUnobservedAliasedRoot covers: only one observed
+// safe root exists in scan results, but an unobserved agent root that the
+// skills CLI would still target becomes an alias before execution — runExec
+// must not be invoked.
+func TestExternalRemoveValidatesUnobservedAliasedRoot(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ t.Setenv("HOME", home)
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ skillDir := filepath.Join(claudeSkills, "only-claude")
+ if err := os.MkdirAll(skillDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(skillDir, "MARKER"), []byte("safe"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ // Codex root starts as a real empty directory (unobserved — skill not there).
+ codexSkills := filepath.Join(home, ".codex", "skills")
+ if err := os.MkdirAll(codexSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ // After "scan": alias the unobserved codex root into claude's tree.
+ if err := os.RemoveAll(codexSkills); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(claudeSkills, codexSkills); err != nil {
+ t.Fatal(err)
+ }
+
+ called := false
+ old := runExec
+ runExec = func(spec runner.ExecSpec) runner.Result {
+ called = true
+ return runner.Result{Program: spec.Program, Args: spec.Args, Cwd: spec.Cwd, ExitCode: 0}
+ }
+ t.Cleanup(func() { runExec = old })
+
+ m := appModel{
+ cwd: cwd,
+ // Stale observations: only the safe claude path is known.
+ result: model.ScanResult{Skills: []*model.Skill{{
+ Name: "only-claude",
+ Scope: model.ScopeGlobal,
+ ObservedPaths: []model.ObservedPath{{
+ Path: skillDir, Scope: model.ScopeGlobal, Agent: "claude-code", Status: model.StatusCopy, SharedRoot: false,
+ }},
+ }}},
+ }
+ action := actions.CommandPreview{
+ ID: "remove",
+ ConfirmValue: "only-claude",
+ Mutates: true,
+ Exec: actions.ExecSpec{Program: "skills", Args: []string{"remove", "only-claude", "--yes", "-g"}},
+ }
+ resModel, cmd := m.executeAction(action)
+ if cmd != nil {
+ t.Fatal("expected remove to refuse due to unobserved aliased agent root")
+ }
+ res := resModel.(appModel)
+ if res.actionResult == nil || !strings.Contains(res.actionResult.Err, "symlinked") {
+ t.Fatalf("expected shared-root refusal from unobserved aliased root, got %#v", res.actionResult)
+ }
+ if called {
+ t.Fatal("runExec must not run when an unobserved targeted root is live-unsafe")
+ }
+ if data, err := os.ReadFile(filepath.Join(skillDir, "MARKER")); err != nil || string(data) != "safe" {
+ t.Fatalf("canonical skill must remain, data=%q err=%v", data, err)
+ }
+}
+
+// TestBrokenLinkDeleteRejectsSymlinkedNestedParent ensures broken-link
+// deletion refuses when a parent below the scope root is a symlink.
+func TestBrokenLinkDeleteRejectsSymlinkedNestedParent(t *testing.T) {
+ home := t.TempDir()
+ cwd := t.TempDir()
+ t.Setenv("HOME", home)
+
+ claudeSkills := filepath.Join(home, ".claude", "skills")
+ if err := os.MkdirAll(claudeSkills, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // Nested parent becomes a symlink to a canonical directory holding a
+ // broken link name that must not be deleted through the alias.
+ canonicalNest := filepath.Join(home, "canonical-nest")
+ if err := os.MkdirAll(canonicalNest, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ brokenInCanonical := filepath.Join(canonicalNest, "broken-link")
+ if err := os.Symlink(filepath.Join(home, "missing-target"), brokenInCanonical); err != nil {
+ t.Fatal(err)
+ }
+ nestLink := filepath.Join(claudeSkills, "nested")
+ if err := os.Symlink(canonicalNest, nestLink); err != nil {
+ t.Fatal(err)
+ }
+ // Path as observed through the owned scope root.
+ observedBroken := filepath.Join(nestLink, "broken-link")
+
+ m := appModel{
+ cwd: cwd,
+ result: model.ScanResult{Skills: []*model.Skill{{
+ Name: "Broken",
+ Scope: model.ScopeGlobal,
+ ObservedPaths: []model.ObservedPath{{
+ Path: observedBroken, Scope: model.ScopeGlobal, Agent: "claude-code", Status: model.StatusBrokenSymlink, SharedRoot: false,
+ }},
+ }}},
+ }
+ action := actions.CommandPreview{
+ ID: "delete_broken_symlink",
+ ConfirmValue: "Broken",
+ Exec: actions.ExecSpec{Internal: "delete_broken_symlink", Args: []string{string(model.ScopeGlobal), "Broken"}},
+ }
+ updated, cmd := m.executeAction(action)
+ next := updated.(appModel)
+ if next.actionResult == nil || next.actionResult.ExitCode != -1 {
+ t.Fatalf("expected failed delete due to symlinked nested parent, got %#v", next.actionResult)
+ }
+ if !strings.Contains(next.actionResult.Err, "symlinked") {
+ t.Fatalf("expected symlinked reason, got %#v", next.actionResult)
+ }
+ // Broken link under canonical nest must remain.
+ if _, err := os.Lstat(brokenInCanonical); err != nil {
+ t.Fatalf("expected canonical broken link to remain, err=%v", err)
+ }
+ // cmd may still rescan on failure paths; either way the link stays.
+ if cmd != nil {
+ _, _ = next.Update(cmd())
+ }
+ if _, err := os.Lstat(brokenInCanonical); err != nil {
+ t.Fatalf("expected canonical broken link to remain after handler, err=%v", err)
+ }
+}
diff --git a/internal/tui/update.go b/internal/tui/update.go
index 780492e..b5ed658 100644
--- a/internal/tui/update.go
+++ b/internal/tui/update.go
@@ -14,6 +14,7 @@ import (
tea "github.com/charmbracelet/bubbletea"
"github.com/alvinunreal/lazyskills/internal/actions"
+ "github.com/alvinunreal/lazyskills/internal/agents"
"github.com/alvinunreal/lazyskills/internal/compat"
"github.com/alvinunreal/lazyskills/internal/locks"
"github.com/alvinunreal/lazyskills/internal/model"
@@ -21,6 +22,10 @@ import (
"github.com/alvinunreal/lazyskills/internal/runner"
)
+// checkDestructivePath is the live, uncached shared-root path validator used
+// immediately before filesystem mutations. Tests may replace it.
+var checkDestructivePath = agents.CheckDestructivePath
+
const previewRefreshDelay = 300 * time.Millisecond
type previewRefreshMsg struct {
@@ -1426,24 +1431,18 @@ func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.C
}
// safety: never move a path reached through a symlinked, shared scope
- // root. The preview builders already refuse to offer these, but this
- // re-checks live observations from the current scan so a stale or
- // forged action can't bypass the gate and mutate a canonical repo
- // shared by other agents.
- sharedRootPaths := map[string]bool{}
- for _, sk := range m.result.Skills {
- for _, obs := range sk.ObservedPaths {
- if obs.SharedRoot {
- sharedRootPaths[obs.Path] = true
- }
- }
- }
-
+ // root. Preview builders refuse these using scan-time observations, but
+ // execution re-validates live ancestry (not cached SharedRoot) so a
+ // topology change after the last scan cannot mutate a canonical repo.
// Preflight validation
var errs []string
for _, item := range plan {
- if sharedRootPaths[item.src] {
- errs = append(errs, fmt.Sprintf("path is reached through a symlinked skills root; refusing to move: %s", compat.SanitizeMetadata(item.src)))
+ if err := checkDestructivePath(item.src, m.cwd); err != nil {
+ errs = append(errs, compat.SanitizeMetadata(err.Error()))
+ continue
+ }
+ if err := checkDestructivePath(item.dest, m.cwd); err != nil {
+ errs = append(errs, compat.SanitizeMetadata(err.Error()))
continue
}
// Check if source exists
@@ -1473,13 +1472,31 @@ func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.C
succeededMoves := 0
if len(errs) == 0 {
- // Execution
+ // Execution: re-validate live ancestry immediately before MkdirAll
+ // (so a topology swap cannot create dirs under a canonical target)
+ // and again after MkdirAll before Rename.
for _, item := range plan {
parent := filepath.Dir(item.dest)
+ if err := checkDestructivePath(item.src, m.cwd); err != nil {
+ errs = append(errs, compat.SanitizeMetadata(err.Error()))
+ break
+ }
+ if err := checkDestructivePath(item.dest, m.cwd); err != nil {
+ errs = append(errs, compat.SanitizeMetadata(err.Error()))
+ break
+ }
if err := os.MkdirAll(parent, 0755); err != nil {
errs = append(errs, fmt.Sprintf("failed to create directory %s: %v", parent, err))
break
}
+ if err := checkDestructivePath(item.src, m.cwd); err != nil {
+ errs = append(errs, compat.SanitizeMetadata(err.Error()))
+ break
+ }
+ if err := checkDestructivePath(item.dest, m.cwd); err != nil {
+ errs = append(errs, compat.SanitizeMetadata(err.Error()))
+ break
+ }
if err := os.Rename(item.src, item.dest); err != nil {
errs = append(errs, fmt.Sprintf("failed to move %s to %s: %v", item.src, item.dest, err))
break
@@ -1551,7 +1568,21 @@ func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.C
continue // safety: never touch working symlinks or canonical files
}
if op.SharedRoot {
- continue // safety: never delete symlinks reached through a shared scope root
+ // Scan-time shared roots are not part of the owned delete
+ // set (preview already gated them). Skip without counting
+ // as failure; live check below still covers owned paths
+ // whose topology changed after the scan.
+ continue
+ }
+ // Live ancestry check: refuse when the path is currently
+ // reached through a shared scope root, or when location/
+ // inspection fails closed.
+ if err := checkDestructivePath(op.Path, m.cwd); err != nil {
+ failed++
+ if firstErr == "" {
+ firstErr = err.Error()
+ }
+ continue
}
info, err := os.Lstat(op.Path)
if err != nil {
@@ -1582,6 +1613,14 @@ func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.C
}
continue
}
+ // Re-check immediately before the unlink.
+ if err := checkDestructivePath(op.Path, m.cwd); err != nil {
+ failed++
+ if firstErr == "" {
+ firstErr = err.Error()
+ }
+ continue
+ }
if err := os.Remove(op.Path); err != nil {
failed++
if firstErr == "" {
@@ -1628,6 +1667,19 @@ func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.C
return m, loadSnapshot(m.cwd)
}
if action.Exec.Interactive {
+ if err := m.validateExternalDestructiveAction(action); err != nil {
+ m.confirming = false
+ m.confirmInput = ""
+ m.confirmError = ""
+ m.actionResult = &runner.Result{
+ Program: action.Exec.Program,
+ Args: action.Exec.Args,
+ ExitCode: -1,
+ Err: compat.SanitizeMetadata(err.Error()),
+ }
+ m.syncViewport()
+ return m, nil
+ }
cmd := exec.Command(action.Exec.Program, action.Exec.Args...)
cmd.Dir = m.cwd
m.running = true
@@ -1656,11 +1708,24 @@ func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.C
m.confirmError = ""
m.syncViewport()
return m, func() tea.Msg {
- result, partialSuccess := m.runBatch(action.Exec.Batch)
+ result, partialSuccess := m.runBatch(action.ID, action.Exec.Batch)
return actionResultMsg{result: result, mutates: action.Mutates, partialSuccess: partialSuccess}
}
}
spec := runner.ExecSpec{Program: action.Exec.Program, Args: action.Exec.Args, Cwd: m.cwd}
+ if err := m.validateExternalDestructiveAction(action); err != nil {
+ m.confirming = false
+ m.confirmInput = ""
+ m.confirmError = ""
+ m.actionResult = &runner.Result{
+ Program: action.Exec.Program,
+ Args: action.Exec.Args,
+ ExitCode: -1,
+ Err: compat.SanitizeMetadata(err.Error()),
+ }
+ m.syncViewport()
+ return m, nil
+ }
m.running = true
m.runningTitle = action.Title
m.actionResult = nil
@@ -1669,6 +1734,20 @@ func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.C
m.confirmError = ""
m.syncViewport()
return m, func() tea.Msg {
+ // Re-validate immediately before the external command runs so a
+ // topology change after confirmation cannot mutate a shared root.
+ if err := m.validateExternalDestructiveAction(action); err != nil {
+ return actionResultMsg{
+ result: runner.Result{
+ Program: action.Exec.Program,
+ Args: action.Exec.Args,
+ Cwd: m.cwd,
+ ExitCode: -1,
+ Err: compat.SanitizeMetadata(err.Error()),
+ },
+ mutates: false,
+ }
+ }
result := runExec(spec)
partialSuccess := cleanupLockAfterRemove(action, m.cwd, &result)
return actionResultMsg{result: result, mutates: action.Mutates, partialSuccess: partialSuccess}
@@ -1708,13 +1787,39 @@ func cleanupLockAfterRemove(action actions.CommandPreview, cwd string, result *r
return false
}
-func (m appModel) runBatch(batch []actions.ExecSpec) (runner.Result, bool) {
+func (m appModel) runBatch(actionID string, batch []actions.ExecSpec) (runner.Result, bool) {
+ // Upfront live validation of every batch item before any mutation.
+ if isExternalDestructiveActionID(actionID) {
+ for _, spec := range batch {
+ if err := m.validateExternalDestructiveSpec(actionID, spec); err != nil {
+ return runner.Result{
+ Program: "bulk",
+ Cwd: m.cwd,
+ ExitCode: -1,
+ Err: compat.SanitizeMetadata(err.Error()),
+ }, false
+ }
+ }
+ }
+
lines := []string{}
succeeded := 0
for i, spec := range batch {
+ prefix := fmt.Sprintf("%d/%d %s", i+1, len(batch), compat.SanitizeMetadata(spec.Program))
+ // Re-validate immediately before each command runs.
+ if isExternalDestructiveActionID(actionID) {
+ if err := m.validateExternalDestructiveSpec(actionID, spec); err != nil {
+ return runner.Result{
+ Program: "bulk",
+ Cwd: m.cwd,
+ ExitCode: -1,
+ Err: compat.SanitizeMetadata(err.Error()),
+ Stdout: strings.Join(append(lines, prefix+" failed"), "\n"),
+ }, succeeded > 0
+ }
+ }
runSpec := runner.ExecSpec{Program: spec.Program, Args: spec.Args, Cwd: m.cwd}
result := runExec(runSpec)
- prefix := fmt.Sprintf("%d/%d %s", i+1, len(batch), compat.SanitizeMetadata(spec.Program))
if result.ExitCode != 0 || result.Err != "" {
result.Stdout = strings.Join(append(lines, prefix+" failed"), "\n")
return result, succeeded > 0
@@ -1725,6 +1830,140 @@ func (m appModel) runBatch(batch []actions.ExecSpec) (runner.Result, bool) {
return runner.Result{Program: "bulk", Cwd: m.cwd, ExitCode: 0, Stdout: strings.Join(lines, "\n")}, false
}
+// isExternalDestructiveActionID reports whether actionID is a PR #38-protected
+// external remove/reinstall (single or bulk) that must re-validate live
+// shared-root ancestry before execution.
+func isExternalDestructiveActionID(id string) bool {
+ switch id {
+ case "remove", "reinstall_update", "bulk_remove", "bulk_reinstall_update":
+ return true
+ default:
+ return false
+ }
+}
+
+func (m appModel) validateExternalDestructiveAction(action actions.CommandPreview) error {
+ if !isExternalDestructiveActionID(action.ID) {
+ return nil
+ }
+ if len(action.Exec.Batch) > 0 {
+ for _, spec := range action.Exec.Batch {
+ if err := m.validateExternalDestructiveSpec(action.ID, spec); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return m.validateExternalDestructiveSpec(action.ID, action.Exec)
+}
+
+func (m appModel) validateExternalDestructiveSpec(actionID string, spec actions.ExecSpec) error {
+ skillName, scope, agentFilter, err := parseExternalDestructiveSpec(actionID, spec)
+ if err != nil {
+ return err
+ }
+ // Validate every current agent location the skills CLI would touch for
+ // this scope/agent selection — including empty/unobserved roots — via
+ // live location data, not stale scan observations.
+ paths, err := agents.DestructiveSkillInstallPaths(m.cwd, skillName, scope, agentFilter)
+ if err != nil {
+ return err
+ }
+ for _, p := range paths {
+ if err := checkDestructivePath(p, m.cwd); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// parseExternalDestructiveSpec extracts skill identity, scope, and optional
+// agent filter from a skills CLI remove/add ExecSpec. Fail closed on
+// unresolvable or ambiguous identity.
+func parseExternalDestructiveSpec(actionID string, spec actions.ExecSpec) (skillName string, scope model.Scope, agentFilter []string, err error) {
+ args := spec.Args
+ global := execArgsContain(args, "-g") || execArgsContain(args, "--global")
+ if global {
+ scope = model.ScopeGlobal
+ } else {
+ scope = model.ScopeProject
+ }
+ agentFilter = agentsFromArgs(args)
+
+ switch {
+ case actionID == "remove" || actionID == "bulk_remove" || execArgsContain(args, "remove"):
+ skillName = removeTargetFromArgs(args)
+ if skillName == "" {
+ return "", "", nil, fmt.Errorf("remove action is missing skill identity")
+ }
+ case actionID == "reinstall_update" || actionID == "bulk_reinstall_update" || execArgsContain(args, "add"):
+ skillName = argAfter(args, "--skill")
+ if skillName == "" {
+ return "", "", nil, fmt.Errorf("reinstall action is missing --skill identity")
+ }
+ default:
+ return "", "", nil, fmt.Errorf("unsupported destructive action %s", actionID)
+ }
+ return skillName, scope, agentFilter, nil
+}
+
+func execArgsContain(args []string, want string) bool {
+ for _, a := range args {
+ if a == want {
+ return true
+ }
+ }
+ return false
+}
+
+func argAfter(args []string, flag string) string {
+ for i := 0; i+1 < len(args); i++ {
+ if args[i] == flag {
+ return args[i+1]
+ }
+ }
+ return ""
+}
+
+// agentsFromArgs collects --agent values from a skills CLI argv. Supports
+// repeated --agent name flags. Bare --agent without a value fails closed via
+// empty filter only when no names were provided (caller treats empty as all).
+func agentsFromArgs(args []string) []string {
+ var out []string
+ for i := 0; i < len(args); i++ {
+ a := args[i]
+ switch {
+ case a == "--agent" || a == "-a":
+ if i+1 >= len(args) || strings.HasPrefix(args[i+1], "-") {
+ // Malformed agent selection: return a sentinel that matches
+ // no location so validation fails closed.
+ return []string{"\x00"}
+ }
+ i++
+ out = append(out, args[i])
+ case strings.HasPrefix(a, "--agent="):
+ v := strings.TrimPrefix(a, "--agent=")
+ if v == "" {
+ return []string{"\x00"}
+ }
+ out = append(out, v)
+ }
+ }
+ return out
+}
+
+func removeTargetFromArgs(args []string) string {
+ for i := 0; i+1 < len(args); i++ {
+ if args[i] == "remove" {
+ t := args[i+1]
+ if t != "" && !strings.HasPrefix(t, "-") {
+ return t
+ }
+ }
+ }
+ return ""
+}
+
func (m appModel) appendEnableDisableActions(previews []actions.CommandPreview, sk *model.Skill) []actions.CommandPreview {
if sk == nil {
return previews