Skip to content

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

Go

MUL-8578: feat(qoder): run squad leader turns on Qoder Cloud Agents (#9907)

Shi Peipei8a7f58330b73
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdx
index 99dd686de0..9c492f48a4 100644
--- a/apps/docs/content/docs/daemon-runtimes.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.mdx
@@ -294,7 +294,7 @@ On the Qoder Cloud Agents page, administrators can edit the connection and repos
Runs beyond the concurrency limit wait in the queue. A follow-up on the same issue continues the agent's previous Qoder session when it is idle. An agent can set a default repository, used when the issue's project has none. The agent is asked to push a branch named after the issue identifier and to prefix the pull request title with it, so the pull request is linked to the issue.
-This first version supports issue runs, chat, creating issues with an agent, progress reporting, cancellation, and recovery from a persisted run journal. Configure models, tools, and skills in Qoder. Files and images attached to issues and chat messages reach the session, PDFs and Office documents included, up to 5 MB per file; larger files are not passed on, and the agent is told they exist. Local directories and creating agents in Qoder Cloud Agents from Multica are not supported. The Runtimes page separates remote runtimes from connected computers. In chat, files the agent delivers with DeliverArtifacts, up to 10 MB each, are attached to its reply.
+This first version supports issue runs, chat, squad leaders, creating issues with an agent, progress reporting, cancellation, and recovery from a persisted run journal. Configure models, tools, and skills in Qoder. Files and images attached to issues and chat messages reach the session, PDFs and Office documents included, up to 5 MB per file; larger files are not passed on, and the agent is told they exist. Local directories and creating agents in Qoder Cloud Agents from Multica are not supported. The Runtimes page separates remote runtimes from connected computers. In chat, files the agent delivers with DeliverArtifacts, up to 10 MB each, are attached to its reply.
For standalone bridge setup and operational limitations, see the [Qoder runtime README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md).
diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdx
index 9946abeb83..be2e55e4ca 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx
@@ -295,7 +295,7 @@ Qoder Cloud Agents 通过远端会话执行分配的任务。Multica 服务端
超出并发上限的任务会排队等待。同一任务的后续运行会在上一会话空闲时继续使用该 Qoder 会话。智能体可以设置默认仓库,在任务所属项目未绑定仓库时使用。智能体会被要求以任务标识命名分支,并在 PR 标题前加上任务标识,以便 PR 自动关联到任务。
-首版支持任务运行、聊天、通过智能体创建任务、进度同步、取消和基于持久化记录的恢复。模型、工具和 skill 在 Qoder 中配置。任务和聊天消息里的附件和图片会交给远端会话,包括 PDF 和 Office 文档,每个文件不超过 5 MB;更大的文件不会传过去,智能体只知道有这些文件。聊天中智能体用 DeliverArtifacts 交付的文件(每个不超过 10 MB)会作为附件随回复发出。暂不支持本地目录,也不支持从 Multica 创建远端 Qoder Cloud Agents 智能体。运行时页面分别展示远端运行时和电脑。
+首版支持任务运行、聊天、担任小队队长、通过智能体创建任务、进度同步、取消和基于持久化记录的恢复。模型、工具和 skill 在 Qoder 中配置。任务和聊天消息里的附件和图片会交给远端会话,包括 PDF 和 Office 文档,每个文件不超过 5 MB;更大的文件不会传过去,智能体只知道有这些文件。聊天中智能体用 DeliverArtifacts 交付的文件(每个不超过 10 MB)会作为附件随回复发出。暂不支持本地目录,也不支持从 Multica 创建远端 Qoder Cloud Agents 智能体。运行时页面分别展示远端运行时和电脑。
独立桥接进程的配置与限制见 [Qoder runtime README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md)。
diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsx
index a7922a3866..7151fce173 100644
--- a/packages/views/modals/quick-create-issue.test.tsx
+++ b/packages/views/modals/quick-create-issue.test.tsx
@@ -509,8 +509,7 @@ describe("AgentCreatePanel", () => {
expect(screen.getByRole("button", { name: /^Create$/i })).toBeEnabled();
expect(screen.queryByText(/daemon.*version/i)).not.toBeInTheDocument();
expect(screen.getAllByText("Bohan").length).toBeGreaterThan(0);
- // The Qoder bridge cannot run squad-leader tasks, so its squads stay hidden.
- expect(screen.queryByText("Cloud Squad")).not.toBeInTheDocument();
+ expect(screen.getByText("Cloud Squad")).toBeInTheDocument();
});
it("blocks Qoder agents when the prompt references an attachment", () => {
diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index b312eec765..387f57d68c 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -175,28 +175,14 @@ export function AgentCreatePanel({
() => new Set(visibleAgents.map((a) => a.id)),
[visibleAgents],
);
- // Qoder Cloud Agents can draft a quick-create issue as a single agent, but
- // its bridge cannot run the squad-leader task that follows a squad
- // assignment, so squads led by a Qoder agent stay hidden.
- const qoderAgentIds = useMemo(() => {
- const qoderRuntimeIds = new Set(
- runtimes.filter((r) => r.provider === "qoder_cloud").map((r) => r.id),
- );
- return new Set(
- visibleAgents
- .filter((a) => a.runtime_id != null && qoderRuntimeIds.has(a.runtime_id))
- .map((a) => a.id),
- );
- }, [visibleAgents, runtimes]);
const visibleSquads = useMemo(
() =>
squads.filter(
(s) =>
!s.archived_at &&
- visibleAgentIds.has(s.leader_id) &&
- !qoderAgentIds.has(s.leader_id),
+ visibleAgentIds.has(s.leader_id),
),
- [squads, visibleAgentIds, qoderAgentIds],
+ [squads, visibleAgentIds],
);
const lastActorType = useQuickCreateStore((s) => s.lastActorType);
diff --git a/server/cmd/qoder-runtime/README.md b/server/cmd/qoder-runtime/README.md
index ec9782b2ea..99cd53245b 100644
--- a/server/cmd/qoder-runtime/README.md
+++ b/server/cmd/qoder-runtime/README.md
@@ -173,7 +173,11 @@ GitHub integration links the pull request back to the issue.
## Current boundaries
-This is a PoC for issue runs and chat turns. Squad coordination, local
+This is a PoC for issue runs, chat turns and squad leader turns. A squad leader
+has no Multica CLI in its Qoder session: it ends its turn with an `OUTCOME:` /
+`REASON:` header and the delegation comment, and the bridge posts the comment
+(which triggers the mentioned members) and records the squad evaluation with the
+task credential. A leader cannot change the issue status. Local
directories, arbitrary Git hosts,
tag/commit checkout, full comment-history hydration, interactive tool approval, custom client-side tools, terminal access,
files delivered by issue runs and billing/usage conversion are not implemented. Set up a Qoder
@@ -181,6 +185,15 @@ Agent that can execute autonomously with its configured tools. `requires_action`
ends the Multica run as failed with the stop reason; approvals are not granted
implicitly.
+Squad quick-create supports Qoder leaders, but quick-create attachments remain
+unsupported. A blocked delegation target fails the leader run and records the
+target ID and admission reason; successfully triggered members keep running.
+Check these results before delegating again. If a comment or evaluation response
+is lost, the bridge fails the run without automatically replaying that write.
+After a restart, delivery that still needs the task credential fails with a
+notice to inspect comments and activity before retrying. Fully delivered turns
+can still finish reporting completion after a restart.
+
Multica custom skills and execution overrides are rejected; built-in Multica
CLI skills are omitted because their local tools are unavailable. Qoder sessions
keep any artifacts they produce; textual result and PR/MR links are returned in
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index c2f7f716f9..aaa708241e 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -2864,7 +2864,7 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {
writeJSON(w, status, payload)
return
}
- if status, payload := h.checkQuickCreateQoderLimits(r.Context(), obsmetrics.RuntimeLookupSourceIssue, agent.RuntimeID, hasSquad, len(req.AttachmentIDs) > 0); status != 0 {
+ if status, payload := h.checkQuickCreateQoderLimits(r.Context(), obsmetrics.RuntimeLookupSourceIssue, agent.RuntimeID, len(req.AttachmentIDs) > 0); status != 0 {
writeJSON(w, status, payload)
return
}
@@ -2982,26 +2982,19 @@ func (h *Handler) checkQuickCreateDaemonVersion(ctx context.Context, source stri
return h.checkQuickCreateDaemonVersionAtLeast(ctx, source, runtimeID, agentpkg.MinQuickCreateCLIVersion)
}
-// checkQuickCreateQoderLimits rejects quick-create requests that a Qoder
-// Cloud Agents leader can create but not run afterwards. The bridge drafts and
-// creates the issue itself, but the run that the new issue's assignment
-// dispatches next fails on the bridge for a squad-leader task or an issue with
-// attachments, so the user would see "created" followed by a failed run.
-func (h *Handler) checkQuickCreateQoderLimits(ctx context.Context, source string, runtimeID pgtype.UUID, squad, attachments bool) (int, map[string]any) {
- if !squad && !attachments {
+// checkQuickCreateQoderLimits keeps attachment-backed quick-create blocked:
+// the bridge can run squad leaders, but cannot draft from these attachments.
+func (h *Handler) checkQuickCreateQoderLimits(ctx context.Context, source string, runtimeID pgtype.UUID, attachments bool) (int, map[string]any) {
+ if !attachments {
return 0, nil
}
rt, err := h.getAgentRuntime(ctx, source, runtimeID)
if err != nil || rt.Provider != qoderruntime.Provider {
return 0, nil
}
- reason := "Qoder Cloud Agents cannot lead a squad; pick the agent directly to create the issue"
- if !squad {
- reason = "Qoder Cloud Agents cannot read attachments; remove them or pick another agent"
- }
return http.StatusUnprocessableEntity, map[string]any{
"code": "agent_unavailable",
- "reason": reason,
+ "reason": "Qoder Cloud Agents cannot read attachments; remove them or pick another agent",
}
}
diff --git a/server/internal/handler/qoder_connection_test.go b/server/internal/handler/qoder_connection_test.go
index 7ad5e485ff..0a68d972a6 100644
--- a/server/internal/handler/qoder_connection_test.go
+++ b/server/internal/handler/qoder_connection_test.go
@@ -9,6 +9,7 @@ import (
"testing"
"github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/testutil"
agentpkg "github.com/multica-ai/multica/server/pkg/agent"
)
@@ -285,29 +286,49 @@ func TestQoderStepLeaseReleasesDatabaseConnection(t *testing.T) {
testutil.Call(t, testHandler.StopQoderConnection, vcsHandlerRequest("POST", "/qoder/stop", nil, "")).Want(200)
}
+func TestQoderSquadQuickCreate(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := dbfx.Runtime(t, "Qoder squad quick-create", testutil.Cols{"provider": "qoder_cloud"})
+ leaderID := dbfx.Agent(t, "Qoder squad leader", runtimeID, testutil.Cols{"runtime_config": `{"qoder_agent_id":"agent_1"}`})
+ squadID := dbfx.Squad(t, "Qoder quick-create squad", leaderID)
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE agent_id=$1`, leaderID)
+
+ var response QuickCreateIssueResponse
+ testutil.Call(t, testHandler.QuickCreateIssue, newRequest(http.MethodPost, "/api/issues/quick-create", map[string]any{
+ "squad_id": squadID, "prompt": "Add a settings page",
+ })).Want(http.StatusAccepted).JSON(&response)
+
+ var agentID string
+ var raw []byte
+ dbfx.QueryRow(t, `SELECT agent_id::text, context FROM agent_task_queue WHERE id=$1`, response.TaskID).Scan(&agentID, &raw)
+ var qc service.QuickCreateContext
+ if err := json.Unmarshal(raw, &qc); err != nil {
+ t.Fatal(err)
+ }
+ if agentID != leaderID || qc.SquadID != squadID {
+ t.Fatalf("quick-create must route to the Qoder leader and retain the squad: agent=%s context=%+v", agentID, qc)
+ }
+
+ testutil.Call(t, testHandler.QuickCreateIssue, newRequest(http.MethodPost, "/api/issues/quick-create", map[string]any{
+ "squad_id": squadID, "prompt": "Read the screenshot", "attachment_ids": []string{"019ec09d-6222-722b-bdfa-427b105d80be"},
+ })).Want(http.StatusUnprocessableEntity)
+}
+
func TestQoderQuickCreateLimits(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
ctx := context.Background()
qoderID := parseUUID(dbfx.Runtime(t, "Qoder quick-create limits runtime", testutil.Cols{"provider": "qoder_cloud", "runtime_mode": "cloud", "metadata": `{}`}))
- for _, tc := range []struct {
- name string
- squad, attachments bool
- want string
- }{
- {"squad", true, false, "lead a squad"},
- {"attachments", false, true, "attachments"},
- } {
- status, payload := testHandler.checkQuickCreateQoderLimits(ctx, "issue", qoderID, tc.squad, tc.attachments)
- if status != http.StatusUnprocessableEntity || payload["code"] != "agent_unavailable" || !strings.Contains(payload["reason"].(string), tc.want) {
- t.Fatalf("%s: Qoder quick-create should be rejected, got %d: %v", tc.name, status, payload)
- }
+ if status, payload := testHandler.checkQuickCreateQoderLimits(ctx, "issue", qoderID, true); status != http.StatusUnprocessableEntity || payload["code"] != "agent_unavailable" || !strings.Contains(payload["reason"].(string), "attachments") {
+ t.Fatalf("Qoder quick-create attachments should be rejected, got %d: %v", status, payload)
}
- if status, payload := testHandler.checkQuickCreateQoderLimits(ctx, "issue", qoderID, false, false); status != 0 {
+ if status, payload := testHandler.checkQuickCreateQoderLimits(ctx, "issue", qoderID, false); status != 0 {
t.Fatalf("plain Qoder quick-create should be accepted, got %d: %v", status, payload)
}
- if status, payload := testHandler.checkQuickCreateQoderLimits(ctx, "issue", parseUUID(testRuntimeID), true, true); status != 0 {
+ if status, payload := testHandler.checkQuickCreateQoderLimits(ctx, "issue", parseUUID(testRuntimeID), true); status != 0 {
t.Fatalf("daemon runtime should be accepted, got %d: %v", status, payload)
}
}
diff --git a/server/internal/qoderruntime/bridge.go b/server/internal/qoderruntime/bridge.go
index c000f9c865..86d317b3b7 100644
--- a/server/internal/qoderruntime/bridge.go
+++ b/server/internal/qoderruntime/bridge.go
@@ -694,6 +694,11 @@ func (b *Bridge) deliver(ctx context.Context, r *run) error {
if err := b.reportCredits(ctx, r); err != nil {
return err
}
+ if r.Leader != nil && r.Outcome == "completed" {
+ if err := b.deliverLeader(ctx, r); err != nil {
+ return err
+ }
+ }
body := map[string]any{"session_id": r.SessionID}
suffix := "/complete"
if r.Outcome == "completed" {
diff --git a/server/internal/qoderruntime/bridge_test.go b/server/internal/qoderruntime/bridge_test.go
index 2ddce8a8d6..6dbaf3b636 100644
--- a/server/internal/qoderruntime/bridge_test.go
+++ b/server/internal/qoderruntime/bridge_test.go
@@ -108,6 +108,7 @@ type harness struct {
usageStatus int
cancelAcks int
cancelAckStatus int
+ comments, evaluations []map[string]any
}
func setup(t *testing.T) *harness {
@@ -144,6 +145,16 @@ func setup(t *testing.T) *harness {
} else {
io.WriteString(w, `{"identifier":"MUL-7"}`)
}
+ case r.URL.Path == "/api/issues/issue-1/comments" && r.Method == http.MethodPost:
+ var c map[string]any
+ json.NewDecoder(r.Body).Decode(&c)
+ h.comments = append(h.comments, c)
+ io.WriteString(w, `{}`)
+ case r.URL.Path == "/api/issues/issue-1/squad-evaluated" && r.Method == http.MethodPost:
+ var e map[string]any
+ json.NewDecoder(r.Body).Decode(&e)
+ h.evaluations = append(h.evaluations, e)
+ io.WriteString(w, `{}`)
case strings.HasPrefix(r.URL.Path, "/api/issues/"):
if h.issueGet != "" {
io.WriteString(w, h.issueGet)
@@ -649,6 +660,65 @@ func TestChatRun(t *testing.T) {
t.Fatalf("result: %#v", h.complete)
}
}
+func leaderRun(t *testing.T, reply string) *harness {
+ t.Helper()
+ h := setup(t)
+ h.task.IsLeaderTask = true
+ h.task.TriggerCommentID = "comment-1"
+ h.task.Agent.Instructions = "## Squad Operating Protocol\nDelegate."
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.failure != nil || !strings.Contains(h.prompt, "Squad Operating Protocol") || !strings.Contains(h.prompt, "OUTCOME:") || strings.Contains(h.prompt, "pull request whose title") {
+ t.Fatalf("incorrect leader prompt: %s (failure %#v)", h.prompt, h.failure)
+ }
+ h.draft(reply)
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ return h
+}
+func TestSquadLeaderRunDelegates(t *testing.T) {
+ h := leaderRun(t, "OUTCOME: action\nREASON: Bob owns the API\n[@Bob](mention://agent/bob) please fix the handler.")
+ if len(h.comments) != 1 || h.comments[0]["content"] != "[@Bob](mention://agent/bob) please fix the handler." || h.comments[0]["parent_id"] != "comment-1" {
+ t.Fatalf("comments: %#v", h.comments)
+ }
+ if len(h.evaluations) != 1 || h.evaluations[0]["outcome"] != "action" || h.evaluations[0]["reason"] != "Bob owns the API" {
+ t.Fatalf("evaluations: %#v", h.evaluations)
+ }
+ if h.complete == nil || h.failure != nil {
+ t.Fatalf("result: %#v %#v", h.complete, h.failure)
+ }
+}
+func TestSquadLeaderNoActionPostsNoComment(t *testing.T) {
+ h := leaderRun(t, "**OUTCOME:** no_action\n**REASON:** progress update only\nNothing to do.")
+ if len(h.comments) != 0 || len(h.evaluations) != 1 || h.evaluations[0]["outcome"] != "no_action" || h.evaluations[0]["reason"] != "progress update only" {
+ t.Fatalf("comments %#v evaluations %#v", h.comments, h.evaluations)
+ }
+ if h.complete == nil {
+ t.Fatalf("not completed: %#v", h.failure)
+ }
+}
+func TestSquadLeaderUnformattedReplyStillDelegates(t *testing.T) {
+ h := leaderRun(t, "[@Bob](mention://agent/bob) take this one.")
+ if len(h.comments) != 1 || len(h.evaluations) != 1 || h.evaluations[0]["outcome"] != "action" {
+ t.Fatalf("comments %#v evaluations %#v", h.comments, h.evaluations)
+ }
+}
+func TestSquadLeaderWithoutIssueFails(t *testing.T) {
+ h := setup(t)
+ h.task.IsLeaderTask = true
+ h.task.IssueID = ""
+ h.task.ChatSessionID = "chat-1"
+ h.task.ChatMessage = "hi"
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.failure == nil || h.creates != 0 {
+ t.Fatalf("expected failure before execution: %#v", h.failure)
+ }
+}
func TestChatAudience(t *testing.T) {
for _, tc := range []struct{ channel, chatType, want string }{
{"", "", "Audience: direct room."},
diff --git a/server/internal/qoderruntime/claim.go b/server/internal/qoderruntime/claim.go
index 51203b8fe1..c700314293 100644
--- a/server/internal/qoderruntime/claim.go
+++ b/server/internal/qoderruntime/claim.go
@@ -28,6 +28,7 @@ type claimedTask struct {
ProjectDescription string `json:"project_description,omitempty"`
HandoffNote string `json:"handoff_note,omitempty"`
CoalescedComments []claimedComment `json:"coalesced_comments,omitempty"`
+ TriggerCommentID string `json:"trigger_comment_id,omitempty"`
TriggerCommentContent string `json:"trigger_comment_content,omitempty"`
TriggerAuthorName string `json:"trigger_author_name,omitempty"`
ProjectResources []claimedResource `json:"project_resources,omitempty"`
diff --git a/server/internal/qoderruntime/leader.go b/server/internal/qoderruntime/leader.go
new file mode 100644
index 0000000000..e25b3c2770
--- /dev/null
+++ b/server/internal/qoderruntime/leader.go
@@ -0,0 +1,191 @@
+package qoderruntime
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// squadLeader holds what a squad-leader run needs to deliver its turn. The
+// Squad Operating Protocol tells a leader to delegate with a mention comment
+// and record its evaluation through the Multica CLI; a managed Qoder session
+// has no CLI, so the agent states both in its final message and the bridge
+// posts them with the task credential. Only a comment created through the
+// comments API triggers the mentioned members.
+type squadLeader struct {
+ IssueID string `json:"issue_id"`
+ TriggerCommentID string `json:"trigger_comment_id,omitempty"`
+ Commented bool `json:"commented,omitempty"`
+ Recorded bool `json:"recorded,omitempty"`
+ // Persist write intent before each POST. Neither endpoint deduplicates an
+ // ambiguous response, so it must never cause an automatic replay.
+ CommentSubmitted bool `json:"comment_submitted,omitempty"`
+ EvaluationSubmitted bool `json:"evaluation_submitted,omitempty"`
+ // The task credential is never persisted; after a restart it is gone and
+ // the run fails instead of delivering the turn.
+ token string
+}
+
+const leaderBridgeNote = `
+Squad leader on Qoder Cloud Agents: this session has no Multica CLI. Never run ` + "`multica`" + ` commands; the bridge performs the delegation comment and the evaluation record from the Squad Operating Protocol for you. Do not change code or open pull requests. End your turn with a final message in exactly this form:
+
+OUTCOME: action | no_action | failed
+REASON: <one short line>
+<the comment body to post on the issue, using the exact mention markdown from the Squad Roster; leave it empty for no_action>
+`
+
+var leaderOutcomeLine = regexp.MustCompile(`(?im)^\s*\**OUTCOME\**\s*:\s*\**\s*(action|no_action|failed)\b.*$`)
+var leaderReasonLine = regexp.MustCompile(`(?im)^\s*\**REASON\**\s*:\s*\**\s*(.*)$`)
+
+// parseLeaderOutput reads the contract in leaderBridgeNote. Output without an
+// OUTCOME line is treated as an action whose whole text is the comment, so a
+// leader that ignored the format still delegates.
+func parseLeaderOutput(output string) (outcome, reason, comment string) {
+ loc := leaderOutcomeLine.FindStringSubmatchIndex(output)
+ if loc == nil {
+ return "action", "", strings.TrimSpace(output)
+ }
+ outcome = strings.ToLower(output[loc[2]:loc[3]])
+ rest := output[loc[1]:]
+ if m := leaderReasonLine.FindStringSubmatchIndex(rest); m != nil && strings.TrimSpace(rest[:m[0]]) == "" {
+ reason = strings.TrimSpace(strings.Trim(rest[m[2]:m[3]], "*"))
+ rest = rest[m[1]:]
+ }
+ comment = strings.TrimSpace(rest)
+ if outcome == "no_action" {
+ comment = ""
+ }
+ return outcome, reason, comment
+}
+
+// deliverLeader posts the delegation comment and records its actual dispatch
+// result before completing. Only a definite rate-limit refusal permits retry.
+func (b *Bridge) deliverLeader(ctx context.Context, r *run) error {
+ l := r.Leader
+ if l.Recorded {
+ return nil
+ }
+ fail := func(reason string) error {
+ r.Outcome, r.Failure = "failed", reason
+ return b.persist()
+ }
+ if l.token == "" {
+ if l.CommentSubmitted || l.Commented {
+ return fail("the bridge restarted during squad leader delivery; check the issue comments and activity before retrying, because members may already be running")
+ }
+ return fail("the bridge restarted before the squad leader turn was delivered; trigger the leader again")
+ }
+ taskAPI := *b.multica
+ taskAPI.token = l.token
+ outcome, reason, comment := parseLeaderOutput(r.Output)
+ if outcome == "action" && comment == "" && r.Failure == "" {
+ r.Failure = "the squad leader reported action without a delegation comment"
+ }
+ const uncertainComment = "squad leader comment delivery could not be confirmed; check the issue comments before retrying, because members may already be running"
+ if l.CommentSubmitted && !l.Commented && r.Failure == "" {
+ r.Failure = uncertainComment
+ }
+ if !l.Commented && comment != "" && r.Failure == "" {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ body := map[string]any{"content": comment, "type": "comment"}
+ if l.TriggerCommentID != "" {
+ body["parent_id"] = l.TriggerCommentID
+ }
+ l.CommentSubmitted = true
+ if err := b.persist(); err != nil {
+ return err
+ }
+ var posted struct {
+ TriggerOutcomes []struct {
+ TargetType string `json:"target_type"`
+ TargetID string `json:"target_id"`
+ Status string `json:"status"`
+ ReasonCode string `json:"reason_code"`
+ } `json:"trigger_outcomes"`
+ }
+ if err := taskAPI.call(ctx, http.MethodPost, "/api/issues/"+url.PathEscape(l.IssueID)+"/comments", body, &posted); err != nil {
+ if rateLimited(err) {
+ l.CommentSubmitted = false
+ if persistErr := b.persist(); persistErr != nil {
+ return persistErr
+ }
+ return err
+ }
+ if definitelyRejected(err) {
+ r.Failure = "Multica rejected the squad leader comment: " + err.Error()
+ } else {
+ r.Failure = uncertainComment
+ }
+ } else {
+ l.Commented = true
+ // Use labels already visible in the delegation, without looking up
+ // names the task may not have permission to read.
+ labels := make(map[string]string)
+ for _, mention := range util.MentionRe.FindAllStringSubmatch(comment, -1) {
+ labels[mention[2]+":"+strings.ToLower(mention[3])] = strings.TrimSpace(mention[1])
+ }
+ var blocked []string
+ for _, target := range posted.TriggerOutcomes {
+ if target.Status == "blocked" {
+ label := target.TargetID
+ if name := labels[target.TargetType+":"+strings.ToLower(target.TargetID)]; name != "" {
+ label = fmt.Sprintf("%s [%s]", name, target.TargetID)
+ }
+ blocked = append(blocked, fmt.Sprintf("%s (%s)", label, target.ReasonCode))
+ }
+ }
+ if len(blocked) > 0 {
+ r.Failure = "squad delegation blocked for " + strings.Join(blocked, ", ") + "; other targets may already be running, so do not repeat the delegation"
+ }
+ }
+ if err := b.persist(); err != nil {
+ return err
+ }
+ }
+ if r.Failure != "" {
+ outcome, reason = "failed", r.Failure
+ }
+ if reason == "" {
+ reason = fmt.Sprintf("Recorded by the Qoder Cloud Agents bridge (%s)", outcome)
+ }
+ if l.EvaluationSubmitted {
+ return fail("squad evaluation delivery could not be confirmed; check the issue activity before retrying and do not repeat the delegation")
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ l.EvaluationSubmitted = true
+ if err := b.persist(); err != nil {
+ return err
+ }
+ err := taskAPI.call(ctx, http.MethodPost, "/api/issues/"+url.PathEscape(l.IssueID)+"/squad-evaluated", map[string]string{"outcome": outcome, "reason": reason}, nil)
+ if err != nil {
+ if rateLimited(err) {
+ l.EvaluationSubmitted = false
+ if persistErr := b.persist(); persistErr != nil {
+ return persistErr
+ }
+ return err
+ }
+ failure := "squad evaluation delivery could not be confirmed; check the issue activity before retrying and do not repeat the delegation"
+ if definitelyRejected(err) {
+ failure = "Multica rejected the squad leader evaluation: " + err.Error()
+ }
+ if r.Failure != "" {
+ failure = r.Failure + "; " + failure
+ }
+ return fail(failure)
+ }
+ l.Recorded = true
+ if outcome == "failed" {
+ r.Outcome, r.Failure = "failed", reason
+ }
+ return b.persist()
+}
diff --git a/server/internal/qoderruntime/leader_test.go b/server/internal/qoderruntime/leader_test.go
new file mode 100644
index 0000000000..45c85a5a3f
--- /dev/null
+++ b/server/internal/qoderruntime/leader_test.go
@@ -0,0 +1,197 @@
+package qoderruntime
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+)
+
+type leaderTransport func(*http.Request) (*http.Response, error)
+
+func (f leaderTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func pendingLeader(t *testing.T, reply string) *harness {
+ t.Helper()
+ h := setup(t)
+ h.task.IsLeaderTask = true
+ h.task.TriggerCommentID = "comment-1"
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.draft(reply)
+ return h
+}
+
+const leaderDelegation = "OUTCOME: action\nREASON: API work\n[@Bob](mention://agent/bob) fix the handler."
+
+func TestSquadLeaderQuickCreateAssignsSquad(t *testing.T) {
+ h := setup(t)
+ quickCreateTask(h)
+ h.task.SquadID = "squad-1"
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.draft(`{"title":"Settings page","description":"Add settings"}`)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete == nil || h.failure != nil || h.issue["assignee_type"] != "squad" || h.issue["assignee_id"] != "squad-1" {
+ t.Fatalf("created issue must keep the selected squad: complete=%v failure=%v issue=%v", h.complete, h.failure, h.issue)
+ }
+}
+
+func TestSquadLeaderLostCommentResponseDoesNotRepost(t *testing.T) {
+ h := pendingLeader(t, leaderDelegation)
+ base := h.b.multica.client.Transport
+ lost := false
+ h.b.multica.client.Transport = leaderTransport(func(r *http.Request) (*http.Response, error) {
+ resp, err := base.RoundTrip(r)
+ if err == nil && !lost && r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/comments") {
+ j, journalErr := readJournal(h.b.path, "test")
+ if journalErr != nil || len(j.Runs) != 1 || !j.Runs[0].Leader.CommentSubmitted || j.Runs[0].Leader.token != "" {
+ t.Fatalf("write intent must be durable and credentials excluded before POST: journal=%+v error=%v", j, journalErr)
+ }
+ lost = true
+ resp.Body.Close()
+ return nil, errors.New("response lost after comment was saved")
+ }
+ return resp, err
+ })
+ _ = h.b.step(context.Background())
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if len(h.comments) != 1 || h.failure == nil || h.complete != nil || !strings.Contains(h.failure["error"].(string), "could not be confirmed") {
+ t.Fatalf("ambiguous comment must fail without replay: comments=%d failure=%v complete=%v", len(h.comments), h.failure, h.complete)
+ }
+ if len(h.evaluations) != 1 || h.evaluations[0]["outcome"] != "failed" {
+ t.Fatalf("evaluation must report the uncertain delivery: %v", h.evaluations)
+ }
+}
+
+func TestSquadLeaderReportsBlockedDelegation(t *testing.T) {
+ const bobID = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
+ const aliceID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ const reply = "OUTCOME: action\nREASON: API work\n[@Bob[API]](mention://agent/" + bobID + ") fix the handler."
+ for _, tc := range []struct {
+ name, reply, outcomes, wantTarget string
+ }{
+ {"agent", reply, `[{"target_type":"agent","target_id":"` + bobID + `","status":"blocked","reason_code":"invocation_not_allowed"}]`, "Bob[API] [" + bobID + "]"},
+ {"partial dispatch", reply, `[{"target_type":"agent","target_id":"` + aliceID + `","status":"queued"},{"target_type":"agent","target_id":"` + bobID + `","status":"blocked","reason_code":"invocation_not_allowed"}]`, "Bob[API] [" + bobID + "]"},
+ {"squad", reply + "\n[@Platform Squad](mention://squad/" + bobID + ") help.", `[{"target_type":"squad","target_id":"` + bobID + `","status":"blocked","reason_code":"invocation_not_allowed"}]`, "Platform Squad [" + bobID + "]"},
+ {"unknown label", reply, `[{"target_type":"agent","target_id":"` + aliceID + `","status":"blocked","reason_code":"invocation_not_allowed"}]`, aliceID},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ h := pendingLeader(t, tc.reply)
+ base := h.b.multica.client.Transport
+ h.b.multica.client.Transport = leaderTransport(func(r *http.Request) (*http.Response, error) {
+ resp, err := base.RoundTrip(r)
+ if err == nil && r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/comments") {
+ resp.Body.Close()
+ resp.Body = io.NopCloser(strings.NewReader(`{"trigger_outcomes":` + tc.outcomes + `}`))
+ }
+ return resp, err
+ })
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if len(h.comments) != 1 || h.complete != nil || h.failure == nil || !strings.Contains(h.failure["error"].(string), "invocation_not_allowed") || !strings.Contains(h.failure["error"].(string), tc.wantTarget) {
+ t.Fatalf("blocked delegation must fail visibly: comments=%v complete=%v failure=%v", h.comments, h.complete, h.failure)
+ }
+ if len(h.evaluations) != 1 || h.evaluations[0]["outcome"] != "failed" || !strings.Contains(h.evaluations[0]["reason"].(string), tc.wantTarget) {
+ t.Fatalf("evaluation must identify the blocked target: %v", h.evaluations)
+ }
+ })
+ }
+}
+
+func TestSquadLeaderEvaluationRateLimitDoesNotRepostComment(t *testing.T) {
+ h := pendingLeader(t, leaderDelegation)
+ base := h.b.multica.client.Transport
+ limited := false
+ h.b.multica.client.Transport = leaderTransport(func(r *http.Request) (*http.Response, error) {
+ if !limited && strings.HasSuffix(r.URL.Path, "/squad-evaluated") {
+ limited = true
+ return &http.Response{StatusCode: 429, Body: io.NopCloser(strings.NewReader(`{}`)), Header: http.Header{}}, nil
+ }
+ return base.RoundTrip(r)
+ })
+ if err := h.b.step(context.Background()); err == nil {
+ t.Fatal("expected rate limit")
+ }
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if len(h.comments) != 1 || len(h.evaluations) != 1 || h.complete == nil {
+ t.Fatalf("retry must record without redelegating: comments=%v evaluations=%v complete=%v", h.comments, h.evaluations, h.complete)
+ }
+}
+
+func TestSquadLeaderLostEvaluationResponseDoesNotReplay(t *testing.T) {
+ h := pendingLeader(t, leaderDelegation)
+ base := h.b.multica.client.Transport
+ lost := false
+ h.b.multica.client.Transport = leaderTransport(func(r *http.Request) (*http.Response, error) {
+ resp, err := base.RoundTrip(r)
+ if err == nil && !lost && strings.HasSuffix(r.URL.Path, "/squad-evaluated") {
+ lost = true
+ resp.Body.Close()
+ return nil, errors.New("response lost after evaluation was saved")
+ }
+ return resp, err
+ })
+ _ = h.b.step(context.Background())
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete != nil || h.failure == nil || len(h.comments) != 1 || len(h.evaluations) != 1 {
+ t.Fatalf("unconfirmed evaluation must not replay writes: complete=%v failure=%v comments=%v evaluations=%v", h.complete, h.failure, h.comments, h.evaluations)
+ }
+}
+
+func TestSquadLeaderRejectedNoActionEvaluationFailsVisibly(t *testing.T) {
+ h := pendingLeader(t, "OUTCOME: no_action\nREASON: progress only")
+ base := h.b.multica.client.Transport
+ h.b.multica.client.Transport = leaderTransport(func(r *http.Request) (*http.Response, error) {
+ if strings.HasSuffix(r.URL.Path, "/squad-evaluated") {
+ return &http.Response{StatusCode: 403, Body: io.NopCloser(strings.NewReader(`{}`)), Header: http.Header{}}, nil
+ }
+ return base.RoundTrip(r)
+ })
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete != nil || h.failure == nil || len(h.comments) != 0 || !strings.Contains(h.failure["error"].(string), "evaluation") {
+ t.Fatalf("refused evaluation must not silently complete: complete=%v failure=%v comments=%v", h.complete, h.failure, h.comments)
+ }
+}
+
+func TestSquadLeaderCompletedDeliverySurvivesRestart(t *testing.T) {
+ h := pendingLeader(t, leaderDelegation)
+ base := h.b.multica.client.Transport
+ refused := false
+ h.b.multica.client.Transport = leaderTransport(func(r *http.Request) (*http.Response, error) {
+ if !refused && strings.HasSuffix(r.URL.Path, "/complete") {
+ refused = true
+ return &http.Response{StatusCode: 503, Body: io.NopCloser(strings.NewReader(`{}`)), Header: http.Header{}}, nil
+ }
+ return base.RoundTrip(r)
+ })
+ if err := h.b.step(context.Background()); err == nil {
+ t.Fatal("expected terminal report error")
+ }
+ j, err := readJournal(h.b.path, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.b.state = j
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete == nil || h.failure != nil || len(h.comments) != 1 || len(h.evaluations) != 1 {
+ t.Fatalf("restart must only retry completion: complete=%v failure=%v comments=%v evaluations=%v", h.complete, h.failure, h.comments, h.evaluations)
+ }
+}
diff --git a/server/internal/qoderruntime/prompt.go b/server/internal/qoderruntime/prompt.go
index d1e1f6ae30..f70634186b 100644
--- a/server/internal/qoderruntime/prompt.go
+++ b/server/internal/qoderruntime/prompt.go
@@ -17,8 +17,8 @@ func (b *Bridge) prepare(ctx context.Context, t *claimedTask) (*run, error) {
}
chat := t.ChatSessionID != ""
quickCreate := !chat && t.IssueID == "" && t.QuickCreatePrompt != ""
- if (t.IssueID != "") == (chat || quickCreate) || t.IsLeaderTask {
- return nil, fmt.Errorf("Qoder bridge currently supports issue, chat and quick-create runs only")
+ if (t.IssueID != "") == (chat || quickCreate) || t.IsLeaderTask && t.IssueID == "" {
+ return nil, fmt.Errorf("Qoder bridge currently supports issue, squad leader, chat and quick-create runs only")
}
if !strings.HasPrefix(t.AuthToken, "mat_") {
return nil, fmt.Errorf("claim is missing a task-scoped credential")
@@ -72,6 +72,9 @@ func (b *Bridge) prepare(ctx context.Context, t *claimedTask) (*run, error) {
if t.Agent != nil {
fmt.Fprintf(&p, "\nAgent instructions:\n%s\n", t.Agent.Instructions)
}
+ if r.Leader != nil {
+ p.WriteString(leaderBridgeNote)
+ }
fmt.Fprintf(&p, "\nWorkspace context:\n%s\n\nProject:\n%s\n%s\n", t.WorkspaceContext, t.ProjectTitle, t.ProjectDescription)
if t.HandoffNote != "" {
fmt.Fprintf(&p, "\nHandoff:\n%s\n", t.HandoffNote)
@@ -150,13 +153,18 @@ func (b *Bridge) issuePrompt(ctx context.Context, t *claimedTask, r *run, p *str
if err := taskAPI.call(ctx, http.MethodGet, "/api/issues/"+url.PathEscape(t.IssueID), nil, &issue); err != nil {
return fmt.Errorf("read issue: %w", err)
}
- p.WriteString("Complete the following Multica issue in your Qoder environment. Return a final summary including code changes, tests and branch/PR/MR links when available. This bridge does not expose a local Multica daemon.\n")
+ if t.IsLeaderTask {
+ r.Leader = &squadLeader{IssueID: t.IssueID, TriggerCommentID: t.TriggerCommentID, token: t.AuthToken}
+ p.WriteString("You lead a Multica squad on the following issue. Follow the Squad Operating Protocol in your agent instructions: coordinate, do not do the work yourself. This bridge does not expose a local Multica daemon.\n")
+ } else {
+ p.WriteString("Complete the following Multica issue in your Qoder environment. Return a final summary including code changes, tests and branch/PR/MR links when available. This bridge does not expose a local Multica daemon.\n")
+ }
if t.PriorSessionID != "" {
r.PriorSessionID = t.PriorSessionID
p.WriteString("This is a follow-up on the same issue. If the earlier conversation is not in your context, rely on the issue and comments below.\n")
}
fmt.Fprintf(p, "\nRun: %s\nIssue: %s\n\n%s\n\n%s\n", t.ID, t.IssueIdentifier, issue.Title, issue.Description)
- if t.IssueIdentifier != "" {
+ if t.IssueIdentifier != "" && !t.IsLeaderTask {
fmt.Fprintf(p, "\nWhen you change code, push a new branch named %s (never the default branch), open a pull request whose title starts with \"%s: \", and put the pull request link in your final summary. Multica links the pull request to this issue through that identifier.\n", BranchName(t.IssueIdentifier, issue.Title), t.IssueIdentifier)
}
return b.attachFiles(ctx, &taskAPI, "Issue attachments", attachmentMountDir, issue.Attachments, r, p)
diff --git a/server/internal/qoderruntime/state.go b/server/internal/qoderruntime/state.go
index 5d9cb270af..8094fe7a2e 100644
--- a/server/internal/qoderruntime/state.go
+++ b/server/internal/qoderruntime/state.go
@@ -54,6 +54,7 @@ type run struct {
QuickCreate *quickCreate `json:"quick_create,omitempty"`
Reply *replyFiles `json:"reply,omitempty"`
Credits runCredits `json:"credits"`
+ Leader *squadLeader `json:"leader,omitempty"`
}
func save(path string, j *journal) error {