Skip to content

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

Go

MUL-8853: feat(dev-env): let an agent start its own environment's daemon (#10221)

Jiayuan Zhang4d11ec31ce10
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1b347b1ee8..8457b21a40 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -613,10 +613,16 @@ Two constraints are enforced rather than documented:
execution-environment helper for every task; `go run` deletes that binary when
the launcher exits, so the daemon would register, heartbeat, and then fail
every task with `fork/exec …/go-build…/exe/multica: no such file or directory`.
-- **`daemon start` is refused under a daemon-managed task.** A checkout below a
- `.multica/daemon_task_context.json` marker cannot start a second daemon
- competing for its own work, so `make up C=daemon` stops with that explanation
- before spending a login on it. Use `C=api,web` there.
+- **Under a daemon-managed task, only the environment's own daemon starts.** A
+ checkout below a `.multica/daemon_task_context.json` marker is an agent's
+ workdir, and the CLI refuses `daemon start`, `stop` and `status` there so a
+ task never operates your own daemon or profile. It makes one exception: an
+ explicit `--profile` that the dev-env registry assigns to an environment (its
+ CLI profile, or the `desktop-localhost-<backend port>` profile its Desktop
+ signs in), pointed at that environment's API, from a process the task's
+ `MULTICA_*` identity was stripped from. `make up` launches the daemon and
+ Desktop exactly that way, so an agent can run `make up C=api,web,daemon` and
+ test a real agent run. `make destroy` stops the daemon and removes its profile.
### Web with realistic content
diff --git a/scripts/dev-env.sh b/scripts/dev-env.sh
index b3968dc61d..f2ecb2049c 100755
--- a/scripts/dev-env.sh
+++ b/scripts/dev-env.sh
@@ -834,24 +834,10 @@ ensure_fixture_issues() {
ok "seeded 2 issues in workspace $WORKSPACE_SLUG"
}
-# The CLI refuses `daemon start` anywhere under a daemon-task marker, so a task
-# cannot spawn a second daemon that competes for its own work. Checking the
-# marker here turns that refusal into one actionable line, before this component
-# has spent a login and a CLI build on an outcome it cannot reach.
-daemon_task_marker() {
- local dir="$REPO_ROOT" marker
- while :; do
- marker="$dir/.multica/daemon_task_context.json"
- if [ -f "$marker" ] && grep -q 'multica-daemon-task' "$marker" 2>/dev/null; then
- printf '%s' "$marker"
- return 0
- fi
- [ "$dir" != "/" ] || break
- dir="$(dirname "$dir")"
- done
- return 0
-}
-
+# Under a daemon-task marker the CLI refuses daemon commands for every profile
+# except one this registry assigns to an environment, reached without the task's
+# identity and pointed at that environment's API — exactly how CLEAN_ENV and
+# the profile written above launch it (server/cmd/multica/dev_env_profile.go).
start_daemon() {
local status state build_commit
@@ -1416,15 +1402,6 @@ cmd_up() {
fi
ok "node, go, curl found"
- if component_selected daemon; then
- local marker
- marker="$(daemon_task_marker)"
- [ -z "$marker" ] || die "The daemon component cannot start under a daemon-managed task.
-This checkout sits below $marker, and the CLI refuses 'daemon start' there so a
-task cannot spawn a second daemon competing for its own work.
-Start the rest with 'make up C=api,web', or run 'make up C=daemon' from your own shell."
- fi
-
step "Environment"
ENV_FILE="$(detect_env_file)"
if [ ! -f "$REPO_ROOT/$ENV_FILE" ]; then
diff --git a/scripts/dev-fixtures.mjs b/scripts/dev-fixtures.mjs
index 32fc3cc994..bb1ab1297c 100644
--- a/scripts/dev-fixtures.mjs
+++ b/scripts/dev-fixtures.mjs
@@ -8,9 +8,9 @@
//
// Replies come from the daemon API, driven with the environment profile's user
// token: the script registers a fixture runtime, then claims, starts and
-// completes each task it caused with canned Markdown. That path works inside a
-// daemon-managed task, where `make up C=daemon` is refused. Every run adds new
-// sessions and issues and then exits; nothing keeps running.
+// completes each task it caused with canned Markdown, so content appears without
+// running a model through `make up C=daemon`. Every run adds new sessions and
+// issues and then exits; nothing keeps running.
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 61884311c1..ec0606e27c 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -165,7 +165,7 @@ type daemonRuntimeProbe struct {
}
func runDaemonProbeRuntimes(cmd *cobra.Command, _ []string) error {
- if err := requireHumanLocalCommand("daemon probe-runtimes"); err != nil {
+ if err := requireHumanLocalDaemonCommand(cmd, "daemon probe-runtimes"); err != nil {
return err
}
cfg, err := daemon.LoadConfig(daemon.Overrides{
@@ -551,7 +551,7 @@ func requireDaemonAuth(profile string) error {
}
func runDaemonStart(cmd *cobra.Command, _ []string) error {
- if err := requireHumanLocalCommand("daemon start"); err != nil {
+ if err := requireHumanLocalDaemonCommand(cmd, "daemon start"); err != nil {
return err
}
foreground, _ := cmd.Flags().GetBool("foreground")
@@ -1388,7 +1388,7 @@ func runDaemonRestart(cmd *cobra.Command, args []string) error {
// --- daemon stop ---
func runDaemonStop(cmd *cobra.Command, _ []string) error {
- if err := requireHumanLocalCommand("daemon stop"); err != nil {
+ if err := requireHumanLocalDaemonCommand(cmd, "daemon stop"); err != nil {
return err
}
profile := resolveProfile(cmd)
@@ -1495,8 +1495,8 @@ func runDaemonStatus(cmd *cobra.Command, _ []string) error {
}
output, _ := cmd.Flags().GetString("output")
- // Safe to list profiles here: daemonStatusHealthPort already rejected an
- // explicit --profile inside a daemon-managed task.
+ // Safe to list profiles here: daemonStatusHealthPort already rejected every
+ // explicit --profile inside a daemon-managed task except a dev-env one.
if err := requireKnownProfile(profile); err != nil {
var unknown *unknownProfileError
if output == "json" && errors.As(err, &unknown) {
@@ -1525,9 +1525,10 @@ func runDaemonStatus(cmd *cobra.Command, _ []string) error {
// possible — and the task's profile is necessarily empty (--profile is
// rejected) while the host may run a named one, which would make every
// named-profile host look like a conflict and break the standing contract
- // that `daemon status` in a task reports on the daemon hosting it.
+ // that `daemon status` in a task reports on the daemon hosting it. A dev-env
+ // profile's port is profile-derived like any other, so it keeps the check.
var conflict *daemonProfileMismatchError
- if daemonAlive(health) && !inDaemonTaskIdentityContext() {
+ if daemonAlive(health) && (!inDaemonTaskIdentityContext() || devEnvOwnsDaemonProfile(cmd)) {
errors.As(daemonIdentityMismatch(health, profile, healthPort), &conflict)
}
@@ -1570,10 +1571,11 @@ func runDaemonStatus(cmd *cobra.Command, _ []string) error {
// whatever profile name the caller passes, so deriving the port there would let
// a task report on a daemon that is not the one hosting it — and for a task
// hosted by a named-profile daemon it would silently probe the default daemon
-// instead. A missing port fails closed rather than guessing.
+// instead. A missing port fails closed rather than guessing. The one exception
+// is a dev-env profile, which names a daemon the task started itself.
func daemonStatusHealthPort(cmd *cobra.Command) (int, error) {
profile := resolveProfile(cmd)
- if !inDaemonTaskIdentityContext() {
+ if !inDaemonTaskIdentityContext() || devEnvOwnsDaemonProfile(cmd) {
return resolveHealthPort(profile), nil
}
if profile != "" {
diff --git a/server/cmd/multica/dev_env_profile.go b/server/cmd/multica/dev_env_profile.go
new file mode 100644
index 0000000000..bb28fbed49
--- /dev/null
+++ b/server/cmd/multica/dev_env_profile.go
@@ -0,0 +1,119 @@
+package main
+
+import (
+ "bufio"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+ "github.com/multica-ai/multica/server/internal/daemon"
+)
+
+// A local development environment started by scripts/dev-env.sh runs its own
+// daemon on a profile the script created, signed in to that environment's own
+// API. A checkout an agent works in sits below the daemon-task marker, so
+// without the exemption here every daemon lifecycle command for that profile
+// is refused, and the agent can test the API, Web and Desktop but never a real
+// agent run.
+//
+// The exemption is narrow on every axis. It covers only the daemon commands
+// dev-env and its Desktop run, only an explicit --profile that the dev-env
+// registry assigns to an environment, only when the daemon would talk to that
+// environment's API, and only from a process the task's identity was stripped
+// 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"
+
+// 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.
+var devEnvManifestValue = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
+
+// requireHumanLocalDaemonCommand is requireHumanLocalCommand for the daemon
+// lifecycle commands a dev-env environment runs against its own profiles.
+func requireHumanLocalDaemonCommand(cmd *cobra.Command, command string) error {
+ err := requireHumanLocalCommand(command)
+ if err != nil && devEnvOwnsDaemonProfile(cmd) {
+ return nil
+ }
+ return err
+}
+
+// devEnvOwnsDaemonProfile reports whether the explicit --profile is the CLI
+// profile of a registered dev-env environment, or the one its Desktop signs
+// in, and the daemon for it would connect to that environment's API.
+func devEnvOwnsDaemonProfile(cmd *cobra.Command) bool {
+ profile := resolveProfile(cmd)
+ if profile == "" || taskIdentityInEnv() {
+ return false
+ }
+ port := devEnvBackendPortForProfile(profile)
+ if port == "" {
+ return false
+ }
+ serverURL, err := daemon.NormalizeServerBaseURL(resolveDaemonServerURL(cmd, profile))
+ return err == nil && serverURL == "http://localhost:"+port
+}
+
+// taskIdentityInEnv reports whether the task's own identity is still in the
+// environment. dev-env launches every component without it; a daemon started
+// with it would hand the task's token and config root to the runs it hosts.
+func taskIdentityInEnv() bool {
+ return inAgentExecutionContext() ||
+ strings.TrimSpace(os.Getenv(cli.TaskConfigRootEnv)) != "" ||
+ strings.TrimSpace(os.Getenv("MULTICA_TOKEN")) != "" ||
+ strings.TrimSpace(os.Getenv("MULTICA_DAEMON_PORT")) != ""
+}
+
+// devEnvBackendPortForProfile returns the backend port of the registered
+// environment that owns profile, or "" when none does. An environment owns its
+// 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))
+ if root == "" {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return ""
+ }
+ root = filepath.Join(home, ".multica", "dev")
+ }
+ manifests, _ := filepath.Glob(filepath.Join(root, "envs", "*", "manifest.env"))
+ for _, path := range manifests {
+ manifest := readDevEnvManifest(path)
+ if manifest["NAME"] != filepath.Base(filepath.Dir(path)) {
+ continue
+ }
+ port := manifest["BACKEND_PORT"]
+ if n, err := strconv.Atoi(port); err != nil || n <= 0 || n > 65535 {
+ continue
+ }
+ if profile == manifest["PROFILE"] || profile == "desktop-localhost-"+port {
+ return port
+ }
+ }
+ return ""
+}
+
+func readDevEnvManifest(path string) map[string]string {
+ values := map[string]string{}
+ f, err := os.Open(path)
+ if err != nil {
+ return values
+ }
+ defer f.Close()
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ key, value, ok := strings.Cut(scanner.Text(), "=")
+ if ok && devEnvManifestValue.MatchString(value) {
+ values[key] = value
+ }
+ }
+ return values
+}
diff --git a/server/cmd/multica/dev_env_profile_test.go b/server/cmd/multica/dev_env_profile_test.go
new file mode 100644
index 0000000000..61188933d5
--- /dev/null
+++ b/server/cmd/multica/dev_env_profile_test.go
@@ -0,0 +1,197 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+const (
+ devEnvTestName = "wt-3"
+ devEnvTestProfile = "dev-wt-3"
+ devEnvTestPort = "18083"
+)
+
+// setupDevEnvTask puts the test inside a daemon-task workdir, with the task's
+// identity stripped the way dev-env's CLEAN_ENV strips it, and registers one
+// environment whose profile points at its own backend.
+func setupDevEnvTask(t *testing.T) {
+ t.Helper()
+ chdirWithDaemonTaskMarker(t)
+ clearDaemonTaskEnv(t)
+ t.Setenv("MULTICA_TOKEN", "")
+ t.Setenv("MULTICA_SERVER_URL", "")
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv(devEnvHomeEnv, t.TempDir())
+
+ writeDevEnvManifest(t, devEnvTestName, "NAME="+devEnvTestName+"\nDIR=/tmp/checkout\nBACKEND_PORT="+devEnvTestPort+"\nPROFILE="+devEnvTestProfile+"\n")
+ writeDevEnvProfile(t, devEnvTestProfile, "http://localhost:"+devEnvTestPort)
+}
+
+func writeDevEnvManifest(t *testing.T, name, body string) {
+ t.Helper()
+ dir := filepath.Join(os.Getenv(devEnvHomeEnv), "envs", name)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "manifest.env"), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func writeDevEnvProfile(t *testing.T, profile, serverURL string) {
+ t.Helper()
+ if err := cli.SaveCLIConfigForProfile(cli.CLIConfig{ServerURL: serverURL, Token: "mul_dev"}, profile); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func devEnvDaemonCmd(t *testing.T, profile string) *cobra.Command {
+ t.Helper()
+ cmd := &cobra.Command{}
+ cmd.Flags().String("profile", "", "")
+ cmd.Flags().String("server-url", "", "")
+ cmd.Flags().String("output", "", "")
+ cmd.Flags().Bool("force", false, "")
+ if profile != "" {
+ if err := cmd.Flags().Set("profile", profile); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return cmd
+}
+
+func TestDevEnvDaemonProfileAllowedInsideTask(t *testing.T) {
+ for _, profile := range []string{devEnvTestProfile, "desktop-localhost-" + devEnvTestPort} {
+ t.Run(profile, func(t *testing.T) {
+ setupDevEnvTask(t)
+ writeDevEnvProfile(t, profile, "http://localhost:"+devEnvTestPort+"/")
+
+ cmd := devEnvDaemonCmd(t, profile)
+ for _, command := range []string{"daemon start", "daemon stop", "daemon probe-runtimes"} {
+ if err := requireHumanLocalDaemonCommand(cmd, command); err != nil {
+ t.Fatalf("%s --profile %s: %v", command, profile, err)
+ }
+ }
+ port, err := daemonStatusHealthPort(cmd)
+ if err != nil {
+ t.Fatalf("daemon status --profile %s: %v", profile, err)
+ }
+ if want := healthPortForProfile(profile); port != want {
+ t.Fatalf("status port = %d, want the profile's own %d", port, want)
+ }
+ // The real command, end to end: nothing is running on the port.
+ if err := runDaemonStop(cmd, nil); err != nil {
+ t.Fatalf("runDaemonStop --profile %s: %v", profile, err)
+ }
+ })
+ }
+}
+
+func TestDevEnvDaemonProfileExemptionStaysNarrow(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ profile string
+ setup func(t *testing.T)
+ }{
+ {name: "default profile", profile: ""},
+ {
+ name: "profile the registry does not assign",
+ profile: "staging",
+ setup: func(t *testing.T) {
+ writeDevEnvProfile(t, "staging", "http://localhost:"+devEnvTestPort)
+ },
+ },
+ {
+ name: "desktop profile of another port",
+ profile: "desktop-localhost-18084",
+ setup: func(t *testing.T) {
+ writeDevEnvProfile(t, "desktop-localhost-18084", "http://localhost:"+devEnvTestPort)
+ },
+ },
+ {
+ name: "profile pointed at another server",
+ profile: devEnvTestProfile,
+ setup: func(t *testing.T) {
+ writeDevEnvProfile(t, devEnvTestProfile, "http://localhost:18084")
+ },
+ },
+ {
+ name: "server URL overridden by the task environment",
+ profile: devEnvTestProfile,
+ setup: func(t *testing.T) {
+ t.Setenv("MULTICA_SERVER_URL", "https://api.multica.ai")
+ },
+ },
+ {
+ name: "task ID still in the environment",
+ profile: devEnvTestProfile,
+ setup: func(t *testing.T) { t.Setenv("MULTICA_TASK_ID", "task-1") },
+ },
+ {
+ name: "task token still in the environment",
+ profile: devEnvTestProfile,
+ setup: func(t *testing.T) { t.Setenv("MULTICA_TOKEN", "mat_task") },
+ },
+ {
+ name: "task daemon port still in the environment",
+ profile: devEnvTestProfile,
+ setup: func(t *testing.T) { t.Setenv("MULTICA_DAEMON_PORT", "19514") },
+ },
+ {
+ name: "task config root still in the environment",
+ profile: devEnvTestProfile,
+ setup: func(t *testing.T) { t.Setenv(cli.TaskConfigRootEnv, t.TempDir()) },
+ },
+ {
+ name: "manifest named for another environment",
+ profile: "dev-other-4",
+ setup: func(t *testing.T) {
+ writeDevEnvManifest(t, "other-4", "NAME=wt-3\nBACKEND_PORT=18084\nPROFILE=dev-other-4\n")
+ writeDevEnvProfile(t, "dev-other-4", "http://localhost:18084")
+ },
+ },
+ {
+ name: "no registry",
+ profile: devEnvTestProfile,
+ setup: func(t *testing.T) { t.Setenv(devEnvHomeEnv, t.TempDir()) },
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ setupDevEnvTask(t)
+ if tc.setup != nil {
+ tc.setup(t)
+ }
+ cmd := devEnvDaemonCmd(t, tc.profile)
+ for _, command := range []string{"daemon start", "daemon stop", "daemon probe-runtimes"} {
+ if err := requireHumanLocalDaemonCommand(cmd, command); err == nil || !strings.Contains(err.Error(), "daemon-managed task") {
+ t.Fatalf("%s was not refused: %v", command, err)
+ }
+ }
+ if _, err := daemonStatusHealthPort(cmd); err == nil {
+ t.Fatal("daemon status was not refused")
+ }
+ })
+ }
+}
+
+// Only start, stop, status and probe-runtimes take the exemption; every other
+// human-local command stays refused for a dev-env profile too.
+func TestDevEnvDaemonProfileLeavesOtherCommandsRefused(t *testing.T) {
+ setupDevEnvTask(t)
+ cmd := devEnvDaemonCmd(t, devEnvTestProfile)
+ cmd.Flags().Bool("foreground", false, "")
+ if err := runDaemonRestart(cmd, nil); err == nil || !strings.Contains(err.Error(), "daemon-managed task") {
+ t.Fatalf("daemon restart --profile %s was not refused: %v", devEnvTestProfile, err)
+ }
+ for _, command := range []string{"login", "logout", "daemon autostart enable"} {
+ if err := requireHumanLocalCommand(command); err == nil {
+ t.Fatalf("%s was allowed inside a task", command)
+ }
+ }
+}
diff --git a/turbo.json b/turbo.json
index 65ae6f7036..4c6a5227a4 100644
--- a/turbo.json
+++ b/turbo.json
@@ -49,7 +49,9 @@
"persistent": true,
// scripts/dev-env.sh opens a Desktop DevTools port (read by
// electron-vite) and signs the dev Desktop in (read by its main process).
- "passThroughEnv": ["REMOTE_DEBUGGING_PORT", "MULTICA_DEV_AUTH_TOKEN"]
+ // Desktop's bundled CLI finds a custom dev-env registry through
+ // MULTICA_DEV_HOME, or refuses its daemon inside an agent task.
+ "passThroughEnv": ["REMOTE_DEBUGGING_PORT", "MULTICA_DEV_AUTH_TOKEN", "MULTICA_DEV_HOME"]
},
"dev:staging": {
"cache": false,