Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(issues): prevent duplicate active issue creation (MUL-2225) (#2602)
iYuand8635ad58009
diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.tsindex 9c1d6814e9..5c122439d1 100644--- a/packages/core/types/autopilot.ts+++ b/packages/core/types/autopilot.ts@@ -4,7 +4,7 @@ export type AutopilotExecutionMode = "create_issue" | "run_only";export type AutopilotTriggerKind = "schedule" | "webhook" | "api";-export type AutopilotRunStatus = "issue_created" | "running" | "completed" | "failed";+export type AutopilotRunStatus = "issue_created" | "running" | "skipped" | "completed" | "failed";export type AutopilotRunSource = "schedule" | "manual" | "webhook" | "api";diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsxindex cd75f41736..5127fec3e1 100644--- a/packages/views/autopilots/components/autopilot-detail-page.tsx+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx@@ -1,7 +1,7 @@"use client";import { useState } from "react";-import { Zap, Play, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil } from "lucide-react";+import { Zap, Play, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil, Ban, ChevronDown, ChevronRight } from "lucide-react";import { useQuery } from "@tanstack/react-query";import { autopilotDetailOptions, autopilotRunsOptions } from "@multica/core/autopilots/queries";import {@@ -59,11 +59,12 @@ function formatDate(date: string): string {});}-type RunStatus = "issue_created" | "running" | "completed" | "failed";+type RunStatus = "issue_created" | "running" | "skipped" | "completed" | "failed";const RUN_VISUAL: Record<RunStatus, { color: string; icon: typeof CheckCircle2; spin?: boolean }> = {issue_created: { color: "text-blue-500", icon: Clock },running: { color: "text-blue-500", icon: Loader2, spin: true },+ skipped: { color: "text-muted-foreground", icon: Ban },completed: { color: "text-emerald-500", icon: CheckCircle2 },failed: { color: "text-destructive", icon: XCircle },};@@ -139,6 +140,77 @@ function RunRow({ run, agentId, agentName }: { run: AutopilotRun; agentId: strinreturn <div className={rowClass}>{content}</div>;}+function RunHistoryList({+ runs,+ agentId,+ agentName,+}: {+ runs: AutopilotRun[];+ agentId: string;+ agentName: string;+}) {+ const visibleRuns = runs.filter((run) => run.status !== "skipped");+ const skippedRuns = runs.filter((run) => run.status === "skipped");++ return (+ <div className="rounded-md border overflow-hidden">+ {visibleRuns.map((run) => (+ <RunRow key={run.id} run={run} agentId={agentId} agentName={agentName} />+ ))}+ {skippedRuns.length > 0 && (+ <SkippedRunsGroup runs={skippedRuns} agentId={agentId} agentName={agentName} />+ )}+ </div>+ );+}++function SkippedRunsGroup({+ runs,+ agentId,+ agentName,+}: {+ runs: AutopilotRun[];+ agentId: string;+ agentName: string;+}) {+ const { t } = useT("autopilots");+ const [open, setOpen] = useState(false);+ const latestRun = runs[0];+ const ToggleIcon = open ? ChevronDown : ChevronRight;++ return (+ <div className="border-t bg-muted/20">+ <button+ type="button"+ className="flex w-full items-center gap-3 px-4 py-2.5 text-left text-sm hover:bg-accent/30 transition-colors"+ onClick={() => setOpen((value) => !value)}+ aria-expanded={open}+ >+ <ToggleIcon className="h-4 w-4 shrink-0 text-muted-foreground" />+ <Ban className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="w-24 shrink-0 text-xs font-medium text-muted-foreground">+ {t(($) => $.run.skipped_group.label)}+ </span>+ <span className="flex-1 min-w-0 text-xs text-muted-foreground truncate">+ {t(($) => $.run.skipped_group.summary, { count: runs.length })}+ </span>+ {latestRun && (+ <span className="w-32 shrink-0 text-right text-xs text-muted-foreground tabular-nums">+ {formatDate(latestRun.triggered_at || latestRun.created_at)}+ </span>+ )}+ </button>+ {open && (+ <div className="border-t bg-background">+ {runs.map((run) => (+ <RunRow key={run.id} run={run} agentId={agentId} agentName={agentName} />+ ))}+ </div>+ )}+ </div>+ );+}+function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autopilotId: string }) {const { t } = useT("autopilots");const deleteTrigger = useDeleteAutopilotTrigger();@@ -501,11 +573,11 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {{t(($) => $.detail.no_runs)}</div>) : (- <div className="rounded-md border overflow-hidden">- {runs.map((run) => (- <RunRow key={run.id} run={run} agentId={autopilot.assignee_id} agentName={getActorName("agent", autopilot.assignee_id)} />- ))}- </div>+ <RunHistoryList+ runs={runs}+ agentId={autopilot.assignee_id}+ agentName={getActorName("agent", autopilot.assignee_id)}+ />)}</section>diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex 53519d236d..de5150ce3e 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -90,12 +90,17 @@"run_status": {"issue_created": "Issue Created","running": "Running",+ "skipped": "Skipped","completed": "Completed","failed": "Failed"},"run": {"issue_linked": "Issue linked",- "view_log": "View execution log"+ "view_log": "View execution log",+ "skipped_group": {+ "label": "Skipped",+ "summary": "{{count}} skipped runs"+ }},"trigger_row": {"disabled_badge": "Disabled",diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex 2dafbfec91..43fcc29cc0 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -90,12 +90,17 @@"run_status": {"issue_created": "已创建 issue","running": "运行中",+ "skipped": "已跳过","completed": "已完成","failed": "失败"},"run": {"issue_linked": "已关联 issue",- "view_log": "查看执行日志"+ "view_log": "查看执行日志",+ "skipped_group": {+ "label": "已跳过",+ "summary": "{{count}} 条跳过的运行"+ }},"trigger_row": {"disabled_badge": "已禁用",diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 5ec6a15d24..e044336f16 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -2,8 +2,11 @@ package mainimport ("context"+ "encoding/json"+ "errors""fmt""io"+ "net/http""net/url""os""strings"@@ -274,6 +277,7 @@ func init() {issueCreateCmd.Flags().String("parent", "", "Parent issue ID")issueCreateCmd.Flags().String("project", "", "Project ID")issueCreateCmd.Flags().String("due-date", "", "Due date (RFC3339 format)")+ issueCreateCmd.Flags().Bool("allow-duplicate", false, "Allow creating an issue even when an active duplicate exists")issueCreateCmd.Flags().String("output", "json", "Output format: table or json")issueCreateCmd.Flags().StringSlice("attachment", nil, "File path(s) to attach (can be specified multiple times)")@@ -567,6 +571,9 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {if v, _ := cmd.Flags().GetString("due-date"); v != "" {body["due_date"] = v}+ if v, _ := cmd.Flags().GetBool("allow-duplicate"); v {+ body["allow_duplicate"] = true+ }aType, aID, hasAssignee, resolveErr := pickAssigneeFromFlags(ctx, client, cmd, "assignee", "assignee-id", issueAssigneeKinds)if resolveErr != nil {return fmt.Errorf("resolve assignee: %w", resolveErr)@@ -620,6 +627,9 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {var result map[string]anyif err := client.PostJSON(ctx, "/api/issues", body, &result); err != nil {+ if msg, ok := activeDuplicateIssueCreateMessage(err); ok {+ return errors.New(msg)+ }return fmt.Errorf("create issue: %w", err)}@@ -653,6 +663,24 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {return cli.PrintJSON(os.Stdout, result)}+func activeDuplicateIssueCreateMessage(err error) (string, bool) {+ var httpErr *cli.HTTPError+ if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusConflict {+ return "", false+ }+ var payload struct {+ Code string `json:"code"`+ Error string `json:"error"`+ }+ if json.Unmarshal([]byte(httpErr.Body), &payload) != nil {+ return "", false+ }+ if payload.Code != "active_duplicate_issue" || payload.Error == "" {+ return "", false+ }+ return payload.Error, true+}+func runIssueUpdate(cmd *cobra.Command, args []string) error {client, err := newAPIClient(cmd)if err != nil {diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 338b7ec77c..478d90014a 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -180,6 +180,98 @@ func TestResolveTextFlag(t *testing.T) {})}+func newIssueCreateTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "create"}+ cmd.Flags().String("title", "", "")+ cmd.Flags().String("description", "", "")+ cmd.Flags().Bool("description-stdin", false, "")+ cmd.Flags().String("description-file", "", "")+ cmd.Flags().String("status", "", "")+ cmd.Flags().String("priority", "", "")+ cmd.Flags().String("assignee", "", "")+ cmd.Flags().String("assignee-id", "", "")+ cmd.Flags().String("parent", "", "")+ cmd.Flags().String("project", "", "")+ cmd.Flags().String("due-date", "", "")+ cmd.Flags().Bool("allow-duplicate", false, "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().StringSlice("attachment", nil, "")+ return cmd+}++func TestRunIssueCreateSendsAllowDuplicate(t *testing.T) {+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/issues" {+ http.NotFound(w, r)+ return+ }+ if r.Method != http.MethodPost {+ t.Errorf("method = %s, want POST", r.Method)+ }+ 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",+ "title": "Duplicate allowed",+ "status": "todo",+ "priority": "none",+ })+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := newIssueCreateTestCmd()+ _ = cmd.Flags().Set("title", "Duplicate allowed")+ _ = cmd.Flags().Set("allow-duplicate", "true")+ if err := runIssueCreate(cmd, nil); err != nil {+ t.Fatalf("runIssueCreate: %v", err)+ }+ if got := body["allow_duplicate"]; got != true {+ t.Fatalf("allow_duplicate = %#v, want true in request body", got)+ }+}++func TestRunIssueCreateShowsDuplicateMessage(t *testing.T) {+ want := "Active duplicate issue exists: YUA-36 SH-PM-SYNTH-01 Synthesize recommendation-to-shortlist planning outputs (status: in_progress). Set allow_duplicate=true or use --allow-duplicate to create another."+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/issues" {+ http.NotFound(w, r)+ return+ }+ w.WriteHeader(http.StatusConflict)+ json.NewEncoder(w).Encode(map[string]any{+ "code": "active_duplicate_issue",+ "error": want,+ "issue": map[string]any{+ "id": "issue-id",+ "identifier": "YUA-36",+ "status": "in_progress",+ },+ })+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := newIssueCreateTestCmd()+ _ = cmd.Flags().Set("title", "SH-PM-SYNTH-01 Synthesize recommendation-to-shortlist planning outputs")+ err := runIssueCreate(cmd, nil)+ if err == nil {+ t.Fatal("runIssueCreate: expected duplicate error")+ }+ if got := err.Error(); got != want {+ t.Fatalf("error = %q, want %q", got, want)+ }+}+func TestTruncateID(t *testing.T) {tests := []struct {name stringdiff --git a/server/internal/cli/client.go b/server/internal/cli/client.goindex 81cb8a72fe..d4814eba82 100644--- a/server/internal/cli/client.go+++ b/server/internal/cli/client.go@@ -59,6 +59,17 @@ type APIClient struct {OS string}+type HTTPError struct {+ Method string+ Path string+ StatusCode int+ Body string+}++func (e *HTTPError) Error() string {+ return fmt.Sprintf("%s %s returned %d: %s", e.Method, e.Path, e.StatusCode, strings.TrimSpace(e.Body))+}+// NewAPIClient creates a new API client for ctrl commands.func NewAPIClient(baseURL, workspaceID, token string) *APIClient {return &APIClient{@@ -227,7 +238,12 @@ func (c *APIClient) PostJSON(ctx context.Context, path string, body any, out anyif resp.StatusCode >= 400 {respData, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("POST %s returned %d: %s", path, resp.StatusCode, strings.TrimSpace(string(respData)))+ return &HTTPError{+ Method: http.MethodPost,+ Path: path,+ StatusCode: resp.StatusCode,+ Body: strings.TrimSpace(string(respData)),+ }}if out == nil {return nildiff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 514c927443..94dafb8b35 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -2,6 +2,7 @@ package handlerimport ("encoding/json"+ "errors""io""net/http""strconv"@@ -9,6 +10,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -690,6 +692,20 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {run, err := h.AutopilotService.DispatchAutopilot(r.Context(), autopilot, pgtype.UUID{}, "manual", nil)if err != nil {+ var duplicate *issueguard.ActiveDuplicateError+ if errors.As(err, &duplicate) {+ writeJSON(w, http.StatusConflict, map[string]any{+ "code": "active_duplicate_issue",+ "error": duplicate.Error(),+ "issue": map[string]any{+ "id": duplicate.ID,+ "identifier": duplicate.Identifier,+ "title": duplicate.Title,+ "status": duplicate.Status,+ },+ })+ return+ }writeError(w, http.StatusInternalServerError, "failed to trigger autopilot: "+err.Error())return}diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex 2959b0b866..3498fb7ba1 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -13,6 +13,7 @@ import ("time""github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype""github.com/jackc/pgx/v5/pgxpool""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/events"@@ -639,6 +640,431 @@ func TestCreateSubIssueUsesExplicitProjectOverParentProject(t *testing.T) {}}+func TestCreateIssueRejectsActiveDuplicate(t *testing.T) {+ ctx := context.Background()+ suffix := fmt.Sprintf("%d", time.Now().UnixNano())+ var projectID, parentID, issueID, duplicateID string+ defer func() {+ for _, id := range []string{duplicateID, issueID, parentID} {+ if id != "" {+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, id)+ }+ }+ if projectID != "" {+ testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, projectID)+ }+ }()++ if err := testPool.QueryRow(ctx, `+ INSERT INTO project (workspace_id, title)+ VALUES ($1, $2)+ RETURNING id+ `, testWorkspaceID, "Duplicate guard project "+suffix).Scan(&projectID); err != nil {+ t.Fatalf("create project fixture: %v", err)+ }++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Duplicate guard parent " + suffix,+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue parent: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var parent IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&parent); err != nil {+ t.Fatalf("decode parent: %v", err)+ }+ parentID = parent.ID++ title := "SH-PM-SYNTH-01 Synthesize recommendation-to-shortlist planning outputs " + suffix+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "status": "in_progress",+ "parent_issue_id": parentID,+ "project_id": projectID,+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue original: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var original IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&original); err != nil {+ t.Fatalf("decode original: %v", err)+ }+ issueID = original.ID++ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": " sh-pm-synth-01 synthesize recommendation-to-shortlist planning outputs " + suffix + " ",+ "parent_issue_id": parentID,+ "project_id": projectID,+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusConflict {+ t.Fatalf("CreateIssue duplicate: expected 409, got %d: %s", w.Code, w.Body.String())+ }+ var conflict struct {+ Code string `json:"code"`+ Error string `json:"error"`+ Issue IssueResponse `json:"issue"`+ }+ if err := json.NewDecoder(w.Body).Decode(&conflict); err != nil {+ t.Fatalf("decode conflict: %v", err)+ }+ if conflict.Code != "active_duplicate_issue" {+ t.Fatalf("code = %q, want active_duplicate_issue", conflict.Code)+ }+ if conflict.Issue.ID != issueID || conflict.Issue.Status != "in_progress" {+ t.Fatalf("conflict issue = %#v, want original %s in_progress", conflict.Issue, issueID)+ }+ if !strings.Contains(conflict.Error, original.Identifier+" "+title) || !strings.Contains(conflict.Error, "allow_duplicate=true") || !strings.Contains(conflict.Error, "--allow-duplicate") {+ t.Fatalf("unexpected duplicate message: %q", conflict.Error)+ }++ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "parent_issue_id": parentID,+ "project_id": projectID,+ "allow_duplicate": true,+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue allow duplicate: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var duplicate IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&duplicate); err != nil {+ t.Fatalf("decode duplicate: %v", err)+ }+ duplicateID = duplicate.ID+ if duplicateID == issueID {+ t.Fatalf("allow duplicate returned original issue id %s", duplicateID)+ }++ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "parent_issue_id": parentID,+ "project_id": projectID,+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusConflict {+ t.Fatalf("CreateIssue duplicate after allow-duplicate: expected 409, got %d: %s", w.Code, w.Body.String())+ }+ if err := json.NewDecoder(w.Body).Decode(&conflict); err != nil {+ t.Fatalf("decode second conflict: %v", err)+ }+ if conflict.Issue.ID != issueID {+ t.Fatalf("conflict issue = %s, want oldest active issue %s", conflict.Issue.ID, issueID)+ }+}++func TestCreateIssueAllowsDuplicateAfterCancelled(t *testing.T) {+ ctx := context.Background()+ title := fmt.Sprintf("Cancelled duplicate guard %d", time.Now().UnixNano())+ var firstID, secondID string+ defer func() {+ for _, id := range []string{secondID, firstID} {+ if id != "" {+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, id)+ }+ }+ }()++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "status": "cancelled",+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue cancelled: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var first IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&first); err != nil {+ t.Fatalf("decode cancelled: %v", err)+ }+ firstID = first.ID++ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue after cancelled: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var second IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&second); err != nil {+ t.Fatalf("decode second: %v", err)+ }+ secondID = second.ID+ if secondID == firstID {+ t.Fatalf("new issue reused cancelled issue id %s", secondID)+ }+}++func TestCreateIssueAllowsDuplicateAfterDone(t *testing.T) {+ ctx := context.Background()+ title := fmt.Sprintf("Done duplicate guard %d", time.Now().UnixNano())+ var firstID, secondID string+ defer func() {+ for _, id := range []string{secondID, firstID} {+ if id != "" {+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, id)+ }+ }+ }()++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "status": "done",+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue done: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var first IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&first); err != nil {+ t.Fatalf("decode done: %v", err)+ }+ firstID = first.ID++ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue after done: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var second IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&second); err != nil {+ t.Fatalf("decode second: %v", err)+ }+ secondID = second.ID+ if secondID == firstID {+ t.Fatalf("new issue reused done issue id %s", secondID)+ }+}++func TestTriggerAutopilotRejectsActiveDuplicateIssue(t *testing.T) {+ ctx := context.Background()+ title := fmt.Sprintf("Autopilot duplicate guard %d", time.Now().UnixNano())+ var issueID, autopilotID string+ defer func() {+ if autopilotID != "" {+ testPool.Exec(ctx, `DELETE FROM autopilot WHERE id = $1`, autopilotID)+ }+ if issueID != "" {+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)+ }+ }()++ var agentID string+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("load test agent: %v", err)+ }++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "status": "todo",+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue existing: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var existing IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&existing); err != nil {+ t.Fatalf("decode existing issue: %v", err)+ }+ issueID = existing.ID++ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Duplicate guard autopilot",+ "assignee_id": agentID,+ "execution_mode": "create_issue",+ "issue_title_template": title,+ })+ testHandler.CreateAutopilot(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var autopilot AutopilotResponse+ if err := json.NewDecoder(w.Body).Decode(&autopilot); err != nil {+ t.Fatalf("decode autopilot: %v", err)+ }+ autopilotID = autopilot.ID++ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/autopilots/"+autopilotID+"/trigger?workspace_id="+testWorkspaceID, nil)+ req = withURLParam(req, "id", autopilotID)+ testHandler.TriggerAutopilot(w, req)+ if w.Code != http.StatusConflict {+ t.Fatalf("TriggerAutopilot duplicate: expected 409, got %d: %s", w.Code, w.Body.String())+ }+ var conflict struct {+ Code string `json:"code"`+ Error string `json:"error"`+ Issue struct {+ ID string `json:"id"`+ Identifier string `json:"identifier"`+ Title string `json:"title"`+ Status string `json:"status"`+ } `json:"issue"`+ }+ if err := json.NewDecoder(w.Body).Decode(&conflict); err != nil {+ t.Fatalf("decode duplicate conflict: %v", err)+ }+ if conflict.Code != "active_duplicate_issue" {+ t.Fatalf("code = %q, want active_duplicate_issue", conflict.Code)+ }+ if conflict.Issue.ID != issueID || conflict.Issue.Identifier != existing.Identifier || conflict.Issue.Status != "todo" {+ t.Fatalf("conflict issue = %#v, want existing %s %s todo", conflict.Issue, issueID, existing.Identifier)+ }+ if !strings.Contains(conflict.Error, "Active duplicate issue exists: "+existing.Identifier+" "+title) {+ t.Fatalf("duplicate error did not mention existing issue: %s", conflict.Error)+ }++ assertAutopilotDuplicateRunSkipped(t, ctx, autopilotID, issueID, existing.Identifier, title)+ assertAutopilotNotFailureMonitorCandidate(t, ctx, autopilotID)++ var count int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title).Scan(&count); err != nil {+ t.Fatalf("count issues: %v", err)+ }+ if count != 1 {+ t.Fatalf("autopilot duplicate guard should leave one matching issue, got %d", count)+ }+}++func TestScheduledAutopilotDuplicateIssueSkipsRun(t *testing.T) {+ ctx := context.Background()+ title := fmt.Sprintf("Scheduled autopilot duplicate guard %d", time.Now().UnixNano())+ var issueID, autopilotID string+ defer func() {+ if autopilotID != "" {+ testPool.Exec(ctx, `DELETE FROM autopilot WHERE id = $1`, autopilotID)+ }+ if issueID != "" {+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)+ }+ }()++ var agentID string+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("load test agent: %v", err)+ }++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "status": "todo",+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue existing: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var existing IssueResponse+ if err := json.NewDecoder(w.Body).Decode(&existing); err != nil {+ t.Fatalf("decode existing issue: %v", err)+ }+ issueID = existing.ID++ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Scheduled duplicate guard autopilot",+ "assignee_id": agentID,+ "execution_mode": "create_issue",+ "issue_title_template": title,+ })+ testHandler.CreateAutopilot(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var autopilot AutopilotResponse+ if err := json.NewDecoder(w.Body).Decode(&autopilot); err != nil {+ t.Fatalf("decode autopilot: %v", err)+ }+ autopilotID = autopilot.ID++ queries := db.New(testPool)+ ap, err := queries.GetAutopilot(ctx, parseUUID(autopilotID))+ if err != nil {+ t.Fatalf("GetAutopilot: %v", err)+ }+ run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "schedule", nil)+ if err != nil {+ t.Fatalf("DispatchAutopilot schedule duplicate: %v", err)+ }+ if run == nil {+ t.Fatal("expected skipped run, got nil")+ }+ if run.Status != "skipped" {+ t.Fatalf("run status = %q, want skipped", run.Status)+ }+ assertAutopilotDuplicateRunSkipped(t, ctx, autopilotID, issueID, existing.Identifier, title)+ assertAutopilotNotFailureMonitorCandidate(t, ctx, autopilotID)+}++func assertAutopilotDuplicateRunSkipped(t *testing.T, ctx context.Context, autopilotID, issueID, identifier, title string) {+ t.Helper()+ var status, failureReason string+ var result []byte+ if err := testPool.QueryRow(ctx, `+ SELECT status, failure_reason, result+ FROM autopilot_run+ WHERE autopilot_id = $1+ ORDER BY created_at DESC+ LIMIT 1+ `, autopilotID).Scan(&status, &failureReason, &result); err != nil {+ t.Fatalf("load autopilot run: %v", err)+ }+ if status != "skipped" {+ t.Fatalf("autopilot duplicate run status = %q, want skipped", status)+ }+ if !strings.Contains(failureReason, identifier+" "+title) {+ t.Fatalf("duplicate run failure_reason = %q, want existing issue details", failureReason)+ }+ var payload struct {+ Code string `json:"code"`+ Issue struct {+ ID string `json:"id"`+ Identifier string `json:"identifier"`+ Title string `json:"title"`+ Status string `json:"status"`+ } `json:"issue"`+ }+ if err := json.Unmarshal(result, &payload); err != nil {+ t.Fatalf("decode duplicate run result: %v", err)+ }+ if payload.Code != "active_duplicate_issue" || payload.Issue.ID != issueID || payload.Issue.Identifier != identifier || payload.Issue.Title != title {+ t.Fatalf("duplicate run result = %#v, want issue %s %s %q", payload, issueID, identifier, title)+ }+}++func assertAutopilotNotFailureMonitorCandidate(t *testing.T, ctx context.Context, autopilotID string) {+ t.Helper()+ candidates, err := db.New(testPool).SelectAutopilotsExceedingFailureThreshold(ctx, db.SelectAutopilotsExceedingFailureThresholdParams{+ MinRuns: 1,+ FailRatioThreshold: 1,+ Since: pgtype.Timestamptz{Time: time.Now().Add(-time.Hour), Valid: true},+ })+ if err != nil {+ t.Fatalf("SelectAutopilotsExceedingFailureThreshold: %v", err)+ }+ for _, candidate := range candidates {+ if uuidToString(candidate.ID) == autopilotID {+ t.Fatalf("duplicate skipped run should not be a failure monitor candidate: %+v", candidate)+ }+ }+}+// TestCreateIssueRejectsNonexistentMemberAssignee covers the bug where any// well-formed UUID was accepted as assignee_id without checking workspace// membership.diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 95cc6d5d50..80131f8759 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -17,6 +17,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/pkg/agent"@@ -26,33 +27,33 @@ import (// IssueResponse is the JSON response for an issue.type IssueResponse struct {- ID string `json:"id"`- WorkspaceID string `json:"workspace_id"`- Number int32 `json:"number"`- Identifier string `json:"identifier"`- Title string `json:"title"`- Description *string `json:"description"`- Status string `json:"status"`- Priority string `json:"priority"`- AssigneeType *string `json:"assignee_type"`- AssigneeID *string `json:"assignee_id"`- CreatorType string `json:"creator_type"`- CreatorID string `json:"creator_id"`- ParentIssueID *string `json:"parent_issue_id"`- ProjectID *string `json:"project_id"`- Position float64 `json:"position"`- DueDate *string `json:"due_date"`- CreatedAt string `json:"created_at"`- UpdatedAt string `json:"updated_at"`- Reactions []IssueReactionResponse `json:"reactions,omitempty"`- Attachments []AttachmentResponse `json:"attachments,omitempty"`+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ Number int32 `json:"number"`+ Identifier string `json:"identifier"`+ Title string `json:"title"`+ Description *string `json:"description"`+ Status string `json:"status"`+ Priority string `json:"priority"`+ AssigneeType *string `json:"assignee_type"`+ AssigneeID *string `json:"assignee_id"`+ CreatorType string `json:"creator_type"`+ CreatorID string `json:"creator_id"`+ ParentIssueID *string `json:"parent_issue_id"`+ ProjectID *string `json:"project_id"`+ Position float64 `json:"position"`+ DueDate *string `json:"due_date"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+ Reactions []IssueReactionResponse `json:"reactions,omitempty"`+ Attachments []AttachmentResponse `json:"attachments,omitempty"`// Labels are bulk-attached by list/detail endpoints so the client can render// chips without an N+1 round-trip per row. Pointer + omitempty so paths that// don't load labels (e.g. UpdateIssue, batch UpdateIssues, the issue:updated// WS broadcast) emit no `labels` field at all — the client merge then// preserves whatever labels are already in cache. nil pointer = "field// absent, do not touch"; non-nil (incl. empty slice) = authoritative list.- Labels *[]LabelResponse `json:"labels,omitempty"`+ Labels *[]LabelResponse `json:"labels,omitempty"`}func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {@@ -286,7 +287,7 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,}escapedPhrase := escapeLike(phrase)- phraseParam := nextArg(escapedPhrase) // $1+ phraseParam := nextArg(escapedPhrase) // $1phraseContains := "'%' || " + phraseParam + " || '%'"phraseStartsWith := phraseParam + " || '%'"@@ -1118,16 +1119,16 @@ func readRuntimeCLIVersion(metadata []byte) string {}type CreateIssueRequest struct {- Title string `json:"title"`- Description *string `json:"description"`- Status string `json:"status"`- Priority string `json:"priority"`- AssigneeType *string `json:"assignee_type"`- AssigneeID *string `json:"assignee_id"`- ParentIssueID *string `json:"parent_issue_id"`- ProjectID *string `json:"project_id"`- DueDate *string `json:"due_date"`- AttachmentIDs []string `json:"attachment_ids,omitempty"`+ Title string `json:"title"`+ Description *string `json:"description"`+ Status string `json:"status"`+ Priority string `json:"priority"`+ AssigneeType *string `json:"assignee_type"`+ AssigneeID *string `json:"assignee_id"`+ ParentIssueID *string `json:"parent_issue_id"`+ ProjectID *string `json:"project_id"`+ DueDate *string `json:"due_date"`+ AttachmentIDs []string `json:"attachment_ids,omitempty"`// OriginType / OriginID stamp the new issue with its provenance so// platform-internal flows can deterministically locate it later. Only// trusted callers should set these — currently the daemon CLI passes@@ -1135,6 +1136,12 @@ type CreateIssueRequest struct {// origin_id=agent_task_queue.id).OriginType *string `json:"origin_type,omitempty"`OriginID *string `json:"origin_id,omitempty"`++ AllowDuplicate bool `json:"allow_duplicate,omitempty"`+}++func duplicateIssueMessage(issue IssueResponse) string {+ return issueguard.DuplicateMessage(issue.Identifier, issue.Title, issue.Status)}func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {@@ -1232,8 +1239,8 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {dueDate = pgtype.Timestamptz{Time: t, Valid: true}}- // Use a transaction to atomically increment the workspace issue counter- // and create the issue with the assigned number.+ // Use a transaction to atomically guard against active duplicates,+ // increment the workspace issue counter, and create the issue.tx, err := h.TxStarter.Begin(r.Context())if err != nil {writeError(w, http.StatusInternalServerError, "failed to create issue")@@ -1242,6 +1249,23 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)+ duplicate, foundDuplicate, err := issueguard.LockAndFindActiveDuplicate(r.Context(), qtx, wsUUID, projectID, parentIssueID, req.Title, req.AllowDuplicate)+ if err != nil {+ slog.Warn("duplicate issue guard failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to create issue")+ return+ }+ if foundDuplicate {+ prefix := h.getIssuePrefix(r.Context(), duplicate.WorkspaceID)+ existing := issueToResponse(duplicate, prefix)+ writeJSON(w, http.StatusConflict, map[string]any{+ "code": "active_duplicate_issue",+ "error": duplicateIssueMessage(existing),+ "issue": existing,+ })+ return+ }+issueNumber, err := qtx.IncrementIssueCounter(r.Context(), wsUUID)if err != nil {slog.Warn("increment issue counter failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)diff --git a/server/internal/issueguard/duplicate.go b/server/internal/issueguard/duplicate.gonew file mode 100644index 0000000000..5a7bc315af--- /dev/null+++ b/server/internal/issueguard/duplicate.go@@ -0,0 +1,86 @@+package issueguard++import (+ "context"+ "errors"+ "fmt"+ "strings"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func NormalizeTitle(title string) string {+ return strings.ToLower(strings.Join(strings.Fields(title), " "))+}++func DuplicateMessage(identifier, title, status string) string {+ return "Active duplicate issue exists: " + identifier + " " + title + " (status: " + status + "). Set allow_duplicate=true or use --allow-duplicate to create another."+}++type ActiveDuplicateError struct {+ ID string+ Identifier string+ Title string+ Status string+}++func (e *ActiveDuplicateError) Error() string {+ return DuplicateMessage(e.Identifier, e.Title, e.Status)+}++func NewActiveDuplicateError(issue db.Issue, issuePrefix string) *ActiveDuplicateError {+ return &ActiveDuplicateError{+ ID: util.UUIDToString(issue.ID),+ Identifier: fmt.Sprintf("%s-%d", issuePrefix, issue.Number),+ Title: issue.Title,+ Status: issue.Status,+ }+}++func LockAndFindActiveDuplicate(+ ctx context.Context,+ q *db.Queries,+ workspaceID pgtype.UUID,+ projectID pgtype.UUID,+ parentIssueID pgtype.UUID,+ title string,+ allowDuplicate bool,+) (db.Issue, bool, error) {+ normalizedTitle := NormalizeTitle(title)+ if normalizedTitle == "" {+ return db.Issue{}, false, nil+ }+ if err := q.LockIssueDuplicateKey(ctx, lockKey(workspaceID, projectID, parentIssueID, normalizedTitle)); err != nil {+ return db.Issue{}, false, err+ }+ if allowDuplicate {+ return db.Issue{}, false, nil+ }++ duplicate, err := q.FindActiveDuplicateIssue(ctx, db.FindActiveDuplicateIssueParams{+ WorkspaceID: workspaceID,+ ProjectID: projectID,+ ParentIssueID: parentIssueID,+ NormalizedTitle: normalizedTitle,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return db.Issue{}, false, nil+ }+ return db.Issue{}, false, err+ }+ return duplicate, true, nil+}++func lockKey(workspaceID, projectID, parentIssueID pgtype.UUID, normalizedTitle string) string {+ return strings.Join([]string{+ "issue-active-duplicate",+ util.UUIDToString(workspaceID),+ util.UUIDToString(projectID),+ util.UUIDToString(parentIssueID),+ normalizedTitle,+ }, "|")+}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex e5f058fccf..15a368d648 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -2,6 +2,8 @@ package serviceimport ("context"+ "encoding/json"+ "errors""fmt""log/slog""strings"@@ -11,6 +13,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -73,6 +76,14 @@ func (s *AutopilotService) DispatchAutopilot(switch autopilot.ExecutionMode {case "create_issue":if err := s.dispatchCreateIssue(ctx, autopilot, &run); err != nil {+ var duplicate *issueguard.ActiveDuplicateError+ if errors.As(err, &duplicate) {+ updatedRun := s.skipDuplicateRun(ctx, autopilot, run, source, duplicate)+ if source == "manual" {+ return &updatedRun, fmt.Errorf("dispatch create_issue: %w", err)+ }+ return &updatedRun, nil+ }s.failRun(ctx, run.ID, err.Error())s.captureAutopilotRunFailed(autopilot, run, source, err.Error())return &run, fmt.Errorf("dispatch create_issue: %w", err)@@ -118,15 +129,22 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopiqtx := s.Queries.WithTx(tx)- // Get next issue number.+ title := s.interpolateTemplate(ap)+ description := s.buildIssueDescription(ap)++ duplicate, foundDuplicate, err := issueguard.LockAndFindActiveDuplicate(ctx, qtx, ap.WorkspaceID, pgtype.UUID{}, pgtype.UUID{}, title, false)+ if err != nil {+ return fmt.Errorf("check duplicate issue: %w", err)+ }+ if foundDuplicate {+ return issueguard.NewActiveDuplicateError(duplicate, s.getIssuePrefix(ap.WorkspaceID))+ }+issueNumber, err := qtx.IncrementIssueCounter(ctx, ap.WorkspaceID)if err != nil {return fmt.Errorf("increment issue counter: %w", err)}- title := s.interpolateTemplate(ap)- description := s.buildIssueDescription(ap)-issue, err := qtx.CreateIssueWithOrigin(ctx, db.CreateIssueWithOriginParams{WorkspaceID: ap.WorkspaceID,Title: title,@@ -345,6 +363,55 @@ func (s *AutopilotService) failRun(ctx context.Context, runID pgtype.UUID, reaso}}+func (s *AutopilotService) skipDuplicateRun(+ ctx context.Context,+ autopilot db.Autopilot,+ run db.AutopilotRun,+ source string,+ duplicate *issueguard.ActiveDuplicateError,+) db.AutopilotRun {+ reason := duplicate.Error()+ result, err := json.Marshal(map[string]any{+ "code": "active_duplicate_issue",+ "issue": map[string]any{+ "id": duplicate.ID,+ "identifier": duplicate.Identifier,+ "title": duplicate.Title,+ "status": duplicate.Status,+ },+ })+ if err != nil {+ slog.Warn("failed to marshal duplicate autopilot result",+ "run_id", util.UUIDToString(run.ID),+ "error", err,+ )+ }++ updatedRun, err := s.Queries.UpdateAutopilotRunSkippedWithResult(ctx, db.UpdateAutopilotRunSkippedWithResultParams{+ ID: run.ID,+ FailureReason: pgtype.Text{String: reason, Valid: true},+ Result: result,+ })+ if err != nil {+ slog.Warn("failed to mark duplicate autopilot run as skipped",+ "run_id", util.UUIDToString(run.ID),+ "error", err,+ )+ return run+ }++ slog.Info("autopilot duplicate issue skipped",+ "autopilot_id", util.UUIDToString(autopilot.ID),+ "run_id", util.UUIDToString(run.ID),+ "source", source,+ "existing_issue_id", duplicate.ID,+ )++ s.Queries.UpdateAutopilotLastRunAt(ctx, autopilot.ID)+ s.publishRunDone(util.UUIDToString(autopilot.WorkspaceID), updatedRun, "skipped")+ return updatedRun+}+// shouldSkipDispatch is the pre-flight admission check from MUL-1899.// Returns (reason, true) when dispatching now would only enqueue a doomed// task — i.e. the assignee agent is gone, archived, has no runtime bound, ordiff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 01e4ff491c..0277ff151b 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -1033,6 +1033,43 @@ func (q *Queries) UpdateAutopilotRunSkipped(ctx context.Context, arg UpdateAutopreturn i, err}+const updateAutopilotRunSkippedWithResult = `-- name: UpdateAutopilotRunSkippedWithResult :one+UPDATE autopilot_run+SET status = 'skipped',+ completed_at = now(),+ failure_reason = $2,+ result = $3+WHERE id = $1+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at+`++type UpdateAutopilotRunSkippedWithResultParams struct {+ ID pgtype.UUID `json:"id"`+ FailureReason pgtype.Text `json:"failure_reason"`+ Result []byte `json:"result"`+}++func (q *Queries) UpdateAutopilotRunSkippedWithResult(ctx context.Context, arg UpdateAutopilotRunSkippedWithResultParams) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, updateAutopilotRunSkippedWithResult, arg.ID, arg.FailureReason, arg.Result)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ )+ return i, err+}+const updateAutopilotTrigger = `-- name: UpdateAutopilotTrigger :oneUPDATE autopilot_trigger SETenabled = COALESCE($2::boolean, enabled),diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 9e77f218be..b0bedc3e74 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -288,6 +288,59 @@ func (q *Queries) DeleteIssue(ctx context.Context, id pgtype.UUID) error {return err}+const findActiveDuplicateIssue = `-- name: FindActiveDuplicateIssue :one+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at FROM issue+WHERE workspace_id = $1+ AND status NOT IN ('done', 'cancelled')+ AND project_id IS NOT DISTINCT FROM $2::uuid+ AND parent_issue_id IS NOT DISTINCT FROM $3::uuid+ AND lower(btrim(regexp_replace(title, '[[:space:]]+', ' ', 'g'))) = $4+ORDER BY created_at ASC+LIMIT 1+`++type FindActiveDuplicateIssueParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`+ NormalizedTitle string `json:"normalized_title"`+}++func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDuplicateIssueParams) (Issue, error) {+ row := q.db.QueryRow(ctx, findActiveDuplicateIssue,+ arg.WorkspaceID,+ arg.ProjectID,+ arg.ParentIssueID,+ arg.NormalizedTitle,+ )+ var i Issue+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Title,+ &i.Description,+ &i.Status,+ &i.Priority,+ &i.AssigneeType,+ &i.AssigneeID,+ &i.CreatorType,+ &i.CreatorID,+ &i.ParentIssueID,+ &i.AcceptanceCriteria,+ &i.ContextRefs,+ &i.Position,+ &i.DueDate,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Number,+ &i.ProjectID,+ &i.OriginType,+ &i.OriginID,+ &i.FirstExecutedAt,+ )+ return i, err+}+const getIssue = `-- name: GetIssue :oneSELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at FROM issueWHERE id = $1@@ -686,6 +739,15 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)return items, nil}+const lockIssueDuplicateKey = `-- name: LockIssueDuplicateKey :exec+SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))+`++func (q *Queries) LockIssueDuplicateKey(ctx context.Context, key string) error {+ _, err := q.db.Exec(ctx, lockIssueDuplicateKey, key)+ return err+}+const markIssueFirstExecuted = `-- name: MarkIssueFirstExecuted :oneUPDATE issuediff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex 4685d98edc..f46962378c 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -146,6 +146,15 @@ SET status = 'skipped', completed_at = now(), failure_reason = $2WHERE id = $1RETURNING *;+-- name: UpdateAutopilotRunSkippedWithResult :one+UPDATE autopilot_run+SET status = 'skipped',+ completed_at = now(),+ failure_reason = $2,+ result = sqlc.narg('result')+WHERE id = $1+RETURNING *;+-- =====================-- Scheduler Queries-- =====================diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 86b02b1712..8ca69dc9e3 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -68,6 +68,19 @@ INSERT INTO issue (sqlc.narg('origin_type'), sqlc.narg('origin_id')) RETURNING *;+-- name: LockIssueDuplicateKey :exec+SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0));++-- name: FindActiveDuplicateIssue :one+SELECT * FROM issue+WHERE workspace_id = $1+ AND status NOT IN ('done', 'cancelled')+ AND project_id IS NOT DISTINCT FROM $2::uuid+ AND parent_issue_id IS NOT DISTINCT FROM $3::uuid+ AND lower(btrim(regexp_replace(title, '[[:space:]]+', ' ', 'g'))) = $4+ORDER BY created_at ASC+LIMIT 1;+-- name: DeleteIssue :execDELETE FROM issue WHERE id = $1;