Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6132 fix: stop stranding daemon task markers in user directories (#6917)
Bohan Jiangceb6c6845c59
diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex f4bf45fcd4..012b3f4588 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -259,11 +259,10 @@ func newAPIClient(cmd *cobra.Command) (*cli.APIClient, error) {// 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.- if !inAgentExecutionContext() && os.Getenv("MULTICA_DAEMON_PORT") == "" {- if markerPath := daemonTaskContextMarkerPath(); markerPath != "" {- return nil, fmt.Errorf("agent execution context requires MULTICA_TOKEN to be a task-scoped mat_ token; detected a daemon task marker at %s — if you are not running inside an agent task this is likely a leftover, remove it and retry", markerPath)- }+ // 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))}return nil, fmt.Errorf("agent execution context requires MULTICA_TOKEN to be a task-scoped mat_ token%s", daemonPortOnlyContextHint())}@@ -407,6 +406,14 @@ func requireTaskLocalConfigRoot() error {return nil}if strings.TrimSpace(os.Getenv(cli.TaskConfigRootEnv)) == "" {+ // The third refusal path a leftover marker can trigger, alongside+ // newAPIClient and requireHumanLocalCommand. It has to name the file+ // 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))+ }return fmt.Errorf("daemon-managed task requires a task-local Multica config root in %s%s", cli.TaskConfigRootEnv, daemonPortOnlyContextHint())}return nil@@ -416,10 +423,20 @@ func requireTaskLocalConfigRoot() error {// set up, or operate the human-owned local daemon/profile. Task API commands// remain available with the injected mat_ token; these local commands do not.func requireHumanLocalCommand(command string) error {- if inDaemonTaskIdentityContext() {- return fmt.Errorf("%s is not available inside a daemon-managed task", command)+ if !inDaemonTaskIdentityContext() {+ return nil}- return nil+ // A task-scoped workdir marker with no task identity in the environment is+ // the one signal that can outlive the task that wrote it: a local_directory+ // run that never cleaned up leaves it in the user's own repository, where it+ // disables every command below this function for that whole directory tree+ // 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))+ }+ return fmt.Errorf("%s is not available inside a daemon-managed task", command)}func hasDaemonTaskContextMarker() bool {diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.goindex 301bde0775..f77284a35f 100644--- a/server/cmd/multica/cmd_agent_test.go+++ b/server/cmd/multica/cmd_agent_test.go@@ -41,7 +41,12 @@ func chdirWithDaemonTaskMarker(t *testing.T) {if err := os.MkdirAll(filepath.Dir(markerPath), 0o755); err != nil {t.Fatalf("create marker dir: %v", err)}- data := []byte(`{"managed_by":"` + execenv.TaskContextMarkerManagedBy + `"}`)+ // Task-scoped: a real workdir marker always carries the identity of the+ // task that wrote it, and that identity is what separates a leftover from+ // the permanent workspaces root marker, which has managed_by and nothing+ // else (MUL-6132). Writing the bare form here would model the root marker+ // rather than the workdir marker these tests are about.+ data := []byte(`{"managed_by":"` + execenv.TaskContextMarkerManagedBy + `","agent_id":"agent-1","issue_id":"issue-1"}`)if err := os.WriteFile(markerPath, data, 0o644); err != nil {t.Fatalf("write marker: %v", err)}diff --git a/server/cmd/multica/stale_marker.go b/server/cmd/multica/stale_marker.gonew file mode 100644index 0000000000..443baf3d9f--- /dev/null+++ b/server/cmd/multica/stale_marker.go@@ -0,0 +1,91 @@+package main++import (+ "encoding/json"+ "fmt"+ "os"+ "strings"++ "github.com/multica-ai/multica/server/internal/cli"+)++// 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.+//+// Two things disqualify a marker from the leftover treatment:+//+// 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.+//+// 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 {+ if inAgentExecutionContext() ||+ strings.TrimSpace(os.Getenv(cli.TaskConfigRootEnv)) != "" ||+ strings.TrimSpace(os.Getenv("MULTICA_DAEMON_PORT")) != "" {+ return ""+ }+ markerPath := daemonTaskContextMarkerPath()+ if markerPath == "" || !markerIsTaskScoped(markerPath) {+ return ""+ }+ return markerPath+}++// markerIsTaskScoped reports whether the marker at path belongs to one specific+// task, as opposed to being the workspaces root marker.+//+// Two different markers share this filename, and daemonTaskContextMarkerPath+// tells them apart by nothing but managed_by. The per-task marker carries the+// identity of the task that wrote it and dies with that task. The workspaces+// root marker carries no identity at all: the daemon re-creates it on every+// start as a permanent, node-wide guard so a subprocess that escapes above its+// workdir still fails closed. Telling anyone to delete THAT — a user, or an+// agent subprocess that lost its environment and is reading the error — closes+// the hole it exists to cover, so it gets the plain refusal instead.+//+// Identity means agent_id OR issue_id, not both: a chat task has no issue, and+// requiring one would misfile its marker as the root marker and lose the hint+// exactly where a leftover is possible. The root marker has neither field, so+// either one present is enough to separate them.+func markerIsTaskScoped(markerPath string) bool {+ data, err := os.ReadFile(markerPath)+ if err != nil {+ return false+ }+ var marker struct {+ AgentID string `json:"agent_id"`+ IssueID string `json:"issue_id"`+ }+ if json.Unmarshal(data, &marker) != nil {+ return false+ }+ 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).+//+// 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 can+// run proves it is safe to: the daemon increments its active task count only+// after a claim returns, so a probe can read zero for a task that is already+// claimed and about to write this very marker. Retirement therefore belongs to+// the daemon, which can serialize it against its own claim path.+func leftoverMarkerSuffix(markerPath string) string {+ return fmt.Sprintf("; detected a daemon task marker at %s — if you are not running inside an agent task this is likely a leftover, remove it and retry", markerPath)+}diff --git a/server/cmd/multica/stale_marker_test.go b/server/cmd/multica/stale_marker_test.gonew file mode 100644index 0000000000..a6b5d0f28e--- /dev/null+++ b/server/cmd/multica/stale_marker_test.go@@ -0,0 +1,182 @@+package main++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/cli"+ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++// seedMarker writes a daemon marker with the given body into a fresh temp+// directory and chdirs into a nested subdirectory, so the CLI's upward walk has+// to find it the same way it would in a user's repository. Returns the marker+// path.+func seedMarker(t *testing.T, body string) string {+ t.Helper()++ workDir := t.TempDir()+ markerPath := filepath.Join(workDir, execenv.TaskContextMarkerRelPath)+ if err := os.MkdirAll(filepath.Dir(markerPath), 0o755); err != nil {+ t.Fatalf("create marker dir: %v", err)+ }+ if err := os.WriteFile(markerPath, []byte(body), 0o644); err != nil {+ t.Fatalf("write marker: %v", err)+ }+ nested := filepath.Join(workDir, "repo", "pkg")+ if err := os.MkdirAll(nested, 0o755); err != nil {+ t.Fatalf("create nested cwd: %v", err)+ }+ t.Chdir(nested)+ return markerPath+}++// issueTaskMarker is the marker an issue task writes: agent and issue both set.+func issueTaskMarker() string {+ return `{"managed_by":"` + execenv.TaskContextMarkerManagedBy + `","agent_id":"agent-1","issue_id":"issue-1"}`+}++// chatTaskMarker is the marker a chat task writes. It has no issue, which is+// why task identity cannot be defined as "agent_id AND issue_id".+func chatTaskMarker() string {+ return `{"managed_by":"` + execenv.TaskContextMarkerManagedBy + `","agent_id":"agent-1"}`+}++// workspacesRootMarker is the permanent node-wide guard: managed_by and nothing+// else. EnsureWorkspacesRootMarker writes exactly this.+func workspacesRootMarker() string {+ return `{"managed_by":"` + execenv.TaskContextMarkerManagedBy + `"}`+}++func seedDaemonTaskMarker(t *testing.T) string {+ t.Helper()+ return seedMarker(t, issueTaskMarker())+}++// refusalPaths returns every CLI entry point that can refuse because of a+// leftover marker, so a new one cannot be added without deciding whether it+// reports the file.+func refusalPaths() map[string]func() error {+ return map[string]func() error{+ "human-local": func() error { return requireHumanLocalCommand("daemon stop") },+ "api": func() error {+ _, err := newAPIClient(testCmd())+ return err+ },+ "task-local-config": requireTaskLocalConfigRoot,+ }+}++func clearDaemonEnvSignals(t *testing.T) {+ t.Helper()+ t.Setenv("MULTICA_AGENT_ID", "")+ t.Setenv("MULTICA_TASK_ID", "")+ t.Setenv("MULTICA_DAEMON_PORT", "")+ t.Setenv(cli.TaskConfigRootEnv, "")+}++// TestLeftoverMarkerReportedIdenticallyOnEveryRefusalPath is the regression test+// for the split the MUL-6132 reviews found: at first only the API path named the+// marker file, and after that requireTaskLocalConfigRoot was still left out, so+// whether a user could act on the refusal depended on which command they+// happened to run first. All three paths must point at the same file with the+// same remedy.+func TestLeftoverMarkerReportedIdenticallyOnEveryRefusalPath(t *testing.T) {+ for _, marker := range []struct{ name, body string }{+ {name: "issue task", body: issueTaskMarker()},+ {name: "chat task", body: chatTaskMarker()},+ } {+ t.Run(marker.name, func(t *testing.T) {+ markerPath := seedMarker(t, marker.body)+ clearDaemonEnvSignals(t)+ t.Setenv("MULTICA_TOKEN", "")+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:8080")++ for name, refuse := range refusalPaths() {+ err := refuse()+ if err == nil {+ t.Fatalf("%s: got nil error; want refusal on a leftover marker", name)+ }+ if !strings.Contains(err.Error(), markerPath) {+ t.Fatalf("%s error should name the marker path %q; got %q", name, markerPath, err.Error())+ }+ if !strings.Contains(err.Error(), "leftover") {+ t.Fatalf("%s error should hint it may be a leftover; got %q", name, err.Error())+ }+ }++ // The CLI never removes the marker: taking down a fail-closed guard+ // needs a proof the CLI cannot produce, because the daemon's active+ // task count only rises after a claim returns.+ if _, statErr := os.Stat(markerPath); statErr != nil {+ t.Fatalf("CLI must not delete the marker: %v", statErr)+ }+ })+ }+}++// TestWorkspacesRootMarkerNeverReportedAsLeftover is the regression test for the+// permanent node-wide guard. It shares a filename with the per-task marker but+// is re-created by the daemon on every start and must never expire. Telling+// anyone to delete it — a user, or an agent subprocess that lost its+// environment and is reading this error — closes the hole it exists to cover.+func TestWorkspacesRootMarkerNeverReportedAsLeftover(t *testing.T) {+ markerPath := seedMarker(t, workspacesRootMarker())+ clearDaemonEnvSignals(t)+ t.Setenv("MULTICA_TOKEN", "")+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:8080")++ if got := leftoverDaemonTaskMarkerPath(); got != "" {+ t.Fatalf("leftoverDaemonTaskMarkerPath() = %q; want \"\" for the workspaces root marker", got)+ }++ for name, refuse := range refusalPaths() {+ err := refuse()+ if err == nil {+ t.Fatalf("%s: got nil error; want the plain refusal to stay in place", name)+ }+ if strings.Contains(err.Error(), "leftover") || strings.Contains(err.Error(), "remove it") {+ t.Fatalf("%s must not describe the workspaces root marker as removable; got %q", name, err.Error())+ }+ }++ if _, statErr := os.Stat(markerPath); statErr != nil {+ t.Fatalf("workspaces root marker must survive: %v", statErr)+ }+}++// TestLeftoverMarkerNotReportedUnderRealTaskIdentity guards the boundary of the+// leftover treatment. A real daemon-managed task announces itself through the+// environment; those refusals are correct and must not be described to the user+// as a stale file to delete.+func TestLeftoverMarkerNotReportedUnderRealTaskIdentity(t *testing.T) {+ for _, tc := range []struct{ name, env, value string }{+ {name: "agent id", env: "MULTICA_AGENT_ID", value: "agent-1"},+ {name: "task id", env: "MULTICA_TASK_ID", value: "task-1"},+ {name: "task config root", env: cli.TaskConfigRootEnv, value: "/tmp/task-multica"},+ {name: "daemon port", env: "MULTICA_DAEMON_PORT", value: "20032"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ markerPath := seedDaemonTaskMarker(t)+ clearDaemonEnvSignals(t)+ t.Setenv(tc.env, tc.value)++ if got := leftoverDaemonTaskMarkerPath(); got != "" {+ t.Fatalf("leftoverDaemonTaskMarkerPath() = %q; want \"\" under real task identity", got)+ }+ // MULTICA_DAEMON_PORT alone is not task identity, so it does not by+ // itself make a human-local command fail; the others do, and when+ // they do the message must stay the plain one.+ if err := requireHumanLocalCommand("daemon stop"); err != nil {+ if strings.Contains(err.Error(), "leftover") {+ t.Fatalf("env-signalled task context must not be reported as a leftover; got %q", err.Error())+ }+ }+ if _, statErr := os.Stat(markerPath); statErr != nil {+ t.Fatalf("marker must survive: %v", statErr)+ }+ })+ }+}diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 0b90da2f42..f8b96e50c6 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -433,6 +433,37 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {// and avoids a conditional that would silently disable cleanup if the// local_directory detection logic ever drifts.manifest := &sidecarManifest{}++ // Arm the rollback BEFORE the first write, not after writeContextFiles+ // returns. writeContextFiles puts the daemon task marker down as its very+ // first act and can then fail on any later step — .agent_context, skill+ // files, project resources — so a defer registered after it returns would+ // miss exactly the failures that strand a marker with nothing else around+ // it. Rolling back an empty manifest is a no-op, which is what makes it+ // safe to arm this early.+ //+ // The manifest that records these writes is not persisted until the end of+ // Prepare, and the caller receives no Environment on any failure path, so+ // none of the teardown defers that normally undo this tree are ever+ // registered. Without this rollback the files stay on disk with no record+ // of what to remove (MUL-6132).+ //+ // In place only. Worktree mode discards the whole worktree on failure just+ // above, and a cloud envRoot is wiped wholesale by the GC — only the+ // local_directory flow writes into a directory that outlives the task and+ // belongs to the user, where a leftover marker disables every multica+ // command in that directory tree until someone removes it by hand.+ if params.LocalWorkDir != "" {+ defer func() {+ if prepareSucceeded {+ return+ }+ if err := rollBackPreparedSidecars(*manifest); err != nil && logger != nil {+ logger.Warn("execenv: roll back sidecars after failed prepare", "work_dir", workDir, "error", err)+ }+ }()+ }+if err := writeContextFiles(workDir, params.Provider, params.Task, manifest); err != nil {return nil, fmt.Errorf("execenv: write context files: %w", err)}@@ -531,6 +562,16 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {}if err := writeSidecarManifest(envRoot, manifest); err != nil {+ // In place the manifest is the ONLY record of what we wrote into the+ // user's own directory, so losing it strands the sidecar tree there+ // permanently — no crash required, a disk or permission hiccup is+ // enough (MUL-6132). Fail so the rollback registered above removes the+ // tree now, while we still hold the in-memory manifest. Elsewhere the+ // manifest is a convenience the GC can do without, so a warning stays+ // the right response.+ if params.LocalWorkDir != "" {+ return nil, fmt.Errorf("execenv: write sidecar manifest: %w", err)+ }logger.Warn("execenv: write sidecar manifest failed (non-fatal)", "error", err)}diff --git a/server/internal/daemon/execenv/prepare_rollback_test.go b/server/internal/daemon/execenv/prepare_rollback_test.gonew file mode 100644index 0000000000..2267715266--- /dev/null+++ b/server/internal/daemon/execenv/prepare_rollback_test.go@@ -0,0 +1,159 @@+package execenv++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"+)++// TestPrepareRollsBackSidecarsWhenPrepareFailsInPlace is the regression test for+// MUL-6132: a local_directory Prepare that fails partway must not leave the+// daemon task marker (or any other sidecar) in the user's own repository.+//+// Before the fix, Prepare wrote the marker early and persisted the manifest that+// records it last, and the caller receives no Environment on a failure — so a+// failed Prepare left a marker no code path knew how to remove, which disabled+// every human-local multica command in that directory tree until someone deleted+// the file by hand.+//+// The induced failure is a pre-existing .cursor/mcp.json, which the managed+// cursor MCP path refuses to overwrite. It is a pure filesystem failure that+// needs no agent CLI on the machine, and it lands after the marker is written.+func TestPrepareRollsBackSidecarsWhenPrepareFailsInPlace(t *testing.T) {+ workspacesRoot := t.TempDir()+ userDir := t.TempDir()++ // The user's own content: the file that makes Prepare fail, plus a plain+ // file that must survive the rollback untouched.+ cursorDir := filepath.Join(userDir, ".cursor")+ if err := os.MkdirAll(cursorDir, 0o755); err != nil {+ t.Fatalf("create .cursor: %v", err)+ }+ if err := os.WriteFile(filepath.Join(cursorDir, "mcp.json"), []byte(`{"mine":true}`), 0o644); err != nil {+ t.Fatalf("seed user mcp.json: %v", err)+ }+ userFile := filepath.Join(userDir, "README.md")+ if err := os.WriteFile(userFile, []byte("user content"), 0o644); err != nil {+ t.Fatalf("seed user file: %v", err)+ }++ _, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-rollback-001",+ TaskID: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",+ AgentName: "Test Agent",+ Provider: "cursor",+ LocalWorkDir: userDir,+ McpConfig: json.RawMessage(`{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}`),+ Task: TaskContextForEnv{+ IssueID: "11111111-2222-3333-4444-555555555555",+ AgentID: "99999999-8888-7777-6666-555555555555",+ },+ }, testLogger())+ if err == nil {+ t.Fatal("Prepare succeeded; expected the pre-existing .cursor/mcp.json to fail it")+ }++ markerPath := filepath.Join(userDir, TaskContextMarkerRelPath)+ if _, statErr := os.Stat(markerPath); !os.IsNotExist(statErr) {+ t.Fatalf("daemon task marker survived a failed Prepare at %s (stat err: %v)", markerPath, statErr)+ }+ if _, statErr := os.Stat(filepath.Join(userDir, ".agent_context")); !os.IsNotExist(statErr) {+ t.Fatalf(".agent_context survived a failed Prepare (stat err: %v)", statErr)+ }++ // The rollback must be scoped to what Prepare created: the user's own+ // files, including the one that caused the failure, stay exactly as they+ // were.+ if data, readErr := os.ReadFile(userFile); readErr != nil || string(data) != "user content" {+ t.Fatalf("rollback touched user content: data=%q err=%v", string(data), readErr)+ }+ if data, readErr := os.ReadFile(filepath.Join(cursorDir, "mcp.json")); readErr != nil || string(data) != `{"mine":true}` {+ t.Fatalf("rollback touched the user's mcp.json: data=%q err=%v", string(data), readErr)+ }+}++// TestPrepareRollsBackWhenWriteContextFilesFailsAfterMarker covers the earliest+// failure window there is: writeContextFiles lays the marker down as its very+// first act, then creates .agent_context, writes skills and writes project+// resources — any of which can fail with the marker already on disk.+//+// The first version of the MUL-6132 fix armed the rollback only after+// writeContextFiles returned, so exactly these failures still stranded a marker+// in the user's repository with nothing else beside it (MUL-6132 review). The+// induced failure is a plain file where .agent_context must be a directory.+func TestPrepareRollsBackWhenWriteContextFilesFailsAfterMarker(t *testing.T) {+ workspacesRoot := t.TempDir()+ userDir := t.TempDir()++ // A regular file at the path writeContextFiles needs as a directory, one+ // step after it writes the marker.+ blocker := filepath.Join(userDir, ".agent_context")+ if err := os.WriteFile(blocker, []byte("user file"), 0o644); err != nil {+ t.Fatalf("seed .agent_context blocker: %v", err)+ }++ _, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-rollback-003",+ TaskID: "cccccccc-dddd-eeee-ffff-000000000000",+ AgentName: "Test Agent",+ LocalWorkDir: userDir,+ Task: TaskContextForEnv{+ IssueID: "33333333-4444-5555-6666-777777777777",+ AgentID: "77777777-6666-5555-4444-333333333333",+ },+ }, testLogger())+ if err == nil {+ t.Fatal("Prepare succeeded; expected the .agent_context blocker to fail it")+ }++ markerPath := filepath.Join(userDir, TaskContextMarkerRelPath)+ if _, statErr := os.Stat(markerPath); !os.IsNotExist(statErr) {+ t.Fatalf("daemon task marker survived a failure inside writeContextFiles at %s (stat err: %v)", markerPath, statErr)+ }+ if data, readErr := os.ReadFile(blocker); readErr != nil || string(data) != "user file" {+ t.Fatalf("rollback touched the user's own file: data=%q err=%v", string(data), readErr)+ }+}++// TestPrepareSucceedsInPlaceAndLeavesMarker guards the other half of the+// contract: the rollback fires only on failure. A Prepare that completes must+// still leave the marker in place — it is the guard that makes a CLI invocation+// from inside the task fail closed — and must persist the manifest that the+// task teardown later uses to remove it.+func TestPrepareSucceedsInPlaceAndLeavesMarker(t *testing.T) {+ workspacesRoot := t.TempDir()+ userDir := t.TempDir()++ env, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-rollback-002",+ TaskID: "bbbbbbbb-cccc-dddd-eeee-ffffffffffff",+ AgentName: "Test Agent",+ LocalWorkDir: userDir,+ Task: TaskContextForEnv{+ IssueID: "22222222-3333-4444-5555-666666666666",+ AgentID: "88888888-7777-6666-5555-444444444444",+ },+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }++ if _, statErr := os.Stat(filepath.Join(userDir, TaskContextMarkerRelPath)); statErr != nil {+ t.Fatalf("successful Prepare did not leave the daemon task marker: %v", statErr)+ }+ if _, statErr := os.Stat(filepath.Join(env.RootDir, sidecarManifestFile)); statErr != nil {+ t.Fatalf("successful Prepare did not persist the sidecar manifest: %v", statErr)+ }++ // And the recorded manifest is what makes the marker removable later.+ if err := CleanupSidecars(env.RootDir); err != nil {+ t.Fatalf("CleanupSidecars: %v", err)+ }+ if _, statErr := os.Stat(filepath.Join(userDir, TaskContextMarkerRelPath)); !os.IsNotExist(statErr) {+ t.Fatalf("marker survived CleanupSidecars (stat err: %v)", statErr)+ }+}diff --git a/server/internal/daemon/execenv/sidecar_manifest.go b/server/internal/daemon/execenv/sidecar_manifest.goindex 261a4424a9..810bf56afc 100644--- a/server/internal/daemon/execenv/sidecar_manifest.go+++ b/server/internal/daemon/execenv/sidecar_manifest.go@@ -209,10 +209,14 @@ func skillSlugCandidate(baseSlug string, attempt int) string {// writeSidecarManifest persists m to {envRoot}/{sidecarManifestFile}.// Empty manifests are still written so a later Cleanup that finds the// file knows tracking was attempted (vs. an old build that predates this-// mechanism, where the file is absent and Cleanup must no-op). Failures-// are returned to the caller; the caller treats them as non-fatal because-// a missed manifest only degrades local_directory cleanup, not task-// execution.+// mechanism, where the file is absent and Cleanup must no-op).+//+// Failures are returned to the caller, and how much they matter depends on+// where the sidecars landed. For a cloud envRoot the manifest is a convenience+// the GC can do without, so Prepare logs and continues. For an in-place+// local_directory run it is the only record of what was written into the user's+// own repository, so Prepare treats the failure as fatal and rolls back while+// it still holds the in-memory manifest (MUL-6132).func writeSidecarManifest(envRoot string, m *sidecarManifest) error {if envRoot == "" {return nil@@ -284,6 +288,20 @@ func CleanupSidecars(envRoot string) error {return fmt.Errorf("parse sidecar manifest %s: %w", manifestPath, err)}+ return rollBackManifest(m, manifestPath)+}++// rollBackManifest removes everything m records, then removes manifestPath+// itself when it is non-empty. It is the shared body of CleanupSidecars (which+// reads m back from disk after the task ran) and rollBackPreparedSidecars+// (which passes the in-memory manifest of a Prepare that never finished, and+// has no manifest file to delete because Prepare failed before writing one).+//+// Splitting it this way is what lets the failed-Prepare path reuse the exact+// deletion semantics documented on CleanupSidecars — ENOENT and non-empty+// directories tolerated, real I/O errors surfaced — instead of growing a second,+// subtly different rollback that would drift from it.+func rollBackManifest(m sidecarManifest, manifestPath string) error {var firstErr errorcaptureErr := func(err error) {if firstErr == nil {@@ -334,13 +352,33 @@ func CleanupSidecars(envRoot string) error {}}- if err := os.Remove(manifestPath); err != nil && !errors.Is(err, fs.ErrNotExist) {- captureErr(fmt.Errorf("remove manifest %s: %w", manifestPath, err))+ if manifestPath != "" {+ if err := os.Remove(manifestPath); err != nil && !errors.Is(err, fs.ErrNotExist) {+ captureErr(fmt.Errorf("remove manifest %s: %w", manifestPath, err))+ }}return firstErr}+// rollBackPreparedSidecars undoes the sidecar writes of a Prepare that failed+// before it could persist the manifest, using the in-memory manifest Prepare+// was still filling in.+//+// This is the only rollback available on that path. Prepare writes the daemon+// task marker and the rest of the sidecar tree into the workdir early, but only+// persists the manifest at the very end; every error return in between leaves+// that tree on disk with no on-disk record of it, and the caller never receives+// an Environment, so no teardown defer downstream knows there is anything to+// clean (MUL-6132). For a local_directory task the workdir is the user's own+// repository, so "left on disk" means a marker that disables every multica+// command in that directory tree until someone deletes it by hand.+//+// There is no manifest file to remove, so manifestPath is empty.+func rollBackPreparedSidecars(m sidecarManifest) error {+ return rollBackManifest(m, "")+}+// removeReusedManagedSkillDirs force-removes the skill directories the prior// dispatch recorded under skillsParent in its sidecar manifest at envRoot,// even when they are now non-empty. It is the reuse-path companion to