Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8857: fix(cli): stop telling a live task to delete its own marker (#10224)
Jiayuan Zhang3ac4969d3334
diff --git a/scripts/dev-env.sh b/scripts/dev-env.shindex f2ecb2049c..a7f3d5308d 100755--- a/scripts/dev-env.sh+++ b/scripts/dev-env.sh@@ -153,6 +153,14 @@ load_manifest() {# shellcheck disable=SC1090. "$file"[ "$NAME" = "$1" ] || die "Manifest $file declares NAME=$NAME; expected $1."+ # Run from an agent task, everything launched for this environment loses the+ # task's MULTICA_* identity (CLEAN_ENV) but still sits under the task's+ # marker. This tells the CLI why, so its refusal does not call the task's own+ # marker a leftover to delete. A human's run exports nothing: a marker in+ # their checkout really can be a leftover.+ if [ -n "${MULTICA_TASK_ID:-}${MULTICA_AGENT_ID:-}${MULTICA_TASK_CONFIG_ROOT:-}" ]; then+ export MULTICA_DEV_ENV="$NAME"+ fi}# Prints nothing (and succeeds) for a missing manifest or key: callers comparediff --git a/scripts/dev-env.test.sh b/scripts/dev-env.test.shindex 66e96734a7..e2e07f5279 100644--- a/scripts/dev-env.test.sh+++ b/scripts/dev-env.test.sh@@ -355,9 +355,15 @@ MULTICA_WORKSPACES_ROOT=/owner/workspaces \dev_env exec clean-env-903 -- sh -c 'test -z "${MULTICA_TASK_CONFIG_ROOT:-}" &&test -z "${MULTICA_TASK_WORKSPACES_ROOT:-}" &&- test "$MULTICA_WORKSPACES_ROOT" = "$1"+ test "$MULTICA_WORKSPACES_ROOT" = "$1" &&+ test "$MULTICA_DEV_ENV" = clean-env-903' _ "$MULTICA_DEV_WORKSPACES_PARENT/multica_workspaces_dev-dev-env-test-903" \- > "$out" 2>&1 || fail "env-exec leaked daemon task identity or owner workspaces root"+ > "$out" 2>&1 || fail "env-exec leaked daemon task identity or owner workspaces root, or did not name its environment"+# Outside a task nothing was stripped, so the CLI must still be free to call a+# marker in the checkout a leftover.+env -u MULTICA_TASK_ID -u MULTICA_AGENT_ID -u MULTICA_TASK_CONFIG_ROOT -u MULTICA_DEV_ENV \+ bash "$root_dir/scripts/dev-env.sh" exec clean-env-903 -- sh -c 'test -z "${MULTICA_DEV_ENV:-}"' \+ > "$out" 2>&1 || fail "env-exec named its environment for a run that stripped no task identity"# scripts/desktop-cdp.mjs finds Desktop through env-exec: a recorded CDP port# becomes its endpoint, and an environment without one never inherits a URL.diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex 5ed60b5702..4fad09b9b8 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -260,13 +260,12 @@ func newAPIClient(cmd *cobra.Command) (*cli.APIClient, error) {token := resolveToken(cmd)if taskContext && !strings.HasPrefix(token, "mat_") {// When the ONLY daemon signal is a workdir marker (no MULTICA_AGENT_ID /- // MULTICA_TASK_ID / MULTICA_DAEMON_PORT), the likeliest cause outside a- // real task is a leftover marker from a crashed daemon task in a- // local_directory. Name the exact file so a normal user can recover- // instead of hitting an opaque "requires mat_ token" error. Shares its- // wording with requireHumanLocalCommand: same cause, same remedy.- if markerPath := leftoverDaemonTaskMarkerPath(); markerPath != "" {- return nil, fmt.Errorf("agent execution context requires MULTICA_TOKEN to be a task-scoped mat_ token%s", leftoverMarkerSuffix(markerPath))+ // MULTICA_TASK_ID / MULTICA_DAEMON_PORT), name the exact file and say+ // whether it can be a leftover, instead of an opaque "requires mat_+ // token" error. Shares its wording with requireHumanLocalCommand: same+ // cause, same remedy.+ if hint := taskMarkerHint(); hint != "" {+ return nil, fmt.Errorf("agent execution context requires MULTICA_TOKEN to be a task-scoped mat_ token%s", hint)}return nil, fmt.Errorf("agent execution context requires MULTICA_TOKEN to be a task-scoped mat_ token%s", daemonPortOnlyContextHint())}@@ -415,8 +414,8 @@ func requireTaskLocalConfigRoot() error {// too: a user hitting this one through `config show` or `auth status`// is as stuck as one hitting the others, and "which command did you// happen to run first" must not decide whether the error is actionable.- if markerPath := leftoverDaemonTaskMarkerPath(); markerPath != "" {- return fmt.Errorf("daemon-managed task requires a task-local Multica config root in %s%s", cli.TaskConfigRootEnv, leftoverMarkerSuffix(markerPath))+ if hint := taskMarkerHint(); hint != "" {+ return fmt.Errorf("daemon-managed task requires a task-local Multica config root in %s%s", cli.TaskConfigRootEnv, hint)}return fmt.Errorf("daemon-managed task requires a task-local Multica config root in %s%s", cli.TaskConfigRootEnv, daemonPortOnlyContextHint())}@@ -437,8 +436,8 @@ func requireHumanLocalCommand(command string) error {// until someone deletes the file by hand (MUL-6132). Name it, so the user// knows which file that is; the bare message below sends them to the source// instead. Mirrors newAPIClient's leftover-marker handling.- if markerPath := leftoverDaemonTaskMarkerPath(); markerPath != "" {- return fmt.Errorf("%s is not available inside a daemon-managed task%s", command, leftoverMarkerSuffix(markerPath))+ if hint := taskMarkerHint(); hint != "" {+ return fmt.Errorf("%s is not available inside a daemon-managed task%s", command, hint)}return fmt.Errorf("%s is not available inside a daemon-managed task", command)}@@ -455,6 +454,11 @@ func daemonTaskContextMarkerPath() string {if err != nil {return ""}+ return daemonTaskContextMarkerPathFrom(dir)+}++// daemonTaskContextMarkerPathFrom is daemonTaskContextMarkerPath starting at dir.+func daemonTaskContextMarkerPathFrom(dir string) string {for {markerPath := filepath.Join(dir, execenv.TaskContextMarkerRelPath)// Only a marker we can read AND whose managed_by matches counts as adiff --git a/server/cmd/multica/dev_env_profile.go b/server/cmd/multica/dev_env_profile.goindex bb28fbed49..cc866a77f2 100644--- a/server/cmd/multica/dev_env_profile.go+++ b/server/cmd/multica/dev_env_profile.go@@ -28,8 +28,10 @@ import (// from. A loopback URL alone proves nothing: a self-hosted install can run its// real server on localhost.-// devEnvHomeEnv mirrors DEV_HOME in scripts/dev-env.sh.-const devEnvHomeEnv = "MULTICA_DEV_HOME"+const (+ devEnvHomeEnv = "MULTICA_DEV_HOME"+ devEnvNameEnv = "MULTICA_DEV_ENV"+)// The registry manifest is written by `printf '%q'`, which leaves values made// of these characters unquoted. Anything else is not a value this check reads.@@ -76,13 +78,9 @@ func taskIdentityInEnv() bool {// PROFILE and the `desktop-localhost-<backend port>` profile its Desktop// derives from the backend URL.func devEnvBackendPortForProfile(profile string) string {- root := strings.TrimSpace(os.Getenv(devEnvHomeEnv))+ root := devEnvHome()if root == "" {- home, err := os.UserHomeDir()- if err != nil {- return ""- }- root = filepath.Join(home, ".multica", "dev")+ return ""}manifests, _ := filepath.Glob(filepath.Join(root, "envs", "*", "manifest.env"))for _, path := range manifests {@@ -101,6 +99,38 @@ func devEnvBackendPortForProfile(profile string) string {return ""}+// launchingDevEnv returns the name of the registered dev-env environment that+// launched this process, or "" when none did. dev-env run from an agent task+// exports devEnvNameEnv to everything it starts with that task's identity+// stripped. It only+// changes what a refusal says, never whether a command is refused, and a name+// the registry does not hold is ignored so a stray export cannot hide a real+// leftover marker.+func launchingDevEnv() string {+ name := strings.TrimSpace(os.Getenv(devEnvNameEnv))+ root := devEnvHome()+ if !devEnvManifestValue.MatchString(name) || root == "" {+ return ""+ }+ manifest := readDevEnvManifest(filepath.Join(root, "envs", name, "manifest.env"))+ if manifest["NAME"] != name {+ return ""+ }+ return name+}++// devEnvHome mirrors DEV_HOME in scripts/dev-env.sh.+func devEnvHome() string {+ if root := strings.TrimSpace(os.Getenv(devEnvHomeEnv)); root != "" {+ return root+ }+ home, err := os.UserHomeDir()+ if err != nil {+ return ""+ }+ return filepath.Join(home, ".multica", "dev")+}+func readDevEnvManifest(path string) map[string]string {values := map[string]string{}f, err := os.Open(path)diff --git a/server/cmd/multica/stale_marker.go b/server/cmd/multica/stale_marker.goindex 443baf3d9f..0a6d413416 100644--- a/server/cmd/multica/stale_marker.go+++ b/server/cmd/multica/stale_marker.go@@ -4,26 +4,66 @@ import ("encoding/json""fmt""os"+ "path/filepath""strings""github.com/multica-ai/multica/server/internal/cli"+ "github.com/multica-ai/multica/server/internal/daemon/execenv")-// leftoverDaemonTaskMarkerPath returns the workdir marker path when a marker is-// the ONLY reason the CLI considers itself inside a daemon-managed task AND-// that marker could actually be a leftover. It returns "" otherwise.+// taskMarkerHint renders the tail every refusal path appends when a+// task-scoped workdir marker is the only reason the CLI considers itself inside+// a daemon-managed task, and "" otherwise://-// Two things disqualify a marker from the leftover treatment:+// - newAPIClient, for API commands+// - requireHumanLocalCommand, for the local daemon/profile commands+// - requireTaskLocalConfigRoot, for config show/set and auth status+//+// All three refusals have the same cause and the same remedy, so they say the+// same thing. Keeping the wording in one place is what stops them from drifting+// again — before MUL-6132 only the API path named the file, so whether a user+// could act on the error depended on which command they happened to run first+// (MUL-6132 review).+//+// A marker alone looks the same whether a crashed local_directory run left it+// in the user's repository or a live task's own process had its identity+// stripped on purpose. Only the first may be removed: an agent that removes its+// own task's marker turns off, for the rest of its run, the guard that keeps it+// off the human's profiles and daemon (MUL-8857). So the hint offers removal+// only when nothing says the task is still there.+func taskMarkerHint() string {+ markerPath := identitylessTaskMarkerPath()+ if markerPath == "" {+ return ""+ }+ if owner := taskMarkerOwner(markerPath); owner != "" {+ return fmt.Sprintf("; the daemon task marker at %s belongs to %s, so without the task's MULTICA_* identity this command may not use local profiles or daemons — the marker is not a leftover, do not remove it", markerPath, owner)+ }+ return leftoverMarkerSuffix(markerPath)+}++// leftoverDaemonTaskMarkerPath returns the marker path when the refusal+// describes that marker as a possible leftover, and "" otherwise.+func leftoverDaemonTaskMarkerPath() string {+ markerPath := identitylessTaskMarkerPath()+ if markerPath == "" || taskMarkerOwner(markerPath) != "" {+ return ""+ }+ return markerPath+}++// identitylessTaskMarkerPath returns the workdir marker path when a+// task-scoped marker is the ONLY reason the CLI considers itself inside a+// daemon-managed task. It returns "" otherwise.//// Any MULTICA_* task identity in the environment means the daemon really did-// launch this process, so the marker is doing its job. MULTICA_DAEMON_PORT-// counts here even though it is not sufficient on its own for identity: it-// still says a daemon environment is present, which is not a leftover's-// fingerprint.+// launch this process, and the plain refusal already says what is going on.+// MULTICA_DAEMON_PORT counts here even though it is not sufficient on its own+// for identity: it still says a daemon environment is present.//// A marker that is not task-scoped is the permanent workspaces root marker,// which never expires and must never be described as removable.-func leftoverDaemonTaskMarkerPath() string {+func identitylessTaskMarkerPath() string {if inAgentExecutionContext() ||strings.TrimSpace(os.Getenv(cli.TaskConfigRootEnv)) != "" ||strings.TrimSpace(os.Getenv("MULTICA_DAEMON_PORT")) != "" {@@ -36,6 +76,58 @@ func leftoverDaemonTaskMarkerPath() string {return markerPath}+// taskMarkerOwner describes the task a marker still belongs to, or returns ""+// when it could be a leftover.+//+// dev-env strips the task's identity from everything it launches (make+// env-exec, its components, the Desktop it starts and that Desktop's daemon),+// so a process it launched is running for the task that called it.+//+// A marker under a daemon workspaces root is in a directory only tasks run in,+// and one a user could act on is in their own repository: the MUL-6132 leftover+// is a local_directory run's. Removing a marker under the root would not lift+// the refusal anyway, since the root marker above it refuses the same command,+// and the daemon's GC owns everything there.+func taskMarkerOwner(markerPath string) string {+ if name := launchingDevEnv(); name != "" {+ return fmt.Sprintf("the agent task running dev-env environment %q, which strips that identity on purpose", name)+ }+ if root := enclosingWorkspacesRoot(markerPath); root != "" {+ return fmt.Sprintf("an agent task workdir under the daemon workspaces root %s", root)+ }+ return ""+}++// enclosingWorkspacesRoot returns the directory holding a workspaces root+// marker above the workdir of the task marker at markerPath, or "".+func enclosingWorkspacesRoot(markerPath string) string {+ dir := filepath.Dir(taskMarkerWorkDir(markerPath))+ for {+ found := daemonTaskContextMarkerPathFrom(dir)+ if found == "" {+ return ""+ }+ workDir := taskMarkerWorkDir(found)+ if !markerIsTaskScoped(found) {+ return workDir+ }+ parent := filepath.Dir(workDir)+ if parent == workDir {+ return ""+ }+ dir = parent+ }+}++// taskMarkerWorkDir is the directory a marker at markerPath was written for.+func taskMarkerWorkDir(markerPath string) string {+ dir := markerPath+ for range strings.Split(filepath.ToSlash(execenv.TaskContextMarkerRelPath), "/") {+ dir = filepath.Dir(dir)+ }+ return dir+}+// markerIsTaskScoped reports whether the marker at path belongs to one specific// task, as opposed to being the workspaces root marker.//@@ -67,18 +159,7 @@ func markerIsTaskScoped(markerPath string) bool {return strings.TrimSpace(marker.AgentID) != "" || strings.TrimSpace(marker.IssueID) != ""}-// leftoverMarkerSuffix renders the shared tail every refusal path appends when-// a task-scoped workdir marker is the only daemon signal:-//-// - newAPIClient, for API commands-// - requireHumanLocalCommand, for the local daemon/profile commands-// - requireTaskLocalConfigRoot, for config show/set and auth status-//-// All three refusals have the same cause and the same remedy, so they say the-// same thing. Keeping the wording in one place is what stops them from drifting-// again — before MUL-6132 only the API path named the file, so whether a user-// could act on the error depended on which command they happened to run first-// (MUL-6132 review).+// leftoverMarkerSuffix is taskMarkerHint for a marker that may be a leftover.//// The CLI deliberately stops at naming the file rather than deleting it.// Removing the marker is removing a fail-closed guard, and no check the CLI candiff --git a/server/cmd/multica/stale_marker_test.go b/server/cmd/multica/stale_marker_test.goindex a6b5d0f28e..961ed0a6a8 100644--- a/server/cmd/multica/stale_marker_test.go+++ b/server/cmd/multica/stale_marker_test.go@@ -75,6 +75,98 @@ func clearDaemonEnvSignals(t *testing.T) {t.Setenv("MULTICA_TASK_ID", "")t.Setenv("MULTICA_DAEMON_PORT", "")t.Setenv(cli.TaskConfigRootEnv, "")+ t.Setenv(devEnvNameEnv, "")+}++// requireLiveTaskMarkerRefusals asserts every refusal path names the marker,+// says it is not a leftover, and never offers to remove it.+func requireLiveTaskMarkerRefusals(t *testing.T, markerPath, owner string) {+ t.Helper()+ if got := leftoverDaemonTaskMarkerPath(); got != "" {+ t.Fatalf("leftoverDaemonTaskMarkerPath() = %q; want \"\" for a live task's marker", got)+ }+ for name, refuse := range refusalPaths() {+ err := refuse()+ if err == nil {+ t.Fatalf("%s: got nil error; want the refusal to stay in place", name)+ }+ msg := err.Error()+ for _, want := range []string{markerPath, owner, "not a leftover, do not remove it"} {+ if !strings.Contains(msg, want) {+ t.Fatalf("%s error should contain %q; got %q", name, want, msg)+ }+ }+ if strings.Contains(msg, "likely a leftover") || strings.Contains(msg, "remove it and retry") {+ t.Fatalf("%s must not tell a live task to remove its marker; got %q", name, msg)+ }+ }+ if _, statErr := os.Stat(markerPath); statErr != nil {+ t.Fatalf("marker must survive: %v", statErr)+ }+}++// TestLiveTaskMarkerUnderWorkspacesRootNotReportedAsLeftover is the MUL-8857+// regression test. A managed task workdir sits under the workspaces root, and a+// process that lost the task's identity there is the task's own — a sandbox, or+// a tool that strips MULTICA_* on purpose. Telling it to remove the marker turns+// off its own guard, and would not even lift the refusal: the root marker above+// still refuses.+func TestLiveTaskMarkerUnderWorkspacesRootNotReportedAsLeftover(t *testing.T) {+ root := t.TempDir()+ rootMarker := filepath.Join(root, execenv.TaskContextMarkerRelPath)+ workDir := filepath.Join(root, "ws", "task", "workdir")+ markerPath := filepath.Join(workDir, execenv.TaskContextMarkerRelPath)+ for path, body := range map[string]string{rootMarker: workspacesRootMarker(), markerPath: issueTaskMarker()} {+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ nested := filepath.Join(workDir, "repo", "server")+ if err := os.MkdirAll(nested, 0o755); err != nil {+ t.Fatal(err)+ }+ t.Chdir(nested)+ clearDaemonEnvSignals(t)+ t.Setenv("MULTICA_TOKEN", "")+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:8080")++ requireLiveTaskMarkerRefusals(t, markerPath, "daemon workspaces root "+root)+}++// TestLiveTaskMarkerUnderDevEnvNotReportedAsLeftover covers a task whose marker+// is not under a workspaces root — a local_directory run — calling the CLI+// through dev-env, which strips the task's identity from everything it runs.+// Only a registered environment counts: a stray export must not hide a real+// leftover.+func TestLiveTaskMarkerUnderDevEnvNotReportedAsLeftover(t *testing.T) {+ setup := func(t *testing.T) string {+ markerPath := seedDaemonTaskMarker(t)+ clearDaemonEnvSignals(t)+ t.Setenv("MULTICA_TOKEN", "")+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:8080")+ t.Setenv(devEnvHomeEnv, t.TempDir())+ writeDevEnvManifest(t, "probe", "NAME=probe\nBACKEND_PORT=18081\nPROFILE=dev-probe\n")+ return markerPath+ }++ t.Run("registered environment", func(t *testing.T) {+ markerPath := setup(t)+ t.Setenv(devEnvNameEnv, "probe")+ requireLiveTaskMarkerRefusals(t, markerPath, `dev-env environment "probe"`)+ })++ for _, name := range []string{"unregistered", "../envs/probe"} {+ t.Run("unregistered "+name, func(t *testing.T) {+ markerPath := setup(t)+ t.Setenv(devEnvNameEnv, name)+ if got := leftoverDaemonTaskMarkerPath(); got != markerPath {+ t.Fatalf("leftoverDaemonTaskMarkerPath() = %q; want the leftover %q", got, markerPath)+ }+ })+ }}// TestLeftoverMarkerReportedIdenticallyOnEveryRefusalPath is the regression test