Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6000 fix(daemon): link user Codex skills into codex-home instead of copying them (#6742)
Bohan Jianga1da8e536fad
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 6185115bee..585fdfebc7 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -408,6 +408,25 @@ jobs:# silently as "ok".run: go test ./internal/daemon/repocache -v -run '^(TestIsolatedCheckoutIsCommittableOnWindows|TestIsolatedCheckoutAcrossVolumesOnWindows)$' -count=1 -timeout=5m+ - name: Test Windows directory-junction link safety+ working-directory: server+ # MUL-6000: the per-task codex-home links the user's real skills into+ # the task directory instead of copying them. On Windows that link is a+ # directory junction whenever os.Symlink is denied (no Developer Mode),+ # and a junction is the one link shape a ModeSymlink check misses:+ # since Go 1.23 os.Lstat reports it as ModeDir|ModeIrregular with no+ # ModeSymlink bit, while its DirEntry still answers IsDir() == true, so+ # filepath.WalkDir descends into the target. Two claims about Windows+ # itself cannot be made on ubuntu: that the per-task skills wipe+ # (os.RemoveAll) drops the junction rather than the user's files, and+ # that the GC's artifact sweep and size accounting refuse to walk+ # through one. The tests call mklink /J directly so the junction shape+ # is exercised even on a runner where symlinks are permitted.+ # -v so a skip is visible instead of passing silently as "ok".+ run: |+ go test ./internal/daemon/execenv -v -run '^(TestSeedUserCodexSkills|TestHydrateCodexSkills)' -count=1 -timeout=5m+ go test ./internal/daemon -v -run '^(TestCleanTaskArtifacts_DoesNotFollowDirectoryJunction|TestTaskSize_DoesNotCountDirectoryJunction)$' -count=1 -timeout=5m+- name: Build Windows CLI helper entrypointworking-directory: serverrun: go build ./cmd/multicadiff --git a/server/internal/daemon/diskusage.go b/server/internal/daemon/diskusage.goindex fcc966685d..e71d5b1121 100644--- a/server/internal/daemon/diskusage.go+++ b/server/internal/daemon/diskusage.go@@ -462,11 +462,19 @@ func taskSize(taskDir string, matcher artifactMatcher) (totalBytes int64, artifaif path == absRoot {return nil}- // Symlinks: never followed, never counted. WalkDir already refuses to- // descend through them, but a symlinked file would otherwise show up- // here as a non-dir entry — drop it explicitly so the size stays- // consistent with cleanTaskArtifacts' refusal to touch link targets.- if entry.Type()&os.ModeSymlink != 0 {+ // Links: never followed, never counted. WalkDir already refuses to+ // descend through a symlink, but a symlinked file would otherwise show+ // up here as a non-dir entry, and a Windows junction is reported as a+ // directory WalkDir does descend (see linkedDirModes) — drop both+ // explicitly so the size stays consistent with cleanTaskArtifacts'+ // refusal to touch link targets.+ if entry.Type()&linkedDirModes != 0 {+ if entry.IsDir() {+ // A junction: WalkDir would descend into the link target.+ // SkipDir is safe here only because the entry is a directory —+ // returning it for a file would skip the remaining siblings.+ return filepath.SkipDir+ }return nil}if entry.IsDir() {diff --git a/server/internal/daemon/execenv/codex_user_skills.go b/server/internal/daemon/execenv/codex_user_skills.goindex 5c1a5c4486..fa4ff6ecd3 100644--- a/server/internal/daemon/execenv/codex_user_skills.go+++ b/server/internal/daemon/execenv/codex_user_skills.go@@ -2,27 +2,38 @@ package execenvimport ("fmt"- "io/fs""log/slog""os""path/filepath""strings")-// seedUserCodexSkills copies user-installed skill directories from the shared+// seedUserCodexSkills links user-installed skill directories from the shared// ~/.codex/skills/ into the per-task CODEX_HOME so the codex CLI discovers// them natively. Codex is the only runtime whose HOME is redirected to a// per-task directory (via the CODEX_HOME env var), so without this step the// CLI never sees the user's `~/.codex/skills/` content.//+// Links, never copies. A copy charges the whole skill tree to every task+// directory — 100 MB for a user with a handful of npm-backed skills — and+// hydrateCodexSkills re-does it on every task start, on the critical path,+// while no GC path ever reclaims it as long as the issue stays open. The two+// other shared resources in the same per-task home already link for the same+// reason: sessions (linkCodexSessionsToStore) and the plugin cache+// (exposeSharedCodexPluginCache). A skill directory is read-only input to the+// CLI, so the write isolation a copy incidentally bought has no requester.+//// Workspace-assigned skills take precedence on name conflict: any user skill// whose sanitized name matches a workspace skill's sanitized name is skipped// here, and writeSkillFiles then writes the workspace version into a clean-// slot.+// slot. writeSkillFiles never writes through a link it did not create:+// allocateCollisionFreeSkillDir probes with os.Lstat, so a link left here+// counts as occupied and the workspace skill lands in a `-multica` sibling.//// Per-skill failures are logged and skipped — a single broken user skill// must not prevent the task from running. Returning an error is reserved for-// failures that prevent listing the shared skills directory at all.+// failures that would affect every skill: listing the shared skills+// directory, or creating the per-task skills directory.func seedUserCodexSkills(codexHome string, workspaceSkills []SkillContextForEnv, logger *slog.Logger) error {sharedSkillsDir := filepath.Join(resolveSharedCodexHome(), "skills")@@ -59,8 +70,9 @@ func seedUserCodexSkills(codexHome string, workspaceSkills []SkillContextForEnv,}src := filepath.Join(sharedSkillsDir, name)// Installers like lark-cli ship each skill as a symlink into a- // shared ~/.agents/skills/<name>/ directory. Resolve symlinks so we- // copy the real content into the per-task home.+ // shared ~/.agents/skills/<name>/ directory. Resolve it so the+ // per-task link points at the real directory instead of at another+ // link, and so the IsDir check below sees the actual target.resolved, err := filepath.EvalSymlinks(src)if err != nil {logger.Warn("execenv: codex user-skill resolve failed", "name", name, "error", err)@@ -70,45 +82,25 @@ func seedUserCodexSkills(codexHome string, workspaceSkills []SkillContextForEnv,if err != nil || !fi.IsDir() {continue}+ // hydrateCodexSkills wipes the skills dir before every seed, so the+ // parent is normally absent here; createDirLink needs it to exist.+ // Created lazily so a task with no eligible user skills still gets no+ // skills directory at all.+ if err := os.MkdirAll(targetSkillsDir, 0o755); err != nil {+ return fmt.Errorf("create codex skills dir %s: %w", targetSkillsDir, err)+ }dst := filepath.Join(targetSkillsDir, name)+ // Removes the link, never the link target: os.RemoveAll unlinks a+ // symlink, and on Windows RemoveDirectory drops a junction while+ // leaving the directory it points at intact.if err := os.RemoveAll(dst); err != nil {logger.Warn("execenv: codex user-skill clean dst failed", "name", name, "error", err)continue}- if err := copyDirTree(resolved, dst); err != nil {- logger.Warn("execenv: codex user-skill copy failed", "name", name, "error", err)+ if err := createDirLink(resolved, dst); err != nil {+ logger.Warn("execenv: codex user-skill link failed", "name", name, "error", err)continue}}return nil}--// copyDirTree walks src recursively and copies every regular file under it-// to the matching path under dst. Nested symlinks are ignored to keep the-// per-task home self-contained; the caller is expected to resolve the root-// before calling.-func copyDirTree(src, dst string) error {- return filepath.WalkDir(src, func(path string, d fs.DirEntry, walkErr error) error {- if walkErr != nil {- return walkErr- }- rel, err := filepath.Rel(src, path)- if err != nil {- return err- }- target := filepath.Join(dst, rel)- if d.IsDir() {- return os.MkdirAll(target, 0o755)- }- if d.Type()&os.ModeSymlink != 0 {- return nil- }- if !d.Type().IsRegular() {- return nil- }- if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {- return err- }- return copyFile(path, target)- })-}diff --git a/server/internal/daemon/execenv/codex_user_skills_test.go b/server/internal/daemon/execenv/codex_user_skills_test.gonew file mode 100644index 0000000000..32c372ffb5--- /dev/null+++ b/server/internal/daemon/execenv/codex_user_skills_test.go@@ -0,0 +1,220 @@+package execenv++import (+ "os"+ "path/filepath"+ "runtime"+ "testing"+)++// User skills reach the per-task CODEX_HOME as links, not copies (MUL-6000).+// Copying charged every task directory the full skill tree — ~100 MB for a+// user with npm-backed skills — re-paid on every task start and never+// reclaimed while the issue stayed open.++func writeUserSkill(t *testing.T, dir, body string) {+ t.Helper()+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatalf("mkdir %s: %v", dir, err)+ }+ if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(body), 0o644); err != nil {+ t.Fatalf("write SKILL.md in %s: %v", dir, err)+ }+}++// assertIsLink fails when path is a real directory rather than a link to one.+// A POSIX symlink reports ModeSymlink; a Windows junction reports+// ModeDir|ModeIrregular (Go 1.23+), which is why the mask covers both.+func assertIsLink(t *testing.T, path string) {+ t.Helper()+ fi, err := os.Lstat(path)+ if err != nil {+ t.Fatalf("lstat %s: %v", path, err)+ }+ if fi.Mode()&(os.ModeSymlink|os.ModeIrregular) == 0 {+ t.Fatalf("%s is a real directory (mode %v), want a link", path, fi.Mode())+ }+}++func TestSeedUserCodexSkillsLinksInsteadOfCopying(t *testing.T) {+ // Cannot use t.Parallel() with t.Setenv.+ sharedHome := t.TempDir()+ t.Setenv("CODEX_HOME", sharedHome)+ userSkill := filepath.Join(sharedHome, "skills", "alpha")+ writeUserSkill(t, userSkill, "alpha v1")++ codexHome := t.TempDir()+ if err := seedUserCodexSkills(codexHome, nil, testLogger()); err != nil {+ t.Fatalf("seedUserCodexSkills: %v", err)+ }++ dst := filepath.Join(codexHome, "skills", "alpha")+ assertIsLink(t, dst)++ body, err := os.ReadFile(filepath.Join(dst, "SKILL.md"))+ if err != nil {+ t.Fatalf("read seeded SKILL.md: %v", err)+ }+ if string(body) != "alpha v1" {+ t.Errorf("seeded SKILL.md = %q, want %q", body, "alpha v1")+ }++ // The decisive proof it is not a copy: content added to the user's real+ // skill directory after seeding is visible through the per-task path.+ if err := os.WriteFile(filepath.Join(userSkill, "reference.md"), []byte("added later"), 0o644); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(dst, "reference.md")); err != nil {+ t.Errorf("per-task skill dir is a snapshot copy, not a link: %v", err)+ }+}++func TestSeedUserCodexSkillsResolvesInstallerSymlink(t *testing.T) {+ // Installers like lark-cli put a symlink in ~/.codex/skills/<name>+ // pointing into a shared ~/.agents/skills/<name>/.+ agentsRoot := t.TempDir()+ realSkill := filepath.Join(agentsRoot, "lark-base")+ writeUserSkill(t, realSkill, "lark-base v1")++ sharedHome := t.TempDir()+ t.Setenv("CODEX_HOME", sharedHome)+ if err := os.MkdirAll(filepath.Join(sharedHome, "skills"), 0o755); err != nil {+ t.Fatal(err)+ }+ installerLink := filepath.Join(sharedHome, "skills", "lark-base")+ if err := os.Symlink(realSkill, installerLink); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }++ codexHome := t.TempDir()+ if err := seedUserCodexSkills(codexHome, nil, testLogger()); err != nil {+ t.Fatalf("seedUserCodexSkills: %v", err)+ }++ dst := filepath.Join(codexHome, "skills", "lark-base")+ assertIsLink(t, dst)+ body, err := os.ReadFile(filepath.Join(dst, "SKILL.md"))+ if err != nil {+ t.Fatalf("symlink-installed skill unreadable through the per-task link: %v", err)+ }+ if string(body) != "lark-base v1" {+ t.Errorf("SKILL.md = %q, want %q", body, "lark-base v1")+ }++ // The per-task link must point at the real directory, not at the+ // installer's own link, so it stays valid if the installer re-points it.+ if runtime.GOOS != "windows" {+ target, err := os.Readlink(dst)+ if err != nil {+ t.Fatalf("readlink %s: %v", dst, err)+ }+ want, err := filepath.EvalSymlinks(realSkill)+ if err != nil {+ t.Fatal(err)+ }+ if target != want {+ t.Errorf("link target = %q, want the resolved skill dir %q", target, want)+ }+ }+}++func TestSeedUserCodexSkillsYieldsToWorkspaceSkill(t *testing.T) {+ sharedHome := t.TempDir()+ t.Setenv("CODEX_HOME", sharedHome)+ writeUserSkill(t, filepath.Join(sharedHome, "skills", "issue-review"), "user version")+ writeUserSkill(t, filepath.Join(sharedHome, "skills", "keeper"), "keeper version")++ codexHome := t.TempDir()+ skills := []SkillContextForEnv{{Name: "Issue Review", Content: "workspace version"}}+ if err := seedUserCodexSkills(codexHome, skills, testLogger()); err != nil {+ t.Fatalf("seedUserCodexSkills: %v", err)+ }++ if _, err := os.Lstat(filepath.Join(codexHome, "skills", "issue-review")); !os.IsNotExist(err) {+ t.Errorf("user skill claimed a workspace skill's slot (err = %v)", err)+ }+ if _, err := os.Lstat(filepath.Join(codexHome, "skills", "keeper")); err != nil {+ t.Errorf("unrelated user skill was dropped: %v", err)+ }+}++func TestSeedUserCodexSkillsWithNoEligibleSkillsCreatesNoDir(t *testing.T) {+ sharedHome := t.TempDir()+ t.Setenv("CODEX_HOME", sharedHome)+ if err := os.MkdirAll(filepath.Join(sharedHome, "skills"), 0o755); err != nil {+ t.Fatal(err)+ }++ codexHome := t.TempDir()+ if err := seedUserCodexSkills(codexHome, nil, testLogger()); err != nil {+ t.Fatalf("seedUserCodexSkills: %v", err)+ }+ if _, err := os.Lstat(filepath.Join(codexHome, "skills")); !os.IsNotExist(err) {+ t.Errorf("skills dir created with nothing to seed (err = %v)", err)+ }+}++// hydrateCodexSkills wipes the skills dir before every seed, on both the+// Prepare and the Reuse path. With links in place that RemoveAll must delete+// the link and never reach through it into the user's real skill directory.+func TestHydrateCodexSkillsWipeKeepsUserSkillContent(t *testing.T) {+ sharedHome := t.TempDir()+ t.Setenv("CODEX_HOME", sharedHome)+ userSkill := filepath.Join(sharedHome, "skills", "alpha")+ writeUserSkill(t, userSkill, "alpha v1")+ if err := os.WriteFile(filepath.Join(userSkill, "reference.md"), []byte("support"), 0o644); err != nil {+ t.Fatal(err)+ }++ codexHome := t.TempDir()+ workspaceSkills := []SkillContextForEnv{{Name: "Beta", Description: "workspace skill", Content: "beta body"}}++ // Twice: Prepare hydrates, then a follow-up task on the same env re-hydrates.+ for i := 0; i < 2; i++ {+ if err := hydrateCodexSkills(codexHome, workspaceSkills, nil, testLogger()); err != nil {+ t.Fatalf("hydrateCodexSkills run %d: %v", i+1, err)+ }+ }++ for _, name := range []string{"SKILL.md", "reference.md"} {+ if _, err := os.Stat(filepath.Join(userSkill, name)); err != nil {+ t.Fatalf("hydrate deleted %s from the user's real skill dir: %v", name, err)+ }+ }+ assertIsLink(t, filepath.Join(codexHome, "skills", "alpha"))+ if _, err := os.Stat(filepath.Join(codexHome, "skills", "beta", "SKILL.md")); err != nil {+ t.Errorf("workspace skill missing after re-hydration: %v", err)+ }+}++// A workspace skill whose name only collides after directory naming — the+// sanitized-name pre-filter does not catch it — must land in a sibling+// directory instead of being written through the user's link.+func TestHydrateCodexSkillsNeverWritesThroughAUserSkillLink(t *testing.T) {+ sharedHome := t.TempDir()+ t.Setenv("CODEX_HOME", sharedHome)+ userSkill := filepath.Join(sharedHome, "skills", "alpha")+ writeUserSkill(t, userSkill, "user version")++ codexHome := t.TempDir()+ skillsDir := filepath.Join(codexHome, "skills")+ if err := seedUserCodexSkills(codexHome, nil, testLogger()); err != nil {+ t.Fatalf("seedUserCodexSkills: %v", err)+ }+ // writeSkillFiles runs without the pre-filter that hydrateCodexSkills+ // applies, which is exactly the case allocateCollisionFreeSkillDir guards.+ if err := writeSkillFiles(skillsDir, []SkillContextForEnv{{Name: "alpha", Content: "workspace version"}}, nil); err != nil {+ t.Fatalf("writeSkillFiles: %v", err)+ }++ body, err := os.ReadFile(filepath.Join(userSkill, "SKILL.md"))+ if err != nil {+ t.Fatalf("read user skill: %v", err)+ }+ if string(body) != "user version" {+ t.Fatalf("workspace skill was written through the link into the user's skill dir: %q", body)+ }+ if _, err := os.Stat(filepath.Join(skillsDir, "alpha-multica", "SKILL.md")); err != nil {+ t.Errorf("colliding workspace skill did not land in a sibling dir: %v", err)+ }+}diff --git a/server/internal/daemon/execenv/codex_user_skills_windows_test.go b/server/internal/daemon/execenv/codex_user_skills_windows_test.gonew file mode 100644index 0000000000..8462c0d32e--- /dev/null+++ b/server/internal/daemon/execenv/codex_user_skills_windows_test.go@@ -0,0 +1,51 @@+//go:build windows++package execenv++import (+ "os"+ "os/exec"+ "path/filepath"+ "testing"+)++// On Windows createDirLink falls back to a directory junction (mklink /J) when+// os.Symlink is denied — the default without Developer Mode. hydrateCodexSkills+// wipes codex-home/skills on every task start, so the wipe must delete the+// junction itself and never reach through it into the user's real skill files.+// os.RemoveAll drops a junction with RemoveDirectory, but only a real Windows+// filesystem proves it; mklink /J is used directly so the junction shape is+// exercised even on a runner where symlinks are permitted.+func TestHydrateCodexSkillsWipeKeepsJunctionTarget(t *testing.T) {+ sharedHome := t.TempDir()+ t.Setenv("CODEX_HOME", sharedHome)+ userSkill := filepath.Join(sharedHome, "skills", "alpha")+ writeUserSkill(t, userSkill, "alpha v1")++ codexHome := t.TempDir()+ junction := filepath.Join(codexHome, "skills", "alpha")+ if err := os.MkdirAll(filepath.Dir(junction), 0o755); err != nil {+ t.Fatal(err)+ }+ if out, err := exec.Command("cmd", "/c", "mklink", "/J", junction, userSkill).CombinedOutput(); err != nil {+ t.Fatalf("mklink /J: %s: %v", out, err)+ }+ if fi, err := os.Lstat(junction); err != nil {+ t.Fatal(err)+ } else if fi.Mode()&os.ModeSymlink != 0 {+ t.Fatalf("expected a junction, got a symlink (mode %v)", fi.Mode())+ }++ if err := hydrateCodexSkills(codexHome, nil, nil, testLogger()); err != nil {+ t.Fatalf("hydrateCodexSkills: %v", err)+ }++ body, err := os.ReadFile(filepath.Join(userSkill, "SKILL.md"))+ if err != nil {+ t.Fatalf("the skills wipe reached through the junction: %v", err)+ }+ if string(body) != "alpha v1" {+ t.Errorf("user SKILL.md = %q, want %q", body, "alpha v1")+ }+ assertIsLink(t, junction)+}diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex f70b4a4dc6..66a42fb93a 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -4582,8 +4582,10 @@ func TestPrepareCodexNoUserSkillsDir(t *testing.T) {// TestPrepareCodexResolvesUserSkillSymlinks covers the lark-cli /// shared-installer case: each user skill is a symlink into a separate-// installer directory. The per-task home must end up with a real copy, not-// a dangling symlink that points outside the task root.+// installer directory. The per-task home links to the resolved installer+// directory — never to the installer's own link, which would leave the CLI+// following a chain that breaks the moment the installer re-points it, and+// never dangling.func TestPrepareCodexResolvesUserSkillSymlinks(t *testing.T) {if runtime.GOOS == "windows" {t.Skip("symlink semantics differ on Windows; covered by Unix path")@@ -4623,12 +4625,19 @@ func TestPrepareCodexResolvesUserSkillSymlinks(t *testing.T) {defer env.Cleanup(true)dst := filepath.Join(env.CodexHome, "skills", "lark-mail")- fi, err := os.Lstat(dst)- if err != nil {+ if _, err := os.Lstat(dst); err != nil {t.Fatalf("seeded skill missing: %v", err)}- if fi.Mode()&os.ModeSymlink != 0 {- t.Errorf("seeded skill should be a real directory, got a symlink")+ target, err := os.Readlink(dst)+ if err != nil {+ t.Fatalf("seeded skill should be a link into the installer dir: %v", err)+ }+ wantTarget, err := filepath.EvalSymlinks(installerRoot)+ if err != nil {+ t.Fatalf("resolve installer dir: %v", err)+ }+ if target != wantTarget {+ t.Errorf("link target = %q, want the resolved installer dir %q", target, wantTarget)}data, err := os.ReadFile(filepath.Join(dst, "SKILL.md"))if err != nil {diff --git a/server/internal/daemon/execenv/hermes_memory.go b/server/internal/daemon/execenv/hermes_memory.goindex a63a2449a6..e6f5855cb6 100644--- a/server/internal/daemon/execenv/hermes_memory.go+++ b/server/internal/daemon/execenv/hermes_memory.go@@ -339,9 +339,9 @@ func copyHermesMemoryEntry(src, dst string, entry os.DirEntry) error {}// copyHermesMemoryTree copies a directory under a memories dir recursively.-// Unlike copyDirTree it refuses (rather than skips) nested symlinks and other-// irregular files, for the same reason: this copy is the only thing standing-// between the source and its deletion.+// It refuses (rather than silently skips) nested symlinks and other irregular+// files: this copy is the only thing standing between the source and its+// deletion.func copyHermesMemoryTree(src, dst string) error {return filepath.WalkDir(src, func(path string, d fs.DirEntry, walkErr error) error {if walkErr != nil {diff --git a/server/internal/daemon/execenv/hermes_memory_test.go b/server/internal/daemon/execenv/hermes_memory_test.goindex 5d71bd1acb..46a44e497d 100644--- a/server/internal/daemon/execenv/hermes_memory_test.go+++ b/server/internal/daemon/execenv/hermes_memory_test.go@@ -325,7 +325,7 @@ func TestMigrateHermesTaskMemoriesRefusesUnsupportedEntries(t *testing.T) {if _, err := os.Stat(storeDir); !os.IsNotExist(err) {t.Fatalf("refused migration left a store behind (err = %v)", err)}- // A nested symlink must be refused too — copyDirTree would have skipped it.+ // A nested symlink must be refused too, not silently skipped.nested := t.TempDir()mustWrite(t, filepath.Join(nested, "notes", "note.md"), "regular")if err := os.Symlink(filepath.Join(nested, "notes", "note.md"), filepath.Join(nested, "notes", "link.md")); err != nil {diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex df8689f6c8..588d27f474 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -651,6 +651,20 @@ func (d *Daemon) cleanTaskDir(taskDir string) {}}+// linkedDirModes are the mode bits that mark a directory entry as a link to+// content the task does not own. Every task-directory walk that deletes or+// measures must refuse to descend through them: the per-task codex-home links+// the user's real skills, Codex session store and plugin cache into itself, so+// descending would put the GC inside the user's home.+//+// ModeSymlink alone is not enough on Windows. createDirLink falls back to a+// directory junction (mklink /J) when os.Symlink is denied — no Developer Mode+// — and since Go 1.23 os.Lstat reports a junction as ModeDir|ModeIrregular+// with no ModeSymlink bit, while its DirEntry still answers IsDir() == true.+// A ModeSymlink-only check therefore lets filepath.WalkDir walk straight into+// the link target.+const linkedDirModes = os.ModeSymlink | os.ModeIrregular+// cleanTaskArtifacts walks taskDir and deletes every directory whose basename// matches one of patterns, plus exact daemon-managed artifact paths. Returns// (removedCount, bytesReclaimed, perPattern).@@ -659,9 +673,9 @@ func (d *Daemon) cleanTaskDir(taskDir string) {// - patterns are basename-only; entries with a path separator are dropped.// - .git subtrees are never descended into, so the agent's git history stays// intact even if a pattern would otherwise match.-// - symlinks are skipped entirely — neither the link nor its target is-// touched, so a malicious or stale link can't redirect the GC outside the-// workdir.+// - linked directories are skipped entirely — neither the link nor its+// target is touched, so a malicious or stale link can't redirect the GC+// outside the workdir. See linkedDirModes for what counts as a link.// - every removal target is verified to live inside taskDir, so a tampered// .gc_meta.json can't trick the daemon into deleting outside its sandbox.func (d *Daemon) cleanTaskArtifacts(taskDir string, patterns []string) (removed int, bytes int64, perPattern map[string]int) {@@ -698,13 +712,13 @@ func (d *Daemon) cleanTaskArtifactsMatching(taskDir string, matcher artifactMatcif entry.Name() == ".git" {return filepath.SkipDir}- // Refuse to follow symlinked directories. WalkDir reports them as type+ // Refuse to follow linked directories. WalkDir reports them as type// Dir on some platforms; lstat to be sure.info, statErr := os.Lstat(path)if statErr != nil {return nil}- if info.Mode()&os.ModeSymlink != 0 {+ if info.Mode()&linkedDirModes != 0 {return filepath.SkipDir}pattern, ok := matcher.matchDirectory(absRoot, path, entry)@@ -730,6 +744,8 @@ func (d *Daemon) cleanTaskArtifactsMatching(taskDir string, matcher artifactMatc}// dirSize returns the total size of all regular files under root, in bytes.+// Linked content is not counted: os.RemoveAll would drop the link and leave+// the target, so counting it would overstate what a removal reclaims.// Non-fatal: errors during the walk are ignored so callers can report a// best-effort byte count without aborting the whole GC cycle.func dirSize(root string) int64 {@@ -738,6 +754,12 @@ func dirSize(root string) int64 {if err != nil {return nil}+ if entry.Type()&linkedDirModes != 0 {+ if entry.IsDir() {+ return filepath.SkipDir+ }+ return nil+ }if entry.IsDir() {return nil}diff --git a/server/internal/daemon/gc_junction_windows_test.go b/server/internal/daemon/gc_junction_windows_test.gonew file mode 100644index 0000000000..6b70d4ec15--- /dev/null+++ b/server/internal/daemon/gc_junction_windows_test.go@@ -0,0 +1,88 @@+//go:build windows++package daemon++import (+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+)++// The per-task codex-home links shared user content into the task directory —+// skills (MUL-6000), the Codex session store, the plugin cache. On Windows+// those links are directory junctions whenever os.Symlink is denied, which is+// the default without Developer Mode.+//+// A junction is the one link shape a ModeSymlink check misses: since Go 1.23+// os.Lstat reports it as ModeDir|ModeIrregular with no ModeSymlink bit, and+// its DirEntry still answers IsDir() == true, so filepath.WalkDir walks+// straight into the target. Only a real Windows filesystem can prove the guard+// holds, which is why this lives in a windows-tagged file with its own CI step.++// createJunction links dst -> src as a directory junction. mklink /J is used+// directly (rather than createDirLink's symlink-first path) so the test always+// exercises the junction shape, even on a runner where symlinks are allowed.+func createJunction(t *testing.T, src, dst string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {+ t.Fatal(err)+ }+ if out, err := exec.Command("cmd", "/c", "mklink", "/J", dst, src).CombinedOutput(); err != nil {+ t.Fatalf("mklink /J %s %s: %s: %v", dst, src, out, err)+ }+ fi, err := os.Lstat(dst)+ if err != nil {+ t.Fatalf("lstat junction: %v", err)+ }+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Fatalf("expected a junction, got a symlink (mode %v) — the test would not cover the junction path", fi.Mode())+ }+}++func TestCleanTaskArtifacts_DoesNotFollowDirectoryJunction(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())++ taskDir := t.TempDir()+ userSkill := t.TempDir()+ keep := filepath.Join(userSkill, "node_modules", "pkg", "index.js")+ if err := os.MkdirAll(filepath.Dir(keep), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(keep, []byte("user content"), 0o644); err != nil {+ t.Fatal(err)+ }++ // Mirrors the real layout: codex-home/skills/<name> junctioned to the+ // user's ~/.codex/skills/<name>.+ createJunction(t, userSkill, filepath.Join(taskDir, "codex-home", "skills", "alpha"))++ removed, _, _ := d.cleanTaskArtifacts(taskDir, []string{"node_modules"})+ if removed != 0 {+ t.Errorf("removed %d artifacts through a junction, want 0", removed)+ }+ if _, err := os.Stat(keep); err != nil {+ t.Fatalf("GC deleted node_modules inside the junction target: %v", err)+ }+}++func TestTaskSize_DoesNotCountDirectoryJunction(t *testing.T) {+ taskDir := t.TempDir()+ linked := t.TempDir()+ if err := os.WriteFile(filepath.Join(linked, "big.bin"), make([]byte, 4096), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(taskDir, "own.bin"), make([]byte, 16), 0o644); err != nil {+ t.Fatal(err)+ }+ createJunction(t, linked, filepath.Join(taskDir, "codex-home", "skills", "alpha"))++ total, artifacts := taskSize(taskDir, newArtifactMatcher([]string{"node_modules"}, nil))+ if total != 16 {+ t.Errorf("total = %d, want 16 (junction target must not be counted)", total)+ }+ if artifacts != 0 {+ t.Errorf("artifacts = %d, want 0", artifacts)+ }+}