Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(task): preserve autopilot attribution after run completion (#9158)
xjha820c9a0efe6
diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 1d4e5c6bc2..31095f83d3 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -550,12 +550,16 @@ func (s *TaskService) attributionForIssueTask(ctx context.Context, issue db.Issu// it. Resolved the same way// run_only dispatch resolves it, so both autopilot execution modes attribute// identically. (A manual trigger carries an actor and is already handled above.)- // The issue only stores the autopilot id, so bridge issue → active run →- // trigger_id to find the trigger.+ // The issue only stores the autopilot id, so bridge issue → latest run →+ // trigger_id, including terminal runs so later handoffs retain the principal.if s != nil && s.Queries != nil && issue.OriginType.Valid &&issue.OriginType.String == "autopilot" && issue.OriginID.Valid {var triggerID pgtype.UUID- if run, err := s.Queries.GetAutopilotRunByIssue(ctx, issue.ID); err == nil {+ if run, err := s.Queries.GetLatestAutopilotRunForIssueAttribution(ctx, db.GetLatestAutopilotRunForIssueAttributionParams{+ IssueID: issue.ID,+ AutopilotID: issue.OriginID,+ WorkspaceID: issue.WorkspaceID,+ }); err == nil {triggerID = run.TriggerID}return triggerOwnerAttribution(ctx, s.Queries, triggerID, issue.WorkspaceID, issue.OriginID, attribution.EvidenceIssueAssignment, issue.ID)diff --git a/server/internal/service/task_autopilot_attribution_test.go b/server/internal/service/task_autopilot_attribution_test.gonew file mode 100644index 0000000000..a45f905798--- /dev/null+++ b/server/internal/service/task_autopilot_attribution_test.go@@ -0,0 +1,120 @@+package service++import (+ "context"+ "errors"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/attribution"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestEnqueueTaskForIssueAutopilotPreservesTriggerOwnerAfterRunCloses(t *testing.T) {+ for _, status := range []string{"issue_created", "running", "completed", "failed", "skipped"} {+ t.Run(status, func(t *testing.T) {+ fx, autopilotOwner := newPrincipalFixture(t)+ triggerOwner := fx.member(t, "handoff-trigger-owner")+ agentID := fx.privateAgentOwnedBy(t, triggerOwner, "handoff")+ autopilotID, triggerID := fx.autopilotWithTrigger(t, agentID, autopilotOwner, triggerOwner)+ fx.Insert(t, "autopilot_rule_version", testutil.Cols{+ "autopilot_id": autopilotID, "workspace_id": fx.WorkspaceID,+ "published_by_type": "member", "published_by_id": autopilotOwner,+ })+ issueID := fx.Issue(t, "autopilot handoff", testutil.Cols{+ "assignee_type": "agent", "assignee_id": agentID,+ "origin_type": "autopilot", "origin_id": autopilotID,+ "status": "in_review",+ })+ fx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID, "trigger_id": triggerID,+ "issue_id": issueID, "source": "schedule", "status": status,+ })+ ctx := context.Background()+ issue, err := fx.q.GetIssue(ctx, util.MustParseUUID(issueID))+ if err != nil {+ t.Fatal(err)+ }+ task, err := fx.svc.TaskSvc.EnqueueTaskForIssue(ctx, issue)+ if err != nil {+ t.Fatalf("enqueue handoff: %v", err)+ }+ fx.Cleanup(t, `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)+ stored, err := fx.q.GetAgentTask(ctx, task.ID)+ if err != nil {+ t.Fatal(err)+ }+ if stored.OriginatorSource.String != string(attribution.SourceTriggerOwner) {+ t.Errorf("source = %q, want trigger_owner", stored.OriginatorSource.String)+ }+ if got := util.UUIDToString(stored.OriginatorUserID); got != triggerOwner {+ t.Errorf("originator = %q, want trigger creator %q", got, triggerOwner)+ }+ if got := util.UUIDToString(stored.AccountableUserID); got != triggerOwner {+ t.Errorf("accountable = %q, want trigger creator %q", got, triggerOwner)+ }+ if status == "completed" || status == "failed" || status == "skipped" {+ if _, err := fx.q.GetAutopilotRunByIssue(ctx, issue.ID); !errors.Is(err, pgx.ErrNoRows) {+ t.Errorf("active-run lookup must exclude %s runs, got %v", status, err)+ }+ }+ })+ }+}++func TestAutopilotIssueAttributionUsesLatestMatchingRun(t *testing.T) {+ fx, owner := newPrincipalFixture(t)+ triggerOwner := fx.member(t, "latest-trigger-owner")+ agentID := fx.privateAgentOwnedBy(t, owner, "latest")+ autopilotID, oldTriggerID := fx.autopilotWithTrigger(t, agentID, owner, owner)+ triggerID := fx.trigger(t, autopilotID, "member", triggerOwner)+ issueID := fx.Issue(t, "latest autopilot run", testutil.Cols{+ "origin_type": "autopilot", "origin_id": autopilotID,+ })+ createdAt := time.Now().Add(-time.Hour)+ for i, id := range []string{oldTriggerID, triggerID} {+ fx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID, "trigger_id": id, "issue_id": issueID,+ "source": "schedule", "status": "completed",+ "created_at": createdAt.Add(time.Duration(i) * time.Minute),+ })+ }+ // A newer run from another autopilot must not supply this issue's principal.+ otherAutopilotID, otherTriggerID := fx.autopilotWithTrigger(t, agentID, owner, owner)+ fx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": otherAutopilotID, "trigger_id": otherTriggerID, "issue_id": issueID,+ "source": "schedule", "status": "completed", "created_at": createdAt.Add(2 * time.Minute),+ })+ ctx := context.Background()+ issue, err := fx.q.GetIssue(ctx, util.MustParseUUID(issueID))+ if err != nil {+ t.Fatal(err)+ }+ got := fx.svc.TaskSvc.attributionForIssueTask(ctx, issue, pgtype.UUID{}, attribution.SourceCommentSource, pgtype.UUID{})+ if got.Source != attribution.SourceTriggerOwner || util.UUIDToString(got.UserID) != triggerOwner {+ t.Fatalf("attribution = %+v, want latest matching trigger owner %s", got, triggerOwner)+ }+ otherWorkspaceID := fx.Workspace(t, "foreign attribution workspace", "foreign-attribution-workspace")+ _, err = fx.q.GetLatestAutopilotRunForIssueAttribution(ctx, db.GetLatestAutopilotRunForIssueAttributionParams{+ IssueID: issue.ID, AutopilotID: issue.OriginID, WorkspaceID: util.MustParseUUID(otherWorkspaceID),+ })+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("foreign workspace lookup = %v, want no rows", err)+ }+ fx.Exec(t, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, fx.WorkspaceID, triggerOwner)+ got = fx.svc.TaskSvc.attributionForIssueTask(ctx, issue, pgtype.UUID{}, attribution.SourceCommentSource, pgtype.UUID{})+ if got.UserID.Valid {+ t.Fatalf("removed trigger creator still authorizes handoff: %+v", got)+ }+ _, err = fx.q.GetLatestAutopilotRunForIssueAttribution(ctx, db.GetLatestAutopilotRunForIssueAttributionParams{+ IssueID: util.MustParseUUID(fx.Issue(t, "unlinked issue")), AutopilotID: issue.OriginID,+ WorkspaceID: issue.WorkspaceID,+ })+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("unlinked issue lookup = %v, want no rows", err)+ }+}diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 72ee5d362f..20ff04b4a8 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -1092,6 +1092,48 @@ func (q *Queries) GetAutopilotTriggerForAutopilot(ctx context.Context, arg GetAureturn i, err}+const getLatestAutopilotRunForIssueAttribution = `-- name: GetLatestAutopilotRunForIssueAttribution :one+SELECT r.id, r.autopilot_id, r.trigger_id, r.source, r.status, r.issue_id, r.task_id, r.triggered_at, r.completed_at, r.failure_reason, r.trigger_payload, r.result, r.created_at, r.squad_id, r.planned_at, r.webhook_delivery_id, r.quota_reservation_id, r.reason_code FROM autopilot_run r+JOIN autopilot a ON a.id = r.autopilot_id+WHERE r.issue_id = $1 AND r.autopilot_id = $2+ AND a.workspace_id = $3+ORDER BY r.created_at DESC, r.id DESC+LIMIT 1+`++type GetLatestAutopilotRunForIssueAttributionParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Attribution survives run completion; lifecycle callers still use the active-run lookup.+func (q *Queries) GetLatestAutopilotRunForIssueAttribution(ctx context.Context, arg GetLatestAutopilotRunForIssueAttributionParams) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, getLatestAutopilotRunForIssueAttribution, arg.IssueID, arg.AutopilotID, arg.WorkspaceID)+ 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,+ &i.SquadID,+ &i.PlannedAt,+ &i.WebhookDeliveryID,+ &i.QuotaReservationID,+ &i.ReasonCode,+ )+ return i, err+}+const getWebhookTriggerByToken = `-- name: GetWebhookTriggerByToken :oneSELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, t.event_filters, t.published_by_type, t.published_by_id, t.created_by_type, t.created_by_id, a.workspace_id AS autopilot_workspace_idFROM autopilot_trigger tdiff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex fdb71b103d..4a50ddd513 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -624,6 +624,15 @@ SELECT * FROM autopilot_runWHERE issue_id = $1 AND status IN ('issue_created', 'running')LIMIT 1;+-- name: GetLatestAutopilotRunForIssueAttribution :one+-- Attribution survives run completion; lifecycle callers still use the active-run lookup.+SELECT r.* FROM autopilot_run r+JOIN autopilot a ON a.id = r.autopilot_id+WHERE r.issue_id = sqlc.arg(issue_id) AND r.autopilot_id = sqlc.arg(autopilot_id)+ AND a.workspace_id = sqlc.arg(workspace_id)+ORDER BY r.created_at DESC, r.id DESC+LIMIT 1;+-- name: FailAutopilotRunsByIssue :many-- Fails active autopilot runs linked to a given issue.-- Must be called BEFORE issue deletion (ON DELETE SET NULL clears issue_id).