Skip to content

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

Go

MUL-6547 fix(daemon): resolve claim project context once, workspace-scoped (#7405)

Bohan Jiangfa797d0063b7
diff --git a/server/internal/handler/claim_project_context_test.go b/server/internal/handler/claim_project_context_test.go
new file mode 100644
index 0000000000..a0babd4cee
--- /dev/null
+++ b/server/internal/handler/claim_project_context_test.go
@@ -0,0 +1,527 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// The claim path resolves project context from a SOFT reference: issue.project_id,
+// chat_session.project_id and the quick-create context JSONB are all plain
+// columns with no foreign key behind them (see the repo's no-FK rule). These
+// tests pin the tenant boundary that resolveClaimProjectContext is responsible
+// for, using the only states that can actually produce a cross-tenant read:
+// a dangling reference to a project in another workspace, and a project_resource
+// row whose own workspace_id disagrees with its project's.
+//
+// Both were reachable before MUL-6547: the issue and quick-create branches read
+// the project with GetProject (no workspace predicate) and every branch listed
+// resources by project_id alone.
+
+// foreignWorkspaceWithProject builds a complete project in a DIFFERENT workspace
+// and returns (workspaceID, projectID). The caller points a same-workspace task
+// at projectID to simulate the corrupt reference.
+func foreignWorkspaceWithProject(t *testing.T, slug, prefix string) (string, string) {
+ t.Helper()
+
+ foreignWorkspaceID := dbfx.Insert(t, "workspace", testutil.Cols{
+ "name": "Foreign " + slug,
+ "slug": slug,
+ "description": "",
+ "issue_prefix": prefix,
+ })
+ foreignProjectID := dbfx.Project(t, foreignProjectTitle, testutil.Cols{
+ "workspace_id": foreignWorkspaceID,
+ "description": foreignProjectDescription,
+ })
+ dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": foreignProjectID,
+ "workspace_id": foreignWorkspaceID,
+ "resource_type": "github_repo",
+ "resource_ref": `{"url":"` + foreignRepoURL + `"}`,
+ "position": 0,
+ })
+ dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": foreignProjectID,
+ "workspace_id": foreignWorkspaceID,
+ "resource_type": "local_directory",
+ "resource_ref": `{"daemon_id":"foreign-daemon","local_path":"` + foreignLocalPath + `","execution_mode":"in_place"}`,
+ "position": 1,
+ })
+ return foreignWorkspaceID, foreignProjectID
+}
+
+const (
+ foreignProjectTitle = "Foreign project must not leak"
+ foreignProjectDescription = "Foreign project instructions must not leak"
+ foreignRepoURL = "https://github.com/example/foreign-tenant-repo"
+ foreignLocalPath = "/srv/foreign-tenant-project"
+ localFallbackRepoURL = "https://github.com/example/local-workspace-fallback"
+)
+
+// assertNoForeignContext fails when any part of the foreign tenant's project
+// reached the claim response, on any field the daemon forwards to the agent.
+func assertNoForeignContext(t *testing.T, body string, extra ...string) {
+ t.Helper()
+ for _, leaked := range append([]string{
+ foreignProjectTitle,
+ foreignProjectDescription,
+ foreignRepoURL,
+ foreignLocalPath,
+ }, extra...) {
+ if leaked == "" {
+ continue
+ }
+ if strings.Contains(body, leaked) {
+ t.Errorf("claim response leaked foreign tenant context %q: %s", leaked, body)
+ }
+ }
+}
+
+type claimProjectFields struct {
+ WorkspaceID string `json:"workspace_id"`
+ Repos []RepoData `json:"repos"`
+ ProjectID string `json:"project_id"`
+ ProjectTitle string `json:"project_title"`
+ ProjectDescription string `json:"project_description"`
+ ProjectResources []ProjectResourceData `json:"project_resources"`
+}
+
+// An issue whose project_id points at another workspace's project must degrade
+// to workspace context. Before MUL-6547 the issue branch used GetProject, which
+// has no workspace predicate, so the foreign project's title, description,
+// repository URL and local path were all serialized into the claim.
+func TestClaimTask_IssueProjectInForeignWorkspace_DegradesToWorkspaceRepos(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ setHandlerTestWorkspaceRepos(t, []map[string]string{
+ {"url": localFallbackRepoURL, "description": "local"},
+ })
+ _, foreignProjectID := foreignWorkspaceWithProject(t, "foreign-issue-project-ws", "FIP")
+
+ var agentID, runtimeID string
+ dbfx.QueryRow(t,
+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&agentID, &runtimeID)
+
+ issueID := dbfx.Issue(t, "issue pointing at a foreign project", testutil.Cols{
+ "project_id": foreignProjectID,
+ "priority": "medium",
+ "number": 88101,
+ })
+ dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "issue_id": issueID,
+ })
+
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,
+ testWorkspaceID, "test-claim-foreign-issue-project")
+ req = withURLParam(req, "runtimeId", runtimeID)
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
+
+ var resp struct {
+ Task *claimProjectFields `json:"task"`
+ }
+ w.JSON(&resp)
+ if resp.Task == nil {
+ t.Fatal("expected task in response")
+ }
+ assertNoForeignContext(t, w.Text(), foreignProjectID)
+
+ if resp.Task.ProjectID != "" {
+ t.Errorf("project_id = %q, want empty for an out-of-workspace project reference", resp.Task.ProjectID)
+ }
+ if len(resp.Task.ProjectResources) != 0 {
+ t.Errorf("project_resources = %+v, want none", resp.Task.ProjectResources)
+ }
+ if len(resp.Task.Repos) != 1 || resp.Task.Repos[0].URL != localFallbackRepoURL {
+ t.Fatalf("repos = %+v, want only the local workspace fallback", resp.Task.Repos)
+ }
+}
+
+// The quick-create branch resolves its project from the task context JSONB
+// rather than an issue row, and used the same unscoped GetProject. It needs its
+// own assertion: a requester who edits the stored project_id must not be able to
+// pull another tenant's resources into the claim.
+func TestClaimTask_QuickCreateProjectInForeignWorkspace_DegradesToWorkspaceRepos(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ setHandlerTestWorkspaceRepos(t, []map[string]string{
+ {"url": localFallbackRepoURL, "description": "local"},
+ })
+ _, foreignProjectID := foreignWorkspaceWithProject(t, "foreign-qc-project-ws", "FQP")
+
+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)
+ quickContext, _ := json.Marshal(map[string]any{
+ "type": "quick_create",
+ "prompt": "create a follow-up issue",
+ "requester_id": testUserID,
+ "workspace_id": testWorkspaceID,
+ "project_id": foreignProjectID,
+ })
+ dbfx.Exec(t, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, context)
+ VALUES ($1, $2, 'queued', 2, $3)
+ `, agentID, runtimeID, quickContext)
+
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,
+ testWorkspaceID, daemonID)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
+
+ var resp struct {
+ Task *claimProjectFields `json:"task"`
+ }
+ w.JSON(&resp)
+ if resp.Task == nil {
+ t.Fatal("expected task in response")
+ }
+ assertNoForeignContext(t, w.Text(), foreignProjectID)
+
+ if resp.Task.ProjectID != "" {
+ t.Errorf("quick-create project_id = %q, want empty for an out-of-workspace project", resp.Task.ProjectID)
+ }
+ if len(resp.Task.ProjectResources) != 0 {
+ t.Errorf("quick-create project_resources = %+v, want none", resp.Task.ProjectResources)
+ }
+ if len(resp.Task.Repos) != 1 || resp.Task.Repos[0].URL != localFallbackRepoURL {
+ t.Fatalf("quick-create repos = %+v, want only the local workspace fallback", resp.Task.Repos)
+ }
+}
+
+// A project_resource row carries its own workspace_id, so a resource can
+// disagree with the project it hangs off. Listing by project_id alone — which
+// every claim branch did before MUL-6547 — serialized that row anyway. The
+// in-workspace resource on the same project must still come through, proving the
+// new predicate filters rather than just emptying the list.
+func TestClaimTask_ProjectResourceFromForeignWorkspace_IsFilteredOut(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ foreignWorkspaceID, _ := foreignWorkspaceWithProject(t, "foreign-resource-ws", "FRW")
+
+ const localRepoURL = "https://github.com/example/local-project-repo"
+ projectID := dbfx.Project(t, "Project with a mismatched resource row")
+ dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": projectID,
+ "workspace_id": testWorkspaceID,
+ "resource_type": "github_repo",
+ "resource_ref": `{"url":"` + localRepoURL + `"}`,
+ "position": 0,
+ })
+ // Same project, foreign workspace_id: only reachable through corrupt data,
+ // which is exactly the case the predicate exists for.
+ dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": projectID,
+ "workspace_id": foreignWorkspaceID,
+ "resource_type": "github_repo",
+ "resource_ref": `{"url":"` + foreignRepoURL + `"}`,
+ "position": 1,
+ })
+ dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": projectID,
+ "workspace_id": foreignWorkspaceID,
+ "resource_type": "local_directory",
+ "resource_ref": `{"daemon_id":"foreign-daemon","local_path":"` + foreignLocalPath + `","execution_mode":"in_place"}`,
+ "position": 2,
+ })
+
+ var agentID, runtimeID string
+ dbfx.QueryRow(t,
+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&agentID, &runtimeID)
+
+ issueID := dbfx.Issue(t, "issue with a mismatched project resource", testutil.Cols{
+ "project_id": projectID,
+ "priority": "medium",
+ "number": 88102,
+ })
+ dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "issue_id": issueID,
+ })
+
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,
+ testWorkspaceID, "test-claim-foreign-resource")
+ req = withURLParam(req, "runtimeId", runtimeID)
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
+
+ var resp struct {
+ Task *claimProjectFields `json:"task"`
+ }
+ w.JSON(&resp)
+ if resp.Task == nil {
+ t.Fatal("expected task in response")
+ }
+ assertNoForeignContext(t, w.Text())
+
+ if resp.Task.ProjectID != projectID {
+ t.Errorf("project_id = %q, want %q", resp.Task.ProjectID, projectID)
+ }
+ if len(resp.Task.ProjectResources) != 1 {
+ t.Fatalf("project_resources count = %d, want only the in-workspace row: %+v",
+ len(resp.Task.ProjectResources), resp.Task.ProjectResources)
+ }
+ if len(resp.Task.Repos) != 1 || resp.Task.Repos[0].URL != localRepoURL {
+ t.Fatalf("repos = %+v, want only the in-workspace project repo", resp.Task.Repos)
+ }
+}
+
+// A run_only autopilot owns its task's workspace. taskToResponse seeds
+// resp.WorkspaceID with the RUNTIME's workspace, and the branch used to widen it
+// only `if resp.WorkspaceID == ""` — a condition that never held, so the
+// isolation check compared the runtime workspace against itself and a
+// cross-workspace autopilot_run_id was dispatched instead of rejected.
+func TestClaimTask_AutopilotRunOnlyForeignWorkspace_CancelsTask(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ var localAgentID, localRuntimeID string
+ dbfx.QueryRow(t,
+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&localAgentID, &localRuntimeID)
+
+ foreignWorkspaceID, foreignProjectID := foreignWorkspaceWithProject(t, "foreign-autopilot-ws", "FAW")
+
+ const foreignAutopilotTitle = "Foreign autopilot must not leak"
+ foreignAutopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{
+ "workspace_id": foreignWorkspaceID,
+ "project_id": foreignProjectID,
+ "title": foreignAutopilotTitle,
+ "assignee_id": localAgentID,
+ "execution_mode": "run_only",
+ "created_by_type": "member",
+ "created_by_id": testUserID,
+ })
+ foreignRunID := dbfx.Insert(t, "autopilot_run", testutil.Cols{
+ "autopilot_id": foreignAutopilotID,
+ "source": "manual",
+ "status": "running",
+ })
+ taskID := dbfx.Task(t, localAgentID, testutil.Cols{
+ "runtime_id": localRuntimeID,
+ "issue_id": nil,
+ "autopilot_run_id": foreignRunID,
+ })
+
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+localRuntimeID+"/claim", nil,
+ testWorkspaceID, "test-claim-foreign-autopilot")
+ req = withURLParam(req, "runtimeId", localRuntimeID)
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusInternalServerError)
+ if !strings.Contains(w.Text(), "task workspace isolation check failed") {
+ t.Fatalf("claim error = %q, want the workspace isolation failure", w.Text())
+ }
+ assertNoForeignContext(t, w.Text(), foreignProjectID)
+ if strings.Contains(w.Text(), foreignAutopilotTitle) {
+ t.Errorf("claim error leaked the foreign autopilot title: %s", w.Text())
+ }
+
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)
+ if status != "cancelled" {
+ t.Fatalf("cross-workspace autopilot task status = %q, want cancelled", status)
+ }
+}
+
+// failQueryDBTX delegates every query to the real pool except the ones whose
+// SQL contains failOn, which fail with a transient-looking error. db.Queries is
+// built on the DBTX interface, so this is the seam that lets a single source
+// read fail while the rest of the claim proceeds normally — the shape of a real
+// DB blip, which a globally broken pool cannot reproduce (it trips the earlier
+// agent-load guard instead).
+type failQueryDBTX struct {
+ db.DBTX
+ failOn string
+ err error
+}
+
+type errRow struct{ err error }
+
+func (r errRow) Scan(...any) error { return r.err }
+
+func (f failQueryDBTX) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ if strings.Contains(sql, f.failOn) {
+ return errRow{err: f.err}
+ }
+ return f.DBTX.QueryRow(ctx, sql, args...)
+}
+
+func (f failQueryDBTX) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
+ if strings.Contains(sql, f.failOn) {
+ return nil, f.err
+ }
+ return f.DBTX.Query(ctx, sql, args...)
+}
+
+// A claim resolves its SOURCE row — issue, chat session, autopilot_run,
+// autopilot — before anything else. Those reads used to be written as
+// `if x, err := ...; err == nil {`, with no else: a failed read silently
+// skipped the whole branch. taskToResponse has already seeded resp.WorkspaceID
+// with the RUNTIME's workspace by then, so the skipped claim sailed through the
+// builder's backstop isolation check (which compared that seed against itself)
+// and dispatched an agent with no issue, no chat input, or no autopilot
+// instructions at all.
+//
+// A transient read failure must instead produce NO claim payload and preserve
+// the task for the stale-dispatched reclaim — cancelling would destroy a valid
+// task over a momentary DB error.
+func TestBuildClaimedTaskResponse_SourceLoadFailure_PreservesTaskAndEmitsNoContext(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ var agentID, runtimeID string
+ dbfx.QueryRow(t,
+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&agentID, &runtimeID)
+
+ projectID := dbfx.Project(t, "Source load failure project")
+ dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": projectID,
+ "workspace_id": testWorkspaceID,
+ "resource_type": "github_repo",
+ "resource_ref": `{"url":"https://github.com/example/must-not-appear"}`,
+ "position": 0,
+ })
+ issueID := dbfx.Issue(t, "source load failure issue", testutil.Cols{
+ "project_id": projectID,
+ "priority": "medium",
+ "number": 88201,
+ })
+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{"project_id": projectID})
+
+ for _, tc := range []struct {
+ name string
+ failOn string
+ cols testutil.Cols
+ }{
+ {
+ name: "issue",
+ failOn: "FROM issue\nWHERE id = $1",
+ cols: testutil.Cols{"runtime_id": runtimeID, "issue_id": issueID},
+ },
+ {
+ name: "chat session",
+ failOn: "FROM chat_session\nWHERE id = $1",
+ cols: testutil.Cols{"runtime_id": runtimeID, "issue_id": nil, "chat_session_id": chatSessionID},
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ taskID := dbfx.Task(t, agentID, tc.cols)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'dispatched' WHERE id = $1`, taskID)
+
+ task := db.AgentTaskQueue{
+ ID: parseUUID(taskID),
+ AgentID: parseUUID(agentID),
+ RuntimeID: parseUUID(runtimeID),
+ Status: "dispatched",
+ }
+ if issueRef, ok := tc.cols["issue_id"].(string); ok {
+ task.IssueID = parseUUID(issueRef)
+ }
+ if chatRef, ok := tc.cols["chat_session_id"].(string); ok {
+ task.ChatSessionID = parseUUID(chatRef)
+ }
+
+ brokenHandler := *testHandler
+ brokenHandler.Queries = db.New(failQueryDBTX{
+ DBTX: testPool,
+ failOn: tc.failOn,
+ err: errors.New("simulated transient read failure"),
+ })
+
+ runtime := db.AgentRuntime{
+ ID: parseUUID(runtimeID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ }
+ req := httptest.NewRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
+
+ resp, _, _, _, failure := brokenHandler.buildClaimedTaskResponse(
+ req, &task, runtime, runtimeID, testWorkspaceID)
+
+ if failure == nil {
+ t.Fatal("expected the claim to be rejected when its source row cannot be read")
+ }
+ if failure.outcome != "error_source_load" {
+ t.Errorf("outcome = %q, want error_source_load", failure.outcome)
+ }
+ if failure.status != http.StatusInternalServerError {
+ t.Errorf("status = %d, want 500", failure.status)
+ }
+
+ // No context may be assembled from a source the handler could not read.
+ if resp.ThreadName != "" {
+ t.Errorf("thread_name = %q, want empty on a failed source read", resp.ThreadName)
+ }
+ if resp.ProjectID != "" || len(resp.ProjectResources) != 0 || len(resp.Repos) != 0 {
+ t.Errorf("project context leaked into a failed claim: project_id=%q resources=%d repos=%d",
+ resp.ProjectID, len(resp.ProjectResources), len(resp.Repos))
+ }
+
+ // A transient failure preserves the task for the reclaim path.
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)
+ if status != "dispatched" {
+ t.Errorf("task status = %q, want it preserved as dispatched for reclaim", status)
+ }
+ })
+ }
+}
+
+// The other half of the split: a source row that is GONE cannot be retried into
+// existence, so it settles terminally instead of spinning in the reclaim loop.
+// Legacy FKs keep this state from arising today (agent_task_queue.issue_id ON
+// DELETE CASCADE and friends), so the branch is exercised directly rather than
+// through a claim.
+func TestRejectClaimSourceLoad_MissingRow_CancelsTask(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ var agentID, runtimeID string
+ dbfx.QueryRow(t,
+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&agentID, &runtimeID)
+
+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": nil})
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'dispatched' WHERE id = $1`, taskID)
+ task := db.AgentTaskQueue{ID: parseUUID(taskID), AgentID: parseUUID(agentID), Status: "dispatched"}
+
+ failure := testHandler.rejectClaimSourceLoad(
+ context.Background(), &task, pgx.ErrNoRows, "issue", uuidToString(task.IssueID))
+ if failure == nil {
+ t.Fatal("expected a failure for a missing source row")
+ }
+ if failure.outcome != "error_source_missing" {
+ t.Errorf("outcome = %q, want error_source_missing", failure.outcome)
+ }
+ if failure.message != "task is missing its issue" {
+ t.Errorf("message = %q, want it to name the missing source", failure.message)
+ }
+
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)
+ if status != "cancelled" {
+ t.Errorf("task status = %q, want cancelled for an unrecoverable source reference", status)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index f6a3ff8129..370955153f 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1789,6 +1789,94 @@ type claimBuildFailure struct {
message string
}
+// rejectClaimSourceLoad settles a claim whose SOURCE row — the issue, chat
+// session, autopilot_run or autopilot the task hangs off — could not be read.
+//
+// Every one of these branches used to swallow the error and fall through on
+// `err == nil`. That is a fail-open: taskToResponse has already seeded
+// resp.WorkspaceID with the RUNTIME's workspace, so a swallowed read ran on to
+// the builder's backstop isolation check, which compared that seeded value
+// against itself and passed. The agent was then dispatched with no issue, no
+// chat input, or no autopilot instructions at all — and, for chat, past the
+// empty-input guard that lives inside the success branch.
+//
+// The two failures settle differently:
+//
+// - The read FAILED (transient: DB blip, timeout, reset). Preserve the
+// just-dispatched task so the stale-dispatched reclaim redelivers it,
+// exactly as the chat-input load does (MUL-4351). This is the reachable
+// case and the one worth fixing.
+// - The row is GONE (ErrNoRows). Cancel: the task can never run, and
+// preserving it would spin in the reclaim loop forever. Legacy FKs
+// currently keep every one of these states from arising —
+// agent_task_queue.issue_id ON DELETE CASCADE,
+// agent_task_queue.chat_session_id ON DELETE SET NULL, and
+// autopilot_run.autopilot_id ON DELETE CASCADE feeding
+// agent_task_queue.autopilot_run_id ON DELETE SET NULL — so this branch is
+// defensive. It is what protects the claim path when those FKs are dropped
+// for the repo's no-FK rule.
+func (h *Handler) rejectClaimSourceLoad(ctx context.Context, task *db.AgentTaskQueue, err error, source, sourceID string) *claimBuildFailure {
+ if errors.Is(err, pgx.ErrNoRows) {
+ slog.Error("task claim: source row is missing; cancelling task",
+ "task_id", uuidToString(task.ID), "source", source, "source_id", sourceID)
+ if _, cerr := h.TaskService.CancelTask(ctx, task.ID); cerr != nil {
+ slog.Error("task claim: cancel after missing source row failed",
+ "task_id", uuidToString(task.ID), "error", cerr)
+ }
+ return &claimBuildFailure{
+ outcome: "error_source_missing",
+ status: http.StatusInternalServerError,
+ message: fmt.Sprintf("task is missing its %s", source),
+ }
+ }
+ slog.Error("task claim: source load failed; preserving task for redelivery",
+ "task_id", uuidToString(task.ID), "source", source, "source_id", sourceID, "error", err)
+ return &claimBuildFailure{
+ outcome: "error_source_load",
+ status: http.StatusInternalServerError,
+ message: fmt.Sprintf("failed to load task %s", source),
+ }
+}
+
+// rejectClaimOnWorkspaceMismatch enforces the claim's tenant boundary against
+// the workspace that OWNS the task's context (issue / chat session / autopilot
+// / quick-create), which is the only authority for MULTICA_WORKSPACE_ID in the
+// agent env. An empty value would make the CLI silently fall back to the
+// user-global config and talk to whatever workspace the user happened to last
+// configure; a value that doesn't match the runtime's workspace means upstream
+// routed a foreign-workspace task here. Both cases hard-fail AND cancel the
+// just-dispatched task so the queue / agent status don't sit stuck until the
+// stale-task sweeper fires minutes later.
+//
+// Every branch calls this as soon as it knows its authoritative workspace and
+// BEFORE it hydrates project context, so "prove ownership, then load" is a
+// property of the structure rather than a check each branch remembers to
+// repeat. Returns nil when the claim may proceed.
+func (h *Handler) rejectClaimOnWorkspaceMismatch(ctx context.Context, task *db.AgentTaskQueue, resolvedWorkspaceID, runtimeID, runtimeWorkspaceID string, hasQuickCreate bool) *claimBuildFailure {
+ if resolvedWorkspaceID != "" && resolvedWorkspaceID == runtimeWorkspaceID {
+ return nil
+ }
+ slog.Error("task claim: workspace isolation check failed, cancelling task",
+ "task_id", uuidToString(task.ID),
+ "runtime_id", runtimeID,
+ "runtime_workspace", runtimeWorkspaceID,
+ "resolved_workspace", resolvedWorkspaceID,
+ "has_issue", task.IssueID.Valid,
+ "has_chat", task.ChatSessionID.Valid,
+ "has_autopilot_run", task.AutopilotRunID.Valid,
+ "has_quick_create", hasQuickCreate,
+ )
+ if _, cerr := h.TaskService.CancelTask(ctx, task.ID); cerr != nil {
+ slog.Error("task claim: cancel after workspace check failed",
+ "task_id", uuidToString(task.ID), "error", cerr)
+ }
+ return &claimBuildFailure{
+ outcome: "error_workspace",
+ status: http.StatusInternalServerError,
+ message: "task workspace isolation check failed",
+ }
+}
+
// remoteMCPDaemonTokenForClaim prepares the short-lived credential the daemon
// uses to resolve write-only Remote MCP secrets for this task. The raw token is
// returned only in the claim response; its hash is committed atomically with
@@ -2132,154 +2220,120 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}
// Include workspace ID and repos so the daemon can set up worktrees.
- //
- // Repo precedence: project-bound github_repo resources override workspace
- // repos when present. Mixing both would just confuse the agent — if a
- // project explicitly attached its repos, those are the authoritative set
- // for issues inside that project. When the project has no github_repo
- // resources (or no project at all), we fall back to the workspace repos.
+ // Project context, repo precedence and the tenant/failure rules around both
+ // live in resolveClaimProjectContext, which every claim path shares.
if task.IssueID.Valid {
- if issue, err := h.Queries.GetIssue(r.Context(), task.IssueID); err == nil {
- resp.WorkspaceID = uuidToString(issue.WorkspaceID)
- resp.ThreadName = issue.Title
-
- // Squad-leader briefing injection: keyed off the task being a
- // leader-task (is_leader_task) carrying a squad_id — NOT off the
- // issue being assigned to a squad. The task flag is stamped at
- // enqueue time and is true for every ISSUE-BOUND path that routes
- // work to a squad leader: direct assign-to-squad, comment
- // @squad-mention (even when the issue itself is assigned to a
- // plain agent — the MUL-3724 case), sub-issue done callback,
- // autopilot squad-assignee, and retry-clone inheritance. The old
- // issue.AssigneeType=="squad" gate missed the comment-mention
- // path, so the leader booted with zero squad context and
- // degraded into doing the work itself instead of orchestrating.
- //
- // NOTE: quick-create tasks do NOT reach this block — they have a
- // NULL issue_id (so the enclosing `task.IssueID.Valid` is false)
- // and do NOT carry is_leader_task / squad_id columns. They route
- // their squad through the task CONTEXT JSON (QuickCreateContext.
- // SquadID) and get their briefing from the separate quick-create
- // branch further below (search `qc.SquadID`). Do not "unify" the
- // two by deleting that branch: it also sets resp.SquadID /
- // resp.SquadName so the new issue defaults to the squad assignee,
- // and there is no issue row to hang this column-based path on.
- //
- // We resolve the squad directly from task.SquadID rather than
- // reverse-looking-up "which squad is this agent the leader of",
- // which is ambiguous when one agent leads multiple squads. The
- // uuidToString(squad.LeaderID) == resp.Agent.ID re-check is kept
- // as a defensive gate: if the squad's leader was swapped after the
- // task was enqueued, we never feed a stale briefing to a
- // non-leader. It also doubles as the dangling-squad_id guard: a
- // squad hard-deleted after enqueue makes GetSquadInWorkspace
- // return no row (err != nil) — we skip injection silently, which
- // is exactly the same observable result as "condition not
- // matched". Claim still succeeds; no stale briefing is emitted.
- // (No FK on squad_id — see migration 127.) We append (not replace)
- // so per-agent instructions stay authoritative; the squad briefing
- // stacks on top as task-specific squad context.
- if task.IsLeaderTask {
- injected := false
- if resp.Agent != nil && task.SquadID.Valid {
- if squad, err := h.Queries.GetSquadInWorkspace(r.Context(), db.GetSquadInWorkspaceParams{
- ID: task.SquadID,
- WorkspaceID: issue.WorkspaceID,
- }); err == nil && uuidToString(squad.LeaderID) == resp.Agent.ID {
- // Parent-status authority is deliberately NARROWER than
- // briefing injection. Injection is keyed off is_leader_task
- // (see above) and therefore also fires on the MUL-3724 path,
- // where the issue belongs to a plain agent and this squad was
- // only @mentioned for help. Granting status ownership there
- // would let a guest squad push someone else's in-flight issue
- // to in_review, so we gate it on the issue actually being
- // assigned to this squad.
- ownsIssueStatus := issue.AssigneeType.Valid &&
- issue.AssigneeType.String == "squad" &&
- uuidToString(issue.AssigneeID) == uuidToString(squad.ID)
- briefing := buildSquadLeaderBriefing(r.Context(), h.Queries, squad, ownsIssueStatus)
- if strings.TrimSpace(resp.Agent.Instructions) == "" {
- resp.Agent.Instructions = briefing
- } else {
- resp.Agent.Instructions = resp.Agent.Instructions + "\n\n" + briefing
- }
- injected = true
- slog.Debug("injected squad leader briefing",
- "squad_id", uuidToString(squad.ID),
- "squad_name", squad.Name,
- "leader_agent_id", resp.Agent.ID,
- "owns_issue_status", ownsIssueStatus,
- )
+ issue, issueErr := h.Queries.GetIssue(r.Context(), task.IssueID)
+ if issueErr != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount,
+ h.rejectClaimSourceLoad(r.Context(), task, issueErr, "issue", uuidToString(task.IssueID))
+ }
+ resp.WorkspaceID = uuidToString(issue.WorkspaceID)
+ if failure := h.rejectClaimOnWorkspaceMismatch(r.Context(), task, resp.WorkspaceID, runtimeID, runtimeWorkspaceID, false); failure != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, failure
+ }
+ resp.ThreadName = issue.Title
+
+ // Squad-leader briefing injection: keyed off the task being a
+ // leader-task (is_leader_task) carrying a squad_id — NOT off the
+ // issue being assigned to a squad. The task flag is stamped at
+ // enqueue time and is true for every ISSUE-BOUND path that routes
+ // work to a squad leader: direct assign-to-squad, comment
+ // @squad-mention (even when the issue itself is assigned to a
+ // plain agent — the MUL-3724 case), sub-issue done callback,
+ // autopilot squad-assignee, and retry-clone inheritance. The old
+ // issue.AssigneeType=="squad" gate missed the comment-mention
+ // path, so the leader booted with zero squad context and
+ // degraded into doing the work itself instead of orchestrating.
+ //
+ // NOTE: quick-create tasks do NOT reach this block — they have a
+ // NULL issue_id (so the enclosing `task.IssueID.Valid` is false)
+ // and do NOT carry is_leader_task / squad_id columns. They route
+ // their squad through the task CONTEXT JSON (QuickCreateContext.
+ // SquadID) and get their briefing from the separate quick-create
+ // branch further below (search `qc.SquadID`). Do not "unify" the
+ // two by deleting that branch: it also sets resp.SquadID /
+ // resp.SquadName so the new issue defaults to the squad assignee,
+ // and there is no issue row to hang this column-based path on.
+ //
+ // We resolve the squad directly from task.SquadID rather than
+ // reverse-looking-up "which squad is this agent the leader of",
+ // which is ambiguous when one agent leads multiple squads. The
+ // uuidToString(squad.LeaderID) == resp.Agent.ID re-check is kept
+ // as a defensive gate: if the squad's leader was swapped after the
+ // task was enqueued, we never feed a stale briefing to a
+ // non-leader. It also doubles as the dangling-squad_id guard: a
+ // squad hard-deleted after enqueue makes GetSquadInWorkspace
+ // return no row (err != nil) — we skip injection silently, which
+ // is exactly the same observable result as "condition not
+ // matched". Claim still succeeds; no stale briefing is emitted.
+ // (No FK on squad_id — see migration 127.) We append (not replace)
+ // so per-agent instructions stay authoritative; the squad briefing
+ // stacks on top as task-specific squad context.
+ if task.IsLeaderTask {
+ injected := false
+ if resp.Agent != nil && task.SquadID.Valid {
+ if squad, err := h.Queries.GetSquadInWorkspace(r.Context(), db.GetSquadInWorkspaceParams{
+ ID: task.SquadID,
+ WorkspaceID: issue.WorkspaceID,
+ }); err == nil && uuidToString(squad.LeaderID) == resp.Agent.ID {
+ // Parent-status authority is deliberately NARROWER than
+ // briefing injection. Injection is keyed off is_leader_task
+ // (see above) and therefore also fires on the MUL-3724 path,
+ // where the issue belongs to a plain agent and this squad was
+ // only @mentioned for help. Granting status ownership there
+ // would let a guest squad push someone else's in-flight issue
+ // to in_review, so we gate it on the issue actually being
+ // assigned to this squad.
+ ownsIssueStatus := issue.AssigneeType.Valid &&
+ issue.AssigneeType.String == "squad" &&
+ uuidToString(issue.AssigneeID) == uuidToString(squad.ID)
+ briefing := buildSquadLeaderBriefing(r.Context(), h.Queries, squad, ownsIssueStatus)
+ if strings.TrimSpace(resp.Agent.Instructions) == "" {
+ resp.Agent.Instructions = briefing
+ } else {
+ resp.Agent.Instructions = resp.Agent.Instructions + "\n\n" + briefing
}
- }
- // Every skip above (NULL squad_id, squad hard-deleted, leader
- // swapped after enqueue) leaves a task the daemon must NOT run
- // as a leader: it has no roster to delegate to and no protocol
- // to follow. The daemon derives its leader role from this flag
- // (MUL-5811), so clearing it here is what keeps
- // "is_leader_task on the wire ⇔ briefing injected" true, and the
- // run degrades to an ordinary agent turn exactly as it did when
- // the daemon inferred the role from the briefing text itself.
- if !injected {
- resp.IsLeaderTask = false
- slog.Warn("squad leader briefing not injected; claim delivered as a non-leader task",
- "task_id", uuidToString(task.ID),
- "squad_id", uuidToString(task.SquadID),
- "agent_id", uuidToString(task.AgentID),
+ injected = true
+ slog.Debug("injected squad leader briefing",
+ "squad_id", uuidToString(squad.ID),
+ "squad_name", squad.Name,
+ "leader_agent_id", resp.Agent.ID,
+ "owns_issue_status", ownsIssueStatus,
)
}
}
-
- var projectRepos []RepoData
- if issue.ProjectID.Valid {
- resp.ProjectID = uuidToString(issue.ProjectID)
- if proj, err := h.Queries.GetProject(r.Context(), issue.ProjectID); err == nil {
- resp.ProjectTitle = proj.Title
- resp.ProjectDescription = proj.Description.String
- }
- if rows := h.listProjectResourcesForProject(r.Context(), issue.ProjectID); len(rows) > 0 {
- out := make([]ProjectResourceData, 0, len(rows))
- for _, row := range rows {
- label := ""
- if row.Label.Valid {
- label = row.Label.String
- }
- ref := json.RawMessage(row.ResourceRef)
- if len(ref) == 0 {
- ref = json.RawMessage("{}")
- }
- out = append(out, ProjectResourceData{
- ID: uuidToString(row.ID),
- ResourceType: row.ResourceType,
- ResourceRef: ref,
- Label: label,
- })
- // Lift github_repo resources into the daemon's repo list
- // so `multica repo checkout` and the meta-skill render
- // them as the issue's repos.
- if row.ResourceType == "github_repo" {
- var payload struct {
- URL string `json:"url"`
- Ref string `json:"ref,omitempty"`
- }
- if json.Unmarshal(row.ResourceRef, &payload) == nil && payload.URL != "" {
- projectRepos = append(projectRepos, RepoData{URL: payload.URL, Ref: strings.TrimSpace(payload.Ref)})
- }
- }
- }
- resp.ProjectResources = out
- }
+ // Every skip above (NULL squad_id, squad hard-deleted, leader
+ // swapped after enqueue) leaves a task the daemon must NOT run
+ // as a leader: it has no roster to delegate to and no protocol
+ // to follow. The daemon derives its leader role from this flag
+ // (MUL-5811), so clearing it here is what keeps
+ // "is_leader_task on the wire ⇔ briefing injected" true, and the
+ // run degrades to an ordinary agent turn exactly as it did when
+ // the daemon inferred the role from the briefing text itself.
+ if !injected {
+ resp.IsLeaderTask = false
+ slog.Warn("squad leader briefing not injected; claim delivered as a non-leader task",
+ "task_id", uuidToString(task.ID),
+ "squad_id", uuidToString(task.SquadID),
+ "agent_id", uuidToString(task.AgentID),
+ )
}
+ }
- if len(projectRepos) > 0 {
- resp.Repos = projectRepos
- } else if ws, err := h.Queries.GetWorkspace(r.Context(), issue.WorkspaceID); err == nil && ws.Repos != nil {
- var repos []RepoData
- if json.Unmarshal(ws.Repos, &repos) == nil && len(repos) > 0 {
- resp.Repos = repos
- }
+ projectCtx, projectErr := h.resolveClaimProjectContext(r.Context(), issue.ProjectID, issue.WorkspaceID)
+ if projectErr != nil {
+ slog.Error("issue claim: load project context failed; preserving task for redelivery",
+ "task_id", uuidToString(task.ID),
+ "issue_id", uuidToString(issue.ID),
+ "error", projectErr)
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
+ outcome: "error_project_context",
+ status: http.StatusInternalServerError,
+ message: "failed to load project context",
}
}
+ projectCtx.applyTo(&resp)
// Load every planned input as one chronological, de-duplicated set.
// The trigger is included here so the delivery receipt can only contain
@@ -2514,301 +2568,296 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
// Chat task: populate workspace/session info from the chat_session table.
if task.ChatSessionID.Valid {
- if cs, err := h.Queries.GetChatSession(r.Context(), task.ChatSessionID); err == nil {
- resp.WorkspaceID = uuidToString(cs.WorkspaceID)
- resp.ChatSessionID = uuidToString(cs.ID)
- resp.ThreadName = cs.Title
- // Legacy compatibility: agent creation no longer creates intro chats,
- // but historical is_agent_intro sessions can still be resumed. Such a
- // session carries no user message on its opening turn, so flag it for
- // the historical self-introduction prompt (MUL-4230). The column stays true for the
- // session's whole life, so gate the intro prompt on the session still
- // having zero human messages — otherwise every follow-up turn after the
- // creator replies would re-run the "introduce yourself" prompt and the
- // agent keeps repeating the same introduction (MUL-4259).
- if cs.IsAgentIntro {
- if hasUser, herr := h.Queries.ChatSessionHasUserMessage(r.Context(), cs.ID); herr != nil {
- slog.Warn("chat intro gate: has-user-message check failed",
- "chat_session_id", uuidToString(cs.ID), "error", herr)
- } else {
- resp.ChatIntro = !hasUser
- }
- }
- // Flag a channel-backed session so the daemon makes the agent aware it
- // is operating inside an IM conversation and not the Multica web app
- // (MUL-3871). Empty for a web-only chat session.
- //
- // The binding is read WITHOUT naming a channel. Every channel writes
- // the same channel_chat_session_binding row and differs only in
- // channel_type, and UNIQUE (chat_session_id) allows at most one, so
- // the row itself is the answer. Enumerating candidate channels here
- // was the bug twice over: the Slack-only lookup reported a Feishu
- // chat as web-backed (MUL-4899), and the {slack, feishu} list that
- // replaced it did the same to WeCom. Downstream that mis-flag makes
- // the brief inject `multica attachment upload` guidance into a
- // conversation that cannot carry attachments at all.
- //
- // ChatInThread stays Slack-only on purpose. It selects between
- // `multica chat history` and `multica chat thread`, and those two
- // endpoints are hardwired to h.SlackHistory (chat_history.go) — there
- // is no history reader on any other channel, so the flag has nothing
- // to select between there and must not imply one exists.
- //
- // chat_type rides along on the same row. It is what lets the
- // per-turn prompt tell the agent whether this chat_session is a room
- // shared by many people or a 1:1 with the bot; the prompt used to
- // describe every chat run as a private 1:1 whatever the room. The
- // shared session service writes the column for every channel
- // (channel/engine/session.go), so no channel needs naming here
- // either.
- if binding, berr := h.Queries.GetChannelChatSessionBindingBySessionAny(r.Context(), cs.ID); berr == nil {
- resp.ChatChannelType = binding.ChannelType
- resp.ChatType = binding.ChatType
- // Whether a file the agent produces reaches this
- // conversation is the server's question, not the daemon's.
- // It takes an adapter that goes back for the bound
- // attachment AND storage for it to go back to, and only
- // this process knows both. Answered here so the daemon
- // never has to infer it from the channel type — an
- // inference that promises delivery on any deployment
- // running WeCom without object storage.
- resp.ChatChannelDeliversFiles = h.channelDeliversFiles(binding.ChannelType)
- if binding.ChannelType == string(slack.TypeSlack) {
- // The latest trigger was a thread reply iff its reply-target
- // thread (last_thread_id) differs from its own message id (a
- // top-level @mention records its own ts as both).
- resp.ChatInThread = binding.LastThreadID.Valid && binding.LastThreadID.String != "" &&
- binding.LastThreadID.String != binding.LastMessageID.String
- }
+ cs, chatErr := h.Queries.GetChatSession(r.Context(), task.ChatSessionID)
+ if chatErr != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount,
+ h.rejectClaimSourceLoad(r.Context(), task, chatErr, "chat session", uuidToString(task.ChatSessionID))
+ }
+ resp.WorkspaceID = uuidToString(cs.WorkspaceID)
+ if failure := h.rejectClaimOnWorkspaceMismatch(r.Context(), task, resp.WorkspaceID, runtimeID, runtimeWorkspaceID, false); failure != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, failure
+ }
+ resp.ChatSessionID = uuidToString(cs.ID)
+ resp.ThreadName = cs.Title
+ // Legacy compatibility: agent creation no longer creates intro chats,
+ // but historical is_agent_intro sessions can still be resumed. Such a
+ // session carries no user message on its opening turn, so flag it for
+ // the historical self-introduction prompt (MUL-4230). The column stays true for the
+ // session's whole life, so gate the intro prompt on the session still
+ // having zero human messages — otherwise every follow-up turn after the
+ // creator replies would re-run the "introduce yourself" prompt and the
+ // agent keeps repeating the same introduction (MUL-4259).
+ if cs.IsAgentIntro {
+ if hasUser, herr := h.Queries.ChatSessionHasUserMessage(r.Context(), cs.ID); herr != nil {
+ slog.Warn("chat intro gate: has-user-message check failed",
+ "chat_session_id", uuidToString(cs.ID), "error", herr)
+ } else {
+ resp.ChatIntro = !hasUser
}
- // A web chat can opt into the same durable project context as an
- // issue-bound task. Revalidate the soft reference in this workspace at
- // claim time: a deleted/stale project degrades to workspace context and
- // can never leak a project from another tenant.
- var projectRepos []RepoData
- if cs.ProjectID.Valid {
- if project, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{
- ID: cs.ProjectID,
- WorkspaceID: cs.WorkspaceID,
- }); err == nil {
- resp.ProjectID = uuidToString(project.ID)
- resp.ProjectTitle = project.Title
- resp.ProjectDescription = project.Description.String
- if rows := h.listProjectResourcesForProject(r.Context(), project.ID); len(rows) > 0 {
- resources := make([]ProjectResourceData, 0, len(rows))
- for _, row := range rows {
- label := ""
- if row.Label.Valid {
- label = row.Label.String
- }
- ref := json.RawMessage(row.ResourceRef)
- if len(ref) == 0 {
- ref = json.RawMessage("{}")
- }
- resources = append(resources, ProjectResourceData{
- ID: uuidToString(row.ID),
- ResourceType: row.ResourceType,
- ResourceRef: ref,
- Label: label,
- })
- if row.ResourceType == "github_repo" {
- var payload struct {
- URL string `json:"url"`
- Ref string `json:"ref,omitempty"`
- }
- if json.Unmarshal(row.ResourceRef, &payload) == nil && payload.URL != "" {
- projectRepos = append(projectRepos, RepoData{URL: payload.URL, Ref: strings.TrimSpace(payload.Ref)})
- }
- }
- }
- resp.ProjectResources = resources
- }
- }
+ }
+ // Flag a channel-backed session so the daemon makes the agent aware it
+ // is operating inside an IM conversation and not the Multica web app
+ // (MUL-3871). Empty for a web-only chat session.
+ //
+ // The binding is read WITHOUT naming a channel. Every channel writes
+ // the same channel_chat_session_binding row and differs only in
+ // channel_type, and UNIQUE (chat_session_id) allows at most one, so
+ // the row itself is the answer. Enumerating candidate channels here
+ // was the bug twice over: the Slack-only lookup reported a Feishu
+ // chat as web-backed (MUL-4899), and the {slack, feishu} list that
+ // replaced it did the same to WeCom. Downstream that mis-flag makes
+ // the brief inject `multica attachment upload` guidance into a
+ // conversation that cannot carry attachments at all.
+ //
+ // ChatInThread stays Slack-only on purpose. It selects between
+ // `multica chat history` and `multica chat thread`, and those two
+ // endpoints are hardwired to h.SlackHistory (chat_history.go) — there
+ // is no history reader on any other channel, so the flag has nothing
+ // to select between there and must not imply one exists.
+ //
+ // chat_type rides along on the same row. It is what lets the
+ // per-turn prompt tell the agent whether this chat_session is a room
+ // shared by many people or a 1:1 with the bot; the prompt used to
+ // describe every chat run as a private 1:1 whatever the room. The
+ // shared session service writes the column for every channel
+ // (channel/engine/session.go), so no channel needs naming here
+ // either.
+ if binding, berr := h.Queries.GetChannelChatSessionBindingBySessionAny(r.Context(), cs.ID); berr == nil {
+ resp.ChatChannelType = binding.ChannelType
+ resp.ChatType = binding.ChatType
+ // Whether a file the agent produces reaches this
+ // conversation is the server's question, not the daemon's.
+ // It takes an adapter that goes back for the bound
+ // attachment AND storage for it to go back to, and only
+ // this process knows both. Answered here so the daemon
+ // never has to infer it from the channel type — an
+ // inference that promises delivery on any deployment
+ // running WeCom without object storage.
+ resp.ChatChannelDeliversFiles = h.channelDeliversFiles(binding.ChannelType)
+ if binding.ChannelType == string(slack.TypeSlack) {
+ // The latest trigger was a thread reply iff its reply-target
+ // thread (last_thread_id) differs from its own message id (a
+ // top-level @mention records its own ts as both).
+ resp.ChatInThread = binding.LastThreadID.Valid && binding.LastThreadID.String != "" &&
+ binding.LastThreadID.String != binding.LastMessageID.String
}
- if len(projectRepos) > 0 {
- resp.Repos = projectRepos
- } else if ws, err := h.Queries.GetWorkspace(r.Context(), cs.WorkspaceID); err == nil && ws.Repos != nil {
- var repos []RepoData
- if json.Unmarshal(ws.Repos, &repos) == nil && len(repos) > 0 {
- resp.Repos = repos
- }
+ }
+ // A web chat can opt into the same durable project context as an
+ // issue-bound task.
+ projectCtx, projectErr := h.resolveClaimProjectContext(r.Context(), cs.ProjectID, cs.WorkspaceID)
+ if projectErr != nil {
+ slog.Error("chat claim: load project context failed; preserving task for redelivery",
+ "task_id", uuidToString(task.ID),
+ "chat_session_id", uuidToString(cs.ID),
+ "error", projectErr)
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
+ outcome: "error_project_context",
+ status: http.StatusInternalServerError,
+ message: "failed to load project context",
}
- if !task.ForceFreshSession {
- // Resume chat sessions only when the stored pointer was produced
- // by the same runtime as the claiming task. When the chat_session
- // pointer is missing (legacy NULL runtime_id), stale (last task
- // failed before reporting completion), or runtime-mismatched, fall
- // back to the most recent task row that recorded a session_id —
- // otherwise a single failed turn would silently drop the entire
- // conversation memory on the next message. The fallback also
- // requires runtime to match.
- if cs.SessionID.Valid && cs.RuntimeID.Valid && cs.RuntimeID == task.RuntimeID {
- resp.PriorSessionID = cs.SessionID.String
- }
- if cs.WorkDir.Valid {
- resp.PriorWorkDir = cs.WorkDir.String
- }
+ }
+ projectCtx.applyTo(&resp)
+ if !task.ForceFreshSession {
+ // Resume chat sessions only when the stored pointer was produced
+ // by the same runtime as the claiming task. When the chat_session
+ // pointer is missing (legacy NULL runtime_id), stale (last task
+ // failed before reporting completion), or runtime-mismatched, fall
+ // back to the most recent task row that recorded a session_id —
+ // otherwise a single failed turn would silently drop the entire
+ // conversation memory on the next message. The fallback also
+ // requires runtime to match.
+ if cs.SessionID.Valid && cs.RuntimeID.Valid && cs.RuntimeID == task.RuntimeID {
+ resp.PriorSessionID = cs.SessionID.String
}
- // Resolve the user-message input batch for this run. A task-owned
- // task (chat_input_task_id set) reads exactly the user messages
- // tagged with its own input owner, so a message that arrived after
- // this turn was sealed can never be absorbed here. Direct-chat
- // tasks have owned their single message since MUL-4351; channel
- // (Slack/Lark) tasks now seal their trailing batch at enqueue too.
- // Only legacy tasks created before that deploy carry a NULL owner
- // and keep the trailing-message selector — the run of user messages
- // after the last assistant row, which also covers a debounced burst
- // (MUL-2968: "看上海天气" then "还有青岛" must both be delivered) —
- // so a rolling deploy never replays their history. Attachments are
- // collected per included message so the agent can
- // `multica attachment download <id>` (the inline markdown URL is
- // signed + 30-min expiring on the CDN).
- var unanswered []db.ChatMessage
- var inputLoadErr error
- if task.ChatInputTaskID.Valid {
- unanswered, inputLoadErr = h.Queries.ListChatInputMessages(r.Context(), task.ChatInputTaskID)
- } else if msgs, err := h.Queries.ListChatMessagesForLegacyTask(r.Context(), cs.ID); err == nil {
- unanswered = trailingUserMessages(msgs)
- } else {
- inputLoadErr = err
+ if cs.WorkDir.Valid {
+ resp.PriorWorkDir = cs.WorkDir.String
}
- // A read failure must NOT masquerade as "zero input". Preserve the
- // just-dispatched task (the stale-dispatched reclaim redelivers it)
- // and reject the claim with 5xx, rather than cancelling a valid direct
- // task on a transient DB error (MUL-4351 review).
- if inputLoadErr != nil {
- slog.Error("chat claim: load chat input messages failed; preserving task for redelivery",
- "task_id", uuidToString(task.ID),
- "chat_session_id", uuidToString(cs.ID),
- "error", inputLoadErr)
- return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
- outcome: "error_chat_input_load",
- status: http.StatusInternalServerError,
- message: "failed to load chat input",
- }
+ }
+ // Resolve the user-message input batch for this run. A task-owned
+ // task (chat_input_task_id set) reads exactly the user messages
+ // tagged with its own input owner, so a message that arrived after
+ // this turn was sealed can never be absorbed here. Direct-chat
+ // tasks have owned their single message since MUL-4351; channel
+ // (Slack/Lark) tasks now seal their trailing batch at enqueue too.
+ // Only legacy tasks created before that deploy carry a NULL owner
+ // and keep the trailing-message selector — the run of user messages
+ // after the last assistant row, which also covers a debounced burst
+ // (MUL-2968: "看上海天气" then "还有青岛" must both be delivered) —
+ // so a rolling deploy never replays their history. Attachments are
+ // collected per included message so the agent can
+ // `multica attachment download <id>` (the inline markdown URL is
+ // signed + 30-min expiring on the CDN).
+ var unanswered []db.ChatMessage
+ var inputLoadErr error
+ if task.ChatInputTaskID.Valid {
+ unanswered, inputLoadErr = h.Queries.ListChatInputMessages(r.Context(), task.ChatInputTaskID)
+ } else if msgs, err := h.Queries.ListChatMessagesForLegacyTask(r.Context(), cs.ID); err == nil {
+ unanswered = trailingUserMessages(msgs)
+ } else {
+ inputLoadErr = err
+ }
+ // A read failure must NOT masquerade as "zero input". Preserve the
+ // just-dispatched task (the stale-dispatched reclaim redelivers it)
+ // and reject the claim with 5xx, rather than cancelling a valid direct
+ // task on a transient DB error (MUL-4351 review).
+ if inputLoadErr != nil {
+ slog.Error("chat claim: load chat input messages failed; preserving task for redelivery",
+ "task_id", uuidToString(task.ID),
+ "chat_session_id", uuidToString(cs.ID),
+ "error", inputLoadErr)
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
+ outcome: "error_chat_input_load",
+ status: http.StatusInternalServerError,
+ message: "failed to load chat input",
}
+ }
- // Input ownership is the claim's fail-closed boundary. Resume-history
- // reads belong after it: a task that cannot load its input is preserved
- // for redelivery and must not spend two more queries before returning.
- if !task.ForceFreshSession {
- // GetLastChatTaskSession currently has exactly two consumers: the
- // prior session and prior workdir fields. Keep this guard coupled to
- // both so adding a third consumer cannot silently skip its fallback.
- if chatSessionResumeFallbackNeeded(resp.PriorSessionID, resp.PriorWorkDir) {
- h.Metrics.RecordChatClaimSessionFallbackNeeded()
- started := time.Now()
- prior, err := h.Queries.GetLastChatTaskSession(r.Context(), cs.ID)
- h.Metrics.ObserveChatClaimLastSessionQuery(time.Since(started).Seconds())
- switch {
- case err == nil && prior.SessionID.Valid:
- h.Metrics.RecordChatClaimSessionFallbackHit()
- if resp.PriorSessionID == "" && prior.RuntimeID == task.RuntimeID {
- resp.PriorSessionID = prior.SessionID.String
- }
- if prior.WorkDir.Valid && resp.PriorWorkDir == "" {
- resp.PriorWorkDir = prior.WorkDir.String
- }
- case errors.Is(err, pgx.ErrNoRows):
- h.Metrics.RecordChatClaimSessionFallbackMiss()
- case err == nil:
- // Defensive only: the SQL excludes NULL session ids, but
- // preserve miss semantics if that contract ever changes.
- h.Metrics.RecordChatClaimSessionFallbackMiss()
- default:
- h.Metrics.RecordChatClaimSessionFallbackError()
+ // Input ownership is the claim's fail-closed boundary. Resume-history
+ // reads belong after it: a task that cannot load its input is preserved
+ // for redelivery and must not spend two more queries before returning.
+ if !task.ForceFreshSession {
+ // GetLastChatTaskSession currently has exactly two consumers: the
+ // prior session and prior workdir fields. Keep this guard coupled to
+ // both so adding a third consumer cannot silently skip its fallback.
+ if chatSessionResumeFallbackNeeded(resp.PriorSessionID, resp.PriorWorkDir) {
+ h.Metrics.RecordChatClaimSessionFallbackNeeded()
+ started := time.Now()
+ prior, err := h.Queries.GetLastChatTaskSession(r.Context(), cs.ID)
+ h.Metrics.ObserveChatClaimLastSessionQuery(time.Since(started).Seconds())
+ switch {
+ case err == nil && prior.SessionID.Valid:
+ h.Metrics.RecordChatClaimSessionFallbackHit()
+ if resp.PriorSessionID == "" && prior.RuntimeID == task.RuntimeID {
+ resp.PriorSessionID = prior.SessionID.String
+ }
+ if prior.WorkDir.Valid && resp.PriorWorkDir == "" {
+ resp.PriorWorkDir = prior.WorkDir.String
}
+ case errors.Is(err, pgx.ErrNoRows):
+ h.Metrics.RecordChatClaimSessionFallbackMiss()
+ case err == nil:
+ // Defensive only: the SQL excludes NULL session ids, but
+ // preserve miss semantics if that contract ever changes.
+ h.Metrics.RecordChatClaimSessionFallbackMiss()
+ default:
+ h.Metrics.RecordChatClaimSessionFallbackError()
}
+ }
- // MUL-5305: continuity-gap disclosure is independent of whether
- // either pointer field needed fallback, so this query stays
- // unconditional for non-force-fresh chat claims.
- started := time.Now()
- missing, err := h.Queries.GetLatestChatTaskRolloutMissing(r.Context(), cs.ID)
- h.Metrics.ObserveChatClaimRolloutMissingQuery(time.Since(started).Seconds())
- if err == nil && missing {
- resp.PriorSessionResumeUnavailable = true
- }
+ // MUL-5305: continuity-gap disclosure is independent of whether
+ // either pointer field needed fallback, so this query stays
+ // unconditional for non-force-fresh chat claims.
+ started := time.Now()
+ missing, err := h.Queries.GetLatestChatTaskRolloutMissing(r.Context(), cs.ID)
+ h.Metrics.ObserveChatClaimRolloutMissingQuery(time.Since(started).Seconds())
+ if err == nil && missing {
+ resp.PriorSessionResumeUnavailable = true
}
+ }
- parts := make([]string, 0, len(unanswered))
- for _, m := range unanswered {
- if strings.TrimSpace(m.Content) != "" {
- parts = append(parts, m.Content)
- }
- if atts, attErr := h.Queries.ListAttachmentsByChatMessage(r.Context(), db.ListAttachmentsByChatMessageParams{
- ChatMessageID: m.ID,
- WorkspaceID: parseUUID(resp.WorkspaceID),
- }); attErr == nil && len(atts) > 0 {
- for _, a := range atts {
- resp.ChatMessageAttachments = append(resp.ChatMessageAttachments, ChatAttachmentMeta{
- ID: uuidToString(a.ID),
- Filename: a.Filename,
- ContentType: a.ContentType,
- })
- }
- }
+ parts := make([]string, 0, len(unanswered))
+ for _, m := range unanswered {
+ if strings.TrimSpace(m.Content) != "" {
+ parts = append(parts, m.Content)
}
- resp.ChatMessage = strings.Join(parts, "\n\n")
-
- // Fail closed: a task-owned direct task that resolves to no user text
- // (and is not the agent's proactive intro) must never dispatch an
- // empty prompt. The send path creates the owning user message in the
- // same transaction as the task, so this only fires on genuinely
- // corrupt state — cancel the just-dispatched task and reject the claim
- // rather than run the agent with nothing to answer (MUL-4351).
- if task.ChatInputTaskID.Valid && !resp.ChatIntro && strings.TrimSpace(resp.ChatMessage) == "" {
- slog.Error("chat claim: task-owned direct task has no user input; cancelling",
- "task_id", uuidToString(task.ID),
- "chat_session_id", uuidToString(cs.ID),
- "chat_input_task_id", uuidToString(task.ChatInputTaskID),
- )
- if _, cerr := h.TaskService.CancelTask(r.Context(), task.ID); cerr != nil {
- slog.Error("chat claim: cancel after empty input failed",
- "task_id", uuidToString(task.ID), "error", cerr)
- }
- return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
- outcome: "error_empty_chat_input",
- status: http.StatusInternalServerError,
- message: "chat task has no user input",
+ if atts, attErr := h.Queries.ListAttachmentsByChatMessage(r.Context(), db.ListAttachmentsByChatMessageParams{
+ ChatMessageID: m.ID,
+ WorkspaceID: parseUUID(resp.WorkspaceID),
+ }); attErr == nil && len(atts) > 0 {
+ for _, a := range atts {
+ resp.ChatMessageAttachments = append(resp.ChatMessageAttachments, ChatAttachmentMeta{
+ ID: uuidToString(a.ID),
+ Filename: a.Filename,
+ ContentType: a.ContentType,
+ })
}
}
+ }
+ resp.ChatMessage = strings.Join(parts, "\n\n")
- if strings.TrimSpace(resp.ThreadName) == "" && resp.ChatMessage != "" {
- resp.ThreadName = resp.ChatMessage
+ // Fail closed: a task-owned direct task that resolves to no user text
+ // (and is not the agent's proactive intro) must never dispatch an
+ // empty prompt. The send path creates the owning user message in the
+ // same transaction as the task, so this only fires on genuinely
+ // corrupt state — cancel the just-dispatched task and reject the claim
+ // rather than run the agent with nothing to answer (MUL-4351).
+ if task.ChatInputTaskID.Valid && !resp.ChatIntro && strings.TrimSpace(resp.ChatMessage) == "" {
+ slog.Error("chat claim: task-owned direct task has no user input; cancelling",
+ "task_id", uuidToString(task.ID),
+ "chat_session_id", uuidToString(cs.ID),
+ "chat_input_task_id", uuidToString(task.ChatInputTaskID),
+ )
+ if _, cerr := h.TaskService.CancelTask(r.Context(), task.ID); cerr != nil {
+ slog.Error("chat claim: cancel after empty input failed",
+ "task_id", uuidToString(task.ID), "error", cerr)
+ }
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
+ outcome: "error_empty_chat_input",
+ status: http.StatusInternalServerError,
+ message: "chat task has no user input",
}
}
+
+ if strings.TrimSpace(resp.ThreadName) == "" && resp.ChatMessage != "" {
+ resp.ThreadName = resp.ChatMessage
+ }
}
// Autopilot run_only task: resolve workspace from autopilot_run →
// autopilot, and include the autopilot instructions because there is no
// issue for the agent to fetch.
if task.AutopilotRunID.Valid {
- if run, err := h.Queries.GetAutopilotRun(r.Context(), task.AutopilotRunID); err == nil {
- resp.AutopilotID = uuidToString(run.AutopilotID)
- resp.AutopilotSource = run.Source
- if run.TriggerPayload != nil {
- resp.AutopilotTriggerPayload = json.RawMessage(run.TriggerPayload)
- }
- if ap, err := h.Queries.GetAutopilot(r.Context(), run.AutopilotID); err == nil {
- resp.AutopilotTitle = ap.Title
- resp.ThreadName = ap.Title
- if ap.Description.Valid {
- resp.AutopilotDescription = ap.Description.String
- }
- if resp.WorkspaceID == "" {
- resp.WorkspaceID = uuidToString(ap.WorkspaceID)
- }
- if len(resp.Repos) == 0 {
- if ws, err := h.Queries.GetWorkspace(r.Context(), ap.WorkspaceID); err == nil && ws.Repos != nil {
- var repos []RepoData
- if json.Unmarshal(ws.Repos, &repos) == nil && len(repos) > 0 {
- resp.Repos = repos
- }
- }
- }
+ run, runErr := h.Queries.GetAutopilotRun(r.Context(), task.AutopilotRunID)
+ if runErr != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount,
+ h.rejectClaimSourceLoad(r.Context(), task, runErr, "autopilot run", uuidToString(task.AutopilotRunID))
+ }
+ ap, apErr := h.Queries.GetAutopilot(r.Context(), run.AutopilotID)
+ if apErr != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount,
+ h.rejectClaimSourceLoad(r.Context(), task, apErr, "autopilot", uuidToString(run.AutopilotID))
+ }
+
+ // The autopilot owns this task's workspace. taskToResponse seeded
+ // resp.WorkspaceID with the RUNTIME's workspace, so the old
+ // `if resp.WorkspaceID == ""` guard never fired and left the isolation
+ // check comparing the runtime workspace against itself. Assign
+ // authoritatively, then prove ownership before exposing any
+ // autopilot-owned context.
+ resp.WorkspaceID = uuidToString(ap.WorkspaceID)
+ if failure := h.rejectClaimOnWorkspaceMismatch(r.Context(), task, resp.WorkspaceID, runtimeID, runtimeWorkspaceID, false); failure != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, failure
+ }
+
+ resp.AutopilotID = uuidToString(run.AutopilotID)
+ resp.AutopilotSource = run.Source
+ if run.TriggerPayload != nil {
+ resp.AutopilotTriggerPayload = json.RawMessage(run.TriggerPayload)
+ }
+ resp.AutopilotTitle = ap.Title
+ resp.ThreadName = ap.Title
+ if ap.Description.Valid {
+ resp.AutopilotDescription = ap.Description.String
+ }
+
+ // A run_only autopilot has no issue from which to inherit project
+ // context, so its configured project is hydrated here. That gives the
+ // daemon the same resource contract as issue-bound and quick-create
+ // tasks: project repositories scope the checkout, while local_directory
+ // lets the daemon select the bound path and write its managed manifest.
+ projectCtx, projectErr := h.resolveClaimProjectContext(r.Context(), ap.ProjectID, ap.WorkspaceID)
+ if projectErr != nil {
+ slog.Error("autopilot claim: load project context failed; preserving task for redelivery",
+ "task_id", uuidToString(task.ID),
+ "autopilot_id", uuidToString(run.AutopilotID),
+ "error", projectErr)
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
+ outcome: "error_project_context",
+ status: http.StatusInternalServerError,
+ message: "failed to load project context",
}
}
+ projectCtx.applyTo(&resp)
}
// Handoff note (MUL-3375) is populated by taskToResponse (the shared mapper
@@ -2829,61 +2878,33 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
resp.QuickCreateAttachmentIDs = append([]string(nil), qc.AttachmentIDs...)
resp.ThreadName = qc.Prompt
resp.WorkspaceID = qc.WorkspaceID
+ if failure := h.rejectClaimOnWorkspaceMismatch(r.Context(), task, resp.WorkspaceID, runtimeID, runtimeWorkspaceID, true); failure != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, failure
+ }
// When the user picked a project in the modal, surface its title
// and resources to the daemon so the agent has the same context
- // it would for an issue-bound task: the prompt template can name
- // the project, and `multica repo checkout` sees the project's
- // github_repo resources instead of the workspace fallback.
- var projectRepos []RepoData
+ // it would for an issue-bound task. A prompt-supplied project id
+ // that does not parse is treated as no project at all.
+ var quickCreateProjectID pgtype.UUID
if qc.ProjectID != "" {
- projectUUID, err := util.ParseUUID(qc.ProjectID)
- if err == nil {
- resp.ProjectID = qc.ProjectID
- if proj, err := h.Queries.GetProject(r.Context(), projectUUID); err == nil {
- resp.ProjectTitle = proj.Title
- resp.ProjectDescription = proj.Description.String
- }
- if rows := h.listProjectResourcesForProject(r.Context(), projectUUID); len(rows) > 0 {
- out := make([]ProjectResourceData, 0, len(rows))
- for _, row := range rows {
- label := ""
- if row.Label.Valid {
- label = row.Label.String
- }
- ref := json.RawMessage(row.ResourceRef)
- if len(ref) == 0 {
- ref = json.RawMessage("{}")
- }
- out = append(out, ProjectResourceData{
- ID: uuidToString(row.ID),
- ResourceType: row.ResourceType,
- ResourceRef: ref,
- Label: label,
- })
- if row.ResourceType == "github_repo" {
- var payload struct {
- URL string `json:"url"`
- Ref string `json:"ref,omitempty"`
- }
- if json.Unmarshal(row.ResourceRef, &payload) == nil && payload.URL != "" {
- projectRepos = append(projectRepos, RepoData{URL: payload.URL, Ref: strings.TrimSpace(payload.Ref)})
- }
- }
- }
- resp.ProjectResources = out
- }
+ if parsed, err := util.ParseUUID(qc.ProjectID); err == nil {
+ quickCreateProjectID = parsed
}
}
-
- if len(projectRepos) > 0 {
- resp.Repos = projectRepos
- } else if ws, err := h.Queries.GetWorkspace(r.Context(), parseUUID(qc.WorkspaceID)); err == nil && ws.Repos != nil {
- var repos []RepoData
- if json.Unmarshal(ws.Repos, &repos) == nil && len(repos) > 0 {
- resp.Repos = repos
+ projectCtx, projectErr := h.resolveClaimProjectContext(r.Context(), quickCreateProjectID, parseUUID(qc.WorkspaceID))
+ if projectErr != nil {
+ slog.Error("quick-create claim: load project context failed; preserving task for redelivery",
+ "task_id", uuidToString(task.ID),
+ "project_id", qc.ProjectID,
+ "error", projectErr)
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
+ outcome: "error_project_context",
+ status: http.StatusInternalServerError,
+ message: "failed to load project context",
}
}
+ projectCtx.applyTo(&resp)
// Parent-issue resolution for quick-create tasks opened from
// "Add sub issue". The handler already verified workspace
@@ -2951,34 +2972,13 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}
}
- // Workspace isolation check: the daemon uses this response's workspace_id
- // as the only authority for MULTICA_WORKSPACE_ID in the agent env. An
- // empty value would make the CLI silently fall back to the user-global
- // config and talk to whatever workspace the user happened to last
- // configure; a value that doesn't match the runtime's workspace means
- // upstream routed a foreign-workspace task here. Both cases must hard-
- // fail AND cancel the just-dispatched task so the queue / agent status
- // don't sit stuck until the stale-task sweeper fires minutes later.
- if resp.WorkspaceID == "" || resp.WorkspaceID != runtimeWorkspaceID {
- slog.Error("task claim: workspace isolation check failed, cancelling task",
- "task_id", uuidToString(task.ID),
- "runtime_id", runtimeID,
- "runtime_workspace", runtimeWorkspaceID,
- "resolved_workspace", resp.WorkspaceID,
- "has_issue", task.IssueID.Valid,
- "has_chat", task.ChatSessionID.Valid,
- "has_autopilot_run", task.AutopilotRunID.Valid,
- "has_quick_create", hasQuickCreate,
- )
- if _, cerr := h.TaskService.CancelTask(r.Context(), task.ID); cerr != nil {
- slog.Error("task claim: cancel after workspace check failed",
- "task_id", uuidToString(task.ID), "error", cerr)
- }
- return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
- outcome: "error_workspace",
- status: http.StatusInternalServerError,
- message: "task workspace isolation check failed",
- }
+ // Catch-all workspace isolation check. Every context branch above already
+ // ran this the moment it resolved its owning workspace, which is what makes
+ // "prove ownership, then hydrate" structural rather than per-branch
+ // discipline. This final call is the backstop for a task that reached here
+ // without any branch claiming it.
+ if failure := h.rejectClaimOnWorkspaceMismatch(r.Context(), task, resp.WorkspaceID, runtimeID, runtimeWorkspaceID, hasQuickCreate); failure != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, failure
}
// Surface a bounded snapshot of the same agent's other in-flight issue
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index bf8bd7cc00..ac777300b9 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -2185,12 +2185,11 @@ func TestClaimTask_ProjectWithoutRepos_FallsBackToWorkspaceRepos(t *testing.T) {
}
}
-// Regression test for #1276: ClaimTaskByRuntime must populate workspace_id in
-// the response for run_only autopilot tasks. Before the fix, resp.WorkspaceID
-// stayed empty because ClaimTaskByRuntime only handled IssueID and
-// ChatSessionID branches, causing the daemon's execenv to fail with
-// "workspace ID is required".
-func TestClaimTask_AutopilotRunOnly_PopulatesWorkspaceID(t *testing.T) {
+// Regression test for #1276: ClaimTaskByRuntime must populate both
+// workspace and project context for run_only autopilot tasks. Project context
+// is what lets the daemon select a bound local_directory and materialize the
+// managed .multica/project/resources.json source manifest before launch.
+func TestClaimTask_AutopilotRunOnly_PopulatesWorkspaceAndProjectContext(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -2202,8 +2201,29 @@ func TestClaimTask_AutopilotRunOnly_PopulatesWorkspaceID(t *testing.T) {
SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1
`, testWorkspaceID).Scan(&agentID, &runtimeID)
+ const projectDescription = "Use only the bound project resources."
+ projectID := dbfx.Project(t, "Run-only autopilot project", testutil.Cols{
+ "description": projectDescription,
+ })
+ const projectRepoURL = "https://github.com/example/run-only-project"
+ dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": projectID,
+ "workspace_id": testWorkspaceID,
+ "resource_type": "github_repo",
+ "resource_ref": `{"url":"` + projectRepoURL + `"}`,
+ "position": 0,
+ })
+ dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": projectID,
+ "workspace_id": testWorkspaceID,
+ "resource_type": "local_directory",
+ "resource_ref": `{"daemon_id":"test-daemon-claim","local_path":"/srv/run-only-project","execution_mode":"in_place"}`,
+ "position": 1,
+ })
+
autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{
"workspace_id": testWorkspaceID,
+ "project_id": projectID,
"title": "claim workspace fixture",
"assignee_id": agentID,
"execution_mode": "run_only",
@@ -2240,8 +2260,13 @@ func TestClaimTask_AutopilotRunOnly_PopulatesWorkspaceID(t *testing.T) {
var resp struct {
Task *struct {
- WorkspaceID string `json:"workspace_id"`
- ThreadName string `json:"thread_name"`
+ WorkspaceID string `json:"workspace_id"`
+ ThreadName string `json:"thread_name"`
+ Repos []RepoData `json:"repos"`
+ ProjectID string `json:"project_id"`
+ ProjectTitle string `json:"project_title"`
+ ProjectDescription string `json:"project_description"`
+ ProjectResources []ProjectResourceData `json:"project_resources"`
} `json:"task"`
}
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
@@ -2259,6 +2284,44 @@ func TestClaimTask_AutopilotRunOnly_PopulatesWorkspaceID(t *testing.T) {
if resp.Task.ThreadName != "claim workspace fixture" {
t.Fatalf("autopilot task thread_name = %q, want autopilot title", resp.Task.ThreadName)
}
+ if resp.Task.ProjectID != projectID {
+ t.Errorf("project_id = %q, want %q", resp.Task.ProjectID, projectID)
+ }
+ if resp.Task.ProjectTitle != "Run-only autopilot project" {
+ t.Errorf("project_title = %q, want run-only project title", resp.Task.ProjectTitle)
+ }
+ if resp.Task.ProjectDescription != projectDescription {
+ t.Errorf("project_description = %q, want %q", resp.Task.ProjectDescription, projectDescription)
+ }
+ if len(resp.Task.ProjectResources) != 2 {
+ t.Fatalf("project_resources count = %d, want 2", len(resp.Task.ProjectResources))
+ }
+ var localDirectory struct {
+ DaemonID string `json:"daemon_id"`
+ LocalPath string `json:"local_path"`
+ ExecutionMode string `json:"execution_mode"`
+ }
+ foundLocalDirectory := false
+ for _, resource := range resp.Task.ProjectResources {
+ if resource.ResourceType != "local_directory" {
+ continue
+ }
+ foundLocalDirectory = true
+ if err := json.Unmarshal(resource.ResourceRef, &localDirectory); err != nil {
+ t.Fatalf("decode local_directory resource: %v", err)
+ }
+ }
+ if !foundLocalDirectory {
+ t.Fatal("local_directory project resource missing from claim")
+ }
+ if localDirectory.DaemonID != "test-daemon-claim" ||
+ localDirectory.LocalPath != "/srv/run-only-project" ||
+ localDirectory.ExecutionMode != "in_place" {
+ t.Fatalf("local_directory = %+v, want bound daemon/path/in_place", localDirectory)
+ }
+ if len(resp.Task.Repos) != 1 || resp.Task.Repos[0].URL != projectRepoURL {
+ t.Fatalf("repos = %+v, want only project repo %q", resp.Task.Repos, projectRepoURL)
+ }
}
// TestClaimTaskByRuntime_TaskWorkspaceMismatch_CancelsAndRejects verifies
diff --git a/server/internal/handler/project_resource.go b/server/internal/handler/project_resource.go
index d929a5789f..6756d34a7f 100644
--- a/server/internal/handler/project_resource.go
+++ b/server/internal/handler/project_resource.go
@@ -5,12 +5,14 @@ import (
"encoding/json"
"errors"
"fmt"
+ "log/slog"
"net/http"
"net/url"
"reflect"
"strings"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
agentpkg "github.com/multica-ai/multica/server/pkg/agent"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -864,15 +866,139 @@ func parseUUIDLoose(s string) (pgtype.UUID, error) {
return u, nil
}
-// listProjectResourcesForProject is a small helper used by the daemon claim
-// handler to attach project resources to outgoing tasks.
-func (h *Handler) listProjectResourcesForProject(ctx context.Context, projectID pgtype.UUID) []db.ProjectResource {
- if !projectID.Valid {
- return nil
+// claimProjectContext is the project-scoped context a daemon claim exposes to
+// the agent: the project identity the prompt names, the resource manifest
+// execenv materializes into .multica/project/resources.json, and the repo list
+// `multica repo checkout` reads.
+type claimProjectContext struct {
+ ProjectID string
+ Title string
+ Description string
+ Resources []ProjectResourceData
+ Repos []RepoData
+}
+
+// applyTo copies the resolved context onto a claim response. Callers assign the
+// whole context or none of it, so a claim can never carry a project's title
+// without its resources.
+func (c claimProjectContext) applyTo(resp *AgentTaskResponse) {
+ resp.ProjectID = c.ProjectID
+ resp.ProjectTitle = c.Title
+ resp.ProjectDescription = c.Description
+ if len(c.Resources) > 0 {
+ resp.ProjectResources = c.Resources
+ }
+ resp.Repos = c.Repos
+}
+
+// resolveClaimProjectContext loads the project context for one daemon claim.
+//
+// Every claim path (issue, chat, autopilot, quick-create) resolves the same
+// thing from a soft project reference, so the tenant and failure rules live
+// here once rather than in a copy per path:
+//
+// - Both reads are workspace-scoped. project_resource carries its own
+// workspace_id, so a corrupt project reference cannot lift another tenant's
+// repository URLs or local paths into a claim.
+// - A read FAILURE is not "no project". It returns an error so the caller can
+// preserve the task for redelivery; collapsing it into the workspace-repo
+// fallback is what lets a transient DB error silently run an agent against
+// the wrong repository (the same rule the chat-input load follows,
+// MUL-4351).
+// - A project that resolves to no row IS "no project": the reference is stale,
+// deleted, or points outside this workspace, and the claim degrades to
+// workspace context.
+//
+// Repo precedence: project-bound github_repo resources override workspace repos
+// when present. Mixing both would just confuse the agent — if a project
+// explicitly attached its repos, those are the authoritative set. With no
+// project, no github_repo resources, or a stale reference, the workspace repos
+// are the fallback.
+func (h *Handler) resolveClaimProjectContext(ctx context.Context, projectID, workspaceID pgtype.UUID) (claimProjectContext, error) {
+ var out claimProjectContext
+
+ if projectID.Valid {
+ project, err := h.Queries.GetProjectInWorkspace(ctx, db.GetProjectInWorkspaceParams{
+ ID: projectID,
+ WorkspaceID: workspaceID,
+ })
+ switch {
+ case err == nil:
+ out.ProjectID = uuidToString(project.ID)
+ out.Title = project.Title
+ out.Description = project.Description.String
+
+ rows, resErr := h.Queries.ListProjectResourcesInWorkspace(ctx, db.ListProjectResourcesInWorkspaceParams{
+ ProjectID: project.ID,
+ WorkspaceID: workspaceID,
+ })
+ if resErr != nil {
+ return claimProjectContext{}, fmt.Errorf("list project resources: %w", resErr)
+ }
+ out.Resources, out.Repos = projectResourcesForClaim(rows)
+ case errors.Is(err, pgx.ErrNoRows):
+ // Stale/deleted/foreign reference: degrade to workspace context.
+ default:
+ return claimProjectContext{}, fmt.Errorf("get project: %w", err)
+ }
}
- rows, err := h.Queries.ListProjectResources(ctx, projectID)
+
+ if len(out.Repos) > 0 {
+ return out, nil
+ }
+
+ ws, err := h.Queries.GetWorkspace(ctx, workspaceID)
if err != nil {
- return nil
+ return claimProjectContext{}, fmt.Errorf("get workspace: %w", err)
+ }
+ if ws.Repos != nil {
+ var repos []RepoData
+ if jsonErr := json.Unmarshal(ws.Repos, &repos); jsonErr != nil {
+ // Corrupt stored JSON is not transient: failing the claim would
+ // wedge every claim in this workspace until someone repairs the
+ // row. Degrade to no repos and leave a trail instead.
+ slog.Error("claim project context: workspace repos are not valid JSON; claiming without repos",
+ "workspace_id", uuidToString(workspaceID), "error", jsonErr)
+ } else if len(repos) > 0 {
+ out.Repos = repos
+ }
+ }
+ return out, nil
+}
+
+// projectResourcesForClaim maps resource rows onto the claim wire shape and
+// lifts github_repo resources into the repo list so `multica repo checkout` and
+// the meta-skill render them as the task's repos.
+func projectResourcesForClaim(rows []db.ProjectResource) ([]ProjectResourceData, []RepoData) {
+ if len(rows) == 0 {
+ return nil, nil
+ }
+ resources := make([]ProjectResourceData, 0, len(rows))
+ var repos []RepoData
+ for _, row := range rows {
+ label := ""
+ if row.Label.Valid {
+ label = row.Label.String
+ }
+ ref := json.RawMessage(row.ResourceRef)
+ if len(ref) == 0 {
+ ref = json.RawMessage("{}")
+ }
+ resources = append(resources, ProjectResourceData{
+ ID: uuidToString(row.ID),
+ ResourceType: row.ResourceType,
+ ResourceRef: ref,
+ Label: label,
+ })
+ if row.ResourceType == "github_repo" {
+ var payload struct {
+ URL string `json:"url"`
+ Ref string `json:"ref,omitempty"`
+ }
+ if json.Unmarshal(row.ResourceRef, &payload) == nil && payload.URL != "" {
+ repos = append(repos, RepoData{URL: payload.URL, Ref: strings.TrimSpace(payload.Ref)})
+ }
+ }
}
- return rows
+ return resources, repos
}
diff --git a/server/pkg/db/generated/project.sql.go b/server/pkg/db/generated/project.sql.go
index 4410548c46..08e81281a0 100644
--- a/server/pkg/db/generated/project.sql.go
+++ b/server/pkg/db/generated/project.sql.go
@@ -92,32 +92,6 @@ func (q *Queries) DeleteProject(ctx context.Context, arg DeleteProjectParams) er
return err
}
-const getProject = `-- name: GetProject :one
-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date FROM project
-WHERE id = $1
-`
-
-func (q *Queries) GetProject(ctx context.Context, id pgtype.UUID) (Project, error) {
- row := q.db.QueryRow(ctx, getProject, id)
- var i Project
- err := row.Scan(
- &i.ID,
- &i.WorkspaceID,
- &i.Title,
- &i.Description,
- &i.Icon,
- &i.Status,
- &i.LeadType,
- &i.LeadID,
- &i.CreatedAt,
- &i.UpdatedAt,
- &i.Priority,
- &i.StartDate,
- &i.DueDate,
- )
- return i, err
-}
-
const getProjectInWorkspace = `-- name: GetProjectInWorkspace :one
SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date FROM project
WHERE id = $1 AND workspace_id = $2
diff --git a/server/pkg/db/generated/project_resource.sql.go b/server/pkg/db/generated/project_resource.sql.go
index 05c52d3927..1818c28109 100644
--- a/server/pkg/db/generated/project_resource.sql.go
+++ b/server/pkg/db/generated/project_resource.sql.go
@@ -227,6 +227,50 @@ func (q *Queries) ListProjectResourcesForProjects(ctx context.Context, projectId
return items, nil
}
+const listProjectResourcesInWorkspace = `-- name: ListProjectResourcesInWorkspace :many
+SELECT id, project_id, workspace_id, resource_type, resource_ref, label, position, created_at, created_by FROM project_resource
+WHERE project_id = $1 AND workspace_id = $2
+ORDER BY position ASC, created_at ASC
+`
+
+type ListProjectResourcesInWorkspaceParams struct {
+ ProjectID pgtype.UUID `json:"project_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Workspace-scoped read for the daemon claim path. project_resource carries its
+// own workspace_id, so a corrupt project reference cannot pull another tenant's
+// repository URLs or local paths into a claim response.
+func (q *Queries) ListProjectResourcesInWorkspace(ctx context.Context, arg ListProjectResourcesInWorkspaceParams) ([]ProjectResource, error) {
+ rows, err := q.db.Query(ctx, listProjectResourcesInWorkspace, arg.ProjectID, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ProjectResource{}
+ for rows.Next() {
+ var i ProjectResource
+ if err := rows.Scan(
+ &i.ID,
+ &i.ProjectID,
+ &i.WorkspaceID,
+ &i.ResourceType,
+ &i.ResourceRef,
+ &i.Label,
+ &i.Position,
+ &i.CreatedAt,
+ &i.CreatedBy,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const updateProjectResource = `-- name: UpdateProjectResource :one
UPDATE project_resource
SET resource_ref = $2,
diff --git a/server/pkg/db/queries/project.sql b/server/pkg/db/queries/project.sql
index a399bd78e7..7f8d8c0bae 100644
--- a/server/pkg/db/queries/project.sql
+++ b/server/pkg/db/queries/project.sql
@@ -5,10 +5,6 @@ WHERE workspace_id = $1
AND (sqlc.narg('priority')::text IS NULL OR priority = sqlc.narg('priority'))
ORDER BY created_at DESC;
--- name: GetProject :one
-SELECT * FROM project
-WHERE id = $1;
-
-- name: GetProjectInWorkspace :one
SELECT * FROM project
WHERE id = $1 AND workspace_id = $2;
diff --git a/server/pkg/db/queries/project_resource.sql b/server/pkg/db/queries/project_resource.sql
index 088b44171b..7050fecfe2 100644
--- a/server/pkg/db/queries/project_resource.sql
+++ b/server/pkg/db/queries/project_resource.sql
@@ -3,6 +3,14 @@ SELECT * FROM project_resource
WHERE project_id = $1
ORDER BY position ASC, created_at ASC;
+-- name: ListProjectResourcesInWorkspace :many
+-- Workspace-scoped read for the daemon claim path. project_resource carries its
+-- own workspace_id, so a corrupt project reference cannot pull another tenant's
+-- repository URLs or local paths into a claim response.
+SELECT * FROM project_resource
+WHERE project_id = $1 AND workspace_id = $2
+ORDER BY position ASC, created_at ASC;
+
-- name: ListProjectResourcesForProjects :many
SELECT * FROM project_resource
WHERE project_id = ANY(sqlc.arg('project_ids')::uuid[])