Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6025: fix(daemon): resolve Windows installer junctions (#6802)
Jamison-Jd582dca0621c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 585fdfebc7..25298060b0 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -427,6 +427,14 @@ jobs:go test ./internal/daemon/execenv -v -run '^(TestSeedUserCodexSkills|TestHydrateCodexSkills)' -count=1 -timeout=5mgo test ./internal/daemon -v -run '^(TestCleanTaskArtifacts_DoesNotFollowDirectoryJunction|TestTaskSize_DoesNotCountDirectoryJunction)$' -count=1 -timeout=5m+ - name: Test Windows agent executable junction resolution+ working-directory: server+ # The standalone Codex installer exposes bin as a directory junction.+ # filepath.EvalSymlinks cannot traverse that reparse-point shape, so+ # only a real Windows filesystem proves both PATH discovery and an+ # explicitly configured path reach the release executable.+ run: go test ./internal/daemon -v -run '^(TestCanonicalExecutablePath|TestResolveAgentExecutablePathKeeps|TestResolveAgentEntry(FollowsRetargetedInstallerJunction|CanonicalizesRediscoveredJunction|ForLaunchRejectsUnverifiedInitialJunctionTarget|ForLaunchRejectsRediscoveredJunctionWhenFinalPathResolutionFails|DoesNotSharePreRetargetSingleflightResult|ForLaunchFailsWhenJunctionKeepsRetargeting)|TestHandleTaskReportsWindowsCodexProcessStartFailure)' -count=1 -timeout=5m+- name: Build Windows CLI helper entrypointworking-directory: serverrun: go build ./cmd/multicadiff --git a/server/internal/daemon/agents_refresh.go b/server/internal/daemon/agents_refresh.goindex 9594249d3e..e232401bb8 100644--- a/server/internal/daemon/agents_refresh.go+++ b/server/internal/daemon/agents_refresh.go@@ -205,11 +205,11 @@ func (d *Daemon) refreshAgentAvailability() []string {// NOT restart. What a user needs when codex or claude upgrades is that// subsequent tasks run the new CLI under the new version's rules — not that// Multica's availability tracks a third party's release cadence. An in-place-// upgrade leaves the pinned path valid, so the new binary is already what-// launches; the two things left stale are the cached version (which keys-// version-sensitive policy such as the Codex sandbox, read back through-// resolveAgentEntry) and the version the server displays. Both are refreshed-// here with running tasks untouched.+// POSIX upgrade changes the binary behind the pinned path; a Windows installer+// upgrade retargets the stable junction resolved by resolveAgentEntry. The two+// things left stale are the cached version (which keys version-sensitive policy+// such as the Codex sandbox) and the version the server displays. Both are+// refreshed here with running tasks untouched.//// detectBuiltinRuntimes does the probing, which buys three properties for free:// probes fan out, a fast failure is retried (runtimeVersionProbeAttempts), anddiff --git a/server/internal/daemon/canonical_path.go b/server/internal/daemon/canonical_path.gonew file mode 100644index 0000000000..47f0cc8225--- /dev/null+++ b/server/internal/daemon/canonical_path.go@@ -0,0 +1,23 @@+//go:build !windows++package daemon++import "path/filepath"++func canonicalPath(path string) (string, error) {+ return filepath.EvalSymlinks(path)+}++func discoveredExecutablePath(path string) string {+ return canonicalExecutablePath(path)+}++var executablePathForLaunch = executablePathForLaunchDefault++func executablePathForLaunchDefault(string) (string, bool, error) {+ return "", false, nil+}++func canonicalConfiguredExecutablePath(path string) string {+ return path+}diff --git a/server/internal/daemon/canonical_path_windows.go b/server/internal/daemon/canonical_path_windows.gonew file mode 100644index 0000000000..f29ff64ee2--- /dev/null+++ b/server/internal/daemon/canonical_path_windows.go@@ -0,0 +1,65 @@+//go:build windows++package daemon++import (+ "path/filepath"+ "syscall"++ "golang.org/x/sys/windows"+)++func canonicalPath(path string) (string, error) {+ pathUTF16, err := windows.UTF16PtrFromString(path)+ if err != nil {+ return "", err+ }+ handle, err := windows.CreateFile(+ pathUTF16,+ 0,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,+ nil,+ windows.OPEN_EXISTING,+ windows.FILE_ATTRIBUTE_NORMAL,+ 0,+ )+ if err != nil {+ return "", err+ }+ defer windows.CloseHandle(handle)++ buffer := make([]uint16, syscall.MAX_PATH)+ for {+ length, err := windows.GetFinalPathNameByHandle(handle, &buffer[0], uint32(len(buffer)), 0)+ if err != nil {+ return "", err+ }+ if length < uint32(len(buffer)) {+ return windows.UTF16ToString(buffer[:length]), nil+ }+ buffer = make([]uint16, length+1)+ }+}++func discoveredExecutablePath(path string) string {+ abs, err := filepath.Abs(path)+ if err != nil {+ return path+ }+ return abs+}++func canonicalConfiguredExecutablePath(path string) string {+ return discoveredExecutablePath(path)+}++var executablePathForLaunch = executablePathForLaunchWindows++func executablePathForLaunchWindows(path string) (string, bool, error) {+ abs, err := filepath.Abs(path)+ if err != nil {+ return "", true, err+ }+ resolved, err := canonicalPath(abs)+ return resolved, true, err+}diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 159408c023..bf9cd5d70e 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -632,9 +632,12 @@ func shellArgsFromEnv(name string) ([]string, error) {return args, nil}-// resolveAgentExecutablePath returns the concrete executable path the daemon+// resolveAgentExecutablePath returns the executable entry point the daemon// should keep for an agent command. Bare command names are pinned to the path// resolved during startup so later PATH changes cannot redirect task launches.+// On Windows this deliberately keeps the stable discovered junction path;+// resolveAgentEntryWithHeal follows it for each launch so installer upgrades+// that retarget a still-live junction take effect without a daemon restart.// When ~/.multica/hooks shadows a real agent binary, skip that hooks directory:// previously generated hook wrappers can execute the same command name and// recurse forever if the daemon records or launches the wrapper.@@ -644,14 +647,14 @@ func resolveAgentExecutablePath(cmd string) (string, error) {return "", err}if strings.ContainsAny(cmd, "/\\") {- return resolved, nil+ return canonicalConfiguredExecutablePath(resolved), nil}if isInMulticaHooksDir(resolved) {if unshadowed, err := lookPathExcludingMulticaHooks(cmd); err == nil {return unshadowed, nil}}- return canonicalExecutablePath(resolved), nil+ return discoveredExecutablePath(resolved), nil}// agentExecutablePresent reports whether path currently resolves to a runnable@@ -705,7 +708,7 @@ func lookPathExcludingMulticaHooks(cmd string) (string, error) {}candidate := filepath.Join(dir, cmd)if isExecutableFile(candidate) {- return canonicalExecutablePath(candidate), nil+ return discoveredExecutablePath(candidate), nil}}return "", exec.ErrNotFound@@ -749,10 +752,13 @@ func samePathDir(a, b string) bool {func canonicalExecutablePath(path string) string {abs, err := filepath.Abs(path)if err != nil {+ slog.Debug("make agent executable path absolute failed; keeping configured path", "path", path, "error", err)return path}- if real, err := filepath.EvalSymlinks(abs); err == nil {+ if real, err := canonicalPath(abs); err == nil {return real+ } else {+ slog.Debug("canonicalize agent executable path failed; keeping absolute path", "path", abs, "error", err)}return abs}diff --git a/server/internal/daemon/config_windows_test.go b/server/internal/daemon/config_windows_test.gonew file mode 100644index 0000000000..7f70f6db72--- /dev/null+++ b/server/internal/daemon/config_windows_test.go@@ -0,0 +1,564 @@+//go:build windows++package daemon++import (+ "bytes"+ "context"+ "errors"+ "io"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/pkg/agent"+)++const (+ longPathExecutableHelperEnv = "MULTICA_LONG_PATH_EXECUTABLE_HELPER"+ longPathExecutableMarkerEnv = "MULTICA_LONG_PATH_EXECUTABLE_MARKER"+)++func TestLongPathExecutableHelper(t *testing.T) {+ if os.Getenv(longPathExecutableHelperEnv) == "1" {+ if marker := os.Getenv(longPathExecutableMarkerEnv); marker != "" {+ executable, err := os.Executable()+ if err != nil {+ os.Exit(2)+ }+ if err := os.WriteFile(marker, []byte(executable), 0o600); err != nil {+ os.Exit(3)+ }+ }+ os.Exit(0)+ }+}++func TestCanonicalExecutablePathResolvesDirectoryJunction(t *testing.T) {+ targetDir := t.TempDir()+ targetBin := filepath.Join(targetDir, "bin")+ if err := os.MkdirAll(targetBin, 0o755); err != nil {+ t.Fatal(err)+ }+ targetExecutable := filepath.Join(targetBin, "codex.exe")+ if err := os.WriteFile(targetExecutable, []byte("test"), 0o755); err != nil {+ t.Fatal(err)+ }++ shimRoot := t.TempDir()+ shimBin := filepath.Join(shimRoot, "bin")+ createJunction(t, targetBin, shimBin)+ shimExecutable := filepath.Join(shimBin, "codex.exe")++ if _, err := filepath.EvalSymlinks(shimExecutable); err == nil {+ t.Fatal("EvalSymlinks unexpectedly resolved a directory junction; test would not reproduce the bug")+ }+ assertResolvedExecutable(t, canonicalExecutablePath(shimExecutable), shimExecutable, targetExecutable)+}++func TestCanonicalExecutablePathKeepsRegularExecutable(t *testing.T) {+ executable := filepath.Join(t.TempDir(), "codex.exe")+ if err := os.WriteFile(executable, []byte("test"), 0o755); err != nil {+ t.Fatal(err)+ }++ assertSameFile(t, canonicalExecutablePath(executable), executable)+}++func TestCanonicalExecutablePathFallsBackForMissingExecutable(t *testing.T) {+ missing := filepath.Join(t.TempDir(), "missing", "codex.exe")+ want, err := filepath.Abs(missing)+ if err != nil {+ t.Fatal(err)+ }++ if got := canonicalExecutablePath(missing); got != want {+ t.Fatalf("canonicalExecutablePath() = %q, want fallback %q", got, want)+ }+}++func TestCanonicalExecutablePathLogsFallbackError(t *testing.T) {+ var logs bytes.Buffer+ previous := slog.Default()+ slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})))+ t.Cleanup(func() { slog.SetDefault(previous) })++ missing := filepath.Join(t.TempDir(), "missing", "codex.exe")+ canonicalExecutablePath(missing)++ got := logs.String()+ if !strings.Contains(got, "canonicalize agent executable path failed") {+ t.Fatalf("canonicalization fallback log = %q, want failure message", got)+ }+ if !strings.Contains(got, missing) {+ t.Fatalf("canonicalization fallback log = %q, want path %q", got, missing)+ }+ if !strings.Contains(got, "error=") {+ t.Fatalf("canonicalization fallback log = %q, want error attribute", got)+ }+}++func TestResolveAgentExecutablePathKeepsPATHJunctionEntryPoint(t *testing.T) {+ _, shimBin := stageJunctionExecutable(t)+ t.Setenv("PATH", shimBin)+ t.Setenv("PATHEXT", ".EXE")++ got, err := resolveAgentExecutablePath("codex")+ if err != nil {+ t.Fatalf("resolveAgentExecutablePath: %v", err)+ }+ if want := filepath.Join(shimBin, "codex.exe"); !strings.EqualFold(got, want) {+ t.Fatalf("resolved PATH entry = %q, want stable junction entry %q", got, want)+ }+}++func TestResolveAgentEntryFollowsRetargetedInstallerJunction(t *testing.T) {+ originalDetect := detectAgentVersion+ detectAgentVersion = func(_ context.Context, path string) (string, error) {+ return filepath.Base(filepath.Dir(filepath.Dir(path))), nil+ }+ t.Cleanup(func() { detectAgentVersion = originalDetect })++ root := t.TempDir()+ releases := filepath.Join(root, "releases")+ installRelease := func(version string) string {+ bin := filepath.Join(releases, version, "bin")+ if err := os.MkdirAll(bin, 0o755); err != nil {+ t.Fatal(err)+ }+ executable := filepath.Join(bin, "codex.exe")+ copyTestExecutable(t, executable)+ return executable+ }+ v1 := installRelease("0.144.1")+ current := filepath.Join(root, "current")+ createJunction(t, filepath.Dir(filepath.Dir(v1)), current)+ visibleBin := filepath.Join(root, "visible", "bin")+ createJunction(t, filepath.Join(current, "bin"), visibleBin)+ stableExecutable := filepath.Join(visibleBin, "codex.exe")++ d := newSelfHealTestDaemon()+ d.setAgentVersion("codex", "0.144.1")+ entry := AgentEntry{Path: stableExecutable, Command: stableExecutable}+ got, version := d.resolveAgentEntry(context.Background(), "codex", entry)+ assertResolvedExecutable(t, got.Path, stableExecutable, v1)+ if version != "0.144.1" {+ t.Fatalf("initial version = %q, want 0.144.1", version)+ }+ assertLaunchesExecutable(t, got.Path, v1)++ v2 := installRelease("0.144.3")+ if err := os.Remove(current); err != nil {+ t.Fatalf("remove current junction: %v", err)+ }+ createJunction(t, filepath.Dir(filepath.Dir(v2)), current)++ got, version = d.resolveAgentEntry(context.Background(), "codex", entry)+ assertResolvedExecutable(t, got.Path, stableExecutable, v2)+ if version != "0.144.3" {+ t.Fatalf("version after retarget = %q, want 0.144.3", version)+ }+ assertLaunchesExecutable(t, got.Path, v2)+}++func TestResolveAgentEntryForLaunchRejectsUnverifiedInitialJunctionTarget(t *testing.T) {+ tests := []struct {+ name string+ detect func(context.Context, string) (string, error)+ check func(error) bool+ wantError string+ }{+ {+ name: "version detection failure",+ detect: func(context.Context, string) (string, error) {+ return "", errors.New("version probe failed")+ },+ check: func(err error) bool { return strings.Contains(err.Error(), "version probe failed") },+ wantError: "version probe failed",+ },+ {+ name: "below minimum version",+ detect: func(context.Context, string) (string, error) {+ return "0.9.0", nil+ },+ check: func(err error) bool {+ var tooOld *agent.BelowMinimumError+ return errors.As(err, &tooOld)+ },+ wantError: "BelowMinimumError",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ originalDetect := detectAgentVersion+ detectAgentVersion = tt.detect+ t.Cleanup(func() { detectAgentVersion = originalDetect })++ _, shimBin := stageJunctionExecutable(t)+ stableExecutable := filepath.Join(shimBin, "codex.exe")+ d := newSelfHealTestDaemon()+ d.setAgentVersion("codex", "0.144.1")+ entry := AgentEntry{Path: stableExecutable, Command: stableExecutable}++ got, _, err := d.resolveAgentEntryForLaunch(context.Background(), "codex", entry)+ if err == nil {+ t.Fatalf("resolveAgentEntryForLaunch launched unverified target %q; want %s", got.Path, tt.wantError)+ }+ if !tt.check(err) {+ t.Fatalf("resolveAgentEntryForLaunch error = %v, want %s", err, tt.wantError)+ }+ })+ }+}++func TestResolveAgentEntryDoesNotSharePreRetargetSingleflightResult(t *testing.T) {+ root := t.TempDir()+ releases := filepath.Join(root, "releases")+ installRelease := func(version string) string {+ bin := filepath.Join(releases, version, "bin")+ if err := os.MkdirAll(bin, 0o755); err != nil {+ t.Fatal(err)+ }+ executable := filepath.Join(bin, "codex.exe")+ copyTestExecutable(t, executable)+ return executable+ }+ v1 := installRelease("0.144.1")+ v2 := installRelease("0.144.3")+ current := filepath.Join(root, "current")+ createJunction(t, filepath.Dir(filepath.Dir(v1)), current)+ visibleBin := filepath.Join(root, "visible", "bin")+ createJunction(t, filepath.Join(current, "bin"), visibleBin)+ stableExecutable := filepath.Join(visibleBin, "codex.exe")++ v1ProbeStarted := make(chan struct{})+ releaseV1Probe := make(chan struct{})+ v2ProbeStarted := make(chan struct{}, 1)+ originalDetect := detectAgentVersion+ detectAgentVersion = func(_ context.Context, path string) (string, error) {+ switch {+ case sameFile(path, v1):+ select {+ case <-v1ProbeStarted:+ default:+ close(v1ProbeStarted)+ }+ <-releaseV1Probe+ return "0.144.1", nil+ case sameFile(path, v2):+ select {+ case v2ProbeStarted <- struct{}{}:+ default:+ }+ return "0.144.3", nil+ default:+ return "", errors.New("unexpected version probe path")+ }+ }+ t.Cleanup(func() { detectAgentVersion = originalDetect })++ d := newSelfHealTestDaemon()+ d.setAgentVersion("codex", "0.144.1")+ entry := AgentEntry{Path: stableExecutable, Command: stableExecutable}+ type resolution struct {+ entry AgentEntry+ version string+ }+ first := make(chan resolution, 1)+ go func() {+ got, version := d.resolveAgentEntry(context.Background(), "codex", entry)+ first <- resolution{entry: got, version: version}+ }()+ <-v1ProbeStarted++ if err := os.Remove(current); err != nil {+ t.Fatalf("remove current junction: %v", err)+ }+ createJunction(t, filepath.Dir(filepath.Dir(v2)), current)++ second := make(chan resolution, 1)+ go func() {+ got, version := d.resolveAgentEntry(context.Background(), "codex", entry)+ second <- resolution{entry: got, version: version}+ }()++ select {+ case <-v2ProbeStarted:+ // The post-retarget caller is verifying v2 independently of the blocked+ // v1 probe, so it cannot inherit the predecessor's singleflight result.+ case <-time.After(5 * time.Second):+ close(releaseV1Probe)+ got := <-second+ t.Fatalf("post-retarget resolution shared the blocked v1 probe: got (%q, %q)", got.entry.Path, got.version)+ }+ close(releaseV1Probe)++ got := <-second+ assertResolvedExecutable(t, got.entry.Path, stableExecutable, v2)+ if got.version != "0.144.3" {+ t.Fatalf("post-retarget version = %q, want 0.144.3", got.version)+ }+ firstGot := <-first+ assertResolvedExecutable(t, firstGot.entry.Path, stableExecutable, v2)+ if firstGot.version != "0.144.3" {+ t.Fatalf("pre-retarget caller final version = %q, want current 0.144.3", firstGot.version)+ }+}++func TestResolveAgentEntryForLaunchFailsWhenJunctionKeepsRetargeting(t *testing.T) {+ root := t.TempDir()+ releases := filepath.Join(root, "releases")+ installRelease := func(version string) string {+ bin := filepath.Join(releases, version, "bin")+ if err := os.MkdirAll(bin, 0o755); err != nil {+ t.Fatal(err)+ }+ executable := filepath.Join(bin, "codex.exe")+ copyTestExecutable(t, executable)+ return executable+ }+ v1 := installRelease("0.144.1")+ v2 := installRelease("0.144.3")+ current := filepath.Join(root, "current")+ retarget := func(target string) {+ if err := os.Remove(current); err != nil && !os.IsNotExist(err) {+ t.Fatalf("remove current junction: %v", err)+ }+ createJunction(t, filepath.Dir(filepath.Dir(target)), current)+ }+ retarget(v1)+ visibleBin := filepath.Join(root, "visible", "bin")+ createJunction(t, filepath.Join(current, "bin"), visibleBin)+ stableExecutable := filepath.Join(visibleBin, "codex.exe")++ originalDetect := detectAgentVersion+ detectAgentVersion = func(_ context.Context, path string) (string, error) {+ if sameFile(path, v1) {+ retarget(v2)+ return "0.144.1", nil+ }+ if sameFile(path, v2) {+ retarget(v1)+ return "0.144.3", nil+ }+ return "", errors.New("unexpected version probe path")+ }+ t.Cleanup(func() { detectAgentVersion = originalDetect })++ d := newSelfHealTestDaemon()+ d.setAgentVersion("codex", "0.144.1")+ entry := AgentEntry{Path: stableExecutable, Command: stableExecutable}+ got, _, err := d.resolveAgentEntryForLaunch(context.Background(), "codex", entry)+ if err == nil {+ t.Fatalf("resolveAgentEntryForLaunch returned stale target %q while junction kept retargeting", got.Path)+ }+ if !strings.Contains(err.Error(), "changed repeatedly") {+ t.Fatalf("resolveAgentEntryForLaunch error = %v, want repeated-retarget failure", err)+ }+}++func TestResolveAgentEntryCanonicalizesRediscoveredJunction(t *testing.T) {+ originalDetect := detectAgentVersion+ detectAgentVersion = func(_ context.Context, path string) (string, error) {+ return "0.144.3", nil+ }+ t.Cleanup(func() { detectAgentVersion = originalDetect })++ targetExecutable, shimBin := stageJunctionExecutable(t)+ t.Setenv("PATH", shimBin)+ t.Setenv("PATHEXT", ".EXE")+ d := newSelfHealTestDaemon()+ d.setAgentVersion("codex", "0.144.1")+ entry := AgentEntry{Path: filepath.Join(t.TempDir(), "removed", "codex.exe"), Command: "codex"}++ got, version := d.resolveAgentEntry(context.Background(), "codex", entry)+ assertResolvedExecutable(t, got.Path, filepath.Join(shimBin, "codex.exe"), targetExecutable)+ if version != "0.144.3" {+ t.Fatalf("rediscovered version = %q, want 0.144.3", version)+ }+}++func TestResolveAgentEntryForLaunchRejectsRediscoveredJunctionWhenFinalPathResolutionFails(t *testing.T) {+ targetExecutable, shimBin := stageJunctionExecutable(t)+ stableExecutable := filepath.Join(shimBin, "codex.exe")+ t.Setenv("PATH", shimBin)+ t.Setenv("PATHEXT", ".EXE")++ originalDetect := detectAgentVersion+ detectCalled := false+ detectAgentVersion = func(context.Context, string) (string, error) {+ detectCalled = true+ return "0.144.3", nil+ }+ t.Cleanup(func() { detectAgentVersion = originalDetect })++ resolutionErr := errors.New("final path volume has no DOS name")+ originalLaunchResolver := executablePathForLaunch+ executablePathForLaunch = func(path string) (string, bool, error) {+ if strings.EqualFold(path, stableExecutable) {+ return "", true, resolutionErr+ }+ return originalLaunchResolver(path)+ }+ t.Cleanup(func() { executablePathForLaunch = originalLaunchResolver })++ var logs bytes.Buffer+ d := newSelfHealTestDaemon()+ d.logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))+ d.setAgentVersion("codex", "0.144.1")+ entry := AgentEntry{Path: filepath.Join(t.TempDir(), "removed", "codex.exe"), Command: "codex"}++ got, _, err := d.resolveAgentEntryForLaunch(context.Background(), "codex", entry)+ if err == nil {+ t.Fatalf("resolveAgentEntryForLaunch returned rediscovered unresolved path %q; want final-path failure", got.Path)+ }+ if !errors.Is(err, resolutionErr) {+ t.Fatalf("resolveAgentEntryForLaunch error = %v, want %v", err, resolutionErr)+ }+ if detectCalled {+ t.Fatal("detectAgentVersion was called for an unverified rediscovered launch target")+ }+ d.resolvedPathsMu.RLock()+ _, cached := d.resolvedPaths["codex"]+ d.resolvedPathsMu.RUnlock()+ if cached {+ t.Fatal("unverified rediscovered launch target was cached in resolvedPaths")+ }+ if strings.EqualFold(got.Path, stableExecutable) || sameFile(got.Path, targetExecutable) {+ t.Fatalf("resolveAgentEntryForLaunch returned a launchable target %q after resolution failure", got.Path)+ }++ logText := logs.String()+ if !strings.Contains(logText, "level=WARN") {+ t.Fatalf("rediscovery resolution failure log = %q, want WARN", logText)+ }+ if !strings.Contains(logText, stableExecutable) {+ t.Fatalf("rediscovery resolution failure log = %q, want path %q", logText, stableExecutable)+ }+ if !strings.Contains(logText, resolutionErr.Error()) {+ t.Fatalf("rediscovery resolution failure log = %q, want error %q", logText, resolutionErr)+ }+}++func TestCanonicalExecutablePathLaunchesBeyondMaxPath(t *testing.T) {+ deep := t.TempDir()+ for len(deep) < 280 {+ deep = filepath.Join(deep, "release-segment-0123456789")+ }+ deep = `\\?\` + deep+ if err := os.MkdirAll(deep, 0o755); err != nil {+ t.Fatalf("create long release path: %v", err)+ }++ target := filepath.Join(deep, "codex.exe")+ copyTestExecutable(t, target)+ shimBin := filepath.Join(t.TempDir(), "bin")+ createJunction(t, deep, shimBin)+ shimExecutable := filepath.Join(shimBin, "codex.exe")++ resolved := canonicalExecutablePath(shimExecutable)+ if !strings.HasPrefix(resolved, `\\?\`) {+ t.Fatalf("resolved long executable dropped extended-length prefix: %q", resolved)+ }+ assertLaunchesExecutable(t, resolved, target)+}++func TestResolveAgentExecutablePathKeepsConfiguredJunctionEntryPoint(t *testing.T) {+ _, shimBin := stageJunctionExecutable(t)+ configured := filepath.Join(shimBin, "codex.exe")++ got, err := resolveAgentExecutablePath(configured)+ if err != nil {+ t.Fatalf("resolveAgentExecutablePath: %v", err)+ }+ if !strings.EqualFold(got, configured) {+ t.Fatalf("resolved configured entry = %q, want stable junction entry %q", got, configured)+ }+}++func assertResolvedExecutable(t *testing.T, got, shim, target string) {+ t.Helper()+ if strings.EqualFold(got, shim) {+ t.Fatalf("resolved executable still points at junction path %q", got)+ }+ assertSameFile(t, got, target)+}++func assertSameFile(t *testing.T, got, want string) {+ t.Helper()+ gotInfo, err := os.Stat(got)+ if err != nil {+ t.Fatalf("stat resolved executable %q: %v", got, err)+ }+ wantInfo, err := os.Stat(want)+ if err != nil {+ t.Fatalf("stat expected executable %q: %v", want, err)+ }+ if !os.SameFile(gotInfo, wantInfo) {+ t.Fatalf("resolved executable %q does not identify expected file %q", got, want)+ }+}++func sameFile(left, right string) bool {+ leftInfo, leftErr := os.Stat(left)+ rightInfo, rightErr := os.Stat(right)+ return leftErr == nil && rightErr == nil && os.SameFile(leftInfo, rightInfo)+}++func assertLaunchesExecutable(t *testing.T, executable, want string) {+ t.Helper()+ marker := filepath.Join(t.TempDir(), "launched-from")+ cmd := exec.Command(executable, "-test.run=^TestLongPathExecutableHelper$")+ cmd.Env = append(os.Environ(),+ longPathExecutableHelperEnv+"=1",+ longPathExecutableMarkerEnv+"="+marker,+ )+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("launch executable %q: %v\n%s", executable, err, output)+ }+ launchedFrom, err := os.ReadFile(marker)+ if err != nil {+ t.Fatalf("read launched executable marker: %v", err)+ }+ assertSameFile(t, string(launchedFrom), want)+}++func copyTestExecutable(t *testing.T, target string) {+ t.Helper()+ source, err := os.Open(os.Args[0])+ if err != nil {+ t.Fatal(err)+ }+ defer source.Close()+ destination, err := os.Create(target)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := io.Copy(destination, source); err != nil {+ destination.Close()+ t.Fatal(err)+ }+ if err := destination.Close(); err != nil {+ t.Fatal(err)+ }+}++func stageJunctionExecutable(t *testing.T) (targetExecutable, shimBin string) {+ t.Helper()+ targetBin := filepath.Join(t.TempDir(), "release", "bin")+ if err := os.MkdirAll(targetBin, 0o755); err != nil {+ t.Fatal(err)+ }+ targetExecutable = filepath.Join(targetBin, "codex.exe")+ if err := os.WriteFile(targetExecutable, []byte("test"), 0o755); err != nil {+ t.Fatal(err)+ }+ shimBin = filepath.Join(t.TempDir(), "installer", "bin")+ createJunction(t, targetBin, shimBin)+ return targetExecutable, shimBin+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex bd6a314c31..a0f8218714 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -421,16 +421,13 @@ type Daemon struct {// newer than that verdict" a fact rather than a hope. Guarded by d.mu.demotionSeq uint64- // resolvedPathsMu guards resolvedPaths, the self-healed executable paths.- // The daemon pins each agent's absolute path at startup so a later PATH- // change can't redirect a task launch. When that pinned path later vanishes- // (a version manager did an in-place upgrade — Homebrew Cask, nvm/fnm),- // resolveAgentEntry re-resolves the original command once and records the- // result here so subsequent launches, model lists, and registrations reuse- // it without re-resolving. Path and detected version are stored together so- // any reader that observes the new path also observes the matching version- // (no "new binary under stale version policy" window). Keyed by provider.- // See MUL-4486.+ // resolvedPathsMu guards concrete executable paths paired with the version+ // detected for each. On POSIX these are self-heals cached after a pinned path+ // vanishes (MUL-4486). On Windows they are launch targets resolved from a+ // stable installer junction; that junction is followed on every launch so a+ // retarget takes effect even while the old release remains installed. Path+ // and version are stored together so no reader can launch a new binary under+ // stale version policy. Keyed by provider.resolvedPathsMu sync.RWMutexresolvedPaths map[string]healedAgent// healGroup coalesces concurrent self-heal re-resolutions per provider so a@@ -821,11 +818,13 @@ type healedAgent struct {}// resolveAgentEntry returns entry with a usable executable path plus the CLI-// version that corresponds to that path, self-healing the pinned Path when it-// has vanished from disk (MUL-4486).+// version that corresponds to that path. It resolves retargetable Windows+// installer junctions per launch and self-heals vanished pinned paths on other+// platforms (MUL-4486).//-// The daemon pins each agent's absolute, symlink-resolved path at startup so a-// later PATH change cannot redirect a task launch. But a version manager+// The daemon pins each agent's discovered entry point at startup so a later+// PATH change cannot redirect a task launch. POSIX discovery also resolves+// symlinks to a concrete path. But a version manager// (Homebrew Cask, nvm/fnm) upgrading in place deletes the old versioned// directory that pinned path points into and repoints the stable command name// at the new version — leaving the daemon holding a path that no longer exists@@ -839,6 +838,8 @@ type healedAgent struct {// updating.//// Behaviour:+// - A Windows stable entry point -> its final target is verified and returned+// with the detected version; a retarget publishes the new pair atomically.// - A previous self-heal that is still live -> returned with its paired// version. This is checked first so that once we've re-resolved to a new// binary, a reappearing stale path (a downgrade / reinstall recreating the@@ -862,6 +863,24 @@ func (d *Daemon) resolveAgentEntry(ctx context.Context, provider string, entry Areturn resolved, version}+// resolveAgentEntryForLaunch is the strict task-launch boundary. Windows+// installer junctions must yield a verified final target before the first+// launch; otherwise the stable entry could retarget after registration and run+// a binary whose version and minimum-version policy were never checked.+func (d *Daemon) resolveAgentEntryForLaunch(ctx context.Context, provider string, entry AgentEntry) (AgentEntry, string, error) {+ resolved, version, outcome := d.resolveAgentEntryWithHeal(ctx, provider, entry)+ if outcome.rejected != nil {+ return entry, d.agentVersion(provider), outcome.rejected+ }+ if outcome.failure != nil {+ return entry, d.agentVersion(provider), fmt.Errorf("resolve agent executable %q for launch: %w", entry.Path, outcome.failure)+ }+ if outcome.adopted.path != "" {+ return resolved, version, nil+ }+ return resolved, version, nil+}+// healOutcome is what one self-heal attempt concluded. At most one half is// meaningful: adopted names a binary that cleared the same gates registration// applies, while rejected carries the typed verdict for a candidate that was@@ -872,6 +891,7 @@ func (d *Daemon) resolveAgentEntry(ctx context.Context, provider string, entry Atype healOutcome struct {adopted healedAgentrejected *agent.BelowMinimumError+ failure error}// resolveAgentEntryWithHeal is resolveAgentEntry plus what the self-heal@@ -884,6 +904,25 @@ type healOutcome struct {// fails, and reports "version detection failed" — which by design leaves the// runtime online, claiming tasks for a CLI that cannot launch.func (d *Daemon) resolveAgentEntryWithHeal(ctx context.Context, provider string, entry AgentEntry) (AgentEntry, string, healOutcome) {+ // Windows installer entry points are stable junctions whose final target can+ // change while the old release remains installed. Resolve the final path on+ // every launch and adopt a changed target only after pairing it with a freshly+ // detected, supported version. Other platforms return handled=false and keep+ // the existing pinned-path self-heal semantics below.+ var launchOutcome healOutcome+ if launchPath, handled, err := executablePathForLaunch(entry.Path); handled {+ if err != nil {+ d.logger.Warn("resolve agent executable for launch failed; keeping discovered path",+ "provider", provider, "path", entry.Path, "error", err)+ launchOutcome.failure = err+ } else if outcome, ok := d.resolveAgentLaunchTarget(ctx, provider, entry, launchPath); ok {+ entry.Path = outcome.adopted.path+ return entry, outcome.adopted.version, outcome+ } else {+ launchOutcome = outcome+ }+ }+// A prior self-heal wins over the original pinned path: it carries a// {path, version} pair we already verified together, so it can never regress// to the mismatched pairing a reappearing stale path would produce.@@ -892,11 +931,12 @@ func (d *Daemon) resolveAgentEntryWithHeal(ctx context.Context, provider string,d.resolvedPathsMu.RUnlock()if ok && agentExecutablePresent(healed.path) {entry.Path = healed.path- return entry, healed.version, healOutcome{adopted: healed}+ launchOutcome.adopted = healed+ return entry, healed.version, launchOutcome}if agentExecutablePresent(entry.Path) {- return entry, d.agentVersion(provider), healOutcome{}+ return entry, d.agentVersion(provider), launchOutcome}if entry.Command == "" {@@ -918,6 +958,63 @@ func (d *Daemon) resolveAgentEntryWithHeal(ctx context.Context, provider string,return entry, outcome.adopted.version, outcome}+// resolveAgentLaunchTarget handles platforms whose stable discovered entry+// point can retarget a different still-live executable. It returns ok only+// when a verified {path, version} pair is available; a rejected or transiently+// unreadable target falls through to the existing path handling so it is never+// published under a stale version.+func (d *Daemon) resolveAgentLaunchTarget(ctx context.Context, provider string, entry AgentEntry, launchPath string) (healOutcome, bool) {+ const maxRetargetAttempts = 4+ for attempt := 0; attempt < maxRetargetAttempts; attempt++ {+ d.resolvedPathsMu.RLock()+ cached, cachedOK := d.resolvedPaths[provider]+ d.resolvedPathsMu.RUnlock()+ if cachedOK && cached.path == launchPath && agentExecutablePresent(cached.path) {+ return healOutcome{adopted: cached}, true+ }++ // Coalesce only callers that observed the same concrete release. A+ // provider-only key can make a post-retarget caller inherit the previous+ // release's result even though both files remain present.+ key := provider + "\x00" + launchPath+ v, _, _ := d.healGroup.Do(key, func() (any, error) {+ d.resolvedPathsMu.RLock()+ current, ok := d.resolvedPaths[provider]+ d.resolvedPathsMu.RUnlock()+ if ok && current.path == launchPath && agentExecutablePresent(current.path) {+ return healOutcome{adopted: current}, nil+ }+ return d.adoptAgentPath(ctx, provider, entry.Command, launchPath, "resolved stable entry point for launch"), nil+ })+ outcome, _ := v.(healOutcome)++ // The installer may retarget while version detection is running. Resolve+ // again before returning and retry against the target visible now.+ currentPath, _, err := executablePathForLaunch(entry.Path)+ if err != nil {+ if outcome.adopted.path != "" {+ return outcome, true+ }+ outcome.failure = err+ return outcome, false+ }+ if currentPath != launchPath {+ launchPath = currentPath+ continue+ }+ if outcome.adopted.path != "" {+ return outcome, true+ }+ if cachedOK && agentExecutablePresent(cached.path) {+ outcome.adopted = cached+ return outcome, true+ }+ return outcome, false+ }++ return healOutcome{failure: errors.New("installer entry point changed repeatedly while resolving it")}, false+}+// healAgentPath re-resolves command for provider and, if a usable binary is// found, records it and returns it. "Usable" means: it resolves, its version// can be detected, and that version meets the same minimum-version gate@@ -946,7 +1043,19 @@ func (d *Daemon) healAgentPath(ctx context.Context, provider, command string) heif !found {return healOutcome{}}+ if launchPath, handled, err := executablePathForLaunch(newPath); handled {+ if err != nil {+ d.logger.Warn("resolve re-discovered agent executable for launch failed; keeping discovered path",+ "provider", provider, "path", newPath, "error", err)+ return healOutcome{failure: err}+ } else {+ newPath = launchPath+ }+ }+ return d.adoptAgentPath(ctx, provider, command, newPath, "re-resolved after pinned path vanished")+}+func (d *Daemon) adoptAgentPath(ctx context.Context, provider, command, newPath, reason string) healOutcome {// Verify before adopting. An in-place "upgrade" that actually repoints at an// older or broken install must not be launched under the daemon's stale// version policy, and must not slip past the minimum-version gate that the@@ -955,7 +1064,7 @@ func (d *Daemon) healAgentPath(ctx context.Context, provider, command string) heif err != nil {d.logger.Warn("re-resolved agent executable failed version detection; keeping pinned path","provider", provider, "command", command, "new_path", newPath, "error", err)- return healOutcome{}+ return healOutcome{failure: err}}if err := checkAgentMinVersion(provider, version); err != nil {var tooOld *agent.BelowMinimumError@@ -966,7 +1075,7 @@ func (d *Daemon) healAgentPath(ctx context.Context, provider, command string) he// transient case the below-minimum machinery must never act on.d.logger.Warn("re-resolved agent executable version could not be validated; keeping pinned path","provider", provider, "command", command, "new_path", newPath, "version", version, "error", err)- return healOutcome{}+ return healOutcome{failure: err}}d.logger.Warn("re-resolved agent executable is below the minimum supported version; not adopting it","provider", provider, "command", command, "new_path", newPath, "version", version, "error", err)@@ -988,8 +1097,8 @@ func (d *Daemon) healAgentPath(ctx context.Context, provider, command string) he// report and any future d.agentVersion reader.d.setAgentVersion(provider, version)- d.logger.Info("re-resolved agent executable after pinned path vanished (in-place upgrade)",- "provider", provider, "command", command, "new_path", newPath, "version", version)+ d.logger.Info("adopted resolved agent executable",+ "provider", provider, "command", command, "new_path", newPath, "version", version, "reason", reason)return healOutcome{adopted: adopted}}@@ -5733,7 +5842,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// upgrade deleted (MUL-4486). Only reached when no custom profile owns// the launch, so a custom runtime's path is never second-guessed and a// custom-only host pays no wasted re-resolution.- entry, resolvedVersion = d.resolveAgentEntry(prepareCtx, provider, entry)+ var resolveErr error+ entry, resolvedVersion, resolveErr = d.resolveAgentEntryForLaunch(prepareCtx, provider, entry)+ if resolveErr != nil {+ return TaskResult{}, resolveErr+ }}if !ok {return TaskResult{}, fmt.Errorf("no agent configured for provider %q", provider)diff --git a/server/internal/daemon/runtime_launch_windows_test.go b/server/internal/daemon/runtime_launch_windows_test.gonew file mode 100644index 0000000000..a545553105--- /dev/null+++ b/server/internal/daemon/runtime_launch_windows_test.go@@ -0,0 +1,87 @@+//go:build windows++package daemon++import (+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++func TestHandleTaskReportsWindowsCodexProcessStartFailure(t *testing.T) {+ invalidExecutable := filepath.Join(t.TempDir(), "codex.exe")+ if err := os.WriteFile(invalidExecutable, []byte("not a Windows executable"), 0o755); err != nil {+ t.Fatal(err)+ }++ var failBody atomic.Value+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/fail"):+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("decode failure body: %v", err)+ } else {+ failBody.Store(body)+ }+ case strings.HasSuffix(r.URL.Path, "/status"):+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{"status":"running"}`)+ return+ }+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ d := New(Config{+ ServerBaseURL: srv.URL,+ WorkspacesRoot: t.TempDir(),+ AgentTimeout: 5 * time.Second,+ }, logger)+ d.executionEnvironmentCommand = nil+ d.client = NewClient(srv.URL)+ d.cancelPollInterval = time.Hour+ d.runtimeIndex["rt-custom-codex"] = Runtime{+ ID: "rt-custom-codex",+ Provider: "codex",+ ProfileID: "profile-invalid-codex",+ }+ d.profileLaunchSpecs["profile-invalid-codex"] = profileLaunchSpec{+ path: invalidExecutable,+ version: "0.147.0",+ }++ d.handleTask(context.Background(), Task{+ ID: "task-windows-launch-failure",+ WorkspaceID: "workspace-windows-launch-failure",+ RuntimeID: "rt-custom-codex",+ IssueID: "issue-windows-launch-failure",+ AgentID: "agent-windows-launch-failure",+ AuthToken: "mat_windows_launch_failure",+ Agent: &AgentData{+ ID: "agent-windows-launch-failure",+ Name: "Windows launch failure agent",+ },+ }, 0)++ body, _ := failBody.Load().(map[string]any)+ if body == nil {+ t.Fatal("runtime CreateProcess failure was not reported through the task /fail endpoint")+ }+ if got := body["error"]; got == nil || !strings.Contains(strings.ToLower(got.(string)), "start codex") {+ t.Fatalf("task failure error = %v, want visible Codex process-start diagnostic", got)+ }+ if got := body["failure_reason"]; got != "agent_error.process_failure" {+ t.Fatalf("task failure reason = %v, want agent_error.process_failure", got)+ }+}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex f26f79df67..d05970891a 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -8,7 +8,7 @@ import (// AgentEntry describes a single available agent CLI.type AgentEntry struct {- Path string // path to CLI binary (pinned at startup; symlink-resolved to a concrete, possibly versioned, path)+ Path string // stable startup-resolved CLI entry point; launch resolution may follow platform links to a concrete path// Command is the bare command name or MULTICA_*_PATH value that Path was// resolved from at startup. It is kept so the daemon can re-resolve Path// if the pinned executable later vanishes — e.g. a version managerdiff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.goindex d7728cb9bc..f0fd1bff19 100644--- a/server/pkg/taskfailure/classify.go+++ b/server/pkg/taskfailure/classify.go@@ -258,6 +258,7 @@ func Classify(rawError string) Reason {"panic","sigsegv","process exited",+ "start codex:","pipe has been ended","file already closed","initialize failed",diff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.goindex 1ca35d8294..a7cc3060e2 100644--- a/server/pkg/taskfailure/classify_test.go+++ b/server/pkg/taskfailure/classify_test.go@@ -214,6 +214,7 @@ func TestClassifyOrderingPriorities(t *testing.T) {// — the upstream classification should win because the// process_failure rule is checked last.{"exit status with 401 upstream", "exit status 1: API Error: 401 Unauthorized", ReasonAgentProviderAuthOrAccess},+ {"windows codex process start", "start codex: fork/exec C:\\invalid\\codex.exe: %1 is not a valid Win32 application.", ReasonAgentProcessFailure},}for _, c := range cases {t.Run(c.name, func(t *testing.T) {