Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(cli): recover daemon executable path (MUL-4514)

Multica Evea91a390d4831
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index ac8caffe14..abeee1fb69 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -22,6 +22,7 @@ import (
"github.com/multica-ai/multica/server/internal/cli"
"github.com/multica-ai/multica/server/internal/daemon"
logger_pkg "github.com/multica-ai/multica/server/internal/logger"
+ "github.com/multica-ai/multica/server/internal/selfexec"
"github.com/multica-ai/multica/server/internal/util"
)
@@ -260,8 +261,8 @@ func runDaemonBackground(cmd *cobra.Command) error {
return fmt.Errorf("%s is already running (pid %v). Use 'daemon restart' to restart it", label, int(pid))
}
- // Resolve current executable.
- exePath, err := os.Executable()
+ // Resolve current executable so the foreground child reuses this binary.
+ exePath, err := selfexec.Resolve()
if err != nil {
return fmt.Errorf("resolve executable path: %w", err)
}
diff --git a/server/internal/cli/update.go b/server/internal/cli/update.go
index cb02999272..72e96e9dee 100644
--- a/server/internal/cli/update.go
+++ b/server/internal/cli/update.go
@@ -19,6 +19,8 @@ import (
"strconv"
"strings"
"time"
+
+ "github.com/multica-ai/multica/server/internal/selfexec"
)
// ChecksumManifestName is the asset name GoReleaser publishes for the
@@ -291,7 +293,7 @@ func MatchKnownBrewPrefix(path string) string {
// IsBrewInstall checks whether the running multica binary was installed via Homebrew.
func IsBrewInstall() bool {
- exePath, err := os.Executable()
+ exePath, err := selfexec.Resolve()
if err != nil {
return false
}
@@ -361,7 +363,7 @@ func UpdateViaDownload(targetVersion string) (string, error) {
// UpdateViaDownloadWithTimeout downloads the latest release binary with a caller-selected timeout.
func UpdateViaDownloadWithTimeout(targetVersion string, downloadTimeout time.Duration) (string, error) {
// Determine current binary path.
- exePath, err := os.Executable()
+ exePath, err := selfexec.Resolve()
if err != nil {
return "", fmt.Errorf("resolve executable path: %w", err)
}
diff --git a/server/internal/cli/update_windows.go b/server/internal/cli/update_windows.go
index 98a7afdead..a2e212b2f1 100644
--- a/server/internal/cli/update_windows.go
+++ b/server/internal/cli/update_windows.go
@@ -6,6 +6,8 @@ import (
"fmt"
"os"
"path/filepath"
+
+ "github.com/multica-ai/multica/server/internal/selfexec"
)
// oldBinarySuffix is appended to the previous executable while a new one is
@@ -49,7 +51,7 @@ func replaceBinary(tmpPath, exePath string) error {
// updates. Windows can't delete a running .exe, so a prior update may have
// left one behind; once the user restarts, this call reclaims the space.
func CleanupStaleUpdateArtifacts() {
- exePath, err := os.Executable()
+ exePath, err := selfexec.Resolve()
if err != nil {
return
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 552d104706..48dee603be 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -23,6 +23,7 @@ import (
"github.com/multica-ai/multica/server/internal/cli"
"github.com/multica-ai/multica/server/internal/daemon/execenv"
"github.com/multica-ai/multica/server/internal/daemon/repocache"
+ "github.com/multica-ai/multica/server/internal/selfexec"
"github.com/multica-ai/multica/server/pkg/agent"
"github.com/multica-ai/multica/server/pkg/skillbundle"
"github.com/multica-ai/multica/server/pkg/taskfailure"
@@ -82,9 +83,10 @@ func (f taskRunnerFunc) run(ctx context.Context, task Task, provider string, slo
}
var (
- isBrewInstall = cli.IsBrewInstall
- getBrewPrefix = cli.GetBrewPrefix
- matchKnownBrewPrefix = cli.MatchKnownBrewPrefix
+ isBrewInstall = cli.IsBrewInstall
+ getBrewPrefix = cli.GetBrewPrefix
+ matchKnownBrewPrefix = cli.MatchKnownBrewPrefix
+ resolveSelfExecutable = selfexec.Resolve
// detectAgentVersion / checkAgentMinVersion are indirections over the
// real agent helpers so tests can run the registration path without
@@ -2682,7 +2684,7 @@ func (d *Daemon) releaseClaimBarrier() {
// For non-brew installs, it resolves to the absolute path of the replaced binary.
// The caller (cmd_daemon.go) checks RestartBinary() and launches the new process.
func (d *Daemon) triggerRestart() {
- newBin, err := os.Executable()
+ newBin, err := resolveSelfExecutable()
if err != nil {
d.logger.Error("could not resolve executable path for restart", "error", err)
return
@@ -4008,7 +4010,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// Some runtimes (e.g. Codex) run in an isolated sandbox that may not
// inherit the daemon's PATH. Prepend the directory of the running
// multica binary so that `multica` commands in the agent always resolve.
- if selfBin, err := os.Executable(); err == nil {
+ if selfBin, err := resolveSelfExecutable(); err == nil {
binDir := filepath.Dir(selfBin)
agentEnv["PATH"] = binDir + string(os.PathListSeparator) + os.Getenv("PATH")
}
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index dd8ae756c6..ea9a254fbb 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -83,6 +83,62 @@ func TestTriggerRestart_BrewLinuxCellarDeleted(t *testing.T) {
}
}
+func TestTriggerRestart_UsesResolvedFallback(t *testing.T) {
+ originalResolveSelfExecutable := resolveSelfExecutable
+ originalIsBrewInstall := isBrewInstall
+ t.Cleanup(func() {
+ resolveSelfExecutable = originalResolveSelfExecutable
+ isBrewInstall = originalIsBrewInstall
+ })
+
+ want := filepath.Join(t.TempDir(), "multica")
+ if err := os.WriteFile(want, []byte("test executable"), 0o755); err != nil {
+ t.Fatalf("write executable fixture: %v", err)
+ }
+ wantResolved, err := filepath.EvalSymlinks(want)
+ if err != nil {
+ t.Fatalf("resolve executable fixture: %v", err)
+ }
+ resolveSelfExecutable = func() (string, error) { return want, nil }
+ isBrewInstall = func() bool { return false }
+
+ canceled := false
+ d := &Daemon{
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ cancelFunc: func() { canceled = true },
+ }
+ d.triggerRestart()
+
+ if got := d.RestartBinary(); got != wantResolved {
+ t.Fatalf("restart binary = %q, want resolved fallback executable %q", got, wantResolved)
+ }
+ if !canceled {
+ t.Fatal("triggerRestart did not initiate graceful shutdown")
+ }
+}
+
+func TestTriggerRestart_ResolveFailureLeavesDaemonRunning(t *testing.T) {
+ originalResolveSelfExecutable := resolveSelfExecutable
+ t.Cleanup(func() { resolveSelfExecutable = originalResolveSelfExecutable })
+ resolveSelfExecutable = func() (string, error) {
+ return "", errors.New("cannot resolve executable")
+ }
+
+ canceled := false
+ d := &Daemon{
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ cancelFunc: func() { canceled = true },
+ }
+ d.triggerRestart()
+
+ if got := d.RestartBinary(); got != "" {
+ t.Fatalf("restart binary = %q, want empty", got)
+ }
+ if canceled {
+ t.Fatal("triggerRestart initiated shutdown without a restart binary")
+ }
+}
+
func TestIsBlockedEnvKey(t *testing.T) {
t.Parallel()
@@ -173,16 +229,25 @@ func TestTriggerRestart_BrewPrefixUnavailable_FallsBackToKnownPrefix(t *testing.
originalIsBrewInstall := isBrewInstall
originalGetBrewPrefix := getBrewPrefix
originalMatchKnownBrewPrefix := matchKnownBrewPrefix
+ originalResolveSelfExecutable := resolveSelfExecutable
t.Cleanup(func() {
isBrewInstall = originalIsBrewInstall
getBrewPrefix = originalGetBrewPrefix
matchKnownBrewPrefix = originalMatchKnownBrewPrefix
+ resolveSelfExecutable = originalResolveSelfExecutable
})
const knownPrefix = "/home/linuxbrew/.linuxbrew"
+ cellarPath := filepath.Join(knownPrefix, "Cellar", "multica", "0.2.9", "bin", "multica")
isBrewInstall = func() bool { return true }
getBrewPrefix = func() string { return "" }
- matchKnownBrewPrefix = func(string) string { return knownPrefix }
+ resolveSelfExecutable = func() (string, error) { return cellarPath, nil }
+ matchKnownBrewPrefix = func(path string) string {
+ if path != cellarPath {
+ t.Fatalf("MatchKnownBrewPrefix path = %q, want resolver result %q", path, cellarPath)
+ }
+ return knownPrefix
+ }
d := &Daemon{
logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
diff --git a/server/internal/migrations/migrations.go b/server/internal/migrations/migrations.go
index 17e6e9e765..c4fac5f521 100644
--- a/server/internal/migrations/migrations.go
+++ b/server/internal/migrations/migrations.go
@@ -6,6 +6,8 @@ import (
"path/filepath"
"sort"
"strings"
+
+ "github.com/multica-ai/multica/server/internal/selfexec"
)
const maxSearchDepth = 4
@@ -41,7 +43,7 @@ func ResolveDir() (string, error) {
func searchRoots() []string {
roots := []string{"."}
- if exe, err := os.Executable(); err == nil {
+ if exe, err := selfexec.Resolve(); err == nil {
roots = append(roots, filepath.Dir(exe))
}
return roots
diff --git a/server/internal/selfexec/selfexec.go b/server/internal/selfexec/selfexec.go
new file mode 100644
index 0000000000..506b90160d
--- /dev/null
+++ b/server/internal/selfexec/selfexec.go
@@ -0,0 +1,50 @@
+// Package selfexec resolves the executable backing the current process.
+package selfexec
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+)
+
+// Resolve prefers the OS-reported executable path. Some launch environments
+// can omit that metadata, so it falls back to argv[0] using normal executable
+// lookup semantics instead of treating a bare command name as relative to the
+// current directory.
+func Resolve() (string, error) {
+ return resolveWith(os.Executable, os.Args)
+}
+
+func resolveWith(osExecutable func() (string, error), args []string) (string, error) {
+ exePath, err := osExecutable()
+ if err == nil {
+ return exePath, nil
+ }
+ osExecutableErr := fmt.Errorf("os.Executable: %w", err)
+
+ if len(args) == 0 || args[0] == "" {
+ return "", errors.Join(osExecutableErr, errors.New("argv[0] is empty"))
+ }
+
+ candidate, fallbackErr := exec.LookPath(args[0])
+ if fallbackErr == nil {
+ candidate, fallbackErr = filepath.Abs(candidate)
+ }
+ if fallbackErr == nil {
+ var info os.FileInfo
+ info, fallbackErr = os.Stat(candidate)
+ if fallbackErr == nil && !info.Mode().IsRegular() {
+ fallbackErr = fmt.Errorf("%s is not a regular file", candidate)
+ }
+ }
+ if fallbackErr != nil {
+ return "", errors.Join(
+ osExecutableErr,
+ fmt.Errorf("resolve argv[0] %q: %w", args[0], fallbackErr),
+ )
+ }
+
+ return candidate, nil
+}
diff --git a/server/internal/selfexec/selfexec_test.go b/server/internal/selfexec/selfexec_test.go
new file mode 100644
index 0000000000..c20eea0d16
--- /dev/null
+++ b/server/internal/selfexec/selfexec_test.go
@@ -0,0 +1,128 @@
+package selfexec
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+func TestResolveWithUsesOSExecutable(t *testing.T) {
+ want := filepath.Join(t.TempDir(), "does-not-need-to-exist")
+
+ got, err := resolveWith(func() (string, error) {
+ return want, nil
+ }, nil)
+ if err != nil {
+ t.Fatalf("resolveWith() error = %v", err)
+ }
+ if got != want {
+ t.Fatalf("resolveWith() = %q, want %q", got, want)
+ }
+}
+
+func TestResolveWithFallsBackToArgv0(t *testing.T) {
+ executableErr := errors.New("cannot find executable path")
+ failExecutable := func() (string, error) { return "", executableErr }
+
+ t.Run("absolute path", func(t *testing.T) {
+ want := writeTestExecutable(t, t.TempDir(), "multica")
+
+ got, err := resolveWith(failExecutable, []string{want})
+ if err != nil {
+ t.Fatalf("resolveWith() error = %v", err)
+ }
+ if got != want {
+ t.Fatalf("resolveWith() = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("relative path", func(t *testing.T) {
+ dir := t.TempDir()
+ want := writeTestExecutable(t, dir, "multica")
+ t.Chdir(dir)
+ argv0 := "." + string(os.PathSeparator) + filepath.Base(want)
+
+ got, err := resolveWith(failExecutable, []string{argv0})
+ if err != nil {
+ t.Fatalf("resolveWith() error = %v", err)
+ }
+ if got != want {
+ t.Fatalf("resolveWith() = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("PATH command", func(t *testing.T) {
+ dir := t.TempDir()
+ want := writeTestExecutable(t, dir, "multica")
+ t.Setenv("PATH", dir)
+
+ got, err := resolveWith(failExecutable, []string{"multica"})
+ if err != nil {
+ t.Fatalf("resolveWith() error = %v", err)
+ }
+ if got != want {
+ t.Fatalf("resolveWith() = %q, want %q", got, want)
+ }
+ })
+}
+
+func TestResolveWithRejectsInvalidFallback(t *testing.T) {
+ executableErr := errors.New("cannot find executable path")
+ failExecutable := func() (string, error) { return "", executableErr }
+
+ tests := []struct {
+ name string
+ args []string
+ want string
+ }{
+ {name: "missing argv0", args: nil, want: "argv[0] is empty"},
+ {name: "empty argv0", args: []string{""}, want: "argv[0] is empty"},
+ {name: "missing executable", args: []string{"multica-does-not-exist"}, want: "multica-does-not-exist"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ _, err := resolveWith(failExecutable, tt.args)
+ if err == nil {
+ t.Fatal("resolveWith() error = nil, want failure")
+ }
+ if !errors.Is(err, executableErr) {
+ t.Fatalf("error = %q, want original os.Executable error", err)
+ }
+ if !strings.Contains(err.Error(), tt.want) {
+ t.Fatalf("error = %q, want %q", err, tt.want)
+ }
+ })
+ }
+
+ if runtime.GOOS != "windows" {
+ t.Run("non-executable file", func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "multica")
+ if err := os.WriteFile(path, []byte("not executable"), 0o644); err != nil {
+ t.Fatalf("write non-executable fixture: %v", err)
+ }
+
+ _, err := resolveWith(failExecutable, []string{path})
+ if err == nil {
+ t.Fatal("resolveWith() error = nil, want failure")
+ }
+ if !errors.Is(err, executableErr) {
+ t.Fatalf("error = %q, want original os.Executable error", err)
+ }
+ })
+ }
+}
+
+func writeTestExecutable(t *testing.T, dir, base string) string {
+ t.Helper()
+ if runtime.GOOS == "windows" {
+ base += ".exe"
+ }
+ path := filepath.Join(dir, base)
+ if err := os.WriteFile(path, []byte("test executable"), 0o755); err != nil {
+ t.Fatalf("write executable fixture: %v", err)
+ }
+ return path
+}