Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent tasks): prevent duplicate self-assignment work (MUL-6168) (#6956)
Multica Eveb5a48eca1348
diff --git a/apps/docs/content/docs/assigning-issues.ja.mdx b/apps/docs/content/docs/assigning-issues.ja.mdxindex e7877782cc..81eccb2581 100644--- a/apps/docs/content/docs/assigning-issues.ja.mdx+++ b/apps/docs/content/docs/assigning-issues.ja.mdx@@ -67,11 +67,15 @@ Multica はエージェントのために[タスク](/tasks)を作成します```bashmultica issue assign MUL-42 --to "Agent name"+multica issue assign MUL-42 --to-id <agent-uuid> --no-start+multica issue status MUL-42 in_progress --no-startmultica issue assign MUL-42 --unassign```スクリプトでは `--to-id <uuid>` を使うと、同名のオブジェクトへの誤マッチを避けられます。UUID は `multica agent list --output json` または `multica workspace member list --output json` で確認できます。+割り当てで担当だけを記録し、新しいタスクを作成しない場合(たとえば同じエージェントが別の実行ですでにそのイシューを処理している場合)は、`--no-start` を使用します。`issue update` と `issue status` でも同じフラグを使用できます。担当とステータスの両方を変更する所有権のみのフローでは、両方のコマンドにこのフラグを指定してください。割り当てを抑止しても、後続のステータス変更による実行は自動では抑止されません。+## 次のステップ- [コメントでエージェントを @メンション](/mentioning-agents) — 担当者を変えずに、新しい依頼を処理します。diff --git a/apps/docs/content/docs/assigning-issues.ko.mdx b/apps/docs/content/docs/assigning-issues.ko.mdxindex 519ed9646f..2451b6b00f 100644--- a/apps/docs/content/docs/assigning-issues.ko.mdx+++ b/apps/docs/content/docs/assigning-issues.ko.mdx@@ -67,11 +67,15 @@ Multica가 에이전트의 [실행 태스크](/tasks)를 만듭니다. 온라인```bashmultica issue assign MUL-42 --to "Agent name"+multica issue assign MUL-42 --to-id <agent-uuid> --no-start+multica issue status MUL-42 in_progress --no-startmultica issue assign MUL-42 --unassign```스크립트에서는 `--to-id <uuid>`를 사용하면 이름이 같은 객체를 잘못 매칭하는 일을 피할 수 있습니다. UUID는 `multica agent list --output json` 또는 `multica workspace member list --output json`으로 확인합니다.+할당이 담당자만 기록하고 새 태스크를 만들면 안 되는 경우(예: 같은 에이전트가 다른 실행에서 이미 해당 이슈를 처리 중인 경우)에는 `--no-start`를 사용하세요. `issue update`와 `issue status`에서도 같은 플래그를 사용할 수 있습니다. 담당자와 상태를 모두 바꾸는 소유권 전용 흐름이라면 두 명령 모두에 이 플래그를 전달해야 합니다. 할당을 억제해도 이후 상태 변경이 시작하는 실행까지 자동으로 억제되지는 않습니다.+## 다음 단계- [댓글에서 에이전트 @멘션하기](/mentioning-agents) — 담당자를 바꾸지 않고 새 문제를 처리합니다.diff --git a/apps/docs/content/docs/assigning-issues.mdx b/apps/docs/content/docs/assigning-issues.mdxindex 508c56ccfa..48e09ff7e8 100644--- a/apps/docs/content/docs/assigning-issues.mdx+++ b/apps/docs/content/docs/assigning-issues.mdx@@ -71,11 +71,15 @@ Changing the assignee, unassigning, or changing the issue status doesn't stop a```bashmultica issue assign MUL-42 --to "Agent name"+multica issue assign MUL-42 --to-id <agent-uuid> --no-start+multica issue status MUL-42 in_progress --no-startmultica issue assign MUL-42 --unassign```In scripts, use `--to-id <uuid>` to avoid matching the wrong object with the same name. Look up UUIDs with `multica agent list --output json` or `multica workspace member list --output json`.+Use `--no-start` when the assignment should record ownership without creating a new task — for example, when the same agent is already handling the issue from another run. The same flag is available on `issue update` and `issue status`. If an ownership-only flow changes both assignment and status, pass it to both commands; suppressing the assignment does not suppress a later status-triggered run.+## Next steps- [@-mention agents in comments](/mentioning-agents) — handle a new question without changing the assignee.diff --git a/apps/docs/content/docs/assigning-issues.zh.mdx b/apps/docs/content/docs/assigning-issues.zh.mdxindex 28a5919442..512a8d0bc4 100644--- a/apps/docs/content/docs/assigning-issues.zh.mdx+++ b/apps/docs/content/docs/assigning-issues.zh.mdx@@ -71,11 +71,15 @@ Multica 会为智能体创建一条[执行任务](/tasks)。在线运行时领```bashmultica issue assign MUL-42 --to "Agent name"+multica issue assign MUL-42 --to-id <agent-uuid> --no-start+multica issue status MUL-42 in_progress --no-startmultica issue assign MUL-42 --unassign```脚本中用 `--to-id <uuid>` 可避免同名对象匹配错误。UUID 通过 `multica agent list --output json` 或 `multica workspace member list --output json` 查看。+如果指派只用于记录负责人、不应创建新任务(例如同一智能体已在另一次执行中处理该 issue),请使用 `--no-start`。`issue update` 和 `issue status` 同样支持这个 flag。如果只记录归属的流程同时修改负责人和状态,两条命令都要传入该 flag;抑制指派不会自动抑制后续状态变更触发的任务。+## 接下来- [在评论中 @智能体](/mentioning-agents) — 不改变负责人,处理新的问题。diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex 449aaf4a0b..c007689a70 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -227,9 +227,9 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| `issue` | `list` | イシューを一覧 | `--status`、`--priority`、`--assignee`、`--project`、`--metadata`(繰り返し可)、`--limit`、`--offset`、`--sort`、`--full-id` || | `get <id>` | 単一のイシューを表示 | || | `create` | イシューを作成 | `--title`(必須)、`--description` / `--description-stdin` / `--description-file`、`--status`、`--priority`、`--assignee`、`--parent`、`--stage`、`--project`、`--start-date`、`--due-date`、`--attachment`(繰り返し可) |-| | `update <id>` | イシューのフィールドを更新 | `create` と同系のフィールドに加え `--position` |-| | `assign <id>` | 割り当てまたは割り当て解除 | `--to`(メンバー、エージェント、スクワッドを名前であいまいマッチ)、`--to-id`、`--unassign` |-| | `status <id> <status>` | ステータスを変更 | |+| | `update <id>` | イシューのフィールドを更新 | `create` と同系のフィールドに加え `--position`、`--no-start` |+| | `assign <id>` | 割り当てまたは割り当て解除 | `--to`(メンバー、エージェント、スクワッドを名前であいまいマッチ)、`--to-id`、`--unassign`、`--no-start` |+| | `status <id> <status>` | ステータスを変更 | `--no-start` || | `reorder <id>` | カラム内で移動 | || | `search <query>` | イシューを検索 | `--limit`、`--include-closed` || | `children <id>` | サブイシューをステージごとに一覧 | |diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex d86820ec99..00da30b4cd 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -227,9 +227,9 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| `issue` | `list` | 이슈 목록 | `--status`, `--priority`, `--assignee`, `--project`, `--metadata`(반복 가능), `--limit`, `--offset`, `--sort`, `--full-id` || | `get <id>` | 이슈 하나 확인 | || | `create` | 이슈 생성 | `--title`(필수), `--description` / `--description-stdin` / `--description-file`, `--status`, `--priority`, `--assignee`, `--parent`, `--stage`, `--project`, `--start-date`, `--due-date`, `--attachment`(반복 가능) |-| | `update <id>` | 이슈 필드 업데이트 | `create`와 같은 종류의 필드에 `--position` 추가 |-| | `assign <id>` | 할당 또는 할당 해제 | `--to`(이름으로 멤버, 에이전트, 스쿼드 fuzzy match), `--to-id`, `--unassign` |-| | `status <id> <status>` | 상태 변경 | |+| | `update <id>` | 이슈 필드 업데이트 | `create`와 같은 종류의 필드에 `--position`, `--no-start` 추가 |+| | `assign <id>` | 할당 또는 할당 해제 | `--to`(이름으로 멤버, 에이전트, 스쿼드 fuzzy match), `--to-id`, `--unassign`, `--no-start` |+| | `status <id> <status>` | 상태 변경 | `--no-start` || | `reorder <id>` | 열 안에서 이동 | || | `search <query>` | 이슈 검색 | `--limit`, `--include-closed` || | `children <id>` | 단계별로 묶은 하위 이슈 목록 | |diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex 5d726f82b8..5eb8f469ed 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -248,9 +248,9 @@ The tables below cover every current top-level command, grouped the way the CLI| `issue` | `list` | List issues | `--status`, `--priority`, `--assignee`, `--project`, `--metadata` (repeatable), `--limit`, `--offset`, `--sort`, `--full-id` || | `get <id>` | Show a single issue | || | `create` | Create an issue | `--title` (required), `--description` / `--description-stdin` / `--description-file`, `--status`, `--priority`, `--assignee`, `--parent`, `--stage`, `--project`, `--start-date`, `--due-date`, `--attachment` (repeatable) |-| | `update <id>` | Update issue fields | Same fields as `create`, plus `--position` |-| | `assign <id>` | Assign or unassign | `--to` (fuzzy name match against members, agents, and squads), `--to-id`, `--unassign` |-| | `status <id> <status>` | Change status | |+| | `update <id>` | Update issue fields | Same fields as `create`, plus `--position`, `--no-start` |+| | `assign <id>` | Assign or unassign | `--to` (fuzzy name match against members, agents, and squads), `--to-id`, `--unassign`, `--no-start` |+| | `status <id> <status>` | Change status | `--no-start` || | `reorder <id>` | Move within a column | || | `search <query>` | Search issues | `--limit`, `--include-closed` || | `children <id>` | List sub-issues grouped by stage | |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 7b53bd33c6..e1510c5961 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -227,9 +227,9 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| `issue` | `list` | 列出 issue | `--status`、`--priority`、`--assignee`、`--project`、`--metadata`(可重复)、`--limit`、`--offset`、`--sort`、`--full-id` || | `get <id>` | 查看单个 issue | || | `create` | 创建 issue | `--title`(必填)、`--description` / `--description-stdin` / `--description-file`、`--status`、`--priority`、`--assignee`、`--parent`、`--stage`、`--project`、`--start-date`、`--due-date`、`--attachment`(可重复) |-| | `update <id>` | 更新 issue 字段 | 与 `create` 同类字段,另有 `--position` |-| | `assign <id>` | 指派或取消指派 | `--to`(名称模糊匹配成员、智能体或小队)、`--to-id`、`--unassign` |-| | `status <id> <status>` | 修改状态 | |+| | `update <id>` | 更新 issue 字段 | 与 `create` 同类字段,另有 `--position`、`--no-start` |+| | `assign <id>` | 指派或取消指派 | `--to`(名称模糊匹配成员、智能体或小队)、`--to-id`、`--unassign`、`--no-start` |+| | `status <id> <status>` | 修改状态 | `--no-start` || | `reorder <id>` | 在列内移动 | || | `search <query>` | 搜索 issue | `--limit`、`--include-closed` || | `children <id>` | 按阶段分组列出子 issue | |diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 8be012b256..a7ec13ea31 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -503,9 +503,11 @@ func init() {issueUpdateCmd.Flags().String("parent", "", "Parent issue ID (use --parent \"\" to clear)")issueUpdateCmd.Flags().Int("stage", 0, "Stage ordinal (>=1) for this sub-issue; see `issue create --stage`")issueUpdateCmd.Flags().Float64("position", 0, "Ordering position within the board column (lower sorts first); prefer `issue reorder` for relative moves")+ issueUpdateCmd.Flags().Bool("no-start", false, "Apply the update without starting an agent run")issueUpdateCmd.Flags().String("output", "json", "Output format: table or json")// issue status+ issueStatusCmd.Flags().Bool("no-start", false, "Change status without starting an agent run")issueStatusCmd.Flags().String("output", "table", "Output format: table or json")// issue reorder@@ -515,6 +517,7 @@ func init() {issueAssignCmd.Flags().String("to", "", "Assignee name (member, agent, or squad; fuzzy match)")issueAssignCmd.Flags().String("to-id", "", "Assignee UUID — member, agent, or squad (mutually exclusive with --to)")issueAssignCmd.Flags().Bool("unassign", false, "Remove current assignee")+ issueAssignCmd.Flags().Bool("no-start", false, "Assign ownership without starting an agent run")issueAssignCmd.Flags().String("output", "json", "Output format: table or json")// issue comment list@@ -1239,6 +1242,7 @@ func activeDuplicateIssueCreateMessage(err error) (string, bool) {}func runIssueUpdate(cmd *cobra.Command, args []string) error {+ noStart, _ := cmd.Flags().GetBool("no-start")statusChanged := cmd.Flags().Changed("status")statusFlag, _ := cmd.Flags().GetString("status")if statusChanged {@@ -1349,6 +1353,9 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {if len(body) == 0 {return fmt.Errorf("no fields to update; use flags like --title, --status, --priority, --assignee, etc.")}+ if noStart {+ body["suppress_run"] = true+ }var result map[string]anyif err := client.PutJSON(ctx, "/api/issues/"+issueRef.ID, body, &result); err != nil {@@ -1374,6 +1381,7 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {func runIssueAssign(cmd *cobra.Command, args []string) error {toName, _ := cmd.Flags().GetString("to")unassign, _ := cmd.Flags().GetBool("unassign")+ noStart, _ := cmd.Flags().GetBool("no-start")toNameSet := cmd.Flags().Changed("to")toIDSet := cmd.Flags().Changed("to-id")@@ -1383,6 +1391,9 @@ func runIssueAssign(cmd *cobra.Command, args []string) error {if (toNameSet || toIDSet) && unassign {return fmt.Errorf("--to/--to-id and --unassign are mutually exclusive")}+ if noStart && unassign {+ return fmt.Errorf("--no-start cannot be used with --unassign")+ }client, err := newAPIClient(cmd)if err != nil {@@ -1412,6 +1423,9 @@ func runIssueAssign(cmd *cobra.Command, args []string) error {if displayTarget == "" {displayTarget = loadActorDisplayLookup(ctx, client).actor(aType, aID)}+ if noStart {+ body["suppress_run"] = true+ }}var result map[string]any@@ -1435,6 +1449,7 @@ func runIssueAssign(cmd *cobra.Command, args []string) error {func runIssueStatus(cmd *cobra.Command, args []string) error {id := args[0]status := args[1]+ noStart, _ := cmd.Flags().GetBool("no-start")if err := validateIssueStatus(status); err != nil {return err@@ -1454,6 +1469,9 @@ func runIssueStatus(cmd *cobra.Command, args []string) error {}body := map[string]any{"status": status}+ if noStart {+ body["suppress_run"] = true+ }var result map[string]anyif err := client.PutJSON(ctx, "/api/issues/"+issueRef.ID, body, &result); err != nil {return fmt.Errorf("update status: %w", err)diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 2a908b3bfb..a12bcbfd2c 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -2817,11 +2817,30 @@ func newIssueUpdateTestCmd() *cobra.Command {cmd.Flags().String("start-date", "", "")cmd.Flags().String("due-date", "", "")cmd.Flags().String("parent", "", "")+ cmd.Flags().Int("stage", 0, "")cmd.Flags().Float64("position", 0, "")+ cmd.Flags().Bool("no-start", false, "")cmd.Flags().String("output", "json", "")return cmd}+func newIssueAssignTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "assign"}+ cmd.Flags().String("to", "", "")+ cmd.Flags().String("to-id", "", "")+ cmd.Flags().Bool("unassign", false, "")+ cmd.Flags().Bool("no-start", false, "")+ cmd.Flags().String("output", "json", "")+ return cmd+}++func newIssueStatusTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "status"}+ cmd.Flags().Bool("no-start", false, "")+ cmd.Flags().String("output", "table", "")+ return cmd+}+func newIssueListTestCmd() *cobra.Command {cmd := &cobra.Command{Use: "list"}cmd.Flags().String("output", "table", "")@@ -2880,6 +2899,118 @@ func TestRunIssueUpdateSendsPosition(t *testing.T) {}}+func TestRunIssueUpdateNoStartSendsSuppressRun(t *testing.T) {+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "todo"})+ case r.Method == http.MethodPut && r.URL.Path == "/api/issues/issue-1":+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("decode body: %v", err)+ }+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "in_progress"})+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "mat_test-token")++ cmd := newIssueUpdateTestCmd()+ _ = cmd.Flags().Set("status", "in_progress")+ _ = cmd.Flags().Set("no-start", "true")+ if err := runIssueUpdate(cmd, []string{"MUL-1"}); err != nil {+ t.Fatalf("runIssueUpdate: %v", err)+ }+ if got := body["suppress_run"]; got != true {+ t.Fatalf("suppress_run = %#v, want true", got)+ }+}++func TestRunIssueStatusNoStartSendsSuppressRun(t *testing.T) {+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "backlog"})+ case r.Method == http.MethodPut && r.URL.Path == "/api/issues/issue-1":+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("decode body: %v", err)+ }+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "in_progress"})+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "mat_test-token")++ cmd := newIssueStatusTestCmd()+ _ = cmd.Flags().Set("no-start", "true")+ if err := runIssueStatus(cmd, []string{"MUL-1", "in_progress"}); err != nil {+ t.Fatalf("runIssueStatus: %v", err)+ }+ if got := body["status"]; got != "in_progress" {+ t.Fatalf("status = %#v, want in_progress", got)+ }+ if got := body["suppress_run"]; got != true {+ t.Fatalf("suppress_run = %#v, want true", got)+ }+}++func TestRunIssueAssignNoStartSendsSuppressRun(t *testing.T) {+ const agentID = "5fb87ac7-23b5-4a7a-81fa-ed295a54545d"+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "todo"})+ case r.Method == http.MethodGet && r.URL.Path == "/api/workspaces/ws-1/members":+ json.NewEncoder(w).Encode([]map[string]any{})+ case r.Method == http.MethodGet && r.URL.Path == "/api/agents":+ json.NewEncoder(w).Encode([]map[string]any{{"id": agentID, "name": "CodeBot"}})+ case r.Method == http.MethodGet && r.URL.Path == "/api/squads":+ json.NewEncoder(w).Encode([]map[string]any{})+ case r.Method == http.MethodPut && r.URL.Path == "/api/issues/issue-1":+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("decode body: %v", err)+ }+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "todo"})+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "mat_test-token")++ cmd := newIssueAssignTestCmd()+ _ = cmd.Flags().Set("to-id", agentID)+ _ = cmd.Flags().Set("no-start", "true")+ if err := runIssueAssign(cmd, []string{"MUL-1"}); err != nil {+ t.Fatalf("runIssueAssign: %v", err)+ }+ if got := body["suppress_run"]; got != true {+ t.Fatalf("suppress_run = %#v, want true", got)+ }+}++func TestRunIssueAssignRejectsNoStartWithUnassign(t *testing.T) {+ cmd := newIssueAssignTestCmd()+ _ = cmd.Flags().Set("unassign", "true")+ _ = cmd.Flags().Set("no-start", "true")+ err := runIssueAssign(cmd, []string{"MUL-1"})+ if err == nil || !strings.Contains(err.Error(), "--no-start") {+ t.Fatalf("expected --no-start validation error, got %v", err)+ }+}+func TestIssueReadCommandsUseInjectedTaskToken(t *testing.T) {const fakeTaskToken = "mat_task_issue_sentinel"ownerHome := t.TempDir()diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex 66a42fb93a..2f1432de45 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -1080,10 +1080,12 @@ func TestInjectRuntimeConfigAvailableCommandsCoreOnly(t *testing.T) {"multica issue comment list <issue-id>","multica issue create --title","multica issue update <id>",+ "multica issue assign <id>",+ "--no-start","--description-file <path>","--parent \"\"","multica repo checkout <url>",- "multica issue status <id> <status>",+ "multica issue status <id> <status> [--no-start]","multica issue comment add <issue-id>","multica issue comment add --help",} {@@ -1132,7 +1134,6 @@ func TestInjectRuntimeConfigAvailableCommandsCoreOnly(t *testing.T) {"multica autopilot delete","multica project get","multica project resource list",- "multica issue assign","multica issue label add","multica issue label remove","multica issue subscriber add",diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex a126134547..ee514d1208 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -260,8 +260,12 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("- `multica issue get <id> --output json` — full issue.\n")b.WriteString("- `multica issue comment list <issue-id> [--roots-only] [--summary] [--thread <comment-id> [--tail N] | --recent N] [--since <RFC3339>] --output json` — thread-aware comment reads. Bound a wide read with `--roots-only --summary` (roots plus `reply_count` / `last_activity_at`, clipped bodies); bound a deep one with `--thread <id> --tail N`; add `--compact` to any JSON read to drop echoed/null/bookkeeping fields. Careful with `--recent N`: it caps THREADS, not comments, and can return the whole history on a small issue. Resolved-thread folding, paging cursors, and full flag semantics: `--help`.\n")b.WriteString("- `multica issue create --title \"...\" [--description-file <path>] [--priority X] [--status X] [--assignee X | --assignee-id <uuid>] [--parent <issue-id>] [--stage N] [--project <project-id>] [--due-date <YYYY-MM-DD>] [--attachment <path>]` — create an issue. For agent-authored long descriptions prefer `--description-file <path>` (heredoc stdin can swallow trailing flags, #4182). Write that file inside your working directory (e.g. `./description.md`), never `/tmp` or shared paths — same workdir rule as `## Comment Formatting`.\n")- b.WriteString("- `multica issue update <id> [--title X] [--description-file <path>] [--priority X] [--status X] [--assignee X] [--parent <issue-id>] [--stage N] [--project <project-id>] [--due-date <YYYY-MM-DD>]` — update fields; pass `--parent \"\"` to clear parent.\n")- b.WriteString("- `multica issue status <id> <status>` — flip status (todo / in_progress / in_review / done / blocked / backlog / cancelled).\n")+ b.WriteString("- `multica issue update <id> [--title X] [--description-file <path>] [--priority X] [--status X] [--assignee X] [--parent <issue-id>] [--stage N] [--project <project-id>] [--due-date <YYYY-MM-DD>] [--no-start]` — update fields; pass `--parent \"\"` to clear parent. `--no-start` applies ownership/status changes without starting another agent run.\n")+ // Assign deliberately stays in the core brief: it is the action that can+ // create an unaware cross-issue run, and agents cannot discover the safe+ // ownership-only --no-start path if the command is hidden behind --help.+ b.WriteString("- `multica issue assign <id> (--to X | --to-id <uuid> | --unassign) [--no-start]` — change ownership. Use `--no-start` when claiming an issue from work already underway so the ownership write does not launch a duplicate run.\n")+ b.WriteString("- `multica issue status <id> <status> [--no-start]` — flip status (todo / in_progress / in_review / done / blocked / backlog / cancelled). Use `--no-start` when the status write belongs to work already underway in another run.\n")b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file`; see `## Comment Formatting` for why. `multica issue comment add --help` for full flags.\n")b.WriteString("- `multica issue metadata list <issue-id> [--output json]` — list KV metadata.\n")@@ -565,7 +569,7 @@ func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("1. Read the issue (`multica issue get`) to understand the context.\n")b.WriteString("2. Read the metadata bag (`multica issue metadata list`) — best-effort, empty `{}` and CLI failures are normal. What to look for: `## Issue Metadata`.\n")b.WriteString("3. 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. In Reply mode 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("4. 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.\n")+ b.WriteString("4. 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 assigning an issue to yourself, check the target issue's comment history for an existing claim and inspect any `## Active sibling runs` with the concrete `run-messages` commands it provides. If assignment or status only records ownership/progress for work already being done, pass `--no-start` on every such command; keep the default start behavior for an intentional handoff to fresh work.\n")if ctx.IsSquadLeader {b.WriteString("5. **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`). 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 {diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex c6dd023a81..8f311685f3 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -76,6 +76,7 @@ const (// Returns "" when none of the blocks apply.func perTurnContextBlocks(task Task) string {var b strings.Builder+ b.WriteString(buildActiveSiblingRunsBlock(task.IssueID, task.ActiveSiblingRuns))if task.PriorSessionResumeUnavailable {b.WriteString(sessionContinuityNoticeFor(task))}@@ -84,6 +85,40 @@ func perTurnContextBlocks(task Task) string {return b.String()}+func buildActiveSiblingRunsBlock(currentIssueID string, runs []ActiveSiblingRunData) string {+ // Sibling issue work is useful context only for another issue task. Chat,+ // autopilot, and quick-create tasks have no current target issue whose claim+ // history they could inspect, so rendering this block there creates an+ // unactionable warning.+ if currentIssueID == "" || len(runs) == 0 {+ return ""+ }+ var b strings.Builder+ b.WriteString("## Active sibling runs\n\n")+ b.WriteString("This agent has other in-flight issue tasks. They may be intentional, but before starting overlapping code or PR work, check for a claim or handoff in the current target issue's comment history")+ fmt.Fprintf(&b, " with `multica issue comment list %s --roots-only --summary --compact --output json`", currentIssueID)+ b.WriteString(", then inspect any relevant sibling task with the concrete `run-messages` command below. If another run assigned this issue, coordinate with that work instead of independently opening a second PR. If you only need to claim ownership or change status for work already underway, use `--no-start` on `multica issue assign`, `multica issue update`, or `multica issue status`.\n\n")+ for _, run := range runs {+ issueLabel := run.IssueIdentifier+ if issueLabel == "" {+ issueLabel = run.IssueID+ }+ fmt.Fprintf(&b, "- %s — task `%s`, status `%s`", issueLabel, run.TaskID, run.Status)+ if run.StartedAt != "" {+ fmt.Fprintf(&b, ", started %s", run.StartedAt)+ } else if run.CreatedAt != "" {+ fmt.Fprintf(&b, ", created %s", run.CreatedAt)+ }+ title := strings.TrimSpace(strings.NewReplacer("\r", " ", "\n", " ").Replace(run.IssueTitle))+ if title != "" {+ fmt.Fprintf(&b, ": %s", title)+ }+ fmt.Fprintf(&b, "; inspect: `multica issue run-messages %s`\n", run.TaskID)+ }+ b.WriteString("\n")+ return b.String()+}+// BuildPrompt constructs the task prompt for an agent CLI.// Keep this minimal — detailed instructions live in CLAUDE.md / AGENTS.md// injected by execenv.InjectRuntimeConfig. The provider string is threadeddiff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex 64429c103a..319e34938f 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -992,6 +992,55 @@ func TestBuildPromptDefaultScansRootsFirst(t *testing.T) {}}+func TestBuildPromptWarnsAboutActiveSiblingRuns(t *testing.T) {+ task := Task{+ IssueID: "issue-target",+ ActiveSiblingRuns: []ActiveSiblingRunData{{+ TaskID: "task-existing",+ IssueID: "issue-source",+ IssueIdentifier: "MUL-6000",+ IssueTitle: "Existing work",+ Status: "running",+ StartedAt: "2026-08-14T03:00:00Z",+ }},+ }+ out := BuildPrompt(task, "claude")+ for _, want := range []string{+ "Active sibling runs",+ "MUL-6000",+ "task-existing",+ "multica issue comment list issue-target --roots-only --summary --compact --output json",+ "multica issue run-messages task-existing",+ "--no-start",+ } {+ if !strings.Contains(out, want) {+ t.Errorf("prompt missing %q\n--- output ---\n%s", want, out)+ }+ }+ if strings.Contains(out, "multica issue runs") {+ t.Errorf("prompt must not direct overlap checks to the target issue's run list\n--- output ---\n%s", out)+ }+ if strings.Contains(out, "run-messages task-existing --issue") {+ t.Errorf("prompt must not resolve the issue when the task id is already complete\n--- output ---\n%s", out)+ }+}++func TestBuildPromptOmitsActiveSiblingRunsForChatTask(t *testing.T) {+ task := Task{+ ChatSessionID: "chat-1",+ ActiveSiblingRuns: []ActiveSiblingRunData{{+ TaskID: "task-existing",+ IssueID: "issue-source",+ IssueIdentifier: "MUL-6000",+ Status: "running",+ }},+ }+ out := BuildPrompt(task, "claude")+ if strings.Contains(out, "Active sibling runs") || strings.Contains(out, "task-existing") {+ t.Errorf("chat prompt must not include issue sibling guidance\n--- output ---\n%s", out)+ }+}+// TestBuildPromptNonSquadLeaderNoRule verifies that non-squad-leader agents// do NOT get the squad leader no_action rule injected.func TestBuildPromptNonSquadLeaderNoRule(t *testing.T) {diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex d05970891a..ed20e13e0d 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -54,6 +54,19 @@ type ProjectResourceData struct {// sharing the canonical JSON shape with the runtime app metadata package.type ConnectedAppData = runtimeapps.ConnectedApp+// ActiveSiblingRunData mirrors the claim-time warning context returned by the+// server for another in-flight issue task owned by this agent. Queued tasks are+// intentionally excluded from this context.+type ActiveSiblingRunData struct {+ TaskID string `json:"task_id"`+ IssueID string `json:"issue_id"`+ IssueIdentifier string `json:"issue_identifier"`+ IssueTitle string `json:"issue_title"`+ Status string `json:"status"`+ CreatedAt string `json:"created_at"`+ StartedAt string `json:"started_at,omitempty"`+}+// Task represents a claimed task from the server.// Agent data (name, skills) is populated by the claim endpoint.type Task struct {@@ -68,6 +81,7 @@ type Task struct {// regardless of task kind so the daemon can inject `## Workspace Context`// into the brief. Empty when the owner hasn't set one.WorkspaceContext string `json:"workspace_context,omitempty"`+ ActiveSiblingRuns []ActiveSiblingRunData `json:"active_sibling_runs,omitempty"`ThreadName string `json:"thread_name,omitempty"` // semantic title for provider-native session/thread historyAgent *AgentData `json:"agent,omitempty"`ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // per-run app capabilities mounted through runtime MCP overlaysdiff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 4ba9724222..215133b191 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -293,6 +293,20 @@ type ProjectResourceData struct {// while sharing the canonical JSON shape with the runtime app metadata package.type ConnectedAppData = runtimeapps.ConnectedApp+// ActiveSiblingRunData is bounded claim-time context about another in-flight+// issue task for the same agent. Queued tasks are intentionally absent because+// they cannot coordinate yet. It lets the daemon warn a newly claimed run+// before it repeats code or PR work already underway elsewhere.+type ActiveSiblingRunData struct {+ TaskID string `json:"task_id"`+ IssueID string `json:"issue_id"`+ IssueIdentifier string `json:"issue_identifier"`+ IssueTitle string `json:"issue_title"`+ Status string `json:"status"`+ CreatedAt string `json:"created_at"`+ StartedAt string `json:"started_at,omitempty"`+}+type AgentTaskResponse struct {ID string `json:"id"`AgentID string `json:"agent_id"`@@ -305,31 +319,32 @@ type AgentTaskResponse struct {// as `## Workspace Context` so every agent running in this workspace —// regardless of issue / chat / autopilot / quick-create — sees the same// shared context. Empty when the workspace owner hasn't set it.- WorkspaceContext string `json:"workspace_context,omitempty"`- ThreadName string `json:"thread_name,omitempty"` // semantic title for provider-native session/thread history- Status string `json:"status"`- Priority int32 `json:"priority"`- DispatchedAt *string `json:"dispatched_at"`- StartedAt *string `json:"started_at"`- CompletedAt *string `json:"completed_at"`- Result any `json:"result"`- Error *string `json:"error"`- FailureReason string `json:"failure_reason,omitempty"` // see TaskService.MaybeRetryFailedTask- Attempt int32 `json:"attempt"`- 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 name- Agent *TaskAgentData `json:"agent,omitempty"`- ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // daemon-claim only: per-run app capabilities mounted through runtime MCP overlays- Repos []RepoData `json:"repos,omitempty"`- ProjectID string `json:"project_id,omitempty"` // issue's project, when present- ProjectTitle string `json:"project_title,omitempty"` // for surfacing in agent context- ProjectDescription string `json:"project_description,omitempty"` // durable project-level context injected into the brief- ProjectResources []ProjectResourceData `json:"project_resources,omitempty"` // resources attached to the project- CreatedAt string `json:"created_at"`- PriorSessionID string `json:"prior_session_id,omitempty"` // session ID from a previous task on same issue- PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issue+ WorkspaceContext string `json:"workspace_context,omitempty"`+ ActiveSiblingRuns []ActiveSiblingRunData `json:"active_sibling_runs,omitempty"`+ ThreadName string `json:"thread_name,omitempty"` // semantic title for provider-native session/thread history+ Status string `json:"status"`+ Priority int32 `json:"priority"`+ DispatchedAt *string `json:"dispatched_at"`+ StartedAt *string `json:"started_at"`+ CompletedAt *string `json:"completed_at"`+ Result any `json:"result"`+ Error *string `json:"error"`+ FailureReason string `json:"failure_reason,omitempty"` // see TaskService.MaybeRetryFailedTask+ Attempt int32 `json:"attempt"`+ 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 name+ Agent *TaskAgentData `json:"agent,omitempty"`+ ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // daemon-claim only: per-run app capabilities mounted through runtime MCP overlays+ Repos []RepoData `json:"repos,omitempty"`+ ProjectID string `json:"project_id,omitempty"` // issue's project, when present+ ProjectTitle string `json:"project_title,omitempty"` // for surfacing in agent context+ ProjectDescription string `json:"project_description,omitempty"` // durable project-level context injected into the brief+ ProjectResources []ProjectResourceData `json:"project_resources,omitempty"` // resources attached to the project+ CreatedAt string `json:"created_at"`+ PriorSessionID string `json:"prior_session_id,omitempty"` // session ID from a previous task on same issue+ PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issue// PriorSessionResumeUnavailable is set when a more recent Codex session was// withheld because its rollout was missing (MUL-5305); PriorSessionID (if// any) is then an older fallback. The daemon surfaces the continuity gap indiff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex e87c732627..cb0af31d51 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -2711,6 +2711,37 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu}}+ // Surface a bounded snapshot of the same agent's other in-flight issue+ // tasks. Queued tasks cannot coordinate yet and are intentionally omitted.+ // This is advisory context, not a queue gate: cross-issue parallelism and+ // serial handoffs remain valid, while the prompt can stop an unaware second+ // run from opening a duplicate PR. Scope the query to the already-validated+ // runtime workspace so corrupt cross-tenant task links never leak.+ if siblings, err := h.Queries.ListActiveSiblingIssueTasks(r.Context(), db.ListActiveSiblingIssueTasksParams{+ AgentID: task.AgentID,+ TaskID: task.ID,+ WorkspaceID: parseUUID(resp.WorkspaceID),+ }); err == nil {+ resp.ActiveSiblingRuns = make([]ActiveSiblingRunData, 0, len(siblings))+ for _, sibling := range siblings {+ resp.ActiveSiblingRuns = append(resp.ActiveSiblingRuns, ActiveSiblingRunData{+ TaskID: uuidToString(sibling.TaskID),+ IssueID: uuidToString(sibling.IssueID),+ IssueIdentifier: fmt.Sprintf("%s-%d", sibling.IssuePrefix, sibling.IssueNumber),+ IssueTitle: sibling.IssueTitle,+ Status: sibling.Status,+ CreatedAt: timestampToString(sibling.CreatedAt),+ StartedAt: timestampToString(sibling.StartedAt),+ })+ }+ } else {+ slog.Warn("task claim: failed to load active sibling runs",+ "task_id", uuidToString(task.ID),+ "agent_id", uuidToString(task.AgentID),+ "error", err,+ )+ }+// Workspace-level Context (workspace.context DB column) — the per-workspace// system prompt that workspace owners set in Settings → General. Inject it// into the brief regardless of task kind (issue / chat / autopilot /diff --git a/server/internal/handler/daemon_batch_claim_test.go b/server/internal/handler/daemon_batch_claim_test.goindex 80f0aae5f5..34c7636fb5 100644--- a/server/internal/handler/daemon_batch_claim_test.go+++ b/server/internal/handler/daemon_batch_claim_test.go@@ -13,9 +13,15 @@ import (// returns, with the few fields these tests assert on.type batchClaimResponse struct {Tasks []struct {- ID string `json:"id"`- RuntimeID string `json:"runtime_id"`- AuthToken string `json:"auth_token"`+ ID string `json:"id"`+ RuntimeID string `json:"runtime_id"`+ AuthToken string `json:"auth_token"`+ ActiveSiblingRuns []struct {+ TaskID string `json:"task_id"`+ IssueID string `json:"issue_id"`+ IssueIdentifier string `json:"issue_identifier"`+ Status string `json:"status"`+ } `json:"active_sibling_runs"`} `json:"tasks"`}@@ -87,6 +93,64 @@ func TestClaimTasksByRuntime_RoutesAcrossRuntimesAndMintsTokens(t *testing.T) {}}+func TestClaimTasksByRuntime_IncludesActiveSiblingRun(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ runtimeID := createClaimReclaimRuntime(t, ctx, "Sibling claim runtime")+ agentID, sourceIssueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Sibling claim agent")+ if _, err := testPool.Exec(ctx, `UPDATE agent SET max_concurrent_tasks = 2 WHERE id = $1`, agentID); err != nil {+ t.Fatalf("raise concurrency: %v", err)+ }+ insertRunningIssueTask(t, agentID, sourceIssueID)++ var targetIssueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'sibling target', 'todo', 'none', $2, 'member',+ (SELECT COALESCE(MAX(number), 82649) + 1 FROM issue WHERE workspace_id = $1), 0)+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&targetIssueID); err != nil {+ t.Fatalf("create target issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, targetIssueID) })+ queuedID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, targetIssueID)++ // A queued task cannot coordinate yet and must not dilute the warning. Seed+ // it after the target so the deterministic claim order still picks queuedID.+ var queuedSiblingIssueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'queued sibling', 'todo', 'none', $2, 'member',+ (SELECT COALESCE(MAX(number), 82649) + 1 FROM issue WHERE workspace_id = $1), 0)+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&queuedSiblingIssueID); err != nil {+ t.Fatalf("create queued sibling issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, queuedSiblingIssueID) })+ seedQueuedIssueTask(t, ctx, agentID, runtimeID, queuedSiblingIssueID)++ w := postBatchClaim(t, testWorkspaceID, []string{runtimeID}, 1)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 1 || resp.Tasks[0].ID != queuedID {+ t.Fatalf("claimed task = %+v, want %s", resp.Tasks, queuedID)+ }+ if len(resp.Tasks[0].ActiveSiblingRuns) != 1 {+ t.Fatalf("active_sibling_runs = %+v, want one running sibling", resp.Tasks[0].ActiveSiblingRuns)+ }+ sibling := resp.Tasks[0].ActiveSiblingRuns[0]+ if sibling.IssueID != sourceIssueID || sibling.Status != "running" || sibling.IssueIdentifier == "" {+ t.Fatalf("wrong sibling payload: %+v", sibling)+ }+}+// TestClaimTasksByRuntime_SkipsCrossWorkspaceRuntime is the security-critical// case: a daemon token scoped to workspace A must not claim a task routed to a// runtime in workspace B, even when B's runtime_id is included in the request.diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex 21b1b5c9ef..bf4d68f5f4 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -3398,6 +3398,171 @@ func TestBacklogToTodoByAgentSameAgentDifferentIssue(t *testing.T) {}}+// TestAssignIssueToSelfWithActiveTargetRunDoesNotDuplicate covers the direct+// assignment form of #6947: an agent already working on an issue may claim its+// ownership, but that ownership write must not enqueue a second run for the+// same (issue, agent) pair.+func TestAssignIssueToSelfWithActiveTargetRunDoesNotDuplicate(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentID := createHandlerTestAgent(t, "Self Assign Active Target", nil)++ issue := createIssueForTest(t, map[string]any{"title": "self-assign active target", "status": "todo"})+ runningTask := createHandlerTestTaskForAgentOnIssue(t, agentID, issue.ID)++ previewRecorder := httptest.NewRecorder()+ previewReq := newRequest("POST", "/api/issues/preview-trigger?workspace_id="+testWorkspaceID, map[string]any{+ "issue_ids": []string{issue.ID},+ "assignee_type": "agent",+ "assignee_id": agentID,+ })+ previewReq.Header.Set("X-Agent-ID", agentID)+ previewReq.Header.Set("X-Task-ID", runningTask)+ testHandler.PreviewIssueTrigger(previewRecorder, previewReq)+ if previewRecorder.Code != http.StatusOK {+ t.Fatalf("PreviewIssueTrigger: expected 200, got %d: %s", previewRecorder.Code, previewRecorder.Body.String())+ }+ var preview IssueTriggerPreviewResponse+ if err := json.NewDecoder(previewRecorder.Body).Decode(&preview); err != nil {+ t.Fatalf("decode preview: %v", err)+ }+ if preview.TotalCount != 0 {+ t.Fatalf("preview promised a duplicate self-assignment run: %+v", preview)+ }++ w := httptest.NewRecorder()+ req := withURLParam(newRequest("PUT", "/api/issues/"+issue.ID, map[string]any{+ "assignee_type": "agent",+ "assignee_id": agentID,+ }), "id", issue.ID)+ req.Header.Set("X-Agent-ID", agentID)+ req.Header.Set("X-Task-ID", runningTask)+ testHandler.UpdateIssue(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := queuedTaskCountFor(t, issue.ID, agentID); got != 0 {+ t.Fatalf("self-assignment duplicated an active target run: got %d queued task(s)", got)+ }+ if got := taskStatus(t, runningTask); got != "running" {+ t.Fatalf("existing target run must survive ownership claim, got status %q", got)+ }+}++func TestShouldSuppressActiveSelfAssignmentFailsClosedOnLookupError(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ const agentID = "1c331d0b-94fd-412a-a7cc-6a209add00a1"+ const issueID = "34c44eb2-bd85-455f-b47c-f39cc7b0b913"+ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ if !testHandler.shouldSuppressActiveSelfAssignment(+ ctx,+ "agent",+ agentID,+ parseUUID(issueID),+ parseUUID(agentID),+ ) {+ t.Fatal("lookup failure must fail closed and suppress duplicate enqueue")+ }+}++// TestAssignDifferentIssueToSelfStillEnqueues locks in the intentional+// cross-issue handoff behavior: an agent working on I1 may assign fresh I2 to+// itself, and I2 still gets a queued run.+func TestAssignDifferentIssueToSelfStillEnqueues(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentID := createHandlerTestAgent(t, "Cross Issue Self Assign", nil)+ source := createIssueForTest(t, map[string]any{"title": "cross-issue source", "status": "todo"})+ target := createIssueForTest(t, map[string]any{"title": "cross-issue target", "status": "todo"})+ sourceTask := createHandlerTestTaskForAgentOnIssue(t, agentID, source.ID)++ w := httptest.NewRecorder()+ req := withURLParam(newRequest("PUT", "/api/issues/"+target.ID, map[string]any{+ "assignee_type": "agent",+ "assignee_id": agentID,+ }), "id", target.ID)+ req.Header.Set("X-Agent-ID", agentID)+ req.Header.Set("X-Task-ID", sourceTask)+ testHandler.UpdateIssue(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := queuedTaskCountFor(t, target.ID, agentID); got != 1 {+ t.Fatalf("cross-issue self-assignment should enqueue one run, got %d", got)+ }+}++// TestBatchAssignFreshIssuesToSelfEnqueuesEach protects triage/autopilot+// batches: being busy on a source issue is not a global self-assignment ban.+// Every fresh target keeps the existing enqueue behavior.+func TestBatchAssignFreshIssuesToSelfEnqueuesEach(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentID := createHandlerTestAgent(t, "Batch Fresh Self Assign", nil)+ source := createIssueForTest(t, map[string]any{"title": "batch source", "status": "todo"})+ target1 := createIssueForTest(t, map[string]any{"title": "batch target one", "status": "todo"})+ target2 := createIssueForTest(t, map[string]any{"title": "batch target two", "status": "todo"})+ sourceTask := createHandlerTestTaskForAgentOnIssue(t, agentID, source.ID)++ w := httptest.NewRecorder()+ req := newRequest("PATCH", "/api/issues/batch?workspace_id="+testWorkspaceID, map[string]any{+ "issue_ids": []string{target1.ID, target2.ID},+ "updates": map[string]any{+ "assignee_type": "agent",+ "assignee_id": agentID,+ },+ })+ req.Header.Set("X-Agent-ID", agentID)+ req.Header.Set("X-Task-ID", sourceTask)+ testHandler.BatchUpdateIssues(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("BatchUpdateIssues: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ for _, target := range []IssueResponse{target1, target2} {+ if got := queuedTaskCountFor(t, target.ID, agentID); got != 1 {+ t.Fatalf("fresh target %s should enqueue one run, got %d", target.ID, got)+ }+ }+}++// TestAssignActiveIssueToDifferentAgentStillEnqueues verifies the duplicate+// guard never turns a real agent-to-agent transfer into an ownership-only+// update. The old task survives per #4963 and the new assignee gets a run.+func TestAssignActiveIssueToDifferentAgentStillEnqueues(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ actorAgent := createHandlerTestAgent(t, "Active Transfer Actor", nil)+ targetAgent := createHandlerTestAgent(t, "Active Transfer Target", nil)+ issue := createIssueForTest(t, map[string]any{"title": "active transfer", "status": "todo"})+ actorTask := createHandlerTestTaskForAgentOnIssue(t, actorAgent, issue.ID)++ w := httptest.NewRecorder()+ req := withURLParam(newRequest("PUT", "/api/issues/"+issue.ID, map[string]any{+ "assignee_type": "agent",+ "assignee_id": targetAgent,+ }), "id", issue.ID)+ req.Header.Set("X-Agent-ID", actorAgent)+ req.Header.Set("X-Task-ID", actorTask)+ testHandler.UpdateIssue(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := queuedTaskCountFor(t, issue.ID, targetAgent); got != 1 {+ t.Fatalf("new assignee should get one queued run, got %d", got)+ }+ if got := taskStatus(t, actorTask); got != "running" {+ t.Fatalf("old active task must survive transfer, got status %q", got)+ }+}+// TestBatchBacklogToTodoByAgentTriggersAssignee mirrors the single-update// serial-chain test on the BatchUpdateIssues path. Earlier the// member-only gate would silently drop agent-driven batch promotions; thediff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex a9bf5e6f3c..1bbf2818bd 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -3159,7 +3159,7 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {AssigneeChanged: assigneeChanged,StatusChanged: statusChanged,},- h.issueTriggerWriteProbe(r, actorType, issue),+ h.issueTriggerWriteProbe(r, actorType, actorID, issue),); ok && !req.SuppressRun {h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, req.HandoffNote)}@@ -3718,7 +3718,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {AssigneeChanged: assigneeChanged,StatusChanged: statusChanged,},- h.issueTriggerWriteProbe(r, actorType, issue),+ h.issueTriggerWriteProbe(r, actorType, actorID, issue),); ok && !req.Updates.SuppressRun {h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, req.Updates.HandoffNote)}diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.goindex 5d7c7cfb74..af062414c9 100644--- a/server/internal/handler/issue_trigger.go+++ b/server/internal/handler/issue_trigger.go@@ -3,6 +3,7 @@ package handlerimport ("context""encoding/json"+ "log/slog""net/http""github.com/jackc/pgx/v5/pgtype"@@ -21,12 +22,22 @@ const maxPreviewTriggerIssues = 500// boundary (validateAssigneePair on assign) and inside enqueueSquadLeaderTask// (canEnqueueSquadLeader), so a write must NOT re-run or sink it — it passes// allow-all. The self-loop check needs the request's X-Task-ID header.-func (h *Handler) issueTriggerWriteProbe(r *http.Request, actorType string, issue db.Issue) service.IssueTriggerProbe {+func (h *Handler) issueTriggerWriteProbe(r *http.Request, actorType, actorID string, issue db.Issue) service.IssueTriggerProbe {return service.IssueTriggerProbe{CanAccessAgent: nil, // allow-all; gate lives at the write boundaryIsSelfLoop: func() bool {return h.isAgentRunningOnIssue(r, actorType, issue)},+ SuppressActiveSelfAssignment: func(agentID pgtype.UUID) bool {+ suppress := h.shouldSuppressActiveSelfAssignment(r.Context(), actorType, actorID, issue.ID, agentID)+ if suppress {+ slog.Info("suppressing duplicate self-assignment enqueue",+ "issue_id", uuidToString(issue.ID),+ "agent_id", uuidToString(agentID),+ )+ }+ return suppress+ },}}@@ -43,7 +54,27 @@ func (h *Handler) issueTriggerPreviewProbe(r *http.Request, actorType, actorID,IsSelfLoop: func() bool {return h.isAgentRunningOnIssue(r, actorType, issue)},+ SuppressActiveSelfAssignment: func(agentID pgtype.UUID) bool {+ return h.shouldSuppressActiveSelfAssignment(r.Context(), actorType, actorID, issue.ID, agentID)+ },+ }+}++// shouldSuppressActiveSelfAssignment prevents a trusted task-scoped agent+// actor from creating another run for the target pair merely to claim issue+// ownership. It intentionally checks the TARGET pair, not whether the actor is+// busy anywhere: cross-issue self handoffs are a supported workflow and must+// still enqueue when the target has no active run. Query errors fail closed+// against the external enqueue side effect while leaving the ownership write+// itself intact. The API still returns success for that ownership write; only+// the server log exposes the failed advisory lookup, because enqueue is the+// optional side effect and suppressing it is safer than risking duplicate work.+func (h *Handler) shouldSuppressActiveSelfAssignment(ctx context.Context, actorType, actorID string, issueID, targetAgentID pgtype.UUID) bool {+ if actorType != "agent" || actorID == "" || actorID != uuidToString(targetAgentID) {+ return false}+ active, err := h.hasActiveTaskForIssueAndAgent(ctx, issueID, targetAgentID)+ return active || err != nil}// dispatchIssueRun executes the enqueue side effect for a decision produced bydiff --git a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md b/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.mdindex 14568a7665..1d4532cdf6 100644--- a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md+++ b/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md@@ -202,6 +202,30 @@ on it. These are the contracts, not advice:`todo` when no active task / retry remains — that is the main server-ownedstatus write on the agent-run path.+## Claim ownership without duplicating a run++Assigning an active issue to an agent normally starts a run. When an agent is+already doing the work and only needs to record ownership, suppress that side+effect explicitly:++```bash+multica issue assign <issue-id> --to-id <agent-id> --no-start+# Or when assignment is part of a wider update:+multica issue update <issue-id> --assignee-id <agent-id> --no-start+# Keep a status change in the same ownership-only flow from starting a run:+multica issue status <issue-id> in_progress --no-start+```++Before self-assigning, inspect the target issue's comment history for an existing+claim, then use the concrete `run-messages` commands in any `## Active sibling+runs` block to inspect work already underway. Apply `--no-start` to every+assignment or status change that belongs to that ownership-only flow; suppressing+the assignment alone does not suppress a later status update. The server also+suppresses a trusted self-assignment when the exact target `(issue, agent)` pair+already has a non-terminal task. It deliberately does not block a same-agent+handoff to a fresh issue: cross-issue serial and batch workflows keep their+existing start behavior.+## Sub-issues: `todo` starts work now, `backlog` parks itOn an agent-assigned issue, create status decides whether the assignee firesdiff --git a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md b/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.mdindex 5cfb80150f..226a93754e 100644--- a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md+++ b/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md@@ -145,6 +145,21 @@ never cancels tasks now. `CancelTasksForIssue` fires only from the issue-deletiopaths (`DeleteIssue` / `BatchDeleteIssues`), where the owning issue row is goingaway, so no task is left orphaned.+## Ownership-only assignment and duplicate-run awareness++| Behavior | Source |+|---|---|+| `issue assign --no-start`, `issue update --no-start`, and `issue status --no-start` send `suppress_run=true` | `server/cmd/multica/cmd_issue.go` (`runIssueAssign`, `runIssueUpdate`, `runIssueStatus`) |+| Update and batch-update apply ownership while skipping dispatch when `suppress_run` is true | `server/internal/handler/issue.go` (`UpdateIssue`, `BatchUpdateIssues`) |+| Trusted direct self-assignment suppresses enqueue only when the target `(issue, agent)` already has a non-terminal task | `server/internal/service/issue_trigger.go` (`WillEnqueueRun`), `server/internal/handler/issue_trigger.go` (`shouldSuppressActiveSelfAssignment`) |+| Claim responses expose a bounded, workspace-scoped snapshot of the same agent's other dispatched/running/waiting issue tasks; queued tasks are excluded | `server/pkg/db/queries/agent.sql` (`ListActiveSiblingIssueTasks`), `server/internal/handler/daemon.go` (`buildClaimedTaskResponse`) |+| Daemon prompts point to the target's comment history and concrete sibling `run-messages` commands | `server/internal/daemon/prompt.go` (`buildActiveSiblingRunsBlock`) |++The self-assignment guard is intentionally pair-scoped. It does not treat+"this agent is busy on some other issue" as a reason to suppress a fresh+cross-issue handoff, because serial sub-issue promotion and triage batches rely+on those assignments creating their normal queued runs.+## Sub-issue stages (barrier wake)| Behavior | File:line |diff --git a/server/internal/service/issue_trigger.go b/server/internal/service/issue_trigger.goindex cbf6fd3308..057e04d55e 100644--- a/server/internal/service/issue_trigger.go+++ b/server/internal/service/issue_trigger.go@@ -32,10 +32,17 @@ const (//// IsSelfLoop reports whether promoting this issue out of backlog would be the// calling agent re-triggering its own running task. Only the status source-// consults it; create and assign never do. A nil func means "not a self-loop".+// consults it. A nil func means "not a self-loop".+//+// SuppressActiveSelfAssignment reports whether a direct agent assignment is a+// trusted agent claiming ownership for itself while the target (issue, agent)+// pair already has a non-terminal task. The ownership update still succeeds;+// only the duplicate enqueue is suppressed. Cross-issue handoffs to a fresh+// target remain runnable. A nil func means "do not suppress".type IssueTriggerProbe struct {- CanAccessAgent func(agent db.Agent) bool- IsSelfLoop func() bool+ CanAccessAgent func(agent db.Agent) bool+ IsSelfLoop func() bool+ SuppressActiveSelfAssignment func(agentID pgtype.UUID) bool}// IssueTriggerInput describes one prospective issue write in its post-write@@ -123,6 +130,10 @@ func (s *IssueService) WillEnqueueRun(ctx context.Context, in IssueTriggerInput,if !canAccess(agent) {return IssueRunTrigger{}, false}+ if source == RunSourceAssign && !in.IsCreate && probe.SuppressActiveSelfAssignment != nil &&+ probe.SuppressActiveSelfAssignment(issue.AssigneeID) {+ return IssueRunTrigger{}, false+ }if source == RunSourceStatus && s.hasPendingRun(ctx, issue.ID, issue.AssigneeID) {return IssueRunTrigger{}, false}@@ -134,6 +145,12 @@ func (s *IssueService) WillEnqueueRun(ctx context.Context, in IssueTriggerInput,}, truecase "squad":+ // Pair-scoped self-assignment suppression intentionally applies only to+ // direct agent ownership. Assigning a squad changes execution context+ // (leader briefing, roles, and member routing), so even when the acting+ // agent is that squad's leader it is an intentional group handoff rather+ // than a redundant direct self-claim. The status path below still uses+ // the leader's pending-task guard.squad, err := s.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: issue.AssigneeID,WorkspaceID: issue.WorkspaceID,diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex dd1769d3e5..6da1b13af8 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -4171,6 +4171,84 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtimreturn items, nil}+const listActiveSiblingIssueTasks = `-- name: ListActiveSiblingIssueTasks :many+SELECT+ atq.id AS task_id,+ i.id AS issue_id,+ w.issue_prefix,+ i.number AS issue_number,+ i.title AS issue_title,+ atq.status,+ atq.created_at,+ atq.started_at+FROM agent_task_queue atq+JOIN issue i ON i.id = atq.issue_id+JOIN workspace w ON w.id = i.workspace_id+WHERE atq.agent_id = $1+ AND atq.id <> $2+ AND i.workspace_id = $3+ AND atq.status IN ('dispatched', 'running', 'waiting_local_directory')+ORDER BY+ CASE atq.status+ WHEN 'running' THEN 0+ WHEN 'waiting_local_directory' THEN 1+ ELSE 2+ END,+ atq.created_at DESC+LIMIT 5+`++type ListActiveSiblingIssueTasksParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++type ListActiveSiblingIssueTasksRow struct {+ TaskID pgtype.UUID `json:"task_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ IssuePrefix string `json:"issue_prefix"`+ IssueNumber int32 `json:"issue_number"`+ IssueTitle string `json:"issue_title"`+ Status string `json:"status"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ StartedAt pgtype.Timestamptz `json:"started_at"`+}++// Claim-time context for agents that can work concurrently. Only tasks already+// handed to a runtime can coordinate with the new claim; queued work is omitted+// so the warning stays high-signal. Bounded so one heavily-used agent cannot+// inflate every claim payload; issue-bound rows carry a concrete run-messages+// lookup target.+func (q *Queries) ListActiveSiblingIssueTasks(ctx context.Context, arg ListActiveSiblingIssueTasksParams) ([]ListActiveSiblingIssueTasksRow, error) {+ rows, err := q.db.Query(ctx, listActiveSiblingIssueTasks, arg.AgentID, arg.TaskID, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListActiveSiblingIssueTasksRow{}+ for rows.Next() {+ var i ListActiveSiblingIssueTasksRow+ if err := rows.Scan(+ &i.TaskID,+ &i.IssueID,+ &i.IssuePrefix,+ &i.IssueNumber,+ &i.IssueTitle,+ &i.Status,+ &i.CreatedAt,+ &i.StartedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :manySELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queueWHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 45bc0a480a..d519b875fa 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -277,6 +277,37 @@ SELECT * FROM agent_task_queueWHERE agent_id = $1ORDER BY created_at DESC;+-- name: ListActiveSiblingIssueTasks :many+-- Claim-time context for agents that can work concurrently. Only tasks already+-- handed to a runtime can coordinate with the new claim; queued work is omitted+-- so the warning stays high-signal. Bounded so one heavily-used agent cannot+-- inflate every claim payload; issue-bound rows carry a concrete run-messages+-- lookup target.+SELECT+ atq.id AS task_id,+ i.id AS issue_id,+ w.issue_prefix,+ i.number AS issue_number,+ i.title AS issue_title,+ atq.status,+ atq.created_at,+ atq.started_at+FROM agent_task_queue atq+JOIN issue i ON i.id = atq.issue_id+JOIN workspace w ON w.id = i.workspace_id+WHERE atq.agent_id = @agent_id+ AND atq.id <> @task_id+ AND i.workspace_id = @workspace_id+ AND atq.status IN ('dispatched', 'running', 'waiting_local_directory')+ORDER BY+ CASE atq.status+ WHEN 'running' THEN 0+ WHEN 'waiting_local_directory' THEN 1+ ELSE 2+ END,+ atq.created_at DESC+LIMIT 5;+-- name: CreateAgentTask :one-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)-- locks the owners' workspace rows in the writer's own transaction and returns