diff --git a/apps/backend/internal/github/AGENTS.md b/apps/backend/internal/github/AGENTS.md index 579203e33b..bd6d85e5fb 100644 --- a/apps/backend/internal/github/AGENTS.md +++ b/apps/backend/internal/github/AGENTS.md @@ -18,10 +18,12 @@ Retain one searching watch per session/repository and one watch per discovered P Watches cannot cover every task PR because sessions can disappear and users can link PRs by URL. Keep the orphan sweep in `service_pr_unwatched.go`. -It reconciles unwatched `github_task_prs` rows and writes lifecycle fields only: -`state`, `merged_at`, and `closed_at`. +It reconciles unwatched `github_task_prs` rows and writes lifecycle fields, +the current `head_sha`, and stored `workflow_attention` when already present. Exclude terminal and detached rows to bound the sweep. -Check and review aggregates belong to the watch-driven path that fetches their evidence. +Actions workflow reads belong to watched sync and feedback paths; the orphan +sweep does not collect new workflow evidence. Check and review aggregates belong +to the watch-driven path that fetches their evidence. The REST PR response alone cannot supply those aggregates. The backend is the only writer of `github_task_prs`. diff --git a/apps/backend/internal/github/client.go b/apps/backend/internal/github/client.go index 21d0959f02..0a4f7c630f 100644 --- a/apps/backend/internal/github/client.go +++ b/apps/backend/internal/github/client.go @@ -127,6 +127,13 @@ type Client interface { // ListCheckRuns lists CI check runs for a given git ref (branch or SHA). ListCheckRuns(ctx context.Context, owner, repo, ref string) ([]CheckRun, error) + // ListWorkflowRuns lists Actions runs associated with the supplied head + // SHA. Implementations must paginate the provider response. + ListWorkflowRuns(ctx context.Context, owner, repo, headSHA string) ([]WorkflowRun, error) + + // ListWorkflowRunJobs lists jobs from one specific workflow-run attempt. + ListWorkflowRunJobs(ctx context.Context, owner, repo string, runID int64, attempt int) ([]WorkflowJob, error) + // GetPRFeedback fetches aggregated feedback (reviews, comments, checks) for a PR. GetPRFeedback(ctx context.Context, owner, repo string, number int) (*PRFeedback, error) diff --git a/apps/backend/internal/github/client_helpers.go b/apps/backend/internal/github/client_helpers.go index bcdabc3097..0109a20e08 100644 --- a/apps/backend/internal/github/client_helpers.go +++ b/apps/backend/internal/github/client_helpers.go @@ -95,13 +95,15 @@ func getPRFeedback(ctx context.Context, c Client, owner, repo string, number int if checks == nil { checks = []CheckRun{} } + workflowAttention, _ := collectWorkflowAttention(ctx, c, owner, repo, pr) hasIssues := hasFailingChecks(checks) || hasChangesRequested(reviews) return &PRFeedback{ - PR: pr, - Reviews: reviews, - Comments: comments, - Checks: checks, - HasIssues: hasIssues, + PR: pr, + Reviews: reviews, + Comments: comments, + Checks: checks, + HasIssues: hasIssues, + WorkflowAttention: workflowAttention, }, nil } @@ -126,7 +128,8 @@ func getPRStatus(ctx context.Context, c Client, owner, repo string, number int) if checks == nil { checks = []CheckRun{} } - return newPRStatus(pr, reviews, checks), nil + workflowAttention, _ := collectWorkflowAttention(ctx, c, owner, repo, pr) + return newPRStatusWithWorkflow(pr, reviews, checks, workflowAttention), nil } // newPRStatus derives the PRStatus rollup from the three upstream reads every @@ -140,10 +143,15 @@ func getPRStatus(ctx context.Context, c Client, owner, repo string, number int) // UnresolvedReviewThreadsPopulated stays false — neither REST caller fetches // review threads, so SyncTaskPR must preserve whatever the GraphQL path stored. func newPRStatus(pr *PR, reviews []PRReview, checks []CheckRun) *PRStatus { + return newPRStatusWithWorkflow(pr, reviews, checks, nil) +} + +func newPRStatusWithWorkflow(pr *PR, reviews []PRReview, checks []CheckRun, workflowAttention *WorkflowAttention) *PRStatus { reviewState, pendingReviewCount := deriveReviewSyncState(pr, reviews) total, passing := countCheckResults(checks) return &PRStatus{ PR: pr, + WorkflowAttention: workflowAttention, ReviewState: reviewState, ChecksState: computeOverallCheckStatus(checks), MergeableState: pr.MergeableState, @@ -175,6 +183,7 @@ func newPRStatus(pr *PR, reviews []PRReview, checks []CheckRun) *PRStatus { // neither REST caller can see the closing actor — that's GraphQL-only // (AC-15). OutcomeFieldsPopulated: true, + WorkflowAttentionPopulated: workflowAttention != nil, mergeQueuePopulated: pr.mergeQueuePopulated, mergeQueueRecoveryPopulated: pr.mergeQueueRecoveryPopulated, } diff --git a/apps/backend/internal/github/client_helpers_test.go b/apps/backend/internal/github/client_helpers_test.go index 66b2467045..24a62cba2f 100644 --- a/apps/backend/internal/github/client_helpers_test.go +++ b/apps/backend/internal/github/client_helpers_test.go @@ -246,6 +246,14 @@ func (c *feedbackConcurrencyClient) ListCheckRuns(ctx context.Context, _ string, return c.checks, nil } +func (c *feedbackConcurrencyClient) ListWorkflowRuns(context.Context, string, string, string) ([]WorkflowRun, error) { + return nil, nil +} + +func (c *feedbackConcurrencyClient) ListWorkflowRunJobs(context.Context, string, string, int64, int) ([]WorkflowJob, error) { + return nil, nil +} + func (c *feedbackConcurrencyClient) wait(ctx context.Context, request string) error { c.started <- request if c.fail != "" && c.fail != request { diff --git a/apps/backend/internal/github/controller_test.go b/apps/backend/internal/github/controller_test.go index 3673fd134e..db6e34372f 100644 --- a/apps/backend/internal/github/controller_test.go +++ b/apps/backend/internal/github/controller_test.go @@ -110,6 +110,12 @@ func (s *stubClient) ListPRComments(context.Context, string, string, int, *time. func (s *stubClient) ListCheckRuns(context.Context, string, string, string) ([]CheckRun, error) { return nil, nil } +func (s *stubClient) ListWorkflowRuns(context.Context, string, string, string) ([]WorkflowRun, error) { + return nil, nil +} +func (s *stubClient) ListWorkflowRunJobs(context.Context, string, string, int64, int) ([]WorkflowJob, error) { + return nil, nil +} func (s *stubClient) GetPRFeedback(context.Context, string, string, int) (*PRFeedback, error) { return nil, nil } diff --git a/apps/backend/internal/github/gh_client.go b/apps/backend/internal/github/gh_client.go index e942796b3d..fa3e119a01 100644 --- a/apps/backend/internal/github/gh_client.go +++ b/apps/backend/internal/github/gh_client.go @@ -772,6 +772,40 @@ func (c *GHClient) ListCheckRuns(ctx context.Context, owner, repo, ref string) ( return mergeChecks(convertRawCheckRuns(checkRunsRaw), convertRawStatusContexts(statusRaw)), nil } +func (c *GHClient) ListWorkflowRuns(ctx context.Context, owner, repo, headSHA string) ([]WorkflowRun, error) { + runsOut, err := c.run(ctx, "api", "--paginate", + fmt.Sprintf("repos/%s/%s/actions/runs?head_sha=%s&per_page=100", owner, repo, url.QueryEscape(headSHA)), + "--jq", ".workflow_runs[]") + if err != nil { + return nil, fmt.Errorf("list workflow runs: %w", err) + } + runsRaw, err := decodeGHWorkflowRuns(runsOut) + if err != nil { + return nil, fmt.Errorf("parse workflow runs: %w", err) + } + runs := make([]WorkflowRun, 0, len(runsRaw)) + for _, raw := range runsRaw { + runs = append(runs, convertRawWorkflowRun(raw)) + } + return runs, nil +} + +func (c *GHClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string, runID int64, attempt int) ([]WorkflowJob, error) { + endpoint := fmt.Sprintf("repos/%s/%s/actions/runs/%d/jobs?per_page=100", owner, repo, runID) + if attempt > 0 { + endpoint = fmt.Sprintf("repos/%s/%s/actions/runs/%d/attempts/%d/jobs?per_page=100", owner, repo, runID, attempt) + } + jobsOut, err := c.run(ctx, "api", "--paginate", endpoint, "--jq", ".jobs[]") + if err != nil { + return nil, fmt.Errorf("list workflow jobs: %w", err) + } + jobsRaw, err := decodeGHWorkflowJobs(jobsOut) + if err != nil { + return nil, fmt.Errorf("parse workflow jobs: %w", err) + } + return convertRawWorkflowJobs(jobsRaw), nil +} + // decodeGHCheckRuns decodes whitespace-separated JSON check-run objects // emitted by gh --paginate --jq '.check_runs[]'. func decodeGHCheckRuns(out string) ([]ghCheckRun, error) { diff --git a/apps/backend/internal/github/gh_client_reads_test.go b/apps/backend/internal/github/gh_client_reads_test.go index a25db87872..1487ccc397 100644 --- a/apps/backend/internal/github/gh_client_reads_test.go +++ b/apps/backend/internal/github/gh_client_reads_test.go @@ -54,6 +54,46 @@ func TestGHClient_GetIssue(t *testing.T) { } } +func TestGHClient_ListWorkflowRunsAndJobs(t *testing.T) { + calls := newFakeGH(t, + ghResponse{ + Prefix: "api --paginate repos/acme/widget/actions/runs?head_sha=feature%2Fsha&per_page=100", + Stdout: `{"id":7,"run_attempt":2,"workflow_id":9,"name":"Run tests","event":"pull_request","status":"completed","conclusion":"action_required","head_sha":"feature/sha","head_branch":"feature","head_repository":{"full_name":"contributor/widget-fork","name":"widget-fork","owner":{"login":"contributor"}},"html_url":"https://github.com/acme/widget/actions/runs/7","created_at":"2026-09-01T10:00:00Z","updated_at":"2026-09-01T11:00:00Z","pull_requests":[]} +{"id":8,"run_attempt":1,"workflow_id":10,"name":"Lint","event":"push","status":"completed","conclusion":"success","head_sha":"feature/sha","head_branch":"feature","html_url":"https://github.com/acme/widget/actions/runs/8","created_at":"2026-09-01T10:00:00Z","updated_at":"2026-09-01T11:00:00Z","pull_requests":[]}`, + }, + ghResponse{ + Prefix: "api --paginate repos/acme/widget/actions/runs/7/attempts/2/jobs?per_page=100", + Stdout: `{"id":70,"name":"approval gate","status":"completed","conclusion":null} +{"id":71,"name":"test","status":"completed","conclusion":"success"}`, + }, + ) + + runs, err := NewGHClient().ListWorkflowRuns(context.Background(), "acme", "widget", "feature/sha") + if err != nil { + t.Fatalf("ListWorkflowRuns: %v", err) + } + assertGHArgv(t, calls(t), 0, []string{ + "api", "--paginate", "repos/acme/widget/actions/runs?head_sha=feature%2Fsha&per_page=100", "--jq", ".workflow_runs[]", + }) + if len(runs) != 2 || runs[0].HeadRepoOwner != "contributor" || runs[0].HeadRepoName != "widget-fork" { + t.Fatalf("runs = %#v", runs) + } + if runs[0].Conclusion != "action_required" || runs[0].RunAttempt != 2 || len(runs[0].PullRequests) != 0 { + t.Fatalf("run[0] = %#v", runs[0]) + } + + jobs, err := NewGHClient().ListWorkflowRunJobs(context.Background(), "acme", "widget", 7, 2) + if err != nil { + t.Fatalf("ListWorkflowRunJobs: %v", err) + } + assertGHArgv(t, calls(t), 1, []string{ + "api", "--paginate", "repos/acme/widget/actions/runs/7/attempts/2/jobs?per_page=100", "--jq", ".jobs[]", + }) + if len(jobs) != 2 || jobs[0].Name != "approval gate" || jobs[0].Conclusion != "" { + t.Fatalf("jobs = %#v", jobs) + } +} + // The gh CLI emits "" (not null) for an open issue's closedAt. func TestGHClient_GetIssue_EmptyClosedAtDecodesToNil(t *testing.T) { newFakeGH(t, ghResponse{ diff --git a/apps/backend/internal/github/graphql.go b/apps/backend/internal/github/graphql.go index 3afeb62f67..645c5ee8fd 100644 --- a/apps/backend/internal/github/graphql.go +++ b/apps/backend/internal/github/graphql.go @@ -209,6 +209,8 @@ type batchedPRResult struct { HeadRefName string `json:"headRefName"` BaseRefName string `json:"baseRefName"` HeadRefOid string `json:"headRefOid"` + HeadRepository ghRepository `json:"headRepository"` + HeadRepoOwner ghRepositoryOwner `json:"headRepositoryOwner"` Additions int `json:"additions"` Deletions int `json:"deletions"` // ChangedFiles is a pointer for the same reason as IsDraft (AC-12a): 0 is @@ -434,7 +436,7 @@ func buildBatchedPRQuery(refs []graphQLPRRef) (string, map[string]any) { // the batched and single-PR paths returning the same data. func prFieldsBlock() string { return `state title url isDraft mergeable mergeStateStatus ` + - `headRefName baseRefName headRefOid additions deletions changedFiles ` + + `headRefName baseRefName headRefOid headRepository { id name nameWithOwner cloneUrl } headRepositoryOwner { login } additions deletions changedFiles ` + `author { login } mergedBy { login } autoMergeRequest { enabledAt } ` + `mergeQueueEntry { id state position estimatedTimeToMerge headCommit { oid } } ` + `createdAt updatedAt mergedAt closedAt ` + @@ -487,6 +489,10 @@ func convertBatchedPRResult(raw *batchedPRResult, owner, repo string, number int AuthorLogin: raw.Author.Login, RepoOwner: owner, RepoName: repo, + HeadRepoNodeID: raw.HeadRepository.ID, + HeadRepoOwner: raw.HeadRepoOwner.Login, + HeadRepoName: raw.HeadRepository.Name, + HeadRepoCloneURL: raw.HeadRepository.CloneURL, Draft: draft, IsDraftObserved: raw.IsDraft != nil, Mergeable: raw.Mergeable == ghMergeableState, @@ -502,6 +508,7 @@ func convertBatchedPRResult(raw *batchedPRResult, owner, repo string, number int MergedAt: parseTimePtr(raw.MergedAt), ClosedAt: parseTimePtr(raw.ClosedAt), } + fillMissingHeadRepositoryIdentity(pr, raw.HeadRepository.NameWithOwner) reviewState := summarizeReviewState(raw.Reviews.Nodes) checksState := "" @@ -544,6 +551,22 @@ func convertBatchedPRResult(raw *batchedPRResult, owner, repo string, number int } } +func fillMissingHeadRepositoryIdentity(pr *PR, nameWithOwner string) { + if pr.HeadRepoOwner != "" && pr.HeadRepoName != "" { + return + } + parts := strings.SplitN(nameWithOwner, "/", 2) + if len(parts) != 2 { + return + } + if pr.HeadRepoOwner == "" { + pr.HeadRepoOwner = parts[0] + } + if pr.HeadRepoName == "" { + pr.HeadRepoName = parts[1] + } +} + func convertMergeQueueEntry(entry *batchedMergeQueueEntry) (string, *int, *int, string, string) { if entry == nil { return "", nil, nil, "", "" diff --git a/apps/backend/internal/github/graphql_test.go b/apps/backend/internal/github/graphql_test.go index 6744bf239b..ee7fc49a3e 100644 --- a/apps/backend/internal/github/graphql_test.go +++ b/apps/backend/internal/github/graphql_test.go @@ -170,7 +170,7 @@ func TestBuildBatchedPRQuery_GroupsByRepo(t *testing.T) { // batched branch query return the same fields. func TestPRFieldsBlock_RequestsOutcomeFields(t *testing.T) { block := prFieldsBlock() - for _, want := range []string{"changedFiles", "mergedBy { login }", "autoMergeRequest", "CLOSED_EVENT"} { + for _, want := range []string{"changedFiles", "mergedBy { login }", "autoMergeRequest", "headRepository {", "headRepositoryOwner { login }", "CLOSED_EVENT"} { if !strings.Contains(block, want) { t.Errorf("prFieldsBlock() missing %q: %s", want, block) } diff --git a/apps/backend/internal/github/mock_client.go b/apps/backend/internal/github/mock_client.go index 44950a7019..b23381bb8b 100644 --- a/apps/backend/internal/github/mock_client.go +++ b/apps/backend/internal/github/mock_client.go @@ -128,6 +128,8 @@ type MockClient struct { reviews map[prKey][]PRReview comments map[prKey][]PRComment checks map[checkKey][]CheckRun + workflowRuns map[workflowRunKey][]WorkflowRun + workflowJobs map[workflowJobKey][]WorkflowJob files map[prKey][]PRFile commits map[prKey][]PRCommitInfo prCommitsFailures map[prKey]int @@ -184,6 +186,8 @@ func NewMockClient() *MockClient { reviews: make(map[prKey][]PRReview), comments: make(map[prKey][]PRComment), checks: make(map[checkKey][]CheckRun), + workflowRuns: make(map[workflowRunKey][]WorkflowRun), + workflowJobs: make(map[workflowJobKey][]WorkflowJob), files: make(map[prKey][]PRFile), commits: make(map[prKey][]PRCommitInfo), prCommitsFailures: make(map[prKey]int), @@ -560,6 +564,20 @@ func (m *MockClient) ListCheckRuns(_ context.Context, owner, repo, ref string) ( return m.checks[checkKey{owner, repo, ref}], nil } +func (m *MockClient) ListWorkflowRuns(_ context.Context, owner, repo, headSHA string) ([]WorkflowRun, error) { + m.mu.RLock() + defer m.mu.RUnlock() + runs := m.workflowRuns[workflowRunKey{Owner: owner, Repo: repo, HeadSHA: headSHA}] + return append([]WorkflowRun(nil), runs...), nil +} + +func (m *MockClient) ListWorkflowRunJobs(_ context.Context, owner, repo string, runID int64, attempt int) ([]WorkflowJob, error) { + m.mu.RLock() + defer m.mu.RUnlock() + jobs := m.workflowJobs[workflowJobKey{Owner: owner, Repo: repo, RunID: runID, Attempt: attempt}] + return append([]WorkflowJob(nil), jobs...), nil +} + func (m *MockClient) GetPRFeedback(ctx context.Context, owner, repo string, number int) (*PRFeedback, error) { return getPRFeedback(ctx, m, owner, repo, number) } @@ -1051,6 +1069,36 @@ func (m *MockClient) ReplaceCheckRuns(owner, repo, ref string, checks []CheckRun m.checks[checkKey{owner, repo, ref}] = cp } +// AddWorkflowRuns appends Actions runs for a PR head SHA. +func (m *MockClient) AddWorkflowRuns(owner, repo, headSHA string, runs []WorkflowRun) { + m.mu.Lock() + defer m.mu.Unlock() + k := workflowRunKey{Owner: owner, Repo: repo, HeadSHA: headSHA} + m.workflowRuns[k] = append(m.workflowRuns[k], runs...) +} + +// ReplaceWorkflowRuns overwrites Actions runs for a PR head SHA. +func (m *MockClient) ReplaceWorkflowRuns(owner, repo, headSHA string, runs []WorkflowRun) { + m.mu.Lock() + defer m.mu.Unlock() + m.workflowRuns[workflowRunKey{Owner: owner, Repo: repo, HeadSHA: headSHA}] = append([]WorkflowRun(nil), runs...) +} + +// AddWorkflowRunJobs appends jobs for one Actions run attempt. +func (m *MockClient) AddWorkflowRunJobs(owner, repo string, runID int64, attempt int, jobs []WorkflowJob) { + m.mu.Lock() + defer m.mu.Unlock() + k := workflowJobKey{Owner: owner, Repo: repo, RunID: runID, Attempt: attempt} + m.workflowJobs[k] = append(m.workflowJobs[k], jobs...) +} + +// ReplaceWorkflowRunJobs overwrites jobs for one Actions run attempt. +func (m *MockClient) ReplaceWorkflowRunJobs(owner, repo string, runID int64, attempt int, jobs []WorkflowJob) { + m.mu.Lock() + defer m.mu.Unlock() + m.workflowJobs[workflowJobKey{Owner: owner, Repo: repo, RunID: runID, Attempt: attempt}] = append([]WorkflowJob(nil), jobs...) +} + // ReplaceReviews overwrites the reviews for a PR. func (m *MockClient) ReplaceReviews(owner, repo string, number int, reviews []PRReview) { m.mu.Lock() @@ -1125,6 +1173,8 @@ func (m *MockClient) Reset() { m.reviews = make(map[prKey][]PRReview) m.comments = make(map[prKey][]PRComment) m.checks = make(map[checkKey][]CheckRun) + m.workflowRuns = make(map[workflowRunKey][]WorkflowRun) + m.workflowJobs = make(map[workflowJobKey][]WorkflowJob) m.files = make(map[prKey][]PRFile) m.commits = make(map[prKey][]PRCommitInfo) m.prCommitsFailures = make(map[prKey]int) diff --git a/apps/backend/internal/github/mock_controller.go b/apps/backend/internal/github/mock_controller.go index 656a2162e4..6388efe5b9 100644 --- a/apps/backend/internal/github/mock_controller.go +++ b/apps/backend/internal/github/mock_controller.go @@ -59,6 +59,8 @@ func (c *MockController) RegisterRoutes(router *gin.Engine) { api.POST("/repo-files", c.addRepoFiles) api.POST("/task-prs", c.associateTaskPR) api.POST("/pr-feedback", c.seedPRFeedback) + api.POST("/workflow-runs", c.addWorkflowRuns) + api.POST("/workflow-jobs", c.addWorkflowRunJobs) api.PUT("/auth-health", c.setAuthHealth) api.PUT("/workspace-connections/:workspaceId", c.setWorkspaceConnection) api.DELETE("/workspace-connections/:workspaceId", c.deleteWorkspaceConnection) @@ -715,6 +717,8 @@ type associateTaskPRRequest struct { AuthorLogin string `json:"author_login"` State string `json:"state"` HeadSHA string `json:"head_sha,omitempty"` + HeadRepoOwner string `json:"head_repo_owner,omitempty"` + HeadRepoName string `json:"head_repo_name,omitempty"` ReviewState string `json:"review_state"` ChecksState string `json:"checks_state"` MergeableState string `json:"mergeable_state"` @@ -844,6 +848,8 @@ func (c *MockController) ensureMockPRForRequest(ctx context.Context, req *associ State: req.State, HeadBranch: req.HeadBranch, HeadSHA: headSHA, + HeadRepoOwner: req.HeadRepoOwner, + HeadRepoName: req.HeadRepoName, BaseBranch: req.BaseBranch, AuthorLogin: req.AuthorLogin, MergeableState: req.MergeableState, @@ -869,12 +875,18 @@ func (c *MockController) ensureMockPRForRequest(ctx context.Context, req *associ // resolves them via ListCheckRuns. func (c *MockController) seedPRFeedback(ctx *gin.Context) { var req struct { - Owner string `json:"owner"` - Repo string `json:"repo"` - PRNumber int `json:"pr_number"` - Checks []CheckRun `json:"checks"` - Reviews []PRReview `json:"reviews"` - Comments []PRComment `json:"comments"` + Owner string `json:"owner"` + Repo string `json:"repo"` + PRNumber int `json:"pr_number"` + Checks []CheckRun `json:"checks"` + Reviews []PRReview `json:"reviews"` + Comments []PRComment `json:"comments"` + WorkflowRuns []WorkflowRun `json:"workflow_runs"` + WorkflowJobs []struct { + RunID int64 `json:"run_id"` + RunAttempt int `json:"run_attempt"` + Jobs []WorkflowJob `json:"jobs"` + } `json:"workflow_jobs"` } if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) @@ -906,6 +918,25 @@ func (c *MockController) seedPRFeedback(ctx *gin.Context) { c.mock.ReplaceCheckRuns(req.Owner, req.Repo, headSHA, req.Checks) c.mock.ReplaceReviews(req.Owner, req.Repo, req.PRNumber, req.Reviews) c.mock.ReplaceComments(req.Owner, req.Repo, req.PRNumber, req.Comments) + for i := range req.WorkflowRuns { + if req.WorkflowRuns[i].HeadSHA == "" { + req.WorkflowRuns[i].HeadSHA = headSHA + } + } + c.mock.ReplaceWorkflowRuns(req.Owner, req.Repo, headSHA, req.WorkflowRuns) + for _, workflowJobs := range req.WorkflowJobs { + attempt := workflowJobs.RunAttempt + if attempt <= 0 { + attempt = 1 + } + c.mock.ReplaceWorkflowRunJobs(req.Owner, req.Repo, workflowJobs.RunID, attempt, workflowJobs.Jobs) + } + // A feedback seed represents a provider-side mutation. Drop the service + // snapshots so the next browser refresh observes the new mock data without + // waiting for the production cache TTL. + if c.service != nil { + c.service.ClearPRCaches() + } ctx.JSON(http.StatusOK, gin.H{ "checks": len(req.Checks), "reviews": len(req.Reviews), @@ -913,6 +944,52 @@ func (c *MockController) seedPRFeedback(ctx *gin.Context) { }) } +func (c *MockController) addWorkflowRuns(ctx *gin.Context) { + var req struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + HeadSHA string `json:"head_sha"` + Runs []WorkflowRun `json:"runs"` + } + if err := ctx.ShouldBindJSON(&req); err != nil || req.Owner == "" || req.Repo == "" || req.HeadSHA == "" { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "owner, repo, head_sha are required"}) + return + } + for i := range req.Runs { + if req.Runs[i].HeadSHA == "" { + req.Runs[i].HeadSHA = req.HeadSHA + } + } + c.mock.ReplaceWorkflowRuns(req.Owner, req.Repo, req.HeadSHA, req.Runs) + if c.service != nil { + c.service.ClearPRCaches() + } + ctx.JSON(http.StatusOK, gin.H{"runs": len(req.Runs)}) +} + +func (c *MockController) addWorkflowRunJobs(ctx *gin.Context) { + var req struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + RunID int64 `json:"run_id"` + RunAttempt int `json:"run_attempt"` + Jobs []WorkflowJob `json:"jobs"` + } + if err := ctx.ShouldBindJSON(&req); err != nil || req.Owner == "" || req.Repo == "" || req.RunID == 0 { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "owner, repo, run_id are required"}) + return + } + attempt := req.RunAttempt + if attempt <= 0 { + attempt = 1 + } + c.mock.ReplaceWorkflowRunJobs(req.Owner, req.Repo, req.RunID, attempt, req.Jobs) + if c.service != nil { + c.service.ClearPRCaches() + } + ctx.JSON(http.StatusOK, gin.H{"jobs": len(req.Jobs)}) +} + // setAuthHealth toggles the mock client's authenticated state so e2e tests // can drive the "Reconnect GitHub" branch in the popover. func (c *MockController) setAuthHealth(ctx *gin.Context) { diff --git a/apps/backend/internal/github/mock_controller_test.go b/apps/backend/internal/github/mock_controller_test.go index 63c048e21b..20297b6470 100644 --- a/apps/backend/internal/github/mock_controller_test.go +++ b/apps/backend/internal/github/mock_controller_test.go @@ -56,6 +56,71 @@ func TestMockControllerSequencesPRCommitFailureThenSuccess(t *testing.T) { } } +func TestMockControllerSeedPRFeedbackClearsPRCaches(t *testing.T) { + router, svc, _ := setupWorkspaceAuthMockController(t) + svc.prFeedbackCache.set("feedback", "stale") + svc.prStatusCache.set("status", "stale") + + response := serveMockJSON(t, router, http.MethodPost, + "/api/v1/github/mock/pr-feedback", + `{"owner":"owner","repo":"repo","pr_number":7,"workflow_runs":[{"id":7,"run_attempt":1,"workflow_id":9,"name":"CI","event":"pull_request","status":"completed","conclusion":"action_required","head_sha":"head"}],"workflow_jobs":[{"run_id":7,"jobs":[{"id":70,"name":"test","status":"completed","conclusion":"success"}]}]}`) + if response.Code != http.StatusOK { + t.Fatalf("seed PR feedback: %d %s", response.Code, response.Body.String()) + } + if _, ok := svc.prFeedbackCache.get("feedback"); ok { + t.Fatal("feedback cache still contains the seeded snapshot") + } + if _, ok := svc.prStatusCache.get("status"); ok { + t.Fatal("status cache still contains the seeded snapshot") + } + mock, ok := svc.client.(*MockClient) + if !ok { + t.Fatalf("service client has type %T, want *MockClient", svc.client) + } + jobs, err := mock.ListWorkflowRunJobs(context.Background(), "owner", "repo", 7, 1) + if err != nil || len(jobs) != 1 { + t.Fatalf("workflow jobs with omitted attempt = %#v, err=%v; want attempt 1", jobs, err) + } +} + +func TestMockControllerWorkflowMutationsClearCachesAndNormalizeEvidence(t *testing.T) { + router, svc, _ := setupWorkspaceAuthMockController(t) + mock, ok := svc.client.(*MockClient) + if !ok { + t.Fatalf("service client has type %T, want *MockClient", svc.client) + } + + svc.prFeedbackCache.set("feedback", "stale") + runsResponse := serveMockJSON(t, router, http.MethodPost, + "/api/v1/github/mock/workflow-runs", + `{"owner":"owner","repo":"repo","head_sha":"head-sha","runs":[{"id":7,"workflow_id":9,"name":"CI","head_sha":""}]}`) + if runsResponse.Code != http.StatusOK { + t.Fatalf("seed workflow runs: %d %s", runsResponse.Code, runsResponse.Body.String()) + } + if _, ok := svc.prFeedbackCache.get("feedback"); ok { + t.Fatal("feedback cache still contains workflow-run mutation snapshot") + } + runs, err := mock.ListWorkflowRuns(context.Background(), "owner", "repo", "head-sha") + if err != nil || len(runs) != 1 || runs[0].HeadSHA != "head-sha" { + t.Fatalf("workflow runs = %#v, err=%v; want requested head SHA copied into run", runs, err) + } + + svc.prStatusCache.set("status", "stale") + jobsResponse := serveMockJSON(t, router, http.MethodPost, + "/api/v1/github/mock/workflow-jobs", + `{"owner":"owner","repo":"repo","run_id":7,"jobs":[{"id":70,"name":"test","status":"completed","conclusion":"success"}]}`) + if jobsResponse.Code != http.StatusOK { + t.Fatalf("seed workflow jobs: %d %s", jobsResponse.Code, jobsResponse.Body.String()) + } + if _, ok := svc.prStatusCache.get("status"); ok { + t.Fatal("status cache still contains workflow-job mutation snapshot") + } + jobs, err := mock.ListWorkflowRunJobs(context.Background(), "owner", "repo", 7, 1) + if err != nil || len(jobs) != 1 { + t.Fatalf("workflow jobs = %#v, err=%v; want omitted attempt normalized to 1", jobs, err) + } +} + func TestMockControllerWorkspaceConnectionsResolveIsolatedPrincipals(t *testing.T) { router, svc, _ := setupWorkspaceAuthMockController(t) registration := serveMockJSON(t, router, http.MethodPut, diff --git a/apps/backend/internal/github/models.go b/apps/backend/internal/github/models.go index 4b70d12d67..87a43a291a 100644 --- a/apps/backend/internal/github/models.go +++ b/apps/backend/internal/github/models.go @@ -389,26 +389,105 @@ type CheckRun struct { CompletedAt *time.Time `json:"completed_at,omitempty"` } +// WorkflowAttentionState describes an Actions workflow observation that is +// separate from check-run success and failure. Unknown means the Actions +// evidence was unavailable or incomplete; none is authoritative absence. +type WorkflowAttentionState string + +const ( + WorkflowAttentionUnknown WorkflowAttentionState = "unknown" + WorkflowAttentionNone WorkflowAttentionState = "none" + WorkflowAttentionApprovalRequired WorkflowAttentionState = "approval_required" + WorkflowAttentionActionRequired WorkflowAttentionState = "action_required" +) + +// WorkflowAttentionRun identifies a selected workflow that needs a human or +// other GitHub action before it can proceed. +type WorkflowAttentionRun struct { + RunID int64 `json:"run_id"` + RunAttempt int `json:"run_attempt"` + WorkflowID int64 `json:"workflow_id"` + Name string `json:"name"` + URL string `json:"url"` + Reason string `json:"reason"` +} + +// WorkflowAttention is the head-scoped Actions observation persisted with a +// pull request. A positive stale observation remains useful only for the +// same head SHA and is never treated as fresh evidence. +type WorkflowAttention struct { + State WorkflowAttentionState `json:"state"` + HeadSHA string `json:"head_sha"` + ObservedAt time.Time `json:"observed_at"` + Stale bool `json:"stale"` + Runs []WorkflowAttentionRun `json:"runs"` +} + +// WorkflowRun is the provider-neutral subset of a GitHub Actions run needed +// to match a run to one pull-request head and classify action_required. +type WorkflowRun struct { + ID int64 `json:"id"` + RunAttempt int `json:"run_attempt"` + WorkflowID int64 `json:"workflow_id"` + Name string `json:"name"` + Event string `json:"event"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + HeadSHA string `json:"head_sha"` + HeadBranch string `json:"head_branch"` + HeadRepoID int64 `json:"head_repo_id"` + HeadRepoOwner string `json:"head_repo_owner"` + HeadRepoName string `json:"head_repo_name"` + HeadRepoURL string `json:"head_repo_url"` + HTMLURL string `json:"html_url"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + PullRequests []WorkflowRunPullRequest `json:"pull_requests"` +} + +// WorkflowRunPullRequest is an association included in a workflow-run API +// response. GitHub can return no associations for a fork pull_request run. +type WorkflowRunPullRequest struct { + Number int `json:"number"` + HeadSHA string `json:"head_sha"` + HeadBranch string `json:"head_branch"` + HeadRepoID int64 `json:"head_repo_id"` + HeadRepoOwner string `json:"head_repo_owner"` + HeadRepoName string `json:"head_repo_name"` + HeadRepoURL string `json:"head_repo_url"` +} + +// WorkflowJob is the current-attempt job subset used to distinguish a +// jobless fork approval gate from other action_required conclusions. +type WorkflowJob struct { + ID int64 `json:"id"` + Name string `json:"name"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` +} + // PRFeedback aggregates all feedback for a PR (fetched live from GitHub). type PRFeedback struct { - PR *PR `json:"pr"` - Reviews []PRReview `json:"reviews"` - Comments []PRComment `json:"comments"` - Checks []CheckRun `json:"checks"` - HasIssues bool `json:"has_issues"` + PR *PR `json:"pr"` + Reviews []PRReview `json:"reviews"` + Comments []PRComment `json:"comments"` + Checks []CheckRun `json:"checks"` + HasIssues bool `json:"has_issues"` + WorkflowAttention *WorkflowAttention `json:"workflow_attention,omitempty"` } // PRStatus contains lightweight PR state used by the background poller. // Unlike PRFeedback, it skips comments to reduce API calls. type PRStatus struct { - PR *PR `json:"pr"` - ReviewState string `json:"review_state"` // "approved", "changes_requested", "pending", "" - ChecksState string `json:"checks_state"` // "success", "failure", "pending", "" - MergeableState string `json:"mergeable_state"` // "clean", "blocked", "behind", "dirty", "has_hooks", "unstable", "draft", "unknown", "" - MergeQueueState string `json:"merge_queue_state"` - MergeQueuePosition *int `json:"merge_queue_position,omitempty"` - MergeQueueEntryID string `json:"merge_queue_entry_id,omitempty"` - MergeQueueEntryHeadSHA string `json:"merge_queue_entry_head_sha,omitempty"` + PR *PR `json:"pr"` + WorkflowAttention *WorkflowAttention `json:"workflow_attention,omitempty"` + ReviewState string `json:"review_state"` // "approved", "changes_requested", "pending", "" + ChecksState string `json:"checks_state"` // "success", "failure", "pending", "" + MergeableState string `json:"mergeable_state"` // "clean", "blocked", "behind", "dirty", "has_hooks", "unstable", "draft", "unknown", "" + MergeQueueState string `json:"merge_queue_state"` + MergeQueuePosition *int `json:"merge_queue_position,omitempty"` + MergeQueueEntryID string `json:"merge_queue_entry_id,omitempty"` + MergeQueueEntryHeadSHA string `json:"merge_queue_entry_head_sha,omitempty"` // A nil estimate is an observed absence when mergeQueuePopulated is true. MergeQueueEstimatedTimeToMergeSeconds *int `json:"merge_queue_estimated_time_to_merge_seconds,omitempty"` MergeQueueLastRemovalID string `json:"merge_queue_last_removal_id,omitempty"` @@ -445,6 +524,9 @@ type PRStatus struct { // a full single pull request or a batched GraphQL result, so a zero/empty // value is a real observation rather than "I didn't look." OutcomeFieldsPopulated bool `json:"outcome_fields_populated,omitempty"` + // WorkflowAttentionPopulated distinguishes a status path that attempted + // the Actions read from legacy callers that did not know this field. + WorkflowAttentionPopulated bool `json:"workflow_attention_populated,omitempty"` // ClosedByLogin is the closed-event actor's login, populated only by the // GraphQL path (closed_by is absent from the REST pulls endpoint and the // gh CLI's PR field set). @@ -563,6 +645,11 @@ type TaskPR struct { // this column existed; never backfilled. Source string `json:"source" db:"source"` + // WorkflowAttentionJSON is the persisted wire value. WorkflowAttention is + // the API-facing decoded form and is hydrated after database reads. + WorkflowAttentionJSON string `json:"-" db:"workflow_attention"` + WorkflowAttention *WorkflowAttention `json:"workflow_attention,omitempty" db:"-"` + // --- PR outcome attribution (five nullable columns, never backfilled) --- // // Every field below is NULL on any row that predates this feature's diff --git a/apps/backend/internal/github/noop_client.go b/apps/backend/internal/github/noop_client.go index 0b76c9b9ea..6fdb757b57 100644 --- a/apps/backend/internal/github/noop_client.go +++ b/apps/backend/internal/github/noop_client.go @@ -89,6 +89,14 @@ func (c *NoopClient) ListCheckRuns(context.Context, string, string, string) ([]C return nil, ErrNoClient } +func (c *NoopClient) ListWorkflowRuns(context.Context, string, string, string) ([]WorkflowRun, error) { + return nil, ErrNoClient +} + +func (c *NoopClient) ListWorkflowRunJobs(context.Context, string, string, int64, int) ([]WorkflowJob, error) { + return nil, ErrNoClient +} + func (c *NoopClient) GetPRFeedback(context.Context, string, string, int) (*PRFeedback, error) { return nil, ErrNoClient } diff --git a/apps/backend/internal/github/pat_client.go b/apps/backend/internal/github/pat_client.go index 0a4b003325..ac12cb2c1b 100644 --- a/apps/backend/internal/github/pat_client.go +++ b/apps/backend/internal/github/pat_client.go @@ -610,6 +610,45 @@ func (c *PATClient) ListCheckRuns(ctx context.Context, owner, repo, ref string) ), nil } +func (c *PATClient) ListWorkflowRuns(ctx context.Context, owner, repo, headSHA string) ([]WorkflowRun, error) { + endpoint := fmt.Sprintf("/repos/%s/%s/actions/runs?head_sha=%s&per_page=100", owner, repo, url.QueryEscape(headSHA)) + var runs []WorkflowRun + for endpoint != "" { + var page struct { + WorkflowRuns []ghWorkflowRun `json:"workflow_runs"` + } + next, err := c.getPaginated(ctx, endpoint, &page) + if err != nil { + return nil, err + } + for _, raw := range page.WorkflowRuns { + runs = append(runs, convertRawWorkflowRun(raw)) + } + endpoint = next + } + return runs, nil +} + +func (c *PATClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string, runID int64, attempt int) ([]WorkflowJob, error) { + endpoint := fmt.Sprintf("/repos/%s/%s/actions/runs/%d/jobs?per_page=100", owner, repo, runID) + if attempt > 0 { + endpoint = fmt.Sprintf("/repos/%s/%s/actions/runs/%d/attempts/%d/jobs?per_page=100", owner, repo, runID, attempt) + } + var jobs []WorkflowJob + for endpoint != "" { + var page struct { + Jobs []ghWorkflowJob `json:"jobs"` + } + next, err := c.getPaginated(ctx, endpoint, &page) + if err != nil { + return nil, err + } + jobs = append(jobs, convertRawWorkflowJobs(page.Jobs)...) + endpoint = next + } + return jobs, nil +} + func (c *PATClient) GetPRFeedback(ctx context.Context, owner, repo string, number int) (*PRFeedback, error) { return getPRFeedback(ctx, c, owner, repo, number) } diff --git a/apps/backend/internal/github/pat_client_test.go b/apps/backend/internal/github/pat_client_test.go index 952d029470..59a3a507f6 100644 --- a/apps/backend/internal/github/pat_client_test.go +++ b/apps/backend/internal/github/pat_client_test.go @@ -235,6 +235,44 @@ func TestPATClient_ListCheckRunsPaginatesCheckRuns(t *testing.T) { } } +func TestPATClient_ListWorkflowRunsPaginatesAndListsAttemptJobs(t *testing.T) { + c, requests := newLinkPaginatedPATServer(t, "/repos/acme/widget/actions/runs", []string{ + `{"workflow_runs":[{"id":7,"run_attempt":1,"workflow_id":9,"name":"Run tests","event":"pull_request","status":"completed","conclusion":"action_required","head_sha":"sha","head_branch":"feature","head_repository":{"full_name":"contributor/widget-fork","name":"widget-fork","owner":{"login":"contributor"}},"html_url":"https://github.com/acme/widget/actions/runs/7","created_at":"2026-09-01T10:00:00Z","updated_at":"2026-09-01T10:00:00Z","pull_requests":[]}]}`, + `{"workflow_runs":[{"id":8,"run_attempt":1,"workflow_id":10,"name":"Lint","event":"pull_request","status":"completed","conclusion":"success","head_sha":"sha","head_branch":"feature","html_url":"https://github.com/acme/widget/actions/runs/8","created_at":"2026-09-01T10:00:00Z","updated_at":"2026-09-01T11:00:00Z","pull_requests":[]}]}`, + }) + + runs, err := c.ListWorkflowRuns(context.Background(), "acme", "widget", "sha") + if err != nil { + t.Fatalf("ListWorkflowRuns: %v", err) + } + if len(runs) != 2 || runs[0].HeadRepoOwner != "contributor" || runs[0].HeadRepoName != "widget-fork" { + t.Fatalf("runs = %#v", runs) + } + if len(*requests) != 2 { + t.Fatalf("workflow run requests = %d, want 2", len(*requests)) + } + if got := parseQueryValues(t, (*requests)[0].Query).Get("head_sha"); got != "sha" { + t.Fatalf("head_sha = %q, want sha", got) + } + if got := parseQueryValues(t, (*requests)[0].Query).Get("per_page"); got != "100" { + t.Fatalf("per_page = %q, want 100", got) + } + + jobClient, jobRequests := newRecordingPATServer(t, map[string]string{ + "/repos/acme/widget/actions/runs/7/attempts/1/jobs": `{"jobs":[{"id":70,"name":"approval gate","status":"completed","conclusion":null}]}`, + }) + jobs, err := jobClient.ListWorkflowRunJobs(context.Background(), "acme", "widget", 7, 1) + if err != nil { + t.Fatalf("ListWorkflowRunJobs: %v", err) + } + if len(jobs) != 1 || jobs[0].Name != "approval gate" || jobs[0].Conclusion != "" { + t.Fatalf("jobs = %#v", jobs) + } + if len(*jobRequests) != 1 || parseQueryValues(t, (*jobRequests)[0].Query).Get("per_page") != "100" { + t.Fatalf("job requests = %#v", *jobRequests) + } +} + func TestPATClient_PRCommitDetailUsesExactSHAAndMergesPages(t *testing.T) { var requested []string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/apps/backend/internal/github/service_pr_feedback_sync.go b/apps/backend/internal/github/service_pr_feedback_sync.go index 0abad31658..2629d6fcd2 100644 --- a/apps/backend/internal/github/service_pr_feedback_sync.go +++ b/apps/backend/internal/github/service_pr_feedback_sync.go @@ -45,7 +45,7 @@ func (s *Service) persistPRFeedbackState(ctx context.Context, workspaceID string if len(rows) == 0 { return } - status := newPRStatus(pr, feedback.Reviews, feedback.Checks) + status := newPRStatusWithWorkflow(pr, feedback.Reviews, feedback.Checks, feedback.WorkflowAttention) // Several tasks in a workspace can link the same PR; each owns its own row. // SyncTaskPR re-narrows by (task, owner, repo, number) internally. seen := make(map[string]struct{}, len(rows)) diff --git a/apps/backend/internal/github/service_pr_unwatched.go b/apps/backend/internal/github/service_pr_unwatched.go index e7f18ea9c4..d366c43e95 100644 --- a/apps/backend/internal/github/service_pr_unwatched.go +++ b/apps/backend/internal/github/service_pr_unwatched.go @@ -62,10 +62,11 @@ func taskPRNeedsUnwatchedSync(tp *TaskPR, now time.Time) bool { // leaves the row for the next attempt, matching the surrounding // reconciliation paths — a dead repo must not fail the caller's sync. // -// Only lifecycle fields are written (see reconcileTaskPRLifecycle). Check and -// review aggregates deliberately stay untouched: they belong to the active, -// watch-covered PR, and a row nobody watches only needs to learn that it -// reached a terminal state. +// Only lifecycle and head-scoped workflow-attention fields are written (see +// reconcileTaskPRLifecycle). Check and review aggregates deliberately stay +// untouched: they belong to the active, watch-covered PR, and a row nobody +// watches only needs to learn that it reached a terminal state or that its +// current head needs provider attention. // // fallbackWorkspaceID covers legacy rows written before task_prs carried // workspace ownership; rows with neither are skipped because there is no @@ -153,8 +154,13 @@ func (s *Service) reconcileTaskPRLifecycle(ctx context.Context, tp *TaskPR, stat pr := status.PR isDraft, changedFiles, mergedByLogin, closedByLogin, autoMergeObservedAt := resolveTaskPROutcomeFields(tp, status) + nextHeadSHA := tp.HeadSHA + if pr.HeadSHA != "" { + nextHeadSHA = pr.HeadSHA + } - changed := tp.State != pr.State || + changed := tp.HeadSHA != nextHeadSHA || + tp.State != pr.State || !timeEqual(tp.MergedAt, pr.MergedAt) || !timeEqual(tp.ClosedAt, pr.ClosedAt) || !boolPtrEqual(tp.IsDraft, isDraft) || @@ -162,8 +168,11 @@ func (s *Service) reconcileTaskPRLifecycle(ctx context.Context, tp *TaskPR, stat !stringPtrEqual(tp.MergedByLogin, mergedByLogin) || !stringPtrEqual(tp.ClosedByLogin, closedByLogin) || !timeEqual(tp.AutoMergeObservedAt, autoMergeObservedAt) + nextWorkflowAttention := resolveTaskPRWorkflowAttention(tp, status, nextHeadSHA) + changed = changed || !workflowAttentionSemanticEqual(tp.WorkflowAttention, nextWorkflowAttention) tp.State = pr.State + tp.HeadSHA = nextHeadSHA tp.MergedAt = pr.MergedAt tp.ClosedAt = pr.ClosedAt tp.IsDraft = isDraft @@ -171,6 +180,8 @@ func (s *Service) reconcileTaskPRLifecycle(ctx context.Context, tp *TaskPR, stat tp.MergedByLogin = mergedByLogin tp.ClosedByLogin = closedByLogin tp.AutoMergeObservedAt = autoMergeObservedAt + tp.WorkflowAttention = nextWorkflowAttention + tp.WorkflowAttentionJSON = marshalWorkflowAttention(nextWorkflowAttention) now := time.Now().UTC() tp.LastSyncedAt = &now @@ -236,7 +247,8 @@ func (s *Service) batchedUnwatchedFetch( // concurrent eviction wins; see Service.markRepoAsMissing. repoErrGen := s.repoErrorGenSnapshot() out, queryErr := runBatchedPRQuery(fetchCtx, exec, refs) - return s.absorbMissingReposErr(out, queryErr, cacheScope, repoErrGen) + out, queryErr = s.absorbMissingReposErr(out, queryErr, cacheScope, repoErrGen) + return out, queryErr }) if err != nil { return nil, err diff --git a/apps/backend/internal/github/service_pr_watch.go b/apps/backend/internal/github/service_pr_watch.go index e0af815bda..40d8843aaf 100644 --- a/apps/backend/internal/github/service_pr_watch.go +++ b/apps/backend/internal/github/service_pr_watch.go @@ -934,6 +934,7 @@ type taskPRSyncState struct { changedFiles *int mergedByLogin, closedByLogin *string autoMergeObservedAt *time.Time + workflowAttention *WorkflowAttention } type taskPRMergeQueueState struct { @@ -1125,12 +1126,13 @@ func (s *Service) prepareTaskPRSyncState(ctx context.Context, tp *TaskPR, status } queue := resolveTaskPRMergeQueueState(tp, status) nextState, nextMergedAt, nextClosedAt := resolveTerminalMergeState(tp, status.PR) - nextIsDraft, nextChangedFiles, nextMergedByLogin, nextClosedByLogin, nextAutoMergeObservedAt := - resolveTaskPROutcomeFields(tp, status) nextHeadSHA := tp.HeadSHA if status.PR.HeadSHA != "" { nextHeadSHA = status.PR.HeadSHA } + nextWorkflowAttention := resolveTaskPRWorkflowAttention(tp, status, nextHeadSHA) + nextIsDraft, nextChangedFiles, nextMergedByLogin, nextClosedByLogin, nextAutoMergeObservedAt := + resolveTaskPROutcomeFields(tp, status) return taskPRSyncState{ checksTotal: nextChecksTotal, checksPassing: nextChecksPassing, unresolved: nextUnresolved, reviewCount: nextReviewCount, pendingReviewCount: nextPendingReviewCount, @@ -1144,6 +1146,7 @@ func (s *Service) prepareTaskPRSyncState(ctx context.Context, tp *TaskPR, status isDraft: nextIsDraft, changedFiles: nextChangedFiles, mergedByLogin: nextMergedByLogin, closedByLogin: nextClosedByLogin, autoMergeObservedAt: nextAutoMergeObservedAt, + workflowAttention: nextWorkflowAttention, } } @@ -1199,6 +1202,11 @@ func taskPRChangedFields(tp *TaskPR, status *PRStatus, next taskPRSyncState) []s "auto_merge_observed_at", !timeEqual(tp.AutoMergeObservedAt, next.autoMergeObservedAt), ) + changed = appendChangedField( + changed, + "workflow_attention", + !workflowAttentionSemanticEqual(tp.WorkflowAttention, next.workflowAttention), + ) return changed } @@ -1262,6 +1270,8 @@ func (s *Service) SyncTaskPR(ctx context.Context, taskID string, status *PRStatu tp.MergedByLogin = next.mergedByLogin tp.ClosedByLogin = next.closedByLogin tp.AutoMergeObservedAt = next.autoMergeObservedAt + tp.WorkflowAttention = next.workflowAttention + tp.WorkflowAttentionJSON = marshalWorkflowAttention(next.workflowAttention) // CommentCount is no longer updated from polling -- only refreshed on-demand now := time.Now().UTC() tp.LastSyncedAt = &now diff --git a/apps/backend/internal/github/service_pr_watch_batched.go b/apps/backend/internal/github/service_pr_watch_batched.go index 4b97ec6a28..469973dc57 100644 --- a/apps/backend/internal/github/service_pr_watch_batched.go +++ b/apps/backend/internal/github/service_pr_watch_batched.go @@ -6,6 +6,7 @@ import ( "fmt" "sort" "strings" + "sync" "time" "go.uber.org/zap" @@ -73,7 +74,7 @@ func (s *Service) syncWatchesBatchedWithClient( return nil, err } numbered, searching := splitPRWatches(watches) - statuses, err := s.fetchBatchedWatchStatuses(ctx, exec, cacheScope, numbered, searching) + statuses, err := s.fetchBatchedWatchStatuses(ctx, client, exec, cacheScope, numbered, searching) if err != nil { return nil, err } @@ -92,6 +93,158 @@ func (s *Service) syncWatchesBatchedWithClient( return results, nil } +const ( + workflowAttentionBatchConcurrency = 4 + workflowAttentionBatchBudget = 5 * time.Second +) + +type workflowAttentionStatusGroup struct { + owner, repo, headSHA string + statuses []*PRStatus +} + +// enrichBatchedWorkflowAttention adds Actions evidence to GraphQL statuses. +// Workflow runs are fetched once per credential scope, target repository, and +// head SHA; job reads are shared within that group. The enrichment is best +// effort so missing Actions permission never discards review or check data. +func (s *Service) enrichBatchedWorkflowAttention( + ctx context.Context, client Client, cacheScope string, statuses map[string]*PRStatus, +) { + groups := groupBatchedWorkflowAttentionStatuses(cacheScope, statuses) + if len(groups) == 0 { + return + } + + baseCtx, cancelBase := derivedFetchContext(ctx) + defer cancelBase() + fetchCtx, cancel := context.WithTimeout(baseCtx, workflowAttentionBatchBudget) + defer cancel() + sem := make(chan struct{}, workflowAttentionBatchConcurrency) + var wg sync.WaitGroup + for _, group := range groups { + group := group + wg.Add(1) + go s.enrichBatchedWorkflowAttentionGroup(fetchCtx, client, cacheScope, group, sem, &wg) + } + wg.Wait() +} + +func groupBatchedWorkflowAttentionStatuses( + cacheScope string, statuses map[string]*PRStatus, +) map[string]*workflowAttentionStatusGroup { + groups := make(map[string]*workflowAttentionStatusGroup) + for _, status := range statuses { + if status == nil || status.PR == nil { + continue + } + if isTerminalPR(status.PR) { + status.WorkflowAttention = workflowAttentionNone(status.PR.HeadSHA) + status.WorkflowAttentionPopulated = true + continue + } + if status.PR.HeadSHA == "" { + status.WorkflowAttention = workflowAttentionUnknown("") + status.WorkflowAttentionPopulated = true + continue + } + key := workflowAttentionBatchKey(cacheScope, status.PR.RepoOwner, status.PR.RepoName, status.PR.HeadSHA) + group := groups[key] + if group == nil { + group = &workflowAttentionStatusGroup{ + owner: status.PR.RepoOwner, repo: status.PR.RepoName, headSHA: status.PR.HeadSHA, + } + groups[key] = group + } + group.statuses = append(group.statuses, status) + } + return groups +} + +func acquireWorkflowAttentionBatchSlot(ctx context.Context, sem chan struct{}) bool { + select { + case sem <- struct{}{}: + return true + case <-ctx.Done(): + return false + } +} + +func markBatchedWorkflowAttentionUnknown(group *workflowAttentionStatusGroup) { + for _, status := range group.statuses { + status.WorkflowAttention = workflowAttentionUnknown(group.headSHA) + status.WorkflowAttentionPopulated = true + } +} + +func (s *Service) enrichBatchedWorkflowAttentionGroup( + ctx context.Context, + client Client, + cacheScope string, + group *workflowAttentionStatusGroup, + sem chan struct{}, + wg *sync.WaitGroup, +) { + defer wg.Done() + if !acquireWorkflowAttentionBatchSlot(ctx, sem) { + markBatchedWorkflowAttentionUnknown(group) + return + } + defer func() { <-sem }() + + key := workflowAttentionBatchKey(cacheScope, group.owner, group.repo, group.headSHA) + value, err, _ := s.syncGroup.Do(key, func() (interface{}, error) { + return client.ListWorkflowRuns(ctx, group.owner, group.repo, group.headSHA) + }) + if err != nil { + if s.logger != nil { + s.logger.Debug("workflow attention read unavailable", + zap.String("owner", group.owner), zap.String("repo", group.repo), zap.Error(err)) + } + markBatchedWorkflowAttentionUnknown(group) + return + } + runs, ok := value.([]WorkflowRun) + if !ok { + markBatchedWorkflowAttentionUnknown(group) + return + } + s.applyBatchedWorkflowAttention(ctx, client, group, runs) +} + +func (s *Service) applyBatchedWorkflowAttention( + ctx context.Context, client Client, group *workflowAttentionStatusGroup, runs []WorkflowRun, +) { + jobs := make(map[workflowJobKey]struct { + value []WorkflowJob + err error + }) + readJobs := func(jobCtx context.Context, runID int64, attempt int) ([]WorkflowJob, error) { + jobKey := workflowJobKey{Owner: group.owner, Repo: group.repo, RunID: runID, Attempt: attempt} + if cached, found := jobs[jobKey]; found { + return cached.value, cached.err + } + value, readErr := client.ListWorkflowRunJobs(jobCtx, group.owner, group.repo, runID, attempt) + jobs[jobKey] = struct { + value []WorkflowJob + err error + }{value: value, err: readErr} + return value, readErr + } + for _, status := range group.statuses { + if status == nil || status.PR == nil { + continue + } + status.WorkflowAttention = classifyWorkflowAttentionWithJobs( + ctx, group.owner, group.repo, status.PR, runs, readJobs, + ) + status.WorkflowAttentionPopulated = true + } +} + +func workflowAttentionBatchKey(cacheScope, owner, repo, headSHA string) string { + return scopedCacheKey(cacheScope, fmt.Sprintf("workflow-attention:%s/%s@%s", strings.ToLower(owner), strings.ToLower(repo), headSHA)) +} + // batchedWatchStatuses is the shared, read-only result of one batched fetch. // // byKey holds every PR the batch resolved, keyed by prStatusCacheKey for @@ -125,7 +278,7 @@ type batchedWatchStatuses struct { // GetPRFeedback / GetPRStatus. The leader's deadline is preserved so // the fetch can't outlive the request budget. func (s *Service) fetchBatchedWatchStatuses( - ctx context.Context, exec GraphQLExecutor, cacheScope string, numbered, searching []*PRWatch, + ctx context.Context, client Client, exec GraphQLExecutor, cacheScope string, numbered, searching []*PRWatch, ) (*batchedWatchStatuses, error) { key := scopedCacheKey(cacheScope, batchedFetchSingleflightKey(numbered, searching)) fetchCtx, cancelFetch := derivedFetchContext(ctx) @@ -146,6 +299,7 @@ func (s *Service) fetchBatchedWatchStatuses( if err := s.fetchBatchedBranchStatuses(fetchCtx, exec, cacheScope, searching, combined, repoErrGen); err != nil { return nil, err } + s.enrichBatchedWorkflowAttention(fetchCtx, client, cacheScope, combined.byKey) return combined, nil }) if err != nil { diff --git a/apps/backend/internal/github/store.go b/apps/backend/internal/github/store.go index d914432dec..f6ed672e77 100644 --- a/apps/backend/internal/github/store.go +++ b/apps/backend/internal/github/store.go @@ -160,6 +160,7 @@ const createTablesSQL = ` closed_by_login TEXT, auto_merge_observed_at DATETIME, source TEXT NOT NULL DEFAULT '', + workflow_attention TEXT NOT NULL DEFAULT '', UNIQUE(task_id, repository_id, pr_number) ); @@ -667,6 +668,9 @@ func (s *Store) initSchemaUpgrades() error { if err := s.addTaskPRSourceColumn(); err != nil { return err } + if err := s.addTaskPRWorkflowAttentionColumn(); err != nil { + return err + } return nil } @@ -730,6 +734,25 @@ func (s *Store) addTaskPRSourceColumn() error { return nil } +// addTaskPRWorkflowAttentionColumn adds the serialized, head-scoped Actions +// observation. Empty is the legacy/unobserved value and is not an assertion +// that no workflow needs attention. +func (s *Store) addTaskPRWorkflowAttentionColumn() error { + cols, err := s.tableColumns("github_task_prs") + if err != nil { + return fmt.Errorf("read github_task_prs columns: %w", err) + } + if _, ok := cols["workflow_attention"]; ok { + return nil + } + if _, err := s.db.Exec(schemaSQLForDriver( + `ALTER TABLE github_task_prs ADD COLUMN workflow_attention TEXT NOT NULL DEFAULT ''`, s.db.DriverName(), + )); err != nil && !dbutil.IsDuplicateColumnError(err) { + return fmt.Errorf("add github_task_prs.workflow_attention: %w", err) + } + return nil +} + // taskPROutcomeColumnDDL lists the five nullable PR-outcome-attribution // columns and their type fragments. Every column is nullable with no // DEFAULT (AC-01): NULL means "never observed" and must never be confused @@ -1641,6 +1664,7 @@ func (s *Store) migratePRTablesForMultiRepo() error { closed_by_login TEXT, auto_merge_observed_at DATETIME, source TEXT NOT NULL DEFAULT '', + workflow_attention TEXT NOT NULL DEFAULT '', UNIQUE(task_id, repository_id, pr_number) )`, // The five outcome-attribution columns and source are selected @@ -1657,7 +1681,7 @@ func (s *Store) migratePRTablesForMultiRepo() error { merge_queue_last_removal_reason, merge_queue_last_removal_before_sha, review_count, pending_review_count, comment_count, additions, deletions, created_at, merged_at, closed_at, last_synced_at, detached_at, updated_at, - is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at, source + is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at, source, workflow_attention ) SELECT id, COALESCE(workspace_id, ''), task_id, COALESCE(repository_id, ''), owner, repo, pr_number, pr_url, pr_title, head_branch, base_branch, COALESCE(head_sha, ''), author_login, state, review_state, checks_state, @@ -1666,7 +1690,7 @@ func (s *Store) migratePRTablesForMultiRepo() error { COALESCE(merge_queue_last_removal_reason, ''), COALESCE(merge_queue_last_removal_before_sha, ''), review_count, pending_review_count, comment_count, additions, deletions, created_at, merged_at, closed_at, last_synced_at, detached_at, updated_at, - is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at, source + is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at, source, workflow_attention FROM github_task_prs`, ) } @@ -1983,6 +2007,7 @@ func (s *Store) CreateTaskPR(ctx context.Context, tp *TaskPR) error { } now := time.Now().UTC() tp.UpdatedAt = now + tp.WorkflowAttentionJSON = marshalWorkflowAttention(tp.WorkflowAttention) return insertTaskPR(ctx, s.db, tp) } @@ -2003,7 +2028,7 @@ const taskPRColumns = `id, workspace_id, task_id, repository_id, owner, repo, pr is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at, head_sha, merge_queue_entry_id, merge_queue_entry_head_sha, merge_queue_last_removal_id, merge_queue_last_removed_at, merge_queue_last_removal_reason, merge_queue_last_removal_before_sha, - source` + source, workflow_attention` // taskPRColumnsQualified is taskPRColumns with each column qualified by the // `gtp` alias, for queries that join github_task_prs against another table. @@ -2016,7 +2041,7 @@ const taskPRColumnsQualified = `gtp.id, gtp.workspace_id, gtp.task_id, gtp.repos gtp.is_draft, gtp.changed_files, gtp.merged_by_login, gtp.closed_by_login, gtp.auto_merge_observed_at, gtp.head_sha, gtp.merge_queue_entry_id, gtp.merge_queue_entry_head_sha, gtp.merge_queue_last_removal_id, gtp.merge_queue_last_removed_at, gtp.merge_queue_last_removal_reason, gtp.merge_queue_last_removal_before_sha, - gtp.source` + gtp.source, gtp.workflow_attention` type taskPRWriter interface { ExecContext(context.Context, string, ...any) (sql.Result, error) @@ -2059,10 +2084,48 @@ func taskPRValues(tp *TaskPR) []any { tp.MergedByLogin, tp.ClosedByLogin, tp.AutoMergeObservedAt, tp.HeadSHA, tp.MergeQueueEntryID, tp.MergeQueueEntryHeadSHA, tp.MergeQueueLastRemovalID, tp.MergeQueueLastRemovedAt, tp.MergeQueueLastRemovalReason, tp.MergeQueueLastRemovalBeforeSHA, - tp.Source, + tp.Source, marshalWorkflowAttention(tp.WorkflowAttention), } } +func marshalWorkflowAttention(attention *WorkflowAttention) string { + if attention == nil { + return "" + } + encoded, err := json.Marshal(attention) + if err != nil { + return "" + } + return string(encoded) +} + +func hydrateTaskPRWorkflowAttention(tp *TaskPR) error { + if tp == nil || strings.TrimSpace(tp.WorkflowAttentionJSON) == "" { + if tp != nil { + tp.WorkflowAttention = nil + } + return nil + } + var attention WorkflowAttention + if err := json.Unmarshal([]byte(tp.WorkflowAttentionJSON), &attention); err != nil { + return fmt.Errorf("decode task PR workflow attention: %w", err) + } + if attention.Runs == nil { + attention.Runs = []WorkflowAttentionRun{} + } + tp.WorkflowAttention = &attention + return nil +} + +func hydrateTaskPRsWorkflowAttention(prs []TaskPR) error { + for i := range prs { + if err := hydrateTaskPRWorkflowAttention(&prs[i]); err != nil { + return err + } + } + return nil +} + // GetTaskPR returns the first PR association for a task. For multi-repo tasks // the result is non-deterministic across repos — use ListTaskPRsByTask instead. func (s *Store) GetTaskPR(ctx context.Context, taskID string) (*TaskPR, error) { @@ -2072,6 +2135,9 @@ func (s *Store) GetTaskPR(ctx context.Context, taskID string) (*TaskPR, error) { if errors.Is(err, sql.ErrNoRows) { return nil, nil } + if err == nil { + err = hydrateTaskPRWorkflowAttention(&tp) + } return &tp, err } @@ -2085,6 +2151,9 @@ func (s *Store) GetTaskPRByID(ctx context.Context, associationID string) (*TaskP if errors.Is(err, sql.ErrNoRows) { return nil, nil } + if err == nil { + err = hydrateTaskPRWorkflowAttention(&tp) + } return &tp, err } @@ -2104,6 +2173,9 @@ func (s *Store) GetTaskPRByRepository(ctx context.Context, taskID, repositoryID if errors.Is(err, sql.ErrNoRows) { return nil, nil } + if err == nil { + err = hydrateTaskPRWorkflowAttention(&tp) + } return &tp, err } @@ -2121,6 +2193,9 @@ func (s *Store) GetTaskPRByRepoAndNumber(ctx context.Context, taskID, repository if errors.Is(err, sql.ErrNoRows) { return nil, nil } + if err == nil { + err = hydrateTaskPRWorkflowAttention(&tp) + } return &tp, err } @@ -2136,6 +2211,9 @@ func (s *Store) GetTaskPRByRepoAndNumberIncludingDetached(ctx context.Context, t if errors.Is(err, sql.ErrNoRows) { return nil, nil } + if err == nil { + err = hydrateTaskPRWorkflowAttention(&tp) + } return &tp, err } @@ -2147,6 +2225,9 @@ func (s *Store) ListTaskPRsByTask(ctx context.Context, taskID string) ([]*TaskPR s.ro.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? AND detached_at IS NULL ORDER BY created_at ASC`), taskID); err != nil { return nil, err } + if err := hydrateTaskPRsWorkflowAttention(prs); err != nil { + return nil, err + } out := make([]*TaskPR, 0, len(prs)) for i := range prs { out = append(out, &prs[i]) @@ -2164,6 +2245,9 @@ func (s *Store) ListTaskPRsByTaskIncludingDetached(ctx context.Context, taskID s s.ro.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? ORDER BY created_at ASC`), taskID); err != nil { return nil, err } + if err := hydrateTaskPRsWorkflowAttention(prs); err != nil { + return nil, err + } out := make([]*TaskPR, 0, len(prs)) for i := range prs { out = append(out, &prs[i]) @@ -2215,11 +2299,16 @@ func (s *Store) RestoreTaskPR(ctx context.Context, taskID, repositoryID string, var outgoing TaskPR err = tx.GetContext(ctx, &outgoing, tx.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), taskID, repositoryID, pr.Number) if err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, err } + if err == nil { + if err := hydrateTaskPRWorkflowAttention(&outgoing); err != nil { + return nil, err + } + } isDraft, changedFiles, mergedByLogin, closedByLogin, autoMergeObservedAt := resolveTaskPROutcomeFields(&outgoing, status) @@ -2228,6 +2317,7 @@ func (s *Store) RestoreTaskPR(ctx context.Context, taskID, repositoryID string, if pr.HeadSHA != "" { headSHA = pr.HeadSHA } + workflowAttention := resolveTaskPRWorkflowAttention(&outgoing, status, headSHA) if _, err := tx.ExecContext(ctx, tx.Rebind( `UPDATE github_task_prs SET owner = ?, repo = ?, pr_url = ?, pr_title = ?, @@ -2236,13 +2326,14 @@ func (s *Store) RestoreTaskPR(ctx context.Context, taskID, repositoryID string, merge_queue_last_removal_id = ?, merge_queue_last_removed_at = ?, merge_queue_last_removal_reason = ?, merge_queue_last_removal_before_sha = ?, additions = ?, deletions = ?, merged_at = ?, closed_at = ?, detached_at = NULL, updated_at = ?, is_draft = ?, changed_files = ?, merged_by_login = ?, closed_by_login = ?, - auto_merge_observed_at = COALESCE(auto_merge_observed_at, ?) + auto_merge_observed_at = COALESCE(auto_merge_observed_at, ?), workflow_attention = ? WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), pr.RepoOwner, pr.RepoName, pr.HTMLURL, pr.Title, pr.HeadBranch, pr.BaseBranch, headSHA, pr.AuthorLogin, pr.State, pr.MergeableState, queue.state, queue.position, queue.entryID, queue.entryHeadSHA, queue.estimate, queue.lastRemovalID, queue.lastRemovedAt, queue.lastRemovalReason, queue.lastRemovalBeforeSHA, pr.Additions, pr.Deletions, pr.MergedAt, pr.ClosedAt, time.Now().UTC(), isDraft, changedFiles, mergedByLogin, closedByLogin, autoMergeObservedAt, + marshalWorkflowAttention(workflowAttention), taskID, repositoryID, pr.Number); err != nil { return nil, err } @@ -2271,6 +2362,9 @@ func (s *Store) ListTaskPRsByTaskIDs(ctx context.Context, taskIDs []string) (map if err := s.ro.SelectContext(ctx, &prs, query, args...); err != nil { return nil, err } + if err := hydrateTaskPRsWorkflowAttention(prs); err != nil { + return nil, err + } return groupTaskPRsByTask(prs), nil } @@ -2283,7 +2377,10 @@ func (s *Store) ListTaskPRsByWorkspaceID(ctx context.Context, workspaceID string s.ro.Rebind(`SELECT `+taskPRColumnsQualified+` FROM github_task_prs gtp INNER JOIN tasks t ON gtp.task_id = t.id WHERE t.workspace_id = ? AND gtp.detached_at IS NULL - ORDER BY gtp.created_at ASC`), workspaceID); err != nil { + ORDER BY gtp.created_at ASC`), workspaceID); err != nil { + return nil, err + } + if err := hydrateTaskPRsWorkflowAttention(prs); err != nil { return nil, err } return groupTaskPRsByTask(prs), nil @@ -2333,7 +2430,10 @@ func (s *Store) ListTaskPRsByPRNumber( INNER JOIN tasks t ON gtp.task_id = t.id WHERE t.workspace_id = ? AND gtp.owner = ? AND gtp.repo = ? AND gtp.pr_number = ? AND gtp.detached_at IS NULL - ORDER BY gtp.created_at ASC`), workspaceID, owner, repo, prNumber); err != nil { + ORDER BY gtp.created_at ASC`), workspaceID, owner, repo, prNumber); err != nil { + return nil, err + } + if err := hydrateTaskPRsWorkflowAttention(prs); err != nil { return nil, err } out := make([]*TaskPR, 0, len(prs)) @@ -2408,6 +2508,8 @@ func (s *Store) ReplaceTaskPR(ctx context.Context, tp *TaskPR, status *PRStatus) } else if tp.HeadSHA == "" && outgoing.ID != "" { tp.HeadSHA = outgoing.HeadSHA } + tp.WorkflowAttention = resolveTaskPRWorkflowAttention(outgoing, status, tp.HeadSHA) + tp.WorkflowAttentionJSON = marshalWorkflowAttention(tp.WorkflowAttention) if tp.RepositoryID != "" { if _, err := tx.ExecContext(ctx, tx.Rebind( @@ -2458,6 +2560,9 @@ func replaceTaskPROutgoingRow(ctx context.Context, tx *sqlx.Tx, tp *TaskPR) (*Ta if err != nil { return nil, err } + if err := hydrateTaskPRWorkflowAttention(&outgoing); err != nil { + return nil, err + } return &outgoing, nil } @@ -2490,7 +2595,7 @@ func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error { additions = ?, deletions = ?, pr_title = ?, base_branch = ?, merged_at = ?, closed_at = ?, last_synced_at = ?, updated_at = ?, is_draft = ?, changed_files = ?, merged_by_login = ?, closed_by_login = ?, - auto_merge_observed_at = COALESCE(auto_merge_observed_at, ?) + auto_merge_observed_at = COALESCE(auto_merge_observed_at, ?), workflow_attention = ? WHERE id = ?`), tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.HeadSHA, tp.MergeQueueState, tp.MergeQueuePosition, tp.MergeQueueEntryID, tp.MergeQueueEntryHeadSHA, tp.MergeQueueEstimatedTimeToMergeSeconds, tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount, @@ -2498,7 +2603,7 @@ func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error { tp.Additions, tp.Deletions, tp.PRTitle, tp.BaseBranch, tp.MergedAt, tp.ClosedAt, tp.LastSyncedAt, tp.UpdatedAt, tp.IsDraft, tp.ChangedFiles, tp.MergedByLogin, tp.ClosedByLogin, - tp.AutoMergeObservedAt, tp.ID); err != nil { + tp.AutoMergeObservedAt, marshalWorkflowAttention(tp.WorkflowAttention), tp.ID); err != nil { return err } if _, err := tx.ExecContext(ctx, tx.Rebind(` diff --git a/apps/backend/internal/github/store_workflow_attention_test.go b/apps/backend/internal/github/store_workflow_attention_test.go new file mode 100644 index 0000000000..b2cbafcaa6 --- /dev/null +++ b/apps/backend/internal/github/store_workflow_attention_test.go @@ -0,0 +1,97 @@ +package github + +import ( + "context" + "strings" + "testing" + "time" +) + +func TestTaskPRWorkflowAttentionRoundTripAndHeadScopedRecovery(t *testing.T) { + store := newTestStore(t) + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Second) + attention := &WorkflowAttention{ + State: WorkflowAttentionApprovalRequired, + HeadSHA: "old-head", + ObservedAt: now, + Runs: []WorkflowAttentionRun{{RunID: 7, RunAttempt: 1, WorkflowID: 9, Name: "Run tests", URL: "https://github.com/acme/widget/actions/runs/7", Reason: workflowAttentionApprovalRequiredReason}}, + } + tp := &TaskPR{ + TaskID: "workflow-attention-task", + WorkspaceID: "workflow-attention-workspace", + Owner: "acme", + Repo: "widget", + PRNumber: 143, + PRURL: "https://github.com/acme/widget/pull/143", + PRTitle: "workflow attention", + HeadBranch: "feature", + BaseBranch: "main", + HeadSHA: "old-head", + State: "open", + WorkflowAttention: attention, + CreatedAt: now, + } + if err := store.CreateTaskPR(ctx, tp); err != nil { + t.Fatalf("CreateTaskPR: %v", err) + } + got, err := store.GetTaskPRByID(ctx, tp.ID) + if err != nil { + t.Fatalf("GetTaskPRByID: %v", err) + } + if got.WorkflowAttention == nil || got.WorkflowAttention.State != WorkflowAttentionApprovalRequired { + t.Fatalf("round-trip workflow attention = %#v, want approval_required", got.WorkflowAttention) + } + + unknown := &PRStatus{ + PR: &PR{HeadSHA: "old-head"}, + WorkflowAttention: workflowAttentionUnknown("old-head"), + WorkflowAttentionPopulated: true, + } + got.WorkflowAttention = resolveTaskPRWorkflowAttention(got, unknown, "old-head") + if err := store.UpdateTaskPR(ctx, got); err != nil { + t.Fatalf("UpdateTaskPR (unavailable same head): %v", err) + } + got, err = store.GetTaskPRByID(ctx, tp.ID) + if err != nil { + t.Fatalf("GetTaskPRByID after unavailable read: %v", err) + } + if got.WorkflowAttention == nil || got.WorkflowAttention.State != WorkflowAttentionApprovalRequired || !got.WorkflowAttention.Stale { + t.Fatalf("same-head unavailable attention = %#v, want stale approval", got.WorkflowAttention) + } + + newHeadStatus := &PRStatus{ + PR: &PR{HeadSHA: "new-head"}, + WorkflowAttention: workflowAttentionUnknown("new-head"), + WorkflowAttentionPopulated: true, + } + got.HeadSHA = "new-head" + got.WorkflowAttention = resolveTaskPRWorkflowAttention(got, newHeadStatus, "new-head") + if err := store.UpdateTaskPR(ctx, got); err != nil { + t.Fatalf("UpdateTaskPR (new head): %v", err) + } + got, err = store.GetTaskPRByID(ctx, tp.ID) + if err != nil { + t.Fatalf("GetTaskPRByID after head change: %v", err) + } + if got.WorkflowAttention == nil || got.WorkflowAttention.State != WorkflowAttentionUnknown || got.WorkflowAttention.HeadSHA != "new-head" || HasActiveWorkflowAttention(got) { + t.Fatalf("new-head attention = %#v, want unknown without active old claim", got.WorkflowAttention) + } +} + +func TestTaskPRWorkflowAttentionColumnIsMigratedAndProjected(t *testing.T) { + store := newTestStore(t) + columns, err := store.tableColumns("github_task_prs") + if err != nil { + t.Fatalf("tableColumns: %v", err) + } + if _, ok := columns["workflow_attention"]; !ok { + t.Fatal("github_task_prs is missing workflow_attention") + } + if err := store.initSchema(false); err != nil { + t.Fatalf("replay schema: %v", err) + } + if !strings.Contains(taskPRColumns, "workflow_attention") || !strings.Contains(taskPRColumnsQualified, "gtp.workflow_attention") { + t.Fatalf("workflow_attention is missing from task PR projections") + } +} diff --git a/apps/backend/internal/github/workflow_attention.go b/apps/backend/internal/github/workflow_attention.go new file mode 100644 index 0000000000..1382f73609 --- /dev/null +++ b/apps/backend/internal/github/workflow_attention.go @@ -0,0 +1,657 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/url" + "sort" + "strings" + "time" +) + +const ( + workflowConclusionActionRequired = "action_required" + workflowEventPullRequest = "pull_request" + workflowStatusCompleted = "completed" +) + +type workflowRunKey struct { + Owner string + Repo string + HeadSHA string +} + +type workflowJobKey struct { + Owner string + Repo string + RunID int64 + Attempt int +} + +// ghWorkflowRun and its nested values are shared by the gh CLI and PAT +// clients because both consume the same Actions REST response shape. +type ghWorkflowRun struct { + ID int64 `json:"id"` + RunAttempt int `json:"run_attempt"` + WorkflowID int64 `json:"workflow_id"` + Name string `json:"name"` + Event string `json:"event"` + Status string `json:"status"` + Conclusion *string `json:"conclusion"` + HeadBranch string `json:"head_branch"` + HeadSHA string `json:"head_sha"` + HTMLURL string `json:"html_url"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + HeadRepository *ghWorkflowRepository `json:"head_repository"` + PullRequests []ghWorkflowPRAssociation `json:"pull_requests"` +} + +type ghWorkflowRepository struct { + ID int64 `json:"id"` + FullName string `json:"full_name"` + Name string `json:"name"` + URL string `json:"url"` + Owner ghWorkflowRepoOwner `json:"owner"` +} + +type ghWorkflowRepoOwner struct { + Login string `json:"login"` +} + +type ghWorkflowPRAssociation struct { + Number int `json:"number"` + Head struct { + Ref string `json:"ref"` + SHA string `json:"sha"` + Repo *ghWorkflowRepository `json:"repo"` + } `json:"head"` +} + +type ghWorkflowJob struct { + ID int64 `json:"id"` + Name string `json:"name"` + Status string `json:"status"` + Conclusion *string `json:"conclusion"` +} + +func convertRawWorkflowRun(raw ghWorkflowRun) WorkflowRun { + run := WorkflowRun{ + ID: raw.ID, + RunAttempt: raw.RunAttempt, + WorkflowID: raw.WorkflowID, + Name: raw.Name, + Event: raw.Event, + Status: raw.Status, + HeadSHA: raw.HeadSHA, + HeadBranch: raw.HeadBranch, + HTMLURL: raw.HTMLURL, + CreatedAt: raw.CreatedAt, + UpdatedAt: raw.UpdatedAt, + } + if raw.Conclusion != nil { + run.Conclusion = *raw.Conclusion + } + if raw.HeadRepository != nil { + repository := workflowRepositoryIdentityFromRaw(raw.HeadRepository) + run.HeadRepoID = repository.ID + run.HeadRepoOwner = repository.Owner + run.HeadRepoName = repository.Name + run.HeadRepoURL = repository.URL + } + for _, association := range raw.PullRequests { + converted := WorkflowRunPullRequest{ + Number: association.Number, + HeadSHA: association.Head.SHA, + HeadBranch: association.Head.Ref, + } + if association.Head.Repo != nil { + repository := workflowRepositoryIdentityFromRaw(association.Head.Repo) + converted.HeadRepoID = repository.ID + converted.HeadRepoOwner = repository.Owner + converted.HeadRepoName = repository.Name + converted.HeadRepoURL = repository.URL + } + run.PullRequests = append(run.PullRequests, converted) + } + return run +} + +func convertRawWorkflowJobs(raw []ghWorkflowJob) []WorkflowJob { + jobs := make([]WorkflowJob, 0, len(raw)) + for _, job := range raw { + converted := WorkflowJob{ID: job.ID, Name: job.Name, Status: job.Status} + if job.Conclusion != nil { + converted.Conclusion = *job.Conclusion + } + jobs = append(jobs, converted) + } + return jobs +} + +func decodeGHWorkflowRuns(out string) ([]ghWorkflowRun, error) { + return decodeJSONStream[ghWorkflowRun](out) +} + +func decodeGHWorkflowJobs(out string) ([]ghWorkflowJob, error) { + return decodeJSONStream[ghWorkflowJob](out) +} + +func decodeJSONStream[T any](out string) ([]T, error) { + if strings.TrimSpace(out) == "" { + return nil, nil + } + decoder := json.NewDecoder(strings.NewReader(out)) + var values []T + for { + var value T + if err := decoder.Decode(&value); err != nil { + if err == io.EOF { + return values, nil + } + return nil, err + } + values = append(values, value) + } +} + +// workflowAttentionUnknown creates an observation that cannot make a +// positive claim. Callers may replace it with a same-head stale observation +// when a later provider read is unavailable. +func workflowAttentionUnknown(headSHA string) *WorkflowAttention { + return &WorkflowAttention{ + State: WorkflowAttentionUnknown, + HeadSHA: headSHA, + ObservedAt: time.Now().UTC(), + Stale: false, + Runs: []WorkflowAttentionRun{}, + } +} + +// collectWorkflowAttention reads and classifies Actions evidence for one PR. +// A failed Actions read is returned alongside an unknown observation so +// callers can preserve an older same-head positive observation without +// treating a permission failure as authoritative absence. +func collectWorkflowAttention( + ctx context.Context, client Client, owner, repo string, pr *PR, +) (*WorkflowAttention, error) { + if pr == nil { + return workflowAttentionUnknown(""), nil + } + if isTerminalPR(pr) { + return workflowAttentionNone(pr.HeadSHA), nil + } + if pr.HeadSHA == "" { + return workflowAttentionUnknown(""), nil + } + + runs, err := client.ListWorkflowRuns(ctx, owner, repo, pr.HeadSHA) + if err != nil { + return workflowAttentionUnknown(pr.HeadSHA), err + } + return classifyWorkflowAttention(ctx, client, owner, repo, pr, runs), nil +} + +func classifyWorkflowAttention( + ctx context.Context, client Client, owner, repo string, pr *PR, runs []WorkflowRun, +) *WorkflowAttention { + return classifyWorkflowAttentionWithJobs(ctx, owner, repo, pr, runs, + func(ctx context.Context, runID int64, attempt int) ([]WorkflowJob, error) { + return client.ListWorkflowRunJobs(ctx, owner, repo, runID, attempt) + }, + ) +} + +type workflowAttentionJobReader func(context.Context, int64, int) ([]WorkflowJob, error) + +func classifyWorkflowAttentionWithJobs( + ctx context.Context, owner, repo string, pr *PR, runs []WorkflowRun, readJobs workflowAttentionJobReader, +) *WorkflowAttention { + if pr == nil { + return workflowAttentionUnknown("") + } + if isTerminalPR(pr) { + return workflowAttentionNone(pr.HeadSHA) + } + if pr.HeadSHA == "" { + return workflowAttentionUnknown("") + } + attention := &WorkflowAttention{ + State: WorkflowAttentionNone, + HeadSHA: pr.HeadSHA, + ObservedAt: time.Now().UTC(), + Runs: []WorkflowAttentionRun{}, + } + + selected := selectCurrentWorkflowRuns(runs, pr) + for _, run := range selected { + if !strings.EqualFold(run.Conclusion, workflowConclusionActionRequired) { + continue + } + attempt := run.RunAttempt + if attempt <= 0 { + attempt = 1 + } + jobs, jobsErr := readJobs(ctx, run.ID, attempt) + reason := workflowAttentionActionRequiredReason + if jobsErr == nil && isForkWorkflowRun(run, owner, repo) && + strings.EqualFold(run.Event, workflowEventPullRequest) && + strings.EqualFold(run.Status, workflowStatusCompleted) && len(jobs) == 0 { + reason = workflowAttentionApprovalRequiredReason + } + attention.Runs = append(attention.Runs, WorkflowAttentionRun{ + RunID: run.ID, + RunAttempt: attempt, + WorkflowID: run.WorkflowID, + Name: run.Name, + URL: run.HTMLURL, + Reason: reason, + }) + if reason == workflowAttentionActionRequiredReason { + attention.State = WorkflowAttentionActionRequired + } + } + if attention.State != WorkflowAttentionActionRequired && len(attention.Runs) > 0 { + attention.State = WorkflowAttentionApprovalRequired + } + sort.SliceStable(attention.Runs, func(i, j int) bool { + return workflowAttentionRunLess(attention.Runs[i], attention.Runs[j]) + }) + return attention +} + +const ( + workflowAttentionApprovalRequiredReason = "approval_required" + workflowAttentionActionRequiredReason = "action_required" +) + +func workflowAttentionNone(headSHA string) *WorkflowAttention { + return &WorkflowAttention{ + State: WorkflowAttentionNone, + HeadSHA: headSHA, + ObservedAt: time.Now().UTC(), + Runs: []WorkflowAttentionRun{}, + } +} + +func isTerminalPR(pr *PR) bool { + if pr == nil { + return false + } + return strings.EqualFold(pr.State, "closed") || strings.EqualFold(pr.State, "merged") || pr.MergedAt != nil +} + +func selectCurrentWorkflowRuns(runs []WorkflowRun, pr *PR) []WorkflowRun { + latest := make(map[string]WorkflowRun) + for _, run := range runs { + if !workflowRunMatchesPR(run, pr) { + continue + } + key := workflowRunGroupKey(run) + current, ok := latest[key] + if !ok || workflowRunNewer(run, current) { + latest[key] = run + } + } + out := make([]WorkflowRun, 0, len(latest)) + for _, run := range latest { + out = append(out, run) + } + sort.Slice(out, func(i, j int) bool { + return workflowRunLess(out[i], out[j]) + }) + return out +} + +func workflowRunMatchesPR(run WorkflowRun, pr *PR) bool { + if pr == nil || run.HeadSHA == "" || run.HeadSHA != pr.HeadSHA { + return false + } + if len(run.PullRequests) > 0 { + return workflowRunHasPRAssociation(run, pr) + } + + // Fork pull_request runs can have an empty pull_requests association. The + // source repository, branch, event, and SHA together are the conservative + // fallback identity in that response shape. + return workflowRunMatchesUnassociatedPR(run, pr) +} + +func workflowRunHasPRAssociation(run WorkflowRun, pr *PR) bool { + for _, association := range run.PullRequests { + if workflowAssociationMatchesPR(association, run, pr) { + return true + } + } + return false +} + +func workflowAssociationMatchesPR(association WorkflowRunPullRequest, run WorkflowRun, pr *PR) bool { + if association.Number != pr.Number { + return false + } + if association.HeadSHA != "" && association.HeadSHA != pr.HeadSHA { + return false + } + if association.HeadBranch != "" && association.HeadBranch != pr.HeadBranch { + return false + } + associationRepository := workflowRepositoryIdentityFromAssociation(association) + if associationRepository.empty() { + return run.HeadRepoID == 0 && run.HeadRepoOwner == "" && run.HeadRepoName == "" && run.HeadRepoURL == "" + } + runRepository := workflowRepositoryIdentityFromRun(run) + merged, ok := mergeWorkflowRepositoryIdentities(associationRepository, runRepository) + return ok && workflowRepositoryIdentityMatchesPR(merged, pr) +} + +func workflowRunMatchesUnassociatedPR(run WorkflowRun, pr *PR) bool { + return strings.EqualFold(run.Event, workflowEventPullRequest) && + run.HeadBranch != "" && run.HeadBranch == pr.HeadBranch && + workflowRepositoryIdentityMatchesPR(workflowRepositoryIdentityFromRun(run), pr) +} + +type workflowRepositoryIdentity struct { + ID int64 + Owner string + Name string + URL string +} + +func workflowRepositoryIdentityFromRaw(repository *ghWorkflowRepository) workflowRepositoryIdentity { + if repository == nil { + return workflowRepositoryIdentity{} + } + identity := workflowRepositoryIdentity{ + ID: repository.ID, + Owner: repository.Owner.Login, + Name: repository.Name, + URL: repository.URL, + } + if owner, name := workflowRepositoryPath(repository.FullName); identity.Owner == "" || identity.Name == "" { + if identity.Owner == "" { + identity.Owner = owner + } + if identity.Name == "" { + identity.Name = name + } + } + if owner, name := workflowRepositoryPath(identity.URL); identity.Owner == "" || identity.Name == "" { + if identity.Owner == "" { + identity.Owner = owner + } + if identity.Name == "" { + identity.Name = name + } + } + return identity +} + +func workflowRepositoryIdentityFromAssociation(association WorkflowRunPullRequest) workflowRepositoryIdentity { + identity := workflowRepositoryIdentity{ + ID: association.HeadRepoID, + Owner: association.HeadRepoOwner, + Name: association.HeadRepoName, + URL: association.HeadRepoURL, + } + if owner, name := workflowRepositoryPath(identity.URL); identity.Owner == "" || identity.Name == "" { + if identity.Owner == "" { + identity.Owner = owner + } + if identity.Name == "" { + identity.Name = name + } + } + return identity +} + +func workflowRepositoryIdentityFromRun(run WorkflowRun) workflowRepositoryIdentity { + identity := workflowRepositoryIdentity{ + ID: run.HeadRepoID, + Owner: run.HeadRepoOwner, + Name: run.HeadRepoName, + URL: run.HeadRepoURL, + } + if owner, name := workflowRepositoryPath(identity.URL); identity.Owner == "" || identity.Name == "" { + if identity.Owner == "" { + identity.Owner = owner + } + if identity.Name == "" { + identity.Name = name + } + } + return identity +} + +func (identity workflowRepositoryIdentity) empty() bool { + return identity.ID == 0 && identity.Owner == "" && identity.Name == "" && identity.URL == "" +} + +func workflowRepositoryPath(value string) (string, string) { + value = strings.TrimSpace(value) + if value == "" { + return "", "" + } + if parsed, err := url.Parse(value); err == nil && parsed.Path != "" { + parts := strings.Split(strings.Trim(parsed.Path, "/"), "/") + for index, part := range parts { + if strings.EqualFold(part, "repos") && len(parts) > index+2 { + return parts[index+1], parts[index+2] + } + } + if parsed.Host != "" && len(parts) >= 2 { + return parts[len(parts)-2], parts[len(parts)-1] + } + } + parts := strings.SplitN(strings.Trim(value, "/"), "/", 2) + if len(parts) == 2 { + return parts[0], parts[1] + } + return "", "" +} + +func mergeWorkflowRepositoryIdentities( + association workflowRepositoryIdentity, + run workflowRepositoryIdentity, +) (workflowRepositoryIdentity, bool) { + if workflowRepositoryIdentitiesConflict(association, run) { + return workflowRepositoryIdentity{}, false + } + merged := association + if merged.ID == 0 { + merged.ID = run.ID + } + if merged.Owner == "" { + merged.Owner = run.Owner + } + if merged.Name == "" { + merged.Name = run.Name + } + if merged.URL == "" { + merged.URL = run.URL + } + return merged, true +} + +func workflowRepositoryIdentitiesConflict(a, b workflowRepositoryIdentity) bool { + return (a.ID != 0 && b.ID != 0 && a.ID != b.ID) || + (a.Owner != "" && b.Owner != "" && !strings.EqualFold(a.Owner, b.Owner)) || + (a.Name != "" && b.Name != "" && !strings.EqualFold(a.Name, b.Name)) +} + +func workflowRepositoryIdentityMatchesPR(identity workflowRepositoryIdentity, pr *PR) bool { + if pr == nil { + return false + } + return !workflowRepositoryIdentityConflictsWithPR(identity, pr) && + workflowRepositoryIdentityHasPositivePRMatch(identity, pr) +} + +func workflowRepositoryIdentityConflictsWithPR(identity workflowRepositoryIdentity, pr *PR) bool { + if identity.ID != 0 && pr.HeadRepoID != 0 && identity.ID != pr.HeadRepoID { + return true + } + if identity.Owner != "" && pr.HeadRepoOwner != "" && !strings.EqualFold(identity.Owner, pr.HeadRepoOwner) { + return true + } + if identity.Name != "" && pr.HeadRepoName != "" && !strings.EqualFold(identity.Name, pr.HeadRepoName) { + return true + } + return false +} + +func workflowRepositoryIdentityHasPositivePRMatch(identity workflowRepositoryIdentity, pr *PR) bool { + return (identity.ID != 0 && pr.HeadRepoID != 0) || + (identity.Owner != "" && identity.Name != "" && pr.HeadRepoOwner != "" && pr.HeadRepoName != "") +} + +func workflowRepoIdentityMatches(ownerA, repoA, ownerB, repoB string) bool { + if ownerA == "" || repoA == "" || ownerB == "" || repoB == "" { + return false + } + return strings.EqualFold(ownerA, ownerB) && strings.EqualFold(repoA, repoB) +} + +func isForkWorkflowRun(run WorkflowRun, owner, repo string) bool { + return !workflowRepoIdentityMatches(run.HeadRepoOwner, run.HeadRepoName, owner, repo) && + run.HeadRepoOwner != "" && run.HeadRepoName != "" +} + +func workflowRunGroupKey(run WorkflowRun) string { + workflow := fmt.Sprintf("id:%d", run.WorkflowID) + if run.WorkflowID == 0 { + workflow = "name:" + strings.ToLower(run.Name) + } + repository := workflowRepositoryIdentityFromRun(run) + source := strings.ToLower(repository.Owner) + "/" + strings.ToLower(repository.Name) + if repository.Owner == "" && repository.Name == "" && repository.ID != 0 { + source = fmt.Sprintf("id:%d", repository.ID) + } + return fmt.Sprintf("%s|event:%s|branch:%s|source:%s", + workflow, strings.ToLower(run.Event), run.HeadBranch, + source) +} + +func workflowRunNewer(candidate, current WorkflowRun) bool { + // UpdatedAt can move forward when an older execution is cancelled or + // otherwise receives a late provider-side update. Compare distinct + // executions by creation time and identity first so that update activity + // cannot make an older execution hide a newer result. + if candidate.ID != current.ID { + if !candidate.CreatedAt.Equal(current.CreatedAt) { + return candidate.CreatedAt.After(current.CreatedAt) + } + return candidate.ID > current.ID + } + if candidate.RunAttempt != current.RunAttempt { + return candidate.RunAttempt > current.RunAttempt + } + if !candidate.UpdatedAt.Equal(current.UpdatedAt) { + return candidate.UpdatedAt.After(current.UpdatedAt) + } + return candidate.CreatedAt.After(current.CreatedAt) +} + +func workflowRunLess(a, b WorkflowRun) bool { + if a.WorkflowID != b.WorkflowID { + return a.WorkflowID < b.WorkflowID + } + if a.Name != b.Name { + return a.Name < b.Name + } + if a.ID != b.ID { + return a.ID < b.ID + } + return a.RunAttempt < b.RunAttempt +} + +func workflowAttentionRunLess(a, b WorkflowAttentionRun) bool { + if a.WorkflowID != b.WorkflowID { + return a.WorkflowID < b.WorkflowID + } + if a.Name != b.Name { + return a.Name < b.Name + } + if a.RunID != b.RunID { + return a.RunID < b.RunID + } + return a.RunAttempt < b.RunAttempt +} + +// HasActiveWorkflowAttention reports whether a stored observation blocks +// merge for the TaskPR's currently observed head. A stale positive remains a +// blocker until a fresh complete observation replaces it. +func HasActiveWorkflowAttention(pr *TaskPR) bool { + if pr == nil || pr.WorkflowAttention == nil || pr.WorkflowAttention.HeadSHA == "" || + pr.WorkflowAttention.HeadSHA != pr.HeadSHA { + return false + } + return pr.WorkflowAttention.State == WorkflowAttentionApprovalRequired || + pr.WorkflowAttention.State == WorkflowAttentionActionRequired +} + +func cloneWorkflowAttention(attention *WorkflowAttention) *WorkflowAttention { + if attention == nil { + return nil + } + clone := *attention + clone.Runs = append([]WorkflowAttentionRun{}, attention.Runs...) + return &clone +} + +func workflowAttentionSemanticEqual(left, right *WorkflowAttention) bool { + if left == nil || right == nil { + return left == right + } + if left.State != right.State || left.HeadSHA != right.HeadSHA || left.Stale != right.Stale || len(left.Runs) != len(right.Runs) { + return false + } + for i := range left.Runs { + if left.Runs[i] != right.Runs[i] { + return false + } + } + return true +} + +// resolveTaskPRWorkflowAttention applies the observation-preservation rules +// at the storage boundary. A missing observation from a legacy or partial +// caller preserves a same-head value, an unavailable fresh read marks the +// same-head value stale, and a head change immediately discards old positive +// evidence. +func resolveTaskPRWorkflowAttention(previous *TaskPR, status *PRStatus, nextHeadSHA string) *WorkflowAttention { + previousAttention := (*WorkflowAttention)(nil) + previousSameHead := previous != nil && previous.HeadSHA != "" && previous.HeadSHA == nextHeadSHA && + (previous.WorkflowAttention == nil || previous.WorkflowAttention.HeadSHA == nextHeadSHA) + if previousSameHead { + previousAttention = previous.WorkflowAttention + } + + if status == nil || !status.WorkflowAttentionPopulated { + return cloneWorkflowAttention(previousAttention) + } + + incoming := cloneWorkflowAttention(status.WorkflowAttention) + if incoming == nil { + incoming = workflowAttentionUnknown(nextHeadSHA) + } + if incoming.HeadSHA == "" { + incoming.HeadSHA = nextHeadSHA + } + if incoming.HeadSHA != nextHeadSHA { + return workflowAttentionUnknown(nextHeadSHA) + } + if incoming.State == WorkflowAttentionUnknown { + if previousAttention != nil { + preserved := cloneWorkflowAttention(previousAttention) + preserved.Stale = true + return preserved + } + incoming.Stale = true + return incoming + } + incoming.Stale = false + return incoming +} diff --git a/apps/backend/internal/github/workflow_attention_test.go b/apps/backend/internal/github/workflow_attention_test.go new file mode 100644 index 0000000000..f9586e4a0b --- /dev/null +++ b/apps/backend/internal/github/workflow_attention_test.go @@ -0,0 +1,329 @@ +package github + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" +) + +type workflowAttentionTestClient struct { + *MockClient + runsErr error + jobsErr error +} + +func (c *workflowAttentionTestClient) ListWorkflowRuns(ctx context.Context, owner, repo, headSHA string) ([]WorkflowRun, error) { + if c.runsErr != nil { + return nil, c.runsErr + } + return c.MockClient.ListWorkflowRuns(ctx, owner, repo, headSHA) +} + +func (c *workflowAttentionTestClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string, runID int64, attempt int) ([]WorkflowJob, error) { + if c.jobsErr != nil { + return nil, c.jobsErr + } + return c.MockClient.ListWorkflowRunJobs(ctx, owner, repo, runID, attempt) +} + +func TestWorkflowAttention_JoblessForkApproval(t *testing.T) { + client := &workflowAttentionTestClient{MockClient: NewMockClient()} + client.AddPR(&PR{ + RepoOwner: "acme", + RepoName: "widget", + Number: 143, + State: "open", + HeadSHA: "head-sha", + HeadBranch: "feature/approval", + HeadRepoOwner: "contributor", + HeadRepoName: "widget-fork", + }) + client.ReplaceWorkflowRuns("acme", "widget", "head-sha", []WorkflowRun{ + { + ID: 34494307522, + RunAttempt: 1, + WorkflowID: 77, + Name: "Run tests", + Event: "pull_request", + Status: "completed", + Conclusion: "action_required", + HeadSHA: "head-sha", + HeadBranch: "feature/approval", + HeadRepoOwner: "contributor", + HeadRepoName: "widget-fork", + CreatedAt: time.Date(2026, 9, 10, 12, 0, 0, 0, time.UTC), + PullRequests: nil, + HTMLURL: "https://github.com/acme/widget/actions/runs/34494307522", + }, + }) + client.ReplaceWorkflowRunJobs("acme", "widget", 34494307522, 1, nil) + + status, err := client.GetPRStatus(context.Background(), "acme", "widget", 143) + if err != nil { + t.Fatalf("GetPRStatus() error = %v", err) + } + if status.WorkflowAttention == nil { + t.Fatal("WorkflowAttention = nil, want approval observation") + } + if got := status.WorkflowAttention.State; got != WorkflowAttentionApprovalRequired { + t.Fatalf("WorkflowAttention.State = %q, want %q", got, WorkflowAttentionApprovalRequired) + } + if status.ChecksTotal != 0 || status.ChecksPassing != 0 { + t.Fatalf("check counts = (%d, %d), want (0, 0)", status.ChecksTotal, status.ChecksPassing) + } + if len(status.WorkflowAttention.Runs) != 1 { + t.Fatalf("workflow attention runs = %d, want 1", len(status.WorkflowAttention.Runs)) + } + if got := status.WorkflowAttention.Runs[0].Name; got != "Run tests" { + t.Fatalf("workflow attention run name = %q, want %q", got, "Run tests") + } +} + +func TestWorkflowAttention_LatestRunAndAssociationFiltering(t *testing.T) { + client := &workflowAttentionTestClient{MockClient: NewMockClient()} + pr := &PR{ + Number: 7, + State: "open", + HeadSHA: "head-sha", + HeadBranch: "feature/approval", + HeadRepoOwner: "contributor", + HeadRepoName: "widget-fork", + RepoOwner: "acme", + RepoName: "widget", + } + client.AddPR(pr) + old := time.Date(2026, 9, 10, 12, 0, 0, 0, time.UTC) + newer := old.Add(time.Hour) + client.ReplaceWorkflowRuns("acme", "widget", pr.HeadSHA, []WorkflowRun{ + {ID: 100, RunAttempt: 1, WorkflowID: 9, Name: "CI", Event: "pull_request", Status: "completed", Conclusion: "action_required", HeadSHA: pr.HeadSHA, HeadBranch: pr.HeadBranch, HeadRepoOwner: "contributor", HeadRepoName: "widget-fork", CreatedAt: old, UpdatedAt: old}, + {ID: 101, RunAttempt: 1, WorkflowID: 9, Name: "CI", Event: "pull_request", Status: "completed", Conclusion: "success", HeadSHA: pr.HeadSHA, HeadBranch: pr.HeadBranch, HeadRepoOwner: "contributor", HeadRepoName: "widget-fork", CreatedAt: newer, UpdatedAt: newer}, + {ID: 102, RunAttempt: 1, WorkflowID: 10, Name: "Other PR", Event: "pull_request", Status: "completed", Conclusion: "action_required", HeadSHA: pr.HeadSHA, HeadBranch: pr.HeadBranch, HeadRepoOwner: "contributor", HeadRepoName: "widget-fork", PullRequests: []WorkflowRunPullRequest{{Number: 99, HeadSHA: pr.HeadSHA, HeadBranch: pr.HeadBranch, HeadRepoOwner: "contributor", HeadRepoName: "widget-fork"}}, CreatedAt: newer, UpdatedAt: newer}, + }) + + attention, err := collectWorkflowAttention(context.Background(), client, "acme", "widget", pr) + if err != nil { + t.Fatalf("collectWorkflowAttention() error = %v", err) + } + if attention.State != WorkflowAttentionNone || len(attention.Runs) != 0 { + t.Fatalf("attention = %#v, want authoritative none after newer success and association filtering", attention) + } +} + +func TestWorkflowAttention_RESTAssociationUsesRepositoryURLIdentity(t *testing.T) { + runs, err := decodeGHWorkflowRuns(`{"id":7,"run_attempt":1,"workflow_id":9,"name":"Run tests","event":"pull_request","status":"completed","conclusion":"action_required","head_sha":"head-sha","head_branch":"feature/approval","head_repository":{"id":123,"full_name":"contributor/widget-fork","name":"widget-fork","owner":{"login":"contributor"}},"pull_requests":[{"number":143,"head":{"ref":"feature/approval","sha":"head-sha","repo":{"id":123,"name":"widget-fork","url":"https://api.github.com/repos/contributor/widget-fork"}}}]}`) + if err != nil { + t.Fatalf("decodeGHWorkflowRuns() error = %v", err) + } + if len(runs) != 1 { + t.Fatalf("decoded runs = %d, want 1", len(runs)) + } + run := convertRawWorkflowRun(runs[0]) + + matchingPR := &PR{ + Number: 143, + HeadSHA: "head-sha", + HeadBranch: "feature/approval", + HeadRepoID: 123, + HeadRepoOwner: "contributor", + HeadRepoName: "widget-fork", + } + if !workflowRunMatchesPR(run, matchingPR) { + t.Fatalf("workflowRunMatchesPR() = false for the REST association shape: %#v", run) + } + + mismatchingPR := *matchingPR + mismatchingPR.HeadRepoID = 456 + if workflowRunMatchesPR(run, &mismatchingPR) { + t.Fatal("workflowRunMatchesPR() = true for a mismatching head repository") + } +} + +func TestWorkflowAttention_NewAssociatedSuccessSupersedesOlderUnassociatedApproval(t *testing.T) { + runs, err := decodeGHWorkflowRuns(`{"id":100,"run_attempt":1,"workflow_id":9,"name":"CI","event":"pull_request","status":"completed","conclusion":"action_required","head_sha":"head-sha","head_branch":"feature/approval","head_repository":{"id":123,"full_name":"contributor/widget-fork","name":"widget-fork","owner":{"login":"contributor"}},"created_at":"2026-09-10T12:00:00Z","updated_at":"2026-09-10T12:00:00Z","pull_requests":[]} +{"id":101,"run_attempt":1,"workflow_id":9,"name":"CI","event":"pull_request","status":"completed","conclusion":"success","head_sha":"head-sha","head_branch":"feature/approval","head_repository":{"id":123,"full_name":"contributor/widget-fork","name":"widget-fork","owner":{"login":"contributor"}},"created_at":"2026-09-10T13:00:00Z","updated_at":"2026-09-10T13:00:00Z","pull_requests":[{"number":143,"head":{"ref":"feature/approval","sha":"head-sha","repo":{"id":123,"name":"widget-fork","url":"https://api.github.com/repos/contributor/widget-fork"}}}]}`) + if err != nil { + t.Fatalf("decodeGHWorkflowRuns() error = %v", err) + } + converted := make([]WorkflowRun, 0, len(runs)) + for _, raw := range runs { + converted = append(converted, convertRawWorkflowRun(raw)) + } + pr := &PR{ + Number: 143, + State: "open", + HeadSHA: "head-sha", + HeadBranch: "feature/approval", + HeadRepoID: 123, + HeadRepoOwner: "contributor", + HeadRepoName: "widget-fork", + RepoOwner: "acme", + RepoName: "widget", + } + + selected := selectCurrentWorkflowRuns(converted, pr) + if len(selected) != 1 || selected[0].ID != 101 { + t.Fatalf("selected workflow runs = %#v, want only newer associated success", selected) + } +} + +func TestWorkflowAttention_NewExecutionWinsOverLateUpdate(t *testing.T) { + pr := &PR{ + Number: 7, + State: "open", + HeadSHA: "head-sha", + HeadBranch: "feature/approval", + HeadRepoOwner: "contributor", + HeadRepoName: "widget-fork", + RepoOwner: "acme", + RepoName: "widget", + } + created := time.Date(2026, 9, 10, 12, 0, 0, 0, time.UTC) + selected := selectCurrentWorkflowRuns([]WorkflowRun{ + { + ID: 100, + RunAttempt: 1, + WorkflowID: 9, + Name: "CI", + Event: "pull_request", + Status: "completed", + Conclusion: "action_required", + HeadSHA: pr.HeadSHA, + HeadBranch: pr.HeadBranch, + HeadRepoOwner: pr.HeadRepoOwner, + HeadRepoName: pr.HeadRepoName, + CreatedAt: created, + UpdatedAt: created.Add(2 * time.Hour), + }, + { + ID: 101, + RunAttempt: 1, + WorkflowID: 9, + Name: "CI", + Event: "pull_request", + Status: "completed", + Conclusion: "success", + HeadSHA: pr.HeadSHA, + HeadBranch: pr.HeadBranch, + HeadRepoOwner: pr.HeadRepoOwner, + HeadRepoName: pr.HeadRepoName, + CreatedAt: created.Add(time.Hour), + UpdatedAt: created.Add(time.Hour), + }, + }, pr) + if len(selected) != 1 || selected[0].ID != 101 { + t.Fatalf("selected workflow runs = %#v, want only newer execution 101", selected) + } +} + +func TestWorkflowAttention_ActionRequiredWithJobsIsGeneric(t *testing.T) { + client := &workflowAttentionTestClient{MockClient: NewMockClient()} + pr := &PR{ + Number: 1, State: "open", HeadSHA: "head-sha", HeadBranch: "feature", + HeadRepoOwner: "contributor", HeadRepoName: "widget-fork", RepoOwner: "acme", RepoName: "widget", + } + client.AddPR(pr) + client.ReplaceWorkflowRuns("acme", "widget", pr.HeadSHA, []WorkflowRun{{ + ID: 44, RunAttempt: 2, WorkflowID: 12, Name: "CI", Event: "pull_request", Status: "completed", Conclusion: "action_required", + HeadSHA: pr.HeadSHA, HeadBranch: pr.HeadBranch, HeadRepoOwner: "contributor", HeadRepoName: "widget-fork", + }}) + client.ReplaceWorkflowRunJobs("acme", "widget", 44, 2, []WorkflowJob{{ID: 55, Name: "test", Status: "completed", Conclusion: "success"}}) + + attention, err := collectWorkflowAttention(context.Background(), client, "acme", "widget", pr) + if err != nil { + t.Fatalf("collectWorkflowAttention() error = %v", err) + } + if attention.State != WorkflowAttentionActionRequired || len(attention.Runs) != 1 || attention.Runs[0].Reason != workflowAttentionActionRequiredReason { + t.Fatalf("attention = %#v, want generic action_required", attention) + } +} + +func TestWorkflowAttention_ClassifierIgnoresTerminalAndHeadlessPRs(t *testing.T) { + runs := []WorkflowRun{{ + ID: 44, RunAttempt: 1, WorkflowID: 12, Name: "CI", Event: "pull_request", Status: "completed", Conclusion: "action_required", + HeadSHA: "head-sha", HeadBranch: "feature", HeadRepoOwner: "contributor", HeadRepoName: "widget-fork", + }} + readJobs := func(context.Context, int64, int) ([]WorkflowJob, error) { + t.Fatal("readJobs called for a PR that cannot have active workflow attention") + return nil, nil + } + + terminal := classifyWorkflowAttentionWithJobs(context.Background(), "acme", "widget", &PR{ + State: "merged", HeadSHA: "head-sha", + }, runs, readJobs) + if terminal.State != WorkflowAttentionNone || terminal.HeadSHA != "head-sha" { + t.Fatalf("terminal attention = %#v, want authoritative none", terminal) + } + + headless := classifyWorkflowAttentionWithJobs(context.Background(), "acme", "widget", &PR{ + State: "open", + }, runs, readJobs) + if headless.State != WorkflowAttentionUnknown || headless.HeadSHA != "" { + t.Fatalf("headless attention = %#v, want unknown", headless) + } +} + +func TestWorkflowAttention_DeniedReadIsUnknown(t *testing.T) { + client := &workflowAttentionTestClient{MockClient: NewMockClient(), runsErr: errors.New("forbidden")} + pr := &PR{State: "open", HeadSHA: "head-sha", RepoOwner: "acme", RepoName: "widget"} + attention, err := collectWorkflowAttention(context.Background(), client, "acme", "widget", pr) + if !errors.Is(err, client.runsErr) { + t.Fatalf("collectWorkflowAttention() error = %v, want forbidden error", err) + } + if attention.State != WorkflowAttentionUnknown || attention.HeadSHA != pr.HeadSHA { + t.Fatalf("attention = %#v, want unknown same-head observation", attention) + } +} + +func TestWorkflowAttention_UnknownPreservesSameHeadAndClearsOnHeadChange(t *testing.T) { + previous := &TaskPR{ + HeadSHA: "old-head", + WorkflowAttention: &WorkflowAttention{ + State: WorkflowAttentionApprovalRequired, + HeadSHA: "old-head", + ObservedAt: time.Now().UTC().Add(-time.Minute), + Runs: []WorkflowAttentionRun{{RunID: 1, Name: "CI", Reason: workflowAttentionApprovalRequiredReason}}, + }, + } + unknown := &PRStatus{ + PR: &PR{HeadSHA: "old-head"}, + WorkflowAttention: workflowAttentionUnknown("old-head"), + WorkflowAttentionPopulated: true, + } + got := resolveTaskPRWorkflowAttention(previous, unknown, "old-head") + if got == nil || got.State != WorkflowAttentionApprovalRequired || !got.Stale { + t.Fatalf("same-head unknown result = %#v, want stale preserved approval", got) + } + if !got.ObservedAt.Equal(previous.WorkflowAttention.ObservedAt) { + t.Fatalf("same-head unavailable observed_at = %v, want last successful observation %v", got.ObservedAt, previous.WorkflowAttention.ObservedAt) + } + + newHead := resolveTaskPRWorkflowAttention(previous, &PRStatus{ + PR: &PR{HeadSHA: "new-head"}, + WorkflowAttention: workflowAttentionUnknown("new-head"), + WorkflowAttentionPopulated: true, + }, "new-head") + if newHead == nil || newHead.State != WorkflowAttentionUnknown || newHead.HeadSHA != "new-head" || HasActiveWorkflowAttention(&TaskPR{HeadSHA: "new-head", WorkflowAttention: newHead}) { + t.Fatalf("new-head result = %#v, want unknown without old active claim", newHead) + } +} + +func TestWorkflowAttentionJSONKeepsRunArraysNonNil(t *testing.T) { + encoded, err := json.Marshal(workflowAttentionNone("head-sha")) + if err != nil { + t.Fatalf("json.Marshal: %v", err) + } + if got := string(encoded); !strings.Contains(got, `"runs":[]`) { + t.Fatalf("workflow attention JSON = %s, want an empty run array", got) + } + + tp := &TaskPR{WorkflowAttentionJSON: `{"state":"unknown","head_sha":"head-sha"}`} + if err := hydrateTaskPRWorkflowAttention(tp); err != nil { + t.Fatalf("hydrateTaskPRWorkflowAttention: %v", err) + } + if tp.WorkflowAttention == nil || tp.WorkflowAttention.Runs == nil { + t.Fatalf("hydrated runs = %#v, want non-nil empty array", tp.WorkflowAttention.Runs) + } +} diff --git a/apps/backend/internal/orchestrator/event_handlers_github_ci_automation.go b/apps/backend/internal/orchestrator/event_handlers_github_ci_automation.go index ae4f94cb6e..849169a268 100644 --- a/apps/backend/internal/orchestrator/event_handlers_github_ci_automation.go +++ b/apps/backend/internal/orchestrator/event_handlers_github_ci_automation.go @@ -834,6 +834,9 @@ func ciAutomationReadyToMerge(pr *github.TaskPR) bool { if pr == nil || pr.State != githubPRStateOpen { return false } + if github.HasActiveWorkflowAttention(pr) { + return false + } if pr.ChecksState != ciAutomationCheckSuccess || pr.MergeableState != "clean" { return false } diff --git a/apps/backend/internal/orchestrator/event_handlers_github_ci_automation_test.go b/apps/backend/internal/orchestrator/event_handlers_github_ci_automation_test.go index f820544a16..65c5cafd89 100644 --- a/apps/backend/internal/orchestrator/event_handlers_github_ci_automation_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_github_ci_automation_test.go @@ -156,6 +156,13 @@ func TestCIAutomationReadyToMerge(t *testing.T) { {name: "pending review", mutate: func(pr *github.TaskPR) { pr.PendingReviewCount = 1 }, want: false}, {name: "not enough approvals", mutate: func(pr *github.TaskPR) { pr.ReviewCount = 0 }, want: false}, {name: "unresolved threads", mutate: func(pr *github.TaskPR) { pr.UnresolvedReviewThreads = 1 }, want: false}, + {name: "workflow attention", mutate: func(pr *github.TaskPR) { + pr.WorkflowAttention = &github.WorkflowAttention{ + State: github.WorkflowAttentionApprovalRequired, + HeadSHA: "head-sha", + } + pr.HeadSHA = "head-sha" + }, want: false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/apps/web/components/github/pr-ci-popover.tsx b/apps/web/components/github/pr-ci-popover.tsx index d6f647e65f..cf6d89153a 100644 --- a/apps/web/components/github/pr-ci-popover.tsx +++ b/apps/web/components/github/pr-ci-popover.tsx @@ -19,6 +19,7 @@ import type { CheckRun, TaskPR } from "@/lib/types/github"; import { PRCIAutomationControls } from "./pr-ci-automation-controls"; import { PRMergeButton } from "./pr-merge-button"; import { PRMergeabilityRow } from "./pr-mergeability-row"; +import { PRWorkflowAttentionNotice } from "./pr-workflow-attention-notice"; import { ChangeRequestCIPopoverFrame, ChangeRequestChecksSection, @@ -289,6 +290,7 @@ export function PRCIPopover({ return ( + {authLost ? ( ) : ( diff --git a/apps/web/components/github/pr-detail-panel.tsx b/apps/web/components/github/pr-detail-panel.tsx index 3dcafa9cc2..b59c32b157 100644 --- a/apps/web/components/github/pr-detail-panel.tsx +++ b/apps/web/components/github/pr-detail-panel.tsx @@ -20,10 +20,11 @@ import { useCommentsStore, isPRFeedbackComment } from "@/lib/state/slices/commen import type { PRFeedbackComment } from "@/lib/state/slices/comments"; import { useToast } from "@/components/toast-provider"; import { submitPRReview } from "@/lib/api/domains/github-pr-api"; -import type { TaskPR, PRFeedback } from "@/lib/types/github"; +import type { TaskPR, PRFeedback, MergeableState } from "@/lib/types/github"; import { PRMergeButton } from "./pr-merge-button"; import { PRMergeabilityNotice, buildConflictResolutionMessage } from "./pr-mergeability-notice"; import { hasActiveMergeQueueEntry, PRMergeQueueStatus } from "./pr-merge-queue-status"; +import { PRWorkflowAttentionNotice } from "./pr-workflow-attention-notice"; import { usePRScopedReviewRequest } from "./use-pr-scoped-review-request"; // --- Dockview panel wrapper --- @@ -387,6 +388,47 @@ function useConflictQueued(sessionId: string, prNumber: number): boolean { ); } +function PRDetailNotice({ + displayPR, + attention, + mergeableState, + mergeable, + isDraft, + prState, + baseBranch, + onResolveConflicts, + resolveDisabled, +}: { + displayPR: TaskPR; + attention?: PRFeedback["workflow_attention"]; + mergeableState: MergeableState | undefined; + mergeable: boolean; + isDraft: boolean; + prState: TaskPR["state"]; + baseBranch: string; + onResolveConflicts: () => void; + resolveDisabled: boolean; +}) { + return ( +
+ + {hasActiveMergeQueueEntry(displayPR) ? ( + + ) : ( + + )} +
+ ); +} + export function PRDetailContent({ taskPR, sessionId }: { taskPR: TaskPR; sessionId: string }) { const { t } = useTranslation(); const workspaceId = useAppStore((state) => state.workspaces.activeId); @@ -458,19 +500,17 @@ export function PRDetailContent({ taskPR, sessionId }: { taskPR: TaskPR; session } notice={ - hasActiveMergeQueueEntry(displayPR) ? ( - - ) : ( - - ) + } /> ); diff --git a/apps/web/components/github/pr-status-chip.tsx b/apps/web/components/github/pr-status-chip.tsx index 5ec630e1dc..989ebbda7b 100644 --- a/apps/web/components/github/pr-status-chip.tsx +++ b/apps/web/components/github/pr-status-chip.tsx @@ -47,6 +47,7 @@ import { import type { AutomationFlags } from "@/components/github/pr-status-automation-badges"; import type { TaskPR } from "@/lib/types/github"; import type { TFunction } from "i18next"; +import { getTaskPRWorkflowAttention } from "./pr-workflow-attention"; const HOVER_OPEN_DELAY_MS = 150; const HOVER_CLOSE_DELAY_MS = 150; @@ -63,6 +64,7 @@ type ChipStatus = | "waiting" | "queued" | "in_progress" + | "attention" | "neutral"; type TriggerRef = { current: HTMLButtonElement | null }; type SingleChipProps = { @@ -96,6 +98,7 @@ function chipStatus(pr: TaskPR): ChipStatus { // getPRStatusColor + PRStatusIcon (dirty = red, behind = amber). if (pr.mergeable_state === "dirty") return "conflict"; if (pr.mergeable_state === "behind") return "behind"; + if (getTaskPRWorkflowAttention(pr)) return "attention"; // Pending checks / pending review must beat checks_state === "success" so a // PR with all checks green but reviewers still outstanding renders as // in-progress, not passed. Without this order, the chip flips to green the @@ -121,6 +124,7 @@ const CHIP_STATUS_RANK: Record = { blocked: 4, behind: 3, queued: 2.5, + attention: 2.25, draft: 0.5, in_progress: 2, waiting: 1.5, @@ -486,6 +490,14 @@ function ChipStatusGlyph({ status }: { status: ChipStatus }) { aria-hidden="true" /> ); + case "attention": + return ( +