Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5811: fix(squad) derive leader role from wire fields, not instructions text (#6519)
Bohan Jiang73ab498d1d4b
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex bbe88bf506..3b62bda538 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -5658,7 +5658,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iAutopilotTriggerPayload: strings.TrimSpace(string(task.AutopilotTriggerPayload)),QuickCreatePrompt: task.QuickCreatePrompt,HandoffNote: task.HandoffNote,- IsSquadLeader: strings.Contains(instructions, "## Squad Operating Protocol"),+ IsSquadLeader: taskIsSquadLeader(task),RequestingUserName: task.RequestingUserName,RequestingUserProfileDescription: task.RequestingUserProfileDescription,InitiatorType: task.InitiatorType,diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex e608148758..38193b6036 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -1162,6 +1162,8 @@ func TestBuildPromptSquadLeaderNoActionProhibition(t *testing.T) {TriggerCommentContent: "Progress update: tests passing.",TriggerAuthorType: "agent",TriggerAuthorName: "Worker",+ IsLeaderTask: true,+ LeaderRoleResolved: true,Agent: &AgentData{Name: "Leader",Instructions: "You lead the team.\n\n## Squad Operating Protocol\n\nYou are the LEADER.",@@ -5042,6 +5044,8 @@ func TestBuildPromptSquadLeaderReplyCommandCarvesOutNoAction(t *testing.T) {TriggerCommentContent: "team update posted",TriggerAuthorType: "member",TriggerAuthorName: "Bohan",+ IsLeaderTask: true,+ LeaderRoleResolved: true,Agent: &AgentData{Name: "Lead",Instructions: "Some instructions\n\n## Squad Operating Protocol\n\nYou are the LEADER...",@@ -5078,6 +5082,8 @@ func TestBuildPromptSquadLeaderMultiThreadCarvesOutNoAction(t *testing.T) {CoalescedComments: []CoalescedCommentData{{ID: "comment-8", ThreadID: "thread-A", Content: "first update"},},+ IsLeaderTask: true,+ LeaderRoleResolved: true,Agent: &AgentData{Name: "Lead",Instructions: "Some instructions\n\n## Squad Operating Protocol\n\nYou are the LEADER...",@@ -5116,6 +5122,7 @@ func TestBuildPromptSquadLeaderMultiThreadCarvesOutNoAction(t *testing.T) {}ordinaryTask := leaderTask+ ordinaryTask.IsLeaderTask = falseordinaryTask.Agent = &AgentData{Name: "Reg", Instructions: "You are a regular agent."}ordinary := BuildPrompt(ordinaryTask, "claude")if !strings.Contains(ordinary, ". Post ONE reply per thread") {diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 4fa2fe28a6..5a5e43ddc2 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -141,7 +141,7 @@ type TaskContextForEnv struct {AutopilotTriggerPayload stringQuickCreatePrompt string // non-empty for quick-create tasksHandoffNote string // assignment handoff instruction; rendered into issue_context.md (MUL-3375)- IsSquadLeader bool // true when the agent is acting as a squad leader (may exit silently on no_action)+ IsSquadLeader bool // true when THIS TASK runs the agent in the squad-leader role (may exit silently on no_action); derived from the claim's is_leader_task / squad_id, never sniffed from instructions text (MUL-5811)// WorkspaceContext is the workspace-level system prompt (workspace.context// in the DB). Rendered into the brief as `## Workspace Context` when// non-empty so every agent in the workspace sees the same shared context,diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 916d7d3f8f..981debf039 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -270,9 +270,11 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>]` — repository checkout on a dedicated branch.\n\n")// Squad maintenance is squad-leader surface: an agent that leads no squad// has no squad to change roles in, so this shipped to every run as dead- // weight (MUL-5442). IsSquadLeader is agent configuration, not per-run- // state, so gating on it keeps the brief byte-stable across runs of one- // session (MUL-5377) — the same reason the workflow already branches on it.+ // weight (MUL-5442). IsSquadLeader is a PER-TASK role (the daemon derives+ // it from the claim's is_leader_task / squad_id), so gating brief content+ // on it does cost byte-stability across runs of one session whenever the+ // role flips. That is an owner-accepted tradeoff, not an open action item;+ // the decision is recorded in MUL-5811.if ctx.IsSquadLeader {b.WriteString("### Squad maintenance\n")b.WriteString("- `multica squad member set-role <squad-id> --member-id <id> --member-type <agent|member> --role <role> [--output json]` — change role in place (use this instead of remove+add).\n\n")@@ -538,8 +540,9 @@ func writeWorkflowAutopilot(b *strings.Builder, ctx TaskContextForEnv) {// a re-trigger (member update / stage barrier) confirms the overall goal// is met; see the Squad Operating Protocol and child-done system comments.//-// ctx.IsSquadLeader is agent configuration, not per-run state, so branching-// on it does not break byte-stability across runs of one session.+// ctx.IsSquadLeader is a PER-TASK role, not agent configuration: branching on+// it here does move brief bytes when the same agent runs leader one turn and+// worker the next. Owner-accepted tradeoff; decision recorded in MUL-5811.func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("**Turn mode.** The per-turn user message names this run's mode on a line of its own: `Turn mode: Reply.` (respond to the comment that message carries — it brings the triggering comment's id and your `--parent` value) or `Turn mode: Ownership.` (an assignment or status change started this run). Steps 1–6 are shared; then **apply exactly one mode block, the one the user message named** — they differ on issue status. No mode line → Reply mode, do not change the issue status.\n\n")diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.goindex 9aeaa5f3ef..0f3df585ea 100644--- a/server/internal/daemon/execenv/runtime_config_test.go+++ b/server/internal/daemon/execenv/runtime_config_test.go@@ -408,6 +408,44 @@ func TestSquadLeaderIssueWorkflowKeepsParentInProgress(t *testing.T) {}}+// TestProtocolHeadingInInstructionsGetsNoLeaderBrief is the brief-side half of+// the MUL-5811 negative regression. IsSquadLeader now comes from the claim's+// is_leader_task / squad_id, so an ordinary agent that documents a+// "## Squad Operating Protocol" section in its own instructions must get the+// ordinary brief — its instructions rendered verbatim under Agent Identity,+// and not one leader-only branch.+func TestProtocolHeadingInInstructionsGetsNoLeaderBrief(t *testing.T) {+ t.Parallel()++ const instructions = "I write docs about squads.\n\n## Squad Operating Protocol\n\nHow leaders dispatch work..."+ out := buildMetaSkillContent("claude", TaskContextForEnv{+ IssueID: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",+ TriggerCommentID: "bbbbbbbb-cccc-dddd-eeee-ffffffffffff",+ AgentName: "Docs writer",+ AgentInstructions: instructions,+ IsSquadLeader: false,+ })++ if !strings.Contains(out, instructions) {+ t.Fatalf("agent instructions must reach the brief verbatim\n---\n%s", out)+ }+ for _, banned := range []string{+ "### Squad maintenance",+ "multica squad member set-role",+ "Squad leader rule:",+ "multica squad activity",+ `Squad Operating Protocol's "Own the parent issue status"`,+ "After this initial dispatch, leave the parent issue `in_progress`",+ } {+ if strings.Contains(out, banned) {+ t.Fatalf("ordinary-agent brief leaked leader-only content %q\n---\n%s", banned, out)+ }+ }+ if !strings.Contains(out, "**Posting your reply as a comment is mandatory**") {+ t.Fatalf("ordinary-agent brief lost the unconditional reply obligation\n---\n%s", out)+ }+}+// Instruction Precedence belongs to the issue workflow only; the issue-less// kinds must not inherit it. After MUL-5377 it applies to every issue run,// comment-triggered or not, because there is a single issue workflow.diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex f71410b631..fc0efdb609 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -603,13 +603,39 @@ func buildAutopilotPrompt(task Task) string {return b.String()}+// squadBriefingMarker is the first heading of the squad-leader briefing the+// server appends to Instructions. It is ONLY a legacy role signal — see+// taskIsSquadLeader — never a role signal against a current server.+const squadBriefingMarker = "## Squad Operating Protocol"+// taskIsSquadLeader reports whether THIS TASK runs the agent as a squad-// leader, identified (for now) by the squad briefing marker the server-// appends to Instructions on leader tasks. Leadership is a PER-TASK role —-// the same agent can be leader one turn and worker the next — so everything-// gated on this rides the per-turn channel. Making the cached brief fully-// role-independent (and replacing this marker check with an explicit role-// signal) is MUL-5811.+// leader. Leadership is a PER-TASK role — the same agent can be leader one+// turn and worker the next — and a current server says so explicitly on the+// wire: `is_leader_task` for issue-bound leader runs, `squad_id` for+// quick-create runs the squad picker routed to its leader. The claim handler+// sets each field on exactly the responses it injected a briefing into, and+// advertises that it did so with `leader_role_resolved`.+//+// The role used to be inferred by sniffing Instructions for the briefing's+// first heading, which made detection depend on user-writable Markdown: any+// ordinary agent whose own instructions happened to contain that heading was+// promoted to leader and handed the leader rules (mandatory `multica squad+// activity`, silent no_action exit).+//+// The capability gate is load-bearing, not ceremony. Servers without it split+// into two groups, and neither can be read by fields alone. Before #4951 the+// claim response carried no `is_leader_task` at all, so a real leader arrives+// with the full briefing and both fields at zero — reading fields would+// silently demote it to a worker. From #4951 until the capability landed the+// flag IS sent, but nothing yet guaranteed it implies an injected briefing, so+// a true flag can arrive with no roster and no protocol. Absent capability+// therefore means "this server never authoritatively answered the question",+// and the legacy text inference — exactly today's behavior against both+// groups — is the only correct read. Drop this branch once a minimum server+// version is enforced (MUL-5811).func taskIsSquadLeader(task Task) bool {- return task.Agent != nil && strings.Contains(task.Agent.Instructions, "## Squad Operating Protocol")+ if !task.LeaderRoleResolved {+ return task.Agent != nil && strings.Contains(task.Agent.Instructions, squadBriefingMarker)+ }+ return task.IsLeaderTask || task.SquadID != ""}diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex 9132c259be..33bbe21fce 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -249,6 +249,8 @@ func TestBuildPromptSquadLeaderNoActionForMemberTrigger(t *testing.T) {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...",},@@ -271,6 +273,8 @@ func TestBuildPromptSquadLeaderNoActionForAgentTrigger(t *testing.T) {TriggerCommentContent: "Deploy complete.",TriggerAuthorType: "agent",TriggerAuthorName: "deploy-boy",+ IsLeaderTask: true,+ LeaderRoleResolved: true,Agent: &AgentData{Instructions: "Some instructions\n\n## Squad Operating Protocol\n\nYou are the LEADER...",},@@ -281,6 +285,165 @@ func TestBuildPromptSquadLeaderNoActionForAgentTrigger(t *testing.T) {}}+// TestTaskIsSquadLeaderReadsProtocolFields pins the role signal to the wire+// fields a current server sets when (and only when) it injects a squad-leader+// briefing, and pins the legacy fallback to what BOTH pre-capability server+// shapes require: those before #4951 (briefing injected, is_leader_task never+// sent) and those after it (flag sent, but no guarantee a briefing came with+// it).+//+// Two regressions live in this table. The "current" instructions-only row is+// MUL-5811 itself: the previous implementation grepped Instructions for the+// briefing heading, so any agent whose own instructions used that heading was+// promoted to squad leader. The "legacy" rows are the inverse — reading the+// fields unconditionally would demote a real leader on an un-upgraded server+// to a plain worker and drop the whole operating protocol.+func TestTaskIsSquadLeaderReadsProtocolFields(t *testing.T) {+ t.Parallel()++ // What an agent's Instructions look like once the server has appended the+ // briefing — and what an ordinary agent that merely writes about squads+ // looks like. They are indistinguishable by text, which is the point.+ const briefed = "Some instructions\n\n## Squad Operating Protocol\n\nYou are the LEADER..."+ const plain = "You are a regular agent."++ cases := []struct {+ name string+ task Task+ want bool+ }{+ // --- current server: leader_role_resolved advertises that+ // is_leader_task / squad_id are authoritative ---+ {+ name: "current: issue-bound leader task",+ task: Task{LeaderRoleResolved: true, IsLeaderTask: true, Agent: &AgentData{Instructions: briefed}},+ want: true,+ },+ {+ name: "current: quick-create routed through a squad picker",+ task: Task{LeaderRoleResolved: true, SquadID: "5f7f7c12-b579-4c6d-aaa0-8ae1d7e72b61", Agent: &AgentData{Instructions: briefed}},+ want: true,+ },+ {+ name: "current: leader flag without agent payload",+ task: Task{LeaderRoleResolved: true, IsLeaderTask: true},+ want: true,+ },+ {+ name: "current: ordinary agent whose own instructions carry the protocol heading",+ task: Task{LeaderRoleResolved: true, Agent: &AgentData{Instructions: briefed}},+ want: false,+ },+ {+ // Briefing withheld by the claim's defensive gate (squad deleted /+ // leader swapped): the server clears the flag, so no leader role.+ name: "current: withheld briefing leaves no leader signal",+ task: Task{LeaderRoleResolved: true, Agent: &AgentData{Instructions: plain}},+ want: false,+ },+ // --- legacy server: no capability, so the injected briefing is the+ // only evidence of the role that server ever produced ---+ {+ name: "legacy: real leader recognised by the injected briefing",+ task: Task{Agent: &AgentData{Instructions: briefed}},+ want: true,+ },+ {+ name: "legacy: ordinary agent",+ task: Task{Agent: &AgentData{Instructions: plain}},+ want: false,+ },+ {+ // Server in [#4951, this change): it sends is_leader_task but can+ // still withhold the briefing. Without a roster or a protocol+ // there is nothing to lead, so the absent briefing wins.+ name: "legacy: leader flag but briefing withheld",+ task: Task{IsLeaderTask: true, Agent: &AgentData{Instructions: plain}},+ want: false,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := taskIsSquadLeader(tc.task); got != tc.want {+ t.Fatalf("taskIsSquadLeader(%s) = %v, want %v", tc.name, got, tc.want)+ }+ })+ }+}++// TestBuildPromptProtocolHeadingInInstructionsIsNotALeader is the end-to-end+// negative regression for MUL-5811: on a current server, a plain agent that+// happens to document a "## Squad Operating Protocol" section in its own+// instructions must get the ordinary comment prompt — no squad activity+// obligation, no silent-exit licence, and the unconditional reply imperative+// intact.+func TestBuildPromptProtocolHeadingInInstructionsIsNotALeader(t *testing.T) {+ t.Parallel()++ out := BuildPrompt(Task{+ IssueID: "issue-123",+ TriggerCommentID: "comment-456",+ TriggerCommentContent: "please take a look",+ TriggerAuthorType: "member",+ TriggerAuthorName: "Bohan",+ LeaderRoleResolved: true,+ Agent: &AgentData{+ Name: "Docs writer",+ Instructions: "I document squads.\n\n## Squad Operating Protocol\n\nHow leaders dispatch work...",+ },+ }, "claude")++ for _, banned := range []string{+ "Squad leader no_action rule",+ "multica squad activity",+ "DO NOT post any comment",+ "Unless your outcome is `no_action`",+ } {+ if strings.Contains(out, banned) {+ t.Fatalf("ordinary agent prompt leaked squad-leader rule %q\n---\n%s", banned, out)+ }+ }+ if !strings.Contains(out, "Post your reply as a comment") {+ t.Fatalf("ordinary agent prompt lost the unconditional reply imperative\n---\n%s", out)+ }+}++// TestBuildPromptLegacyServerKeepsBriefingBasedLeaderRole is the other half of+// the compatibility contract. A server predating `leader_role_resolved` still+// injects the briefing but never sends is_leader_task on claim (#4951), so an+// upgraded daemon that trusted the fields alone would demote a real squad+// leader to a plain worker and drop the entire operating protocol. Absent+// capability must keep the legacy briefing-marker inference.+func TestBuildPromptLegacyServerKeepsBriefingBasedLeaderRole(t *testing.T) {+ t.Parallel()++ out := BuildPrompt(Task{+ IssueID: "issue-123",+ TriggerCommentID: "comment-456",+ TriggerCommentContent: "LGTM",+ TriggerAuthorType: "member",+ TriggerAuthorName: "Bohan",+ // No LeaderRoleResolved and no IsLeaderTask — an old server sends+ // neither, and the injected briefing is the only evidence it produced.+ Agent: &AgentData{+ Name: "Lead",+ Instructions: "You lead the team.\n\n## Squad Operating Protocol\n\nYou are the LEADER...",+ },+ }, "claude")++ for _, want := range []string{+ "Squad leader no_action rule",+ "multica squad activity",+ "DO NOT post any comment",+ } {+ if !strings.Contains(out, want) {+ t.Fatalf("legacy-server leader prompt lost %q\n---\n%s", want, out)+ }+ }+}+func TestBuildChatPromptAttachmentIDsCanBeBoundToCreatedIssues(t *testing.T) {task := Task{ChatSessionID: "sess-1",diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 6545de3c0f..38c4e4a6fe 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -76,6 +76,7 @@ type Task struct {ProjectDescription string `json:"project_description,omitempty"` // durable project-level context injected into the briefProjectResources []ProjectResourceData `json:"project_resources,omitempty"` // project-scoped resources to expose to the agentIsLeaderTask bool `json:"is_leader_task,omitempty"` // true when executing in the squad-leader coordinator role+ LeaderRoleResolved bool `json:"leader_role_resolved,omitempty"` // server capability: IsLeaderTask/SquadID authoritatively answer "is this a leader run". Absent on servers predating it — those before #4951 never sent is_leader_task at all, later ones send it without this guarantee — so taskIsSquadLeader falls back to the briefing marker for both (MUL-5811)PriorSessionID string `json:"prior_session_id,omitempty"` // Claude session ID from a previous task on this issuePriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on this issuePriorSessionResumeUnavailable bool `json:"prior_session_resume_unavailable,omitempty"` // MUL-5305: server signals a more recent Codex session was withheld (rollout missing) and PriorSessionID (if any) is an older fallback; the run must disclose the continuity gap even if that older session resumes cleanly. Absent/false on old servers.diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 99ded185a7..16e0df0771 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -318,6 +318,7 @@ type AgentTaskResponse struct {MaxAttempts int32 `json:"max_attempts"`ParentTaskID *string `json:"parent_task_id,omitempty"`IsLeaderTask bool `json:"is_leader_task,omitempty"`+ LeaderRoleResolved bool `json:"leader_role_resolved,omitempty"` // claim-only capability, always true here: IsLeaderTask/SquadID authoritatively answer "is this a leader run", so the daemon must not infer the role from briefing text. Servers predating it make no such promise — before #4951 they sent no is_leader_task at all, after it they sent the flag without guaranteeing a briefing — so a daemon seeing no capability keeps the legacy inference. Never rendered into a prompt; see daemon.taskIsSquadLeader (MUL-5811). Mirror field: internal/daemon/types.go, same JSON nameAgent *TaskAgentData `json:"agent,omitempty"`ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // daemon-claim only: per-run app capabilities mounted through runtime MCP overlaysRepos []RepoData `json:"repos,omitempty"`diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex e9431e5737..beb6fd64f6 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1636,6 +1636,12 @@ type claimBuildFailure struct {func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQueue, runtime db.AgentRuntime, runtimeID, runtimeWorkspaceID string) (resp AgentTaskResponse, deliveredCommentIDs []pgtype.UUID, agentSkillCount, builtinSkillCount int, failure *claimBuildFailure) {// Build response with fresh agent data (name + skills + custom_env + custom_args).resp = taskToResponse(*task, runtimeWorkspaceID)+ // Claim-only capability: this server resolves the squad-leader role on the+ // wire (is_leader_task / squad_id), so the daemon must not re-derive it+ // from the briefing text. Set unconditionally — on every claim, leader or+ // not — because its absence is what tells an upgraded daemon it is talking+ // to a server too old to have answered the question (MUL-5811).+ resp.LeaderRoleResolved = truesupportsCoalescedComments := requestHasClientCapability(r, protocol.DaemonCapabilityCoalescedCommentsV1)// Empty-but-non-nil so pgx persists '{}' rather than NULL for tasks without// comment input. Comment tasks replace this with the ids actually embedded@@ -1806,33 +1812,53 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu// (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 resp.Agent != nil && task.IsLeaderTask && 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+ 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,+ )}- 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,+ }+ // 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),)}}diff --git a/server/internal/handler/squad_briefing_claim_test.go b/server/internal/handler/squad_briefing_claim_test.goindex c7ccca2a83..289917361b 100644--- a/server/internal/handler/squad_briefing_claim_test.go+++ b/server/internal/handler/squad_briefing_claim_test.go@@ -10,10 +10,11 @@ import ()// claimAgentInstructionsForTest claims the next queued task for runtimeID and-// returns the claimed task id plus the agent Instructions carried on the claim-// response (the field the squad-leader briefing is injected into). Empty task-// id means no task was claimed.-func claimAgentInstructionsForTest(t *testing.T, runtimeID string) (taskID string, instructions string, raw string) {+// returns the claimed task id, the agent Instructions carried on the claim+// response (the field the squad-leader briefing is injected into), and the+// is_leader_task flag the daemon derives its squad-leader role from+// (MUL-5811). Empty task id means no task was claimed.+func claimAgentInstructionsForTest(t *testing.T, runtimeID string) (taskID string, instructions string, isLeaderTask bool, raw string) {t.Helper()w := httptest.NewRecorder()@@ -28,8 +29,10 @@ func claimAgentInstructionsForTest(t *testing.T, runtimeID string) (taskID strinvar resp struct {Task *struct {- ID string `json:"id"`- Agent *struct {+ ID string `json:"id"`+ IsLeaderTask bool `json:"is_leader_task"`+ LeaderRoleResolved bool `json:"leader_role_resolved"`+ Agent *struct {Instructions string `json:"instructions"`} `json:"agent"`} `json:"task"`@@ -38,13 +41,20 @@ func claimAgentInstructionsForTest(t *testing.T, runtimeID string) (taskID strint.Fatalf("decode claim response: %v", err)}if resp.Task == nil {- return "", "", w.Body.String()+ return "", "", false, w.Body.String()+ }+ // Every claim must advertise the capability, leader or not: its absence is+ // how a daemon detects a server too old to resolve the role, and silently+ // dropping it would send every upgraded daemon back to inferring the role+ // from instructions text — the bug MUL-5811 removed.+ if !resp.Task.LeaderRoleResolved {+ t.Fatalf("claim response must set leader_role_resolved=true: %s", w.Body.String())}var instr stringif resp.Task.Agent != nil {instr = resp.Task.Agent.Instructions}- return resp.Task.ID, instr, w.Body.String()+ return resp.Task.ID, instr, resp.Task.IsLeaderTask, w.Body.String()}// squadBriefingClaimFixture wires a runtime + leader agent + squad and returns@@ -128,13 +138,18 @@ func TestClaim_LeaderTaskFromCommentMention_InjectsBriefing(t *testing.T) {fx := newSquadBriefingClaimFixture(t, ctx, "Briefing inject")want := enqueueClaimTask(t, ctx, fx, true /*isLeader*/, true /*withSquadID*/)- got, instr, raw := claimAgentInstructionsForTest(t, fx.RuntimeID)+ got, instr, isLeader, raw := claimAgentInstructionsForTest(t, fx.RuntimeID)if got != want {t.Fatalf("claimed task id = %q, want %q: %s", got, want, raw)}if !strings.Contains(instr, "## Squad Operating Protocol") || !strings.Contains(instr, "## Squad Roster") {t.Fatalf("expected squad-leader briefing in agent instructions, got:\n%s", instr)}+ // The daemon reads its leader role off this flag (MUL-5811), so an+ // injected briefing must arrive with the flag set.+ if !isLeader {+ t.Fatalf("claim injected the briefing but reported is_leader_task=false: %s", raw)+ }}// TestClaim_NonLeaderTask_NoBriefing guards the negative: a task that is NOT a@@ -148,10 +163,13 @@ func TestClaim_NonLeaderTask_NoBriefing(t *testing.T) {fx := newSquadBriefingClaimFixture(t, ctx, "Briefing nonleader")enqueueClaimTask(t, ctx, fx, false /*isLeader*/, true /*withSquadID*/)- _, instr, _ := claimAgentInstructionsForTest(t, fx.RuntimeID)+ _, instr, isLeader, raw := claimAgentInstructionsForTest(t, fx.RuntimeID)if strings.Contains(instr, "## Squad Operating Protocol") || strings.Contains(instr, "## Squad Roster") {t.Fatalf("non-leader task must NOT get squad briefing, got:\n%s", instr)}+ if isLeader {+ t.Fatalf("non-leader task must not report is_leader_task=true: %s", raw)+ }}// TestClaim_LeaderTaskWithDanglingSquadID_NoBriefing is the load-bearing@@ -188,13 +206,18 @@ func TestClaim_LeaderTaskWithDanglingSquadID_NoBriefing(t *testing.T) {t.Fatalf("expected task.squad_id to remain the dangling UUID after squad delete (no FK)")}- got, instr, raw := claimAgentInstructionsForTest(t, fx.RuntimeID)+ got, instr, isLeader, raw := claimAgentInstructionsForTest(t, fx.RuntimeID)if got != want {t.Fatalf("claimed task id = %q, want %q (claim must still succeed 200): %s", got, want, raw)}if strings.Contains(instr, "## Squad Operating Protocol") || strings.Contains(instr, "## Squad Roster") {t.Fatalf("dangling squad_id must NOT get squad briefing, got:\n%s", instr)}+ // A leader task with no briefing has no roster to delegate to, so the+ // daemon must not run it in the leader role either (MUL-5811).+ if isLeader {+ t.Fatalf("skipped injection must clear is_leader_task on the claim response: %s", raw)+ }}// leader tasks enqueued before migration 127 (or by an old binary) have a NULL@@ -209,8 +232,43 @@ func TestClaim_LeaderTaskWithoutSquadID_NoBriefing(t *testing.T) {fx := newSquadBriefingClaimFixture(t, ctx, "Briefing nullsquad")enqueueClaimTask(t, ctx, fx, true /*isLeader*/, false /*withSquadID*/)- _, instr, _ := claimAgentInstructionsForTest(t, fx.RuntimeID)+ _, instr, isLeader, raw := claimAgentInstructionsForTest(t, fx.RuntimeID)if strings.Contains(instr, "## Squad Operating Protocol") || strings.Contains(instr, "## Squad Roster") {t.Fatalf("leader task with NULL squad_id must NOT get squad briefing, got:\n%s", instr)}+ if isLeader {+ t.Fatalf("skipped injection must clear is_leader_task on the claim response: %s", raw)+ }+}++// TestClaim_LeaderSwappedAfterEnqueue_NoBriefingAndNoLeaderRole covers the+// third skip path: the squad still exists, but its leader was reassigned after+// this task was enqueued, so the claiming agent is no longer the leader. The+// defensive gate already withheld the briefing; the flag must follow it down,+// otherwise the daemon would boot a former leader into the leader role with no+// roster and no protocol (MUL-5811).+func TestClaim_LeaderSwappedAfterEnqueue_NoBriefingAndNoLeaderRole(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ fx := newSquadBriefingClaimFixture(t, ctx, "Briefing swapped")+ want := enqueueClaimTask(t, ctx, fx, true /*isLeader*/, true /*withSquadID*/)++ // Hand the squad to a different agent AFTER enqueue.+ otherAgentID, _ := createClaimReclaimAgentAndIssue(t, ctx, fx.RuntimeID, "Briefing swapped newleader")+ if _, err := testPool.Exec(ctx, `UPDATE squad SET leader_id = $2 WHERE id = $1`, fx.SquadID, otherAgentID); err != nil {+ t.Fatalf("swap squad leader: %v", err)+ }++ got, instr, isLeader, raw := claimAgentInstructionsForTest(t, fx.RuntimeID)+ if got != want {+ t.Fatalf("claimed task id = %q, want %q (claim must still succeed 200): %s", got, want, raw)+ }+ if strings.Contains(instr, "## Squad Operating Protocol") || strings.Contains(instr, "## Squad Roster") {+ t.Fatalf("former leader must NOT get squad briefing, got:\n%s", instr)+ }+ if isLeader {+ t.Fatalf("skipped injection must clear is_leader_task on the claim response: %s", raw)+ }}diff --git a/server/internal/handler/squad_briefing_test.go b/server/internal/handler/squad_briefing_test.goindex a755cab52c..83f1d24a28 100644--- a/server/internal/handler/squad_briefing_test.go+++ b/server/internal/handler/squad_briefing_test.go@@ -76,10 +76,12 @@ func TestSquadOperatingProtocolScopesParentStatusOwnership(t *testing.T) {}}- // The IsSquadLeader marker the daemon greps for must survive both ways,- // or a guest leader silently loses its no_action / silent-exit behavior.+ // Both variants must keep the protocol header. The daemon no longer+ // derives IsSquadLeader from it (MUL-5811 — it reads is_leader_task /+ // squad_id off the claim), but it is still the section title the leader+ // rules in the brief and the per-turn prompt refer to by name.if !strings.Contains(guest, "## Squad Operating Protocol") {- t.Error("guest-leader protocol lost the header the daemon keys IsSquadLeader off")+ t.Error("guest-leader protocol lost its section header")}}diff --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 bd2352b50e..8c7b5bafb4 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@@ -99,6 +99,20 @@ Contracts:yet. Injection is broader than authority on purpose: it is keyed off`is_leader_task`, which also fires for `@squad` mentions on issues owned bysomeone else (MUL-3724);+- when the claim's defensive gate withholds the briefing (NULL `squad_id`,+ squad hard-deleted, leader swapped after enqueue), the handler also clears+ `is_leader_task` on the claim response, so the wire flag means "briefing+ injected" and the run degrades to an ordinary agent turn. The daemon derives+ the leader role from that flag (plus `squad_id` for quick-create), never from+ the briefing text (MUL-5811);+- every claim response carries `leader_role_resolved: true`, the capability+ that tells the daemon those fields are authoritative. Servers predating it+ omit it, and a daemon seeing it absent falls back to the legacy+ "`## Squad Operating Protocol` appears in instructions" inference. That is+ the only correct read of either older shape: before #4951 no `is_leader_task`+ was sent at all, and after it the flag was sent without any guarantee that a+ briefing came with it. The field is claim-only and never rendered into a+ prompt;- `instructions` section appears only when non-empty (squad_briefing.go:110-112);- archived agent members are skipped from roster (squad_briefing.go:178-179);- agent member roster rows list assigned workspace skills via