Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8603: fix Quick Create CLI resolution in login shells (#9937)
Bohan Jiang88091a4da05e
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 8cda0157bd..d6cf97dba2 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8730,13 +8730,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}}}- // Ensure the multica CLI is on PATH inside the agent's environment.- // 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 := resolveSelfExecutable(); err == nil {- binDir := filepath.Dir(selfBin)- agentEnv["PATH"] = binDir + string(os.PathListSeparator) + os.Getenv("PATH")+ if err := configureTaskCLIEnvironment(agentEnv); err != nil {+ return TaskResult{}, err}// Point Codex to the per-task CODEX_HOME so it discovers skills natively// without polluting the system ~/.codex/skills/.diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 9751f0a20b..6780b5f709 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -370,6 +370,7 @@ func TestConfigureCodexTaskShellEnvironment(t *testing.T) {"CUSTOM_FLAG": "enabled","UNAUTHORIZED_TOKEN": "daemon-secret","MULTICA_TASK_CONFIG_ROOT": "/task/multica-config",+ "MULTICA_CLI_PATH": "/task/bin/multica","MULTICA_SERVER_URL": "https://task.example","MULTICA_TOKEN": "mat_task",}@@ -385,7 +386,7 @@ func TestConfigureCodexTaskShellEnvironment(t *testing.T) {t.Fatalf("read config.toml: %v", err)}config := string(data)- for _, want := range []string{"SystemRoot", "USERPROFILE", "CUSTOM_ACCESS_TOKEN", "CUSTOM_FLAG", "MULTICA_TASK_CONFIG_ROOT", "MULTICA_SERVER_URL", "MULTICA_TOKEN"} {+ for _, want := range []string{"SystemRoot", "USERPROFILE", "CUSTOM_ACCESS_TOKEN", "CUSTOM_FLAG", "MULTICA_TASK_CONFIG_ROOT", "MULTICA_CLI_PATH", "MULTICA_SERVER_URL", "MULTICA_TOKEN"} {if !strings.Contains(config, want) {t.Errorf("config.toml missing %q:\n%s", want, config)}diff --git a/server/internal/daemon/execenv/runtime_config_cli_test.go b/server/internal/daemon/execenv/runtime_config_cli_test.gonew file mode 100644index 0000000000..fdc82c31da--- /dev/null+++ b/server/internal/daemon/execenv/runtime_config_cli_test.go@@ -0,0 +1,38 @@+package execenv++import (+ "strings"+ "testing"+)++func TestRuntimeBriefPinsTaskCLI(t *testing.T) {+ original := runtimeGOOS+ t.Cleanup(func() { runtimeGOOS = original })+ for _, tc := range []struct {+ goos, command string+ }{+ {"darwin", `"$MULTICA_CLI_PATH"`},+ {"linux", `"$MULTICA_CLI_PATH"`},+ {"windows", `& "$env:MULTICA_CLI_PATH"`},+ } {+ runtimeGOOS = tc.goos+ for kind, ctx := range map[string]TaskContextForEnv{+ "issue": {IssueID: "issue-1"}, "chat": {ChatSessionID: "chat-1"},+ "autopilot": {AutopilotRunID: "run-1"}, "quick-create": {QuickCreatePrompt: "create work"},+ } {+ brief := buildMetaSkillContent("codex", ctx)+ for _, want := range []string{+ "The daemon sets `MULTICA_CLI_PATH` to its own CLI executable",+ "invoke `" + tc.command + " ...` instead",+ "do not resolve `multica` through PATH",+ } {+ if !strings.Contains(brief, want) {+ t.Errorf("%s/%s brief missing %q", tc.goos, kind, want)+ }+ }+ if kind == "quick-create" && !strings.Contains(brief, "Run exactly one `"+tc.command+" issue create --output json` invocation") {+ t.Errorf("%s quick-create workflow does not use the pinned CLI", tc.goos)+ }+ }+ }+}diff --git a/server/internal/daemon/execenv/runtime_config_kind_test.go b/server/internal/daemon/execenv/runtime_config_kind_test.goindex b66903240e..6a5e223032 100644--- a/server/internal/daemon/execenv/runtime_config_kind_test.go+++ b/server/internal/daemon/execenv/runtime_config_kind_test.go@@ -231,7 +231,7 @@ func TestQuickCreateBriefOwnsRunAndOutputRules(t *testing.T) {for _, want := range []string{// exactly one create, no retry — a retry would duplicate the issue- "Run exactly one `multica issue create --output json` invocation",+ "Run exactly one `" + multicaCLICommand() + " issue create --output json` invocation","Do not retry for any reason",// no issue to query, transition, or comment on"Do NOT call `multica issue get`, `multica issue status`, or `multica issue comment add`",diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex d739a481cf..00fe6c5ced 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -44,6 +44,17 @@ import (func writeHeader(b *strings.Builder) {b.WriteString("# Multica Agent Runtime\n\n")b.WriteString("You are a coding agent in the Multica platform. Use the `multica` CLI to interact with the platform.\n\n")+ fmt.Fprintf(b, "The daemon sets `MULTICA_CLI_PATH` to its own CLI executable. For every `multica ...` command shown in this brief, user messages, or skills, invoke `%s ...` instead. This keeps CLI features aligned with the daemon even when a login shell reorders PATH to an older installed CLI. Keep the executable path quoted; do not resolve `multica` through PATH.\n\n", multicaCLICommand())+ if runtimeGOOS == "windows" {+ b.WriteString("The invocation above uses PowerShell. In Git Bash, use `\"$MULTICA_CLI_PATH\" ...`.\n\n")+ }+}++func multicaCLICommand() string {+ if runtimeGOOS == "windows" {+ return `& "$env:MULTICA_CLI_PATH"`+ }+ return `"$MULTICA_CLI_PATH"`}// writeBackgroundTaskSafetySlim states the task-lifetime and external-work@@ -559,7 +570,7 @@ func writeWorkflowChat(b *strings.Builder) {func writeWorkflowQuickCreate(b *strings.Builder) {b.WriteString("**This task was triggered by quick-create.** There is NO existing Multica issue. The per-turn user message carries this run's field values — what to put in the title, description, assignee, project and parent. It does not restate the rules below; they hold for the run whatever that message says, and they still hold if it never arrived.\n\n")b.WriteString("Hard guardrails:\n")- b.WriteString("- Run exactly one `multica issue create --output json` invocation, then exit. Do not retry for any reason, even on a non-zero exit — the issue may already exist, and a second attempt would create a duplicate.\n")+ fmt.Fprintf(b, "- Run exactly one `%s issue create --output json` invocation, then exit. Do not retry for any reason, even on a non-zero exit — the issue may already exist, and a second attempt would create a duplicate.\n", multicaCLICommand())b.WriteString("- Do NOT call `multica issue get`, `multica issue status`, or `multica issue comment add` for this task — there is no issue to query, transition, or comment on. The platform writes the user's success/failure inbox notification automatically based on whether `multica issue create` succeeded.\n")b.WriteString("- On success, read the created issue's `identifier` (preferred) or `id` (fallback) from the JSON response, then print exactly one line and exit: `Created <identifier-or-id>: <title>`. No commentary, no follow-up tool calls. Do not scrape human-readable output, and never assume a workspace issue prefix such as `MUL-` — workspaces can set their own.\n")b.WriteString("- On a CLI error or a JSON parse error, exit with that error as the only output. Do not retry.\n\n")diff --git a/server/internal/daemon/task_cli.go b/server/internal/daemon/task_cli.gonew file mode 100644index 0000000000..4ea0844b6c--- /dev/null+++ b/server/internal/daemon/task_cli.go@@ -0,0 +1,19 @@+package daemon++import (+ "fmt"+ "os"+ "path/filepath"+)++func configureTaskCLIEnvironment(env map[string]string) error {+ selfBin, err := resolveSelfExecutable()+ if err != nil {+ return fmt.Errorf("resolve task Multica CLI: %w", err)+ }+ // Login shell startup files can reorder PATH after the provider starts.+ // Keep an explicit executable for the commands in the runtime brief.+ env["MULTICA_CLI_PATH"] = selfBin+ env["PATH"] = filepath.Dir(selfBin) + string(os.PathListSeparator) + os.Getenv("PATH")+ return nil+}diff --git a/server/internal/daemon/task_cli_test.go b/server/internal/daemon/task_cli_test.gonew file mode 100644index 0000000000..54e2e34b62--- /dev/null+++ b/server/internal/daemon/task_cli_test.go@@ -0,0 +1,111 @@+package daemon++import (+ "context"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "testing"+ "time"+)++func stubTaskCLI(t *testing.T, path string) {+ t.Helper()+ original := resolveSelfExecutable+ t.Cleanup(func() { resolveSelfExecutable = original })+ resolveSelfExecutable = func() (string, error) { return path, nil }+}++func TestConfigureTaskCLIEnvironment(t *testing.T) {+ cliPath := filepath.Join(t.TempDir(), "Desktop App", "multica")+ stubTaskCLI(t, cliPath)+ inheritedPath := filepath.Join(t.TempDir(), "old-cli")+ t.Setenv("PATH", inheritedPath)+ env := map[string]string{"MULTICA_TOKEN": "mat_fixture"}+ if err := configureTaskCLIEnvironment(env); err != nil {+ t.Fatal(err)+ }+ if env["MULTICA_CLI_PATH"] != cliPath {+ t.Fatalf("CLI path = %q, want daemon executable %q", env["MULTICA_CLI_PATH"], cliPath)+ }+ wantPath := filepath.Dir(cliPath) + string(os.PathListSeparator) + inheritedPath+ if env["PATH"] != wantPath {+ t.Fatalf("PATH = %q, want %q", env["PATH"], wantPath)+ }+ layerCustomEnvAndHermesHome(env, map[string]string{+ "MULTICA_CLI_PATH": "other-cli",+ "multica_cli_path": "other-cli",+ "PATH": "other-path",+ }, "", nil)+ if env["MULTICA_CLI_PATH"] != cliPath || env["PATH"] != wantPath || env["MULTICA_TOKEN"] != "mat_fixture" {+ t.Fatal("custom environment replaced the daemon CLI or task credential")+ }+ if _, ok := env["multica_cli_path"]; ok {+ t.Fatal("custom environment introduced a case alias for the daemon CLI")+ }+}++func TestConfigureTaskCLIEnvironmentResolutionFailure(t *testing.T) {+ original := resolveSelfExecutable+ t.Cleanup(func() { resolveSelfExecutable = original })+ wantErr := errors.New("executable unavailable")+ resolveSelfExecutable = func() (string, error) { return "", wantErr }+ env := map[string]string{}+ if err := configureTaskCLIEnvironment(env); !errors.Is(err, wantErr) {+ t.Fatalf("error = %v, want executable resolution failure", err)+ }+ if len(env) != 0 {+ t.Fatalf("failed resolution changed the environment: %v", env)+ }+}++func TestTaskCLICommandSurvivesShellPathOverride(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("POSIX shell regression; PowerShell command syntax is covered by runtime brief tests")+ }+ root := t.TempDir()+ binDir := filepath.Join(root, "Desktop App ' $ ` ;")+ staleDir := filepath.Join(root, "homebrew")+ for _, dir := range []string{binDir, staleDir} {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ }+ cliPath := filepath.Join(binDir, "multica")+ writeTestExecutable(t, cliPath, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"))+ writeTestExecutable(t, filepath.Join(staleDir, "multica"), []byte("#!/bin/sh\nprintf '%s\\n' 'unknown flag: --assignee-picker' >&2\nexit 2\n"))+ stubTaskCLI(t, cliPath)+ env := map[string]string{}+ if err := configureTaskCLIEnvironment(env); err != nil {+ t.Fatal(err)+ }+ // A shell startup file can put a stale installation ahead of the PATH+ // that the daemon supplied to the provider process.+ profile := filepath.Join(root, "profile")+ if err := os.WriteFile(profile, []byte("PATH=\"$TASK_TEST_STALE_BIN\"\nexport PATH\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct {+ name, command, want string+ wantErr bool+ }{+ {"PATH lookup uses stale CLI", `multica`, "unknown flag: --assignee-picker\n", true},+ {"explicit CLI supports picker", `"$MULTICA_CLI_PATH"`, "issue\ncreate\n--title\nA quoted title\n--assignee-picker\n", false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, "/bin/sh", "-c", ". \"$TASK_TEST_PROFILE\"\n"+tc.command+` issue create --title "A quoted title" --assignee-picker`)+ cmd.Env = append(os.Environ(), "TASK_TEST_PROFILE="+profile, "TASK_TEST_STALE_BIN="+staleDir)+ for key, value := range env {+ cmd.Env = append(cmd.Env, key+"="+value)+ }+ out, err := cmd.CombinedOutput()+ if (err != nil) != tc.wantErr || string(out) != tc.want {+ t.Fatalf("command error = %v, output = %q; want error=%v, output=%q", err, out, tc.wantErr, tc.want)+ }+ })+ }+}diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.goindex 292e7a96b0..7052d7a994 100644--- a/server/pkg/agent/kiro.go+++ b/server/pkg/agent/kiro.go@@ -12,6 +12,8 @@ import ("sync""sync/atomic""time"++ "github.com/mattn/go-shellwords")// kiroReaderDrainGrace bounds how long the turn waits for trailing ACP@@ -719,24 +721,45 @@ func isKiroIssueCommentAddTool(msg Message) bool {}func isKiroIssueCommentAddCommand(command string) bool {- parts := trimLeadingEnvAssignments(strings.Fields(command))+ parts := kiroCommandWords(command)// Some runtimes route terminal calls through a shell wrapper such as// `sh -c "multica issue comment add ..."`; unwrap a single such layer so// the real invocation is still recognized.if len(parts) >= 3 && isPOSIXShellName(parts[0]) && parts[1] == "-c" {- inner := strings.Trim(strings.Join(parts[2:], " "), "\"'")- parts = trimLeadingEnvAssignments(strings.Fields(inner))+ parts = kiroCommandWords(parts[2])}if len(parts) < 4 {return false}- executable := strings.TrimPrefix(parts[0], "./")- if executable != "multica" && !strings.HasSuffix(executable, "/multica") {- return false+ executable := strings.ReplaceAll(strings.TrimPrefix(parts[0], "./"), `\`, "/")+ switch executable {+ case "$MULTICA_CLI_PATH", "${MULTICA_CLI_PATH}", "$env:MULTICA_CLI_PATH", "${env:MULTICA_CLI_PATH}":+ case "multica", "multica.exe":+ default:+ if !strings.HasSuffix(executable, "/multica") && !strings.HasSuffix(executable, "/multica.exe") {+ return false+ }}return parts[1] == "issue" && parts[2] == "comment" && parts[3] == "add"}+func kiroCommandWords(command string) []string {+ command = strings.TrimSpace(command)+ if after, ok := strings.CutPrefix(command, "&"); ok {+ // PowerShell uses & to invoke a quoted executable and treats+ // backslashes as literal path separators, not POSIX escapes.+ command = strings.ReplaceAll(strings.TrimSpace(after), `\`, `\\`)+ }+ // Parse syntax only; never expand environment variables or execute+ // command substitutions from the tool payload.+ parser := shellwords.Parser{}+ parts, err := parser.Parse(command)+ if err != nil {+ return nil+ }+ return trimLeadingEnvAssignments(parts)+}+// trimLeadingEnvAssignments drops leading `KEY=VALUE` tokens so an invocation// like `MULTICA_TOKEN=x multica issue comment add ...` is still recognized.func trimLeadingEnvAssignments(parts []string) []string {diff --git a/server/pkg/agent/kiro_test.go b/server/pkg/agent/kiro_test.goindex a8dbd2e122..3912c82a1d 100644--- a/server/pkg/agent/kiro_test.go+++ b/server/pkg/agent/kiro_test.go@@ -397,9 +397,32 @@ func TestKiroIssueCommentAddCommand(t *testing.T) {{`sh -c "multica issue comment add issue-1 --content-file ./reply.md"`, true},{`bash -c 'multica issue comment add issue-1'`, true},{`/bin/sh -c "multica issue comment add issue-1"`, true},+ {`"$MULTICA_CLI_PATH" issue comment add issue-1 --content-file ./reply.md`, true},+ {`"$MULTICA_CLI_PATH" issue comment add issue-1 --content-file ./reply.md --output table && rm ./reply.md`, true},+ {`${MULTICA_CLI_PATH} issue comment add issue-1`, true},+ {`"${MULTICA_CLI_PATH}" issue comment add issue-1`, true},+ {`'/Applications/Multica App/bin/multica' issue comment add issue-1`, true},+ {`"/Applications/Multica App/bin/multica" issue comment add issue-1`, true},+ {`MULTICA_TOKEN=x "$MULTICA_CLI_PATH" issue comment add issue-1`, true},+ {`sh -c '"$MULTICA_CLI_PATH" issue comment add issue-1'`, true},+ {`bash -c '"/Applications/Multica App/bin/multica" issue comment add issue-1'`, true},+ {`& "$env:MULTICA_CLI_PATH" issue comment add issue-1 --content-file ./reply.md`, true},+ {`& $env:MULTICA_CLI_PATH issue comment add issue-1`, true},+ {`& "${env:MULTICA_CLI_PATH}" issue comment add issue-1`, true},+ {`& "C:\Program Files\Multica\multica.exe" issue comment add issue-1`, true},+ {`& 'C:\Program Files\Multica\multica.exe' issue comment add issue-1`, true},{"multica issue get issue-1", false},{"echo multica issue comment add issue-1", false},{`sh -c "echo multica issue comment add issue-1"`, false},+ {`echo "$MULTICA_CLI_PATH" issue comment add issue-1`, false},+ {`echo done; "$MULTICA_CLI_PATH" issue comment add issue-1`, false},+ {`sh -c 'echo "$MULTICA_CLI_PATH" issue comment add issue-1'`, false},+ {`& echo "$env:MULTICA_CLI_PATH" issue comment add issue-1`, false},+ {`"$MULTICA_CLI_PATH" issue get issue-1`, false},+ {`"$OTHER_CLI_PATH" issue comment add issue-1`, false},+ {`& "$env:OTHER_CLI_PATH" issue comment add issue-1`, false},+ {`"/Applications/Multica App/bin/not-multica" issue comment add issue-1`, false},+ {`"$MULTICA_CLI_PATH issue comment add issue-1`, false},{"FOO=bar", false},{"", false},}@@ -494,10 +517,7 @@ const closeErrorFrame = `printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603// close handshake. `toolName` picks a title that does NOT normalize to// "terminal"; `command` selects goal_complete (empty) vs comment-add.func fakeKiroACPRunningToolCloseErrorScript(toolName, command string) string {- params := `{}`- if command != "" {- params = `{"command":"` + command + `"}`- }+ params, _ := json.Marshal(map[string]string{"command": command})return `#!/bin/shwhile IFS= read -r line; doid=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')@@ -509,7 +529,7 @@ while IFS= read -r line; doprintf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_running"}}\n' "$id";;*'"method":"session/prompt"'*)- printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_running","update":{"type":"ToolCall","toolCallId":"tc-running","name":"` + toolName + `","status":"pending","parameters":` + params + `}}}\n'+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_running","update":{"type":"ToolCall","toolCallId":"tc-running","name":"` + toolName + `","status":"pending","parameters":` + string(params) + `}}}'` + closeErrorFrame + `exit 0;;@@ -553,10 +573,7 @@ func TestKiroBackendDoesNotCompleteRunningGoalCompleteWithoutResult(t *testing.T// before the -32603 close handshake. `toolName` deliberately uses a title that// does NOT normalize to "terminal" to prove recognition is title-independent.func fakeKiroACPCompletedToolCloseErrorScript(toolName, command string) string {- params := `{}`- if command != "" {- params = `{"command":"` + command + `"}`- }+ params, _ := json.Marshal(map[string]string{"command": command})return `#!/bin/shwhile IFS= read -r line; doid=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')@@ -568,7 +585,7 @@ while IFS= read -r line; doprintf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_completed"}}\n' "$id";;*'"method":"session/prompt"'*)- printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_completed","update":{"type":"ToolCall","toolCallId":"tc-done","name":"` + toolName + `","status":"pending","parameters":` + params + `}}}\n'+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_completed","update":{"type":"ToolCall","toolCallId":"tc-done","name":"` + toolName + `","status":"pending","parameters":` + string(params) + `}}}'printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_completed","update":{"type":"ToolCallUpdate","toolCallId":"tc-done","status":"completed","name":"` + toolName + `","output":"ok"}}}\n'` + closeErrorFrame + `exit 0@@ -597,6 +614,33 @@ func TestKiroBackendTreatsCompletedCommentAddWithNonTerminalTitleAsCompleted(t *}}+func TestKiroBackendPreservesPinnedCLICommentResult(t *testing.T) {+ t.Parallel()+ const command = `"$MULTICA_CLI_PATH" issue comment add issue-1 --content-file ./reply.md`+ completed := fakeKiroACPCompletedToolCloseErrorScript("execute_bash", command)+ for _, tc := range []struct {+ name, script, wantStatus string+ }{+ {"completed comment", completed, "completed"},+ {"failed comment", strings.Replace(completed, `"status":"completed"`, `"status":"failed"`, 1), "failed"},+ {"comment without result", fakeKiroACPRunningToolCloseErrorScript("execute_bash", command), "failed"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ result := runKiroCloseErrorScript(t, tc.script)+ if result.Status != tc.wantStatus {+ t.Fatalf("status = %q, want %q (error=%q)", result.Status, tc.wantStatus, result.Error)+ }+ if tc.wantStatus == "completed" && result.Error != "" {+ t.Fatalf("completed comment retained close error: %q", result.Error)+ }+ if tc.wantStatus == "failed" && !strings.Contains(result.Error, "Kiro failed to generate a response") {+ t.Fatalf("unsuccessful comment lost close error: %q", result.Error)+ }+ })+ }+}+// fakeKiroACPRealGPT56SolCloseErrorScript reproduces the EXACT ACP frame shape// captured from a live kiro-cli 2.12.3 + gpt-5.6-sol session (see #5509 /// MUL-4860). Three things about this shape broke the older guards: