diff --git a/docs/operating.md b/docs/operating.md
index 6d56d9c..2e715e5 100644
--- a/docs/operating.md
+++ b/docs/operating.md
@@ -62,7 +62,7 @@ operation=install status=completed touch=applied create=33 replace=0 remove=0 un
`cortex install --target-dir
` projects the catalog as plain `SKILL.md` files into an
existing directory, with the same transactional guarantees as a runtime install: manifest,
ownership, backup, rollback, and readback. There is no host to probe, so there is no version
-certification step; the path must already exist and be a directory.
+certification step; the path must be absolute and clean, already exist, and be a directory.
The output follows the [Agent Skills](https://agentskills.io/) specification: each capability
lands at `skills/cortex-/SKILL.md` with `name`, `description`, `license`, and
@@ -72,13 +72,22 @@ the same way as self-contained skills; a directory target never runs `qa run` ba
adds no QA route.
```bash
-cortex install --target-dir ./agent-skills
+cortex install --target-dir "$PWD/agent-skills"
operation=install status=completed touch=applied create=33 ...
runtime=directory presence=present compatibility=compatible action=configure touch=applied
```
- `error=invalid_target` (exit 64) — the path is missing, relative, or not a directory.
+ Doctor, update, and uninstall refuse an empty, relative, or unclean `--target-dir` (a
+ trailing separator counts as unclean: pass `/path/dir`, not `/path/dir/`) with the
+ same error before reading or writing anything; an empty value never falls back to the
+ runtime mode. A malformed command line is still refused first as `invalid_command` (for
+ example `update --target-dir ` without `--catalog`). Update, like install, also
+ refuses an absolute target that is missing or not a directory as `invalid_target`
+ (exit 64): there is nothing to update. Doctor reports a missing target as
+ `presence=absent` instead of refusing it, uninstall refuses a missing target with
+ `uninstall=not_installed` and exit 3, and uninstall also refuses a filesystem root.
- Update and uninstall work on the recorded ownership:
`cortex update --target-dir --catalog ./catalog [--apply]` (a target with no prior
state is refused with `reason=not_installed` instead of becoming a first install), and
diff --git a/internal/cli/directory_lifecycle_test.go b/internal/cli/directory_lifecycle_test.go
index 53c4442..d3be827 100644
--- a/internal/cli/directory_lifecycle_test.go
+++ b/internal/cli/directory_lifecycle_test.go
@@ -3,10 +3,14 @@ package cli
import (
"bytes"
"context"
+ "errors"
"os"
"path/filepath"
+ "runtime"
"strings"
"testing"
+
+ "github.com/refactor-ia/cortex/internal/skillroot"
)
// directoryLifecycleInstall installs the shipped catalog into a target
@@ -78,6 +82,80 @@ func TestUpdateDirectoryTargetFailsClosedOnUnknownState(t *testing.T) {
}
}
+// TestUpdateDirectoryTargetRefusesMissingOrNonDirectory pins the #390 ruling:
+// update refuses an absolute target that is missing or not a directory as
+// invalid_target, the same as install, and writes nothing.
+func TestUpdateDirectoryTargetRefusesMissingOrNonDirectory(t *testing.T) {
+ for _, apply := range []bool{false, true} {
+ for _, kind := range []string{"missing", "file"} {
+ name := kind
+ if apply {
+ name += "/apply"
+ }
+ t.Run(name, func(t *testing.T) {
+ home := canonicalHome(t)
+ target := filepath.Join(home, "agent-skills")
+ if kind == "file" {
+ if err := os.WriteFile(target, []byte("user bytes"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before := homeListing(t, home)
+ args := []string{"update", "--target-dir", target, "--catalog", "../../catalog"}
+ if apply {
+ args = append(args, "--apply")
+ }
+ code, stdout, stderr := runRefusal(t, home, args)
+ if code != exitUsage || stdout != "" || stderr != invalidTargetRefusal {
+ t.Fatalf("exit = %d stdout = %q stderr = %q, want %d \"\" %q", code, stdout, stderr, exitUsage, invalidTargetRefusal)
+ }
+ if after := homeListing(t, home); after != before {
+ t.Fatalf("home changed on refusal: %q, want %q", after, before)
+ }
+ })
+ }
+ }
+}
+
+// Doctor keeps reporting a missing absolute target instead of refusing it
+// (#390): exit 0, presence=absent, and nothing created.
+func TestDoctorDirectoryTargetReportsMissingAsAbsent(t *testing.T) {
+ home := canonicalHome(t)
+ target := filepath.Join(home, "agent-skills")
+ code, stdout, stderr := runRefusal(t, home, []string{"doctor", "--target-dir", target})
+ if code != exitOK || stderr != "" || stdout != "target="+target+" presence=absent\n" {
+ t.Fatalf("exit = %d stdout = %q stderr = %q", code, stdout, stderr)
+ }
+ if _, err := os.Lstat(target); !os.IsNotExist(err) {
+ t.Fatalf("missing target must not be created: %v", err)
+ }
+}
+
+// homeListing lists every path and file content under root.
+func homeListing(t *testing.T, root string) string {
+ t.Helper()
+ var entries []string
+ err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ line := path
+ if !entry.IsDir() {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ line += "=" + string(data)
+ }
+ entries = append(entries, line)
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return strings.Join(entries, "\n")
+}
+
func TestUninstallDirectoryTargetRemovesOnlyOwnedFiles(t *testing.T) {
home := canonicalHome(t)
target := filepath.Join(home, "agent-skills")
@@ -127,6 +205,184 @@ func TestUninstallDirectoryTargetRemovesOnlyOwnedFiles(t *testing.T) {
}
}
+// guardedUninstallDependencies fails the test if a command falls back to the
+// canonical all-roots uninstall, so a refusal test can never reach the real
+// user home even when the refusal is missing.
+func guardedUninstallDependencies(t *testing.T) uninstallDependencies {
+ t.Helper()
+ deps := defaultUninstallDependencies()
+ deps.resolveRoots = func() ([]skillroot.UninstallRoot, error) {
+ t.Error("canonical uninstall roots were resolved")
+ return nil, errors.New("canonical uninstall roots must not be resolved")
+ }
+ return deps
+}
+
+// TestDirectoryTargetCommandsRefuseRelativeTargets pins issue #372: every
+// command that consumes --target-dir refuses a path install would refuse,
+// with the same diagnostic and exit code, and writes nothing.
+func TestDirectoryTargetCommandsRefuseRelativeTargets(t *testing.T) {
+ const existing = "test-relative-target-372"
+ shipped, err := filepath.Abs(filepath.Join("..", "..", "catalog"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The relative fixture lives in a temporary working directory, never in
+ // the package source tree.
+ t.Chdir(t.TempDir())
+ if err := os.MkdirAll(existing, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(existing, "foreign-sentinel.txt"), []byte("user bytes"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ listing := func(root string) string {
+ var names []string
+ err := filepath.WalkDir(root, func(path string, _ os.DirEntry, err error) error {
+ names = append(names, path)
+ return err
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return strings.Join(names, "\n")
+ }
+ before := listing(existing)
+ // Extra arguments make each command reach its target check: update gets a
+ // valid catalog and --apply so a refusal cannot come from the catalog.
+ commands := map[string][]string{
+ "install": nil,
+ "doctor": nil,
+ "update": {"--catalog", shipped, "--apply"},
+ "uninstall": nil,
+ }
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cwd, err = filepath.EvalSymlinks(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // unclean is absolute and names the existing directory, so only the clean
+ // check can refuse it. trailing-separator is the form shell completion
+ // produces. empty is what an unset shell variable passes.
+ unclean := cwd + string(filepath.Separator) + "." + string(filepath.Separator) + existing
+ trailing := filepath.Join(cwd, existing) + string(filepath.Separator)
+ targets := map[string]string{"existing": existing, "missing": "relative/missing-target", "unclean": unclean, "trailing-separator": trailing, "empty": ""}
+ if runtime.GOOS == "windows" {
+ volume := filepath.VolumeName(cwd)
+ targets["drive-relative"] = volume + existing
+ targets["rooted-without-drive"] = strings.TrimPrefix(cwd, volume) + `\` + existing
+ targets["mixed-separators"] = cwd + "/" + existing
+ }
+ for command, extra := range commands {
+ for name, target := range targets {
+ t.Run(command+"/"+name, func(t *testing.T) {
+ home := canonicalHome(t)
+ args := append([]string{command, "--target-dir", target}, extra...)
+ code, stdout, stderr := runRefusal(t, home, args)
+ if code != exitUsage || stdout != "" || stderr != invalidTargetRefusal {
+ t.Fatalf("exit = %d stdout = %q stderr = %q, want %d \"\" %q", code, stdout, stderr, exitUsage, invalidTargetRefusal)
+ }
+ if after := listing(existing); after != before {
+ t.Fatalf("relative target changed: %q, want %q", after, before)
+ }
+ if after := listing(home); after != home {
+ t.Fatalf("home changed on refusal: %q", after)
+ }
+ if _, err := os.Stat("relative"); !os.IsNotExist(err) {
+ t.Fatalf("missing relative target was created: %v", err)
+ }
+ })
+ }
+ }
+ t.Run("install/equals-form", func(t *testing.T) {
+ code, stdout, stderr := runRefusal(t, canonicalHome(t), []string{"install", "--target-dir=" + existing})
+ if code != exitUsage || stdout != "" || stderr != invalidTargetRefusal {
+ t.Fatalf("exit = %d stdout = %q stderr = %q", code, stdout, stderr)
+ }
+ })
+ t.Run("update/target-checked-before-catalog", func(t *testing.T) {
+ code, stdout, stderr := runRefusal(t, canonicalHome(t), []string{"update", "--target-dir", existing, "--catalog", "missing-catalog", "--apply"})
+ if code != exitUsage || stdout != "" || stderr != invalidTargetRefusal {
+ t.Fatalf("exit = %d stdout = %q stderr = %q", code, stdout, stderr)
+ }
+ })
+ // An explicit empty --runtime is a usage error, so the runtime mode never
+ // reaches the directory mode through an empty runtime ID.
+ t.Run("update/empty-runtime-is-a-usage-error", func(t *testing.T) {
+ code, stdout, stderr := runRefusal(t, canonicalHome(t), []string{"update", "--runtime", "", "--catalog", shipped})
+ if code != exitUsage || stdout != "" || stderr != "error=invalid_command\n" {
+ t.Fatalf("exit = %d stdout = %q stderr = %q", code, stdout, stderr)
+ }
+ })
+ // Contradictory modes are a usage error even when the runtime is empty,
+ // the same as with a non-empty runtime.
+ t.Run("update/empty-runtime-with-target-is-a-usage-error", func(t *testing.T) {
+ code, stdout, stderr := runRefusal(t, canonicalHome(t), []string{"update", "--runtime", "", "--target-dir", filepath.Join(cwd, existing), "--catalog", shipped})
+ if code != exitUsage || stdout != "" || stderr != "error=invalid_command\n" {
+ t.Fatalf("exit = %d stdout = %q stderr = %q", code, stdout, stderr)
+ }
+ })
+ // An empty first --target-dir still counts as given, so a second one is a
+ // duplicate flag rather than a silent override.
+ for command, extra := range map[string][]string{"doctor": nil, "update": {"--catalog", shipped}, "uninstall": nil} {
+ t.Run(command+"/duplicate-target-after-empty", func(t *testing.T) {
+ args := append([]string{command, "--target-dir", "", "--target-dir", filepath.Join(cwd, existing)}, extra...)
+ code, stdout, stderr := runRefusal(t, canonicalHome(t), args)
+ if code != exitUsage || stdout != "" || stderr != "error=invalid_command\n" {
+ t.Fatalf("exit = %d stdout = %q stderr = %q", code, stdout, stderr)
+ }
+ if after := listing(existing); after != before {
+ t.Fatalf("target changed: %q, want %q", after, before)
+ }
+ })
+ }
+ // Control: the shared check must not over-refuse a valid absolute target.
+ t.Run("doctor/accepts-valid-absolute", func(t *testing.T) {
+ code, stdout, stderr := runRefusal(t, canonicalHome(t), []string{"doctor", "--target-dir", filepath.Join(cwd, existing)})
+ if code != exitOK || stderr != "" || !strings.Contains(stdout, " presence=present ") {
+ t.Fatalf("exit = %d stdout = %q stderr = %q", code, stdout, stderr)
+ }
+ })
+}
+
+func TestValidTargetDir(t *testing.T) {
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ sep := string(filepath.Separator)
+ for _, test := range []struct {
+ name string
+ target string
+ want bool
+ }{
+ {"absolute clean", filepath.Join(cwd, "agent-skills"), true},
+ {"relative", "agent-skills", false},
+ {"dot relative", "." + sep + "agent-skills", false},
+ {"unclean", cwd + sep + "." + sep + "agent-skills", false},
+ {"parent element", filepath.Join(cwd, "a") + sep + ".." + sep + "agent-skills", false},
+ {"trailing separator", filepath.Join(cwd, "agent-skills") + sep, false},
+ {"empty", "", false},
+ } {
+ if got := validTargetDir(test.target); got != test.want {
+ t.Errorf("%s: validTargetDir(%q) = %v, want %v", test.name, test.target, got, test.want)
+ }
+ }
+}
+
+const invalidTargetRefusal = "error=invalid_target\n"
+
+// runRefusal runs one CLI invocation with guarded uninstall dependencies.
+func runRefusal(t *testing.T, home string, args []string) (int, string, string) {
+ t.Helper()
+ var stdout, stderr bytes.Buffer
+ code := runWithDependencies(context.Background(), args, &stdout, &stderr, nil, directoryInstallDependencies(t, home), guardedUninstallDependencies(t))
+ return code, stdout.String(), stderr.String()
+}
+
// A missing target directory trivially has no prior Cortex ownership, so
// uninstall fails closed exactly like an existing directory without
// ownership records (issue #358) and creates nothing on disk.
diff --git a/internal/cli/doctor.go b/internal/cli/doctor.go
index 2b5ed45..909b96e 100644
--- a/internal/cli/doctor.go
+++ b/internal/cli/doctor.go
@@ -97,24 +97,30 @@ func runWithDependencies(ctx context.Context, args []string, stdout, stderr io.W
// directory has no host to probe, and its presence, writability, and prior
// ownership are the whole answer to whether an install into it can proceed.
func runDoctorCommand(ctx context.Context, args []string, stdout, stderr io.Writer, runner runtimeprobe.Runner, policy runtimecompat.Policy, resolveRoots func() ([]skillroot.UninstallRoot, error)) int {
- targetDir := ""
+ targetDir, targetSet := "", false
for index := 0; index < len(args); index++ {
switch args[index] {
case "--target-dir":
- if targetDir != "" || index+1 >= len(args) {
+ if targetSet || index+1 >= len(args) {
writeError(stderr, "invalid_command")
return exitUsage
}
- targetDir = args[index+1]
+ targetDir, targetSet = args[index+1], true
index++
default:
writeError(stderr, "invalid_command")
return exitUsage
}
}
- if targetDir == "" {
+ // A given --target-dir is validated even when empty: an unset shell
+ // variable must not silently turn into the host runtime report.
+ if !targetSet {
return runDoctor(ctx, stdout, stderr, runner, policy, resolveRoots)
}
+ if !validTargetDir(targetDir) {
+ writeError(stderr, "invalid_target")
+ return exitUsage
+ }
return runDoctorDirectoryTarget(stdout, targetDir)
}
@@ -695,22 +701,24 @@ func defaultUninstallDependencies() uninstallDependencies {
// scan: exactly the directory the caller installed into is inspected, and
// only the files its ownership records name are removed.
func runUninstallCommand(args []string, stdout, stderr io.Writer, deps uninstallDependencies) int {
- targetDir := ""
+ targetDir, targetSet := "", false
for index := 0; index < len(args); index++ {
switch args[index] {
case "--target-dir":
- if targetDir != "" || index+1 >= len(args) {
+ if targetSet || index+1 >= len(args) {
writeError(stderr, "invalid_command")
return exitUsage
}
- targetDir = args[index+1]
+ targetDir, targetSet = args[index+1], true
index++
default:
writeError(stderr, "invalid_command")
return exitUsage
}
}
- if targetDir == "" {
+ // A given --target-dir is validated even when empty: an unset shell
+ // variable must never fall through to the all-roots uninstall.
+ if !targetSet {
return runUninstall(stdout, stderr, deps)
}
return runDirectoryUninstall(targetDir, stdout, stderr, deps)
@@ -719,6 +727,10 @@ func runUninstallCommand(args []string, stdout, stderr io.Writer, deps uninstall
// runDirectoryUninstall removes exactly the Cortex-owned files of one
// previously installed directory target and never touches foreign files.
func runDirectoryUninstall(targetDir string, stdout, stderr io.Writer, deps uninstallDependencies) int {
+ if !validTargetDir(targetDir) {
+ writeError(stderr, "invalid_target")
+ return exitUsage
+ }
root, err := skillroot.NewUninstallRoot(runtimematrix.RuntimeDirectory, skilldest.RootKindDirectory, targetDir)
if err != nil {
writeError(stderr, "invalid_target")
diff --git a/internal/cli/install.go b/internal/cli/install.go
index bd8488b..94895b7 100644
--- a/internal/cli/install.go
+++ b/internal/cli/install.go
@@ -96,6 +96,20 @@ func parseTargetDir(args []string) (string, bool, error) {
return "", false, nil
}
+// validTargetDir is the one path check shared by every command that consumes
+// --target-dir (issue #372): a target must be absolute and clean, so a relative
+// path never resolves against the caller's working directory.
+func validTargetDir(target string) bool {
+ return filepath.IsAbs(target) && target == filepath.Clean(target)
+}
+
+// usableTargetDir is the install and update target check: a valid path that
+// names an existing directory. The path check runs first so a relative path is
+// never stat'ed against the caller's working directory.
+func usableTargetDir(target string) bool {
+ return validTargetDir(target) && existingDirectory(target)
+}
+
// runDirectoryInstall projects the catalog into the caller-owned directory.
// The backup root stays under the user home like every other install: backups
// are a Cortex ownership artifact, and writing them inside the target would
@@ -105,12 +119,7 @@ func runDirectoryInstall(stdout, stderr io.Writer, target string, deps installDe
// malformed target shares the one explicit invalid_target diagnostic
// (issue #367): a relative path that exists on disk would otherwise pass
// the stat check below and surface as install_composition_failed.
- if !filepath.IsAbs(target) || target != filepath.Clean(target) {
- writeError(stderr, "invalid_target")
- return exitUsage
- }
- info, err := os.Stat(target)
- if err != nil || !info.IsDir() {
+ if !usableTargetDir(target) {
writeError(stderr, "invalid_target")
return exitUsage
}
diff --git a/internal/cli/update.go b/internal/cli/update.go
index e9d573b..d8a83ee 100644
--- a/internal/cli/update.go
+++ b/internal/cli/update.go
@@ -78,7 +78,9 @@ func runWithUpdateDependencies(ctx context.Context, args []string, stdout, stder
writeError(stderr, "invalid_command")
return exitUsage
}
- if targetDir != "" {
+ // The runtime mode always carries a runtime ID, so its absence means the
+ // directory mode, including an empty --target-dir value.
+ if runtimeID == "" {
return runDirectoryUpdate(stdout, stderr, targetDir, catalogDir, apply)
}
reports, err := probe(ctx, runner)
@@ -139,21 +141,21 @@ func runWithUpdateDependencies(ctx context.Context, args []string, stdout, stder
// default runtime or target. The two selection modes are mutually exclusive.
func parseUpdateArgs(args []string) (runtimematrix.RuntimeID, string, bool, bool, string, bool) {
var runtimeID, catalogDir, targetDir string
- apply, adoptGuidance := false, false
+ apply, adoptGuidance, runtimeSet, targetSet := false, false, false, false
for len(args) > 0 {
flag := args[0]
args = args[1:]
switch flag {
case "--runtime":
- if runtimeID != "" || targetDir != "" || len(args) == 0 {
+ if runtimeSet || targetSet || len(args) == 0 {
return "", "", false, false, "", false
}
- runtimeID, args = args[0], args[1:]
+ runtimeID, args, runtimeSet = args[0], args[1:], true
case "--target-dir":
- if targetDir != "" || runtimeID != "" || len(args) == 0 {
+ if targetSet || runtimeSet || len(args) == 0 {
return "", "", false, false, "", false
}
- targetDir, args = args[0], args[1:]
+ targetDir, args, targetSet = args[0], args[1:], true
case "--catalog":
if catalogDir != "" || len(args) == 0 {
return "", "", false, false, "", false
@@ -173,7 +175,9 @@ func parseUpdateArgs(args []string) (runtimematrix.RuntimeID, string, bool, bool
return "", "", false, false, "", false
}
}
- if targetDir != "" {
+ // A given --target-dir selects the directory mode even when its value is
+ // empty, so the target check refuses it rather than the runtime mode.
+ if targetSet {
if catalogDir == "" || adoptGuidance {
return "", "", false, false, "", false
}
@@ -236,11 +240,13 @@ func buildUpdateCandidate(runtimeID runtimematrix.RuntimeID, catalogDir string,
// resolved into the caller-owned root, and readiness is revalidated through
// installcoord.PreflightDirectoryTarget before any write.
func runDirectoryUpdate(stdout, stderr io.Writer, targetDir, catalogDir string, apply bool) int {
- decision := runtimematrix.DirectoryTargetMatrix().Decisions[0]
- info, err := os.Stat(targetDir)
- if err != nil || !info.IsDir() {
- return writeUpdateRefusal(stdout, decision, "target_absent")
+ // A missing or non-directory target has nothing to update, so it is
+ // refused the same way install refuses it (issue #390).
+ if !usableTargetDir(targetDir) {
+ writeError(stderr, "invalid_target")
+ return exitUsage
}
+ decision := runtimematrix.DirectoryTargetMatrix().Decisions[0]
plan, err := buildDirectoryUpdateCandidate(targetDir, catalogDir)
if err != nil {
writeError(stderr, "invalid_catalog")