Skip to content

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

Go

MUL-6368: Prevent cross-agent task and workdir contamination (#7205)

Multica Eveeb2a94e86099
diff --git a/server/cmd/multica/cmd_repo.go b/server/cmd/multica/cmd_repo.go
index 7f266d534d..e2d43bcafb 100644
--- a/server/cmd/multica/cmd_repo.go
+++ b/server/cmd/multica/cmd_repo.go
@@ -343,6 +343,10 @@ func runRepoCheckout(cmd *cobra.Command, args []string) error {
workspaceID := os.Getenv("MULTICA_WORKSPACE_ID")
agentName := os.Getenv("MULTICA_AGENT_NAME")
taskID := os.Getenv("MULTICA_TASK_ID")
+ taskToken := os.Getenv("MULTICA_TOKEN")
+ if taskToken == "" {
+ return fmt.Errorf("MULTICA_TOKEN not set (repo checkout requires the active task credential)")
+ }
// Use current working directory as the checkout target.
workDir, err := os.Getwd()
@@ -381,6 +385,7 @@ func runRepoCheckout(cmd *cobra.Command, args []string) error {
return fmt.Errorf("create daemon checkout request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+taskToken)
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("connect to daemon: %w", err)
diff --git a/server/cmd/multica/cmd_repo_test.go b/server/cmd/multica/cmd_repo_test.go
index 07dd9030cb..5df28315ac 100644
--- a/server/cmd/multica/cmd_repo_test.go
+++ b/server/cmd/multica/cmd_repo_test.go
@@ -200,6 +200,9 @@ func TestRunRepoCheckoutForwardsManagedCheckoutMode(t *testing.T) {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("decode checkout body: %v", err)
}
+ if got := r.Header.Get("Authorization"); got != "Bearer mat_repo_checkout_test" {
+ t.Fatalf("Authorization = %q, want task-scoped bearer", got)
+ }
json.NewEncoder(w).Encode(map[string]string{
"path": "/work/repo",
"branch_name": "agent/test/task",
@@ -211,6 +214,7 @@ func TestRunRepoCheckoutForwardsManagedCheckoutMode(t *testing.T) {
t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
t.Setenv("MULTICA_AGENT_NAME", "Test Agent")
t.Setenv("MULTICA_TASK_ID", "task-1")
+ t.Setenv("MULTICA_TOKEN", "mat_repo_checkout_test")
t.Setenv("MULTICA_REPO_CHECKOUT_MODE", "isolated")
previousRef := repoCheckoutRef
@@ -231,6 +235,16 @@ func TestRunRepoCheckoutForwardsManagedCheckoutMode(t *testing.T) {
}
}
+func TestRunRepoCheckoutRequiresTaskCredential(t *testing.T) {
+ t.Setenv("MULTICA_DAEMON_PORT", "12345")
+ t.Setenv("MULTICA_TOKEN", "")
+
+ err := runRepoCheckout(&cobra.Command{}, []string{"https://github.com/org/repo.git"})
+ if err == nil || !strings.Contains(err.Error(), "MULTICA_TOKEN not set") {
+ t.Fatalf("runRepoCheckout error = %v, want missing task credential", err)
+ }
+}
+
func TestRunRepoCheckoutRetriesServiceUnavailable(t *testing.T) {
attempts := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -252,6 +266,7 @@ func TestRunRepoCheckoutRetriesServiceUnavailable(t *testing.T) {
t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
t.Setenv("MULTICA_AGENT_NAME", "Test Agent")
t.Setenv("MULTICA_TASK_ID", "task-1")
+ t.Setenv("MULTICA_TOKEN", "mat_repo_checkout_test")
if err := runRepoCheckout(&cobra.Command{}, []string{"https://github.com/org/repo.git"}); err != nil {
t.Fatalf("runRepoCheckout: %v", err)
@@ -270,6 +285,7 @@ func TestRunRepoCheckoutDoesNotRetryUnmarkedServiceUnavailable(t *testing.T) {
defer srv.Close()
t.Setenv("MULTICA_DAEMON_PORT", strings.TrimPrefix(srv.URL, "http://127.0.0.1:"))
+ t.Setenv("MULTICA_TOKEN", "mat_repo_checkout_test")
if err := runRepoCheckout(&cobra.Command{}, []string{"https://github.com/org/repo.git"}); err == nil {
t.Fatal("runRepoCheckout unexpectedly succeeded")
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 6646a009dd..a227651737 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -121,8 +121,22 @@ func repoCheckoutModeFor(provider, goos string) string {
var (
taskPrepareLeaseRefresh = 15 * time.Second
taskPrepareLeaseTimeout = 10 * time.Second
+ errInvalidTaskIdentity = errors.New("invalid task identity")
)
+func validateTaskIdentity(task Task) error {
+ if strings.TrimSpace(task.AgentID) == "" {
+ return fmt.Errorf("%w: task %s has no authoritative agent_id", errInvalidTaskIdentity, task.ID)
+ }
+ if task.Agent == nil {
+ return fmt.Errorf("%w: task %s has no agent payload (agent_id=%s)", errInvalidTaskIdentity, task.ID, task.AgentID)
+ }
+ if task.Agent.ID != task.AgentID {
+ return fmt.Errorf("%w: task %s agent_id=%s but agent.id=%s", errInvalidTaskIdentity, task.ID, task.AgentID, task.Agent.ID)
+ }
+ return nil
+}
+
func taskScopedAuthToken(task Task) (string, error) {
token := strings.TrimSpace(task.AuthToken)
if token == "" {
@@ -552,6 +566,13 @@ type Daemon struct {
activeStores map[string]int // persistent store path (per-conversation Codex sessions, per-agent Hermes memories) -> live-task refcount; guards the store from GC mid-task (MUL-4424)
deletingStores map[string]bool // store paths a GC delete has reserved; markActive waits these out so a task never mounts a store mid-removal
+ // repoCheckoutTasks binds the localhost /repo/checkout endpoint to the
+ // task-scoped bearer token of a currently running agent. The request body is
+ // never an identity source: workspace, task, agent, and allowed workdir all
+ // come from this registry.
+ repoCheckoutTasksMu sync.RWMutex
+ repoCheckoutTasks map[string]activeRepoCheckoutTask
+
// localPathLocks serialises agent tasks whose project resource is a
// local_directory pinned to this daemon. Two tasks targeting the same
// on-disk path run sequentially; the second blocks on the lock and is
@@ -5205,6 +5226,9 @@ func (e *worktreePreservedError) Error() string { return e.err.Error() }
func (e *worktreePreservedError) Unwrap() error { return e.err }
func taskRunFailureReason(err error) string {
+ if errors.Is(err, errInvalidTaskIdentity) {
+ return taskfailure.ReasonInvalidTaskIdentity.String()
+ }
if errors.Is(err, errTaskPrepareTimeout) {
return taskfailure.ReasonTimeout.String()
}
@@ -5705,14 +5729,13 @@ func sessionHomeReachable(provider string, env *execenv.Environment, envReused b
return envReused
}
-// shouldReusePriorWorkdir keeps the local_directory lock invariant without
-// forcing every squad-leader follow-up onto a fresh provider session. Worker
-// tasks already expose their current local-directory assignment, so their
-// existing reuse behavior remains unchanged. Leader tasks intentionally skip
-// that assignment and its lock; they may therefore reuse only directories
+// shouldReusePriorWorkdir keeps the local_directory lock and cross-agent
+// isolation invariants without forcing managed follow-ups onto a fresh
+// provider session. Every managed issue or chat task may reuse only directories
// that resolve to the {workspace}/{task}/workdir shape, carry Prepare-time
-// managed-env provenance for the same workspace/issue/agent, and carry a
-// matching daemon task-context marker.
+// managed-env provenance for the same workspace/scope/agent, and carry a
+// matching daemon task-context marker. Other task kinds have no durable scope
+// with which to prove ownership and therefore start fresh.
//
// Reuse eligibility is deliberately keyed off .managed_env.json (written by
// execenv.Prepare) and NOT .gc_meta.json (written only after the task reaches
@@ -5726,9 +5749,6 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmen
if task.PriorWorkDir == "" || localAssignment != nil {
return false
}
- if !task.IsLeaderTask {
- return true
- }
root, err := filepath.EvalSymlinks(workspacesRoot)
if err != nil {
@@ -5750,15 +5770,15 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmen
if len(parts) != 3 || parts[0] != task.WorkspaceID || parts[1] == "" || parts[2] != "workdir" {
return false
}
- if task.AgentID == "" || task.IssueID == "" {
+ if task.AgentID == "" || (task.IssueID == "" && task.ChatSessionID == "") {
return false
}
- // Managed-env provenance is written only for non-local managed issue envs,
- // so its presence (plus the workspace/issue/agent match) proves this is a
+ // Managed-env provenance is written only for non-local resumable envs, so
+ // its presence (plus the workspace/scope/agent match) proves this is a
// safe daemon-managed reuse target and not a residual local_directory path.
prov, err := execenv.ReadManagedEnvProvenance(filepath.Dir(workdir))
if err != nil || prov.ManagedBy != execenv.ManagedEnvProvenanceManagedBy ||
- prov.WorkspaceID != task.WorkspaceID || prov.IssueID != task.IssueID ||
+ prov.WorkspaceID != task.WorkspaceID ||
prov.AgentID != task.AgentID {
return false
}
@@ -5768,15 +5788,21 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmen
return false
}
var marker struct {
- ManagedBy string `json:"managed_by"`
- AgentID string `json:"agent_id"`
- IssueID string `json:"issue_id"`
+ ManagedBy string `json:"managed_by"`
+ AgentID string `json:"agent_id"`
+ IssueID string `json:"issue_id"`
+ ChatSessionID string `json:"chat_session_id"`
}
if json.Unmarshal(data, &marker) != nil {
return false
}
- return marker.ManagedBy == execenv.TaskContextMarkerManagedBy &&
- marker.AgentID == task.AgentID && marker.IssueID == task.IssueID
+ if marker.ManagedBy != execenv.TaskContextMarkerManagedBy || marker.AgentID != task.AgentID {
+ return false
+ }
+ if task.IssueID != "" {
+ return prov.IssueID == task.IssueID && marker.IssueID == task.IssueID
+ }
+ return prov.ChatSessionID == task.ChatSessionID && marker.ChatSessionID == task.ChatSessionID
}
// gateCodexResumeToRolloutPresence drops the prior Codex session when its
@@ -6099,6 +6125,14 @@ func skillRefFromBundle(bundle SkillData) SkillRefData {
}
func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot int, taskLog *slog.Logger) (taskResult TaskResult, returnErr error) {
+ // A claim carries the task-row agent id both at the top level and inside
+ // the expanded agent configuration. The top-level id is authoritative
+ // because it is also bound into the task-scoped token. Never prepare or
+ // reuse a workdir when the two identities disagree.
+ if err := validateTaskIdentity(task); err != nil {
+ return TaskResult{}, err
+ }
+
// Refuse to spawn an agent without a workspace. An empty workspace_id
// here would make MULTICA_WORKSPACE_ID empty in the agent env, and the
// CLI would otherwise silently fall back to the user-global config — a
@@ -6187,15 +6221,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
agentName := "agent"
- var agentID string
var skills []SkillData
var instructions string
- if task.Agent != nil {
- agentID = task.Agent.ID
- agentName = task.Agent.Name
- skills = task.Agent.Skills
- instructions = task.Agent.Instructions
- }
+ agentName = task.Agent.Name
+ skills = task.Agent.Skills
+ instructions = task.Agent.Instructions
// Prepare isolated execution environment.
// Repos are passed as metadata only — the agent checks them out on demand
@@ -6213,7 +6243,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// absent). Seed the brief's continuity disclosure from it; the local
// resume gates below only ever OR it to true, so the signal is monotonic.
PriorSessionResumeUnavailable: task.PriorSessionResumeUnavailable,
- AgentID: agentID,
+ AgentID: task.AgentID,
AgentName: agentName,
AgentInstructions: instructions,
AgentSkills: convertSkillsForEnv(skills),
@@ -7065,6 +7095,20 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
return TaskResult{Status: "completed", Comment: "", WorkDir: env.WorkDir, EnvRoot: env.RootDir}, nil
}
+ // Authenticate the localhost repo-checkout endpoint with the same
+ // task-scoped token the child receives. The endpoint derives identity and
+ // branch ownership from this in-memory record instead of trusting request
+ // fields or ambient process environment. Register only for the provider
+ // execution window and always remove the credential afterwards.
+ d.registerActiveRepoCheckoutTask(agentToken, activeRepoCheckoutTask{
+ WorkspaceID: task.WorkspaceID,
+ TaskID: task.ID,
+ AgentID: task.AgentID,
+ AgentName: task.Agent.Name,
+ WorkDir: env.WorkDir,
+ })
+ defer d.clearActiveRepoCheckoutTask(agentToken)
+
taskLog.Debug("invoking backend",
"provider", provider,
"model", model,
diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.go
index ee113838c6..62139b708a 100644
--- a/server/internal/daemon/execenv/context.go
+++ b/server/internal/daemon/execenv/context.go
@@ -24,9 +24,10 @@ const TaskContextMarkerRelPath = ".multica/daemon_task_context.json"
const TaskContextMarkerManagedBy = "multica-daemon-task"
type taskContextMarkerFile struct {
- ManagedBy string `json:"managed_by"`
- AgentID string `json:"agent_id,omitempty"`
- IssueID string `json:"issue_id,omitempty"`
+ ManagedBy string `json:"managed_by"`
+ AgentID string `json:"agent_id,omitempty"`
+ IssueID string `json:"issue_id,omitempty"`
+ ChatSessionID string `json:"chat_session_id,omitempty"`
}
// EnsureWorkspacesRootMarker writes a persistent daemon-task marker at
@@ -212,9 +213,10 @@ func writeTaskContextMarker(workDir string, ctx TaskContextForEnv, manifest *sid
// cleanup. If a crash leaves it behind, the CLI intentionally treats it
// as daemon context and fails closed instead of using a user PAT.
payload := taskContextMarkerFile{
- ManagedBy: TaskContextMarkerManagedBy,
- AgentID: ctx.AgentID,
- IssueID: ctx.IssueID,
+ ManagedBy: TaskContextMarkerManagedBy,
+ AgentID: ctx.AgentID,
+ IssueID: ctx.IssueID,
+ ChatSessionID: ctx.ChatSessionID,
}
data, err := json.MarshalIndent(payload, "", " ")
if err != nil {
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 8c7d1c68ce..c7cc62c89d 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -468,20 +468,21 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
return nil, fmt.Errorf("execenv: write context files: %w", err)
}
- // Persist managed-env provenance for non-local issue envs at Prepare time
+ // Persist managed-env provenance for non-local resumable envs at Prepare time
// (not on completion, where .gc_meta.json is written). A same-issue
// follow-up can be claimed the instant the prior task completes — before
// the prior handler writes .gc_meta.json — so reuse eligibility must be
// provable from an artifact that exists the moment the env is created. Only
- // managed (non-local_directory) issue envs get this marker; that is exactly
- // the set squad-leader reuse targets (MUL-4886). Non-fatal: a write failure
+ // managed (non-local_directory) issue and chat envs get this marker; that is
+ // exactly the set with a durable conversation scope. Non-fatal: a write failure
// only costs the next follow-up its session reuse (it falls back to a fresh
// session), which must never block dispatching this task.
- if params.LocalWorkDir == "" && params.Task.IssueID != "" {
+ if params.LocalWorkDir == "" && (params.Task.IssueID != "" || params.Task.ChatSessionID != "") {
if err := WriteManagedEnvProvenance(envRoot, ManagedEnvProvenance{
- WorkspaceID: params.WorkspaceID,
- IssueID: params.Task.IssueID,
- AgentID: params.Task.AgentID,
+ WorkspaceID: params.WorkspaceID,
+ IssueID: params.Task.IssueID,
+ ChatSessionID: params.Task.ChatSessionID,
+ AgentID: params.Task.AgentID,
}); err != nil && logger != nil {
logger.Warn("execenv: write managed env provenance failed (non-fatal); a follow-up may start a fresh session", "error", err)
}
@@ -1004,8 +1005,8 @@ const ManagedEnvProvenanceManagedBy = "multica-daemon-managed-env"
// ManagedEnvProvenance is persisted to .managed_env.json inside the env root at
// Prepare time (NOT on completion, unlike .gc_meta.json). It records that this
-// env root is a daemon-managed, non-local_directory issue env owned by a
-// specific workspace/issue/agent.
+// env root is a daemon-managed, non-local_directory resumable env owned by a
+// specific workspace, conversation scope, and agent.
//
// Its whole reason to exist is timing. A squad-leader follow-up on the same
// issue can be claimed the instant the prior task completes — the server's
@@ -1014,18 +1015,19 @@ const ManagedEnvProvenanceManagedBy = "multica-daemon-managed-env"
// eligibility off .gc_meta.json therefore raced: the successor read a
// not-yet-written file and started a fresh session (MUL-4886). This marker is
// on disk from the moment the env is created, so the successor can prove reuse
-// safety inside that window. It is written ONLY for non-local managed issue
-// envs, so its presence is itself the "safe to reuse, not a user
+// safety inside that window. It is written only for non-local managed issue or
+// chat envs, so its presence is itself the "safe to reuse, not a user
// local_directory" assertion; see shouldReusePriorWorkdir.
type ManagedEnvProvenance struct {
- ManagedBy string `json:"managed_by"`
- WorkspaceID string `json:"workspace_id"`
- IssueID string `json:"issue_id"`
- AgentID string `json:"agent_id"`
+ ManagedBy string `json:"managed_by"`
+ WorkspaceID string `json:"workspace_id"`
+ IssueID string `json:"issue_id,omitempty"`
+ ChatSessionID string `json:"chat_session_id,omitempty"`
+ AgentID string `json:"agent_id"`
}
// WriteManagedEnvProvenance persists the reuse-eligibility marker at the env
-// root. Callers must only invoke it for non-local_directory issue envs, since
+// root. Callers must only invoke it for non-local_directory resumable envs, since
// the file's presence is the non-local assertion. ManagedBy is stamped here so
// callers cannot forget the discriminator.
func WriteManagedEnvProvenance(envRoot string, p ManagedEnvProvenance) error {
diff --git a/server/internal/daemon/execenv/managed_env_provenance_test.go b/server/internal/daemon/execenv/managed_env_provenance_test.go
index c26be3aea8..d47f862e3b 100644
--- a/server/internal/daemon/execenv/managed_env_provenance_test.go
+++ b/server/internal/daemon/execenv/managed_env_provenance_test.go
@@ -72,10 +72,9 @@ func TestPrepareLocalDirectoryWritesNoProvenance(t *testing.T) {
}
}
-// TestPrepareNonIssueEnvWritesNoProvenance confirms non-issue envs (chat,
-// autopilot, quick-create) get no provenance: reuse targets only issue tasks,
-// so writing it elsewhere would be dead weight.
-func TestPrepareNonIssueEnvWritesNoProvenance(t *testing.T) {
+// TestPrepareManagedChatEnvWritesProvenance confirms chat reuse has the same
+// ownership proof as issue reuse while remaining scoped to its conversation.
+func TestPrepareManagedChatEnvWritesProvenance(t *testing.T) {
root := t.TempDir()
env, err := Prepare(PrepareParams{
WorkspacesRoot: root,
@@ -92,7 +91,11 @@ func TestPrepareNonIssueEnvWritesNoProvenance(t *testing.T) {
}
defer env.Cleanup(true)
- if _, err := ReadManagedEnvProvenance(env.RootDir); !os.IsNotExist(err) {
- t.Fatalf("non-issue Prepare must not write managed env provenance; got err = %v", err)
+ prov, err := ReadManagedEnvProvenance(env.RootDir)
+ if err != nil {
+ t.Fatalf("read chat managed env provenance: %v", err)
+ }
+ if prov.WorkspaceID != "ws-prov-chat" || prov.ChatSessionID != "chat-1" || prov.AgentID != "agent-chat" || prov.IssueID != "" {
+ t.Fatalf("chat provenance owner mismatch: %+v", prov)
}
}
diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.go
index 779fd03ec0..524bb01d85 100644
--- a/server/internal/daemon/health.go
+++ b/server/internal/daemon/health.go
@@ -8,6 +8,7 @@ import (
"net"
"net/http"
"os"
+ "path/filepath"
"runtime"
"strings"
"time"
@@ -107,6 +108,74 @@ type repoCheckoutRequest struct {
RetryBusy bool `json:"retry_busy,omitempty"`
}
+type activeRepoCheckoutTask struct {
+ WorkspaceID string
+ TaskID string
+ AgentID string
+ AgentName string
+ WorkDir string
+}
+
+// registerActiveRepoCheckoutTask binds checkout identity to the active task.
+// The token prevents unauthenticated localhost callers from choosing another
+// task's identity or workdir. It is not an OS-user isolation boundary: another
+// process that can steal the child's environment token can authenticate as
+// that task and already holds its API credential.
+func (d *Daemon) registerActiveRepoCheckoutTask(token string, task activeRepoCheckoutTask) {
+ d.repoCheckoutTasksMu.Lock()
+ defer d.repoCheckoutTasksMu.Unlock()
+ if d.repoCheckoutTasks == nil {
+ d.repoCheckoutTasks = make(map[string]activeRepoCheckoutTask)
+ }
+ d.repoCheckoutTasks[token] = task
+}
+
+func (d *Daemon) clearActiveRepoCheckoutTask(token string) {
+ d.repoCheckoutTasksMu.Lock()
+ delete(d.repoCheckoutTasks, token)
+ d.repoCheckoutTasksMu.Unlock()
+}
+
+func (d *Daemon) activeRepoCheckoutTask(r *http.Request) (activeRepoCheckoutTask, bool) {
+ const bearer = "Bearer "
+ header := strings.TrimSpace(r.Header.Get("Authorization"))
+ if !strings.HasPrefix(header, bearer) {
+ return activeRepoCheckoutTask{}, false
+ }
+ token := strings.TrimSpace(strings.TrimPrefix(header, bearer))
+ if token == "" {
+ return activeRepoCheckoutTask{}, false
+ }
+ d.repoCheckoutTasksMu.RLock()
+ task, ok := d.repoCheckoutTasks[token]
+ d.repoCheckoutTasksMu.RUnlock()
+ return task, ok
+}
+
+func authorizeRepoCheckoutWorkDir(activeRoot, requested string) (string, error) {
+ root, err := filepath.Abs(activeRoot)
+ if err != nil {
+ return "", err
+ }
+ root, err = filepath.EvalSymlinks(root)
+ if err != nil {
+ return "", err
+ }
+ workdir, err := filepath.Abs(requested)
+ if err != nil {
+ return "", err
+ }
+ workdir, err = filepath.EvalSymlinks(workdir)
+ if err != nil {
+ return "", err
+ }
+ rel, err := filepath.Rel(root, workdir)
+ if err != nil || !filepath.IsLocal(rel) {
+ return "", errors.New("workdir is outside the active task workdir")
+ }
+ return workdir, nil
+}
+
const (
repoCheckoutLockWaitTimeout = 10 * time.Second
repoCheckoutRetryAfter = 2 * time.Second
@@ -224,6 +293,11 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
+ activeTask, ok := d.activeRepoCheckoutTask(r)
+ if !ok {
+ http.Error(w, "repo checkout requires an active task credential", http.StatusUnauthorized)
+ return
+ }
var req repoCheckoutRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -247,6 +321,22 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {
http.Error(w, "invalid checkout_mode", http.StatusBadRequest)
return
}
+ if req.WorkspaceID != activeTask.WorkspaceID || req.TaskID != activeTask.TaskID {
+ http.Error(w, "repo checkout task context does not match the active task", http.StatusForbidden)
+ return
+ }
+ authorizedWorkDir, authErr := authorizeRepoCheckoutWorkDir(activeTask.WorkDir, req.WorkDir)
+ if authErr != nil {
+ http.Error(w, "repo checkout workdir is not owned by the active task", http.StatusForbidden)
+ return
+ }
+ // Identity is derived from the token-bound active task. AgentName and the
+ // other caller-supplied fields are compatibility inputs only and never
+ // decide branch ownership.
+ req.WorkspaceID = activeTask.WorkspaceID
+ req.TaskID = activeTask.TaskID
+ req.AgentName = activeTask.AgentName
+ req.WorkDir = authorizedWorkDir
if d.repoCache == nil {
http.Error(w, "repo cache not initialized", http.StatusInternalServerError)
diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.go
index e8accda3ba..a9c2cb873c 100644
--- a/server/internal/daemon/health_test.go
+++ b/server/internal/daemon/health_test.go
@@ -3,6 +3,7 @@ package daemon
import (
"context"
"encoding/json"
+ "io"
"log/slog"
"net/http"
"net/http/httptest"
@@ -319,12 +320,13 @@ func TestRepoCheckoutUsesTaskScopedProjectRefByDefault(t *testing.T) {
const workspaceID = "ws-checkout"
const repoURL = "https://github.com/org/repo.git"
cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}
- d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, cache)
+ workDir := t.TempDir()
+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)
d.registerTaskRepos(workspaceID, "task-1", []RepoData{{URL: repoURL, Ref: "release/v2"}})
rec := httptest.NewRecorder()
- body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"/tmp/work","task_id":"task-1"}`)
- d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))
+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + workDir + `","agent_name":"Other Agent","task_id":"task-1"}`)
+ d.repoCheckoutHandler().ServeHTTP(rec, authorizedRepoCheckoutRequest(body))
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
@@ -332,6 +334,52 @@ func TestRepoCheckoutUsesTaskScopedProjectRefByDefault(t *testing.T) {
if got := cache.lastCreateParams().Ref; got != "release/v2" {
t.Fatalf("CreateWorktree Ref = %q, want release/v2", got)
}
+ if got := cache.lastCreateParams().AgentName; got != "Test Agent" {
+ t.Fatalf("CreateWorktree AgentName = %q, want token-bound active agent", got)
+ }
+}
+
+func TestRepoCheckoutRejectsMissingTaskCredential(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-checkout"
+ const repoURL = "https://github.com/org/repo.git"
+ cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}
+ workDir := t.TempDir()
+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)
+
+ rec := httptest.NewRecorder()
+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + workDir + `","task_id":"task-1"}`)
+ d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401, got %d: %s", rec.Code, rec.Body.String())
+ }
+ if got := cache.lastCreateParams(); got != (repocache.WorktreeParams{}) {
+ t.Fatalf("unauthorized checkout reached repo cache: %+v", got)
+ }
+}
+
+func TestRepoCheckoutRejectsAnotherTaskWorkdir(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-checkout"
+ const repoURL = "https://github.com/org/repo.git"
+ cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}
+ workDir := t.TempDir()
+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)
+ otherWorkDir := t.TempDir()
+
+ rec := httptest.NewRecorder()
+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + otherWorkDir + `","task_id":"task-1"}`)
+ d.repoCheckoutHandler().ServeHTTP(rec, authorizedRepoCheckoutRequest(body))
+
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d: %s", rec.Code, rec.Body.String())
+ }
+ if got := cache.lastCreateParams(); got != (repocache.WorktreeParams{}) {
+ t.Fatalf("cross-task workdir checkout reached repo cache: %+v", got)
+ }
}
func TestRepoCheckoutExplicitRefOverridesProjectDefault(t *testing.T) {
@@ -340,12 +388,13 @@ func TestRepoCheckoutExplicitRefOverridesProjectDefault(t *testing.T) {
const workspaceID = "ws-checkout"
const repoURL = "https://github.com/org/repo.git"
cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}
- d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, cache)
+ workDir := t.TempDir()
+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)
d.registerTaskRepos(workspaceID, "task-1", []RepoData{{URL: repoURL, Ref: "release/v2"}})
rec := httptest.NewRecorder()
- body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"/tmp/work","task_id":"task-1","ref":"hotfix"}`)
- d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))
+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + workDir + `","task_id":"task-1","ref":"hotfix"}`)
+ d.repoCheckoutHandler().ServeHTTP(rec, authorizedRepoCheckoutRequest(body))
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
@@ -361,11 +410,12 @@ func TestRepoCheckoutForwardsIsolatedMode(t *testing.T) {
const workspaceID = "ws-checkout"
const repoURL = "https://github.com/org/repo.git"
cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}
- d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, cache)
+ workDir := t.TempDir()
+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)
rec := httptest.NewRecorder()
- body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"/tmp/work","task_id":"task-1","checkout_mode":"isolated"}`)
- d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))
+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + workDir + `","task_id":"task-1","checkout_mode":"isolated"}`)
+ d.repoCheckoutHandler().ServeHTTP(rec, authorizedRepoCheckoutRequest(body))
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
@@ -381,11 +431,12 @@ func TestRepoCheckoutRejectsUnknownMode(t *testing.T) {
const workspaceID = "ws-checkout"
const repoURL = "https://github.com/org/repo.git"
cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}
- d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, cache)
+ workDir := t.TempDir()
+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)
rec := httptest.NewRecorder()
- body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"/tmp/work","task_id":"task-1","checkout_mode":"unsafe"}`)
- d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))
+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + workDir + `","task_id":"task-1","checkout_mode":"unsafe"}`)
+ d.repoCheckoutHandler().ServeHTTP(rec, authorizedRepoCheckoutRequest(body))
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d: %s", rec.Code, rec.Body.String())
@@ -401,11 +452,12 @@ func TestRepoCheckoutReturnsRetryableBusyToCapableClient(t *testing.T) {
const workspaceID = "ws-checkout"
const repoURL = "https://github.com/org/repo.git"
cache := &busyRepoCache{recordingRepoCache: recordingRepoCache{lookupPath: "/cache/org/repo.git"}}
- d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, cache)
+ workDir := t.TempDir()
+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)
rec := httptest.NewRecorder()
- body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"/tmp/work","task_id":"task-1","retry_busy":true}`)
- d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))
+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + workDir + `","task_id":"task-1","retry_busy":true}`)
+ d.repoCheckoutHandler().ServeHTTP(rec, authorizedRepoCheckoutRequest(body))
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("expected 503, got %d: %s", rec.Code, rec.Body.String())
@@ -421,7 +473,7 @@ func TestRepoCheckoutReturnsRetryableBusyToCapableClient(t *testing.T) {
}
}
-func newRepoCheckoutTestDaemon(t *testing.T, workspaceID, repoURL string, cache repoCacheBackend) *Daemon {
+func newRepoCheckoutTestDaemon(t *testing.T, workspaceID, repoURL, workDir string, cache repoCacheBackend) *Daemon {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/daemon/workspaces/"+workspaceID+"/repos" {
@@ -435,7 +487,7 @@ func newRepoCheckoutTestDaemon(t *testing.T, workspaceID, repoURL string, cache
})
}))
t.Cleanup(srv.Close)
- return &Daemon{
+ d := &Daemon{
cfg: Config{CLIVersion: "v1.0.0"},
client: NewClient(srv.URL),
repoCache: cache,
@@ -444,6 +496,20 @@ func newRepoCheckoutTestDaemon(t *testing.T, workspaceID, repoURL string, cache
},
logger: slog.Default(),
}
+ d.registerActiveRepoCheckoutTask("mat_repo_checkout_test", activeRepoCheckoutTask{
+ WorkspaceID: workspaceID,
+ TaskID: "task-1",
+ AgentID: "agent-1",
+ AgentName: "Test Agent",
+ WorkDir: workDir,
+ })
+ return d
+}
+
+func authorizedRepoCheckoutRequest(body io.Reader) *http.Request {
+ req := httptest.NewRequest(http.MethodPost, "/repo/checkout", body)
+ req.Header.Set("Authorization", "Bearer mat_repo_checkout_test")
+ return req
}
type busyRepoCache struct {
diff --git a/server/internal/daemon/leader_workdir_reuse_test.go b/server/internal/daemon/leader_workdir_reuse_test.go
index 84d17af658..88ffa52e1c 100644
--- a/server/internal/daemon/leader_workdir_reuse_test.go
+++ b/server/internal/daemon/leader_workdir_reuse_test.go
@@ -84,18 +84,43 @@ func TestRunTaskSquadLeaderDoesNotReuseExternalPriorWorkdir(t *testing.T) {
}
}
-// TestShouldReusePriorWorkdirNonLeaderReusesUnchanged locks the refactor's
-// non-leader branch: the leader-only provenance/marker gate must not touch the
-// pre-existing behavior where any non-local prior workdir is reused.
-func TestShouldReusePriorWorkdirNonLeaderReusesUnchanged(t *testing.T) {
+// TestShouldReusePriorWorkdirNonLeaderRequiresProvenance prevents an ordinary
+// task from inheriting another agent's repository and Git HEAD merely because
+// the server offered that path.
+func TestShouldReusePriorWorkdirNonLeaderRequiresProvenance(t *testing.T) {
t.Parallel()
root := t.TempDir()
task := leaderReuseTestTask("task-non-leader")
task.IsLeaderTask = false
task.PriorWorkDir = filepath.Join(root, "anything", "workdir")
+ if shouldReusePriorWorkdir(task, nil, root) {
+ t.Fatal("non-leader task reused a prior workdir without any ownership provenance")
+ }
+}
+
+func TestShouldReusePriorWorkdirChatAcceptsMatchingConversation(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ workDir := filepath.Join(root, "ws-chat", "12345678", "workdir")
+ writeChatTaskMarker(t, workDir, "agent-chat", "chat-session")
+ writeChatManagedEnvProvenance(t, workDir, "ws-chat", "chat-session", "agent-chat")
+
+ task := leaderReuseTestTask("task-chat")
+ task.WorkspaceID = "ws-chat"
+ task.IssueID = ""
+ task.ChatSessionID = "chat-session"
+ task.AgentID = "agent-chat"
+ task.IsLeaderTask = false
+ task.PriorWorkDir = workDir
if !shouldReusePriorWorkdir(task, nil, root) {
- t.Fatal("non-leader task must reuse its prior workdir without any provenance requirement")
+ t.Fatalf("chat task did not reuse its fully-provenanced conversation workdir %q", workDir)
+ }
+
+ task.ChatSessionID = "another-chat"
+ if shouldReusePriorWorkdir(task, nil, root) {
+ t.Fatal("chat task reused a workdir belonging to another conversation")
}
}
@@ -300,6 +325,19 @@ func writeLeaderTaskMarker(t *testing.T, workDir, agentID, issueID string) {
}
}
+func writeChatTaskMarker(t *testing.T, workDir, agentID, chatSessionID string) {
+ t.Helper()
+
+ markerPath := filepath.Join(workDir, execenv.TaskContextMarkerRelPath)
+ if err := os.MkdirAll(filepath.Dir(markerPath), 0o755); err != nil {
+ t.Fatalf("mkdir marker dir: %v", err)
+ }
+ marker := []byte(`{"managed_by":"` + execenv.TaskContextMarkerManagedBy + `","agent_id":"` + agentID + `","chat_session_id":"` + chatSessionID + `"}`)
+ if err := os.WriteFile(markerPath, marker, 0o644); err != nil {
+ t.Fatalf("write marker: %v", err)
+ }
+}
+
func writeLeaderManagedEnvProvenance(t *testing.T, workDir, workspaceID, issueID, agentID string) {
t.Helper()
@@ -316,6 +354,22 @@ func writeLeaderManagedEnvProvenance(t *testing.T, workDir, workspaceID, issueID
}
}
+func writeChatManagedEnvProvenance(t *testing.T, workDir, workspaceID, chatSessionID, agentID string) {
+ t.Helper()
+
+ envRoot := filepath.Dir(workDir)
+ if err := os.MkdirAll(envRoot, 0o755); err != nil {
+ t.Fatalf("mkdir env root: %v", err)
+ }
+ if err := execenv.WriteManagedEnvProvenance(envRoot, execenv.ManagedEnvProvenance{
+ WorkspaceID: workspaceID,
+ ChatSessionID: chatSessionID,
+ AgentID: agentID,
+ }); err != nil {
+ t.Fatalf("write managed env provenance: %v", err)
+ }
+}
+
func leaderReuseTestTask(id string) Task {
return Task{
ID: id,
diff --git a/server/internal/daemon/task_identity_test.go b/server/internal/daemon/task_identity_test.go
new file mode 100644
index 0000000000..65a7d46f77
--- /dev/null
+++ b/server/internal/daemon/task_identity_test.go
@@ -0,0 +1,45 @@
+package daemon
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+func TestRunTaskRejectsMismatchedAgentIdentityBeforePreparation(t *testing.T) {
+ t.Parallel()
+
+ d := &Daemon{}
+ _, err := d.runTask(context.Background(), Task{
+ ID: "task-identity-mismatch",
+ WorkspaceID: "workspace-a",
+ AgentID: "agent-a",
+ Agent: &AgentData{ID: "agent-b", Name: "Agent B"},
+ }, "claude", 0, slog.Default())
+ if !errors.Is(err, errInvalidTaskIdentity) {
+ t.Fatalf("runTask error = %v, want invalid task identity", err)
+ }
+ if got := taskRunFailureReason(err); got != taskfailure.ReasonInvalidTaskIdentity.String() {
+ t.Fatalf("failure reason = %q, want %q", got, taskfailure.ReasonInvalidTaskIdentity)
+ }
+}
+
+func TestValidateTaskIdentityRequiresExpandedAgent(t *testing.T) {
+ t.Parallel()
+
+ err := validateTaskIdentity(Task{ID: "task-agent-missing", AgentID: "agent-a"})
+ if !errors.Is(err, errInvalidTaskIdentity) {
+ t.Fatalf("validateTaskIdentity error = %v, want invalid task identity", err)
+ }
+}
+
+func TestValidateTaskIdentityAcceptsMatchingAgent(t *testing.T) {
+ t.Parallel()
+
+ if err := validateTaskIdentity(Task{ID: "task-agent-match", AgentID: "agent-a", Agent: &AgentData{ID: "agent-a"}}); err != nil {
+ t.Fatalf("validateTaskIdentity: %v", err)
+ }
+}
diff --git a/server/internal/daemon/workdir_race_test.go b/server/internal/daemon/workdir_race_test.go
index 6b7e294a95..652f979996 100644
--- a/server/internal/daemon/workdir_race_test.go
+++ b/server/internal/daemon/workdir_race_test.go
@@ -141,7 +141,8 @@ func TestRunTask_StartTaskCalledAfterWorkdirOnDisk(t *testing.T) {
WorkspaceID: workspaceID,
RuntimeID: "rt-1",
IssueID: "issue-runtask",
- Agent: &AgentData{Name: "test-agent"},
+ AgentID: "agent-runtask",
+ Agent: &AgentData{ID: "agent-runtask", Name: "test-agent"},
}
taskLog := slog.New(slog.NewTextHandler(io.Discard, nil))
@@ -215,6 +216,7 @@ printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id
WorkspaceID: workspaceID,
RuntimeID: "rt-1",
IssueID: "issue-private-temp",
+ AgentID: "agent-private-temp",
AuthToken: "mat_private_temp",
Agent: &AgentData{
ID: "agent-private-temp",
@@ -446,6 +448,7 @@ printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id
WorkspaceID: workspaceID,
RuntimeID: "rt-1",
IssueID: "issue-temp-base",
+ AgentID: "agent-temp-base",
AuthToken: "mat_temp_base",
Agent: &AgentData{
ID: "agent-temp-base",
@@ -545,6 +548,7 @@ printf 'ran\n' > "$CAPTURE_FILE"
WorkspaceID: "ws-temp-base-invalid",
RuntimeID: "rt-1",
IssueID: "issue-temp-base-invalid",
+ AgentID: "agent-temp-base-invalid",
AuthToken: "mat_temp_base_invalid",
Agent: &AgentData{
ID: "agent-temp-base-invalid",
@@ -627,7 +631,8 @@ func TestRunTask_ExtendsPrepareLeaseDuringStartTask(t *testing.T) {
WorkspaceID: workspaceID,
RuntimeID: "rt-1",
IssueID: "issue-runtask-start-lease",
- Agent: &AgentData{Name: "test-agent"},
+ AgentID: "agent-runtask-start-lease",
+ Agent: &AgentData{ID: "agent-runtask-start-lease", Name: "test-agent"},
}
taskLog := slog.New(slog.NewTextHandler(io.Discard, nil))
@@ -717,7 +722,8 @@ func TestRunTask_PrepareTimeoutStopsLeaseDuringBlockedStartTask(t *testing.T) {
WorkspaceID: "ws-runtask-start-timeout",
RuntimeID: "rt-1",
IssueID: "issue-runtask-start-timeout",
- Agent: &AgentData{Name: "test-agent"},
+ AgentID: "agent-runtask-start-timeout",
+ Agent: &AgentData{ID: "agent-runtask-start-timeout", Name: "test-agent"},
}
taskLog := slog.New(slog.NewTextHandler(io.Discard, nil))
startedAt := time.Now()
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 9dfd0ac88c..da5ed0bcf7 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1858,6 +1858,23 @@ func chatSessionResumeFallbackNeeded(priorSessionID, priorWorkDir string) bool {
return priorSessionID == "" || priorWorkDir == ""
}
+func rerunSourceMatchesTaskScope(task, source db.AgentTaskQueue) bool {
+ if task.AgentID != source.AgentID {
+ return false
+ }
+ if task.IssueID.Valid {
+ return source.IssueID.Valid && task.IssueID == source.IssueID
+ }
+ if task.ChatSessionID.Valid {
+ return source.ChatSessionID.Valid && task.ChatSessionID == source.ChatSessionID
+ }
+ return false
+}
+
+func claimResponseAgentIdentityMatches(resp AgentTaskResponse) bool {
+ return resp.AgentID != "" && resp.Agent != nil && resp.Agent.ID == resp.AgentID
+}
+
// buildClaimedTaskResponse assembles the full daemon claim payload for a
// single already-claimed task and computes the exact comment ids embedded in
// it (deliveredCommentIDs). Shared by the per-runtime handler
@@ -1884,104 +1901,145 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
if composioMCPEnabled {
resp.ConnectedApps = parseRuntimeConnectedAppsForClaim(task.RuntimeConnectedApps, task.ID)
}
- if agent, err := h.Queries.GetAgent(r.Context(), task.AgentID); err == nil {
- useSkillRefs := requestHasClientCapability(r, protocol.DaemonCapabilitySkillBundlesV1)
- var customEnv map[string]string
- if agent.CustomEnv != nil {
- if err := json.Unmarshal(agent.CustomEnv, &customEnv); err != nil {
- slog.Warn("failed to unmarshal agent custom_env", "agent_id", uuidToString(agent.ID), "error", err)
- }
+ agent, err := h.Queries.GetAgent(r.Context(), task.AgentID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ // The current schema cascades agent deletion to task rows, so a
+ // durable orphan task cannot normally reach this branch. It remains a
+ // fail-closed guard for a deletion racing response assembly or for
+ // externally corrupted data; settlement may report that the task row
+ // already disappeared, but no claim payload is dispatched either way.
+ slog.Error("daemon claim: task agent no longer exists; refusing dispatch",
+ "task_id", uuidToString(task.ID), "agent_id", uuidToString(task.AgentID))
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, h.failClaimedTaskBeforeLaunch(
+ r.Context(), task,
+ "Task identity is invalid: the assigned agent no longer exists.",
+ taskfailure.ReasonInvalidTaskIdentity,
+ "error_invalid_task_identity", http.StatusConflict, "task agent no longer exists",
+ )
}
- var customArgs []string
- if agent.CustomArgs != nil {
- if err := json.Unmarshal(agent.CustomArgs, &customArgs); err != nil {
- slog.Warn("failed to unmarshal agent custom_args", "agent_id", uuidToString(agent.ID), "error", err)
- }
+ slog.Error("daemon claim: load task agent failed; requeueing claim",
+ "task_id", uuidToString(task.ID), "agent_id", uuidToString(task.AgentID), "error", err)
+ if _, requeueErr := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), *task); requeueErr != nil {
+ slog.Error("daemon claim: requeue after agent load failure failed; stale reclaim will recover it",
+ "task_id", uuidToString(task.ID), "error", requeueErr)
}
- var mcpConfig json.RawMessage
- if agent.McpConfig != nil {
- mcpConfig = json.RawMessage(agent.McpConfig)
- }
- // Fold in the workspace MCP servers this agent has been explicitly
- // given (GH #6062). Only bound AND enabled servers are read, so a
- // workspace library entry nobody added reaches nothing. Read on every
- // claim, exactly like the agent column, so an admin's edit or a toggle
- // lands on the agent's next task with nothing to restart. Errors —
- // including a failed read — leave the agent config untouched: a broken
- // shared entry must never take away servers the agent runs with today.
- if bound, err := h.Queries.ListEnabledAgentMcpServers(r.Context(), agent.ID); err != nil {
- slog.Warn("daemon claim: load agent mcp servers failed; using agent mcp_config",
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
+ outcome: "error_load_task_agent",
+ status: http.StatusInternalServerError,
+ message: "failed to load task agent",
+ }
+ }
+ useSkillRefs := requestHasClientCapability(r, protocol.DaemonCapabilitySkillBundlesV1)
+ var customEnv map[string]string
+ if agent.CustomEnv != nil {
+ if err := json.Unmarshal(agent.CustomEnv, &customEnv); err != nil {
+ slog.Warn("failed to unmarshal agent custom_env", "agent_id", uuidToString(agent.ID), "error", err)
+ }
+ }
+ var customArgs []string
+ if agent.CustomArgs != nil {
+ if err := json.Unmarshal(agent.CustomArgs, &customArgs); err != nil {
+ slog.Warn("failed to unmarshal agent custom_args", "agent_id", uuidToString(agent.ID), "error", err)
+ }
+ }
+ var mcpConfig json.RawMessage
+ if agent.McpConfig != nil {
+ mcpConfig = json.RawMessage(agent.McpConfig)
+ }
+ // Fold in the workspace MCP servers this agent has been explicitly
+ // given (GH #6062). Only bound AND enabled servers are read, so a
+ // workspace library entry nobody added reaches nothing. Read on every
+ // claim, exactly like the agent column, so an admin's edit or a toggle
+ // lands on the agent's next task with nothing to restart. Errors —
+ // including a failed read — leave the agent config untouched: a broken
+ // shared entry must never take away servers the agent runs with today.
+ if bound, err := h.Queries.ListEnabledAgentMcpServers(r.Context(), agent.ID); err != nil {
+ slog.Warn("daemon claim: load agent mcp servers failed; using agent mcp_config",
+ "task_id", uuidToString(task.ID), "agent_id", uuidToString(agent.ID), "error", err)
+ } else if len(bound) > 0 {
+ bindings := make([]WorkspaceMcpBinding, 0, len(bound))
+ for _, server := range bound {
+ bindings = append(bindings, WorkspaceMcpBinding{Name: server.Name, Config: json.RawMessage(server.Config)})
+ }
+ if resolved, err := ResolveAgentMcpConfig(bindings, mcpConfig); err != nil {
+ slog.Warn("daemon claim: resolve agent mcp servers failed; falling back to agent mcp_config",
"task_id", uuidToString(task.ID), "agent_id", uuidToString(agent.ID), "error", err)
- } else if len(bound) > 0 {
- bindings := make([]WorkspaceMcpBinding, 0, len(bound))
- for _, server := range bound {
- bindings = append(bindings, WorkspaceMcpBinding{Name: server.Name, Config: json.RawMessage(server.Config)})
- }
- if resolved, err := ResolveAgentMcpConfig(bindings, mcpConfig); err != nil {
- slog.Warn("daemon claim: resolve agent mcp servers failed; falling back to agent mcp_config",
- "task_id", uuidToString(task.ID), "agent_id", uuidToString(agent.ID), "error", err)
- } else {
- mcpConfig = resolved
- }
- }
- // Layer the per-task overlay (set at enqueue from the initiator
- // user's active integrations — currently Composio) on top of the
- // agent's saved mcp_config. Overlay wins on server-name collisions
- // because it carries the live user-scoped session URL. Errors are
- // logged but never fail the claim: a broken overlay must not prevent
- // the agent from running with its base config.
- if composioMCPEnabled && len(task.RuntimeMcpOverlay) > 0 {
- if merged, err := mergeMCPOverlay(mcpConfig, json.RawMessage(task.RuntimeMcpOverlay)); err != nil {
- slog.Warn("daemon claim: merge runtime_mcp_overlay failed; falling back to agent mcp_config", "task_id", uuidToString(task.ID), "error", err)
- } else {
- mcpConfig = merged
- }
- }
- // runtime_config is stored as JSONB and may legitimately be the
- // empty object `{}` for agents that haven't opted into any
- // provider-specific tuning. Forward only non-empty payloads so the
- // daemon's per-provider decoders treat absent-or-empty identically.
- var runtimeConfig json.RawMessage
- if rc := bytes.TrimSpace(agent.RuntimeConfig); len(rc) > 0 && !bytes.Equal(rc, []byte("{}")) && !bytes.Equal(rc, []byte("null")) {
- runtimeConfig = json.RawMessage(agent.RuntimeConfig)
- }
- resp.Agent = &TaskAgentData{
- ID: uuidToString(agent.ID),
- Name: agent.Name,
- Instructions: agent.Instructions,
- CustomEnv: customEnv,
- CustomArgs: customArgs,
- McpConfig: mcpConfig,
- Model: agent.Model.String,
- ThinkingLevel: agent.ThinkingLevel.String,
- ServiceTier: agent.ServiceTier.String,
- RuntimeConfig: runtimeConfig,
- DisabledRuntimeSkills: disabledRuntimeSkillsFor(agent.DisabledRuntimeSkills, runtimeID, runtime.Provider),
- }
- // System agents carry a product-owned instruction layer that ships with
- // this binary instead of being copied into their row at creation. That
- // is what makes it hot-updatable: editing the embedded file and
- // deploying reaches every existing workspace on its next task, with no
- // migration and no client upgrade. agent.Instructions holds only the
- // workspace's own notes, so a release can never overwrite them.
- //
- // Composing here covers every task kind, because this is the single
- // place a claimed task's agent payload is assembled.
- if agent.SystemKey.String == service.MikaSystemKey {
- resp.Agent.Instructions = service.ComposeMikaInstructions(agent.Name, agent.Instructions)
- }
- if useSkillRefs {
- _, skillRefs := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)
- agentSkillCount = len(skillRefs)
- resp.Agent.SkillRefs = skillRefs
} else {
- skills := h.TaskService.LoadAgentSkills(r.Context(), task.AgentID)
- agentSkillCount = len(skills)
- builtinSkills := h.TaskService.BuiltinSkills()
- builtinSkillCount = len(builtinSkills)
- skills = append(skills, builtinSkills...)
- resp.Agent.Skills = skills
- }
+ mcpConfig = resolved
+ }
+ }
+ // Layer the per-task overlay (set at enqueue from the initiator
+ // user's active integrations — currently Composio) on top of the
+ // agent's saved mcp_config. Overlay wins on server-name collisions
+ // because it carries the live user-scoped session URL. Errors are
+ // logged but never fail the claim: a broken overlay must not prevent
+ // the agent from running with its base config.
+ if composioMCPEnabled && len(task.RuntimeMcpOverlay) > 0 {
+ if merged, err := mergeMCPOverlay(mcpConfig, json.RawMessage(task.RuntimeMcpOverlay)); err != nil {
+ slog.Warn("daemon claim: merge runtime_mcp_overlay failed; falling back to agent mcp_config", "task_id", uuidToString(task.ID), "error", err)
+ } else {
+ mcpConfig = merged
+ }
+ }
+ // runtime_config is stored as JSONB and may legitimately be the
+ // empty object `{}` for agents that haven't opted into any
+ // provider-specific tuning. Forward only non-empty payloads so the
+ // daemon's per-provider decoders treat absent-or-empty identically.
+ var runtimeConfig json.RawMessage
+ if rc := bytes.TrimSpace(agent.RuntimeConfig); len(rc) > 0 && !bytes.Equal(rc, []byte("{}")) && !bytes.Equal(rc, []byte("null")) {
+ runtimeConfig = json.RawMessage(agent.RuntimeConfig)
+ }
+ resp.Agent = &TaskAgentData{
+ ID: uuidToString(agent.ID),
+ Name: agent.Name,
+ Instructions: agent.Instructions,
+ CustomEnv: customEnv,
+ CustomArgs: customArgs,
+ McpConfig: mcpConfig,
+ Model: agent.Model.String,
+ ThinkingLevel: agent.ThinkingLevel.String,
+ ServiceTier: agent.ServiceTier.String,
+ RuntimeConfig: runtimeConfig,
+ DisabledRuntimeSkills: disabledRuntimeSkillsFor(agent.DisabledRuntimeSkills, runtimeID, runtime.Provider),
+ }
+ // System agents carry a product-owned instruction layer that ships with
+ // this binary instead of being copied into their row at creation. That
+ // is what makes it hot-updatable: editing the embedded file and
+ // deploying reaches every existing workspace on its next task, with no
+ // migration and no client upgrade. agent.Instructions holds only the
+ // workspace's own notes, so a release can never overwrite them.
+ //
+ // Composing here covers every task kind, because this is the single
+ // place a claimed task's agent payload is assembled.
+ if agent.SystemKey.String == service.MikaSystemKey {
+ resp.Agent.Instructions = service.ComposeMikaInstructions(agent.Name, agent.Instructions)
+ }
+ if useSkillRefs {
+ _, skillRefs := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)
+ agentSkillCount = len(skillRefs)
+ resp.Agent.SkillRefs = skillRefs
+ } else {
+ skills := h.TaskService.LoadAgentSkills(r.Context(), task.AgentID)
+ agentSkillCount = len(skills)
+ builtinSkills := h.TaskService.BuiltinSkills()
+ builtinSkillCount = len(builtinSkills)
+ skills = append(skills, builtinSkills...)
+ resp.Agent.Skills = skills
+ }
+ if !claimResponseAgentIdentityMatches(resp) {
+ responseAgentID := ""
+ if resp.Agent != nil {
+ responseAgentID = resp.Agent.ID
+ }
+ slog.Error("daemon claim: response agent identity mismatch; refusing dispatch",
+ "task_id", uuidToString(task.ID), "task_agent_id", resp.AgentID, "response_agent_id", responseAgentID)
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, h.failClaimedTaskBeforeLaunch(
+ r.Context(), task,
+ "Task identity is invalid: the task and response agent disagree.",
+ taskfailure.ReasonInvalidTaskIdentity,
+ "error_invalid_task_identity", http.StatusConflict, "task response agent identity mismatch",
+ )
}
// Resolve the runtime owner's profile description so the daemon can
@@ -2343,7 +2401,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
// directory. PriorWorkDir is offered regardless of runtime (a shared
// mount may still resolve it); only the per-cwd session is
// runtime-gated.
- if src, err := h.Queries.GetAgentTask(r.Context(), task.RerunOfTaskID); err == nil {
+ if src, err := h.Queries.GetAgentTask(r.Context(), task.RerunOfTaskID); err == nil && rerunSourceMatchesTaskScope(*task, src) {
if src.WorkDir.Valid {
resp.PriorWorkDir = src.WorkDir.String
}
@@ -2357,6 +2415,16 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
if src.SessionRolloutMissing {
resp.PriorSessionResumeUnavailable = true
}
+ } else if err == nil {
+ slog.Warn("daemon claim: rerun source belongs to another agent or scope; starting fresh",
+ "task_id", uuidToString(task.ID),
+ "task_agent_id", uuidToString(task.AgentID),
+ "task_issue_id", uuidToString(task.IssueID),
+ "source_task_id", uuidToString(src.ID),
+ "source_agent_id", uuidToString(src.AgentID),
+ "source_issue_id", uuidToString(src.IssueID),
+ )
+ resp.PriorSessionResumeUnavailable = true
}
} else if !task.ForceFreshSession {
// Non-rerun follow-up on the same issue: resume the most recent
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index ca73ebc83f..cacb2c2d90 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -2570,16 +2570,38 @@ func TestCompleteTask_AssignmentTriggered_DoesNotSuppressTrivialDoneOutput(t *te
}
}
+func TestClaimResponseAgentIdentityMatches(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ resp AgentTaskResponse
+ want bool
+ }{
+ {name: "matching", resp: AgentTaskResponse{AgentID: "agent-a", Agent: &TaskAgentData{ID: "agent-a"}}, want: true},
+ {name: "mismatched", resp: AgentTaskResponse{AgentID: "agent-a", Agent: &TaskAgentData{ID: "agent-b"}}},
+ {name: "missing top-level identity", resp: AgentTaskResponse{Agent: &TaskAgentData{ID: "agent-a"}}},
+ {name: "missing response agent", resp: AgentTaskResponse{AgentID: "agent-a"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := claimResponseAgentIdentityMatches(tc.resp); got != tc.want {
+ t.Fatalf("claimResponseAgentIdentityMatches() = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
type claimRuntimeGuardTask struct {
- PriorSessionID string `json:"prior_session_id"`
- PriorWorkDir string `json:"prior_work_dir"`
- ChatMessage string `json:"chat_message"`
- ThreadName string `json:"thread_name"`
- QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids"`
- QuickCreatePriority string `json:"quick_create_priority"`
- QuickCreateDueDate string `json:"quick_create_due_date"`
- ProjectID string `json:"project_id"`
- ProjectDescription string `json:"project_description"`
+ PriorSessionID string `json:"prior_session_id"`
+ PriorWorkDir string `json:"prior_work_dir"`
+ PriorSessionResumeUnavailable bool `json:"prior_session_resume_unavailable"`
+ ChatMessage string `json:"chat_message"`
+ ThreadName string `json:"thread_name"`
+ QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids"`
+ QuickCreatePriority string `json:"quick_create_priority"`
+ QuickCreateDueDate string `json:"quick_create_due_date"`
+ ProjectID string `json:"project_id"`
+ ProjectDescription string `json:"project_description"`
}
func claimTaskForRuntimeGuard(t *testing.T, runtimeID, daemonID string) *claimRuntimeGuardTask {
@@ -3003,6 +3025,37 @@ func TestClaimTask_ManualRetryReusesWorkdir(t *testing.T) {
t.Fatalf("PriorSessionID = %q, want empty (cross-runtime session cannot resolve)", task.PriorSessionID)
}
})
+
+ t.Run("different_agent_source_starts_fresh", func(t *testing.T) {
+ issueNum++
+ issueID := dbfx.Issue(t, "manual-retry-cross-agent fixture", testutil.Cols{
+ "status": "in_progress",
+ "number": issueNum,
+ })
+ otherAgentID := dbfx.Agent(t, "Rerun Source Other Agent", runtimeID, testutil.Cols{})
+ sourceID := dbfx.Task(t, otherAgentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "issue_id": issueID,
+ "status": "failed",
+ "session_id": "other-agent-session",
+ "work_dir": "/tmp/other-agent-workdir",
+ })
+ dbfx.Exec(t, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority,
+ rerun_of_task_id, force_fresh_session
+ )
+ VALUES ($1, $2, $3, 'queued', 0, $4, TRUE)
+ `, agentID, runtimeID, issueID, sourceID)
+
+ task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)
+ if task.PriorWorkDir != "" || task.PriorSessionID != "" {
+ t.Fatalf("cross-agent rerun inherited source pointers: session=%q workdir=%q", task.PriorSessionID, task.PriorWorkDir)
+ }
+ if !task.PriorSessionResumeUnavailable {
+ t.Fatal("cross-agent rerun must disclose that the requested source was not resumable")
+ }
+ })
}
func TestClaimTask_ChatPriorSessionRuntimeGuard(t *testing.T) {
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
index 9c0e4a9a2e..fbcddab48f 100644
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
@@ -47,7 +47,7 @@ multica repo checkout <url> --ref <branch-or-sha>
`runtime update` and `runtime delete` are writes. Starting a runtime update is limited to its owner or a workspace owner/admin; the original initiator may keep polling that specific in-flight request if their admin role changes. `runtime delete` removes a runtime registration; if active agents are still bound, it refuses unless the user explicitly passes `--cascade`, which unbinds those agents and cancels their queued/running tasks before deleting the runtime. Unbinding keeps the agents and everything they own — instructions, skills, chats, labels, channel installations, autopilots and task history — and only clears `agent.runtime_id`; an unbound agent cannot run until it is bound to a runtime again (`multica agent update <id> --runtime-id <runtime-id>`), and every trigger path refuses it with `agent_runtime_required`. `repo checkout` creates a dedicated branch in the task working directory. Most runtimes use a linked worktree; Linux and Windows Codex use task-local Git metadata so a task can stage and commit without making the shared `.repos` cache writable.
-`repo checkout` requires `MULTICA_DAEMON_PORT`; it is intended to run inside a daemon task. If absent, you are not in the normal agent checkout path. When a project `github_repo` resource has `resource_ref.ref`, `repo checkout <url>` uses that ref by default for the current task; an explicit `repo checkout <url> --ref <branch-or-sha>` overrides it.
+`repo checkout` requires both `MULTICA_DAEMON_PORT` and the injected task-scoped `MULTICA_TOKEN`; it is intended to run inside the active daemon task and from that task's workdir (or a descendant). The local daemon authenticates the token against its active-task registry, derives workspace/task/agent identity itself, and rejects a caller-supplied workdir outside that task. If either variable is absent, you are not in the normal agent checkout path. When a project `github_repo` resource has `resource_ref.ref`, `repo checkout <url>` uses that ref by default for the current task; an explicit `repo checkout <url> --ref <branch-or-sha>` overrides it.
## Task CLI boundary
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
index 2acf9219bb..aef3ae11a7 100644
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
@@ -5,8 +5,8 @@
- `runtime update` posts to `/api/runtimes/{runtime-id}/update`; with `--wait` it polls update status. Initiation enforces runtime-owner or workspace-owner/admin access through `canEditRuntime`; status polling additionally permits that request's immutable initiator so an in-flight poll survives an admin-role change (`server/internal/handler/runtime_update.go` and `runtime.go`).
- `runtime delete` deletes `/api/runtimes/{runtime-id}`; with `--cascade`, it first reads the `runtime_has_active_agents` conflict payload and posts those ids to `/api/runtimes/{runtime-id}/unbind-agents-and-delete` (the older `/archive-agents-and-delete` path still routes to the same handler for installed clients). Both delete paths run `unbindRuntimeForDelete` in `server/internal/handler/runtime.go`: user agents are unbound (`runtime_id = NULL`, MUL-5559), their task history is detached so deleting the runtime cannot cascade it away, active tasks are cancelled, and only `kind='system'` agents are hard-deleted.
- `server/cmd/multica/cmd_repo.go` registers `repo checkout <url> [--ref]`.
-- `repo checkout` requires `MULTICA_DAEMON_PORT`, sends `workspace_id`, `workdir`, `ref`, `agent_name`, `task_id`, and the daemon-managed optional `checkout_mode` to local daemon `/repo/checkout`, then prints the checked-out path.
-- `server/internal/daemon/health.go` resolves the checkout ref: request `ref` wins; otherwise it asks `server/internal/daemon/daemon.go` for the current task's project repo default ref. It forwards the validated isolated-checkout mode into `repocache.WorktreeParams`.
+- `repo checkout` requires `MULTICA_DAEMON_PORT` plus the injected task-scoped `MULTICA_TOKEN`. It sends the token as a localhost bearer credential along with `workspace_id`, `workdir`, `ref`, `agent_name`, `task_id`, and the daemon-managed optional `checkout_mode`, then prints the checked-out path.
+- `server/internal/daemon/daemon.go` registers each provider execution in an in-memory checkout registry keyed by its task token and removes it when execution ends. `server/internal/daemon/health.go` authenticates `/repo/checkout` against that registry, requires the requested workspace/task and canonical workdir to belong to the active task, and derives the branch's agent name from the registry instead of trusting the request. It then resolves the checkout ref: request `ref` wins; otherwise it asks `daemon.go` for the current task's project repo default ref, and forwards the validated isolated-checkout mode into `repocache.WorktreeParams`.
- `server/internal/daemon/daemon.go` injects `MULTICA_REPO_CHECKOUT_MODE=isolated` for Linux and Windows Codex tasks. Linux keeps the isolated checkout it already had; Windows Codex now uses the same layout to cover its native sandbox, where a linked worktree's external gitdir stays read-only and `git add` / `git commit` fail from inside the checkout (multica-ai/multica#6449). That failure only bites a Windows user who opted into `windows.sandbox` — `server/internal/daemon/execenv/codex_sandbox.go` defaults both Linux and Windows Codex to `danger-full-access` — but the checkout layout is chosen per platform, not per sandbox policy, so it does not depend on a task's resolved policy. `server/internal/daemon/repocache/cache.go` implements the mode as a local clone with task-local Git metadata and the real repository as `origin`; on Windows it clones with `--no-hardlinks` so the checkout's objects are private copies rather than NTFS links that share one file and security descriptor with the cache. Other runtimes keep the linked-worktree path.
- When the bare cache is a partial clone, that isolated checkout must have `remote.origin.promisor` / `partialclonefilter` restored before its first `checkout`: `git clone --local` neither inherits them nor errors on the missing objects it leaves behind, so the checkout would otherwise succeed with an empty working tree. The linked-worktree path shares the cache's own config and needs no such repair.
- `server/cmd/server/router.go` registers daemon APIs under `/api/daemon`, including workspace repos and task claim.
diff --git a/server/pkg/llm/outbound_contract_test.go b/server/pkg/llm/outbound_contract_test.go
index a1795b358d..2bbe8df74d 100644
--- a/server/pkg/llm/outbound_contract_test.go
+++ b/server/pkg/llm/outbound_contract_test.go
@@ -102,7 +102,7 @@ func TestUnconfiguredClientMakesZeroUpstreamRequests(t *testing.T) {
// passing while the real client dials OpenAI. So prove the counter can move
// — a configured client must reach the same transport.
transport := &countingHTTPClient{}
- configured := New(Config{APIKey: "test-key", BaseURL: "http://127.0.0.1:1", HTTPClient: transport, MaxRetries: -1})
+ configured := New(Config{APIKey: "test-key", BaseURL: "http://127.0.0.1:1", HTTPClient: transport, MaxRetries: retries(0)})
if _, err := configured.GenerateText(context.Background(), "", "system", "hi"); err == nil {
t.Fatal("expected the refusing transport to fail a configured client's call")
}
diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.go
index 2a3846e646..e24acc71c6 100644
--- a/server/pkg/taskfailure/failure.go
+++ b/server/pkg/taskfailure/failure.go
@@ -26,7 +26,7 @@
// queued_expired, runtime_offline, runtime_reconnect_timeout,
// runtime_recovery, timeout, iteration_limit, agent_blocked,
// api_invalid_request, skill_bundle_unavailable,
-// runtime_cli_timeout
+// runtime_cli_timeout, invalid_task_identity
//
// - 14 agent-side values (with `agent_error.` prefix) produced by
// Classify(rawError) when the agent process surfaced an error string.
@@ -131,6 +131,13 @@ const (
// taskRunFailureReason in daemon/daemon.go.
ReasonRuntimeCLITimeout Reason = "runtime_cli_timeout"
+ // ReasonInvalidTaskIdentity: the daemon refused a claimed task because
+ // the task row's authoritative agent_id was absent or disagreed with the
+ // nested agent payload. The agent process is never launched. This is
+ // deliberately non-retryable: retrying the same contradictory claim would
+ // only repeat an isolation failure.
+ ReasonInvalidTaskIdentity Reason = "invalid_task_identity"
+
// Agent process side: failure surfaced by the agent CLI / SDK as
// an error string. Classify(rawError) is responsible for picking
// the right sub-reason from the string. IsAgentError returns true
@@ -206,7 +213,7 @@ const (
ReasonAgentUnknown Reason = "agent_error.unknown"
)
-// allReasons is the canonical ordered list of the 24 reasons. Order is
+// allReasons is the canonical ordered list of the 25 reasons. Order is
// stable so callers (e.g. Prometheus collectors that pre-warm series via
// AllReasons) can build deterministic label sets across restarts.
//
@@ -227,6 +234,7 @@ var allReasons = []Reason{
ReasonAPIInvalidRequest,
ReasonSkillBundleUnavailable,
ReasonRuntimeCLITimeout,
+ ReasonInvalidTaskIdentity,
// Agent process side: provider errors.
ReasonAgentProviderAuthOrAccess,
diff --git a/server/pkg/taskfailure/failure_test.go b/server/pkg/taskfailure/failure_test.go
index ac9f619602..2a5f0eed0c 100644
--- a/server/pkg/taskfailure/failure_test.go
+++ b/server/pkg/taskfailure/failure_test.go
@@ -28,6 +28,8 @@ func TestReasonStringWireValues(t *testing.T) {
{ReasonAgentBlocked, "agent_blocked"},
{ReasonAPIInvalidRequest, "api_invalid_request"},
{ReasonSkillBundleUnavailable, "skill_bundle_unavailable"},
+ {ReasonRuntimeCLITimeout, "runtime_cli_timeout"},
+ {ReasonInvalidTaskIdentity, "invalid_task_identity"},
// Agent-side.
{ReasonAgentProviderAuthOrAccess, "agent_error.provider_auth_or_access"},
{ReasonAgentProviderQuotaLimit, "agent_error.provider_quota_limit"},
@@ -45,7 +47,7 @@ func TestReasonStringWireValues(t *testing.T) {
{ReasonAgentUnknown, "agent_error.unknown"},
}
- if got, want := len(cases), 23; got != want {
+ if got, want := len(cases), 25; got != want {
t.Fatalf("constant count = %d, want %d (canonical taxonomy size)", got, want)
}
@@ -74,6 +76,8 @@ func TestIsAgentError(t *testing.T) {
ReasonAgentBlocked,
ReasonAPIInvalidRequest,
ReasonSkillBundleUnavailable,
+ ReasonRuntimeCLITimeout,
+ ReasonInvalidTaskIdentity,
}
for _, r := range platformSide {
if r.IsAgentError() {
@@ -114,8 +118,8 @@ func TestAllReasonsContents(t *testing.T) {
t.Parallel()
got := AllReasons()
- if len(got) != 24 {
- t.Fatalf("AllReasons() returned %d entries, want 24", len(got))
+ if len(got) != 25 {
+ t.Fatalf("AllReasons() returned %d entries, want 25", len(got))
}
seen := make(map[Reason]bool, len(got))
@@ -132,8 +136,8 @@ func TestAllReasonsContents(t *testing.T) {
}
}
- if platformCount != 10 {
- t.Errorf("AllReasons(): platform-side count = %d, want 10", platformCount)
+ if platformCount != 11 {
+ t.Errorf("AllReasons(): platform-side count = %d, want 11", platformCount)
}
if agentCount != 14 {
t.Errorf("AllReasons(): agent-side count = %d, want 14", agentCount)
@@ -148,7 +152,7 @@ func TestAllReasonsContents(t *testing.T) {
ReasonRuntimeRecovery,
ReasonTimeout, ReasonIterationLimit, ReasonAgentBlocked,
ReasonAPIInvalidRequest, ReasonSkillBundleUnavailable,
- ReasonRuntimeCLITimeout,
+ ReasonRuntimeCLITimeout, ReasonInvalidTaskIdentity,
ReasonAgentProviderAuthOrAccess, ReasonAgentProviderQuotaLimit,
ReasonAgentProviderCapacityOrRateLimit, ReasonAgentProviderServerError,
ReasonAgentProviderNetwork, ReasonAgentProcessFailure,