From 1227271acea4ece3529fbd74a194f57a71d4284b Mon Sep 17 00:00:00 2001 From: barbatjuan <168854156+barbatjuan@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:55:40 +0200 Subject: [PATCH 1/5] fix(cli): refuse relative --target-dir in doctor, update, and uninstall install refused a relative or unclean --target-dir as invalid_target (#369), but doctor accepted it, probed the directory with a temporary file, and exited 0, while update reported invalid_catalog or target_absent. Every command that consumes --target-dir now runs the same validTargetDir check before reading or writing the directory, and refuses with error=invalid_target and exit 64. docs/operating.md used a relative path in its install example; it now uses an absolute one and states the shared rule. Fixes #372 --- docs/operating.md | 6 ++- internal/cli/directory_lifecycle_test.go | 61 ++++++++++++++++++++++++ internal/cli/doctor.go | 8 ++++ internal/cli/install.go | 9 +++- internal/cli/update.go | 4 ++ 5 files changed, 85 insertions(+), 3 deletions(-) diff --git a/docs/operating.md b/docs/operating.md index 2b0ba42..6972113 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,15 @@ 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 a relative or unclean `--target-dir` the same way, + before reading or writing the directory. - 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 811321e..456590f 100644 --- a/internal/cli/directory_lifecycle_test.go +++ b/internal/cli/directory_lifecycle_test.go @@ -126,3 +126,64 @@ func TestUninstallDirectoryTargetRemovesOnlyOwnedFiles(t *testing.T) { t.Fatalf("owned skill files must be removed, left: %v", leftover) } } + +// 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" + if err := os.MkdirAll(existing, 0o700); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(existing) }) + if err := os.WriteFile(filepath.Join(existing, "foreign-sentinel.txt"), []byte("user bytes"), 0o600); err != nil { + t.Fatal(err) + } + listing := func() []string { + var names []string + err := filepath.WalkDir(existing, func(path string, _ os.DirEntry, err error) error { + names = append(names, path) + return err + }) + if err != nil { + t.Fatal(err) + } + return names + } + before := listing() + // 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", "../../catalog", "--apply"}, + "uninstall": nil, + } + cwd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + // unclean is absolute and names the existing directory, so only the clean + // check can refuse it. + unclean := cwd + string(filepath.Separator) + "." + string(filepath.Separator) + existing + targets := map[string]string{"existing": existing, "missing": "relative/missing-target", "unclean": unclean} + for command, extra := range commands { + for name, target := range targets { + t.Run(command+"/"+name, func(t *testing.T) { + home := canonicalHome(t) + var stdout, stderr bytes.Buffer + args := append([]string{command, "--target-dir", target}, extra...) + code := runWithDependencies(context.Background(), args, &stdout, &stderr, nil, directoryInstallDependencies(t, home), defaultUninstallDependencies()) + if code != exitUsage || stdout.Len() != 0 || stderr.String() != "error=invalid_target\n" { + t.Fatalf("exit = %d stdout = %q stderr = %q, want %d \"\" %q", code, stdout.String(), stderr.String(), exitUsage, "error=invalid_target\n") + } + if after := listing(); strings.Join(after, "\n") != strings.Join(before, "\n") { + t.Fatalf("relative target changed: %q, want %q", after, before) + } + if _, err := os.Stat("relative"); !os.IsNotExist(err) { + t.Fatalf("missing relative target was created: %v", err) + } + }) + } + } +} diff --git a/internal/cli/doctor.go b/internal/cli/doctor.go index 14e8a70..fa79676 100644 --- a/internal/cli/doctor.go +++ b/internal/cli/doctor.go @@ -115,6 +115,10 @@ func runDoctorCommand(ctx context.Context, args []string, stdout, stderr io.Writ if targetDir == "" { return runDoctor(ctx, stdout, stderr, runner, policy, resolveRoots) } + if !validTargetDir(targetDir) { + writeError(stderr, "invalid_target") + return exitUsage + } return runDoctorDirectoryTarget(stdout, targetDir) } @@ -591,6 +595,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 dc0720c..a46d9ca 100644 --- a/internal/cli/install.go +++ b/internal/cli/install.go @@ -96,6 +96,13 @@ 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) +} + // 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,7 +112,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) { + if !validTargetDir(target) { writeError(stderr, "invalid_target") return exitUsage } diff --git a/internal/cli/update.go b/internal/cli/update.go index 01a9880..0bee5fe 100644 --- a/internal/cli/update.go +++ b/internal/cli/update.go @@ -235,6 +235,10 @@ 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 { + if !validTargetDir(targetDir) { + writeError(stderr, "invalid_target") + return exitUsage + } decision := runtimematrix.DirectoryTargetMatrix().Decisions[0] info, err := os.Stat(targetDir) if err != nil || !info.IsDir() { From ff42157a67eaa902e12454de224bf430696c608e Mon Sep 17 00:00:00 2001 From: barbatjuan <168854156+barbatjuan@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:14:54 +0200 Subject: [PATCH 2/5] fix(cli): validate an empty --target-dir instead of falling back doctor and uninstall treated `--target-dir ""` as an absent flag: doctor ran the host runtime report, and uninstall ran the canonical all-roots uninstall, so `cortex uninstall --target-dir "$TARGET"` with an unset TARGET removed every Cortex-owned skill and exited 0. update refused the same input as invalid_command. All three now track whether the flag was given and refuse an empty value with error=invalid_target, exit 64, like install. The refusal test adds the empty value, Windows path shapes (drive-relative, rooted without a drive, mixed separators), install's --target-dir= form, target-before-catalog precedence for update, and an unchanged home. Its uninstall dependencies fail the test if the canonical roots are ever resolved, so it cannot touch a real home. docs/operating.md now states exactly which inputs every command refuses and which answers stay command-specific. Refs #372 --- docs/operating.md | 7 ++- internal/cli/directory_lifecycle_test.go | 69 ++++++++++++++++++++---- internal/cli/doctor.go | 20 ++++--- internal/cli/update.go | 16 +++--- 4 files changed, 85 insertions(+), 27 deletions(-) diff --git a/docs/operating.md b/docs/operating.md index 6972113..72982f4 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -79,8 +79,11 @@ runtime=directory presence=present compatibility=compatible action=configure tou ``` - `error=invalid_target` (exit 64) — the path is missing, relative, or not a directory. - Doctor, update, and uninstall refuse a relative or unclean `--target-dir` the same way, - before reading or writing the directory. + Doctor, update, and uninstall refuse an empty, relative, or unclean `--target-dir` with the + same error before reading or writing anything; an empty value never falls back to the + runtime mode. A missing absolute target keeps each command's own answer (doctor reports + `presence=absent`, update refuses with `reason=target_absent`), 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 456590f..af3bd8d 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 @@ -127,6 +131,19 @@ 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. @@ -139,18 +156,18 @@ func TestDirectoryTargetCommandsRefuseRelativeTargets(t *testing.T) { if err := os.WriteFile(filepath.Join(existing, "foreign-sentinel.txt"), []byte("user bytes"), 0o600); err != nil { t.Fatal(err) } - listing := func() []string { + listing := func(root string) string { var names []string - err := filepath.WalkDir(existing, func(path string, _ os.DirEntry, err error) error { + 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 names + return strings.Join(names, "\n") } - before := listing() + 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{ @@ -164,26 +181,56 @@ func TestDirectoryTargetCommandsRefuseRelativeTargets(t *testing.T) { t.Fatal(err) } // unclean is absolute and names the existing directory, so only the clean - // check can refuse it. + // check can refuse it. empty is what an unset shell variable passes. unclean := cwd + string(filepath.Separator) + "." + string(filepath.Separator) + existing - targets := map[string]string{"existing": existing, "missing": "relative/missing-target", "unclean": unclean} + targets := map[string]string{"existing": existing, "missing": "relative/missing-target", "unclean": unclean, "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) - var stdout, stderr bytes.Buffer args := append([]string{command, "--target-dir", target}, extra...) - code := runWithDependencies(context.Background(), args, &stdout, &stderr, nil, directoryInstallDependencies(t, home), defaultUninstallDependencies()) - if code != exitUsage || stdout.Len() != 0 || stderr.String() != "error=invalid_target\n" { - t.Fatalf("exit = %d stdout = %q stderr = %q, want %d \"\" %q", code, stdout.String(), stderr.String(), exitUsage, "error=invalid_target\n") + 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(); strings.Join(after, "\n") != strings.Join(before, "\n") { + 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) + } + }) +} + +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() } diff --git a/internal/cli/doctor.go b/internal/cli/doctor.go index fa79676..0c9af9f 100644 --- a/internal/cli/doctor.go +++ b/internal/cli/doctor.go @@ -97,22 +97,24 @@ 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) { @@ -571,22 +573,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) diff --git a/internal/cli/update.go b/internal/cli/update.go index 0bee5fe..dc7847f 100644 --- a/internal/cli/update.go +++ b/internal/cli/update.go @@ -77,7 +77,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) @@ -138,21 +140,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, targetSet := false, false, false for len(args) > 0 { flag := args[0] args = args[1:] switch flag { case "--runtime": - if runtimeID != "" || targetDir != "" || len(args) == 0 { + if runtimeID != "" || targetSet || len(args) == 0 { return "", "", false, false, "", false } runtimeID, args = args[0], args[1:] case "--target-dir": - if targetDir != "" || runtimeID != "" || len(args) == 0 { + if targetSet || runtimeID != "" || 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 @@ -172,7 +174,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 } From 12c56622b1b2060ab181a2678751b09f85f1afa9 Mon Sep 17 00:00:00 2001 From: barbatjuan <168854156+barbatjuan@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:18:07 +0200 Subject: [PATCH 3/5] docs(cli): note that usage errors precede the --target-dir check (Refs #372) --- docs/operating.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/operating.md b/docs/operating.md index 72982f4..ff69293 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -81,7 +81,8 @@ runtime=directory presence=present compatibility=compatible action=configure tou - `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` with the same error before reading or writing anything; an empty value never falls back to the - runtime mode. A missing absolute target keeps each command's own answer (doctor reports + runtime mode. A malformed command line is still refused first as `invalid_command` (for + example `update --target-dir ` without `--catalog`). A missing absolute target keeps each command's own answer (doctor reports `presence=absent`, update refuses with `reason=target_absent`), and uninstall also refuses a filesystem root. - Update and uninstall work on the recorded ownership: From ccf3ebf50f317c9eb11516a0b6060f4dbc035e3a Mon Sep 17 00:00:00 2001 From: barbatjuan <168854156+barbatjuan@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:32:03 +0200 Subject: [PATCH 4/5] test(cli): pin trailing separators, the empty runtime, and a valid target Address the fleet review on #388: - A trailing separator (the form shell completion produces) is refused as invalid_target by every --target-dir command. On main, doctor accepted it and reported presence, update failed with the misleading invalid_catalog (exit 70), and install and uninstall already refused it; the change is pinned and named in docs/operating.md. - update --runtime "" stays a usage error, so the runtime mode never reaches the directory mode through an empty runtime ID. - A valid absolute target is still accepted (doctor control case), and TestValidTargetDir pins the check itself, including over-refusal. Refs #372 --- docs/operating.md | 3 +- internal/cli/directory_lifecycle_test.go | 46 ++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/docs/operating.md b/docs/operating.md index ff69293..a152931 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -79,7 +79,8 @@ runtime=directory presence=present compatibility=compatible action=configure tou ``` - `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` with the + 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`). A missing absolute target keeps each command's own answer (doctor reports diff --git a/internal/cli/directory_lifecycle_test.go b/internal/cli/directory_lifecycle_test.go index af3bd8d..52d5c7a 100644 --- a/internal/cli/directory_lifecycle_test.go +++ b/internal/cli/directory_lifecycle_test.go @@ -181,9 +181,11 @@ func TestDirectoryTargetCommandsRefuseRelativeTargets(t *testing.T) { t.Fatal(err) } // unclean is absolute and names the existing directory, so only the clean - // check can refuse it. empty is what an unset shell variable passes. + // 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 - targets := map[string]string{"existing": existing, "missing": "relative/missing-target", "unclean": unclean, "empty": ""} + 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 @@ -223,6 +225,46 @@ func TestDirectoryTargetCommandsRefuseRelativeTargets(t *testing.T) { 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", "../../catalog"}) + if code != exitUsage || stdout != "" || stderr != "error=invalid_command\n" { + t.Fatalf("exit = %d stdout = %q stderr = %q", code, stdout, stderr) + } + }) + // 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" From 79102dfec152b98af839dd74fa397075044bad00 Mon Sep 17 00:00:00 2001 From: Juan Barbat Date: Thu, 12 Nov 2026 17:38:21 -0300 Subject: [PATCH 5/5] fix(cli): refuse missing or non-directory update targets as invalid_target Refs #390 --- docs/operating.md | 8 +- internal/cli/directory_lifecycle_test.go | 112 ++++++++++++++++++++++- internal/cli/install.go | 14 +-- internal/cli/update.go | 16 ++-- 4 files changed, 129 insertions(+), 21 deletions(-) diff --git a/docs/operating.md b/docs/operating.md index 9d9eb94..4544507 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -83,9 +83,11 @@ runtime=directory presence=present compatibility=compatible action=configure tou 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`). A missing absolute target keeps each command's own answer (doctor reports - `presence=absent`, update refuses with `reason=target_absent`), and uninstall also - refuses a filesystem root. + 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 a581cc9..d3be827 100644 --- a/internal/cli/directory_lifecycle_test.go +++ b/internal/cli/directory_lifecycle_test.go @@ -82,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") @@ -149,10 +223,16 @@ func guardedUninstallDependencies(t *testing.T) uninstallDependencies { // 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) } - t.Cleanup(func() { _ = os.RemoveAll(existing) }) if err := os.WriteFile(filepath.Join(existing, "foreign-sentinel.txt"), []byte("user bytes"), 0o600); err != nil { t.Fatal(err) } @@ -173,13 +253,17 @@ func TestDirectoryTargetCommandsRefuseRelativeTargets(t *testing.T) { commands := map[string][]string{ "install": nil, "doctor": nil, - "update": {"--catalog", "../../catalog", "--apply"}, + "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. @@ -228,11 +312,33 @@ func TestDirectoryTargetCommandsRefuseRelativeTargets(t *testing.T) { // 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", "../../catalog"}) + 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)}) diff --git a/internal/cli/install.go b/internal/cli/install.go index a46d9ca..d2ad9e2 100644 --- a/internal/cli/install.go +++ b/internal/cli/install.go @@ -103,6 +103,13 @@ 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 @@ -112,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 !validTargetDir(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 dc7847f..b748492 100644 --- a/internal/cli/update.go +++ b/internal/cli/update.go @@ -140,18 +140,18 @@ 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, targetSet := false, 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 != "" || targetSet || 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 targetSet || runtimeID != "" || len(args) == 0 { + if targetSet || runtimeSet || len(args) == 0 { return "", "", false, false, "", false } targetDir, args, targetSet = args[0], args[1:], true @@ -239,15 +239,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 { - if !validTargetDir(targetDir) { + // 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] - info, err := os.Stat(targetDir) - if err != nil || !info.IsDir() { - return writeUpdateRefusal(stdout, decision, "target_absent") - } plan, err := buildDirectoryUpdateCandidate(targetDir, catalogDir) if err != nil { writeError(stderr, "invalid_catalog")