Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6622: fix(server): authorize squad activity by task provenance (#7489)
Multica Eve2284420966f1
diff --git a/server/cmd/multica/cmd_squad.go b/server/cmd/multica/cmd_squad.goindex 1be625b0f5..2b30e2b5e8 100644--- a/server/cmd/multica/cmd_squad.go+++ b/server/cmd/multica/cmd_squad.go@@ -450,7 +450,13 @@ Outcome must be one of:failed — leader encountered an errorThis command is intended to be called by squad leader agents after each-trigger to record their decision in the issue timeline.`,+trigger to record their decision in the issue timeline.++Pass the issue the current turn is running on. That issue does not need to+be assigned to your squad — authorization comes from the leader task itself,+so @squad mentions on an individually owned issue and leader tasks bound to a+child issue both record fine. A leader woken by a stage barrier runs on the+parent issue, so record against the parent.`,Args: exactArgs(2),RunE: runSquadActivity,}diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 818d8d6559..5b89fd30f3 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -692,7 +692,7 @@ func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("2. Catch up on the comment history — this is mandatory, not optional — in two bounded reads, never one bulk pull: scan every thread cheaply (`--roots-only --summary --compact`), then expand only the threads that matter (`--thread <id> --tail 30 --compact`). Earlier comments often carry context the issue body lacks. Skipping this step is the most common cause of agents acting on stale or incomplete instructions — so always run the scan, even when the trigger looks self-contained. When a comment triggered this run, the per-turn user message names the thread to expand first; the scan is how you decide whether any OTHER thread is also relevant.\n")b.WriteString("3. If any part of what this turn will produce is what the issue itself asks for, set `in_progress` FIRST (skip when the issue is already in an `in_progress`-category status, or when your Agent Identity forbids status writes): the board should show the issue being worked while you work, not only after. The kind of activity — research, design, planning, review — never decides this; only whether the output is part of THIS issue's ask. Then complete the task within your Agent Identity boundaries (`## Instruction Precedence` lists the actions Agent Identity can forbid). If your role is delegation-only, perform the allowed delegation work and stop once that outcome is delivered. Before self-assigning, check the target issue's comment history for an existing claim and any `## Active sibling runs` block; when assignment or status only records ownership/progress for work already underway, pass `--no-start` on every such command (the default start behavior is for handing off fresh work).\n")if ctx.IsSquadLeader {- b.WriteString("4. **Post your final results as a comment** (unless your outcome is `no_action` — in that case, calling `multica squad activity <issue-id> no_action --reason \"...\"` alone is sufficient; you MUST exit without posting any comment. DO NOT post a comment announcing no_action or saying you are exiting silently): post it with `multica issue comment add` using the platform-correct non-inline mode from ## Comment Formatting (never inline `--content`). When the per-turn user message carries a triggering comment, reply in its thread with the `--parent` value it gives you for THIS turn (never one from an earlier turn); when it lists several threads, post one reply per thread. With no triggering comment, post a new top-level comment. Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered.\n")+ b.WriteString("4. **Post your final results as a comment** (unless your outcome is `no_action` — in that case, calling `multica squad activity <issue-id> no_action --reason \"...\"` alone is sufficient; you MUST exit without posting any comment. DO NOT post a comment announcing no_action or saying you are exiting silently. If that call fails, the exception lapses: post exactly one short comment with the outcome instead): post it with `multica issue comment add` using the platform-correct non-inline mode from ## Comment Formatting (never inline `--content`). When the per-turn user message carries a triggering comment, reply in its thread with the `--parent` value it gives you for THIS turn (never one from an earlier turn); when it lists several threads, post one reply per thread. With no triggering comment, post a new top-level comment. Your results are only visible to the user if posted via this CLI call; text in your terminal or run logs is NOT delivered.\n")} else {b.WriteString("4. **Post your final results as a comment — this step is mandatory**: post it with `multica issue comment add` using the platform-correct non-inline mode from ## Comment Formatting (never inline `--content`). When the per-turn user message carries a triggering comment, reply in its thread with the `--parent` value it gives you for THIS turn (never one from an earlier turn); when it lists several threads, post one reply per thread. With no triggering comment, post a new top-level comment. `## Output` states why this call is the only delivery channel.\n")}@@ -867,7 +867,7 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {}default:if ctx.IsSquadLeader {- b.WriteString("⚠️ **Final results MUST be delivered via `multica issue comment add`** — unless your outcome is `no_action`. When you evaluate a trigger and decide no action is needed, calling `multica squad activity <issue-id> no_action --reason \"...\"` alone is sufficient; you MUST exit without posting any comment. DO NOT post a comment that announces no_action, acknowledges another agent, or says you are exiting silently — such comments are noise. For all other outcomes (`action`, `failed`), a comment is still mandatory.\n\n")+ b.WriteString("⚠️ **Final results MUST be delivered via `multica issue comment add`** — unless your outcome is `no_action`. When you evaluate a trigger and decide no action is needed, calling `multica squad activity <issue-id> no_action --reason \"...\"` alone is sufficient; you MUST exit without posting any comment. DO NOT post a comment that announces no_action, acknowledges another agent, or says you are exiting silently — such comments are noise. For all other outcomes (`action`, `failed`), a comment is still mandatory. If the `squad activity` call itself fails, the no_action exception does not apply — post exactly one short comment with the outcome so the decision is not lost, and no more than one.\n\n")} else {b.WriteString("⚠️ **Final results MUST be delivered via `multica issue comment add`.** The user does NOT see your terminal output or run logs — only comments on the issue.\n\n")}diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex ec619ac983..893053b173 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -396,7 +396,7 @@ func buildCommentPrompt(task Task, provider string) string {task.IssueID)}if taskIsSquadLeader(task) {- fmt.Fprintf(&b, "⚠️ **Squad leader no_action rule:** If you decide no action is needed, call `multica squad activity %s no_action --reason \"...\"` and EXIT. DO NOT post any comment — not even one that says \"no action needed\" or \"exiting silently\". The squad activity call records your decision; a comment is redundant noise.\n\n", task.IssueID)+ fmt.Fprintf(&b, "⚠️ **Squad leader no_action rule:** If you decide no action is needed, call `multica squad activity %s no_action --reason \"...\"` and EXIT. DO NOT post any comment — not even one that says \"no action needed\" or \"exiting silently\". The squad activity call records your decision; a comment is redundant noise. The comment prohibition is conditional on that call SUCCEEDING: if it exits non-zero, your decision has no trace anywhere, so post exactly ONE short comment stating the outcome and the error instead of exiting silently. That failure comment is this turn's only comment — it does not license a second one.\n\n", task.IssueID)}}fmt.Fprintf(&b, "Start by running `multica issue get %s --output json` to understand your task, then decide how to proceed.\n\n", task.IssueID)diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex 2738bc82d8..02b21e39c2 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -236,6 +236,37 @@ func TestBuildQuickCreatePromptParentPinning(t *testing.T) {}}+// TestBuildPromptSquadLeaderNoActionFailureFallback locks the escape hatch added+// in MUL-6622 / GH #7487. The comment prohibition is conditional on the+// `squad activity` call succeeding — the server only rejects a leader comment+// once the no_action activity exists — so a failed call must not end the turn in+// silence. The fallback is capped at ONE comment so it cannot collide with the+// one-comment-per-turn rule.+func TestBuildPromptSquadLeaderNoActionFailureFallback(t *testing.T) {+ out := BuildPrompt(Task{+ IssueID: "issue-123",+ TriggerCommentID: "comment-456",+ TriggerCommentContent: "LGTM",+ TriggerAuthorType: "member",+ TriggerAuthorName: "Bohan",+ IsLeaderTask: true,+ LeaderRoleResolved: true,+ Agent: &AgentData{+ Instructions: "Some instructions\n\n## Squad Operating Protocol\n\nYou are the LEADER...",+ },+ }, "claude")++ for _, want := range []string{+ "conditional on that call SUCCEEDING",+ "post exactly ONE short comment",+ "does not license a second one",+ } {+ if !strings.Contains(out, want) {+ t.Errorf("squad leader no_action rule must contain %q, got:\n%s", want, out)+ }+ }+}+// TestBuildPromptSquadLeaderNoActionForMemberTrigger verifies that the// squad leader no_action prohibition is injected in the per-turn prompt// regardless of whether the triggering comment was posted by an agent ordiff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.goindex 0171adb534..3d6f5e190c 100644--- a/server/internal/handler/squad.go+++ b/server/internal/handler/squad.go@@ -11,6 +11,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/logger"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -946,6 +947,17 @@ func (h *Handler) UpdateSquadMemberRole(w http.ResponseWriter, r *http.Request)// RecordSquadLeaderEvaluation records a squad leader's evaluation decision// into the unified activity_log. Called by the leader agent via CLI after// each trigger to record whether it took action, stayed silent, or failed.+//+// The leader-turn check is task-provenance based (is_leader_task + squad_id on+// the X-Task-ID row), the SAME source the claim path uses to inject the squad+// briefing and the mandatory-recording instruction. The target issue's own+// assignee is deliberately NOT consulted: leaders legitimately run on issues+// that are not squad-assigned. See MUL-6622 / GH #7487.+//+// Two authorization gates, in this order: the caller must own the task, and must+// still be the squad's leader. The first is what makes it safe to quote the+// task's issue id in an error; the second is what keeps a claim-downgraded run+// (see the comment at gate 2) from writing a leader verdict.func (h *Handler) RecordSquadLeaderEvaluation(w http.ResponseWriter, r *http.Request) {issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))if !ok {@@ -966,38 +978,102 @@ func (h *Handler) RecordSquadLeaderEvaluation(w http.ResponseWriter, r *http.Reqreturn}- // The issue must be assigned to a squad.- if !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {- writeError(w, http.StatusBadRequest, "issue is not assigned to a squad")+ // Authority for "is this run a squad leader turn" is the TASK ROW, not the+ // target issue's assignee (MUL-6622 / GH #7487). is_leader_task + squad_id+ // are stamped at enqueue time and are exactly what the claim path keys the+ // squad briefing and the mandatory-`squad activity` instruction off+ // (handler/daemon.go, daemon/prompt.go taskIsSquadLeader). Gating this+ // endpoint on issue.assignee_type == "squad" instead made the recording+ // call unsatisfiable on the paths where a leader legitimately runs on a+ // non-squad-assigned issue — a `@squad` mention on an issue owned by a+ // plain agent, or a leader task bound to a child issue — and because the+ // no_action instruction forbids substituting a comment, the decision left+ // no trace at all.+ //+ // Check ORDER is load-bearing. Every rejection below the ownership gate may+ // quote task-derived ids; every rejection above it must not. `GetAgentTask`+ // is a global lookup by id, so tenant scoping (GetAgentTaskInWorkspace,+ // which joins the owning agent's workspace) and the "caller owns this task"+ // gate both come first — otherwise an unrelated task id, probed through an+ // issue the caller can legitimately read, would echo back a foreign+ // workspace's issue id.+ taskID := r.Header.Get("X-Task-ID")+ taskUUID, ok := parseUUIDOrBadRequest(w, taskID, "task id")+ if !ok {return}-- squad, err := h.Queries.GetSquadInWorkspace(r.Context(), db.GetSquadInWorkspaceParams{- ID: issue.AssigneeID,+ task, err := h.Queries.GetAgentTaskInWorkspace(r.Context(), db.GetAgentTaskInWorkspaceParams{+ ID: taskUUID,WorkspaceID: issue.WorkspaceID,})- if err != nil {- writeError(w, http.StatusNotFound, "squad not found")+ if err != nil || !task.IssueID.Valid {+ writeError(w, http.StatusBadRequest, "task does not belong to issue")return}- // Security: only the squad leader agent can record evaluations.+ // Security gate 1: the caller must be the agent this task was enqueued for.workspaceID := uuidToString(issue.WorkspaceID)userID := requestUserID(r)actorType, actorID := h.resolveActor(r, userID, workspaceID)- if actorType != "agent" || actorID != uuidToString(squad.LeaderID) {+ if actorType != "agent" || !task.AgentID.Valid || actorID != uuidToString(task.AgentID) {writeError(w, http.StatusForbidden, "only the squad leader agent can record evaluations")return}- taskID := r.Header.Get("X-Task-ID")- taskUUID, ok := parseUUIDOrBadRequest(w, taskID, "task id")- if !ok {+ // Past the ownership gate, naming the task's own issue is safe — and useful:+ // a leader woken by a stage barrier / child-done callback runs on the PARENT+ // issue, so recording against the child it just read is the common mistake.+ if uuidToString(task.IssueID) != uuidToString(issue.ID) {+ writeError(w, http.StatusBadRequest,+ "task does not belong to issue; record the evaluation on issue "+uuidToString(task.IssueID)+" (the issue this task is running on)")return}- task, err := h.Queries.GetAgentTask(r.Context(), taskUUID)- if err != nil || !task.IssueID.Valid || uuidToString(task.IssueID) != uuidToString(issue.ID) {- writeError(w, http.StatusBadRequest, "task does not belong to issue")+ // Narrowing vs. the old behavior: a leader agent running a NON-leader task+ // on a squad-assigned issue (for example a same-squad worker task) used to+ // be accepted here. It is rejected now — it is not running as the leader,+ // and the runtime only mandates this call when taskIsSquadLeader(task).+ if !task.IsLeaderTask {+ writeError(w, http.StatusBadRequest, "task is not a squad leader task")+ return+ }+ if !task.SquadID.Valid {+ // Pre-MUL-3730 rows can be leader tasks without a stamped squad. Log it+ // rather than failing silently from the operator's point of view.+ slog.Warn("squad leader evaluation: leader task has no squad_id",+ append(logger.RequestAttrs(r),+ "task_id", uuidToString(task.ID),+ "issue_id", uuidToString(issue.ID),+ )...)+ writeError(w, http.StatusBadRequest, "leader task has no squad_id")+ return+ }++ squad, err := h.Queries.GetSquadInWorkspace(r.Context(), db.GetSquadInWorkspaceParams{+ ID: task.SquadID,+ WorkspaceID: issue.WorkspaceID,+ })+ if err != nil {+ writeError(w, http.StatusNotFound, "squad not found")+ return+ }++ // Security gate 2: the caller must still be this squad's leader.+ //+ // `is_leader_task` on the row records the enqueue-time INTENT, which is not+ // always the role the claim actually delivered: when the leader was swapped+ // between enqueue and claim, the claim path clears resp.IsLeaderTask and the+ // run proceeds as an ordinary agent turn, while the row keeps+ // is_leader_task = true (handler/daemon.go, "claim delivered as a non-leader+ // task"). Trusting the row alone would let such a downgraded run write a+ // leader verdict — and, on no_action, suppress its own comment. Until the+ // delivered role is persisted, the live leader check is the only thing that+ // distinguishes the two, so it stays.+ //+ // Cost of the conservative choice: a leader rotated away MID-run is refused+ // here. That no longer means silence — the injected rules now tell a leader+ // whose recording call failed to leave a short comment instead.+ if actorID != uuidToString(squad.LeaderID) {+ writeError(w, http.StatusForbidden, "only the squad leader agent can record evaluations")return}@@ -1013,9 +1089,13 @@ func (h *Handler) RecordSquadLeaderEvaluation(w http.ResponseWriter, r *http.ReqWorkspaceID: issue.WorkspaceID,IssueID: issue.ID,ActorType: pgtype.Text{String: "agent", Valid: true},- ActorID: squad.LeaderID,- Action: "squad_leader_evaluated",- Details: details,+ // task.AgentID, not squad.LeaderID: the no_action comment suppression+ // lookup matches actor_id against task.agent_id+ // (service.HasSquadLeaderNoActionEvaluationForTask), so this column has+ // to carry the task's agent for suppression to find the row at all.+ ActorID: task.AgentID,+ Action: "squad_leader_evaluated",+ Details: details,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to record evaluation")diff --git a/server/internal/handler/squad_briefing.go b/server/internal/handler/squad_briefing.goindex 6c5d870b3b..04fdf44329 100644--- a/server/internal/handler/squad_briefing.go+++ b/server/internal/handler/squad_briefing.go@@ -57,6 +57,13 @@ Your responsibilities, in order:` + "`" + `failed` + "`" + ` (you hit an error).This is mandatory on every turn — it records your decision in theissue timeline so humans can see you evaluated the trigger.+ Record it against the issue THIS turn is running on (the issue id in+ your task context). It does not need to be assigned to your squad.+ If the call fails, make sure the turn still leaves a record, without+ breaking the one-comment-per-turn rule: post a short comment with the+ outcome and the error ONLY if you have not already commented this turn+ (the no_action case). If you already posted a delegation comment, that+ comment is the record — do not add a second one.4. **Stop after dispatching.** Once your delegation comment is postedand evaluation recorded, end your turn. Do not continue working,do not write code, do not open files. You will be re-triggered@@ -130,7 +137,10 @@ const squadOperatingProtocolHardRules = `Hard rules:explaining the gap (and @mention the issue's reporter if possible)rather than silently doing the work.- ALWAYS call ` + "`" + `multica squad activity` + "`" + ` before ending your turn —- even when the outcome is no_action.+ even when the outcome is no_action. If it errors on a turn where you+ posted no comment, leave one short comment instead; never let an+ evaluation end with no record at all, and never post a second comment+ just to report the error.- A child issue you create with ` + "`" + `--status todo` + "`" + ` and an agent assigneealready fires that agent automatically — the assignment IS the trigger.If you also @mention the same agent on this parent issue for the samediff --git a/server/internal/handler/squad_briefing_test.go b/server/internal/handler/squad_briefing_test.goindex 83f1d24a28..c0007c4b3a 100644--- a/server/internal/handler/squad_briefing_test.go+++ b/server/internal/handler/squad_briefing_test.go@@ -13,6 +13,31 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")+// TestSquadOperatingProtocolRecordsAgainstTheTurnsIssue locks the recording+// contract the protocol teaches (MUL-6622 / GH #7487): record against the issue+// this turn runs on — squad assignment of that issue is irrelevant — and, when+// the call fails, leave a trace WITHOUT breaking one-comment-per-turn. The+// conditional matters: on the `action` path a delegation comment already exists,+// so an unconditional "post a comment on failure" would demand a second one.+func TestSquadOperatingProtocolRecordsAgainstTheTurnsIssue(t *testing.T) {+ for _, ownsStatus := range []bool{true, false} {+ compact := strings.Join(strings.Fields(squadOperatingProtocolFor(ownsStatus)), " ")+ for _, want := range []string{+ "Record it against the issue THIS turn is running on",+ "It does not need to be assigned to your squad",+ "without breaking the one-comment-per-turn rule",+ "ONLY if you have not already commented this turn",+ "do not add a second one",+ "never post a second comment just to report the error",+ } {+ if !strings.Contains(compact, want) {+ t.Errorf("owns_status=%v: expected squad operating protocol to contain %q\n--- protocol ---\n%s",+ ownsStatus, want, compact)+ }+ }+ }+}+// TestSquadOperatingProtocolOwnsParentStatus locks the parent-issue status// contract: first dispatch moves todo→in_progress and stays there; only a// later confirmation of overall completion may advance to in_review; done isdiff --git a/server/internal/handler/squad_evaluation_provenance_test.go b/server/internal/handler/squad_evaluation_provenance_test.gonew file mode 100644index 0000000000..51bf6eb50e--- /dev/null+++ b/server/internal/handler/squad_evaluation_provenance_test.go@@ -0,0 +1,291 @@+package handler++import (+ "context"+ "net/http"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++// These tests pin the authorization contract of RecordSquadLeaderEvaluation+// after MUL-6622 / GH #7487. Two gates, in order: the caller owns the task, and+// the caller is still the squad's leader. The target issue's own assignee is+// deliberately not consulted.++type squadEvalFixture struct {+ SquadID string+ LeaderID string+ OtherID string+ SquadIssueID string // issue assigned to the squad+}++func newSquadEvalFixture(t *testing.T) squadEvalFixture {+ t.Helper()++ leaderID := createHandlerTestAgent(t, "Squad Eval Leader", nil)+ otherID := createHandlerTestAgent(t, "Squad Eval Other", nil)+ squadID := dbfx.Squad(t, "Squad Eval", leaderID)+ issueID := dbfx.Issue(t, "squad eval owner issue", testutil.Cols{+ "assignee_type": "squad",+ "assignee_id": squadID,+ })++ return squadEvalFixture{+ SquadID: squadID,+ LeaderID: leaderID,+ OtherID: otherID,+ SquadIssueID: issueID,+ }+}++// leaderTask seeds a running task bound to issueID. isLeaderTask / squadID carry+// the exact provenance under test; an empty squadID leaves squad_id NULL.+func leaderTask(t *testing.T, agentID, issueID string, isLeaderTask bool, squadID string) string {+ t.Helper()++ cols := testutil.Cols{+ "runtime_id": handlerTestRuntimeID(t),+ "status": "running",+ "issue_id": issueID,+ "started_at": testutil.Raw("now()"),+ "is_leader_task": isLeaderTask,+ }+ if squadID != "" {+ cols["squad_id"] = squadID+ }+ return dbfx.Task(t, agentID, cols)+}++func evaluationRequest(issueID, agentID, taskID, outcome string) *http.Request {+ return testutil.WithHeaders(+ testutil.WithURLParams(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/squad-evaluated",+ map[string]any{"outcome": outcome, "reason": "test reason"}),+ "id", issueID,+ ),+ "X-Agent-ID", agentID,+ "X-Task-ID", taskID,+ )+}++type recordedEvaluation struct {+ ActorID string+ SquadID string+ Outcome string+}++func loadEvaluations(t *testing.T, issueID string) []recordedEvaluation {+ t.Helper()++ rows, err := testPool.Query(context.Background(), `+ SELECT actor_id, details->>'squad_id', details->>'outcome'+ FROM activity_log+ WHERE issue_id = $1 AND action = 'squad_leader_evaluated'+ ORDER BY created_at ASC+ `, issueID)+ if err != nil {+ t.Fatalf("load evaluations: %v", err)+ }+ defer rows.Close()++ var out []recordedEvaluation+ for rows.Next() {+ var e recordedEvaluation+ if err := rows.Scan(&e.ActorID, &e.SquadID, &e.Outcome); err != nil {+ t.Fatalf("scan evaluation: %v", err)+ }+ out = append(out, e)+ }+ return out+}++// The regression: a leader task on an issue owned by an individual agent (the+// `@squad`-mention path) used to be rejected with "issue is not assigned to a+// squad", dropping the decision entirely.+func TestRecordSquadLeaderEvaluation_AcceptedOnNonSquadAssignedIssue(t *testing.T) {+ fx := newSquadEvalFixture(t)+ issueID := dbfx.Issue(t, "agent-owned issue", testutil.Cols{+ "assignee_type": "agent",+ "assignee_id": fx.OtherID,+ })+ taskID := leaderTask(t, fx.LeaderID, issueID, true, fx.SquadID)++ testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,+ evaluationRequest(issueID, fx.LeaderID, taskID, "no_action")).Want(http.StatusCreated)++ got := loadEvaluations(t, issueID)+ if len(got) != 1 {+ t.Fatalf("expected exactly one recorded evaluation, got %d", len(got))+ }+ // actor_id must be the task's agent: the no_action comment suppression+ // lookup matches on task.agent_id.+ if got[0].ActorID != fx.LeaderID {+ t.Fatalf("actor_id: want task agent %s, got %s", fx.LeaderID, got[0].ActorID)+ }+ if got[0].SquadID != fx.SquadID {+ t.Fatalf("details.squad_id: want task squad %s, got %s", fx.SquadID, got[0].SquadID)+ }+ if got[0].Outcome != "no_action" {+ t.Fatalf("outcome: want no_action, got %s", got[0].Outcome)+ }+}++// A child issue the leader itself is running on records fine too — the parent's+// squad assignment is irrelevant to the check.+func TestRecordSquadLeaderEvaluation_AcceptedOnChildIssueBoundTask(t *testing.T) {+ fx := newSquadEvalFixture(t)+ childID := dbfx.Issue(t, "squad child issue", testutil.Cols{+ "assignee_type": "agent",+ "assignee_id": fx.OtherID,+ "parent_issue_id": fx.SquadIssueID,+ })+ taskID := leaderTask(t, fx.LeaderID, childID, true, fx.SquadID)++ testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,+ evaluationRequest(childID, fx.LeaderID, taskID, "action")).Want(http.StatusCreated)++ if got := loadEvaluations(t, childID); len(got) != 1 {+ t.Fatalf("expected one recorded evaluation on the child, got %d", len(got))+ }+}++// Behavior narrowing made explicit: the leader agent running a task that is NOT+// a leader task is not running as the leader, so it may not record.+func TestRecordSquadLeaderEvaluation_RejectsNonLeaderTask(t *testing.T) {+ fx := newSquadEvalFixture(t)+ taskID := leaderTask(t, fx.LeaderID, fx.SquadIssueID, false, fx.SquadID)++ testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,+ evaluationRequest(fx.SquadIssueID, fx.LeaderID, taskID, "no_action")).Want(http.StatusBadRequest)++ if got := loadEvaluations(t, fx.SquadIssueID); len(got) != 0 {+ t.Fatalf("expected no evaluation recorded, got %d", len(got))+ }+}++// A leader task without a stamped squad cannot be attributed to a squad.+func TestRecordSquadLeaderEvaluation_RejectsLeaderTaskWithoutSquadID(t *testing.T) {+ fx := newSquadEvalFixture(t)+ taskID := leaderTask(t, fx.LeaderID, fx.SquadIssueID, true, "")++ testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,+ evaluationRequest(fx.SquadIssueID, fx.LeaderID, taskID, "no_action")).Want(http.StatusBadRequest)++ if got := loadEvaluations(t, fx.SquadIssueID); len(got) != 0 {+ t.Fatalf("expected no evaluation recorded, got %d", len(got))+ }+}++// Recording still binds to the task's own issue, and the error names it — the+// stage-barrier case wakes the leader on the PARENT, so a leader that reaches+// for the child id gets told where to record instead of a dead end. Naming it is+// only safe because the ownership gate has already passed.+func TestRecordSquadLeaderEvaluation_RejectsCrossIssueTaskAndNamesTaskIssue(t *testing.T) {+ fx := newSquadEvalFixture(t)+ childID := dbfx.Issue(t, "stage barrier child", testutil.Cols{+ "assignee_type": "agent",+ "assignee_id": fx.OtherID,+ })+ taskID := leaderTask(t, fx.LeaderID, fx.SquadIssueID, true, fx.SquadID)++ body := testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,+ evaluationRequest(childID, fx.LeaderID, taskID, "no_action")).Want(http.StatusBadRequest).Text()++ if !strings.Contains(body, fx.SquadIssueID) {+ t.Fatalf("expected the error to name the task's issue %s, got %q", fx.SquadIssueID, body)+ }+ if got := loadEvaluations(t, childID); len(got) != 0 {+ t.Fatalf("expected no evaluation recorded on the child, got %d", len(got))+ }+}++// An agent that is not the task's agent may not record on its behalf, and the+// rejection must not disclose anything about that task.+func TestRecordSquadLeaderEvaluation_RejectsForeignAgentWithoutLeakingTaskIssue(t *testing.T) {+ fx := newSquadEvalFixture(t)+ leaderOnly := dbfx.Issue(t, "leader-only issue", testutil.Cols{+ "assignee_type": "squad",+ "assignee_id": fx.SquadID,+ })+ taskID := leaderTask(t, fx.LeaderID, leaderOnly, true, fx.SquadID)++ body := testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,+ evaluationRequest(fx.SquadIssueID, fx.OtherID, taskID, "no_action")).Want(http.StatusForbidden).Text()++ if strings.Contains(body, leaderOnly) {+ t.Fatalf("403 body leaked the task's issue id %s: %q", leaderOnly, body)+ }+ if got := loadEvaluations(t, fx.SquadIssueID); len(got) != 0 {+ t.Fatalf("expected no evaluation recorded, got %d", len(got))+ }+}++// Tenant isolation: a task id from another workspace must be unreadable through+// an issue the caller legitimately owns, and its issue id must not appear in the+// response. GetAgentTask is a global lookup, so the workspace-scoped query plus+// the ownership gate are what stop the probe.+func TestRecordSquadLeaderEvaluation_RejectsForeignWorkspaceTaskWithoutLeakingItsIssue(t *testing.T) {+ fx := newSquadEvalFixture(t)++ foreignUser := dbfx.User(t, "Squad Eval Foreign User", "[email protected]")+ foreignWorkspace := dbfx.Workspace(t, "Squad Eval Foreign", "squad-eval-foreign")+ dbfx.Member(t, foreignWorkspace, foreignUser, "owner")+ foreignRuntime := dbfx.Runtime(t, "Squad Eval Foreign Runtime", testutil.Cols{+ "workspace_id": foreignWorkspace,+ "owner_id": foreignUser,+ })+ foreignAgent := dbfx.Agent(t, "Squad Eval Foreign Agent", foreignRuntime, testutil.Cols{+ "workspace_id": foreignWorkspace,+ "owner_id": foreignUser,+ })+ foreignSquad := dbfx.Squad(t, "Squad Eval Foreign Squad", foreignAgent, testutil.Cols{+ "workspace_id": foreignWorkspace,+ "creator_id": foreignUser,+ })+ foreignIssue := dbfx.Issue(t, "foreign workspace issue", testutil.Cols{+ "workspace_id": foreignWorkspace,+ "creator_id": foreignUser,+ "assignee_type": "squad",+ "assignee_id": foreignSquad,+ })+ foreignTask := dbfx.Task(t, foreignAgent, testutil.Cols{+ "runtime_id": foreignRuntime,+ "status": "running",+ "issue_id": foreignIssue,+ "started_at": testutil.Raw("now()"),+ "is_leader_task": true,+ "squad_id": foreignSquad,+ })++ body := testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,+ evaluationRequest(fx.SquadIssueID, fx.LeaderID, foreignTask, "no_action")).+ Want(http.StatusBadRequest).Text()++ if strings.Contains(body, foreignIssue) {+ t.Fatalf("rejection leaked a foreign workspace issue id %s: %q", foreignIssue, body)+ }+ if got := loadEvaluations(t, fx.SquadIssueID); len(got) != 0 {+ t.Fatalf("expected no evaluation recorded, got %d", len(got))+ }+}++// The claim path clears the leader role when the leader was swapped before the+// claim, but leaves is_leader_task = true on the row. The row therefore records+// enqueue-time intent, not the delivered role, so a run that was downgraded to+// an ordinary agent turn must not be able to write a leader verdict here.+func TestRecordSquadLeaderEvaluation_RejectsAfterLeaderChange(t *testing.T) {+ fx := newSquadEvalFixture(t)+ taskID := leaderTask(t, fx.LeaderID, fx.SquadIssueID, true, fx.SquadID)++ newLeader := createHandlerTestAgent(t, "Squad Eval New Leader", nil)+ dbfx.Exec(t, `UPDATE squad SET leader_id = $1 WHERE id = $2`, newLeader, fx.SquadID)++ testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,+ evaluationRequest(fx.SquadIssueID, fx.LeaderID, taskID, "no_action")).Want(http.StatusForbidden)++ if got := loadEvaluations(t, fx.SquadIssueID); len(got) != 0 {+ t.Fatalf("expected no evaluation recorded after a leader change, got %d", len(got))+ }+}diff --git a/server/internal/handler/squad_no_action_test.go b/server/internal/handler/squad_no_action_test.goindex 56bd920312..f91afef76b 100644--- a/server/internal/handler/squad_no_action_test.go+++ b/server/internal/handler/squad_no_action_test.go@@ -9,10 +9,12 @@ import ("testing""github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/testutil")type runningSquadLeaderTaskFixture struct {IssueID string+ SquadID stringLeaderID stringTaskID stringTriggerCommentID string@@ -20,44 +22,30 @@ type runningSquadLeaderTaskFixture struct {func newRunningSquadLeaderTaskFixture(t *testing.T) runningSquadLeaderTaskFixture {t.Helper()- ctx := context.Background()fx := newSquadCommentTriggerFixture(t)issueID := uuidToString(fx.Issue.ID)var runtimeID string- if err := testPool.QueryRow(ctx, `- SELECT runtime_id FROM agent WHERE id = $1- `, fx.LeaderID).Scan(&runtimeID); err != nil {- t.Fatalf("load leader runtime: %v", err)- }-- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)- VALUES ($1, $2, 'member', $3, 'LGTM', 'comment')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("create trigger comment: %v", err)- }-- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, trigger_comment_id,- status, priority, started_at- )- VALUES ($1, $2, $3, $4, 'running', 0, now())- RETURNING id- `, fx.LeaderID, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("create running squad leader task: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent WHERE id = $1`, fx.LeaderID).Scan(&runtimeID)++ triggerCommentID := dbfx.Comment(t, issueID, "LGTM")++ // is_leader_task + squad_id are what RecordSquadLeaderEvaluation authorizes+ // against (MUL-6622); a leader task without them is not a leader turn.+ taskID := dbfx.Task(t, fx.LeaderID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "trigger_comment_id": triggerCommentID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ "is_leader_task": true,+ "squad_id": fx.SquadID,})return runningSquadLeaderTaskFixture{IssueID: issueID,+ SquadID: fx.SquadID,LeaderID: fx.LeaderID,TaskID: taskID,TriggerCommentID: triggerCommentID,diff --git a/server/internal/service/builtin_skills/multica-squads/SKILL.md b/server/internal/service/builtin_skills/multica-squads/SKILL.mdindex 3cd63dc496..f608639bd0 100644--- a/server/internal/service/builtin_skills/multica-squads/SKILL.md+++ b/server/internal/service/builtin_skills/multica-squads/SKILL.md@@ -78,6 +78,20 @@ multica squad activity <issue-id> action|no_action|failed --reason "<why>" --out`activity` is a write: it records the leader's evaluation decision on an issue.Use it only when acting as the squad leader after evaluating a trigger.+Which issue it accepts: **the issue your current turn is running on**. The+target issue does NOT need to be assigned to your squad — a `@squad` mention on+an issue owned by an individual agent, or a leader task bound to a child issue,+all record fine. What the server checks is your task row (`is_leader_task` plus+a stamped `squad_id`), not the issue's assignee. A leader woken by a stage+barrier runs on the PARENT issue, so record against the parent, not the child+you just read; passing an unrelated issue id is rejected and the error names the+issue you should have used.++If the call fails, do not exit silently — the comment prohibition on `no_action`+only applies once the recording succeeded. Post one short comment with the+outcome instead, and only when this turn has not already commented: on the+`action` path your delegation comment is already that record.+Issue/comment commands often needed with squads:```bashdiff --git a/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md b/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.mdindex 6647342671..9b0de9a9b4 100644--- a/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md+++ b/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md@@ -122,6 +122,47 @@ Contracts:members carry no skills segment (squad_briefing.go renderMemberRow);- no traced behavior injects `instructions` into every squad member.+## Leader Evaluation Recording++Source:++```text+server/internal/handler/squad.go # RecordSquadLeaderEvaluation ~949+server/cmd/multica/cmd_squad.go # runSquadActivity ~459+server/internal/service/squad_no_action.go # HasSquadLeaderNoActionEvaluationForTask+server/internal/handler/comment.go # no_action comment rejection ~1851+```++Contracts:++- authority is the TASK row from `X-Task-ID`, not the issue's assignee:+ `task.issue_id == issue.id`, `task.is_leader_task`, `task.squad_id` valid.+ The squad is loaded from `task.squad_id`; the target issue may be assigned to+ anyone (MUL-6622 / GH #7487). The pre-fix `issue.assignee_type == "squad"`+ gate diverged from the claim-side `is_leader_task` gate and made the call+ unsatisfiable on `@squad`-on-agent-issue and leader-task-on-child paths;+- the task is loaded with `GetAgentTaskInWorkspace`, not `GetAgentTask`: the+ latter is a global lookup by id, and the rejection path quotes the task's+ issue id. Check order is load-bearing — tenant scope, then "caller owns this+ task", and only then any message naming a task-derived id;+- two authorization gates: `task.agent_id == caller`, then+ `squad.leader_id == caller`. The second is required because+ `is_leader_task` on the row is enqueue-time INTENT: when the leader was+ swapped before the claim, `handler/daemon.go` clears `resp.IsLeaderTask` and+ runs the task as an ordinary agent turn while the row keeps+ `is_leader_task = true`. Without the live check, such a downgraded run could+ write a leader verdict and suppress its own comment. Removing this gate+ requires persisting the role the claim actually delivered;+- `activity_log.actor_id` is `task.agent_id`, not `squad.leader_id`: the+ `no_action` comment suppression lookup matches on `task.agent_id`, so the+ live leader id there would silently break suppression;+- a leader agent running a NON-leader task is rejected — it is not running as+ the leader, and the runtime only mandates the call for `is_leader_task`;+- the `no_action` comment prohibition is conditional on this write succeeding+ (comment.go:1851 checks the activity exists), so the injected instructions+ tell leaders to fall back to a comment when the call errors — capped at one+ comment, and only when the turn has not already commented.+## Issue AssignmentSource: