Skip to content
13 changes: 11 additions & 2 deletions docs/operating.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ operation=install status=completed touch=applied create=33 replace=0 remove=0 un
`cortex install --target-dir <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-<name>/SKILL.md` with `name`, `description`, `license`, and
Expand All @@ -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 <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 <dir> --catalog ./catalog [--apply]` (a target with no prior
state is refused with `reason=not_installed` instead of becoming a first install), and
Expand Down
256 changes: 256 additions & 0 deletions internal/cli/directory_lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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.
Expand Down
28 changes: 20 additions & 8 deletions internal/cli/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
Expand All @@ -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")
Expand Down
Loading
Loading