fix(github): harden auto-merge and surface task automation (#3128)

This commit is contained in:
Carlos Florêncio
2026-08-28 22:23:45 +00:00
committed by GitHub
parent 6929536ddc
commit ace26dfd99
91 changed files with 5290 additions and 316 deletions
@@ -26,7 +26,18 @@ func (r *githubTaskStatusSummaryPRReader) ListTaskStatusSummaryPullRequests(
if err != nil {
return nil, err
}
automationByTask, err := r.gh.ListTaskPRAutomationOptionsByTaskIDs(ctx, taskIDs)
if err != nil {
return nil, err
}
for taskID, prs := range prsByTask {
optionsByKey := make(map[string]*github.TaskPRAutomationOptions, len(automationByTask[taskID]))
for _, options := range automationByTask[taskID] {
if options == nil {
continue
}
optionsByKey[fmt.Sprintf("%s#%d", options.RepositoryID, options.PRNumber)] = options
}
for _, pr := range prs {
if pr == nil {
continue
@@ -39,6 +50,7 @@ func (r *githubTaskStatusSummaryPRReader) ListTaskStatusSummaryPullRequests(
if pr.RequiredReviews != nil {
requiredReviews = *pr.RequiredReviews
}
options := optionsByKey[key]
result[taskID] = append(result[taskID], statussummary.PullRequestInput{
Key: key,
State: pr.State,
@@ -53,6 +65,8 @@ func (r *githubTaskStatusSummaryPRReader) ListTaskStatusSummaryPullRequests(
RequiredReviews: requiredReviews,
ChecksTotal: pr.ChecksTotal,
ChecksPassing: pr.ChecksPassing,
AutoFixEnabled: options != nil && options.AutoFixEnabled,
AutoMergeEnabled: options != nil && options.AutoMergeEnabled,
})
}
}
@@ -114,3 +114,38 @@ func TestGitHubTaskStatusSummaryPRReaderPreservesMergeQueueState(t *testing.T) {
t.Fatalf("MergeQueueState = %q, want %q", inputs[0].MergeQueueState, queuePR.MergeQueueState)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10
func TestGitHubTaskStatusSummaryPRReaderIncludesPerPRAutomationFlags(t *testing.T) {
ctx := context.Background()
store := newStatusSummaryTestStore(t)
queuePR := &github.TaskPR{
TaskID: "task-automation-summary", RepositoryID: "repo-automation-summary", PRNumber: 42,
PRURL: "https://example.test/42", State: "open", CreatedAt: time.Now().UTC(),
}
if err := store.CreateTaskPR(ctx, queuePR); err != nil {
t.Fatalf("CreateTaskPR: %v", err)
}
autoFix := true
autoMerge := true
if _, err := store.UpdateTaskPRAutomationOptions(ctx, queuePR.TaskID, queuePR.RepositoryID, queuePR.PRNumber,
github.TaskPRAutomationOptionsPatch{AutoFixEnabled: &autoFix, AutoMergeEnabled: &autoMerge}, false,
); err != nil {
t.Fatalf("UpdateTaskPRAutomationOptions: %v", err)
}
reader := &githubTaskStatusSummaryPRReader{
gh: github.NewService(nil, "", nil, store, nil, nil),
}
result, err := reader.ListTaskStatusSummaryPullRequests(ctx, []string{queuePR.TaskID})
if err != nil {
t.Fatalf("ListTaskStatusSummaryPullRequests: %v", err)
}
inputs := result[queuePR.TaskID]
if len(inputs) != 1 {
t.Fatalf("summary inputs = %+v, want one input", inputs)
}
if !inputs[0].AutoFixEnabled || !inputs[0].AutoMergeEnabled {
t.Fatalf("automation flags = %+v, want both enabled", inputs[0])
}
}
+35 -4
View File
@@ -20,12 +20,43 @@ const (
MergeOutcomeMerged MergeOutcome = "merged"
MergeOutcomeQueued MergeOutcome = "queued"
mergeStatusFailed = "failed"
mergePollInterval = time.Second
)
// MergePRRequest defines the optional merge method and the pull-request head
// that GitHub must still expose when it accepts the merge.
type MergePRRequest struct {
MergeMethod string
ExpectedHeadSHA string
}
type mergeAsyncResponse struct {
Status string `json:"status"`
UUID string `json:"uuid"`
Message string `json:"message"`
Status string `json:"status"`
Details mergeAsyncResponseDetails `json:"details"`
}
type mergeAsyncResponseDetails struct {
UUID string `json:"uuid"`
Message string `json:"message"`
ExpectedHeadSHA string `json:"expected_head_sha"`
}
func waitForMergePoll(ctx context.Context, delay time.Duration) error {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func newMergeFailureError(details mergeAsyncResponseDetails) error {
if details.ExpectedHeadSHA != "" {
return fmt.Errorf("GitHub rejected merge for expected head %s: %s", details.ExpectedHeadSHA, details.Message)
}
return fmt.Errorf("GitHub rejected merge: %s", details.Message)
}
func normalizeMergeOutcome(status string) (MergeOutcome, error) {
@@ -120,7 +151,7 @@ type Client interface {
RequestReviewers(ctx context.Context, owner, repo string, number int, reviewers []string) error
// MergePR merges a pull request immediately or queues it according to GitHub policy.
MergePR(ctx context.Context, owner, repo string, number int, mergeMethod string) (MergeOutcome, error)
MergePR(ctx context.Context, owner, repo string, number int, request MergePRRequest) (MergeOutcome, error)
// ListRepoBranches lists branches for a repository.
ListRepoBranches(ctx context.Context, owner, repo string) ([]RepoBranch, error)
@@ -86,6 +86,7 @@ func (c *Controller) RegisterHTTPRoutes(router *gin.Engine) {
api.DELETE("/tasks/:taskId/issue", c.httpUnlinkTaskIssue)
api.GET("/tasks/:taskId/ci-options", c.httpGetTaskCIOptions)
api.PATCH("/tasks/:taskId/ci-options", c.httpPatchTaskCIOptions)
api.POST("/tasks/:taskId/ci-automation/retry-merge", c.httpRetryTaskCIAutoMerge)
api.GET("/prs/:owner/:repo/:number", c.httpGetPRFeedback)
api.GET("/prs/:owner/:repo/:number/info", c.httpGetPRInfo)
@@ -407,6 +408,48 @@ func (c *Controller) httpPatchTaskCIOptions(ctx *gin.Context) {
ctx.JSON(http.StatusOK, resp)
}
type retryTaskCIAutoMergeRequest struct {
RepositoryID string `json:"repository_id"`
PRNumber int `json:"pr_number"`
}
func (c *Controller) httpRetryTaskCIAutoMerge(ctx *gin.Context) {
var request retryTaskCIAutoMergeRequest
if err := ctx.ShouldBindJSON(&request); err != nil || strings.TrimSpace(request.RepositoryID) == "" || request.PRNumber <= 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "repository_id and pr_number are required"})
return
}
pr, err := c.service.RetryTaskCIAutoMerge(
ctx.Request.Context(), ctx.Param("taskId"), strings.TrimSpace(request.RepositoryID), request.PRNumber,
)
if err != nil {
if errors.Is(err, ErrTaskCIMergeRetryNotAllowed) {
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
c.writeTaskCIOptionsError(ctx, err, "retry merge", "failed to retry automatic merge")
return
}
var publishErr error
if c.service == nil || c.service.eventBus == nil {
publishErr = errors.New("event bus unavailable")
} else {
event := bus.NewEvent(events.GitHubTaskPRUpdated, "github", pr)
publishErr = c.service.eventBus.Publish(ctx.Request.Context(), events.GitHubTaskPRUpdated, event)
}
if publishErr != nil {
if clearErr := c.service.ClearTaskCIMergeRetryAuthorization(
ctx.Request.Context(), pr.TaskID, pr.RepositoryID, pr.PRNumber,
); clearErr != nil {
c.logger.Debug("clear automatic merge retry authorization failed",
zap.String("task_id", pr.TaskID), zap.Error(clearErr))
}
c.writeTaskCIOptionsError(ctx, publishErr, "publish automatic merge retry", "failed to queue automatic merge retry")
return
}
ctx.JSON(http.StatusAccepted, gin.H{"accepted": true})
}
func (c *Controller) writeTaskCIOptionsError(ctx *gin.Context, err error, operation, message string) {
if errors.Is(err, ErrTaskNotFound) ||
errors.Is(err, repoerrors.ErrWorkspaceNotFound) ||
+157 -2
View File
@@ -132,9 +132,9 @@ func (s *stubClient) RequestReviewers(ctx context.Context, owner, repo string, n
}
return nil
}
func (s *stubClient) MergePR(ctx context.Context, owner, repo string, number int, mergeMethod string) (MergeOutcome, error) {
func (s *stubClient) MergePR(ctx context.Context, owner, repo string, number int, request MergePRRequest) (MergeOutcome, error) {
if s.mergePRFn != nil {
return s.mergePRFn(ctx, owner, repo, number, mergeMethod)
return s.mergePRFn(ctx, owner, repo, number, request.MergeMethod)
}
return MergeOutcomeMerged, nil
}
@@ -1250,6 +1250,161 @@ func TestHttpTaskCIOptions_DefaultAndPatch(t *testing.T) {
}
}
func TestHttpRetryMergeAcceptsLinkedFailedAttemptAndPublishesEvaluation(t *testing.T) {
svc, store := setupWatchServiceTest(t)
eventBus := &mockEventBus{}
svc.eventBus = eventBus
router := gin.New()
useControllerTestWorkspace(router)
NewController(svc, newControllerTestLogger()).RegisterHTTPRoutes(router)
ctx := context.Background()
pr := &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "acme", Repo: "widget", PRNumber: 42,
State: "open", CreatedAt: time.Now().UTC(),
}
if err := store.CreateTaskPR(ctx, pr); err != nil {
t.Fatalf("seed task PR: %v", err)
}
if err := store.RecordTaskCIMergeAttempt(ctx, TaskCIMergeAttempt{
TaskID: pr.TaskID, RepositoryID: pr.RepositoryID, PRNumber: pr.PRNumber,
Signature: "ready-v1", AttemptedHeadSHA: "head-v1",
}); err != nil {
t.Fatalf("reserve attempt: %v", err)
}
if err := store.RecordTaskCIMergeAttemptResult(
ctx, pr.TaskID, pr.RepositoryID, pr.PRNumber,
"ready-v1", TaskCIMergeResultFailed, "merge PR: provider unavailable",
); err != nil {
t.Fatalf("record failure: %v", err)
}
body := bytes.NewBufferString(`{"repository_id":"repo-1","pr_number":42}`)
req := httptest.NewRequest(http.MethodPost, "/api/v1/github/tasks/task-1/ci-automation/retry-merge", body)
req.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
if response.Code != http.StatusAccepted {
t.Fatalf("status = %d, want 202: %s", response.Code, response.Body.String())
}
state, err := store.GetTaskCIPRState(ctx, pr.TaskID, pr.RepositoryID, pr.PRNumber)
if err != nil {
t.Fatalf("get state: %v", err)
}
if state == nil || !state.MergeRetryPending {
t.Fatalf("retry authorization not persisted: %+v", state)
}
if eventBus.publishedCount() != 1 {
t.Fatalf("published events = %d, want 1", eventBus.publishedCount())
}
event := eventBus.events[0]
if event.Type != "github.task_pr.updated" {
t.Fatalf("event type = %q, want github.task_pr.updated", event.Type)
}
published, ok := event.Data.(*TaskPR)
if !ok || published.RepositoryID != pr.RepositoryID || published.PRNumber != pr.PRNumber {
t.Fatalf("published PR = %#v, want exact linked PR", event.Data)
}
}
func TestHttpRetryMergeClearsAuthorizationWhenPublishFails(t *testing.T) {
svc, store := setupWatchServiceTest(t)
svc.eventBus = &mockEventBus{err: errors.New("publish unavailable")}
router := gin.New()
useControllerTestWorkspace(router)
NewController(svc, newControllerTestLogger()).RegisterHTTPRoutes(router)
ctx := context.Background()
pr := &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "acme", Repo: "widget", PRNumber: 42,
State: "open", CreatedAt: time.Now().UTC(),
}
if err := store.CreateTaskPR(ctx, pr); err != nil {
t.Fatalf("seed task PR: %v", err)
}
if err := store.RecordTaskCIMergeAttempt(ctx, TaskCIMergeAttempt{
TaskID: pr.TaskID, RepositoryID: pr.RepositoryID, PRNumber: pr.PRNumber,
Signature: "ready-v1", AttemptedHeadSHA: "head-v1",
}); err != nil {
t.Fatalf("reserve attempt: %v", err)
}
if err := store.RecordTaskCIMergeAttemptResult(
ctx, pr.TaskID, pr.RepositoryID, pr.PRNumber,
"ready-v1", TaskCIMergeResultFailed, "merge PR: provider unavailable",
); err != nil {
t.Fatalf("record failure: %v", err)
}
req := httptest.NewRequest(
http.MethodPost,
"/api/v1/github/tasks/task-1/ci-automation/retry-merge",
bytes.NewBufferString(`{"repository_id":"repo-1","pr_number":42}`),
)
req.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
if response.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500: %s", response.Code, response.Body.String())
}
state, err := store.GetTaskCIPRState(ctx, pr.TaskID, pr.RepositoryID, pr.PRNumber)
if err != nil {
t.Fatalf("get state: %v", err)
}
if state == nil || state.MergeRetryPending {
t.Fatalf("retry authorization remained pending after publish failure: %+v", state)
}
}
func TestHttpRetryMergeRejectsUnlinkedAndDuplicateRequests(t *testing.T) {
svc, store := setupWatchServiceTest(t)
svc.eventBus = &mockEventBus{}
router := gin.New()
useControllerTestWorkspace(router)
NewController(svc, newControllerTestLogger()).RegisterHTTPRoutes(router)
ctx := context.Background()
pr := &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "acme", Repo: "widget", PRNumber: 42,
State: "open", CreatedAt: time.Now().UTC(),
}
if err := store.CreateTaskPR(ctx, pr); err != nil {
t.Fatalf("seed task PR: %v", err)
}
if err := store.RecordTaskCIMergeAttempt(ctx, TaskCIMergeAttempt{
TaskID: pr.TaskID, RepositoryID: pr.RepositoryID, PRNumber: pr.PRNumber,
Signature: "ready-v1", AttemptedHeadSHA: "head-v1",
}); err != nil {
t.Fatalf("reserve attempt: %v", err)
}
if err := store.RecordTaskCIMergeAttemptResult(
ctx, pr.TaskID, pr.RepositoryID, pr.PRNumber,
"ready-v1", TaskCIMergeResultFailed, "merge PR: provider unavailable",
); err != nil {
t.Fatalf("record failure: %v", err)
}
request := func(body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/github/tasks/task-1/ci-automation/retry-merge", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
return response
}
unlinked := request(`{"repository_id":"repo-1","pr_number":99}`)
if unlinked.Code != http.StatusBadRequest {
t.Fatalf("unlinked status = %d, want 400: %s", unlinked.Code, unlinked.Body.String())
}
first := request(`{"repository_id":"repo-1","pr_number":42}`)
if first.Code != http.StatusAccepted {
t.Fatalf("first status = %d, want 202: %s", first.Code, first.Body.String())
}
duplicate := request(`{"repository_id":"repo-1","pr_number":42}`)
if duplicate.Code != http.StatusConflict {
t.Fatalf("duplicate status = %d, want 409: %s", duplicate.Code, duplicate.Body.String())
}
}
// TestHttpPatchTaskCIOptions_TargetsOnePRWithoutAffectingSibling covers AC6:
// a PATCH naming one linked PR's repository_id/pr_number sets the switch for
// that PR only; a second linked PR's row is unchanged.
+53 -21
View File
@@ -32,7 +32,8 @@ const ghAccessibleReposPathFmt = "/user/repos?affiliation=%s&sort=pushed&per_pag
// GHClient implements Client using the gh CLI.
type GHClient struct {
rateTracker *RateTracker
rateTracker *RateTracker
mergePollWait func(context.Context, time.Duration) error
}
// NewGHClient creates a new gh CLI-based client.
@@ -919,55 +920,86 @@ func (c *GHClient) RequestReviewers(ctx context.Context, owner, repo string, num
return nil
}
func (c *GHClient) MergePR(ctx context.Context, owner, repo string, number int, mergeMethod string) (MergeOutcome, error) {
func (c *GHClient) MergePR(ctx context.Context, owner, repo string, number int, request MergePRRequest) (MergeOutcome, error) {
endpoint := fmt.Sprintf("repos/%s/%s/pulls/%d/merge-async", owner, repo, number)
args := []string{"api", endpoint, "-X", "PUT", "-f", "merge_action=default"}
if mergeMethod != "" {
args = append(args, "-f", "merge_method="+mergeMethod)
if request.MergeMethod != "" {
args = append(args, "-f", "merge_method="+request.MergeMethod)
}
if request.ExpectedHeadSHA != "" {
args = append(args, "-f", "sha="+request.ExpectedHeadSHA)
}
out, err := c.run(ctx, args...)
conflictBody := false
response, err := decodeInitialMergeAsyncResponse(endpoint, number, out, err)
if err != nil {
return "", err
}
response, err = c.pollMergeAsyncResponse(ctx, endpoint, number, response)
if err != nil {
return "", err
}
if response.Status == mergeStatusFailed {
return "", newMergeFailureError(response.Details)
}
return normalizeMergeOutcome(response.Status)
}
func decodeInitialMergeAsyncResponse(endpoint string, number int, out string, runErr error) (mergeAsyncResponse, error) {
conflictBody := false
if runErr != nil {
// Surface status-based errors as GitHubAPIError so httpMergePR can
// translate merge rejections for gh CLI users, matching the PAT path.
if code, ok := ghMergeStatusCode(err); ok {
if code, ok := ghMergeStatusCode(runErr); ok {
if code != http.StatusConflict {
return "", &GitHubAPIError{StatusCode: code, Endpoint: endpoint, Body: err.Error()}
return mergeAsyncResponse{}, &GitHubAPIError{StatusCode: code, Endpoint: endpoint, Body: runErr.Error()}
}
out = err.Error()
out = runErr.Error()
conflictBody = true
} else {
return "", fmt.Errorf("merge PR #%d: %w", number, err)
return mergeAsyncResponse{}, fmt.Errorf("merge PR #%d: %w", number, runErr)
}
}
var response mergeAsyncResponse
jsonBody := out
if start := strings.Index(jsonBody, "{"); start >= 0 {
if end := strings.LastIndex(jsonBody, "}"); end >= start {
jsonBody = jsonBody[start : end+1]
}
} else if conflictBody {
return "", &GitHubAPIError{StatusCode: http.StatusConflict, Endpoint: endpoint, Body: out}
return mergeAsyncResponse{}, &GitHubAPIError{StatusCode: http.StatusConflict, Endpoint: endpoint, Body: out}
}
var response mergeAsyncResponse
if unmarshalErr := json.Unmarshal([]byte(jsonBody), &response); unmarshalErr != nil {
return "", fmt.Errorf("decode GitHub merge response: %w", unmarshalErr)
return mergeAsyncResponse{}, fmt.Errorf("decode GitHub merge response: %w", unmarshalErr)
}
return response, nil
}
func (c *GHClient) pollMergeAsyncResponse(
ctx context.Context,
endpoint string,
number int,
response mergeAsyncResponse,
) (mergeAsyncResponse, error) {
for response.Status == "pending" {
if response.UUID == "" {
return "", fmt.Errorf("GitHub merge response is pending without a UUID")
if response.Details.UUID == "" {
return mergeAsyncResponse{}, fmt.Errorf("GitHub merge response is pending without a UUID")
}
result, runErr := c.run(ctx, "api", endpoint+"/"+response.UUID)
wait := c.mergePollWait
if wait == nil {
wait = waitForMergePoll
}
if waitErr := wait(ctx, mergePollInterval); waitErr != nil {
return mergeAsyncResponse{}, fmt.Errorf("wait to poll merge PR #%d: %w", number, waitErr)
}
result, runErr := c.run(ctx, "api", endpoint+"/"+response.Details.UUID)
if runErr != nil {
return "", fmt.Errorf("poll merge PR #%d: %w", number, runErr)
return mergeAsyncResponse{}, fmt.Errorf("poll merge PR #%d: %w", number, runErr)
}
if unmarshalErr := json.Unmarshal([]byte(result), &response); unmarshalErr != nil {
return "", fmt.Errorf("decode GitHub merge response: %w", unmarshalErr)
return mergeAsyncResponse{}, fmt.Errorf("decode GitHub merge response: %w", unmarshalErr)
}
}
if response.Status == mergeStatusFailed {
return "", fmt.Errorf("GitHub rejected merge: %s", response.Message)
}
return normalizeMergeOutcome(response.Status)
return response, nil
}
// ghMergeStatusCode extracts the HTTP status code from a gh CLI merge error.
@@ -531,7 +531,7 @@ func TestGHClient_SubmitReview(t *testing.T) {
func TestGHClient_MergePR(t *testing.T) {
t.Run("sends the merge method", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `{"status":"merged"}`})
if _, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, "squash"); err != nil {
if _, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"}); err != nil {
t.Fatalf("MergePR: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
@@ -541,7 +541,7 @@ func TestGHClient_MergePR(t *testing.T) {
})
t.Run("omits the merge method when unset", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `{"status":"merged"}`})
if _, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, ""); err != nil {
if _, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{}); err != nil {
t.Fatalf("MergePR: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
@@ -551,6 +551,19 @@ func TestGHClient_MergePR(t *testing.T) {
})
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.1
func TestGHClient_MergePR_SendsExpectedHeadSHA(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `{"status":"merged"}`})
request := MergePRRequest{MergeMethod: "squash", ExpectedHeadSHA: "abc123"}
if _, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, request); err != nil {
t.Fatalf("MergePR: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/pulls/42/merge-async", "-X", "PUT",
"-f", "merge_action=default", "-f", "merge_method=squash", "-f", "sha=abc123",
})
}
// The gh path must surface merge rejections as *GitHubAPIError so httpMergePR
// can translate them the same way it does for the PAT client.
func TestGHClient_MergePR_StatusIsRecoverable(t *testing.T) {
@@ -566,7 +579,7 @@ func TestGHClient_MergePR_StatusIsRecoverable(t *testing.T) {
for _, tc := range cases {
t.Run(http.StatusText(tc.want), func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: tc.stderr, Exit: 1})
_, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, "merge")
_, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "merge"})
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) {
t.Fatalf("err = %v, want a *GitHubAPIError", err)
@@ -583,18 +596,75 @@ func TestGHClient_MergePR_StatusIsRecoverable(t *testing.T) {
func TestGHClient_MergePR_AlreadyQueuedIsIdempotent(t *testing.T) {
newFakeGH(t,
ghResponse{Prefix: "api repos/acme/widget/pulls/42/merge-async/request-1", Stdout: `{"status":"enqueued","uuid":"request-1"}`},
ghResponse{Prefix: "api repos/", Stderr: `{"status":"pending","uuid":"request-1"} gh: HTTP 409`, Exit: 1},
ghResponse{Prefix: "api repos/acme/widget/pulls/42/merge-async/request-1", Stdout: `{"status":"enqueued","details":{"message":"Pull request was added to the merge queue."}}`},
ghResponse{Prefix: "api repos/", Stderr: `{"status":"pending","details":{"message":"Merge request enqueued.","uuid":"request-1","merge_method":"squash","merge_action":"default","expected_head_sha":"abc123"}} gh: HTTP 409`, Exit: 1},
)
outcome, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, "squash")
outcome, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"})
if err != nil || outcome != MergeOutcomeQueued {
t.Fatalf("outcome = %q, err = %v, want queued", outcome, err)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.3
func TestGHClient_MergePR_PollsNestedPendingResponse(t *testing.T) {
calls := newFakeGH(t,
ghResponse{Prefix: "api repos/acme/widget/pulls/42/merge-async/request-1", Stdout: `{"status":"merged","details":{"sha":"abc123"}}`},
ghResponse{Prefix: "api repos/", Stdout: `{"status":"pending","details":{"message":"Merge request enqueued.","uuid":"request-1","merge_method":"squash","merge_action":"default","expected_head_sha":"abc123"}}`},
)
outcome, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"})
if err != nil || outcome != MergeOutcomeMerged {
t.Fatalf("outcome = %q, err = %v, want merged", outcome, err)
}
assertGHArgv(t, calls(t), 1, []string{
"api", "repos/acme/widget/pulls/42/merge-async/request-1",
})
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.7
func TestGHClient_MergePR_PendingPollHonorsContextBeforeNextRequest(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api repos/",
Stdout: `{"status":"pending","details":{"uuid":"request-1"}}`,
})
client := NewGHClient()
var gotDelay time.Duration
client.mergePollWait = func(_ context.Context, delay time.Duration) error {
gotDelay = delay
return context.DeadlineExceeded
}
_, err := client.MergePR(
context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"},
)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("MergePR error = %v, want context deadline", err)
}
if got := len(calls(t)); got != 1 {
t.Fatalf("request count = %d, want only the initial request before cancellation", got)
}
if gotDelay != time.Second {
t.Fatalf("poll delay = %s, want one second", gotDelay)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.13
func TestGHClient_MergePR_ReportsNestedFailureMessage(t *testing.T) {
newFakeGH(t, ghResponse{
Prefix: "api repos/",
Stdout: `{"status":"failed","details":{"message":"Branch protection blocked the merge.","expected_head_sha":"abc123"}}`,
})
_, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"})
if err == nil || !strings.Contains(err.Error(), "Branch protection blocked the merge.") ||
!strings.Contains(err.Error(), "abc123") {
t.Fatalf("err = %v, want the nested provider message and expected head", err)
}
}
func TestGHClient_MergePR_UnmappedStatusFallsBackToAPlainWrap(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "gh: HTTP 500: server error", Exit: 1})
_, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, "merge")
_, err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "merge"})
if err == nil || !strings.Contains(err.Error(), "merge PR #42") {
t.Fatalf("err = %v, want a plain wrap naming the PR", err)
}
+38 -8
View File
@@ -2,6 +2,7 @@ package github
import (
"context"
"errors"
"fmt"
"sort"
"strings"
@@ -58,10 +59,11 @@ type requestedReviewers struct {
// mergedPR records a MergePR call for test assertions.
type mergedPR struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Number int `json:"number"`
MergeMethod string `json:"merge_method"`
Owner string `json:"owner"`
Repo string `json:"repo"`
Number int `json:"number"`
MergeMethod string `json:"merge_method"`
ExpectedHeadSHA string `json:"expected_head_sha"`
}
// mockPRMergeQueueState is the provider-side queue snapshot used by the E2E
@@ -134,6 +136,7 @@ type MockClient struct {
requestedReviews []requestedReviewers
mergedPRs []mergedPR
mergeOutcomes map[prKey]MergeOutcome
mergeFailures map[prKey]string
mergeMethods map[repoKey]RepoMergeMethods
repositoryDetails map[repoKey]*GitHubRepository
gists map[string]mockGist
@@ -187,6 +190,7 @@ func NewMockClient() *MockClient {
commitDetails: make(map[commitDetailKey]PRCommitDetail),
mergeMethods: make(map[repoKey]RepoMergeMethods),
mergeOutcomes: make(map[prKey]MergeOutcome),
mergeFailures: make(map[prKey]string),
repositoryDetails: make(map[repoKey]*GitHubRepository),
gists: make(map[string]mockGist),
repoFiles: make(map[repoKey][]repoFileEntry),
@@ -768,13 +772,27 @@ func (m *MockClient) SetRepoMergeMethods(owner, repo string, methods RepoMergeMe
m.mergeMethods[repoKey{owner, repo}] = methods
}
func (m *MockClient) MergePR(_ context.Context, owner, repo string, number int, mergeMethod string) (MergeOutcome, error) {
func (m *MockClient) MergePR(_ context.Context, owner, repo string, number int, request MergePRRequest) (MergeOutcome, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.mergedPRs = append(m.mergedPRs, mergedPR{
Owner: owner, Repo: repo, Number: number, MergeMethod: mergeMethod,
Owner: owner, Repo: repo, Number: number, MergeMethod: request.MergeMethod,
ExpectedHeadSHA: request.ExpectedHeadSHA,
})
outcome := m.mergeOutcomes[prKey{owner, repo, number}]
key := prKey{owner, repo, number}
if request.ExpectedHeadSHA != "" {
pr, ok := m.prs[key]
if !ok {
return "", fmt.Errorf("pull request not found for expected head %s", request.ExpectedHeadSHA)
}
if pr.HeadSHA != request.ExpectedHeadSHA {
return "", fmt.Errorf("pull request head changed: expected %s, current %s", request.ExpectedHeadSHA, pr.HeadSHA)
}
}
if message := m.mergeFailures[key]; message != "" {
return "", errors.New(message)
}
outcome := m.mergeOutcomes[key]
if outcome == "" {
outcome = MergeOutcomeMerged
}
@@ -793,7 +811,18 @@ func (m *MockClient) MergePR(_ context.Context, owner, repo string, number int,
func (m *MockClient) SetMergeOutcome(owner, repo string, number int, outcome MergeOutcome) {
m.mu.Lock()
defer m.mu.Unlock()
m.mergeOutcomes[prKey{owner, repo, number}] = outcome
key := prKey{owner, repo, number}
m.mergeOutcomes[key] = outcome
delete(m.mergeFailures, key)
}
// SetMergeFailure configures a provider diagnostic for one pull request.
func (m *MockClient) SetMergeFailure(owner, repo string, number int, message string) {
m.mu.Lock()
defer m.mu.Unlock()
key := prKey{owner, repo, number}
m.mergeFailures[key] = strings.TrimSpace(message)
delete(m.mergeOutcomes, key)
}
func (m *MockClient) CreateGist(_ context.Context, in CreateGistInput) (*GistResponse, error) {
@@ -1104,6 +1133,7 @@ func (m *MockClient) Reset() {
m.requestedReviews = nil
m.mergedPRs = nil
m.mergeOutcomes = make(map[prKey]MergeOutcome)
m.mergeFailures = make(map[prKey]string)
m.mergeMethods = make(map[repoKey]RepoMergeMethods)
m.gists = make(map[string]mockGist)
m.deletedGists = nil
@@ -0,0 +1,36 @@
package github
import (
"context"
"strings"
"testing"
)
func TestMockClientMergePRRecordsExpectedHeadAndRejectsMismatch(t *testing.T) {
client := NewMockClient()
client.AddPR(&PR{RepoOwner: "acme", RepoName: "demo", Number: 42, HeadSHA: "head-current"})
_, err := client.MergePR(context.Background(), "acme", "demo", 42, MergePRRequest{
MergeMethod: "squash", ExpectedHeadSHA: "head-reviewed",
})
if err == nil || !strings.Contains(err.Error(), "head") {
t.Fatalf("head mismatch error = %v, want head diagnostic", err)
}
attempts := client.MergedPRs()
if len(attempts) != 1 || attempts[0].ExpectedHeadSHA != "head-reviewed" {
t.Fatalf("attempts = %+v, want reviewed head", attempts)
}
}
func TestMockClientMergePRReturnsConfiguredFailure(t *testing.T) {
client := NewMockClient()
client.AddPR(&PR{RepoOwner: "acme", RepoName: "demo", Number: 42, HeadSHA: "head-current"})
client.SetMergeFailure("acme", "demo", 42, "provider unavailable")
_, err := client.MergePR(context.Background(), "acme", "demo", 42, MergePRRequest{
MergeMethod: "squash", ExpectedHeadSHA: "head-current",
})
if err == nil || !strings.Contains(err.Error(), "provider unavailable") {
t.Fatalf("configured failure = %v, want provider diagnostic", err)
}
}
@@ -523,21 +523,38 @@ func (c *MockController) setPRCommitsFailures(ctx *gin.Context) {
func (c *MockController) setMergeOutcome(ctx *gin.Context) {
var req struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Number int `json:"number"`
Outcome MergeOutcome `json:"outcome"`
Owner string `json:"owner"`
Repo string `json:"repo"`
Number int `json:"number"`
Outcome string `json:"outcome"`
}
if err := ctx.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Owner) == "" ||
strings.TrimSpace(req.Repo) == "" || req.Number <= 0 ||
(req.Outcome != MergeOutcomeMerged && req.Outcome != MergeOutcomeQueued) {
strings.TrimSpace(req.Repo) == "" || req.Number <= 0 || !validMockMergeOutcome(req.Outcome) {
respondInvalidPayload(ctx)
return
}
c.mock.SetMergeOutcome(req.Owner, req.Repo, req.Number, req.Outcome)
switch req.Outcome {
case "failed":
c.mock.SetMergeFailure(req.Owner, req.Repo, req.Number, "mock merge provider unavailable")
case "pending":
c.mock.SetMergeFailure(req.Owner, req.Repo, req.Number, "mock merge request remained pending")
case "head_mismatch":
c.mock.SetMergeFailure(req.Owner, req.Repo, req.Number, "mock merge head mismatch")
default:
c.mock.SetMergeOutcome(req.Owner, req.Repo, req.Number, MergeOutcome(req.Outcome))
}
ctx.JSON(http.StatusOK, gin.H{"outcome": req.Outcome})
}
func validMockMergeOutcome(outcome string) bool {
switch outcome {
case string(MergeOutcomeMerged), string(MergeOutcomeQueued), "failed", "pending", "head_mismatch":
return true
default:
return false
}
}
type mockMergeQueueTransitionRequest struct {
TaskID string `json:"task_id"`
Owner string `json:"owner"`
+12
View File
@@ -730,6 +730,8 @@ type TaskCIPRAutomationState struct {
AutoFixExhaustedAt *time.Time `json:"auto_fix_exhausted_at" db:"auto_fix_exhausted_at"`
LastMergeSignature string `json:"last_merge_signature" db:"last_merge_signature"`
LastMergeAttemptAt *time.Time `json:"last_merge_attempt_at,omitempty" db:"last_merge_attempt_at"`
LastMergeResult string `json:"last_merge_result" db:"last_merge_result"`
MergeRetryPending bool `json:"-" db:"merge_retry_pending"`
LastQueueAttemptHeadSHA string `json:"last_queue_attempt_head_sha" db:"last_queue_attempt_head_sha"`
LastQueueFixEventID string `json:"last_queue_fix_event_id" db:"last_queue_fix_event_id"`
LastQueueRemovalCause string `json:"last_queue_removal_cause" db:"last_queue_removal_cause"`
@@ -740,10 +742,19 @@ type TaskCIPRAutomationState struct {
LastLifecyclePromptAt *time.Time `json:"last_lifecycle_prompt_at,omitempty" db:"last_lifecycle_prompt_at"`
LastLifecycleSessionID *string `json:"last_lifecycle_session_id,omitempty" db:"last_lifecycle_session_id"`
LastError *string `json:"last_error,omitempty" db:"last_error"`
LastErrorKind string `json:"last_error_kind" db:"last_error_kind"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
const (
TaskCIMergeResultInFlight = "in_flight"
TaskCIMergeResultFailed = "failed"
TaskCIMergeResultAccepted = "accepted"
TaskCIErrorKindAutoMerge = "auto_merge"
TaskCIErrorKindAutoFix = "auto_fix"
)
// TaskCIFixAttempt records an auto-fix prompt attempt for a task PR.
type TaskCIFixAttempt struct {
TaskID string
@@ -779,6 +790,7 @@ type TaskCIMergeQueueObservation struct {
RemovalEventID string
RemovalCause string
RemovalObservedHeadSHA string
Accepted bool
}
// TaskPRLifecyclePrompt records an accepted lifecycle prompt checkpoint.
+1 -1
View File
@@ -125,7 +125,7 @@ func (c *NoopClient) RequestReviewers(context.Context, string, string, int, []st
return ErrNoClient
}
func (c *NoopClient) MergePR(context.Context, string, string, int, string) (MergeOutcome, error) {
func (c *NoopClient) MergePR(context.Context, string, string, int, MergePRRequest) (MergeOutcome, error) {
return "", ErrNoClient
}
+17 -7
View File
@@ -728,11 +728,14 @@ func (c *PATClient) RequestReviewers(ctx context.Context, owner, repo string, nu
return c.post(ctx, endpoint, jsonBody)
}
func (c *PATClient) MergePR(ctx context.Context, owner, repo string, number int, mergeMethod string) (MergeOutcome, error) {
func (c *PATClient) MergePR(ctx context.Context, owner, repo string, number int, request MergePRRequest) (MergeOutcome, error) {
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/merge-async", owner, repo, number)
payload := map[string]string{"merge_action": "default"}
if mergeMethod != "" {
payload["merge_method"] = mergeMethod
if request.MergeMethod != "" {
payload["merge_method"] = request.MergeMethod
}
if request.ExpectedHeadSHA != "" {
payload["sha"] = request.ExpectedHeadSHA
}
jsonBody, err := json.Marshal(payload)
if err != nil {
@@ -742,20 +745,27 @@ func (c *PATClient) MergePR(ctx context.Context, owner, repo string, number int,
if err := c.putJSON(ctx, endpoint, jsonBody, &response); err != nil {
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusConflict ||
json.Unmarshal([]byte(apiErr.Body), &response) != nil || response.UUID == "" {
json.Unmarshal([]byte(apiErr.Body), &response) != nil || response.Details.UUID == "" {
return "", err
}
}
for response.Status == "pending" {
if response.UUID == "" {
if response.Details.UUID == "" {
return "", fmt.Errorf("GitHub merge response is pending without a UUID")
}
if err := c.get(ctx, endpoint+"/"+response.UUID, &response); err != nil {
wait := c.mergePollWait
if wait == nil {
wait = waitForMergePoll
}
if waitErr := wait(ctx, mergePollInterval); waitErr != nil {
return "", fmt.Errorf("wait to poll merge PR #%d: %w", number, waitErr)
}
if err := c.get(ctx, endpoint+"/"+response.Details.UUID, &response); err != nil {
return "", err
}
}
if response.Status == mergeStatusFailed {
return "", fmt.Errorf("GitHub rejected merge: %s", response.Message)
return "", newMergeFailureError(response.Details)
}
return normalizeMergeOutcome(response.Status)
}
@@ -75,7 +75,7 @@ func TestPATClient_MergePR(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusOK, `{"status":"merged"}`
})
if _, err := c.MergePR(context.Background(), "acme", "widget", 42, "squash"); err != nil {
if _, err := c.MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"}); err != nil {
t.Fatalf("MergePR: %v", err)
}
got := (*requests)[0]
@@ -93,7 +93,7 @@ func TestPATClient_MergePR(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusOK, `{"status":"merged"}`
})
if _, err := c.MergePR(context.Background(), "acme", "widget", 42, ""); err != nil {
if _, err := c.MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{}); err != nil {
t.Fatalf("MergePR: %v", err)
}
if (*requests)[0].Body != `{"merge_action":"default"}` {
@@ -101,6 +101,18 @@ func TestPATClient_MergePR(t *testing.T) {
(*requests)[0].Body)
}
})
t.Run("sends the expected head SHA", func(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusOK, `{"status":"merged"}`
})
request := MergePRRequest{MergeMethod: "squash", ExpectedHeadSHA: "abc123"}
if _, err := c.MergePR(context.Background(), "acme", "widget", 42, request); err != nil {
t.Fatalf("MergePR: %v", err)
}
if got := (*requests)[0].Body; got != `{"merge_action":"default","merge_method":"squash","sha":"abc123"}` {
t.Errorf("body = %q, want expected head SHA", got)
}
})
}
// A merge rejection must stay recoverable as *GitHubAPIError so the HTTP
@@ -111,7 +123,7 @@ func TestPATClient_MergePR_StatusIsRecoverable(t *testing.T) {
c, _ := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return status, `{"message":"Pull Request is not mergeable"}`
})
_, err := c.MergePR(context.Background(), "acme", "widget", 42, "merge")
_, err := c.MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "merge"})
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) {
t.Fatalf("err = %v, want a *GitHubAPIError", err)
@@ -132,16 +144,70 @@ func TestPATClient_MergePR_StatusIsRecoverable(t *testing.T) {
func TestPATClient_MergePR_AlreadyQueuedIsIdempotent(t *testing.T) {
c, _ := newRecordingPATServerFunc(t, func(r *http.Request) (int, string) {
if r.Method == http.MethodGet {
return http.StatusOK, `{"status":"enqueued","uuid":"request-1"}`
return http.StatusOK, `{"status":"enqueued","details":{"message":"Pull request was added to the merge queue."}}`
}
return http.StatusConflict, `{"status":"pending","uuid":"request-1"}`
return http.StatusConflict, `{"status":"pending","details":{"message":"Merge request enqueued.","uuid":"request-1","merge_method":"squash","merge_action":"default","expected_head_sha":"abc123"}}`
})
outcome, err := c.MergePR(context.Background(), "acme", "widget", 42, "squash")
outcome, err := c.MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"})
if err != nil || outcome != MergeOutcomeQueued {
t.Fatalf("outcome = %q, err = %v, want queued", outcome, err)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.3
func TestPATClient_MergePR_PollsNestedPendingResponse(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(r *http.Request) (int, string) {
if r.Method == http.MethodGet {
return http.StatusOK, `{"status":"merged","details":{"sha":"abc123"}}`
}
return http.StatusAccepted, `{"status":"pending","details":{"message":"Merge request enqueued.","uuid":"request-1","merge_method":"squash","merge_action":"default","expected_head_sha":"abc123"}}`
})
outcome, err := c.MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"})
if err != nil || outcome != MergeOutcomeMerged {
t.Fatalf("outcome = %q, err = %v, want merged", outcome, err)
}
if len(*requests) != 2 || (*requests)[1].Path != "/repos/acme/widget/pulls/42/merge-async/request-1" {
t.Fatalf("requests = %#v, want a poll for request-1", *requests)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.7
func TestPATClient_MergePR_PendingPollHonorsContextBeforeNextRequest(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusAccepted, `{"status":"pending","details":{"uuid":"request-1"}}`
})
var gotDelay time.Duration
c.mergePollWait = func(_ context.Context, delay time.Duration) error {
gotDelay = delay
return context.DeadlineExceeded
}
_, err := c.MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"})
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("MergePR error = %v, want context deadline", err)
}
if got := len(*requests); got != 1 {
t.Fatalf("request count = %d, want only the initial request before cancellation", got)
}
if gotDelay != time.Second {
t.Fatalf("poll delay = %s, want one second", gotDelay)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.13
func TestPATClient_MergePR_ReportsNestedFailureMessage(t *testing.T) {
c, _ := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusOK, `{"status":"failed","details":{"message":"Branch protection blocked the merge.","expected_head_sha":"abc123"}}`
})
_, err := c.MergePR(context.Background(), "acme", "widget", 42, MergePRRequest{MergeMethod: "squash"})
if err == nil || !strings.Contains(err.Error(), "Branch protection blocked the merge.") ||
!strings.Contains(err.Error(), "abc123") {
t.Fatalf("err = %v, want the nested provider message and expected head", err)
}
}
func TestPATClient_CreateGist(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusCreated, `{"id":"abc123","html_url":"https://gist.github.com/abc123",
+11
View File
@@ -333,6 +333,17 @@ func (s *Service) ListTaskPRsByTaskIDs(ctx context.Context, taskIDs []string) (m
return s.store.ListTaskPRsByTaskIDs(ctx, taskIDs)
}
// ListTaskPRAutomationOptionsByTaskIDs forwards bounded per-PR automation
// hydration for task-summary projection without exposing the GitHub store.
func (s *Service) ListTaskPRAutomationOptionsByTaskIDs(
ctx context.Context, taskIDs []string,
) (map[string][]*TaskPRAutomationOptions, error) {
if s.store == nil {
return map[string][]*TaskPRAutomationOptions{}, nil
}
return s.store.ListTaskPRAutomationOptionsByTaskIDs(ctx, taskIDs)
}
// TestEventBus returns the event bus for test/mock use only.
func (s *Service) TestEventBus() bus.EventBus {
return s.eventBus
@@ -185,8 +185,11 @@ func (s *Service) MergePRForAutomation(
ctx context.Context,
workspaceID, owner, repo string,
number int,
mergeMethod string,
mergeMethod, expectedHeadSHA string,
) error {
if strings.TrimSpace(expectedHeadSHA) == "" {
return fmt.Errorf("automatic merge requires an expected head SHA")
}
if err := s.ensureRepositoryInWorkspaceScope(ctx, workspaceID, owner, repo); err != nil {
return err
}
@@ -198,7 +201,9 @@ func (s *Service) MergePRForAutomation(
return err
}
_, err = s.mergePRWithClient(
ctx, resolved.Client, resolved.CacheScope, owner, repo, number, mergeMethod,
ctx, resolved.Client, resolved.CacheScope, owner, repo, number, MergePRRequest{
MergeMethod: mergeMethod, ExpectedHeadSHA: expectedHeadSHA,
},
)
return err
}
@@ -0,0 +1,18 @@
package github
import (
"context"
"strings"
"testing"
)
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.1
func TestMergePRForAutomationRequiresExpectedHeadSHA(t *testing.T) {
service := &Service{}
err := service.MergePRForAutomation(
context.Background(), "workspace-1", "acme", "widget", 42, "squash", "",
)
if err == nil || !strings.Contains(err.Error(), "expected head SHA") {
t.Fatalf("error = %v, want expected-head validation", err)
}
}
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"strings"
"time"
promptcfg "github.com/kandev/kandev/config/prompts"
)
@@ -82,6 +83,42 @@ func (s *Service) UpdateTaskCIOptions(ctx context.Context, taskID string, patch
return response, err
}
// RetryTaskCIAutoMerge authorizes one new evaluation of a failed automatic
// merge for the exact linked PR. The caller publishes the returned PR through
// the normal PR-updated event path; this method never calls GitHub.
func (s *Service) RetryTaskCIAutoMerge(
ctx context.Context, taskID, repositoryID string, prNumber int,
) (*TaskPR, error) {
if s.store == nil {
return nil, errStoreUnavailable
}
if _, err := s.resolveAuthorizedTaskWorkspace(ctx, taskID); err != nil {
return nil, err
}
targets, err := s.resolveTaskPRAutomationTargets(ctx, taskID, &repositoryID, &prNumber)
if err != nil {
return nil, err
}
if len(targets) != 1 {
return nil, ErrTaskPRNotLinked
}
if err := s.store.AuthorizeTaskCIMergeRetry(ctx, taskID, repositoryID, prNumber, time.Now().UTC()); err != nil {
return nil, err
}
return targets[0], nil
}
// ClearTaskCIMergeRetryAuthorization removes a retry authorization that could
// not be delivered to the automation evaluator.
func (s *Service) ClearTaskCIMergeRetryAuthorization(
ctx context.Context, taskID, repositoryID string, prNumber int,
) error {
if s.store == nil {
return errStoreUnavailable
}
return s.store.ClearTaskCIMergeRetryAuthorization(ctx, taskID, repositoryID, prNumber)
}
// resolveAuthorizedTaskWorkspace resolves ownership through the task service
// before any user-facing CI-option read or mutation. Unit tests and legacy
// auth-disabled embeddings without a task store retain their unscoped path;
@@ -240,6 +277,16 @@ func (s *Service) RecordTaskCIMergeAttempt(ctx context.Context, attempt TaskCIMe
return s.store.RecordTaskCIMergeAttempt(ctx, attempt)
}
// RecordTaskCIMergeAttemptResult completes a reserved auto-merge attempt.
func (s *Service) RecordTaskCIMergeAttemptResult(
ctx context.Context, taskID, repositoryID string, prNumber int, signature, result, message string,
) error {
if s.store == nil {
return errStoreUnavailable
}
return s.store.RecordTaskCIMergeAttemptResult(ctx, taskID, repositoryID, prNumber, signature, result, message)
}
// RecordTaskCIMergeQueueObservation persists active queue membership and the
// latest removal cause so automation can recover safely after a restart.
func (s *Service) RecordTaskCIMergeQueueObservation(ctx context.Context, observation TaskCIMergeQueueObservation) error {
@@ -257,6 +304,14 @@ func (s *Service) RecordTaskCIError(ctx context.Context, taskID, repositoryID st
return s.store.RecordTaskCIError(ctx, taskID, repositoryID, prNumber, message)
}
// RecordTaskCIAutoMergeError records a typed automatic-merge error.
func (s *Service) RecordTaskCIAutoMergeError(ctx context.Context, taskID, repositoryID string, prNumber int, message string) error {
if s.store == nil {
return errStoreUnavailable
}
return s.store.RecordTaskCIAutoMergeError(ctx, taskID, repositoryID, prNumber, message)
}
// MarkTaskCIAutoFixExhausted records that auto-fix reached its per-PR round cap.
func (s *Service) MarkTaskCIAutoFixExhausted(ctx context.Context, taskID, repositoryID string, prNumber int, message string) error {
if s.store == nil {
+6 -6
View File
@@ -128,7 +128,7 @@ func (s *Service) MergePR(ctx context.Context, owner, repo string, number int, m
if s.client == nil {
return "", ErrNoClient
}
return s.mergePRWithClient(ctx, s.client, "legacy", owner, repo, number, mergeMethod)
return s.mergePRWithClient(ctx, s.client, "legacy", owner, repo, number, MergePRRequest{MergeMethod: mergeMethod})
}
// MergePRForWorkspace performs a user-triggered merge using the workspace's
@@ -153,7 +153,7 @@ func (s *Service) MergePRForWorkspace(
return AuthPrincipal{}, "", err
}
outcome, err := s.mergePRWithClient(
ctx, resolved.Client, resolved.CacheScope, owner, repo, number, mergeMethod,
ctx, resolved.Client, resolved.CacheScope, owner, repo, number, MergePRRequest{MergeMethod: mergeMethod},
)
return resolved.Principal, outcome, err
}
@@ -165,9 +165,9 @@ func (s *Service) mergePRWithClient(
owner string,
repo string,
number int,
mergeMethod string,
request MergePRRequest,
) (MergeOutcome, error) {
if mergeMethod == "" {
if request.MergeMethod == "" {
// Resolve to an allowed method up-front so we don't rely on GitHub's
// "default to merge" behavior, which 405s on repos that disallow
// merge commits (squash-only / rebase-only). Best-effort: if the
@@ -176,11 +176,11 @@ func (s *Service) mergePRWithClient(
// blocking the merge attempt.
if methods, err := s.getRepoMergeMethods(ctx, client, cacheScope, owner, repo); err == nil {
if pick := pickDefaultMergeMethod(methods); pick != "" {
mergeMethod = pick
request.MergeMethod = pick
}
}
}
return client.MergePR(ctx, owner, repo, number, mergeMethod)
return client.MergePR(ctx, owner, repo, number, request)
}
// GetRepoMergeMethods returns the merge methods a repo allows, cached for
@@ -762,9 +762,13 @@ type mockEventBus struct {
mu sync.Mutex
events []*bus.Event
publishedCh chan struct{}
err error
}
func (m *mockEventBus) Publish(_ context.Context, _ string, event *bus.Event) error {
if m.err != nil {
return m.err
}
m.mu.Lock()
m.events = append(m.events, event)
m.mu.Unlock()
+228 -19
View File
@@ -418,6 +418,8 @@ const createTablesSQL = `
auto_fix_exhausted_at DATETIME,
last_merge_signature TEXT NOT NULL DEFAULT '',
last_merge_attempt_at DATETIME,
last_merge_result TEXT NOT NULL DEFAULT '',
merge_retry_pending BOOLEAN NOT NULL DEFAULT 0,
last_queue_attempt_head_sha TEXT NOT NULL DEFAULT '',
last_queue_fix_event_id TEXT NOT NULL DEFAULT '',
last_queue_removal_cause TEXT NOT NULL DEFAULT '',
@@ -428,6 +430,7 @@ const createTablesSQL = `
last_lifecycle_prompt_at DATETIME,
last_lifecycle_session_id TEXT,
last_error TEXT,
last_error_kind TEXT NOT NULL DEFAULT '',
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
PRIMARY KEY (task_id, repository_id, pr_number)
@@ -1072,6 +1075,9 @@ func (s *Store) addTaskPRAgentAutomationColumns() error {
{"closed_prompt_override", "ALTER TABLE github_task_ci_options ADD COLUMN closed_prompt_override TEXT"},
},
"github_task_ci_pr_state": {
{"last_merge_result", "ALTER TABLE github_task_ci_pr_state ADD COLUMN last_merge_result TEXT NOT NULL DEFAULT ''"},
{"merge_retry_pending", "ALTER TABLE github_task_ci_pr_state ADD COLUMN merge_retry_pending BOOLEAN NOT NULL DEFAULT 0"},
{"last_error_kind", "ALTER TABLE github_task_ci_pr_state ADD COLUMN last_error_kind TEXT NOT NULL DEFAULT ''"},
{"last_queue_attempt_head_sha", "ALTER TABLE github_task_ci_pr_state ADD COLUMN last_queue_attempt_head_sha TEXT NOT NULL DEFAULT ''"},
{"last_queue_fix_event_id", "ALTER TABLE github_task_ci_pr_state ADD COLUMN last_queue_fix_event_id TEXT NOT NULL DEFAULT ''"},
{"last_queue_removal_cause", "ALTER TABLE github_task_ci_pr_state ADD COLUMN last_queue_removal_cause TEXT NOT NULL DEFAULT ''"},
@@ -1097,6 +1103,20 @@ func (s *Store) addTaskPRAgentAutomationColumns() error {
}
}
}
return s.backfillTaskCIAutoMergeErrorKinds()
}
func (s *Store) backfillTaskCIAutoMergeErrorKinds() error {
_, err := s.db.Exec(`
UPDATE github_task_ci_pr_state
SET last_error_kind = ?
WHERE last_error_kind = ''
AND (last_error LIKE 'merge PR:%'
OR last_error LIKE 'PR status is not freshly synced for auto-merge%')`,
TaskCIErrorKindAutoMerge)
if err != nil {
return fmt.Errorf("backfill CI auto-merge error kinds: %w", err)
}
return nil
}
@@ -2501,6 +2521,7 @@ func resetTaskCIAutoFixStateForTask(
last_fix_enqueued_at = NULL,
last_fix_session_id = NULL,
last_error = CASE WHEN auto_fix_exhausted_at IS NOT NULL THEN NULL ELSE last_error END,
last_error_kind = CASE WHEN auto_fix_exhausted_at IS NOT NULL THEN '' ELSE last_error_kind END,
auto_fix_exhausted_at = NULL,
updated_at = ?
WHERE task_id = ?`, now, taskID)
@@ -2558,6 +2579,34 @@ func (s *Store) ListTaskPRAutomationOptions(ctx context.Context, taskID string)
return out, nil
}
// ListTaskPRAutomationOptionsByTaskIDs returns stored per-PR automation rows
// grouped by task. It is used by bounded task-summary hydration so a task list
// does not issue one options query for each visible row.
func (s *Store) ListTaskPRAutomationOptionsByTaskIDs(
ctx context.Context, taskIDs []string,
) (map[string][]*TaskPRAutomationOptions, error) {
if len(taskIDs) == 0 {
return make(map[string][]*TaskPRAutomationOptions), nil
}
query, args, err := sqlx.In(
`SELECT * FROM github_task_pr_automation_options WHERE task_id IN (?) ORDER BY task_id ASC, repository_id ASC, pr_number ASC`,
taskIDs,
)
if err != nil {
return nil, err
}
query = s.ro.Rebind(query)
var rows []TaskPRAutomationOptions
if err := s.ro.SelectContext(ctx, &rows, query, args...); err != nil {
return nil, err
}
result := make(map[string][]*TaskPRAutomationOptions)
for i := range rows {
result[rows[i].TaskID] = append(result[rows[i].TaskID], &rows[i])
}
return result, nil
}
// UpdateTaskPRAutomationOptions applies a partial update to one PR's
// automation switches, upserting the row if absent. reviewerChanged mirrors
// the task-wide reviewer rebind: the caller resolves it once (comparing the
@@ -2701,6 +2750,7 @@ func resetTaskCIAutoFixState(
last_fix_enqueued_at = NULL,
last_fix_session_id = NULL,
last_error = CASE WHEN auto_fix_exhausted_at IS NOT NULL THEN NULL ELSE last_error END,
last_error_kind = CASE WHEN auto_fix_exhausted_at IS NOT NULL THEN '' ELSE last_error_kind END,
auto_fix_exhausted_at = NULL,
updated_at = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, now, taskID, repositoryID, prNumber)
@@ -2824,6 +2874,7 @@ func (s *Store) RecordTaskCIFixAttempt(ctx context.Context, attempt TaskCIFixAtt
WHEN excluded.last_queue_removal_cause <> '' THEN excluded.last_queue_removal_cause
ELSE github_task_ci_pr_state.last_queue_removal_cause END,
last_error = NULL,
last_error_kind = '',
updated_at = excluded.updated_at`,
attempt.TaskID, attempt.RepositoryID, attempt.PRNumber, attempt.Signature,
attempt.CheckpointJSON, when, nullableString(attempt.SessionID), roundCount,
@@ -2845,35 +2896,162 @@ func (s *Store) RefreshTaskCIFixCheckpoint(ctx context.Context, taskID, reposito
last_fix_enqueued_at = NULL,
last_fix_session_id = NULL,
last_error = NULL,
last_error_kind = '',
updated_at = excluded.updated_at`,
taskID, repositoryID, prNumber, signature, checkpointJSON, now, now)
return err
})
}
// RecordTaskCIMergeAttempt records an auto-merge attempt signature.
var ErrTaskCIMergeAttemptAlreadyReserved = errors.New("CI auto-merge attempt already reserved")
var ErrTaskCIMergeAttemptNotFound = errors.New("CI auto-merge attempt not found")
var ErrTaskCIMergeRetryNotAllowed = errors.New("CI auto-merge retry is not available")
const taskCIMergeRetryInFlightTTL = 2 * time.Minute
// AuthorizeTaskCIMergeRetry persists one single-use authorization to
// reevaluate a failed or expired automatic merge attempt.
func (s *Store) AuthorizeTaskCIMergeRetry(
ctx context.Context, taskID, repositoryID string, prNumber int, requestedAt time.Time,
) error {
if requestedAt.IsZero() {
requestedAt = time.Now().UTC()
}
expiredBefore := requestedAt.Add(-taskCIMergeRetryInFlightTTL)
return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error {
result, err := tx.ExecContext(ctx, `
UPDATE github_task_ci_pr_state SET
merge_retry_pending = 1,
updated_at = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?
AND merge_retry_pending = 0
AND (
(last_merge_result = ? AND last_error_kind = ?)
OR (last_merge_result = ? AND last_merge_attempt_at <= ?)
)`,
now, taskID, repositoryID, prNumber,
TaskCIMergeResultFailed, TaskCIErrorKindAutoMerge,
TaskCIMergeResultInFlight, expiredBefore)
if err != nil {
return err
}
rows, err := result.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return ErrTaskCIMergeRetryNotAllowed
}
return nil
})
}
// ClearTaskCIMergeRetryAuthorization rolls back a one-shot retry authorization
// when its follow-up event could not be published. This keeps a failed publish
// from leaving the PR permanently blocked behind merge_retry_pending.
func (s *Store) ClearTaskCIMergeRetryAuthorization(
ctx context.Context, taskID, repositoryID string, prNumber int,
) error {
return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error {
_, err := tx.ExecContext(ctx, `
UPDATE github_task_ci_pr_state
SET merge_retry_pending = 0, updated_at = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?
AND merge_retry_pending = 1`,
now, taskID, repositoryID, prNumber)
return err
})
}
// RecordTaskCIMergeAttempt reserves an auto-merge attempt signature before
// the provider side effect. An unchanged signature cannot replace an existing
// reservation or terminal result.
func (s *Store) RecordTaskCIMergeAttempt(ctx context.Context, attempt TaskCIMergeAttempt) error {
when := attempt.AttemptedAt
if when.IsZero() {
when = time.Now().UTC()
}
return s.mutateTaskCIPRState(ctx, attempt.TaskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error {
_, err := tx.ExecContext(ctx, `
result, err := tx.ExecContext(ctx, `
INSERT INTO github_task_ci_pr_state (
task_id, repository_id, pr_number, last_merge_signature, last_merge_attempt_at,
last_queue_attempt_head_sha, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
last_merge_result, merge_retry_pending, last_queue_attempt_head_sha, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
ON CONFLICT(task_id, repository_id, pr_number) DO UPDATE SET
last_merge_signature = excluded.last_merge_signature,
last_merge_attempt_at = excluded.last_merge_attempt_at,
last_merge_result = excluded.last_merge_result,
merge_retry_pending = 0,
last_queue_attempt_head_sha = CASE
WHEN excluded.last_queue_attempt_head_sha <> '' THEN excluded.last_queue_attempt_head_sha
ELSE github_task_ci_pr_state.last_queue_attempt_head_sha END,
last_error = NULL,
updated_at = excluded.updated_at`,
last_error = CASE WHEN github_task_ci_pr_state.last_error_kind = ?
THEN NULL ELSE github_task_ci_pr_state.last_error END,
last_error_kind = CASE WHEN github_task_ci_pr_state.last_error_kind = ?
THEN '' ELSE github_task_ci_pr_state.last_error_kind END,
updated_at = excluded.updated_at
WHERE github_task_ci_pr_state.last_merge_signature <> excluded.last_merge_signature
OR github_task_ci_pr_state.merge_retry_pending = 1`,
attempt.TaskID, attempt.RepositoryID, attempt.PRNumber, attempt.Signature, when,
attempt.AttemptedHeadSHA, now, now)
return err
TaskCIMergeResultInFlight, attempt.AttemptedHeadSHA, now, now,
TaskCIErrorKindAutoMerge, TaskCIErrorKindAutoMerge)
if err != nil {
return err
}
rows, err := result.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return ErrTaskCIMergeAttemptAlreadyReserved
}
return nil
})
}
// RecordTaskCIMergeAttemptResult completes a reserved attempt and updates its
// typed error in the same transaction.
func (s *Store) RecordTaskCIMergeAttemptResult(
ctx context.Context,
taskID, repositoryID string,
prNumber int,
signature, result, message string,
) error {
if result != TaskCIMergeResultFailed && result != TaskCIMergeResultAccepted {
return fmt.Errorf("invalid CI auto-merge result %q", result)
}
return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error {
outcome, err := tx.ExecContext(ctx, `
UPDATE github_task_ci_pr_state SET
last_merge_result = ?,
last_error = CASE
WHEN ? = ? THEN ?
WHEN ? = ? AND last_error_kind = ? THEN NULL
ELSE last_error END,
last_error_kind = CASE
WHEN ? = ? THEN ?
WHEN ? = ? AND last_error_kind = ? THEN ''
ELSE last_error_kind END,
updated_at = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?
AND last_merge_signature = ?`,
result,
result, TaskCIMergeResultFailed, strings.TrimSpace(message),
result, TaskCIMergeResultAccepted, TaskCIErrorKindAutoMerge,
result, TaskCIMergeResultFailed, TaskCIErrorKindAutoMerge,
result, TaskCIMergeResultAccepted, TaskCIErrorKindAutoMerge,
now, taskID, repositoryID, prNumber, signature)
if err != nil {
return err
}
rows, err := outcome.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return ErrTaskCIMergeAttemptNotFound
}
return nil
})
}
@@ -2885,18 +3063,28 @@ func (s *Store) RecordTaskCIMergeAttempt(ctx context.Context, attempt TaskCIMerg
func (s *Store) RecordTaskCIMergeQueueObservation(ctx context.Context, observation TaskCIMergeQueueObservation) error {
return s.mutateTaskCIPRState(ctx, observation.TaskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error {
baselineHead := ""
mergeResult := ""
if observation.ActiveQueueHeadSHA != "" || observation.Accepted {
mergeResult = TaskCIMergeResultAccepted
}
if observation.ActiveQueueHeadSHA == "" {
baselineHead = observation.RemovalObservedHeadSHA
}
_, err := tx.ExecContext(ctx, `
INSERT INTO github_task_ci_pr_state (
task_id, repository_id, pr_number, last_merge_signature,
task_id, repository_id, pr_number, last_merge_signature, last_merge_result,
last_queue_attempt_head_sha, last_queue_removal_cause, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(task_id, repository_id, pr_number) DO UPDATE SET
last_merge_signature = CASE
WHEN excluded.last_merge_signature <> '' THEN excluded.last_merge_signature
ELSE github_task_ci_pr_state.last_merge_signature END,
last_merge_result = CASE
WHEN excluded.last_merge_result <> '' THEN excluded.last_merge_result
ELSE github_task_ci_pr_state.last_merge_result END,
merge_retry_pending = CASE
WHEN excluded.last_merge_result = ? THEN 0
ELSE github_task_ci_pr_state.merge_retry_pending END,
last_queue_attempt_head_sha = CASE
WHEN excluded.last_queue_attempt_head_sha <> ''
THEN excluded.last_queue_attempt_head_sha
@@ -2905,10 +3093,19 @@ func (s *Store) RecordTaskCIMergeQueueObservation(ctx context.Context, observati
WHEN excluded.last_queue_removal_cause <> ''
THEN excluded.last_queue_removal_cause
ELSE github_task_ci_pr_state.last_queue_removal_cause END,
last_error = CASE
WHEN excluded.last_merge_result = ? AND github_task_ci_pr_state.last_error_kind = ?
THEN NULL ELSE github_task_ci_pr_state.last_error END,
last_error_kind = CASE
WHEN excluded.last_merge_result = ? AND github_task_ci_pr_state.last_error_kind = ?
THEN '' ELSE github_task_ci_pr_state.last_error_kind END,
updated_at = excluded.updated_at`,
observation.TaskID, observation.RepositoryID, observation.PRNumber,
observation.MergeSignature,
observation.ActiveQueueHeadSHA, observation.RemovalCause, now, now)
observation.MergeSignature, mergeResult,
observation.ActiveQueueHeadSHA, observation.RemovalCause, now, now,
TaskCIMergeResultAccepted,
TaskCIMergeResultAccepted, TaskCIErrorKindAutoMerge,
TaskCIMergeResultAccepted, TaskCIErrorKindAutoMerge)
if err != nil {
return err
}
@@ -2927,15 +3124,25 @@ func (s *Store) RecordTaskCIMergeQueueObservation(ctx context.Context, observati
// RecordTaskCIError stores the latest user-visible CI automation error for a task PR.
func (s *Store) RecordTaskCIError(ctx context.Context, taskID, repositoryID string, prNumber int, message string) error {
return s.recordTaskCIError(ctx, taskID, repositoryID, prNumber, "", message)
}
// RecordTaskCIAutoMergeError stores an error produced by the automatic merge path.
func (s *Store) RecordTaskCIAutoMergeError(ctx context.Context, taskID, repositoryID string, prNumber int, message string) error {
return s.recordTaskCIError(ctx, taskID, repositoryID, prNumber, TaskCIErrorKindAutoMerge, message)
}
func (s *Store) recordTaskCIError(ctx context.Context, taskID, repositoryID string, prNumber int, kind, message string) error {
return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error {
_, err := tx.ExecContext(ctx, `
INSERT INTO github_task_ci_pr_state (
task_id, repository_id, pr_number, last_error, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?)
task_id, repository_id, pr_number, last_error, last_error_kind, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(task_id, repository_id, pr_number) DO UPDATE SET
last_error = excluded.last_error,
last_error_kind = excluded.last_error_kind,
updated_at = excluded.updated_at`,
taskID, repositoryID, prNumber, strings.TrimSpace(message), now, now)
taskID, repositoryID, prNumber, strings.TrimSpace(message), kind, now, now)
return err
})
}
@@ -2945,13 +3152,14 @@ func (s *Store) MarkTaskCIAutoFixExhausted(ctx context.Context, taskID, reposito
return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error {
_, err := tx.ExecContext(ctx, `
INSERT INTO github_task_ci_pr_state (
task_id, repository_id, pr_number, auto_fix_exhausted_at, last_error, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?)
task_id, repository_id, pr_number, auto_fix_exhausted_at, last_error, last_error_kind, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(task_id, repository_id, pr_number) DO UPDATE SET
auto_fix_exhausted_at = excluded.auto_fix_exhausted_at,
last_error = excluded.last_error,
last_error_kind = excluded.last_error_kind,
updated_at = excluded.updated_at`,
taskID, repositoryID, prNumber, now, strings.TrimSpace(message), now, now)
taskID, repositoryID, prNumber, now, strings.TrimSpace(message), TaskCIErrorKindAutoFix, now, now)
return err
})
}
@@ -2960,7 +3168,7 @@ func (s *Store) MarkTaskCIAutoFixExhausted(ctx context.Context, taskID, reposito
func (s *Store) ClearTaskCIError(ctx context.Context, taskID, repositoryID string, prNumber int) error {
return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error {
_, err := tx.ExecContext(ctx, `
UPDATE github_task_ci_pr_state SET last_error = NULL, updated_at = ?
UPDATE github_task_ci_pr_state SET last_error = NULL, last_error_kind = '', updated_at = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?`,
now, taskID, repositoryID, prNumber)
return err
@@ -3034,6 +3242,7 @@ func (s *Store) RecordTaskPRLifecyclePrompt(ctx context.Context, prompt TaskPRLi
last_lifecycle_prompt_at = excluded.last_lifecycle_prompt_at,
last_lifecycle_session_id = excluded.last_lifecycle_session_id,
last_error = NULL,
last_error_kind = '',
updated_at = excluded.updated_at`,
prompt.TaskID, prompt.RepositoryID, prompt.PRNumber,
prompt.Event == "review_requested", prompt.ReviewRequested,
@@ -2,6 +2,9 @@ package github
import (
"context"
"errors"
"strings"
"sync"
"testing"
"time"
)
@@ -21,6 +24,7 @@ func TestStoreTaskPRAgentAutomationSchema(t *testing.T) {
"pr_scope_migrated_at",
},
"github_task_ci_pr_state": {
"merge_retry_pending",
"review_request_initialized",
"last_review_requested",
"last_observed_pr_state",
@@ -53,6 +57,114 @@ func TestStoreTaskPRAgentAutomationSchema(t *testing.T) {
}
}
func TestStoreRetryMergeAuthorizesOneSameSignatureAttempt(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
attempt := TaskCIMergeAttempt{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
Signature: "ready-v1", AttemptedHeadSHA: "head-v1", AttemptedAt: time.Now().UTC(),
}
if err := store.RecordTaskCIMergeAttempt(ctx, attempt); err != nil {
t.Fatalf("reserve initial attempt: %v", err)
}
if err := store.RecordTaskCIMergeAttemptResult(
ctx, attempt.TaskID, attempt.RepositoryID, attempt.PRNumber,
attempt.Signature, TaskCIMergeResultFailed, "merge PR: provider unavailable",
); err != nil {
t.Fatalf("record failed attempt: %v", err)
}
if err := store.AuthorizeTaskCIMergeRetry(
ctx, attempt.TaskID, attempt.RepositoryID, attempt.PRNumber, time.Now().UTC(),
); err != nil {
t.Fatalf("authorize retry: %v", err)
}
state, err := store.GetTaskCIPRState(ctx, attempt.TaskID, attempt.RepositoryID, attempt.PRNumber)
if err != nil {
t.Fatalf("get authorized state: %v", err)
}
if state == nil || !state.MergeRetryPending {
t.Fatalf("retry authorization not persisted: %+v", state)
}
if err := store.RecordTaskCIMergeAttempt(ctx, attempt); err != nil {
t.Fatalf("consume retry authorization: %v", err)
}
state, err = store.GetTaskCIPRState(ctx, attempt.TaskID, attempt.RepositoryID, attempt.PRNumber)
if err != nil {
t.Fatalf("get consumed state: %v", err)
}
if state == nil || state.MergeRetryPending {
t.Fatalf("retry authorization was not consumed: %+v", state)
}
if err := store.RecordTaskCIMergeAttempt(ctx, attempt); !errors.Is(err, ErrTaskCIMergeAttemptAlreadyReserved) {
t.Fatalf("second same-signature retry error = %v, want %v", err, ErrTaskCIMergeAttemptAlreadyReserved)
}
}
func TestStoreRetryMergeRejectsAcceptedAndDuplicateRequests(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
attempt := TaskCIMergeAttempt{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
Signature: "ready-v1", AttemptedHeadSHA: "head-v1", AttemptedAt: time.Now().UTC(),
}
if err := store.RecordTaskCIMergeAttempt(ctx, attempt); err != nil {
t.Fatalf("reserve attempt: %v", err)
}
if err := store.RecordTaskCIMergeAttemptResult(
ctx, attempt.TaskID, attempt.RepositoryID, attempt.PRNumber,
attempt.Signature, TaskCIMergeResultFailed, "merge PR: provider unavailable",
); err != nil {
t.Fatalf("record failure: %v", err)
}
if err := store.AuthorizeTaskCIMergeRetry(
ctx, attempt.TaskID, attempt.RepositoryID, attempt.PRNumber, time.Now().UTC(),
); err != nil {
t.Fatalf("authorize first retry: %v", err)
}
if err := store.AuthorizeTaskCIMergeRetry(
ctx, attempt.TaskID, attempt.RepositoryID, attempt.PRNumber, time.Now().UTC(),
); !errors.Is(err, ErrTaskCIMergeRetryNotAllowed) {
t.Fatalf("duplicate authorization error = %v, want %v", err, ErrTaskCIMergeRetryNotAllowed)
}
if err := store.RecordTaskCIMergeAttempt(ctx, TaskCIMergeAttempt{
TaskID: attempt.TaskID, RepositoryID: attempt.RepositoryID, PRNumber: 43,
Signature: "ready-v2", AttemptedHeadSHA: "head-v2", AttemptedAt: time.Now().UTC(),
}); err != nil {
t.Fatalf("reserve accepted attempt: %v", err)
}
if err := store.RecordTaskCIMergeAttemptResult(
ctx, attempt.TaskID, attempt.RepositoryID, 43,
"ready-v2", TaskCIMergeResultAccepted, "",
); err != nil {
t.Fatalf("record accepted attempt: %v", err)
}
if err := store.AuthorizeTaskCIMergeRetry(
ctx, attempt.TaskID, attempt.RepositoryID, 43, time.Now().UTC(),
); !errors.Is(err, ErrTaskCIMergeRetryNotAllowed) {
t.Fatalf("accepted authorization error = %v, want %v", err, ErrTaskCIMergeRetryNotAllowed)
}
}
func TestStoreRetryMergeAllowsExpiredInFlightAttempt(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
attempt := TaskCIMergeAttempt{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
Signature: "ready-v1", AttemptedHeadSHA: "head-v1", AttemptedAt: time.Now().UTC().Add(-3 * time.Minute),
}
if err := store.RecordTaskCIMergeAttempt(ctx, attempt); err != nil {
t.Fatalf("reserve stale attempt: %v", err)
}
if err := store.AuthorizeTaskCIMergeRetry(
ctx, attempt.TaskID, attempt.RepositoryID, attempt.PRNumber, time.Now().UTC(),
); err != nil {
t.Fatalf("authorize expired retry: %v", err)
}
}
// TestStoreTaskPRAutomationOptionsSchemaReplay confirms initSchema can run
// twice against the same database without error — the fresh-DB CREATE TABLE
// and the idempotent ADD COLUMN/fan-out migration must both tolerate replay.
@@ -511,6 +623,244 @@ func TestStoreTaskCIMergeQueueRecoveryState(t *testing.T) {
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.2
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.8
func TestStoreTaskCIMergeAttemptJournalSchema(t *testing.T) {
store := newTestStore(t)
columns, err := store.tableColumns("github_task_ci_pr_state")
if err != nil {
t.Fatalf("read journal columns: %v", err)
}
for _, name := range []string{"last_merge_result", "last_error_kind"} {
if _, ok := columns[name]; !ok {
t.Errorf("missing journal column %q", name)
}
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.2
func TestStoreTaskCIMergeAttemptReservationBlocksUnchangedAttempt(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
first := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
attempt := TaskCIMergeAttempt{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
Signature: "ready-head-a", AttemptedHeadSHA: "head-a", AttemptedAt: first,
}
if err := store.RecordTaskCIMergeAttempt(ctx, attempt); err != nil {
t.Fatalf("reserve first merge attempt: %v", err)
}
attempt.AttemptedAt = first.Add(time.Minute)
if err := store.RecordTaskCIMergeAttempt(ctx, attempt); err == nil ||
!strings.Contains(err.Error(), "already reserved") {
t.Fatalf("reserve unchanged attempt error = %v, want already reserved", err)
}
state, err := store.GetTaskCIPRState(ctx, "task-1", "repo-1", 42)
if err != nil {
t.Fatalf("get merge attempt: %v", err)
}
if state.LastMergeResult != TaskCIMergeResultInFlight {
t.Fatalf("merge result = %q, want in_flight", state.LastMergeResult)
}
if state.LastMergeAttemptAt == nil || !state.LastMergeAttemptAt.Equal(first) {
t.Fatalf("attempt time = %v, want first reservation %v", state.LastMergeAttemptAt, first)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.5
func TestStoreTaskCIMergeQueueObservationReconcilesOnlyAutoMergeError(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
now := time.Now().UTC()
if _, err := store.db.Exec(`
INSERT INTO github_task_ci_pr_state (
task_id, repository_id, pr_number, last_merge_signature, last_merge_result,
last_error, last_error_kind, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
"task-1", "repo-1", 42, "merge-a", TaskCIMergeResultFailed,
"merge PR: provider status was lost", TaskCIErrorKindAutoMerge, now, now); err != nil {
t.Fatalf("seed failed merge attempt: %v", err)
}
if err := store.RecordTaskCIMergeQueueObservation(ctx, TaskCIMergeQueueObservation{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
ActiveQueueHeadSHA: "head-a", MergeSignature: "merge-a",
}); err != nil {
t.Fatalf("record queue observation: %v", err)
}
state, err := store.GetTaskCIPRState(ctx, "task-1", "repo-1", 42)
if err != nil {
t.Fatalf("get reconciled attempt: %v", err)
}
if state.LastMergeResult != TaskCIMergeResultAccepted || state.LastError != nil || state.LastErrorKind != "" {
t.Fatalf("reconciled state = %+v, want accepted with cleared merge error", state)
}
if _, err := store.db.Exec(`
UPDATE github_task_ci_pr_state
SET last_error = ?, last_error_kind = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?`,
"auto-fix failed", "auto_fix", "task-1", "repo-1", 42); err != nil {
t.Fatalf("seed unrelated error: %v", err)
}
if err := store.RecordTaskCIMergeQueueObservation(ctx, TaskCIMergeQueueObservation{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
ActiveQueueHeadSHA: "head-a", MergeSignature: "merge-a",
}); err != nil {
t.Fatalf("record repeated queue observation: %v", err)
}
state, err = store.GetTaskCIPRState(ctx, "task-1", "repo-1", 42)
if err != nil {
t.Fatalf("get unrelated error state: %v", err)
}
if state.LastError == nil || *state.LastError != "auto-fix failed" || state.LastErrorKind != "auto_fix" {
t.Fatalf("unrelated error was cleared: %+v", state)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.2
func TestStoreTaskCIMergeAttemptResultRecordsFailureAtomically(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
if err := store.RecordTaskCIMergeAttempt(ctx, TaskCIMergeAttempt{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
Signature: "ready-head-a", AttemptedHeadSHA: "head-a",
}); err != nil {
t.Fatalf("reserve merge attempt: %v", err)
}
message := "merge PR: GitHub response was lost"
if err := store.RecordTaskCIMergeAttemptResult(
ctx, "task-1", "repo-1", 42, "ready-head-a", TaskCIMergeResultFailed, message,
); err != nil {
t.Fatalf("record failed merge attempt: %v", err)
}
state, err := store.GetTaskCIPRState(ctx, "task-1", "repo-1", 42)
if err != nil {
t.Fatalf("get failed merge attempt: %v", err)
}
if state.LastMergeResult != TaskCIMergeResultFailed || state.LastErrorKind != TaskCIErrorKindAutoMerge {
t.Fatalf("failed merge state = %+v", state)
}
if state.LastError == nil || *state.LastError != message {
t.Fatalf("last error = %v, want %q", state.LastError, message)
}
if err := store.MarkTaskCIAutoFixExhausted(
ctx, "task-1", "repo-1", 42, "CI auto-fix paused after the round limit",
); err != nil {
t.Fatalf("record auto-fix exhaustion: %v", err)
}
state, err = store.GetTaskCIPRState(ctx, "task-1", "repo-1", 42)
if err != nil {
t.Fatalf("get auto-fix exhaustion state: %v", err)
}
if state.LastError == nil || *state.LastError != "CI auto-fix paused after the round limit" ||
state.LastErrorKind != TaskCIErrorKindAutoFix {
t.Fatalf("auto-fix error did not replace merge error atomically: %+v", state)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.3
func TestStoreTaskCIMergeAttemptResultIsSignatureBound(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
for _, signature := range []string{"ready-head-a", "ready-head-b"} {
if err := store.RecordTaskCIMergeAttempt(ctx, TaskCIMergeAttempt{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
Signature: signature, AttemptedHeadSHA: strings.TrimPrefix(signature, "ready-"),
}); err != nil {
t.Fatalf("reserve %s: %v", signature, err)
}
}
err := store.RecordTaskCIMergeAttemptResult(
ctx, "task-1", "repo-1", 42, "ready-head-a", TaskCIMergeResultAccepted, "",
)
if !errors.Is(err, ErrTaskCIMergeAttemptNotFound) {
t.Fatalf("stale result error = %v, want attempt not found", err)
}
state, err := store.GetTaskCIPRState(ctx, "task-1", "repo-1", 42)
if err != nil {
t.Fatalf("get current attempt: %v", err)
}
if state.LastMergeSignature != "ready-head-b" || state.LastMergeResult != TaskCIMergeResultInFlight {
t.Fatalf("current attempt was overwritten: %+v", state)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.2
func TestStoreTaskCIMergeAttemptReservationIsConcurrentSafe(t *testing.T) {
store := newTestStore(t)
start := make(chan struct{})
results := make(chan error, 2)
attempt := TaskCIMergeAttempt{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
Signature: "ready-head-a", AttemptedHeadSHA: "head-a",
}
var wg sync.WaitGroup
for range 2 {
wg.Add(1)
go func() {
defer wg.Done()
<-start
results <- store.RecordTaskCIMergeAttempt(context.Background(), attempt)
}()
}
close(start)
wg.Wait()
close(results)
reserved, blocked := 0, 0
for err := range results {
switch {
case err == nil:
reserved++
case errors.Is(err, ErrTaskCIMergeAttemptAlreadyReserved):
blocked++
default:
t.Fatalf("reserve merge attempt: %v", err)
}
}
if reserved != 1 || blocked != 1 {
t.Fatalf("reserved=%d blocked=%d, want one each", reserved, blocked)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.8
func TestStoreTaskCIAutoMergeErrorKindBackfillIsNarrow(t *testing.T) {
store := newTestStore(t)
now := time.Now().UTC()
for _, row := range []struct {
repositoryID string
message string
}{
{repositoryID: "known", message: "merge PR: GitHub unavailable"},
{repositoryID: "unknown", message: "review prompt failed"},
} {
if _, err := store.db.Exec(`
INSERT INTO github_task_ci_pr_state (
task_id, repository_id, pr_number, last_error, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?)`,
"task-1", row.repositoryID, 42, row.message, now, now); err != nil {
t.Fatalf("seed %s error: %v", row.repositoryID, err)
}
}
if err := store.backfillTaskCIAutoMergeErrorKinds(); err != nil {
t.Fatalf("backfill error kinds: %v", err)
}
known, err := store.GetTaskCIPRState(context.Background(), "task-1", "known", 42)
if err != nil {
t.Fatalf("get known error: %v", err)
}
unknown, err := store.GetTaskCIPRState(context.Background(), "task-1", "unknown", 42)
if err != nil {
t.Fatalf("get unknown error: %v", err)
}
if known.LastErrorKind != TaskCIErrorKindAutoMerge {
t.Fatalf("known error kind = %q, want auto_merge", known.LastErrorKind)
}
if unknown.LastErrorKind != "" {
t.Fatalf("unknown error kind = %q, want empty", unknown.LastErrorKind)
}
}
func TestStoreTaskCIPRState_MarkExhaustedAndResetOnReenable(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
+7 -5
View File
@@ -1,6 +1,7 @@
package github
import (
"context"
"fmt"
"net/http"
"time"
@@ -32,11 +33,12 @@ type TokenPrincipal struct {
// token source. The token itself remains private while principal metadata is
// available for authorization, rate-limit, cache, and attribution keys.
type TokenClient struct {
token string
httpClient *http.Client
username string // cached after first GetAuthenticatedUser call
rateTracker *RateTracker
principal TokenPrincipal
token string
httpClient *http.Client
username string // cached after first GetAuthenticatedUser call
rateTracker *RateTracker
principal TokenPrincipal
mergePollWait func(context.Context, time.Duration) error
}
// PATClient remains an alias so existing callers retain source compatibility.
@@ -6,6 +6,7 @@ import (
"fmt"
"strconv"
"strings"
"sync"
"time"
"go.uber.org/zap"
@@ -61,12 +62,14 @@ type GitHubService interface {
RecordTaskCIFixAttempt(ctx context.Context, attempt github.TaskCIFixAttempt) error
RefreshTaskCIFixCheckpoint(ctx context.Context, taskID, repositoryID string, prNumber int, signature, checkpointJSON string) error
RecordTaskCIMergeAttempt(ctx context.Context, attempt github.TaskCIMergeAttempt) error
RecordTaskCIMergeAttemptResult(ctx context.Context, taskID, repositoryID string, prNumber int, signature, result, message string) error
RecordTaskCIMergeQueueObservation(ctx context.Context, observation github.TaskCIMergeQueueObservation) error
RecordTaskCIError(ctx context.Context, taskID, repositoryID string, prNumber int, message string) error
RecordTaskCIAutoMergeError(ctx context.Context, taskID, repositoryID string, prNumber int, message string) error
MarkTaskCIAutoFixExhausted(ctx context.Context, taskID, repositoryID string, prNumber int, message string) error
ClearTaskCIError(ctx context.Context, taskID, repositoryID string, prNumber int) error
GetPRFeedbackForAutomation(ctx context.Context, workspaceID, owner, repo string, number int) (*github.PRFeedback, error)
MergePRForAutomation(ctx context.Context, workspaceID, owner, repo string, number int, mergeMethod string) error
MergePRForAutomation(ctx context.Context, workspaceID, owner, repo string, number int, mergeMethod, expectedHeadSHA string) error
ListActivePRWatches(ctx context.Context) ([]*github.PRWatch, error)
ReserveReviewPRTask(ctx context.Context, watchID, repoOwner, repoName string, prNumber int, prURL string) (bool, error)
AssignReviewPRTaskID(ctx context.Context, watchID, repoOwner, repoName string, prNumber int, taskID string) error
@@ -299,24 +302,135 @@ func (s *Service) startTaskPRCIAutomationWithRefresh(ctx context.Context, pr *gi
if pr == nil {
return
}
s.ciAutomationMu.Lock()
if s.ciAutomationStopped {
s.ciAutomationMu.Unlock()
return
}
if s.ciAutomationCtx == nil {
s.ciAutomationCtx, s.ciAutomationCancel = context.WithCancel(context.Background())
}
workerCtx := s.ciAutomationCtx
s.ciAutomationWorkers.Add(1)
s.ciAutomationMu.Unlock()
key := fmt.Sprintf("%s|%s|%d", pr.TaskID, pr.RepositoryID, pr.PRNumber)
if _, loaded := s.ciAutomationInFlight.LoadOrStore(key, struct{}{}); loaded {
s.logger.Debug("CI automation already in flight",
request := ciAutomationRequest{ctx: ctx, pr: pr, refresh: refresh}
if !s.ciAutomationInFlight.Enqueue(key, request) {
s.ciAutomationWorkers.Done()
s.logger.Debug("CI automation follow-up coalesced",
zap.String("task_id", pr.TaskID),
zap.String("repository_id", pr.RepositoryID),
zap.Int("pr_number", pr.PRNumber))
return
}
go func() {
defer s.ciAutomationInFlight.Delete(key)
automationCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), ciAutomationDetachedTimeout)
defer cancel()
if err := s.handleTaskPRCIAutomationWithRefresh(automationCtx, pr, refresh); err != nil {
s.logger.Debug("CI automation handling failed", zap.String("task_id", pr.TaskID), zap.Error(err))
defer s.ciAutomationWorkers.Done()
for {
if workerCtx.Err() != nil {
return
}
automationCtx, cancel := context.WithTimeout(workerCtx, ciAutomationDetachedTimeout)
err := s.handleTaskPRCIAutomationWithRefresh(automationCtx, request.pr, request.refresh)
cancel()
if err != nil {
s.logger.Debug("CI automation handling failed", zap.String("task_id", request.pr.TaskID), zap.Error(err))
}
var ok bool
request, ok = s.ciAutomationInFlight.Next(key)
if !ok {
return
}
}
}()
}
type ciAutomationRequest struct {
ctx context.Context
pr *github.TaskPR
refresh bool
}
type ciAutomationWork struct {
pending *ciAutomationRequest
}
// ciAutomationCoordinator owns the per-PR worker lifecycle. Enqueue returns
// true only to the caller that must start the worker. Later requests replace
// the single pending follow-up while preserving the strongest refresh need.
type ciAutomationCoordinator struct {
mu sync.Mutex
works map[string]*ciAutomationWork
}
func (c *ciAutomationCoordinator) Enqueue(key string, request ciAutomationRequest) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.works == nil {
c.works = make(map[string]*ciAutomationWork)
}
if work, ok := c.works[key]; ok {
if work.pending != nil && work.pending.refresh {
request.refresh = true
}
work.pending = &request
return false
}
c.works[key] = &ciAutomationWork{}
return true
}
func (c *ciAutomationCoordinator) Next(key string) (ciAutomationRequest, bool) {
c.mu.Lock()
defer c.mu.Unlock()
work, ok := c.works[key]
if !ok {
return ciAutomationRequest{}, false
}
if work.pending != nil {
request := *work.pending
work.pending = nil
return request, true
}
delete(c.works, key)
return ciAutomationRequest{}, false
}
// Has reports whether a worker is currently active for key. It is intentionally
// read-only so tests can observe coalescing without exposing coordinator state.
func (c *ciAutomationCoordinator) Has(key string) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, exists := c.works[key]
return exists
}
func (s *Service) resetCIAutomationWorkers() {
s.ciAutomationMu.Lock()
defer s.ciAutomationMu.Unlock()
s.ciAutomationStopped = false
s.ciAutomationCtx, s.ciAutomationCancel = context.WithCancel(context.Background())
}
func (s *Service) stopCIAutomationWorkers() {
s.ciAutomationMu.Lock()
s.ciAutomationStopped = true
cancel := s.ciAutomationCancel
s.ciAutomationMu.Unlock()
if cancel != nil {
cancel()
}
done := make(chan struct{})
go func() {
s.ciAutomationWorkers.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(sendNowClaimRecoveryTimeout):
s.logger.Warn("timed out waiting for CI automation workers during shutdown")
}
}
// handleNewReviewPR creates a task for a new PR needing review.
// Auto-start is determined by the workflow step's on_enter actions.
func (s *Service) handleNewReviewPR(ctx context.Context, event *bus.Event) error {
@@ -120,10 +120,10 @@ func (s *Service) handleTaskPRCIAutomationWithRefresh(ctx context.Context, pr *g
if options.AutoFixEnabled && ciAutomationCanAutoFixFromFeedback(pr) {
autoFixBlockedMerge, autoFixError = s.handleTaskPRCIAutoFix(ctx, pr, options)
}
ciError := ""
ciError := ciAutomationMergeOutcome{}
if !autoFixBlockedMerge && options.AutoMergeEnabled && ciAutomationReadyToMerge(pr) {
if !freshlySynced {
ciError = "PR status is not freshly synced for auto-merge"
ciError = ciAutomationMergeOutcome{message: "PR status is not freshly synced for auto-merge"}
} else {
ciError = s.handleTaskPRCIAutoMerge(ctx, pr)
}
@@ -133,8 +133,8 @@ func (s *Service) handleTaskPRCIAutomationWithRefresh(ctx context.Context, pr *g
s.recordCIAutomationError(ctx, pr, autoFixError)
s.publishTaskCIOptionsState(ctx, pr.TaskID)
}
if ciError != "" {
s.recordCIAutomationError(ctx, pr, ciError)
if ciError.message != "" && !ciError.journaled {
s.recordCIAutoMergeError(ctx, pr, ciError.message)
s.publishTaskCIOptionsState(ctx, pr.TaskID)
}
return nil
@@ -390,20 +390,22 @@ func (s *Service) handleTaskPRCIAutoFixEmptyDelta(ctx context.Context, pr *githu
return false
}
func (s *Service) handleTaskPRCIAutoMerge(ctx context.Context, pr *github.TaskPR) string {
type ciAutomationMergeOutcome struct {
message string
journaled bool
}
func (s *Service) handleTaskPRCIAutoMerge(ctx context.Context, pr *github.TaskPR) ciAutomationMergeOutcome {
if ciAutomationHasActiveMergeQueueEntry(pr) {
return ""
return ciAutomationMergeOutcome{}
}
signature := ciAutomationMergeSignature(pr)
state, err := s.githubService.GetTaskCIPRState(ctx, pr.TaskID, pr.RepositoryID, pr.PRNumber)
if err != nil {
s.logger.Debug("load CI automation merge state failed; attempting merge without dedupe", zap.String("task_id", pr.TaskID), zap.Error(err))
s.logger.Debug("load CI automation merge state failed; durable reservation will decide", zap.String("task_id", pr.TaskID), zap.Error(err))
} else if state != nil {
if state.LastMergeSignature == signature {
return ""
}
if pr.HeadSHA != "" && state.LastQueueAttemptHeadSHA == pr.HeadSHA {
return ""
if outcome, handled := s.ciAutomationExistingMergeOutcome(ctx, pr, signature, state); handled {
return outcome
}
}
attempt := github.TaskCIMergeAttempt{
@@ -414,18 +416,81 @@ func (s *Service) handleTaskPRCIAutoMerge(ctx context.Context, pr *github.TaskPR
AttemptedAt: time.Now().UTC(),
AttemptedHeadSHA: pr.HeadSHA,
}
if err := s.githubService.MergePRForAutomation(
ctx, pr.WorkspaceID, pr.Owner, pr.Repo, pr.PRNumber, "",
); err != nil {
return fmt.Sprintf("merge PR: %v", err)
if err := s.githubService.RecordTaskCIMergeAttempt(context.WithoutCancel(ctx), attempt); err != nil {
if errors.Is(err, github.ErrTaskCIMergeAttemptAlreadyReserved) {
return ciAutomationMergeOutcome{}
}
return ciAutomationMergeOutcome{message: fmt.Sprintf("reserve merge PR attempt: %v", err)}
}
_ = s.githubService.RecordTaskCIMergeAttempt(context.WithoutCancel(ctx), attempt)
_ = s.githubService.ClearTaskCIError(context.WithoutCancel(ctx), pr.TaskID, pr.RepositoryID, pr.PRNumber)
return ""
return s.executeCIAutoMerge(ctx, pr, signature)
}
func (s *Service) ciAutomationExistingMergeOutcome(
ctx context.Context,
pr *github.TaskPR,
signature string,
state *github.TaskCIPRAutomationState,
) (ciAutomationMergeOutcome, bool) {
if state.LastMergeSignature != signature {
return ciAutomationQueueAttemptOutcome(pr, state)
}
if state.LastMergeResult == github.TaskCIMergeResultInFlight &&
state.LastMergeAttemptAt != nil && time.Since(*state.LastMergeAttemptAt) > ciAutomationDetachedTimeout {
message := "merge PR: previous automatic merge attempt did not reach a terminal state"
if recordErr := s.githubService.RecordTaskCIMergeAttemptResult(
context.WithoutCancel(ctx), pr.TaskID, pr.RepositoryID, pr.PRNumber,
signature, github.TaskCIMergeResultFailed, message,
); recordErr != nil {
return ciAutomationMergeOutcome{message: fmt.Sprintf("%s; record expired merge attempt: %v", message, recordErr)}, true
}
if !state.MergeRetryPending {
return ciAutomationMergeOutcome{message: message, journaled: true}, true
}
}
if !state.MergeRetryPending {
return ciAutomationMergeOutcome{}, true
}
return ciAutomationQueueAttemptOutcome(pr, state)
}
func ciAutomationQueueAttemptOutcome(
pr *github.TaskPR,
state *github.TaskCIPRAutomationState,
) (ciAutomationMergeOutcome, bool) {
if pr.HeadSHA != "" && state.LastQueueAttemptHeadSHA == pr.HeadSHA && !state.MergeRetryPending {
return ciAutomationMergeOutcome{}, true
}
return ciAutomationMergeOutcome{}, false
}
func (s *Service) executeCIAutoMerge(
ctx context.Context,
pr *github.TaskPR,
signature string,
) ciAutomationMergeOutcome {
if err := s.githubService.MergePRForAutomation(
ctx, pr.WorkspaceID, pr.Owner, pr.Repo, pr.PRNumber, "", pr.HeadSHA,
); err != nil {
message := fmt.Sprintf("merge PR: %v", err)
if recordErr := s.githubService.RecordTaskCIMergeAttemptResult(
context.WithoutCancel(ctx), pr.TaskID, pr.RepositoryID, pr.PRNumber,
signature, github.TaskCIMergeResultFailed, message,
); recordErr != nil {
return ciAutomationMergeOutcome{message: fmt.Sprintf("%s; record failed merge attempt: %v", message, recordErr)}
}
return ciAutomationMergeOutcome{message: message, journaled: true}
}
if err := s.githubService.RecordTaskCIMergeAttemptResult(
context.WithoutCancel(ctx), pr.TaskID, pr.RepositoryID, pr.PRNumber,
signature, github.TaskCIMergeResultAccepted, "",
); err != nil {
return ciAutomationMergeOutcome{message: fmt.Sprintf("record accepted merge PR attempt: %v", err)}
}
return ciAutomationMergeOutcome{}
}
func (s *Service) recordTaskPRMergeQueueObservation(ctx context.Context, pr *github.TaskPR) {
if pr == nil || (pr.MergeQueueLastRemovalID == "" && !ciAutomationHasActiveMergeQueueEntry(pr)) {
if pr == nil || (pr.MergeQueueLastRemovalID == "" && !ciAutomationHasActiveMergeQueueEntry(pr) && pr.State != githubPRStateMerged) {
return
}
removal, _ := ciAutomationQueueRemovalSnapshot(pr)
@@ -435,6 +500,7 @@ func (s *Service) recordTaskPRMergeQueueObservation(ctx context.Context, pr *git
PRNumber: pr.PRNumber,
RemovalEventID: pr.MergeQueueLastRemovalID,
RemovalObservedHeadSHA: pr.HeadSHA,
Accepted: pr.State == githubPRStateMerged,
}
if ciAutomationHasActiveMergeQueueEntry(pr) {
observation.ActiveQueueHeadSHA = pr.MergeQueueEntryHeadSHA
@@ -518,6 +584,19 @@ func (s *Service) recordCIAutomationError(ctx context.Context, pr *github.TaskPR
}
}
func (s *Service) recordCIAutoMergeError(ctx context.Context, pr *github.TaskPR, message string) {
s.logger.Warn("CI auto-merge error",
zap.String("task_id", pr.TaskID),
zap.String("repository_id", pr.RepositoryID),
zap.Int("pr_number", pr.PRNumber),
zap.String("error", message))
if err := s.githubService.RecordTaskCIAutoMergeError(
context.WithoutCancel(ctx), pr.TaskID, pr.RepositoryID, pr.PRNumber, message,
); err != nil {
s.logger.Debug("record CI auto-merge error failed", zap.String("task_id", pr.TaskID), zap.Error(err))
}
}
func ciAutomationCanAutoFixFromFeedback(pr *github.TaskPR) bool {
return pr != nil && pr.State != taskPRAgentEventClosed && pr.State != taskPRAgentEventMerged
}
@@ -909,7 +988,30 @@ func encodeCIAutomationCheckpoint(checkpoint ciAutomationCheckpoint) (string, st
}
func ciAutomationMergeSignature(pr *github.TaskPR) string {
payload := fmt.Sprintf("%s|%s|%d|%s|%s|%d|%d|%s|%s|%s|%d|%d", pr.TaskID, pr.RepositoryID, pr.PRNumber, pr.HeadSHA, pr.HeadBranch, pr.Additions, pr.Deletions, pr.ChecksState, pr.ReviewState, pr.MergeableState, pr.ReviewCount, pr.UnresolvedReviewThreads)
sum := sha256.Sum256([]byte(payload))
requiredReviews := 0
requiredReviewsObserved := pr.RequiredReviews != nil
if pr.RequiredReviews != nil {
requiredReviews = *pr.RequiredReviews
}
payload, _ := json.Marshal(struct {
TaskID, RepositoryID, HeadSHA, HeadBranch, State string
PRNumber, Additions, Deletions int
ChecksState, ReviewState, MergeableState string
ReviewCount, PendingReviewCount int
RequiredReviewsObserved bool
RequiredReviews, ChecksTotal, ChecksPassing int
UnresolvedReviewThreads int
}{
TaskID: pr.TaskID, RepositoryID: pr.RepositoryID, PRNumber: pr.PRNumber,
HeadSHA: pr.HeadSHA, HeadBranch: pr.HeadBranch,
State: pr.State,
Additions: pr.Additions, Deletions: pr.Deletions,
ChecksState: pr.ChecksState, ReviewState: pr.ReviewState, MergeableState: pr.MergeableState,
ReviewCount: pr.ReviewCount, PendingReviewCount: pr.PendingReviewCount,
RequiredReviewsObserved: requiredReviewsObserved, RequiredReviews: requiredReviews,
ChecksTotal: pr.ChecksTotal, ChecksPassing: pr.ChecksPassing,
UnresolvedReviewThreads: pr.UnresolvedReviewThreads,
})
sum := sha256.Sum256(payload)
return hex.EncodeToString(sum[:])
}
@@ -82,7 +82,7 @@ func (s *autoMergeFailureThenReviewRequestService) MergePRForAutomation(
_ string,
owner, repo string,
number int,
method string,
method, _ string,
) error {
return s.MergePR(ctx, owner, repo, number, method)
}
@@ -91,10 +91,22 @@ func (s *storeBackedLifecycleGitHubService) GetTaskCIPRState(ctx context.Context
return s.store.GetTaskCIPRState(ctx, taskID, repositoryID, prNumber)
}
func (s *storeBackedLifecycleGitHubService) RecordTaskCIMergeAttemptResult(
ctx context.Context, taskID, repositoryID string, prNumber int, signature, result, message string,
) error {
return s.store.RecordTaskCIMergeAttemptResult(ctx, taskID, repositoryID, prNumber, signature, result, message)
}
func (s *storeBackedLifecycleGitHubService) RecordTaskCIError(ctx context.Context, taskID, repositoryID string, prNumber int, message string) error {
return s.store.RecordTaskCIError(ctx, taskID, repositoryID, prNumber, message)
}
func (s *storeBackedLifecycleGitHubService) RecordTaskCIAutoMergeError(
ctx context.Context, taskID, repositoryID string, prNumber int, message string,
) error {
return s.store.RecordTaskCIAutoMergeError(ctx, taskID, repositoryID, prNumber, message)
}
func (s *storeBackedLifecycleGitHubService) ClearTaskCIError(ctx context.Context, taskID, repositoryID string, prNumber int) error {
return s.store.ClearTaskCIError(ctx, taskID, repositoryID, prNumber)
}
@@ -1228,6 +1240,7 @@ func TestHandleTaskPRCIAutomationAutoMergeUsesFreshSync(t *testing.T) {
fresh.ChecksState = "success"
fresh.ReviewState = "approved"
fresh.MergeableState = "clean"
fresh.HeadSHA = "reviewed-head"
now := time.Now().UTC()
fresh.LastSyncedAt = &now
ghSvc := &mockGitHubService{
@@ -1248,6 +1261,9 @@ func TestHandleTaskPRCIAutomationAutoMergeUsesFreshSync(t *testing.T) {
if ghSvc.mergeCalls != 1 {
t.Fatalf("expected merge from fresh synced PR state, got %d", ghSvc.mergeCalls)
}
if ghSvc.mergeExpectedHeadSHA != "reviewed-head" {
t.Fatalf("expected head SHA = %q, want reviewed-head", ghSvc.mergeExpectedHeadSHA)
}
}
func TestHandleTaskPRCIAutomationAutoMergeUsesPartialSyncMatch(t *testing.T) {
@@ -1266,6 +1282,7 @@ func TestHandleTaskPRCIAutomationAutoMergeUsesPartialSyncMatch(t *testing.T) {
ChecksState: "success",
ReviewState: "approved",
MergeableState: "clean",
HeadSHA: "head-a",
LastSyncedAt: &now,
}
ghSvc := &mockGitHubService{
@@ -1323,6 +1340,9 @@ func TestHandleTaskPRCIAutomationAutoMergeRequiresFreshSync(t *testing.T) {
if len(ghSvc.ciErrors) != 1 || ghSvc.ciErrors[0].LastError == nil || !strings.Contains(*ghSvc.ciErrors[0].LastError, "not freshly synced") {
t.Fatalf("expected stale sync error to be recorded, got %+v", ghSvc.ciErrors)
}
if ghSvc.ciErrors[0].LastErrorKind != github.TaskCIErrorKindAutoMerge {
t.Fatalf("error kind = %q, want auto_merge", ghSvc.ciErrors[0].LastErrorKind)
}
}
func TestCIAutomationHasFreshPRStatusAt(t *testing.T) {
@@ -2496,6 +2516,36 @@ func TestCIAutomationMergeSignatureIgnoresVolatileUpdatedAt(t *testing.T) {
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.3
func TestCIAutomationMergeSignatureIncludesEveryReadinessGate(t *testing.T) {
required := 1
base := github.TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42, HeadSHA: "head-a",
ChecksState: "success", ReviewState: "approved", MergeableState: "clean",
ReviewCount: 1, RequiredReviews: &required, ChecksTotal: 2, ChecksPassing: 2,
}
before := ciAutomationMergeSignature(&base)
tests := []struct {
name string
mutate func(*github.TaskPR)
}{
{name: "PR lifecycle state", mutate: func(pr *github.TaskPR) { pr.State = "closed" }},
{name: "pending reviews", mutate: func(pr *github.TaskPR) { pr.PendingReviewCount++ }},
{name: "required review presence", mutate: func(pr *github.TaskPR) { pr.RequiredReviews = nil }},
{name: "required review value", mutate: func(pr *github.TaskPR) { value := 2; pr.RequiredReviews = &value }},
{name: "pending check count", mutate: func(pr *github.TaskPR) { pr.ChecksPassing-- }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
changed := base
test.mutate(&changed)
if after := ciAutomationMergeSignature(&changed); after == before {
t.Fatalf("signature did not change for %s", test.name)
}
})
}
}
func TestHandleTaskPRCIAutomationRecordsErrorWhenNoPromptableSession(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
@@ -2617,7 +2667,7 @@ func TestHandleTaskPRCIAutomationMergesWhenStateReadFails(t *testing.T) {
}
}
func TestHandleTaskPRCIAutomationRetriesMergeAfterTransientFailure(t *testing.T) {
func TestHandleTaskPRCIAutomationDoesNotRetryUnchangedMergeAfterFailure(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task-1", "session-1", models.TaskSessionStateRunning)
@@ -2640,6 +2690,7 @@ func TestHandleTaskPRCIAutomationRetriesMergeAfterTransientFailure(t *testing.T)
ChecksState: "success",
ReviewState: "approved",
MergeableState: "clean",
HeadSHA: "head-a",
}
now := time.Now().UTC()
pr.LastSyncedAt = &now
@@ -2651,16 +2702,147 @@ func TestHandleTaskPRCIAutomationRetriesMergeAfterTransientFailure(t *testing.T)
if ghSvc.mergeCalls != 1 {
t.Fatalf("expected one merge call, got %d", ghSvc.mergeCalls)
}
if len(ghSvc.mergeAttempts) != 0 {
t.Fatalf("expected failed merge not to record dedupe signature, got %+v", ghSvc.mergeAttempts)
if len(ghSvc.mergeAttempts) != 1 {
t.Fatalf("expected failed merge to keep one reservation, got %+v", ghSvc.mergeAttempts)
}
ghSvc.mergeErr = nil
if err := svc.handleTaskPRCIAutomation(ctx, pr); err != nil {
t.Fatalf("retry auto-merge: %v", err)
}
if ghSvc.mergeCalls != 2 || len(ghSvc.mergeAttempts) != 1 {
t.Fatalf("expected retry to merge and record one attempt, calls=%d attempts=%d", ghSvc.mergeCalls, len(ghSvc.mergeAttempts))
if ghSvc.mergeCalls != 1 || len(ghSvc.mergeAttempts) != 1 {
t.Fatalf("expected unchanged failure to remain blocked, calls=%d attempts=%d", ghSvc.mergeCalls, len(ghSvc.mergeAttempts))
}
pr.HeadSHA = "head-b"
ghSvc.triggerPRSyncAllPRs = []*github.TaskPR{pr}
if err := svc.handleTaskPRCIAutomation(ctx, pr); err != nil {
t.Fatalf("merge changed head: %v", err)
}
if ghSvc.mergeCalls != 2 || len(ghSvc.mergeAttempts) != 2 {
t.Fatalf("expected changed head to rearm once, calls=%d attempts=%d", ghSvc.mergeCalls, len(ghSvc.mergeAttempts))
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.5
func TestRecordTaskPRMergeQueueObservationReconcilesMergedPR(t *testing.T) {
svc := &Service{}
message := "merge PR: provider status was lost"
ghSvc := &mockGitHubService{ciPRState: &github.TaskCIPRAutomationState{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
LastMergeResult: github.TaskCIMergeResultFailed,
LastError: &message, LastErrorKind: github.TaskCIErrorKindAutoMerge,
}}
svc.SetGitHubService(ghSvc)
svc.recordTaskPRMergeQueueObservation(context.Background(), &github.TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
State: githubPRStateMerged, HeadSHA: "head-a",
})
if ghSvc.ciPRState.LastMergeResult != github.TaskCIMergeResultAccepted ||
ghSvc.ciPRState.LastError != nil || ghSvc.ciPRState.LastErrorKind != "" {
t.Fatalf("merged reconciliation state = %+v", ghSvc.ciPRState)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.4
func TestHandleTaskPRCIAutomationConsumesExplicitMergeRetryAuthorization(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task-1", "session-1", models.TaskSessionStateRunning)
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
now := time.Now().UTC()
pr := &github.TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "acme", Repo: "widget", PRNumber: 42,
State: "open", ChecksState: "success", ReviewState: "approved", MergeableState: "clean",
HeadSHA: "head-a", LastSyncedAt: &now,
}
ghSvc := &mockGitHubService{
ciOptionsResp: &github.TaskCIOptionsResponse{TaskID: "task-1", AutoMergeEnabled: true},
triggerPRSyncAllPRs: []*github.TaskPR{pr},
ciPRState: &github.TaskCIPRAutomationState{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
LastMergeSignature: ciAutomationMergeSignature(pr),
LastMergeResult: github.TaskCIMergeResultFailed,
LastQueueAttemptHeadSHA: pr.HeadSHA,
MergeRetryPending: true,
},
}
svc.SetGitHubService(ghSvc)
if err := svc.handleTaskPRCIAutomation(ctx, pr); err != nil {
t.Fatalf("handle explicit merge retry: %v", err)
}
if ghSvc.mergeCalls != 1 || len(ghSvc.mergeAttempts) != 1 {
t.Fatalf("merge calls = %d attempts = %d, want one", ghSvc.mergeCalls, len(ghSvc.mergeAttempts))
}
if ghSvc.ciPRState.MergeRetryPending {
t.Fatal("explicit retry authorization was not consumed")
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.2
func TestHandleTaskPRCIAutomationExpiresStaleInFlightMergeWithoutResubmission(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task-1", "session-1", models.TaskSessionStateRunning)
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
now := time.Now().UTC()
pr := &github.TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "acme", Repo: "widget", PRNumber: 42,
State: "open", ChecksState: "success", ReviewState: "approved", MergeableState: "clean",
HeadSHA: "head-a", LastSyncedAt: &now,
}
staleAttempt := now.Add(-ciAutomationDetachedTimeout - time.Second)
ghSvc := &mockGitHubService{
ciOptionsResp: &github.TaskCIOptionsResponse{TaskID: "task-1", AutoMergeEnabled: true},
triggerPRSyncAllPRs: []*github.TaskPR{pr},
ciPRState: &github.TaskCIPRAutomationState{
TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 42,
LastMergeSignature: ciAutomationMergeSignature(pr),
LastMergeResult: github.TaskCIMergeResultInFlight, LastMergeAttemptAt: &staleAttempt,
},
}
svc.SetGitHubService(ghSvc)
if err := svc.handleTaskPRCIAutomation(ctx, pr); err != nil {
t.Fatalf("handle stale in-flight merge: %v", err)
}
if ghSvc.mergeCalls != 0 {
t.Fatalf("merge calls = %d, want no resubmission", ghSvc.mergeCalls)
}
if ghSvc.ciPRState.LastMergeResult != github.TaskCIMergeResultFailed {
t.Fatalf("merge result = %q, want failed", ghSvc.ciPRState.LastMergeResult)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.6
func TestHandleTaskPRCIAutomationReservationFailurePreventsProviderCall(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task-1", "session-1", models.TaskSessionStateRunning)
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
now := time.Now().UTC()
pr := &github.TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "acme", Repo: "widget", PRNumber: 42,
State: "open", ChecksState: "success", ReviewState: "approved", MergeableState: "clean",
HeadSHA: "head-a", LastSyncedAt: &now,
}
ghSvc := &mockGitHubService{
ciOptionsResp: &github.TaskCIOptionsResponse{TaskID: "task-1", AutoMergeEnabled: true},
triggerPRSyncAllPRs: []*github.TaskPR{pr},
mergeAttemptErr: errors.New("state store unavailable"),
}
svc.SetGitHubService(ghSvc)
if err := svc.handleTaskPRCIAutomation(ctx, pr); err != nil {
t.Fatalf("handle reservation failure: %v", err)
}
if ghSvc.mergeCalls != 0 {
t.Fatalf("merge calls = %d, want zero", ghSvc.mergeCalls)
}
if len(ghSvc.ciErrors) != 1 || ghSvc.ciErrors[0].LastErrorKind != github.TaskCIErrorKindAutoMerge {
t.Fatalf("typed retryable error = %+v", ghSvc.ciErrors)
}
}
@@ -2698,10 +2880,10 @@ func TestHandlePRFeedbackStartsAutomationForMatchingPR(t *testing.T) {
if ghSvc.lastExactPRLookup.Owner != "acme" || ghSvc.lastExactPRLookup.Repo != "back" || ghSvc.lastExactPRLookup.PRNumber != 2 {
t.Fatalf("unexpected exact lookup: %+v", ghSvc.lastExactPRLookup)
}
if _, loaded := svc.ciAutomationInFlight.Load("task-1|repo-back|2"); !loaded {
if !svc.ciAutomationInFlight.Has("task-1|repo-back|2") {
t.Fatal("expected automation to run for matching repo-back PR")
}
if _, loaded := svc.ciAutomationInFlight.Load("task-1|repo-front|1"); loaded {
if svc.ciAutomationInFlight.Has("task-1|repo-front|1") {
t.Fatal("unexpected automation for non-matching repo-front PR")
}
close(block)
@@ -2734,10 +2916,10 @@ func TestHandleTaskCIOptionsUpdatedStartsAutomationForTaskPRs(t *testing.T) {
t.Fatalf("handle CI options updated: %v", err)
}
<-started
if _, loaded := svc.ciAutomationInFlight.Load("task-1|repo-front|1"); !loaded {
if !svc.ciAutomationInFlight.Has("task-1|repo-front|1") {
t.Fatal("expected automation to run for repo-front PR")
}
if _, loaded := svc.ciAutomationInFlight.Load("task-1|repo-back|2"); !loaded {
if !svc.ciAutomationInFlight.Has("task-1|repo-back|2") {
t.Fatal("expected automation to run for repo-back PR")
}
close(block)
@@ -2839,7 +3021,7 @@ func TestHandleTaskCIOptionsUpdatedStartsAutomationForPartialSyncResults(t *test
case <-time.After(200 * time.Millisecond):
t.Fatal("timed out waiting for CI automation to start")
}
if _, loaded := svc.ciAutomationInFlight.Load("task-1|repo-1|42"); !loaded {
if !svc.ciAutomationInFlight.Has("task-1|repo-1|42") {
t.Fatal("expected automation to run for partial sync result")
}
if len(ghSvc.ciErrors) != 0 {
@@ -2948,7 +3130,7 @@ func waitForCIAutomationIdle(t *testing.T, svc *Service, key string, timeout tim
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
for {
if _, loaded := svc.ciAutomationInFlight.Load(key); !loaded {
if !svc.ciAutomationInFlight.Has(key) {
return
}
select {
@@ -108,8 +108,10 @@ type mockGitHubService struct {
fixAttempts []github.TaskCIFixAttempt
fixCheckpointRefresh []github.TaskCIFixAttempt
mergeAttempts []github.TaskCIMergeAttempt
mergeAttemptErr error
mergeCalls int
mergeErr error
mergeExpectedHeadSHA string
ciErrors []github.TaskCIPRAutomationState
ciExhausted []github.TaskCIPRAutomationState
lifecyclePrompts []github.TaskPRLifecyclePrompt
@@ -217,7 +219,40 @@ func (m *mockGitHubService) RefreshTaskCIFixCheckpoint(_ context.Context, taskID
return nil
}
func (m *mockGitHubService) RecordTaskCIMergeAttempt(_ context.Context, attempt github.TaskCIMergeAttempt) error {
if m.mergeAttemptErr != nil {
return m.mergeAttemptErr
}
if m.ciPRState != nil && m.ciPRState.LastMergeSignature == attempt.Signature && !m.ciPRState.MergeRetryPending {
return github.ErrTaskCIMergeAttemptAlreadyReserved
}
m.mergeAttempts = append(m.mergeAttempts, attempt)
if m.ciPRState == nil {
m.ciPRState = &github.TaskCIPRAutomationState{
TaskID: attempt.TaskID, RepositoryID: attempt.RepositoryID, PRNumber: attempt.PRNumber,
}
}
m.ciPRState.LastMergeSignature = attempt.Signature
m.ciPRState.LastMergeResult = github.TaskCIMergeResultInFlight
m.ciPRState.MergeRetryPending = false
m.ciPRState.LastMergeAttemptAt = &attempt.AttemptedAt
return nil
}
func (m *mockGitHubService) RecordTaskCIMergeAttemptResult(
_ context.Context, taskID, repositoryID string, prNumber int, signature, result, message string,
) error {
if m.ciPRState == nil {
m.ciPRState = &github.TaskCIPRAutomationState{
TaskID: taskID, RepositoryID: repositoryID, PRNumber: prNumber,
}
}
if m.ciPRState.LastMergeSignature != "" && m.ciPRState.LastMergeSignature != signature {
return github.ErrTaskCIMergeAttemptNotFound
}
m.ciPRState.LastMergeResult = result
if result == github.TaskCIMergeResultFailed {
m.ciPRState.LastError = &message
m.ciPRState.LastErrorKind = github.TaskCIErrorKindAutoMerge
}
return nil
}
func (m *mockGitHubService) RecordTaskCIMergeQueueObservation(_ context.Context, observation github.TaskCIMergeQueueObservation) error {
@@ -229,6 +264,13 @@ func (m *mockGitHubService) RecordTaskCIMergeQueueObservation(_ context.Context,
if observation.ActiveQueueHeadSHA != "" {
m.ciPRState.LastQueueAttemptHeadSHA = observation.ActiveQueueHeadSHA
}
if observation.ActiveQueueHeadSHA != "" || observation.Accepted {
m.ciPRState.LastMergeResult = github.TaskCIMergeResultAccepted
if m.ciPRState.LastErrorKind == github.TaskCIErrorKindAutoMerge {
m.ciPRState.LastError = nil
m.ciPRState.LastErrorKind = ""
}
}
if observation.RemovalCause != "" {
m.ciPRState.LastQueueRemovalCause = observation.RemovalCause
}
@@ -243,6 +285,13 @@ func (m *mockGitHubService) RecordTaskCIError(_ context.Context, taskID, reposit
})
return nil
}
func (m *mockGitHubService) RecordTaskCIAutoMergeError(_ context.Context, taskID, repositoryID string, prNumber int, message string) error {
m.ciErrors = append(m.ciErrors, github.TaskCIPRAutomationState{
TaskID: taskID, RepositoryID: repositoryID, PRNumber: prNumber,
LastError: &message, LastErrorKind: github.TaskCIErrorKindAutoMerge,
})
return nil
}
func (m *mockGitHubService) MarkTaskCIAutoFixExhausted(_ context.Context, taskID, repositoryID string, prNumber int, message string) error {
now := time.Now().UTC()
m.ciExhausted = append(m.ciExhausted, github.TaskCIPRAutomationState{
@@ -251,6 +300,7 @@ func (m *mockGitHubService) MarkTaskCIAutoFixExhausted(_ context.Context, taskID
PRNumber: prNumber,
AutoFixExhaustedAt: &now,
LastError: &message,
LastErrorKind: github.TaskCIErrorKindAutoFix,
})
return nil
}
@@ -315,8 +365,9 @@ func (m *mockGitHubService) MergePR(context.Context, string, string, int, string
}
func (m *mockGitHubService) MergePRForAutomation(
ctx context.Context, _, owner, repo string, number int, method string,
ctx context.Context, _, owner, repo string, number int, method, expectedHeadSHA string,
) error {
m.mergeExpectedHeadSHA = expectedHeadSHA
return m.MergePR(ctx, owner, repo, number, method)
}
func (m *mockGitHubService) EnsurePRWatch(_ context.Context, _, _, _, _, _, branch string) (*github.PRWatch, error) {
+17 -3
View File
@@ -665,9 +665,9 @@ type Service struct {
// GitHub service for PR auto-detection on push
githubService GitHubService
// ciAutomationInFlight prevents PR feedback and task-PR update events from
// racing duplicate auto-fix prompts or merge calls for the same PR.
ciAutomationInFlight sync.Map
// ciAutomationInFlight serializes each PR's evaluation and coalesces one
// follow-up request instead of dropping an event that arrives mid-run.
ciAutomationInFlight ciAutomationCoordinator
// GitLab MR lifecycle notification automation. Nil-safe: without it,
// gitlab.task_mr.updated events are observed but no lifecycle prompt is
@@ -1051,6 +1051,15 @@ type Service struct {
sendNowCancel context.CancelFunc
sendNowStopped bool
sendNowWorkers sync.WaitGroup
// ciAutomationWorkers owns the asynchronous per-PR automation loops. The
// service-owned context lets Stop cancel in-flight evaluations and prevents
// workers from outliving the orchestrator across a restart.
ciAutomationMu sync.Mutex
ciAutomationCtx context.Context
ciAutomationCancel context.CancelFunc
ciAutomationStopped bool
ciAutomationWorkers sync.WaitGroup
}
type RouteAction string
@@ -1219,6 +1228,7 @@ func NewService(
// Create the service (watcher will be created after we have handlers)
sendNowCtx, sendNowCancel := context.WithCancel(context.Background())
ciAutomationCtx, ciAutomationCancel := context.WithCancel(context.Background())
s := &Service{
config: cfg,
logger: svcLogger,
@@ -1238,6 +1248,8 @@ func NewService(
reservedPromptCallbacks: newReservedPromptCallbackOwner(),
sendNowCtx: sendNowCtx,
sendNowCancel: sendNowCancel,
ciAutomationCtx: ciAutomationCtx,
ciAutomationCancel: ciAutomationCancel,
idleReaper: newIdleSessionReaper(),
}
// Always publish queue-status after a task-scoped queue purge so the
@@ -2369,6 +2381,7 @@ func (s *Service) Start(ctx context.Context) error {
s.logger.Info("starting orchestrator service")
s.resetReservedPromptCallbacks()
s.resetSendNowWorkers()
s.resetCIAutomationWorkers()
// Reconcile session state from persisted runtime state on startup.
// This does NOT launch any agent processes — sessions are recovered lazily
@@ -2502,6 +2515,7 @@ func (s *Service) Stop() error {
s.cancelAllClarificationWatchdogs()
s.cancelAllTransientRetries()
s.stopSendNowWorkers()
s.stopCIAutomationWorkers()
if len(errs) > 0 {
return errs[0]
@@ -78,13 +78,15 @@ type GitSummary struct {
// PullRequestSummary is intentionally an aggregate plus one representative
// identity. It is not a list of PR records.
type PullRequestSummary struct {
Count int `json:"count,omitempty"`
OpenCount int `json:"open_count,omitempty"`
Attention bool `json:"attention,omitempty"`
AggregateState string `json:"aggregate_state,omitempty"`
State string `json:"state,omitempty"`
Number int `json:"number,omitempty"`
URL string `json:"url,omitempty"`
Count int `json:"count,omitempty"`
OpenCount int `json:"open_count,omitempty"`
Attention bool `json:"attention,omitempty"`
AutoFixEnabled bool `json:"auto_fix_enabled,omitempty"`
AutoMergeEnabled bool `json:"auto_merge_enabled,omitempty"`
AggregateState string `json:"aggregate_state,omitempty"`
State string `json:"state,omitempty"`
Number int `json:"number,omitempty"`
URL string `json:"url,omitempty"`
}
// StoredTaskStatusSummary is the persistence boundary for one task. The
@@ -189,6 +189,8 @@ type pullRequestObservation struct {
requiredReviews int
checksTotal int
checksPassing int
autoFixEnabled bool
autoMergeEnabled bool
}
func NewProjector(cfg ProjectorConfig) *Projector {
@@ -244,6 +246,7 @@ func (p *Projector) Start(ctx context.Context) error {
events.BuildPermissionRequestWildcardSubject(),
events.BuildGitEventWildcardSubject(),
events.GitHubTaskPRUpdated,
events.GitHubTaskCIOptionsUpdated,
events.MessageQueueStatusChanged,
}
for _, pattern := range patterns {
@@ -331,6 +334,14 @@ func (p *Projector) handleEvent(ctx context.Context, event *bus.Event) error {
}
return fmt.Errorf("task status summary %q has no workspace", taskID)
}
pullRequestChanged := false
if event.Type == events.GitHubTaskCIOptionsUpdated && p.loadPullRequests != nil {
before := derivePullRequestSummary(state)
if err := p.restorePullRequestObservations(ctx, taskID, state); err != nil {
return err
}
pullRequestChanged = !equalPullRequestSummary(before, derivePullRequestSummary(state))
}
taskErrorChanged := false
if p.loadTaskLaunchError != nil && isTaskErrorRefreshEvent(event.Type) {
taskErrorChanged, err = p.refreshTaskLaunchError(ctx, taskID, state)
@@ -359,11 +370,11 @@ func (p *Projector) handleEvent(ctx context.Context, event *bus.Event) error {
if refreshErr != nil {
return refreshErr
}
changed := p.applySourceEventLocked(state, event.Type, data) || pendingChanged || taskErrorChanged
changed := p.applySourceEventLocked(state, event.Type, data) || pendingChanged || taskErrorChanged || pullRequestChanged
return p.persistPendingRefreshLocked(ctx, taskID, state, changed, event.Type, data)
}
changed := p.applySourceEventLocked(state, event.Type, data) || taskErrorChanged
changed := p.applySourceEventLocked(state, event.Type, data) || taskErrorChanged || pullRequestChanged
if !changed {
return nil
}
@@ -777,6 +777,21 @@ func (p *Projector) applyPREventLocked(state *projectionState, data map[string]i
checksTotal: intValueOrZero(data["checks_total"]),
checksPassing: intValueOrZero(data["checks_passing"]),
}
// PR refresh events do not carry the per-PR automation switches. Preserve
// the last authoritative values from the CI-options projection instead of
// treating an omitted field as an explicit disable. A future producer may
// include either field; in that case its bool is authoritative, including
// false.
if existing, ok := state.prs[key]; ok {
observation.autoFixEnabled = existing.autoFixEnabled
observation.autoMergeEnabled = existing.autoMergeEnabled
}
if value, ok := data["auto_fix_enabled"].(bool); ok {
observation.autoFixEnabled = value
}
if value, ok := data["auto_merge_enabled"].(bool); ok {
observation.autoMergeEnabled = value
}
if value, ok := intValue(data["required_reviews"]); ok {
observation.requiredReviews = maxInt(value, 0)
}
@@ -31,6 +31,8 @@ func applyPullRequestInputs(state *projectionState, inputs []PullRequestInput) {
requiredReviews: maxInt(input.RequiredReviews, 0),
checksTotal: maxInt(input.ChecksTotal, 0),
checksPassing: maxInt(input.ChecksPassing, 0),
autoFixEnabled: input.AutoFixEnabled,
autoMergeEnabled: input.AutoMergeEnabled,
}
}
}
@@ -52,6 +54,12 @@ func derivePullRequestSummary(state *projectionState) *PullRequestSummary {
summary.Count++
if strings.EqualFold(observation.state, prStateOpen) {
summary.OpenCount++
if observation.autoFixEnabled {
summary.AutoFixEnabled = true
}
if observation.autoMergeEnabled {
summary.AutoMergeEnabled = true
}
}
if pullRequestNeedsAttention(observation) {
summary.Attention = true
@@ -71,6 +79,13 @@ func derivePullRequestSummary(state *projectionState) *PullRequestSummary {
return &summary
}
func equalPullRequestSummary(left, right *PullRequestSummary) bool {
if left == nil || right == nil {
return left == right
}
return *left == *right
}
func pullRequestNeedsAttention(pr pullRequestObservation) bool {
if strings.EqualFold(pr.reviewState, prStateChanges) ||
strings.EqualFold(pr.checksState, prStateFailure) ||
@@ -102,6 +102,96 @@ func TestProjectorRehydratesPullRequestObservationsAfterRestartWithoutAggregate(
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10
func TestProjectorRefreshesAutomationFlagsAfterCIOptionsUpdate(t *testing.T) {
store := newProjectorTestStore()
store.rows["task-pr-options-refresh"] = &StoredTaskStatusSummary{
TaskID: "task-pr-options-refresh",
WorkspaceID: "workspace-1",
Summary: TaskStatusSummary{
Revision: 1,
PullRequest: &PullRequestSummary{
Count: 1, OpenCount: 1, State: prStateOpen, Number: 41,
AutoFixEnabled: true,
},
},
}
loaderCalls := 0
projector := NewProjector(ProjectorConfig{
Store: store,
ResolveWorkspace: func(context.Context, string) (string, error) {
return "workspace-1", nil
},
LoadPullRequests: func(context.Context, string) ([]PullRequestInput, error) {
loaderCalls++
return []PullRequestInput{{
Key: "repo-a#41", State: prStateOpen, Number: 41,
AutoFixEnabled: loaderCalls == 1,
}}, nil
},
Now: func() time.Time { return time.Date(2026, 8, 16, 0, 30, 0, 0, time.UTC) },
})
if err := projector.HandleEvent(context.Background(), bus.NewEvent(events.GitHubTaskCIOptionsUpdated, "test", map[string]interface{}{
"task_id": "task-pr-options-refresh", "workspace_id": "workspace-1",
})); err != nil {
t.Fatalf("replay CI options event: %v", err)
}
updated := store.summary("task-pr-options-refresh")
if updated == nil || updated.PullRequest == nil || updated.PullRequest.AutoFixEnabled {
t.Fatalf("updated summary = %+v, want auto-fix disabled", updated)
}
if loaderCalls != 2 {
t.Fatalf("PR loader calls = %d, want initial load plus options refresh", loaderCalls)
}
}
func TestProjectorPreservesAutomationFlagsAcrossPRRefresh(t *testing.T) {
store := newProjectorTestStore()
loaderCalls := 0
projector := NewProjector(ProjectorConfig{
Store: store,
ResolveWorkspace: func(context.Context, string) (string, error) {
return "workspace-1", nil
},
LoadPullRequests: func(context.Context, string) ([]PullRequestInput, error) {
loaderCalls++
return []PullRequestInput{{
Key: "repo-a#41", State: prStateOpen, Number: 41,
AutoFixEnabled: loaderCalls > 1,
}}, nil
},
Now: func() time.Time { return time.Date(2026, 8, 16, 0, 30, 0, 0, time.UTC) },
})
prEvent := func() *bus.Event {
return bus.NewEvent(events.GitHubTaskPRUpdated, "test", map[string]interface{}{
"task_id": "task-pr-options-preserve", "workspace_id": "workspace-1",
"repository_id": "repo-a", "state": prStateOpen, "pr_number": 41,
"pr_url": "https://example.test/41",
})
}
if err := projector.HandleEvent(context.Background(), prEvent()); err != nil {
t.Fatalf("initial PR refresh: %v", err)
}
if err := projector.HandleEvent(context.Background(), bus.NewEvent(events.GitHubTaskCIOptionsUpdated, "test", map[string]interface{}{
"task_id": "task-pr-options-preserve", "workspace_id": "workspace-1",
})); err != nil {
t.Fatalf("CI options refresh: %v", err)
}
if err := projector.HandleEvent(context.Background(), prEvent()); err != nil {
t.Fatalf("subsequent PR refresh: %v", err)
}
got := store.summary("task-pr-options-preserve")
if got == nil || got.PullRequest == nil || !got.PullRequest.AutoFixEnabled {
t.Fatalf("PR summary after refresh = %+v, want auto-fix preserved", got)
}
if loaderCalls != 2 {
t.Fatalf("PR loader calls = %d, want initial load plus options refresh", loaderCalls)
}
}
func TestProjectorRehydratesSourceObservationsWithoutPersistedSummary(t *testing.T) {
store := newProjectorTestStore()
sessionLoaderCalls := 0
@@ -41,6 +41,8 @@ type PullRequestInput struct {
RequiredReviews int
ChecksTotal int
ChecksPassing int
AutoFixEnabled bool
AutoMergeEnabled bool
}
// RebuildInput contains the authoritative bounded facts available from
@@ -86,6 +86,44 @@ func TestBuildFromAuthoritativeAggregatesDurableSources(t *testing.T) {
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10
func TestBuildFromAuthoritativeAggregatesAutomationOnlyForOpenPullRequests(t *testing.T) {
got := BuildFromAuthoritative(RebuildInput{
PRObserved: true,
PullRequests: []PullRequestInput{
{Key: "repo-a#1", State: prStateOpen, Number: 1, AutoFixEnabled: true},
{Key: "repo-a#2", State: prStateOpen, Number: 2, AutoMergeEnabled: true},
{Key: "repo-a#3", State: prStateMerged, Number: 3, AutoFixEnabled: true, AutoMergeEnabled: true},
{Key: "repo-a#4", State: prStateClosed, Number: 4, AutoFixEnabled: true, AutoMergeEnabled: true},
},
})
if got.PullRequest == nil {
t.Fatal("pull request summary is nil")
}
if !got.PullRequest.AutoFixEnabled || !got.PullRequest.AutoMergeEnabled {
t.Fatalf("automation flags = %+v, want both active flags", got.PullRequest)
}
}
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10
func TestBuildFromAuthoritativeOmitsAutomationForTerminalPullRequests(t *testing.T) {
got := BuildFromAuthoritative(RebuildInput{
PRObserved: true,
PullRequests: []PullRequestInput{
{Key: "repo-a#3", State: prStateMerged, Number: 3, AutoFixEnabled: true},
{Key: "repo-a#4", State: prStateClosed, Number: 4, AutoMergeEnabled: true},
},
})
if got.PullRequest == nil {
t.Fatal("pull request summary is nil")
}
if got.PullRequest.AutoFixEnabled || got.PullRequest.AutoMergeEnabled {
t.Fatalf("terminal automation flags = %+v, want both false", got.PullRequest)
}
}
func TestDeriveForegroundActivityPrefersGeneratingOverBackground(t *testing.T) {
got := deriveForegroundActivity([]string{activityBackground, activityGenerating})
if got != activityGenerating {
@@ -0,0 +1,113 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
const hookMocks = vi.hoisted(() => ({
error: null as string | null,
options: null as TaskCIAutomationOptions | null,
refresh: vi.fn(),
retryMerge: vi.fn(),
}));
vi.mock("@/hooks/domains/github/use-task-ci-options", () => ({
useTaskCIAutomationOptions: () => ({
options: hookMocks.options,
loading: false,
saving: false,
error: hookMocks.error,
refresh: hookMocks.refresh,
retryMerge: hookMocks.retryMerge,
update: vi.fn(),
resetPrompt: vi.fn(),
}),
}));
vi.mock("@/components/toast-provider", () => ({
useToast: () => ({ toast: vi.fn() }),
}));
vi.mock("@/components/github/pr-ci-automation-prompt-dialog", () => ({
CIAutomationPromptDialog: () => null,
}));
vi.mock("@/components/github/pr-ci-automation-rows", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/components/github/pr-ci-automation-rows")>();
return {
...actual,
CIAutomationHeader: () => null,
CIAutomationOptionRows: () => null,
};
});
import { PRCIAutomationControls } from "./pr-ci-automation-controls";
const pr = {
task_id: "task-1",
repository_id: "repo-1",
pr_number: 42,
} as TaskPR;
function makeOptions(errorKind: string): TaskCIAutomationOptions {
return {
task_id: "task-1",
auto_fix_enabled: false,
auto_merge_enabled: true,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: "Default prompt",
using_default_prompt: true,
updated_at: "2026-08-28T10:00:00Z",
pr_options: [],
pr_states: [
{
task_id: "task-1",
repository_id: "repo-1",
pr_number: 42,
last_error: "merge PR: provider unavailable",
last_error_kind: errorKind,
} as TaskCIAutomationOptions["pr_states"][number],
],
};
}
beforeEach(() => {
hookMocks.error = null;
hookMocks.options = makeOptions("auto_merge");
hookMocks.refresh.mockReset().mockResolvedValue(null);
hookMocks.retryMerge.mockReset().mockResolvedValue({ accepted: true });
});
afterEach(cleanup);
describe("PRCIAutomationControls retry actions", () => {
it("rearms only a typed auto-merge error for the exact linked PR", () => {
render(<PRCIAutomationControls pr={pr} />);
const action = screen.getByRole("button", { name: "Retry" });
expect(action.className).toContain("h-11");
fireEvent.click(action);
expect(hookMocks.retryMerge).toHaveBeenCalledWith("repo-1", 42);
expect(hookMocks.refresh).not.toHaveBeenCalled();
});
it("refreshes state for a stored error that is not an auto-merge failure", () => {
hookMocks.options = makeOptions("auto_fix");
render(<PRCIAutomationControls pr={pr} />);
fireEvent.click(screen.getByRole("button", { name: "Refresh" }));
expect(hookMocks.refresh).toHaveBeenCalledTimes(1);
expect(hookMocks.retryMerge).not.toHaveBeenCalled();
});
it("refreshes state after a load error and never rearms merge", () => {
hookMocks.options = null;
hookMocks.error = "backend unavailable";
render(<PRCIAutomationControls pr={pr} />);
fireEvent.click(screen.getByRole("button", { name: "Refresh" }));
expect(hookMocks.refresh).toHaveBeenCalledTimes(1);
expect(hookMocks.retryMerge).not.toHaveBeenCalled();
});
});
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { useToast } from "@/components/toast-provider";
import { useTaskCIAutomationOptions } from "@/hooks/domains/github/use-task-ci-options";
import {
@@ -17,9 +18,10 @@ import {
} from "@/components/github/pr-ci-automation-rows";
export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
const { options, loading, saving, error, refresh, update, resetPrompt } =
const { options, loading, saving, error, refresh, update, resetPrompt, retryMerge } =
useTaskCIAutomationOptions(pr.task_id);
const { toast } = useToast();
const { t } = useTranslation();
const [promptOpen, setPromptOpen] = useState(false);
const [promptDraft, setPromptDraft] = useState("");
const automationState = findCIAutomationStateForPR(options?.pr_states, pr);
@@ -48,9 +50,11 @@ export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
repository_id: pr.repository_id ?? "",
pr_number: pr.pr_number,
};
Promise.resolve(update(scoped)).catch(() => reportError("Failed to update CI automation."));
Promise.resolve(update(scoped)).catch(() =>
reportError(t("github:failedToUpdateCiAutomation")),
);
},
[pr, reportError, update],
[pr, reportError, t, update],
);
// The auto-fix prompt override stays task-level (applies to every linked
@@ -60,18 +64,26 @@ export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
if (!value) return;
Promise.resolve(update({ auto_fix_prompt_override: value }))
.then(() => setPromptOpen(false))
.catch(() => reportError("Failed to save auto-fix prompt."));
}, [promptDraft, reportError, update]);
.catch(() => reportError(t("github:failedToSaveAutoFixPrompt")));
}, [promptDraft, reportError, t, update]);
const useDefaultPrompt = useCallback(() => {
Promise.resolve(resetPrompt())
.then(() => setPromptOpen(false))
.catch(() => reportError("Failed to reset auto-fix prompt."));
}, [reportError, resetPrompt]);
.catch(() => reportError(t("github:failedToResetAutoFixPrompt")));
}, [reportError, resetPrompt, t]);
const retryLoad = useCallback(() => {
Promise.resolve(refresh()).catch(() => reportError("Failed to load CI automation."));
}, [refresh, reportError]);
Promise.resolve(refresh()).catch(() =>
reportError(t("github:failedToLoadCiAutomationOptions")),
);
}, [refresh, reportError, t]);
const retryAutoMerge = useCallback(() => {
Promise.resolve(retryMerge(pr.repository_id ?? "", pr.pr_number))
.then(() => toast({ description: t("github:autoMergeRetryAccepted") }))
.catch(() => reportError(t("github:failedToRetryAutoMerge")));
}, [pr.pr_number, pr.repository_id, reportError, retryMerge, t, toast]);
const disabled = loading || saving || !options;
return (
@@ -93,14 +105,17 @@ export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
patchOption={patchOption}
automationState={automationState}
/>
{automationState?.last_error && (
<CIAutomationErrorRow
error={automationState.last_error}
loading={loading}
onRetry={retryLoad}
/>
)}
{error && <CIAutomationErrorRow error={error} loading={loading} onRetry={retryLoad} />}
<PRCIAutomationErrors
storedError={automationState?.last_error}
storedErrorKind={automationState?.last_error_kind}
loadError={error}
loading={loading}
saving={saving}
retryLabel={t("github:retry")}
refreshLabel={t("github:refresh")}
onRetryMerge={retryAutoMerge}
onRefresh={retryLoad}
/>
<CIAutomationPromptDialog
open={promptOpen}
prompt={promptDraft}
@@ -113,3 +128,47 @@ export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
</div>
);
}
function PRCIAutomationErrors({
storedError,
storedErrorKind,
loadError,
loading,
saving,
retryLabel,
refreshLabel,
onRetryMerge,
onRefresh,
}: {
storedError?: string | null;
storedErrorKind?: string;
loadError?: string | null;
loading: boolean;
saving: boolean;
retryLabel: string;
refreshLabel: string;
onRetryMerge: () => void;
onRefresh: () => void;
}) {
const mergeError = storedErrorKind === "auto_merge";
return (
<>
{storedError && (
<CIAutomationErrorRow
error={storedError}
loading={loading || saving}
actionLabel={mergeError ? retryLabel : refreshLabel}
onAction={mergeError ? onRetryMerge : onRefresh}
/>
)}
{loadError && (
<CIAutomationErrorRow
error={loadError}
loading={loading}
actionLabel={refreshLabel}
onAction={onRefresh}
/>
)}
</>
);
}
@@ -104,13 +104,14 @@ export function CIAutomationRow({
export function CIAutomationErrorRow({
error,
loading,
onRetry,
actionLabel,
onAction,
}: {
error: string;
loading: boolean;
onRetry: () => void;
actionLabel: string;
onAction: () => void;
}) {
const { t } = useTranslation();
return (
<div
role="alert"
@@ -121,12 +122,12 @@ export function CIAutomationErrorRow({
type="button"
variant="ghost"
size="sm"
className="h-6 cursor-pointer gap-1 px-2 text-[11px]"
className="h-11 min-w-11 cursor-pointer gap-1 px-2 text-[11px] sm:h-6 sm:min-w-0"
disabled={loading}
onClick={onRetry}
onClick={onAction}
>
<IconRefresh className={`h-3 w-3 ${loading ? "animate-spin" : ""}`} />
{t("github:retry")}
{actionLabel}
</Button>
</div>
);
@@ -290,7 +290,9 @@ describe("PRCIPopover automation status", () => {
auto_fix_exhausted_at: null,
last_merge_signature: "",
last_merge_attempt_at: null,
last_merge_result: "",
last_error: "No promptable task session is available.",
last_error_kind: "",
created_at: "",
updated_at: "",
},
@@ -338,10 +340,12 @@ describe("PRCIPopover automation status", () => {
auto_fix_exhausted_at: null,
last_merge_signature: "",
last_merge_attempt_at: null,
last_merge_result: "",
last_queue_attempt_head_sha: "head-a",
last_queue_fix_event_id: "",
last_queue_removal_cause: "provider_changed",
last_error: null,
last_error_kind: "",
created_at: "",
updated_at: "",
},
@@ -599,12 +603,12 @@ describe("PRCIPopover task prompts", () => {
expect(hookMocks.updateMock).not.toHaveBeenCalled();
});
it("offers retry after CI automation options fail to load", () => {
it("offers refresh after CI automation options fail to load", () => {
hookMocks.error = BACKEND_UNAVAILABLE;
renderPopover();
expect(screen.getByText(BACKEND_UNAVAILABLE)).not.toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
fireEvent.click(screen.getByRole("button", { name: "Refresh" }));
expect(hookMocks.refreshMock).toHaveBeenCalledTimes(1);
});
@@ -143,7 +143,9 @@ function makeCIPrState(roundCount: number, exhausted = false) {
auto_fix_exhausted_at: exhausted ? "2026-06-18T11:00:00Z" : null,
last_merge_signature: "",
last_merge_attempt_at: null,
last_merge_result: "" as const,
last_error: exhausted ? "CI auto-fix paused after 10 rounds for this PR" : null,
last_error_kind: "",
created_at: "2026-06-18T10:00:00Z",
updated_at: "2026-06-18T10:00:00Z",
};
@@ -0,0 +1,51 @@
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
import { automationForPR } from "./pr-status-automation-badges";
import type { TaskPRInfo } from "@/components/task/task-pr-info";
export type { TaskPRInfo } from "@/components/task/task-pr-info";
export type TaskPRAutomationDetail = {
number: number;
repository?: string;
autoFixEnabled: boolean;
autoMergeEnabled: boolean;
};
export type TaskPRAutomationSummary = {
autoFixEnabled: boolean;
autoMergeEnabled: boolean;
details: TaskPRAutomationDetail[];
};
export function getTaskPRAutomationSummary(
prs: TaskPR[],
prInfo?: TaskPRInfo,
options?: TaskCIAutomationOptions | null,
): TaskPRAutomationSummary {
const activePRs = prs.filter((pr) => pr.state.trim().toLowerCase() === "open");
// The bounded task-row projection is the source of truth until the full PR
// list is hydrated. Keep its flags visible even when a previously hydrated
// options response is present but the scoped PR records are not.
if (!options || prs.length === 0) {
return {
autoFixEnabled: prInfo?.autoFixEnabled === true,
autoMergeEnabled: prInfo?.autoMergeEnabled === true,
details: [],
};
}
const details = activePRs.map((pr) => {
const automation = automationForPR(options, pr);
const repository = [pr.owner, pr.repo].filter(Boolean).join("/") || undefined;
return {
number: pr.pr_number,
...(repository ? { repository } : {}),
autoFixEnabled: automation.autoFix,
autoMergeEnabled: automation.autoMerge,
};
});
return {
autoFixEnabled: details.some((detail) => detail.autoFixEnabled),
autoMergeEnabled: details.some((detail) => detail.autoMergeEnabled),
details,
};
}
@@ -0,0 +1,312 @@
"use client";
import { IconGitPullRequest } from "@tabler/icons-react";
import {
forwardRef,
type FocusEventHandler,
type MouseEventHandler,
type PointerEventHandler,
type ReactNode,
type Ref,
} from "react";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@kandev/ui/drawer";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import type { TaskPR } from "@/lib/types/github";
import type { TaskPRTooltipHydrationStatus } from "@/hooks/domains/github/use-task-pr-tooltip-hydration";
import { useChangeRequestTaskTooltipState } from "@/components/integrations/use-change-request-task-tooltip-state";
import type { TaskPRAutomationSummary, TaskPRInfo } from "./pr-task-automation";
export type PRTaskIconDisclosureProps = {
taskId: string;
prInfo?: TaskPRInfo;
prs: TaskPR[];
hasFullData: boolean;
singlePR: TaskPR | null;
readyToMerge: boolean;
allReadyToMerge: boolean;
displayState: string | undefined;
displayCount: number;
iconColor: string;
ariaLabel: string;
icon: ReactNode;
content: ReactNode;
};
export function AutomationIndicatorDots({
autoFixEnabled,
autoMergeEnabled,
}: Pick<TaskPRAutomationSummary, "autoFixEnabled" | "autoMergeEnabled">) {
return (
<>
{autoFixEnabled && (
<span
data-testid="pr-task-automation-auto-fix"
className="absolute left-0 top-0 h-1.5 w-1.5 rounded-full bg-yellow-400 ring-1 ring-background"
aria-hidden="true"
/>
)}
{autoMergeEnabled && (
<span
data-testid="pr-task-automation-auto-merge"
className="absolute right-0 top-0 h-1.5 w-1.5 rounded-full bg-purple-500 ring-1 ring-background"
aria-hidden="true"
/>
)}
</>
);
}
export function PRTaskIconGlyph({ automation }: { automation: TaskPRAutomationSummary }) {
return (
<span className="relative inline-flex h-3.5 w-3.5 shrink-0">
<IconGitPullRequest aria-hidden="true" className="h-3.5 w-3.5" />
<AutomationIndicatorDots
autoFixEnabled={automation.autoFixEnabled}
autoMergeEnabled={automation.autoMergeEnabled}
/>
</span>
);
}
export function PRTaskIconDrawer({
open,
onOpenChange,
t,
...props
}: PRTaskIconDisclosureProps & {
open: boolean;
onOpenChange: (open: boolean) => void;
t: ReturnType<typeof useTranslation>["t"];
}) {
const { prs, prInfo, singlePR, content } = props;
return (
<Drawer open={open} onOpenChange={onOpenChange}>
<DrawerTrigger asChild>
<PRTaskIconTrigger
{...props}
touch
open={open}
onClick={(event) => event.stopPropagation()}
/>
</DrawerTrigger>
<DrawerContent
data-testid={`pr-task-automation-drawer-${props.taskId}`}
className="max-h-[80dvh] flex flex-col"
>
<DrawerHeader className="shrink-0 border-b py-2">
<DrawerTitle className="text-sm">
{prs.length > 1
? t("github:pullRequestCount", { count: prs.length })
: t("github:pullRequestStatus", { number: singlePR?.pr_number ?? prInfo?.number })}
</DrawerTitle>
<DrawerDescription className="sr-only">
{t("github:pullRequestCiStatusReviewsAnd")}
</DrawerDescription>
</DrawerHeader>
<div className="min-h-0 flex-1 overflow-y-auto p-3" data-vaul-no-drag>
{content}
</div>
</DrawerContent>
</Drawer>
);
}
export function PRTaskIconTooltip({
tooltip,
...props
}: PRTaskIconDisclosureProps & {
tooltip: ReturnType<typeof useChangeRequestTaskTooltipState>;
}) {
return (
<Tooltip open={tooltip.open}>
<TooltipTrigger asChild>
<PRTaskIconTrigger
{...props}
onPointerEnter={tooltip.onPointerEnter}
onPointerLeave={tooltip.onPointerLeave}
onFocus={tooltip.onFocus}
onBlur={tooltip.onBlur}
/>
</TooltipTrigger>
<TooltipContent
sideOffset={6}
onEscapeKeyDown={tooltip.onEscapeKeyDown}
className="w-80 max-w-[calc(100vw-1rem)] p-3"
>
{props.content}
</TooltipContent>
</Tooltip>
);
}
type PRTaskIconTriggerProps = PRTaskIconDisclosureProps & {
touch?: boolean;
open?: boolean;
onClick?: MouseEventHandler<HTMLButtonElement>;
onPointerEnter?: PointerEventHandler<HTMLSpanElement>;
onPointerLeave?: PointerEventHandler<HTMLSpanElement>;
onFocus?: FocusEventHandler<HTMLSpanElement>;
onBlur?: FocusEventHandler<HTMLSpanElement>;
};
export const PRTaskIconTrigger = forwardRef<HTMLElement, PRTaskIconTriggerProps>(
function PRTaskIconTrigger(
{
touch = false,
open = false,
onClick,
taskId,
prInfo: _prInfo,
prs,
hasFullData,
singlePR: _singlePR,
readyToMerge,
allReadyToMerge,
displayState,
displayCount,
iconColor,
ariaLabel,
icon,
content: _content,
onPointerEnter,
onPointerLeave,
onFocus,
onBlur,
...triggerAttributes
},
ref: Ref<HTMLElement>,
) {
const commonAttributes = {
"data-testid": `pr-task-icon-${taskId}`,
"data-pr-state": displayState,
"data-pr-count": displayCount,
"data-pr-ready-to-merge": hasFullData
? String(prs.length === 1 ? readyToMerge : allReadyToMerge)
: undefined,
"aria-label": ariaLabel,
};
const contents = (
<span className="inline-flex items-center gap-0.5">
{icon}
{prs.length > 1 ? (
<span className="text-[9px] font-semibold leading-none tabular-nums">{prs.length}</span>
) : null}
</span>
);
if (touch) {
return (
<button
ref={ref as Ref<HTMLButtonElement>}
type="button"
{...triggerAttributes}
{...commonAttributes}
aria-haspopup="dialog"
aria-expanded={open}
className={cn(
"relative inline-flex h-3.5 w-3.5 shrink-0 cursor-pointer items-center justify-center [@media(pointer:coarse)]:after:absolute [@media(pointer:coarse)]:after:-inset-[15px] [@media(pointer:coarse)]:after:content-['']",
iconColor,
)}
onPointerDown={(event) => event.stopPropagation()}
onClick={onClick}
>
{contents}
</button>
);
}
return (
<span
ref={ref as Ref<HTMLSpanElement>}
{...triggerAttributes}
{...commonAttributes}
role="img"
tabIndex={0}
className={cn("inline-flex shrink-0 items-center", prs.length > 1 && "gap-0.5", iconColor)}
onPointerEnter={onPointerEnter}
onPointerLeave={onPointerLeave}
onFocus={onFocus}
onBlur={onBlur}
>
{contents}
</span>
);
},
);
export function TaskPRAutomationDetails({
summary,
status,
}: {
summary: TaskPRAutomationSummary;
status?: TaskPRTooltipHydrationStatus;
}) {
const { t } = useTranslation();
const hasAutomation = summary.autoFixEnabled || summary.autoMergeEnabled;
if (!hasAutomation && summary.details.length === 0) return null;
const detailContent =
summary.details.length > 0 ? (
<div className="mt-1 space-y-1">
{summary.details.map((detail) => (
<div
key={`${detail.repository ?? ""}-${detail.number}`}
className="flex flex-wrap items-center gap-x-2 gap-y-1"
>
<span className="font-medium">
{detail.repository
? t("github:prTaskStatusRepositoryNumber", {
repository: detail.repository,
number: detail.number,
})
: t("github:prTaskStatusNumber", { number: detail.number })}
</span>
{detail.autoFixEnabled && (
<span className="text-yellow-500">{t("github:autoFix")}</span>
)}
{detail.autoMergeEnabled && (
<span className="text-purple-400">{t("github:autoMerge")}</span>
)}
</div>
))}
</div>
) : null;
const loadingContent =
status === "loading" || status === "idle" ? (
<p className="mt-1 text-muted-foreground">{t("github:taskPrDetailsLoading")}</p>
) : null;
return (
<section
data-testid="pr-task-automation-details"
className="mt-2 border-t border-border/60 pt-2 text-xs"
>
<h4 className="font-medium text-foreground">{t("github:automation")}</h4>
{detailContent ?? loadingContent}
</section>
);
}
export function CompactPRTooltipContent({ status }: { status: TaskPRTooltipHydrationStatus }) {
const { t } = useTranslation();
if (status === "loading" || status === "idle") {
return (
<span data-testid="pr-task-tooltip-loading" className="text-sm text-muted-foreground">
{t("github:taskPrDetailsLoading")}
</span>
);
}
if (status === "unavailable") {
return (
<span data-testid="pr-task-tooltip-unavailable" className="text-sm text-muted-foreground">
{t("github:taskPrDetailsUnavailable")}
</span>
);
}
return null;
}
@@ -0,0 +1,163 @@
import { describe, expect, it } from "vitest";
import { getTaskPRAutomationSummary } from "./pr-task-icon";
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
return {
id: "id",
workspace_id: "workspace-1",
task_id: "task",
owner: "o",
repo: "r",
pr_number: 1,
pr_url: "",
pr_title: "Test PR",
head_branch: "feat",
base_branch: "main",
author_login: "alice",
state: "open",
review_state: "",
checks_state: "",
mergeable_state: "",
review_count: 0,
pending_review_count: 0,
comment_count: 0,
unresolved_review_threads: 0,
checks_total: 0,
checks_passing: 0,
additions: 0,
deletions: 0,
created_at: "",
merged_at: null,
closed_at: null,
last_synced_at: null,
updated_at: "",
...overrides,
};
}
function makeOptions(): TaskCIAutomationOptions {
return {
task_id: "task",
workspace_id: "workspace-1",
auto_fix_enabled: false,
auto_merge_enabled: false,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: "",
using_default_prompt: true,
updated_at: "2026-08-01T00:00:00Z",
pr_states: [],
pr_options: [
{
task_id: "task",
repository_id: "repo-a",
pr_number: 1,
auto_fix_enabled: true,
auto_merge_enabled: false,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
created_at: "",
updated_at: "",
},
{
task_id: "task",
repository_id: "repo-b",
pr_number: 2,
auto_fix_enabled: false,
auto_merge_enabled: true,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
created_at: "",
updated_at: "",
},
{
task_id: "task",
repository_id: "repo-c",
pr_number: 3,
auto_fix_enabled: true,
auto_merge_enabled: true,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
created_at: "",
updated_at: "",
},
],
};
}
describe("getTaskPRAutomationSummary", () => {
it("aggregates independent active PR settings and ignores terminal PRs", () => {
const summary = getTaskPRAutomationSummary(
[
makePR({ repository_id: "repo-a", pr_number: 1 }),
makePR({ repository_id: "repo-b", pr_number: 2 }),
makePR({ repository_id: "repo-c", pr_number: 3, state: "merged" }),
],
undefined,
makeOptions(),
);
expect(summary).toEqual({
autoFixEnabled: true,
autoMergeEnabled: true,
details: [
{ number: 1, repository: "o/r", autoFixEnabled: true, autoMergeEnabled: false },
{ number: 2, repository: "o/r", autoFixEnabled: false, autoMergeEnabled: true },
],
});
});
it("uses bounded row flags before per-PR details hydrate", () => {
expect(
getTaskPRAutomationSummary([], {
number: 7,
state: "open",
autoFixEnabled: true,
autoMergeEnabled: true,
}),
).toEqual({
autoFixEnabled: true,
autoMergeEnabled: true,
details: [],
});
});
it("keeps bounded row flags while full PR records are temporarily unavailable", () => {
expect(
getTaskPRAutomationSummary(
[],
{ number: 7, state: "open", autoFixEnabled: true, autoMergeEnabled: false },
makeOptions(),
),
).toEqual({
autoFixEnabled: true,
autoMergeEnabled: false,
details: [],
});
});
it("retains repository identity when linked PR numbers overlap", () => {
const summary = getTaskPRAutomationSummary(
[
makePR({ owner: "acme", repo: "frontend", repository_id: "repo-a", pr_number: 7 }),
makePR({ owner: "acme", repo: "backend", repository_id: "repo-b", pr_number: 7 }),
],
undefined,
{
...makeOptions(),
pr_options: [
{ ...makeOptions().pr_options[0], repository_id: "repo-a", pr_number: 7 },
{ ...makeOptions().pr_options[1], repository_id: "repo-b", pr_number: 7 },
],
},
);
expect(summary.details.map(({ repository, number }) => ({ repository, number }))).toEqual([
{ repository: "acme/frontend", number: 7 },
{ repository: "acme/backend", number: 7 },
]);
});
});
@@ -7,13 +7,16 @@ import { TaskContributionIcons } from "@/components/task/task-contribution-icons
import { PRTaskIcon } from "./pr-task-icon";
import type { AppState } from "@/lib/state/store";
import type { TaskPR } from "@/lib/types/github";
import type { TaskCIAutomationOptions } from "@/lib/types/github";
const listTaskPRsMock = vi.hoisted(() => vi.fn());
const getTaskCIAutomationOptionsMock = vi.hoisted(() => vi.fn());
const TASK_ID = "task-1";
const WORKSPACE_ID = "workspace-1";
vi.mock("@/lib/api/domains/github-api", () => ({
listTaskPRs: listTaskPRsMock,
getTaskCIAutomationOptions: getTaskCIAutomationOptionsMock,
}));
function renderWithStore(initialState: Partial<AppState> | undefined, ui: ReactNode) {
@@ -58,8 +61,40 @@ function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
};
}
function makeAutomationOptions(
overrides: Partial<TaskCIAutomationOptions> = {},
): TaskCIAutomationOptions {
return {
task_id: TASK_ID,
workspace_id: WORKSPACE_ID,
auto_fix_enabled: true,
auto_merge_enabled: true,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: "",
using_default_prompt: true,
updated_at: "2026-08-01T00:00:00Z",
pr_states: [],
pr_options: [
{
task_id: TASK_ID,
repository_id: "repo-1",
pr_number: 1,
auto_fix_enabled: true,
auto_merge_enabled: true,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
created_at: "",
updated_at: "",
},
],
...overrides,
};
}
beforeEach(() => {
listTaskPRsMock.mockReset().mockReturnValue(new Promise(() => {}));
getTaskCIAutomationOptionsMock.mockReset().mockResolvedValue(undefined);
});
afterEach(() => cleanup());
@@ -177,3 +212,46 @@ describe("PRTaskIcon corrupted store entry", () => {
expect(document.activeElement).toBe(screen.getByTestId(`pr-task-icon-${TASK_ID}`));
});
});
describe("PRTaskIcon automation indicators", () => {
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10
it("renders independent automation dots from the bounded row projection", () => {
renderWithStore(
{ workspaces: { items: [], activeId: WORKSPACE_ID } },
<TaskContributionIcons
taskId={TASK_ID}
prInfo={{ number: 7, state: "open", autoFixEnabled: true, autoMergeEnabled: true }}
/>,
);
expect(screen.getByTestId("pr-task-automation-auto-fix")).not.toBeNull();
expect(screen.getByTestId("pr-task-automation-auto-merge")).not.toBeNull();
});
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.11
it("shows per-PR automation details after the icon disclosure hydrates", async () => {
const response = Promise.resolve({
task_prs: { [TASK_ID]: [makePR({ repository_id: "repo-1" })] },
});
listTaskPRsMock.mockReturnValue(response);
getTaskCIAutomationOptionsMock.mockResolvedValue(makeAutomationOptions());
renderWithStore(
{ workspaces: { items: [], activeId: WORKSPACE_ID } },
<TaskContributionIcons taskId={TASK_ID} prInfo={{ number: 1, state: "open" }} />,
);
fireEvent.pointerEnter(screen.getByTestId(`pr-task-icon-${TASK_ID}`), {
pointerType: "mouse",
});
await act(async () => {
await response;
});
await waitFor(() =>
expect(screen.getAllByTestId("pr-task-automation-details").length).toBeGreaterThan(0),
);
expect(screen.getAllByText("o/r PR #1").length).toBeGreaterThan(0);
expect(screen.getAllByText("Auto-fix").length).toBeGreaterThan(0);
expect(screen.getAllByText("Auto-merge").length).toBeGreaterThan(0);
});
});
+85 -80
View File
@@ -1,9 +1,7 @@
"use client";
import { IconGitPullRequest } from "@tabler/icons-react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import { useAppStore } from "@/components/state-provider";
import { useChangeRequestTaskTooltipState } from "@/components/integrations/use-change-request-task-tooltip-state";
import {
@@ -14,10 +12,24 @@ import {
import {
getTaskPRsForCurrentWorkspace,
useTaskPRTooltipHydration,
type TaskPRTooltipHydrationStatus,
} from "@/hooks/domains/github/use-task-pr-tooltip-hydration";
import type { TaskPR } from "@/lib/types/github";
import type { TaskCIAutomationOptions } from "@/lib/types/github";
import { useTouchDrawer } from "@/hooks/use-compact-task-chrome";
import { derivePRTaskStatusSummary, PRTaskStatusSummary } from "./pr-task-status-summary";
import {
CompactPRTooltipContent,
PRTaskIconDrawer,
PRTaskIconGlyph,
PRTaskIconTooltip,
TaskPRAutomationDetails,
type PRTaskIconDisclosureProps,
} from "./pr-task-icon-disclosure";
import { getTaskPRAutomationSummary, type TaskPRInfo } from "./pr-task-automation";
export type { TaskPRInfo } from "./pr-task-automation";
export { getTaskPRAutomationSummary } from "./pr-task-automation";
export { AutomationIndicatorDots } from "./pr-task-icon-disclosure";
const MUTED_FOREGROUND = CHANGE_REQUEST_STATUS_COLORS.muted;
const PURPLE_500 = CHANGE_REQUEST_STATUS_COLORS.merged;
@@ -238,15 +250,9 @@ export function pickDefaultPR(prs: TaskPR[]): TaskPR | null {
return best;
}
export type TaskPRInfo = {
number: number;
state: string;
aggregateState?: string;
};
export function PRTaskIcon({ taskId, prInfo }: { taskId: string; prInfo?: TaskPRInfo }) {
const prs = useAppStore((state) => getTaskPRsForCurrentWorkspace(state, taskId));
const hydration = useTaskPRTooltipHydration(taskId);
const hydration = useTaskPRTooltipHydration(taskId, { includeAutomation: true });
const fullPRs = Array.isArray(prs) && prs.length > 0 ? prs : [];
// Defensive: an upstream payload may briefly seed byTaskId[taskId] with a
@@ -254,7 +260,15 @@ export function PRTaskIcon({ taskId, prInfo }: { taskId: string; prInfo?: TaskPR
// instead of falling through into a full-data summary, where for-of throws.
if (fullPRs.length === 0 && !prInfo) return null;
return <PRTaskIconView taskId={taskId} prInfo={prInfo} prs={fullPRs} hydration={hydration} />;
return (
<PRTaskIconView
taskId={taskId}
prInfo={prInfo}
prs={fullPRs}
hydration={hydration}
automationOptions={hydration.automationOptions}
/>
);
}
type TaskPRIconPresentation = {
@@ -289,21 +303,27 @@ function PRTaskIconView({
prInfo,
prs,
hydration,
automationOptions,
}: {
taskId: string;
prInfo?: TaskPRInfo;
prs: TaskPR[];
hydration: ReturnType<typeof useTaskPRTooltipHydration>;
automationOptions: TaskCIAutomationOptions | null;
}) {
const { t } = useTranslation();
const { hydrate } = hydration;
const hasFullData = prs.length > 0;
const tooltip = useChangeRequestTaskTooltipState(
!hasFullData && prInfo
? () => {
void hydration.hydrate();
}
: undefined,
);
const usesTouchDrawer = useTouchDrawer();
const [drawerOpen, setDrawerOpen] = useState(false);
const automation = getTaskPRAutomationSummary(prs, prInfo, automationOptions);
const needsHydration =
!hasFullData ||
((automation.autoFixEnabled || automation.autoMergeEnabled) && !automationOptions);
const hydrateOnDisclosure = useCallback(() => {
if (needsHydration) void hydrate();
}, [hydrate, needsHydration]);
const tooltip = useChangeRequestTaskTooltipState(hydrateOnDisclosure);
const {
singlePR,
readyToMerge,
@@ -314,52 +334,56 @@ function PRTaskIconView({
displayCount,
} = getTaskPRIconPresentation(prs, prInfo);
const ariaLabel =
const statusAriaLabel =
prs.length > 1
? t("github:pullRequestStatuses", { count: prs.length })
: t("github:pullRequestStatus", { number: singlePR?.pr_number ?? prInfo?.number });
const automationAria = [
automation.autoFixEnabled ? t("github:autoFixEnabledAria") : null,
automation.autoMergeEnabled ? t("github:autoMergeEnabledAria") : null,
]
.filter(Boolean)
.join(", ");
const ariaLabel = automationAria ? `${statusAriaLabel}, ${automationAria}` : statusAriaLabel;
return (
<Tooltip open={tooltip.open}>
<TooltipTrigger asChild>
<span
data-testid={`pr-task-icon-${taskId}`}
data-pr-state={displayState}
data-pr-count={displayCount}
data-pr-ready-to-merge={
hasFullData ? String(prs.length === 1 ? readyToMerge : allReadyToMerge) : undefined
}
role="img"
tabIndex={0}
aria-label={ariaLabel}
onPointerEnter={tooltip.onPointerEnter}
onPointerLeave={tooltip.onPointerLeave}
onFocus={tooltip.onFocus}
onBlur={tooltip.onBlur}
className={cn(
"inline-flex items-center shrink-0",
prs.length > 1 && "gap-0.5",
iconColor,
)}
>
<IconGitPullRequest aria-hidden="true" className="h-3.5 w-3.5" />
{prs.length > 1 ? (
<span className="text-[9px] font-semibold leading-none tabular-nums">{prs.length}</span>
) : null}
</span>
</TooltipTrigger>
<TooltipContent
sideOffset={6}
onEscapeKeyDown={tooltip.onEscapeKeyDown}
className="w-80 max-w-[calc(100vw-1rem)] p-3"
>
{hasFullData ? (
<PRTaskStatusSummary summaries={summaries} />
) : (
<CompactPRTooltipContent status={hydration.status} />
)}
</TooltipContent>
</Tooltip>
const disclosureProps: PRTaskIconDisclosureProps = {
taskId,
prInfo,
prs,
hasFullData,
singlePR,
readyToMerge,
allReadyToMerge,
displayState,
displayCount,
iconColor,
ariaLabel,
icon: <PRTaskIconGlyph automation={automation} />,
content: hasFullData ? (
<>
<PRTaskStatusSummary summaries={summaries} />
<TaskPRAutomationDetails summary={automation} />
</>
) : (
<>
<CompactPRTooltipContent status={hydration.status} />
<TaskPRAutomationDetails summary={automation} status={hydration.status} />
</>
),
};
return usesTouchDrawer ? (
<PRTaskIconDrawer
{...disclosureProps}
open={drawerOpen}
onOpenChange={(nextOpen) => {
setDrawerOpen(nextOpen);
if (nextOpen) hydrateOnDisclosure();
}}
t={t}
/>
) : (
<PRTaskIconTooltip {...disclosureProps} tooltip={tooltip} />
);
}
@@ -368,22 +392,3 @@ function getTaskPRIconColor(prs: TaskPR[], prInfo?: TaskPRInfo): string {
if (prs.length > 1) return aggregatePRStatusColor(prs);
return getPRAggregateStatusColor(prInfo?.aggregateState ?? prInfo?.state);
}
function CompactPRTooltipContent({ status }: { status: TaskPRTooltipHydrationStatus }) {
const { t } = useTranslation();
if (status === "loading" || status === "idle") {
return (
<span data-testid="pr-task-tooltip-loading" className="text-sm text-muted-foreground">
{t("github:taskPrDetailsLoading")}
</span>
);
}
if (status === "unavailable") {
return (
<span data-testid="pr-task-tooltip-unavailable" className="text-sm text-muted-foreground">
{t("github:taskPrDetailsUnavailable")}
</span>
);
}
return null;
}
@@ -154,6 +154,34 @@ describe("toSheetItem", () => {
});
});
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10
describe("toSheetItem automation indicators", () => {
it("carries bounded automation indicators onto the mobile sheet row", () => {
const item = toSheetItem(
task({
statusSummary: {
revision: 1,
updated_at: UPDATED_AT,
pull_request: {
number: 42,
state: "open",
auto_fix_enabled: true,
auto_merge_enabled: true,
},
},
}),
emptyCtx(),
);
expect(item.prInfo).toEqual({
number: 42,
state: "Open",
autoFixEnabled: true,
autoMergeEnabled: true,
});
});
});
describe("toSheetItem queued prompt count", () => {
it("carries the queued prompt count from the task status summary", () => {
const item = toSheetItem(
@@ -8,6 +8,7 @@ import { statusSummaryActiveErrorPreview } from "@/lib/task-status-summary";
import type { WipQueueStatus } from "@/lib/kanban/wip-queue";
import { resolveTaskRepositorySlugs } from "@/lib/sidebar/sidebar-task-repositories";
import { effectiveTaskPendingAction } from "../task-select-helpers";
import { taskPRInfoFromSummary } from "../task-pr-info";
export type SheetItemCtx = {
repositoryPathsById: Map<string, string | undefined>;
@@ -60,6 +61,7 @@ function sheetStatus(task: KanbanState["tasks"][number], ctx: SheetItemCtx) {
: (task.primarySessionId ?? null),
hasPendingClarification: pending.clarification,
hasPendingPermission: pending.permission,
prInfo: taskPRInfoFromSummary(summary),
agentErrorMessage: statusSummaryActiveErrorPreview(
summary,
ctx.acknowledgedAgentErrors,
@@ -1,28 +1,35 @@
"use client";
import { IconGitPullRequest } from "@tabler/icons-react";
import { getPRAggregateStatusColor, PRTaskIcon } from "@/components/github/pr-task-icon";
import {
AutomationIndicatorDots,
getPRAggregateStatusColor,
getTaskPRAutomationSummary,
PRTaskIcon,
type TaskPRInfo,
} from "@/components/github/pr-task-icon";
import { MRTaskIcon } from "@/components/gitlab/mr-task-icon";
import { cn } from "@/lib/utils";
/** Shows PR icon from store (real data) or from prInfo prop (prototype/mock). */
function TaskPRIcon({
taskId,
prInfo,
}: {
taskId?: string;
prInfo?: { number: number; state: string; aggregateState?: string };
}) {
function TaskPRIcon({ taskId, prInfo }: { taskId?: string; prInfo?: TaskPRInfo }) {
if (taskId) return <PRTaskIcon taskId={taskId} prInfo={prInfo} />;
if (!prInfo) return null;
const color = getPRAggregateStatusColor(prInfo.aggregateState ?? prInfo.state);
const automation = getTaskPRAutomationSummary([], prInfo);
return (
<span
data-testid={taskId ? `pr-task-icon-${taskId}` : "pr-task-icon"}
data-pr-state={prInfo.state}
className={cn("inline-flex items-center shrink-0", color)}
>
<IconGitPullRequest className="h-3.5 w-3.5" />
<span className="relative inline-flex h-3.5 w-3.5 shrink-0">
<IconGitPullRequest className="h-3.5 w-3.5" />
<AutomationIndicatorDots
autoFixEnabled={automation.autoFixEnabled}
autoMergeEnabled={automation.autoMergeEnabled}
/>
</span>
</span>
);
}
@@ -37,7 +44,7 @@ export function TaskContributionIcons({
prInfo,
}: {
taskId?: string;
prInfo?: { number: number; state: string; aggregateState?: string };
prInfo?: TaskPRInfo;
}) {
return (
<>
+28
View File
@@ -0,0 +1,28 @@
import type { TaskStatusSummary } from "@/lib/types/task-status-summary";
export type TaskPRInfo = {
number: number;
state: string;
aggregateState?: string;
autoFixEnabled?: boolean;
autoMergeEnabled?: boolean;
};
function capitalize(value: string): string {
return value.length > 0 ? value[0].toUpperCase() + value.slice(1) : value;
}
/** Map the bounded task-level PR projection to the shared sidebar icon shape. */
export function taskPRInfoFromSummary(
summary: TaskStatusSummary | null | undefined,
): TaskPRInfo | undefined {
const pullRequest = summary?.pull_request;
if (!pullRequest?.number) return undefined;
return {
number: pullRequest.number,
state: capitalize(pullRequest.state ?? pullRequest.aggregate_state ?? "open"),
aggregateState: pullRequest.aggregate_state,
...(pullRequest.auto_fix_enabled ? { autoFixEnabled: true } : {}),
...(pullRequest.auto_merge_enabled ? { autoMergeEnabled: true } : {}),
};
}
@@ -159,6 +159,34 @@ describe("buildSidebarItem", () => {
});
});
// @covers AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10
describe("buildSidebarItem automation indicators", () => {
it("carries bounded automation indicators into the row PR info", () => {
const item = buildSidebarItem(
task({
statusSummary: {
revision: 2,
updated_at: UPDATED_AT,
pull_request: {
number: 42,
state: "open",
auto_fix_enabled: true,
auto_merge_enabled: true,
},
},
}),
emptyContext(),
);
expect(item.prInfo).toEqual({
number: 42,
state: "Open",
autoFixEnabled: true,
autoMergeEnabled: true,
});
});
});
describe("buildSidebarItem activity", () => {
it("maps summary activity and falls back through task update to creation", () => {
const projected = buildSidebarItem(
@@ -5,6 +5,7 @@ import { statusSummaryActiveErrorPreview } from "@/lib/task-status-summary";
import { workflowStepTitle } from "./task-session-sidebar-aggregate";
import type { WipQueueStatus } from "@/lib/kanban/wip-queue";
import { resolveTaskRepositorySlugs } from "@/lib/sidebar/sidebar-task-repositories";
import { taskPRInfoFromSummary } from "./task-pr-info";
type SidebarItemContext = {
repositorySlugById: Map<string, string | undefined>;
@@ -26,22 +27,6 @@ function summaryDiffStats(
return additions > 0 || deletions > 0 ? { additions, deletions } : undefined;
}
function capitalize(value: string): string {
return value.length > 0 ? value[0].toUpperCase() + value.slice(1) : value;
}
function summaryPRInfo(
summary: TaskStatusSummary | null | undefined,
): { number: number; state: string; aggregateState?: string } | undefined {
const pullRequest = summary?.pull_request;
if (!pullRequest?.number) return undefined;
return {
number: pullRequest.number,
state: capitalize(pullRequest.state ?? pullRequest.aggregate_state ?? "open"),
aggregateState: pullRequest.aggregate_state,
};
}
function repositoryPathFromSummary(
summary: TaskStatusSummary | null | undefined,
): string | undefined {
@@ -118,7 +103,7 @@ function sidebarStatus(
comparisonUnavailable: summary?.git?.comparison_unavailable === true,
hasPendingClarification: pending.clarification,
hasPendingPermission: pending.permission,
prInfo: summaryPRInfo(summary),
prInfo: taskPRInfoFromSummary(summary),
issueInfo: issueInfoForTask(task),
queuedCount: summary?.queued_prompt_count,
wipQueue: context.wipQueueByTaskId?.get(task.id),
+15 -3
View File
@@ -1552,7 +1552,7 @@ export class ApiClient {
owner: string,
repo: string,
number: number,
outcome: "merged" | "queued",
outcome: "merged" | "queued" | "failed" | "pending" | "head_mismatch",
): Promise<void> {
await this.request("PUT", "/api/v1/github/mock/merge-outcomes", {
owner,
@@ -1590,10 +1590,22 @@ export class ApiClient {
}
async mockGitHubGetMergeAttempts(): Promise<
Array<{ owner: string; repo: string; number: number; merge_method: string }>
Array<{
owner: string;
repo: string;
number: number;
merge_method: string;
expected_head_sha: string;
}>
> {
const response = await this.request<{
attempts?: Array<{ owner: string; repo: string; number: number; merge_method: string }>;
attempts?: Array<{
owner: string;
repo: string;
number: number;
merge_method: string;
expected_head_sha: string;
}>;
}>("GET", "/api/v1/github/mock/merge-attempts");
return response.attempts ?? [];
}
@@ -30,6 +30,7 @@ async function seedTaskWithPR(
await apiClient.mockGitHubAssociateTaskPR({
task_id: task.id,
workspace_id: seedData.workspaceId,
repository_id: seedData.repositoryId,
owner: OWNER,
repo: REPO,
pr_number: PR_NUMBER,
@@ -376,6 +377,83 @@ test.describe("PR CI automation options", () => {
await expect(popover.getByRole("alert")).toContainText(
"Lifecycle prompt could not be delivered to a task session.",
);
await expect(popover.getByRole("button", { name: "Refresh" })).toBeVisible();
});
test("desktop retries one failed automatic merge for the reviewed head", async ({
testPage,
apiClient,
seedData,
}) => {
test.setTimeout(120_000);
const headSHA = "head-auto-merge-retry-desktop";
const taskId = await seedTaskWithPR(apiClient, seedData, "CI auto-merge retry desktop", {
head_sha: headSHA,
checks_state: "success",
checks_total: 1,
checks_passing: 1,
unresolved_review_threads: 0,
mergeable_state: "clean",
});
await apiClient.mockGitHubSetMergeOutcome(OWNER, REPO, PR_NUMBER, "failed");
await apiClient.updateTaskCIAutomationOptions(taskId, {
repository_id: seedData.repositoryId,
pr_number: PR_NUMBER,
auto_merge_enabled: true,
});
await expect
.poll(async () => {
const options = await apiClient.getTaskCIAutomationOptions(taskId);
const state = options.pr_states.find((item) => item.pr_number === PR_NUMBER);
return { kind: state?.last_error_kind, result: state?.last_merge_result };
})
.toEqual({ kind: "auto_merge", result: "failed" });
await expect.poll(() => apiClient.mockGitHubGetMergeAttempts()).toHaveLength(1);
// An unchanged provider event reevaluates the PR but cannot repeat the
// failed signature without an explicit retry authorization.
await apiClient.mockGitHubTransitionMergeQueue({
task_id: taskId,
owner: OWNER,
repo: REPO,
pr_number: PR_NUMBER,
head_sha: headSHA,
merge_queue_state: "",
checks: [{ name: "required", status: "completed", conclusion: "success" }],
});
await expect.poll(() => apiClient.mockGitHubGetMergeAttempts()).toHaveLength(1);
const session = await openTask(testPage, taskId);
const popover = session.prTopbarPopover();
const retry = popover.getByRole("button", { name: "Retry" });
await expect(retry).toBeVisible();
await apiClient.mockGitHubSetMergeOutcome(OWNER, REPO, PR_NUMBER, "queued");
await retry.click();
await expect.poll(() => apiClient.mockGitHubGetMergeAttempts()).toHaveLength(2);
const attempts = await apiClient.mockGitHubGetMergeAttempts();
expect(attempts).toEqual([
expect.objectContaining({
owner: OWNER,
repo: REPO,
number: PR_NUMBER,
expected_head_sha: headSHA,
}),
expect.objectContaining({
owner: OWNER,
repo: REPO,
number: PR_NUMBER,
expected_head_sha: headSHA,
}),
]);
await expect
.poll(async () => {
const options = await apiClient.getTaskCIAutomationOptions(taskId);
const state = options.pr_states.find((item) => item.pr_number === PR_NUMBER);
return { error: state?.last_error ?? null, result: state?.last_merge_result };
})
.toEqual({ error: null, result: "accepted" });
});
test("desktop merge queue recovery proves repair and new-head requeue", async ({
@@ -38,6 +38,7 @@ async function seedTaskWithPR(
await apiClient.mockGitHubAssociateTaskPR({
task_id: task.id,
workspace_id: seedData.workspaceId,
repository_id: seedData.repositoryId,
owner: OWNER,
repo: REPO,
pr_number: PR_NUMBER,
@@ -261,6 +262,7 @@ test.describe("mobile PR CI automation options", () => {
await expect(drawer.getByRole("alert")).toContainText(
"Lifecycle prompt could not be delivered to a task session.",
);
await expect(drawer.getByRole("button", { name: "Refresh" })).toBeVisible();
await expect(drawer.getByTestId("pr-workflow-row")).toHaveCount(30);
const scrollBody = drawer.locator("[data-vaul-no-drag]");
@@ -283,6 +285,67 @@ test.describe("mobile PR CI automation options", () => {
expect(documentMetrics.scrollWidth).toBeLessThanOrEqual(documentMetrics.clientWidth);
});
test("mobile retries one failed automatic merge without page overflow", async ({
testPage,
apiClient,
seedData,
}) => {
test.setTimeout(120_000);
const headSHA = "head-auto-merge-retry-mobile";
const taskId = await seedTaskWithPR(apiClient, seedData, "CI auto-merge retry mobile", {
head_sha: headSHA,
checks_state: "success",
checks_total: 1,
checks_passing: 1,
unresolved_review_threads: 0,
mergeable_state: "clean",
});
await apiClient.mockGitHubSetMergeOutcome(OWNER, REPO, PR_NUMBER, "failed");
await apiClient.updateTaskCIAutomationOptions(taskId, {
repository_id: seedData.repositoryId,
pr_number: PR_NUMBER,
auto_merge_enabled: true,
});
await expect
.poll(async () => {
const options = await apiClient.getTaskCIAutomationOptions(taskId);
const state = options.pr_states.find((item) => item.pr_number === PR_NUMBER);
return { kind: state?.last_error_kind, result: state?.last_merge_result };
})
.toEqual({ kind: "auto_merge", result: "failed" });
await testPage.goto(`/t/${taskId}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await session.tapPRStatusChip();
const drawer = session.prStatusChipDrawer();
const retry = drawer.getByRole("button", { name: "Retry" });
await expect(retry).toBeVisible();
const retryBox = await retry.boundingBox();
expect(retryBox).not.toBeNull();
expect(retryBox!.height).toBeGreaterThanOrEqual(44);
expect(retryBox!.width).toBeGreaterThanOrEqual(44);
await apiClient.mockGitHubSetMergeOutcome(OWNER, REPO, PR_NUMBER, "queued");
await retry.tap();
await expect.poll(() => apiClient.mockGitHubGetMergeAttempts()).toHaveLength(2);
const attempts = await apiClient.mockGitHubGetMergeAttempts();
expect(attempts.every((attempt) => attempt.expected_head_sha === headSHA)).toBe(true);
await expect
.poll(async () => {
const options = await apiClient.getTaskCIAutomationOptions(taskId);
const state = options.pr_states.find((item) => item.pr_number === PR_NUMBER);
return { error: state?.last_error ?? null, result: state?.last_merge_result };
})
.toEqual({ error: null, result: "accepted" });
expect(
await testPage.evaluate(
() => document.documentElement.scrollWidth <= document.documentElement.clientWidth,
),
).toBe(true);
});
test("mobile merge queue recovery proves repair and new-head requeue", async ({
testPage,
apiClient,
@@ -0,0 +1,144 @@
import { test, expect, type SeedData } from "../../fixtures/test-base";
import { SessionPage } from "../../pages/session-page";
import type { ApiClient } from "../../helpers/api-client";
const OWNER = "testorg";
const REPO = "testrepo";
const PR_NUMBER = 190;
async function seedSidebarAutomation(
apiClient: ApiClient,
seedData: SeedData,
): Promise<{ navigationTaskId: string; targetTaskId: string }> {
await apiClient.mockGitHubReset();
await apiClient.mockGitHubSetUser("test-user");
const stepOptions = {
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
};
const navigationTask = await apiClient.seedTask(
seedData.workspaceId,
"Mobile automation navigation",
stepOptions,
);
const targetTask = await apiClient.seedTask(
seedData.workspaceId,
"Mobile automation target",
stepOptions,
);
await apiClient.mockGitHubAssociateTaskPR({
task_id: targetTask.task_id,
workspace_id: seedData.workspaceId,
repository_id: seedData.repositoryId,
owner: OWNER,
repo: REPO,
pr_number: PR_NUMBER,
pr_url: `https://github.com/${OWNER}/${REPO}/pull/${PR_NUMBER}`,
pr_title: "Mobile sidebar automation indicators",
head_branch: "feat/mobile-sidebar-automation-indicators",
base_branch: "main",
author_login: "test-user",
state: "open",
review_state: "approved",
checks_state: "success",
mergeable_state: "clean",
});
await apiClient.updateTaskCIAutomationOptions(targetTask.task_id, {
repository_id: seedData.repositoryId,
pr_number: PR_NUMBER,
auto_fix_enabled: true,
auto_merge_enabled: true,
});
return { navigationTaskId: navigationTask.task_id, targetTaskId: targetTask.task_id };
}
test.describe("Mobile sidebar PR automation indicators", () => {
test("shows touch indicators, details, and terminal-state cleanup", async ({
testPage,
apiClient,
seedData,
prCapture,
}) => {
test.setTimeout(120_000);
const { navigationTaskId, targetTaskId } = await seedSidebarAutomation(apiClient, seedData);
await expect
.poll(
async () => {
const response = await apiClient.listTasks(seedData.workspaceId);
return response.tasks.find((task) => task.id === targetTaskId)?.status_summary
?.pull_request;
},
{ timeout: 15_000 },
)
.toMatchObject({
auto_fix_enabled: true,
auto_merge_enabled: true,
});
await testPage.goto(`/t/${navigationTaskId}`);
await new SessionPage(testPage).waitForLoad();
await testPage.getByTestId("mobile-session-menu").tap();
const sheet = testPage.getByRole("dialog", { name: "Tasks" });
const targetRow = sheet.locator(`[data-task-row-id="${targetTaskId}"]`);
await expect(targetRow).toBeVisible();
const icon = targetRow.getByTestId(`pr-task-icon-${targetTaskId}`);
await expect(icon).toBeVisible();
await expect(icon.getByTestId("pr-task-automation-auto-fix")).toBeVisible();
await expect(icon.getByTestId("pr-task-automation-auto-merge")).toBeVisible();
const navigationURL = testPage.url();
await icon.tap();
const drawer = testPage.getByTestId(`pr-task-automation-drawer-${targetTaskId}`);
await expect(drawer).toBeVisible();
const automationDetails = drawer.getByTestId("pr-task-automation-details");
await expect(automationDetails).toBeVisible();
await expect(automationDetails.getByText(`PR #${PR_NUMBER}`)).toBeVisible();
await expect(automationDetails.getByText("Auto-fix")).toBeVisible();
await expect(automationDetails.getByText("Auto-merge")).toBeVisible();
await expect
.poll(async () =>
testPage.evaluate(
() => document.documentElement.scrollWidth <= document.documentElement.clientWidth,
),
)
.toBe(true);
await prCapture.screenshot("sidebar-automation-indicators-mobile", {
caption: "Mobile task switcher shows touch-sized PR automation indicators and details.",
});
await testPage.keyboard.press("Escape");
await expect(drawer).toHaveCount(0);
await expect(icon).toBeFocused();
await expect(testPage).toHaveURL(navigationURL);
await apiClient.mockGitHubAssociateTaskPR({
task_id: targetTaskId,
workspace_id: seedData.workspaceId,
repository_id: seedData.repositoryId,
owner: OWNER,
repo: REPO,
pr_number: PR_NUMBER,
pr_url: `https://github.com/${OWNER}/${REPO}/pull/${PR_NUMBER}`,
pr_title: "Mobile sidebar automation indicators",
head_branch: "feat/mobile-sidebar-automation-indicators",
base_branch: "main",
author_login: "test-user",
state: "closed",
review_state: "approved",
checks_state: "success",
mergeable_state: "clean",
});
await expect
.poll(async () => {
const response = await apiClient.listTasks(seedData.workspaceId);
const pullRequest = response.tasks.find((task) => task.id === targetTaskId)?.status_summary
?.pull_request;
return pullRequest?.auto_fix_enabled === true || pullRequest?.auto_merge_enabled === true;
})
.toBe(false);
await expect(icon.getByTestId("pr-task-automation-auto-fix")).toHaveCount(0);
await expect(icon.getByTestId("pr-task-automation-auto-merge")).toHaveCount(0);
});
});
@@ -167,6 +167,138 @@ test.describe("PR status badge", () => {
}
});
test("shows sidebar automation indicators and refreshes them for active PRs", async ({
testPage,
apiClient,
seedData,
prCapture,
}) => {
test.setTimeout(120_000);
const { task } = await seedBadgeTest(
apiClient,
seedData.workspaceId,
seedData.agentProfileId,
seedData.repositoryId,
"Sidebar automation indicators",
);
const activePRNumber = 188;
const mergedPRNumber = 189;
const basePR = {
task_id: task.id,
workspace_id: seedData.workspaceId,
repository_id: seedData.repositoryId,
owner: "testorg",
repo: "testrepo",
pr_url: "",
pr_title: "Sidebar automation indicator PR",
head_branch: "feat/sidebar-automation-indicators",
base_branch: "main",
author_login: "test-user",
review_state: "approved",
checks_state: "success",
mergeable_state: "clean",
} as const;
await apiClient.mockGitHubAssociateTaskPR({
...basePR,
pr_number: activePRNumber,
pr_url: `https://github.com/testorg/testrepo/pull/${activePRNumber}`,
state: "open",
});
await apiClient.mockGitHubAssociateTaskPR({
...basePR,
pr_number: mergedPRNumber,
pr_url: `https://github.com/testorg/testrepo/pull/${mergedPRNumber}`,
state: "merged",
});
await apiClient.updateTaskCIAutomationOptions(task.id, {
repository_id: seedData.repositoryId,
pr_number: activePRNumber,
auto_fix_enabled: true,
auto_merge_enabled: false,
});
await apiClient.updateTaskCIAutomationOptions(task.id, {
repository_id: seedData.repositoryId,
pr_number: mergedPRNumber,
auto_fix_enabled: false,
auto_merge_enabled: true,
});
await expect
.poll(async () => {
const response = await apiClient.listTasks(seedData.workspaceId);
const pullRequest = response.tasks.find((candidate) => candidate.id === task.id)
?.status_summary?.pull_request;
return {
auto_fix_enabled: pullRequest?.auto_fix_enabled ?? false,
auto_merge_enabled: pullRequest?.auto_merge_enabled ?? false,
};
})
.toMatchObject({
auto_fix_enabled: true,
auto_merge_enabled: false,
});
await testPage.goto("/tasks");
await expect(testPage.getByTestId("tasks-list")).toBeVisible();
const sidebar = testPage.getByTestId("app-sidebar");
const taskRow = sidebar.getByTestId("sidebar-task-item").filter({ hasText: task.title });
const icon = taskRow.getByTestId(`pr-task-icon-${task.id}`);
await expect(icon).toBeVisible();
await expect(icon.getByTestId("pr-task-automation-auto-fix")).toBeVisible();
await expect(icon.getByTestId("pr-task-automation-auto-merge")).toHaveCount(0);
await expect(icon).toHaveAttribute("aria-label", /auto-fix enabled/);
await icon.hover();
const tooltip = testPage.locator('div[data-slot="tooltip-content"]:not([data-state="closed"])');
const automationDetails = tooltip.locator(
':scope > [data-testid="pr-task-automation-details"]',
);
await expect(automationDetails).toBeVisible();
await expect(
automationDetails.getByText(`testorg/testrepo PR #${activePRNumber}`),
).toBeVisible();
await expect(automationDetails.getByText(`testorg/testrepo PR #${mergedPRNumber}`)).toHaveCount(
0,
);
await prCapture.screenshot("sidebar-automation-indicators-desktop", {
caption: "Task sidebar PR icon shows independent active automation indicators.",
});
await apiClient.updateTaskCIAutomationOptions(task.id, {
repository_id: seedData.repositoryId,
pr_number: activePRNumber,
auto_merge_enabled: true,
});
await expect
.poll(async () => {
const response = await apiClient.listTasks(seedData.workspaceId);
const pullRequest = response.tasks.find((candidate) => candidate.id === task.id)
?.status_summary?.pull_request;
return pullRequest?.auto_merge_enabled === true;
})
.toBe(true);
await expect(icon.getByTestId("pr-task-automation-auto-merge")).toBeVisible();
await apiClient.mockGitHubAssociateTaskPR({
...basePR,
pr_number: activePRNumber,
pr_url: `https://github.com/testorg/testrepo/pull/${activePRNumber}`,
state: "closed",
});
await expect
.poll(async () => {
const response = await apiClient.listTasks(seedData.workspaceId);
const pullRequest = response.tasks.find((candidate) => candidate.id === task.id)
?.status_summary?.pull_request;
return pullRequest?.auto_fix_enabled === true || pullRequest?.auto_merge_enabled === true;
})
.toBe(false);
await expect(icon.getByTestId("pr-task-automation-auto-fix")).toHaveCount(0);
await expect(icon.getByTestId("pr-task-automation-auto-merge")).toHaveCount(0);
});
/**
* Regression for the "CI pending" bug: GitHub reports all checks passed
* (one skipped, many successful). We used to compute "pending" because
@@ -6,11 +6,13 @@ import type { TaskCIAutomationOptions } from "@/lib/types/github";
const apiMocks = vi.hoisted(() => ({
getOptionsMock: vi.fn(),
retryMergeMock: vi.fn(),
updateOptionsMock: vi.fn(),
}));
vi.mock("@/lib/api/domains/github-api", () => ({
getTaskCIAutomationOptions: apiMocks.getOptionsMock,
retryTaskCIAutoMerge: apiMocks.retryMergeMock,
updateTaskCIAutomationOptions: apiMocks.updateOptionsMock,
}));
@@ -37,6 +39,7 @@ function makeOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCIAu
beforeEach(() => {
apiMocks.getOptionsMock.mockReset();
apiMocks.retryMergeMock.mockReset();
apiMocks.updateOptionsMock.mockReset();
});
@@ -79,6 +82,24 @@ describe("useTaskCIAutomationOptions", () => {
expect(result.current.saving).toBe(false);
});
it("requests an explicit merge retry without treating acceptance as provider success", async () => {
apiMocks.getOptionsMock.mockResolvedValue(makeOptions());
apiMocks.retryMergeMock.mockResolvedValue({ accepted: true });
const { result } = renderHook(() => useTaskCIAutomationOptions("task-1"), { wrapper });
await waitFor(() => expect(result.current.options).not.toBeNull());
await act(async () => {
await result.current.retryMerge("repo-1", 42);
});
expect(apiMocks.retryMergeMock).toHaveBeenCalledWith("task-1", "repo-1", 42, {
cache: "no-store",
});
expect(apiMocks.getOptionsMock).toHaveBeenCalledTimes(1);
expect(result.current.saving).toBe(false);
});
it("does not auto-retry after a load error", async () => {
apiMocks.getOptionsMock.mockRejectedValue(new Error("backend unavailable"));
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useRef } from "react";
import {
getTaskCIAutomationOptions,
retryTaskCIAutoMerge,
updateTaskCIAutomationOptions,
} from "@/lib/api/domains/github-api";
import { useAppStore } from "@/components/state-provider";
@@ -16,6 +17,7 @@ function errorMessage(error: unknown): string {
export function useTaskCIAutomationOptions(taskId: string | null) {
const refreshRequestRef = useRef<Record<string, number>>({});
const updateRequestRef = useRef<Record<string, number>>({});
const retryRequestRef = useRef<Record<string, number>>({});
const options = useAppStore((state) =>
taskId ? (state.taskCIAutomation.byTaskId[taskId] ?? null) : null,
);
@@ -86,6 +88,29 @@ export function useTaskCIAutomationOptions(taskId: string | null) {
const resetPrompt = useCallback(() => update({ auto_fix_prompt_override: null }), [update]);
const retryMerge = useCallback(
async (repositoryId: string, prNumber: number): Promise<{ accepted: boolean } | null> => {
if (!taskId) return null;
const requestId = (retryRequestRef.current[taskId] ?? 0) + 1;
retryRequestRef.current[taskId] = requestId;
setSaving(taskId, true);
setError(taskId, null);
try {
return await retryTaskCIAutoMerge(taskId, repositoryId, prNumber, { cache: "no-store" });
} catch (err) {
if (retryRequestRef.current[taskId] === requestId) {
setError(taskId, errorMessage(err));
}
throw err;
} finally {
if (retryRequestRef.current[taskId] === requestId) {
setSaving(taskId, false);
}
}
},
[setError, setSaving, taskId],
);
useEffect(() => {
if (!taskId || options || loading || error) return;
void refresh().catch(() => {
@@ -93,5 +118,5 @@ export function useTaskCIAutomationOptions(taskId: string | null) {
});
}, [error, loading, options, refresh, taskId]);
return { options, loading, saving, error, refresh, update, resetPrompt };
return { options, loading, saving, error, refresh, update, resetPrompt, retryMerge };
}
@@ -4,11 +4,14 @@ import type { ReactNode } from "react";
import { StateProvider, useAppStoreApi } from "@/components/state-provider";
import type { AppState } from "@/lib/state/store";
import type { TaskPR } from "@/lib/types/github";
import type { TaskCIAutomationOptions } from "@/lib/types/github";
const listTaskPRsMock = vi.hoisted(() => vi.fn());
const getTaskCIAutomationOptionsMock = vi.hoisted(() => vi.fn());
vi.mock("@/lib/api/domains/github-api", () => ({
listTaskPRs: listTaskPRsMock,
getTaskCIAutomationOptions: getTaskCIAutomationOptionsMock,
}));
import { useTaskPRTooltipHydration } from "./use-task-pr-tooltip-hydration";
@@ -59,6 +62,24 @@ function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
};
}
function makeAutomationOptions(
overrides: Partial<TaskCIAutomationOptions> = {},
): TaskCIAutomationOptions {
return {
task_id: "task-1",
workspace_id: WORKSPACE_A,
auto_fix_enabled: true,
auto_merge_enabled: false,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: "",
using_default_prompt: true,
updated_at: "2026-08-01T00:00:00Z",
pr_states: [],
pr_options: [],
...overrides,
};
}
function createStateWrapper(initialState: Partial<AppState> = {}) {
return function StateTestWrapper({ children }: { children: ReactNode }) {
return (
@@ -83,6 +104,7 @@ function useHydrationWithStore(taskId: string) {
beforeEach(() => {
listTaskPRsMock.mockReset();
getTaskCIAutomationOptionsMock.mockReset();
});
afterEach(() => {
@@ -142,6 +164,59 @@ describe("useTaskPRTooltipHydration request coordination", () => {
});
});
describe("useTaskPRTooltipHydration automation details", () => {
it("hydrates PR details and automation options together on demand", async () => {
const pr = makePR();
listTaskPRsMock.mockResolvedValue({ task_prs: { "task-1": [pr] } });
const options = makeAutomationOptions();
getTaskCIAutomationOptionsMock.mockResolvedValue(options);
const { result } = renderHook(
() => useTaskPRTooltipHydration("task-1", { includeAutomation: true }),
{ wrapper: createStateWrapper() },
);
expect(listTaskPRsMock).not.toHaveBeenCalled();
expect(getTaskCIAutomationOptionsMock).not.toHaveBeenCalled();
await act(async () => {
await result.current.hydrate();
});
expect(listTaskPRsMock).toHaveBeenCalledWith(["task-1"], { cache: "no-store" });
expect(getTaskCIAutomationOptionsMock).toHaveBeenCalledWith("task-1", { cache: "no-store" });
expect(result.current.automationOptions).toEqual(options);
});
it("uses a newer WebSocket automation update while the disclosure stays mounted", async () => {
const pr = makePR();
listTaskPRsMock.mockResolvedValue({ task_prs: { "task-1": [pr] } });
const initial = makeAutomationOptions();
getTaskCIAutomationOptionsMock.mockResolvedValue(initial);
const { result } = renderHook(
() => ({
hydration: useTaskPRTooltipHydration("task-1", { includeAutomation: true }),
store: useAppStoreApi(),
}),
{ wrapper: createStateWrapper() },
);
await act(async () => {
await result.current.hydration.hydrate();
});
const updated = makeAutomationOptions({
auto_merge_enabled: true,
updated_at: "2026-08-01T00:01:00Z",
});
act(() => {
result.current.store.getState().setTaskCIAutomationOptions("task-1", updated);
});
await waitFor(() => expect(result.current.hydration.automationOptions).toEqual(updated));
});
});
describe("useTaskPRTooltipHydration context guards", () => {
it("keeps a WebSocket entry when the older HTTP response resolves later", async () => {
const response = deferred<{ task_prs: Record<string, TaskPR[]> }>();
@@ -3,17 +3,22 @@
import { useCallback, useEffect, useRef, useState } from "react";
import type { StoreApi } from "zustand";
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { listTaskPRs } from "@/lib/api/domains/github-api";
import { getTaskCIAutomationOptions, listTaskPRs } from "@/lib/api/domains/github-api";
import type { AppState } from "@/lib/state/store";
import { isCurrentWorkspaceContext } from "@/lib/state/workspace-context";
import type { TaskPRScope } from "@/lib/state/slices/github/types";
import type { TaskPR } from "@/lib/types/github";
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
export type TaskPRTooltipHydrationStatus = "idle" | "loading" | "unavailable";
type TaskPRRequestRegistry = Map<string, Promise<TaskPR[]>>;
type TaskAutomationRequestRegistry = Map<string, Promise<TaskCIAutomationOptions | null>>;
const requestRegistryByStore = new WeakMap<StoreApi<AppState>, TaskPRRequestRegistry>();
const automationRequestRegistryByStore = new WeakMap<
StoreApi<AppState>,
TaskAutomationRequestRegistry
>();
function hasTaskPRs(value: unknown): value is TaskPR[] {
return Array.isArray(value) && value.length > 0;
@@ -37,6 +42,14 @@ function getRequestRegistry(store: StoreApi<AppState>): TaskPRRequestRegistry {
return registry;
}
function getAutomationRequestRegistry(store: StoreApi<AppState>): TaskAutomationRequestRegistry {
const existing = automationRequestRegistryByStore.get(store);
if (existing) return existing;
const registry: TaskAutomationRequestRegistry = new Map();
automationRequestRegistryByStore.set(store, registry);
return registry;
}
function isSamePR(left: TaskPR, right: TaskPR): boolean {
if (left.id && right.id && left.id === right.id) return true;
return (
@@ -104,14 +117,57 @@ function requestTaskPRs(
return request;
}
export function useTaskPRTooltipHydration(taskId: string): {
function requestTaskAutomationOptions(
store: StoreApi<AppState>,
scope: TaskPRScope & { workspaceId: string },
taskId: string,
): Promise<TaskCIAutomationOptions | null> {
if (typeof getTaskCIAutomationOptions !== "function") return Promise.resolve(null);
const registry = getAutomationRequestRegistry(store);
const key = requestKey(scope.workspaceId, scope.workspaceContextGeneration, taskId);
const existing = registry.get(key);
if (existing) return existing;
const request = Promise.resolve(getTaskCIAutomationOptions(taskId, { cache: "no-store" }));
registry.set(key, request);
request.then(
() => {
if (registry.get(key) === request) registry.delete(key);
},
() => {
if (registry.get(key) === request) registry.delete(key);
},
);
return request;
}
function automationOptionsForScope(
options: TaskCIAutomationOptions | null | undefined,
workspaceId: string | null,
): TaskCIAutomationOptions | null {
if (!options) return null;
if (options.workspace_id && workspaceId && options.workspace_id !== workspaceId) return null;
return options;
}
export function useTaskPRTooltipHydration(
taskId: string,
hydrationOptions: { includeAutomation?: boolean } = {},
): {
status: TaskPRTooltipHydrationStatus;
hydrate: () => Promise<TaskPR[]>;
automationOptions: TaskCIAutomationOptions | null;
} {
const store = useAppStoreApi();
const workspaceId = useAppStore((state) => state.workspaces.activeId);
const workspaceContextGeneration = useAppStore((state) => state.workspaceContextGeneration);
const storedAutomationOptions = useAppStore((state) =>
automationOptionsForScope(state.taskCIAutomation?.byTaskId?.[taskId], workspaceId),
);
const [status, setStatus] = useState<TaskPRTooltipHydrationStatus>("idle");
const [hydratedAutomationOptions, setHydratedAutomationOptions] =
useState<TaskCIAutomationOptions | null>(null);
const includeAutomation = hydrationOptions.includeAutomation === true;
const scopeKey = `${workspaceId ?? ""}\u0000${workspaceContextGeneration}\u0000${taskId}`;
const scopeRef = useRef({ key: scopeKey, generation: 0 });
if (scopeRef.current.key !== scopeKey) {
@@ -122,6 +178,7 @@ export function useTaskPRTooltipHydration(taskId: string): {
}
useEffect(() => {
setStatus("idle");
setHydratedAutomationOptions(null);
}, [scopeKey]);
const hydrate = useCallback(() => {
@@ -141,26 +198,50 @@ export function useTaskPRTooltipHydration(taskId: string): {
}
const current = store.getState();
const cached = getTaskPRsForScope(current, taskId, scope);
if (cached) {
if (isCurrentScope()) setStatus("idle");
const cachedAutomation = automationOptionsForScope(
current.taskCIAutomation?.byTaskId?.[taskId],
scope.workspaceId,
);
if (cached && (!includeAutomation || cachedAutomation)) {
if (isCurrentScope()) {
setHydratedAutomationOptions(cachedAutomation);
setStatus("idle");
}
return Promise.resolve(cached);
}
if (isCurrentScope()) setStatus("loading");
return requestTaskPRs(store, scope, taskId).then(
(prs) => {
if (isCurrentScope()) {
mergeMissingTaskPRs(store, taskId, prs, scope);
setStatus(getTaskPRsForScope(store.getState(), taskId, scope) ? "idle" : "unavailable");
const prRequest = cached ? Promise.resolve(cached) : requestTaskPRs(store, scope, taskId);
let automationRequest: Promise<TaskCIAutomationOptions | null> = Promise.resolve(null);
if (includeAutomation) {
automationRequest = cachedAutomation
? Promise.resolve(cachedAutomation)
: requestTaskAutomationOptions(store, scope, taskId);
}
return Promise.allSettled([prRequest, automationRequest]).then((results) => {
const prResult = results[0];
const automationResult = results[1];
const prs = prResult.status === "fulfilled" ? prResult.value : [];
const automation = automationResult.status === "fulfilled" ? automationResult.value : null;
if (isCurrentScope()) {
if (prs.length > 0) mergeMissingTaskPRs(store, taskId, prs, scope);
if (automation) {
store.getState().setTaskCIAutomationOptions(taskId, automation);
setHydratedAutomationOptions(automation);
}
return prs;
},
() => {
if (isCurrentScope()) setStatus("unavailable");
return [];
},
);
}, [store, taskId, workspaceContextGeneration, workspaceId]);
setStatus(getTaskPRsForScope(store.getState(), taskId, scope) ? "idle" : "unavailable");
}
return prs;
});
}, [includeAutomation, store, taskId, workspaceContextGeneration, workspaceId]);
return { status, hydrate };
return {
status,
hydrate,
// Prefer the store entry because WebSocket updates replace the fetched
// snapshot while the disclosure remains mounted. Fall back to the local
// snapshot for compatibility with callers/tests that provide no store
// entry (for example, a request that completed before state hydration).
automationOptions: storedAutomationOptions ?? hydratedAutomationOptions,
};
}
+19
View File
@@ -167,6 +167,25 @@ export async function updateTaskCIAutomationOptions(
);
}
export async function retryTaskCIAutoMerge(
taskId: string,
repositoryId: string,
prNumber: number,
options?: ApiRequestOptions,
) {
return fetchJson<{ accepted: boolean }>(
`/api/v1/github/tasks/${encodeURIComponent(taskId)}/ci-automation/retry-merge`,
{
...options,
init: {
...(options?.init ?? {}),
method: "POST",
body: JSON.stringify({ repository_id: repositoryId, pr_number: prNumber }),
},
},
);
}
// PR watches
export async function listPRWatches(workspaceId: string, options?: ApiRequestOptions) {
const params = new URLSearchParams({ workspace_id: workspaceId });
@@ -0,0 +1,41 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/config", () => ({
getBackendConfig: () => ({ apiBaseUrl: "http://api.test" }),
}));
import { retryTaskCIAutoMerge } from "./github-api";
const fetchSpy = vi.fn<(...args: Parameters<typeof fetch>) => Promise<Response>>();
beforeEach(() => {
fetchSpy.mockReset();
vi.stubGlobal("fetch", fetchSpy);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("GitHub automatic merge retry", () => {
it("requests one retry for the exact linked PR", async () => {
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify({ accepted: true }), {
status: 202,
headers: { "Content-Type": "application/json" },
}),
);
await retryTaskCIAutoMerge("task-1", "repo-1", 42);
const call = fetchSpy.mock.calls.at(-1);
expect(String(call?.[0])).toBe(
"http://api.test/api/v1/github/tasks/task-1/ci-automation/retry-merge",
);
expect(call?.[1]?.method).toBe("POST");
expect(JSON.parse(String(call?.[1]?.body))).toEqual({
repository_id: "repo-1",
pr_number: 42,
});
});
});
+2
View File
@@ -330,6 +330,7 @@ export type TaskCIPRAutomationState = {
auto_fix_exhausted_at: string | null;
last_merge_signature: string;
last_merge_attempt_at: string | null;
last_merge_result: "" | "in_flight" | "failed" | "accepted";
last_queue_attempt_head_sha?: string;
last_queue_fix_event_id?: string;
last_queue_removal_cause?: CIAutomationQueueRemovalCause | string;
@@ -340,6 +341,7 @@ export type TaskCIPRAutomationState = {
last_lifecycle_prompt_at?: string | null;
last_lifecycle_session_id?: string | null;
last_error: string | null;
last_error_kind: string;
created_at: string;
updated_at: string;
};
@@ -38,6 +38,8 @@ export type TaskStatusSummary = {
count?: number;
open_count?: number;
attention?: boolean;
auto_fix_enabled?: boolean;
auto_merge_enabled?: boolean;
aggregate_state?: string;
state?: string;
number?: number;
+2
View File
@@ -75,6 +75,7 @@ describe("registerGitHubHandlers CI options", () => {
auto_fix_exhausted_at: null,
last_merge_signature: "",
last_merge_attempt_at: null,
last_merge_result: "",
review_request_initialized: false,
last_review_requested: false,
last_observed_pr_state: "open",
@@ -82,6 +83,7 @@ describe("registerGitHubHandlers CI options", () => {
last_lifecycle_prompt_at: null,
last_lifecycle_session_id: null,
last_error: "Tests are failing",
last_error_kind: "",
created_at: NEWER_UPDATED_AT,
updated_at: NEWER_UPDATED_AT,
};
+6
View File
@@ -382,6 +382,7 @@
"prTaskStatusCi": "CI",
"prTaskStatusMerge": "Merge",
"prTaskStatusNumber": "PR #{{number}}",
"prTaskStatusRepositoryNumber": "{{repository}} PR #{{number}}",
"prTaskStatusReview": "Review",
"prTaskStatusState": "State",
"prepareAppOnGithub": "Prepare App on GitHub",
@@ -576,7 +577,11 @@
"failedToFetchPrFeedback": "Failed to fetch PR feedback",
"failedToFetchPrFiles": "Failed to fetch PR files",
"failedToLoadCiAutomationOptions": "Failed to load CI automation options.",
"failedToResetAutoFixPrompt": "Failed to reset the auto-fix prompt.",
"failedToRetryAutoMerge": "Failed to retry the automatic merge.",
"failedToSaveAutoFixPrompt": "Failed to save the auto-fix prompt.",
"failedToSearchGitHub": "Failed to search GitHub",
"failedToUpdateCiAutomation": "Failed to update CI automation.",
"pullRequestNumbered": "Pull Request #{{number}}",
"mergeQueueEstimate_one": "Estimated merge time: {{count}} minute.",
"mergeQueueEstimate_other": "Estimated merge time: {{count}} minutes.",
@@ -592,6 +597,7 @@
"mergeQueueStatus": "Merge queue: {{state}}",
"mergeQueueSubMinuteEstimate": "Estimated merge time: less than a minute.",
"autoMergeOrRequeueWhenReady": "Auto-merge or requeue when ready",
"autoMergeRetryAccepted": "Automatic merge retry requested.",
"autoFixQueueSupportQueued": "Will repair failed queue checks or conflicts.",
"autoFixQueueSupportEnable": "Enable to send this actionable queue failure to the agent.",
"autoFixQueueSupportRequested": "Repair requested for this removal.",
+6
View File
@@ -382,6 +382,7 @@
"prTaskStatusCi": "ĆĨ",
"prTaskStatusMerge": "Ḿēŕĝē",
"prTaskStatusNumber": "ƤŔ #{{number}}",
"prTaskStatusRepositoryNumber": "{{repository}} ƤŔ #{{number}}",
"prTaskStatusReview": "Ŕēvĩēŵ",
"prTaskStatusState": "Śţàţē",
"prepareAppOnGithub": "Ƥŕēƥàŕē Àƥƥ ōń ĜĩţĤũƀ",
@@ -576,7 +577,11 @@
"failedToFetchPrFeedback": "Ƒàĩĺēď ţō ƒēţćĥ ƤŔ ƒēēďƀàćķ",
"failedToFetchPrFiles": "Ƒàĩĺēď ţō ƒēţćĥ ƤŔ ƒĩĺēś",
"failedToLoadCiAutomationOptions": "Ƒàĩĺēď ţō ĺōàď ĆĨ àũţōḿàţĩōń ōƥţĩōńś.",
"failedToResetAutoFixPrompt": "Ƒàĩĺēď ţō ŕēśēţ ţĥē àũţō-ƒĩx ƥŕōḿƥţ.",
"failedToRetryAutoMerge": "Ƒàĩĺēď ţō ŕēţŕŷ ţĥē àũţōḿàţĩć ḿēŕĝē.",
"failedToSaveAutoFixPrompt": "Ƒàĩĺēď ţō śàvē ţĥē àũţō-ƒĩx ƥŕōḿƥţ.",
"failedToSearchGitHub": "Ƒàĩĺēď ţō śēàŕćĥ ĜĩţĤũƀ",
"failedToUpdateCiAutomation": "Ƒàĩĺēď ţō ũƥďàţē ĆĨ àũţōḿàţĩōń.",
"pullRequestNumbered": "Ƥũĺĺ Ŕēqũēśţ #{{number}}",
"mergeQueueEstimate_one": "Ēśţĩḿàţēď ḿēŕĝē ţĩḿē: {{count}} ḿĩńũţē.",
"mergeQueueEstimate_other": "Ēśţĩḿàţēď ḿēŕĝē ţĩḿē: {{count}} ḿĩńũţēś.",
@@ -592,6 +597,7 @@
"mergeQueueStatus": "Ḿēŕĝē qũēũē: {{state}}",
"mergeQueueSubMinuteEstimate": "Ēśţĩḿàţēď ḿēŕĝē ţĩḿē: ĺēśś ţĥàń à ḿĩńũţē.",
"autoMergeOrRequeueWhenReady": "Àũţō-ḿēŕĝē ōŕ ŕēqũēũē ŵĥēń ŕēàďŷ",
"autoMergeRetryAccepted": "Àũţōḿàţĩć ḿēŕĝē ŕēţŕŷ ŕēqũēśţēď.",
"autoFixQueueSupportQueued": "Ŵĩĺĺ ŕēƥàĩŕ ƒàĩĺēď qũēũē ćĥēćķś ōŕ ćōńƒĺĩćţś.",
"autoFixQueueSupportEnable": "Ēńàƀĺē ţō śēńď ţĥĩś àćţĩōńàƀĺē qũēũē ƒàĩĺũŕē ţō ţĥē àĝēńţ.",
"autoFixQueueSupportRequested": "Ŕēƥàĩŕ ŕēqũēśţēď ƒōŕ ţĥĩś ŕēḿōvàĺ.",
+6
View File
@@ -546,11 +546,16 @@
"failedToFetchPrFeedback": "Falha ao obter o feedback do PR",
"failedToFetchPrFiles": "Falha ao obter os ficheiros do PR",
"failedToLoadCiAutomationOptions": "Falha ao carregar as opções de automação de CI.",
"failedToResetAutoFixPrompt": "Falha ao repor a instrução de correção automática.",
"failedToRetryAutoMerge": "Falha ao repetir o merge automático.",
"failedToSaveAutoFixPrompt": "Falha ao guardar a instrução de correção automática.",
"failedToSearchGitHub": "Falha ao pesquisar no GitHub",
"failedToUpdateCiAutomation": "Falha ao atualizar a automação de CI.",
"mergeable": "Integrável",
"prTaskStatusCi": "CI",
"prTaskStatusMerge": "Integração",
"prTaskStatusNumber": "PR #{{number}}",
"prTaskStatusRepositoryNumber": "{{repository}} PR n.º {{number}}",
"prTaskStatusReview": "Revisão",
"prTaskStatusState": "Estado",
"pullRequestCiStatusAria": "Estado de CI do pull request #{{number}}{{automation}}",
@@ -592,6 +597,7 @@
"mergeQueueStatus": "Fila de merge: {{state}}",
"mergeQueueSubMinuteEstimate": "Tempo estimado até ao merge: menos de um minuto.",
"autoMergeOrRequeueWhenReady": "Fazer merge ou voltar a colocar em fila quando estiver pronto",
"autoMergeRetryAccepted": "Foi pedida uma nova tentativa de merge automático.",
"autoFixQueueSupportQueued": "Corrige verificações falhadas ou conflitos da fila.",
"autoFixQueueSupportEnable": "Ative para enviar esta falha acionável da fila ao agente.",
"autoFixQueueSupportRequested": "Correção pedida para esta remoção.",
+6
View File
@@ -382,6 +382,7 @@
"prTaskStatusCi": "CI",
"prTaskStatusMerge": "合并",
"prTaskStatusNumber": "PR #{{number}}",
"prTaskStatusRepositoryNumber": "{{repository}} 拉取请求 #{{number}}",
"prTaskStatusReview": "审阅",
"prTaskStatusState": "状态",
"prepareAppOnGithub": "在 GitHub 上准备应用",
@@ -563,7 +564,11 @@
"failedToFetchPrFeedback": "获取 PR 反馈失败",
"failedToFetchPrFiles": "获取 PR 文件失败",
"failedToLoadCiAutomationOptions": "加载 CI 自动化选项失败。",
"failedToResetAutoFixPrompt": "重置自动修复提示失败。",
"failedToRetryAutoMerge": "重试自动合并失败。",
"failedToSaveAutoFixPrompt": "保存自动修复提示失败。",
"failedToSearchGitHub": "在 GitHub 上搜索失败",
"failedToUpdateCiAutomation": "更新 CI 自动化失败。",
"pullRequestNumbered": "Pull Request #{{number}}",
"timeAgoDays_one": "{{count}} 天前",
"timeAgoDays_other": "{{count}} 天前",
@@ -592,6 +597,7 @@
"mergeQueueStatus": "合并队列:{{state}}",
"mergeQueueSubMinuteEstimate": "预计合并时间:少于一分钟",
"autoMergeOrRequeueWhenReady": "就绪时自动合并或重新排队",
"autoMergeRetryAccepted": "已请求重试自动合并。",
"autoFixQueueSupportQueued": "将修复队列检查失败或冲突。",
"autoFixQueueSupportEnable": "启用后将此可处理的队列失败发送给智能体。",
"autoFixQueueSupportRequested": "已请求修复此移除事件。",
+8 -2
View File
@@ -382,6 +382,7 @@
"prTaskStatusCi": "CI",
"prTaskStatusMerge": "合併",
"prTaskStatusNumber": "PR #{{number}}",
"prTaskStatusRepositoryNumber": "{{repository}} 拉取請求 #{{number}}",
"prTaskStatusReview": "審閱",
"prTaskStatusState": "狀態",
"prepareAppOnGithub": "在 GitHub 上準備應用",
@@ -497,8 +498,8 @@
"taskAutoFixPrompt": "任務自動修復提示詞",
"taskGitAccess": "任務 Git 存取",
"taskLabelled": "任務:{{title}}",
"taskPrDetailsLoading": "正在載入拉取請求詳情...",
"taskPrDetailsUnavailable": "拉取請求詳情不可用",
"taskPrDetailsLoading": "正在載入拉取要求詳情...",
"taskPrDetailsUnavailable": "拉取要求詳情不可用",
"taskPrompt": "任務提示詞",
"tasks": "任務",
"tasksCreatedByThisWatcherLand": "此監控建立的任務會進入所選工作區。",
@@ -563,7 +564,11 @@
"failedToFetchPrFeedback": "擷取 PR 反饋失敗",
"failedToFetchPrFiles": "擷取 PR 檔案失敗",
"failedToLoadCiAutomationOptions": "載入 CI 自動化選項失敗。",
"failedToResetAutoFixPrompt": "重置自動修復提示失敗。",
"failedToRetryAutoMerge": "重試自動合併失敗。",
"failedToSaveAutoFixPrompt": "儲存自動修復提示失敗。",
"failedToSearchGitHub": "在 GitHub 上搜尋失敗",
"failedToUpdateCiAutomation": "更新 CI 自動化失敗。",
"pullRequestNumbered": "Pull Request #{{number}}",
"timeAgoDays_one": "{{count}} 天前",
"timeAgoDays_other": "{{count}} 天前",
@@ -592,6 +597,7 @@
"mergeQueueStatus": "合併佇列:{{state}}",
"mergeQueueSubMinuteEstimate": "預計合併時間:少於一分鐘",
"autoMergeOrRequeueWhenReady": "就緒時自動合併或重新排隊",
"autoMergeRetryAccepted": "已請求重試自動合併。",
"autoFixQueueSupportQueued": "將修復佇列檢查失敗或衝突。",
"autoFixQueueSupportEnable": "啓用後將此可處理的佇列失敗傳送給代理程式。",
"autoFixQueueSupportRequested": "已請求修復此移除事件。",
+8 -2
View File
@@ -382,6 +382,7 @@
"prTaskStatusCi": "CI",
"prTaskStatusMerge": "合併",
"prTaskStatusNumber": "PR #{{number}}",
"prTaskStatusRepositoryNumber": "{{repository}} 拉取請求 #{{number}}",
"prTaskStatusReview": "審閱",
"prTaskStatusState": "狀態",
"prepareAppOnGithub": "在 GitHub 上準備應用",
@@ -497,8 +498,8 @@
"taskAutoFixPrompt": "任務自動修復提示詞",
"taskGitAccess": "任務 Git 存取",
"taskLabelled": "任務:{{title}}",
"taskPrDetailsLoading": "正在載入提取要求詳細資料...",
"taskPrDetailsUnavailable": "提取要求詳細資料不可用",
"taskPrDetailsLoading": "正在載入提取要求詳情...",
"taskPrDetailsUnavailable": "提取要求詳情不可用",
"taskPrompt": "任務提示詞",
"tasks": "任務",
"tasksCreatedByThisWatcherLand": "此監控建立的任務會進入所選工作區。",
@@ -563,7 +564,11 @@
"failedToFetchPrFeedback": "擷取 PR 意見回饋失敗",
"failedToFetchPrFiles": "擷取 PR 檔案失敗",
"failedToLoadCiAutomationOptions": "載入 CI 自動化選項失敗。",
"failedToResetAutoFixPrompt": "重置自動修復提示失敗。",
"failedToRetryAutoMerge": "重試自動合併失敗。",
"failedToSaveAutoFixPrompt": "儲存自動修復提示失敗。",
"failedToSearchGitHub": "在 GitHub 上搜尋失敗",
"failedToUpdateCiAutomation": "更新 CI 自動化失敗。",
"pullRequestNumbered": "Pull Request #{{number}}",
"timeAgoDays_one": "{{count}} 天前",
"timeAgoDays_other": "{{count}} 天前",
@@ -592,6 +597,7 @@
"mergeQueueStatus": "合併佇列:{{state}}",
"mergeQueueSubMinuteEstimate": "預計合併時間:少於一分鐘",
"autoMergeOrRequeueWhenReady": "就緒時自動合併或重新排隊",
"autoMergeRetryAccepted": "已請求重試自動合併。",
"autoFixQueueSupportQueued": "將修復佇列檢查失敗或衝突。",
"autoFixQueueSupportEnable": "啟用後將此可處理的佇列失敗傳送給代理程式。",
"autoFixQueueSupportRequested": "已請求修復此移除事件。",
@@ -0,0 +1,81 @@
# ADR-2026-08-28-bind-github-auto-merge-attempts-to-reviewed-head: Bind GitHub auto-merge attempts to the reviewed head
**Status:** accepted
**Date:** 2026-08-28
**Area:** backend, frontend, protocol, security, GitHub
## Context
Kandev refreshes a linked pull request before it starts an automatic merge.
The GitHub request does not include the head SHA from that refresh.
Thus, a force-push can change the merge target between the refresh and the request.
Kandev records an automatic merge signature only after GitHub accepts the request.
An unchanged provider error therefore starts another request during each later evaluation.
This behavior conflicts with the durable per-PR deduplication contract.
The automation error row has one Retry control.
For a stored automation error, this control reloads state but does not retry the failed operation.
An active queue observation can also prove that GitHub accepted a request while the old error remains visible.
## Decision
Each automatic GitHub merge request must include the non-empty head SHA from the fresh readiness snapshot.
GitHub must reject the request if the current head differs from that SHA.
Kandev must reserve an automatic merge attempt in durable per-PR state before it calls GitHub.
The reservation includes the readiness signature, head SHA, time, and attempt result.
The readiness signature includes all merge gates that can re-arm automatic work.
An unchanged signature cannot start another automatic request after an in-flight, failed, queued, or merged result.
A changed signature can start one new automatic request after all readiness gates pass.
If Kandev cannot persist the reservation, it does not call GitHub.
An explicit retry is a scoped command, not an options update or a state refresh.
The command names one linked pull request and authorizes one new evaluation of a failed signature.
It does not bypass readiness checks, head binding, repository scope, or GitHub policy.
Automation errors carry a typed operation source.
An authoritative active queue or merged observation reconciles the attempt as accepted.
That observation clears only an obsolete auto-merge error.
Pending GitHub merge operations use bounded status polling.
The clients wait at least one second between status requests and stop when the operation context ends.
## Consequences
- A reviewed readiness snapshot cannot merge a later force-pushed head.
- Restarts and repeated PR polls do not replay one automatic merge side effect.
- A user can retry a failed merge without toggling automation or changing the pull request.
- Queue adoption removes a stale merge-submission error without erasing an unrelated automation error.
- The per-PR automation state gains typed attempt results and error sources.
- Existing recognized merge errors need a compatibility backfill for their error source.
- Client tests need a controllable poll delay so focused tests remain fast.
## Alternatives Considered
### Trust the current GitHub head at request time
Rejected. The request could merge code that did not produce the readiness snapshot.
### Retry every provider error during later polls
Rejected. Repeated automatic side effects can consume rate limits and hide persistent authorization or policy errors.
### Use exponential automatic retry for transient errors
Rejected. GitHub can accept an asynchronous request before Kandev receives its final status.
An explicit retry or a changed readiness signature gives a safer authorization boundary.
### Reset the attempt by toggling auto-merge
Rejected. An options control must not serve as an implicit side-effect retry command.
### Overload the options PATCH with a retry field
Rejected. A retry is an action with per-request authorization and result semantics, not stored configuration.
## Related Decisions
- [Bind Automation Mutations to Event Targets](2026-08-09-bind-automation-mutations-to-event-targets.md)
- [Separate Current Contribution and Local Checkout Histories](2026-08-10-remote-contribution-head-drift.md)
+1
View File
@@ -214,3 +214,4 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-08-27-bounded-agent-profile-recency | [Store Agent Profile Recency in Bounded Context Rows](2026-08-27-bounded-agent-profile-recency.md) | accepted | backend, frontend, protocol | 2026-08-27 |
| 2026-08-27-protect-deferred-launch-attribution | [Protect Deferred Launch Attribution](2026-08-27-protect-deferred-launch-attribution.md) | accepted | backend, protocol | 2026-08-27 |
| 2026-08-27-preserve-legacy-sqlite-before-default-initialization | [Preserve Legacy SQLite Data Before Default Initialization](2026-08-27-preserve-legacy-sqlite-before-default-initialization.md) | accepted | backend, cli, operations | 2026-08-27 |
| 2026-08-28-bind-github-auto-merge-attempts-to-reviewed-head | [Bind GitHub Auto-Merge Attempts to the Reviewed Head](2026-08-28-bind-github-auto-merge-attempts-to-reviewed-head.md) | accepted | backend, frontend, protocol, security, GitHub | 2026-08-28 |
@@ -0,0 +1,79 @@
---
created: 2026-08-28
status: done
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
legacy_specs: []
---
# Implementation Plan: GitHub Async Merge Response Contract Fix
## Overview
Correct both GitHub clients to decode the documented asynchronous merge
response. Add provider-boundary tests before the production correction.
## Scope
### In scope
- Decode `details.uuid` from pending asynchronous merge responses.
- Decode `details.message` from failed asynchronous merge responses.
- Poll accepted and existing merge requests through both GitHub clients.
- Replace flat response fixtures with the documented nested response shape.
### Out of scope
- Changes to merge eligibility or automation policy.
- Changes to merge-queue observation or persistence.
- UI, localization, database, and public documentation changes.
- Automatic merge retries after a terminal GitHub failure.
## Technical approach
Update `mergeAsyncResponse` in `apps/backend/internal/github/client.go`. Model
the provider `details` object with its UUID and message fields.
Update `GHClient.MergePR` and `PATClient.MergePR` to read the nested fields.
Keep the existing status normalization and the `gh` conflict-body extraction.
Add real response shapes to `gh_client_commands_test.go` and
`pat_client_writes_test.go`. Each client test first receives a nested pending
response. It then polls the UUID and receives a terminal result.
## Tests
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.3`: Both clients poll
`details.uuid` and return the final merged or queued outcome.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.13`: Both clients report
`details.message` for a terminal failed result.
- The `gh` client keeps its embedded JSON extraction for a `409` response.
## E2E tests
No new Playwright test is required. Existing merge-action and CI automation
tests cover normalized outcomes. This fix changes the external provider
decoder below the mock-provider boundary.
## Work orders
- [x] [Task 01: Decode async merge details](task-01-decode-async-merge-details.md)
## Verification results
- The RED test run failed all six nested-response cases for the expected
missing UUID and message behavior.
- `go test -tags fts5 ./internal/github -run 'Test(GHClient|PATClient)_MergePR'`
passed 21 tests.
- `python3 scripts/lint-spec-files.py --all` passed.
- `git diff --check` passed.
- The targeted `gofmt -l` command returned no files.
## Risks
- The `gh` client receives a `409` body inside CLI error text. The correction
must preserve the existing JSON extraction.
- Both clients share the response model. A partial correction can leave one
authentication route broken.
@@ -0,0 +1,94 @@
---
id: "01-decode-async-merge-details"
title: "Decode async merge details"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001
acceptance_criteria:
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.3
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.13
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
---
# Task 01: Decode Async Merge Details
## Summary
Decode GitHub asynchronous merge details in the shared response model. Use
the nested UUID for polling and the nested message for terminal errors.
## In scope
- Add a failing nested-response regression test for each GitHub client.
- Model the documented `details.uuid` and `details.message` fields.
- Poll nested pending responses to a terminal merged or queued outcome.
- Handle a nested pending response from an existing-request conflict.
- Report the nested message from a terminal failed response.
## Out of scope
- GitHub merge eligibility and queue policy.
- Automation retry cadence and deduplication.
- Frontend or persistence changes.
## Acceptance
- Both clients poll the UUID from the provider `details` object.
- Both clients return the existing normalized terminal outcomes.
- A terminal failed result includes the provider message in the error.
## Verification
```bash
# Run from apps/backend.
go test -tags fts5 ./internal/github -run 'Test(GHClient|PATClient)_MergePR'
# Run from the repository root.
python3 scripts/lint-spec-files.py --all
```
## Files likely touched
- `apps/backend/internal/github/client.go`
- `apps/backend/internal/github/gh_client.go`
- `apps/backend/internal/github/pat_client.go`
- `apps/backend/internal/github/gh_client_commands_test.go`
- `apps/backend/internal/github/pat_client_writes_test.go`
- `docs/specs/integrations/system-design/github-pr-merge-queue.md`
## Dependencies
None.
## Risks
- The `gh` conflict response contains JSON and CLI error text.
- The PAT client receives the same response through an HTTP error body.
## Parallelism
`sequential`
## Inputs
- GitHub PR merge-queue requirement and system design.
- Existing asynchronous merge clients and response tests.
- GitHub's documented `status` and nested `details` response object.
## Results
- Added provider-shaped nested pending, conflict, merged, queued, and failed
response fixtures for both GitHub clients.
- The RED test run failed all six focused cases for the expected missing UUID
and message behavior.
- Added the shared `details` response model. Both clients now poll
`details.uuid` and report `details.message`.
- `go test -tags fts5 ./internal/github -run 'Test(GHClient|PATClient)_MergePR'`
passed 21 tests.
- `python3 scripts/lint-spec-files.py --all` passed.
- `git diff --check` passed. The targeted `gofmt -l` command returned no
files.
@@ -0,0 +1,171 @@
---
created: 2026-08-28
status: done
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
- ../../specs/integrations/system-design/github-pr-merge-queue-recovery.md
legacy_specs: []
---
# Implementation Plan: GitHub Auto-Merge Reliability
## Overview
Make each automatic merge attempt safe across force-pushes, provider delays,
concurrent evaluations, and backend restarts. Bind GitHub to the reviewed head.
Reserve each attempt before the provider call. Reconcile accepted queue and
merged states, and expose one explicit retry for a failed attempt.
The provider contract lands first. The durable attempt journal follows it. The
API and shared responsive controls then expose explicit retry. Desktop and
mobile E2E tests prove the complete outcome. Public documentation closes the
delivery package.
## Scope
### In scope
- Send the reviewed head SHA with automatic GitHub merge requests.
- Pace asynchronous merge-status polling within the operation context.
- Store one durable attempt reservation and result per pull request.
- Prevent unchanged automatic retries across events and restarts.
- Reconcile active queue and merged observations with the attempt journal.
- Classify recognized legacy automatic-merge errors during migration.
- Add a scoped explicit retry command for a failed automatic attempt.
- Provide the same retry outcome in the desktop popover and phone drawer.
- Document retry and merge-queue behavior for users.
### Out of scope
- Changing the auto-merge option value or default.
- Retrying an unchanged failed attempt without a user command.
- Bypassing GitHub checks, reviews, mergeability, rules, or permissions.
- Changing the manual merge action's current head-binding contract.
- Adding a new dialog, drawer, page, or automation preference.
- GitLab merge-request automation.
## Technical approach
### Provider request and polling
Replace positional merge parameters with a request value that can carry the
merge method and expected head SHA. Require the SHA on the automatic path and
send it through both GitHub clients. Preserve the manual merge behavior.
Decode the provider's expected-head diagnostic. Wait at least one second
between pending reads. Keep the existing two-minute budget and stop waits when
the context ends. Use an injected wait boundary in focused tests.
### Durable attempt journal
Extend `github_task_ci_pr_state` with the attempt result and typed error kind.
Reserve the readiness signature and head in a transaction before GitHub is
called. Record `failed` or `accepted` after the provider result. Treat the
existing per-PR singleflight as an optimization, not the correctness boundary.
Adopt an observed active queue entry and reconcile a merged pull request as
accepted. Clear only a typed `auto_merge` error. On restart, reconcile an
`in_flight` attempt before it expires to a failed state. Do not submit the same
signature automatically.
### Explicit retry and responsive controls
Add a task-scoped endpoint that accepts the exact linked repository and pull
request. Persist retry authorization, publish the normal evaluation event, and
return `202 Accepted`. The evaluator refreshes state and runs every readiness
gate before it can call GitHub.
The shared automation controls call this command only for an `auto_merge`
error. Other stored errors show Refresh. State-loading failures keep their
existing refresh retry. Mobile continues to use the inset status drawer with
one scroll owner and a shared target of at least 44 by 44 CSS pixels.
### Integrated test support and documentation
Extend the mock GitHub controller and the E2E API client with pending, failure,
queue, merge, and head-mismatch outcomes. Prove one provider request per
authorization on desktop and mobile. Update the public GitHub integration and
session-review guides with the user-visible retry rules.
## Tests
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.1`: provider request and service
tests prove expected-head transmission and mismatch failure.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.2`: store and evaluator tests prove
reservation before the side effect, concurrent deduplication, and restart
safety.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.3`: signature tests prove changed
head or gates can rearm one attempt only after every gate passes.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.4`: controller, service, evaluator,
and E2E tests prove exact-PR retry without gate or permission bypass.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.5`: sync and evaluator tests prove
queue and merged reconciliation with typed error clearing.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.6`: store-failure tests prove that
GitHub is not called and a retryable per-PR error appears.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.7`: deterministic wait tests prove
one-second pacing, cancellation, and the bounded deadline.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.8`: migration tests prove narrow
legacy classification and preservation of unknown errors.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.9`: component and desktop/mobile
E2E tests prove explicit merge retry and separate state refresh.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003.1-.8`: evaluator
regression tests preserve queue adoption, same-head blocking, and new-head
requeue behavior.
## E2E tests
- Desktop: extend `apps/web/e2e/tests/pr/ci-automation-options.spec.ts`. Produce
an automatic merge failure, select Retry, and assert one request for the
named pull request. Then publish an active queue entry and assert that the
obsolete automatic-merge error clears.
- Mobile: extend
`apps/web/e2e/tests/pr/mobile-ci-automation-options.spec.ts` with the same
outcome under touch input. Assert the 44-pixel target, internal drawer
scrolling, and no document-level horizontal overflow.
- Both flows cover a provider head mismatch, an unchanged failed signature, an
accepted queue entry, a merged pull request, and a non-merge loading error.
## Work orders
- [x] [Task 01: Bind and pace asynchronous merge](task-01-bind-and-pace-asynchronous-merge.md)
- [x] [Task 02: Journal automatic merge attempts](task-02-journal-automatic-merge-attempts.md)
- [x] [Task 03: Expose explicit merge retry](task-03-expose-explicit-merge-retry.md)
- [x] [Task 04: Prove responsive merge retry](task-04-prove-responsive-merge-retry.md)
- [x] [Task 05: Document merge retry behavior](task-05-document-merge-retry-behavior.md)
## Verification commands
```bash
make -C apps/backend test
make -C apps/backend lint
cd apps && pnpm --filter @kandev/web lint
cd apps/web && pnpm run typecheck
cd apps/web && pnpm run i18n:check
cd apps/web && pnpm e2e:raw --project=chromium e2e/tests/pr/ci-automation-options.spec.ts
cd apps/web && pnpm e2e:raw --project=mobile-chrome e2e/tests/pr/mobile-ci-automation-options.spec.ts
python3 scripts/lint-spec-files.py --all
node --test scripts/validate-public-docs.test.mjs
node scripts/validate-public-docs.mjs
git diff --check
```
## Risks
- The GitHub client interface has many mocks. A request-value migration can
expose callers outside automation.
- Timer tests can become slow or flaky without an injected wait boundary.
- Legacy error classification can erase the wrong error if it accepts broad
text. The migration must recognize only stable server prefixes.
- A crashed `in_flight` attempt can require user retry when GitHub exposes no
queue or merge observation. This failure is safer than duplicate submission.
- Concurrent HTTP and event evaluations can race. The durable reservation and
transaction must remain the correctness boundary.
- New error-kind and action copy requires all five locale catalogs.
- Manual merge behavior must remain unchanged while the automatic path gains
expected-head enforcement.
## Open questions
None.
@@ -0,0 +1,88 @@
---
id: "01-bind-and-pace-asynchronous-merge"
title: "Bind and pace asynchronous merge"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
acceptance_criteria:
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.1
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.7
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
---
# Task 01: Bind and Pace Asynchronous Merge
## Summary
Carry the reviewed head SHA through the automatic merge provider call. Pace
pending status requests and keep the operation bounded by context.
## In scope
- Replace positional merge parameters with a typed request value.
- Require an expected head on the automation service path.
- Send GitHub's `sha` field through the CLI and PAT clients.
- Decode the provider expected-head diagnostic.
- Wait at least one second between pending reads.
- Add deterministic provider, service, mismatch, timeout, and cancellation tests.
## Out of scope
- Attempt persistence or retry authorization.
- Changes to manual merge eligibility or presentation.
## Acceptance
- An automatic request cannot merge a head that differs from the refreshed head.
- Pending reads occur no more than once per second.
- Cancellation and the existing deadline stop polling promptly.
- Manual merge behavior remains unchanged.
## Verification
```bash
go test -tags fts5 ./internal/github -run 'Test(GHClient|PATClient).*MergePR|TestMergePRForAutomation'
```
Run the command from `apps/backend`.
## Files likely touched
- `apps/backend/internal/github/client.go`
- `apps/backend/internal/github/gh_client.go`
- `apps/backend/internal/github/pat_client.go`
- `apps/backend/internal/github/service_pr.go`
- `apps/backend/internal/github/gh_client_commands_test.go`
- `apps/backend/internal/github/pat_client_writes_test.go`
- `apps/backend/internal/github/service_pr_auth_test.go`
## Dependencies
None.
## Risks
- Interface changes affect provider mocks and non-automation callers.
- Real waits can make tests slow. Tests need an injected wait boundary.
## Parallelism
`sequential`
## Inputs
- Integration acceptance criteria 002.1 and 002.7.
- GitHub asynchronous merge response and expected-head contracts.
## Results
- Added a typed merge request with an optional method and expected head SHA.
- Required a non-empty expected head on the automatic merge service path.
- Sent GitHub's `sha` field through the CLI and token clients.
- Added context-aware one-second pacing before pending status reads.
- Included the provider's expected head in failed-request diagnostics.
- Verification: focused GitHub tests passed, 26 tests.
- Verification: orchestrator head-forwarding regression passed, 1 test.
@@ -0,0 +1,108 @@
---
id: "02-journal-automatic-merge-attempts"
title: "Journal automatic merge attempts"
status: done
wave: 2
depends_on:
- "01-bind-and-pace-asynchronous-merge"
plan: "plan.md"
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003
acceptance_criteria:
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.2
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.3
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.5
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.6
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.8
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003.1
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003.2
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003.3
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003.7
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003.8
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
- ../../specs/integrations/system-design/github-pr-merge-queue-recovery.md
---
# Task 02: Journal Automatic Merge Attempts
## Summary
Persist the readiness signature, attempted head, result, and error kind before
the provider side effect. Reconcile queue, merge, failure, and restart states.
## In scope
- Add attempt-result and error-kind columns to CI per-PR state.
- Round-trip the fields through every store path.
- Classify only recognized legacy automatic-merge errors during migration.
- Reserve an `in_flight` attempt in a transaction before the provider call.
- Record failed and accepted results.
- Reconcile active queue and merged observations as accepted.
- Clear only typed automatic-merge errors.
- Expire an unreconciled restart attempt to failed without resubmission.
- Preserve same-head removal guards and changed-head requeue behavior.
- Add store, evaluator, failure-injection, concurrency, and restart tests.
## Out of scope
- The HTTP retry command and frontend action.
- New queue-removal classifications.
## Acceptance
- One readiness signature causes no more than one automatic provider request.
- A storage failure causes no provider request and exposes a retryable error.
- Queue or merged state repairs an ambiguous provider result safely.
- Unrelated automation errors survive queue and merged reconciliation.
- A changed eligible head can authorize one later attempt.
## Verification
```bash
go test -tags fts5 ./internal/github ./internal/orchestrator -run 'Test.*(MergeAttempt|AutoMerge|QueueAttempt|MergeSignature)'
go test -race -tags fts5 ./internal/github ./internal/orchestrator -run 'Test.*(MergeAttempt|AutoMerge)'
```
Run the commands from `apps/backend`.
## Files likely touched
- `apps/backend/internal/github/models.go`
- `apps/backend/internal/github/store.go`
- `apps/backend/internal/github/service_ci_automation.go`
- `apps/backend/internal/orchestrator/event_handlers_github_ci_automation.go`
- `apps/backend/internal/orchestrator/event_handlers_github_ci_automation_recovery.go`
- Focused store, service, evaluator, and recovery test files.
## Dependencies
- Task 01 provides the head-bound provider request.
## Risks
- Every CI-state insert, update, restore, and replace path must preserve fields.
- An overly broad legacy migration can misclassify an unrelated error.
- Singleflight alone cannot prevent a duplicate after restart.
## Parallelism
`sequential`
## Inputs
- Task 01 provider contract.
- Integration acceptance criteria 002.2, 002.3, 002.5, 002.6, and 002.8.
- Existing queue-recovery acceptance criteria 003.1 through 003.8.
## Results
- Added durable `in_flight`, `failed`, and `accepted` attempt results.
- Reserved each readiness signature before the GitHub side effect.
- Bound completion results to the reserved signature to reject stale results.
- Added typed automatic-merge errors and a narrow legacy backfill.
- Reconciled active queue and merged observations without clearing unrelated errors.
- Expired stale in-flight attempts to failed without automatic resubmission.
- Extended the readiness signature with every merge gate.
- Verification: focused backend tests passed, 32 tests.
- Verification: focused race tests passed, 23 tests.
@@ -0,0 +1,104 @@
---
id: "03-expose-explicit-merge-retry"
title: "Expose explicit merge retry"
status: done
wave: 3
depends_on:
- "02-journal-automatic-merge-attempts"
plan: "plan.md"
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
acceptance_criteria:
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.4
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.9
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
---
# Task 03: Expose Explicit Merge Retry
## Summary
Add a task-scoped command that rearms one failed automatic merge attempt. Wire
the shared desktop and mobile controls to that command.
## In scope
- Add the retry route, controller, service method, and exact-PR authorization.
- Persist retry authorization and publish the normal evaluation event.
- Return `202 Accepted` without claiming provider success.
- Extend frontend API types and automation state with the typed error kind.
- Call explicit retry only for an `auto_merge` error.
- Label other stored errors as Refresh and keep load-error refresh behavior.
- Keep the existing desktop popover and inset mobile status drawer.
- Keep one mobile scroll owner and a 44-by-44-pixel shared action target.
- Add backend, API-client, hook, component, and locale tests.
- Add copy to the five required locale catalogs.
## Out of scope
- Direct provider calls from the controller.
- A new dialog, drawer, route, or automation switch.
- Relaxing any readiness or provider rule.
## Acceptance
- Retry addresses only the named pull request linked to the authorized task.
- The command reevaluates every current readiness gate.
- Desktop and mobile expose the same action and feedback.
- A state-load failure refreshes state and never rearms a merge attempt.
## Verification
```bash
go test -tags fts5 ./internal/github -run 'Test.*Retry.*Merge'
cd apps/web && pnpm test -- components/github/pr-ci-automation-controls.test.tsx
cd apps/web && pnpm run typecheck
cd apps/web && pnpm run i18n:check
```
Run Go from `apps/backend`. Run pnpm from the locations shown.
## Files likely touched
- `apps/backend/internal/github/controller.go`
- `apps/backend/internal/github/service_ci_automation.go`
- Backend controller and service test files.
- `apps/web/lib/api/domains/github-api.ts`
- `apps/web/lib/types/github.ts`
- `apps/web/hooks/domains/github/use-task-ci-options.ts`
- `apps/web/components/github/pr-ci-automation-controls.tsx`
- Focused frontend test files.
- `apps/web/src/locales/{en,pt-pt,zh-cn,zh-hk,zh-tw}/github.json`
## Dependencies
- Task 02 provides the durable attempt and retry-authorization state.
## Risks
- The endpoint must not accept a repository or pull request outside the task.
- Error-kind copy must remain complete across all required locales.
- The mobile drawer must keep a single scroll owner.
## Parallelism
`sequential`
## Inputs
- Task 02 attempt journal.
- Integration acceptance criteria 002.4 and 002.9.
- Existing shared desktop and mobile automation controls.
## Results
- Added an authorized task-scoped `202 Accepted` retry command for one linked
pull request and published the normal PR evaluation event.
- Persisted a single-use retry authorization that the attempt reservation
consumes atomically, including duplicate and stale in-flight guards.
- Added typed frontend error handling so only `auto_merge` failures rearm a
merge. Other stored and loading errors retain state refresh.
- Kept the shared desktop and mobile controls and added a 44-pixel mobile
action target with complete localized copy.
- Passed the focused backend retry tests, component/API/hook tests, TypeScript
typecheck, and the complete i18n check.
@@ -0,0 +1,95 @@
---
id: "04-prove-responsive-merge-retry"
title: "Prove responsive merge retry"
status: done
wave: 4
depends_on:
- "03-expose-explicit-merge-retry"
plan: "plan.md"
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
acceptance_criteria:
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.4
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.5
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.9
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
---
# Task 04: Prove Responsive Merge Retry
## Summary
Extend mock GitHub behavior and prove the complete retry and reconciliation
outcome in the existing desktop popover and phone drawer.
## In scope
- Add mock outcomes for pending, failure, head mismatch, queue, and merge.
- Expose request counts and target pull-request identity to E2E tests.
- Cover the automatic failure and explicit retry flow on desktop.
- Cover the same outcome with touch input on mobile.
- Prove unchanged state does not retry automatically.
- Prove an active queue or merged observation clears only the merge error.
- Prove a loading error performs state refresh only.
- Assert the mobile target size, internal scrolling, and page overflow contract.
## Out of scope
- Product behavior beyond the approved requirements.
- A new E2E page object for unrelated pull-request actions.
## Acceptance
- Each authorization produces at most one provider request.
- Retry targets the selected pull request on desktop and mobile.
- Queue and merged observations remove obsolete merge errors.
- Responsive behavior meets the existing drawer and touch contracts.
## Verification
```bash
cd apps/web && pnpm e2e:raw --project=chromium e2e/tests/pr/ci-automation-options.spec.ts
cd apps/web && pnpm e2e:raw --project=mobile-chrome e2e/tests/pr/mobile-ci-automation-options.spec.ts
```
## Files likely touched
- `apps/backend/internal/github/mock_controller.go`
- `apps/web/e2e/api/github.ts`
- `apps/web/e2e/tests/pr/ci-automation-options.spec.ts`
- `apps/web/e2e/tests/pr/mobile-ci-automation-options.spec.ts`
## Dependencies
- Task 03 exposes the backend and frontend retry path.
## Risks
- E2E request counts need stable reset and isolation between tests.
- Mock pending behavior must not add real one-second delays to unrelated tests.
## Parallelism
`parallel-safe-with-task-05`
## Inputs
- Task 03 retry command and responsive controls.
- Existing automation E2E fixtures and mobile status drawer.
## Results
- Extended the mock provider with deterministic merged, queued, failed,
pending-exhaustion, and head-mismatch outcomes plus expected-head attempt
evidence.
- Added desktop and mobile flows that prove unchanged failures do not retry,
explicit retry targets the same PR and reviewed head once, and accepted
results clear the typed merge error.
- Proved lifecycle errors retain Refresh, the mobile retry target is at least
44 by 44 CSS pixels, the drawer keeps internal scrolling, and the document
does not overflow horizontally.
- Fixed the evaluator integration exposed by E2E: explicit retry now overrides
the same-head queue guard, and concurrent PR events coalesce one follow-up
evaluation instead of dropping it.
- Passed all 6 desktop Chromium cases and all 5 mobile Chrome cases in the
task-defined specifications.
@@ -0,0 +1,87 @@
---
id: "05-document-merge-retry-behavior"
title: "Document merge retry behavior"
status: done
wave: 4
depends_on:
- "03-expose-explicit-merge-retry"
plan: "plan.md"
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
acceptance_criteria:
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.4
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.5
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.9
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
---
# Task 05: Document Merge Retry Behavior
## Summary
Explain how automatic merge binds the current head, pauses after a failed
unchanged attempt, and resumes through explicit retry or a new eligible state.
## In scope
- Update the public GitHub integration guide.
- Update the public session and review guide.
- Explain queue adoption and obsolete automatic-error reconciliation.
- Distinguish merge retry from state refresh.
- Use Simplified Technical English and current product terminology.
- Run public-documentation and link validation.
## Out of scope
- Internal schema or endpoint details.
- Documentation for GitLab automation.
## Acceptance
- Users can identify when Kandev retries automatically and when it waits.
- Users can distinguish Retry from Refresh.
- The guides explain behavior for active queue and merged pull requests.
## Verification
```bash
node --test scripts/validate-public-docs.test.mjs
node scripts/validate-public-docs.mjs
python3 scripts/lint-spec-files.py --all
```
Run the commands from the repository root.
## Files likely touched
- `docs/public/integrations.md`
- `docs/public/sessions-and-review.md`
## Dependencies
- Task 03 finalizes the visible labels and retry outcome.
## Risks
- Documentation can drift if the final action label changes during implementation.
- The guide must not imply that Retry bypasses GitHub policy.
## Parallelism
`parallel-safe-with-task-04`
## Inputs
- Task 03 user-visible retry behavior.
- Integration acceptance criteria 002.4, 002.5, and 002.9.
## Results
- Documented that automatic merge binds the reviewed head and does not repeat
an unchanged failed attempt without a new eligible state or explicit Retry.
- Explained that Retry requests one new evaluation for the selected pull
request, while Refresh only reloads state and cannot authorize a merge.
- Documented that active queue and merged observations reconcile the attempt as
accepted and clear only an obsolete automatic-merge error.
- Passed the public-document tests, public-document validator, and complete
specification lint.
@@ -0,0 +1,140 @@
---
created: 2026-08-28
status: completed
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
- REQ-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
- ../../specs/platform/system-design/bounded-task-status-delivery.md
legacy_specs: []
---
# Implementation Plan: GitHub Sidebar Automation Indicators
## Overview
Show active GitHub auto-fix and auto-merge settings directly on the task-row
pull-request icon. Extend the bounded task summary first so every visible row
has reliable state without an HTTP request. Then add the two corner indicators,
detailed desktop and touch disclosure, and end-to-end coverage.
## Scope
### In scope
- Aggregate active per-pull-request auto-fix and auto-merge state into the
bounded task summary.
- Update the summary after an option change, pull-request lifecycle change,
unlink, restart, or list hydration.
- Show a yellow top-left auto-fix dot and a purple top-right auto-merge dot on
the task-row pull-request icon.
- Let both indicators appear together without obscuring the pull-request glyph
or its status color.
- Identify enabled settings and their active pull requests through pointer,
keyboard, and touch disclosure.
- Preserve the shared desktop sidebar and mobile task-switcher row behavior.
### Out of scope
- Editing automation settings from a task row.
- Showing automation indicators for merged or closed pull requests.
- Adding indicators to GitLab merge-request icons.
- Loading full automation options for every visible task row.
- Changing the colors or precedence of pull-request lifecycle status.
## Technical approach
### Bounded automation projection
Add `auto_fix_enabled` and `auto_merge_enabled` to
`statussummary.PullRequestSummary` and the frontend `TaskStatusSummary` type.
Add both switches to the internal keyed pull-request observation. Derive each
summary flag with an `any active PR enabled` rule and omit false values.
Extend `githubTaskStatusSummaryPRReader` to batch the linked pull requests and
their stored `TaskPRAutomationOptions`. The status-summary projector subscribes
to `GitHubTaskCIOptionsUpdated` and refreshes authoritative pull-request
observations for the affected task before publishing a replacement summary.
Boot hydration, restart rehydration, compare-and-set rebases, and PR lifecycle
events continue through the same loader and projector boundary.
Pipe the two bounded flags through the desktop and mobile task item models into
the pull-request icon. A task row does not mount the eager automation-options
hook and does not issue one request per task.
### Icon and disclosure
Keep the existing 14-pixel pull-request glyph and status color. Wrap the glyph
in a relative inline box. Render a small yellow dot at the top-left for
auto-fix and a small purple dot at the top-right for auto-merge. Give each dot
a surface-colored ring and a stable test ID. Extend the icon's accessible name
with localized automation state so color is supplementary.
Fine pointers and keyboard focus keep the existing tooltip. Its Automation
section uses lazily hydrated `TaskCIOptionsResponse.pr_options` to identify the
enabled settings for each active pull request. Coarse pointers use the existing
compact task-status drawer pattern. The mobile trigger has a 44-pixel touch
target, stops row navigation only for the disclosure gesture, returns focus on
dismissal, and keeps one internal scroll owner without horizontal overflow.
Extend the current tooltip hydration boundary to fetch pull-request details and
automation options together on first disclosure. Deduplicate concurrent loads
per workspace generation and task, discard stale workspace responses, and
reuse the existing GitHub store and matching helpers.
## Tests
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10`: status-summary model,
projector, rebuild, adapter, mapper, and icon tests prove independent and
combined flags, active-only aggregation, live updates, and restart hydration.
- `AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.11`: component and hydration tests
prove per-pull-request details, accessible text, pointer/focus behavior, and
touch disclosure.
- `AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.1-.3`: projector and task-row
tests prove the state is bounded, rebuildable, delivered through task-summary
updates, and does not add per-row session or automation subscriptions.
## E2E tests
- Desktop Chromium extends `apps/web/e2e/tests/pr/pr-status-badge.spec.ts`.
Seed independent and combined settings, reload the task list, assert both dot
positions remain within the icon box, hover the icon, and verify the named
per-pull-request automation details.
- Mobile Chrome adds
`apps/web/e2e/tests/pr/mobile-pr-sidebar-automation-indicators.spec.ts`.
Open the task-switcher drawer, assert the same dots, tap the touch-sized PR
target, verify the automation drawer content, dismiss it, and assert no
document-level horizontal overflow.
- Both projects prove merged and closed pull requests do not show active dots
and an option update changes the row without opening the task.
## Work orders
- [x] [Task 01: Project sidebar automation state](task-01-project-sidebar-automation-state.md) — completed
- [x] [Task 02: Render responsive automation indicators](task-02-render-responsive-automation-indicators.md) — completed
## Verification results
Completed. Backend projection, frontend row mapping, responsive disclosures, and regression
coverage are implemented.
- `go test -tags fts5 ./internal/task/statussummary ./internal/backendapp ./internal/github` — passed (2,473 tests).
- `pnpm test -- components/github/pr-task-icon.automation.test.ts components/github/pr-task-icon.render.test.tsx components/github/pr-ci-automation-controls.test.tsx components/github/pr-ci-popover.automation.test.tsx components/task/task-session-sidebar-item.test.ts components/task/mobile/session-task-switcher-sheet.test.tsx hooks/domains/github/use-task-pr-tooltip-hydration.test.tsx hooks/domains/github/use-task-ci-options.test.tsx lib/api/domains/github-api.test.ts lib/api/domains/github-auto-merge-api.test.ts` — passed (94 tests).
- `pnpm --filter @kandev/web lint` — passed.
- `pnpm run typecheck` — passed.
- `pnpm run i18n:check` — passed.
- Managed Chromium E2E for the sidebar automation scenario — passed.
- Managed Mobile Chrome E2E for the sidebar automation scenario — passed.
## Risks
- Joining per-pull-request options incorrectly can attach settings to the same
PR number in another repository. Matching must retain repository identity.
- Parsing only the option-update event payload can lose sibling PR state. The
projector must refresh the complete authoritative observation set.
- Mounting the existing eager options hook in every task row would create an
unbounded request fan-out and violate the task-summary contract.
- A touch disclosure inside a navigable task row can trigger both actions. The
icon gesture must stop row navigation without changing desktop row behavior.
- Tiny overlay dots can disappear against status colors without a contrasting
ring or can obscure the glyph if positioned outside its local icon box.
@@ -0,0 +1,103 @@
---
id: "01-project-sidebar-automation-state"
title: "Project sidebar automation state"
status: completed
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
- REQ-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001
acceptance_criteria:
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10
- AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.1
- AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.2
- AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.3
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
- ../../specs/platform/system-design/bounded-task-status-delivery.md
---
# Task 01: Project Sidebar Automation State
## Summary
Extend the bounded task status summary with active GitHub auto-fix and
auto-merge flags. Keep the projection authoritative across live option and
pull-request changes, list hydration, and backend restart.
## In scope
- Extend backend and frontend task-summary contracts with two optional flags.
- Include repository-qualified per-pull-request automation options in the
authoritative pull-request loader.
- Aggregate only open linked pull requests.
- Refresh the complete pull-request observation set after an automation-option
update.
- Pipe the flags through desktop and mobile task-row item models.
- Add backend and frontend contract tests before implementation.
## Out of scope
- Rendering dots, tooltips, or drawers.
- Loading detailed automation options from task rows.
- Changing automation settings or provider actions.
## Acceptance
- Independent and combined active settings produce the correct two bounded
flags, while merged and closed pull requests do not contribute.
- Boot, restart, option-update, pull-request-update, and compare-and-set paths
converge on the same complete replacement summary.
- Desktop and mobile item models receive the flags without mounting a per-row
automation-options request.
## Verification
```bash
cd apps/backend && go test -tags fts5 ./internal/task/statussummary ./internal/backendapp ./internal/github
cd apps/web && pnpm test -- lib/ws/handlers/tasks-status-summary.test.ts components/task/task-session-sidebar-item.test.ts components/task/mobile/session-task-switcher-sheet-hooks.test.ts
```
## Files likely touched
- `apps/backend/internal/task/statussummary/model.go`
- `apps/backend/internal/task/statussummary/rebuild.go`
- `apps/backend/internal/task/statussummary/projector.go`
- `apps/backend/internal/task/statussummary/projector_events.go`
- `apps/backend/internal/task/statussummary/projector_pr.go`
- `apps/backend/internal/backendapp/status_summary_adapter.go`
- `apps/web/lib/types/task-status-summary.ts`
- `apps/web/components/task/task-session-sidebar-item.ts`
- `apps/web/components/task/mobile/session-task-switcher-sheet-item.ts`
## Dependencies
None.
## Risks
- Per-pull-request option matching must use repository ID and PR number.
- The projector must replace its complete PR observation map on option updates
so disabled or terminal siblings cannot leave a stale aggregate flag.
## Parallelism
`sequential`
## Inputs
- Integration acceptance criterion 002.10.
- Bounded task-status delivery criteria 001.1 through 001.3.
- Existing pull-request summary projector and authoritative loader.
## Results
Implemented and verified. The bounded summary now carries active-only
auto-fix and auto-merge flags, refreshes the complete PR observation set after
option updates, and hydrates repository-qualified options through the existing
batch reader. Desktop and mobile row mappers preserve the flags without adding
per-row requests.
Verification: focused backend packages passed (2,473 tests), focused mapper
and hydration suites passed, and the desktop/mobile sidebar E2E scenarios
passed.
@@ -0,0 +1,108 @@
---
id: "02-render-responsive-automation-indicators"
title: "Render responsive automation indicators"
status: completed
wave: 2
depends_on:
- "01-project-sidebar-automation-state"
plan: "plan.md"
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
- REQ-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001
acceptance_criteria:
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10
- AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.11
- AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.1
- AC-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001.3
system_design:
- ../../specs/integrations/system-design/github-pr-merge-queue.md
- ../../specs/platform/system-design/bounded-task-status-delivery.md
---
# Task 02: Render Responsive Automation Indicators
## Summary
Render the two corner dots on the task-row pull-request icon and expose the
enabled per-pull-request settings through the existing desktop and mobile
status disclosure patterns.
## In scope
- Add independent yellow auto-fix and purple auto-merge dots with a contrasting
ring and stable selectors.
- Extend accessible icon text with enabled automation state.
- Lazily hydrate and deduplicate per-pull-request automation details when the
icon disclosure opens.
- Extend the desktop tooltip for pointer and keyboard users.
- Add a touch-sized mobile trigger and compact drawer with the same information.
- Add localized copy in all supported catalogs.
- Add component, hydration, desktop E2E, and mobile E2E tests before production
implementation.
## Out of scope
- Automation mutation controls in the tooltip or drawer.
- New task-row settings or presentation preferences.
- GitLab merge-request indicators.
## Acceptance
- The PR glyph remains readable with either dot or both dots, and each dot stays
inside its local icon box.
- Pointer hover, keyboard focus, and touch activation expose the same enabled
settings and active pull-request identities without eager row requests.
- Mobile preserves the task row's primary navigation, uses a 44-pixel trigger,
returns focus after dismissal, and creates no document horizontal overflow.
## Verification
```bash
cd apps/web && pnpm test -- components/github/pr-task-icon.automation.test.tsx hooks/domains/github/use-task-pr-tooltip-hydration.test.tsx
cd apps/web && pnpm run lint
cd apps/web && pnpm run typecheck
cd apps/web && pnpm run i18n:check
cd apps/web && pnpm e2e:run --project chromium tests/pr/pr-status-badge.spec.ts -- --grep "sidebar automation indicators"
cd apps/web && pnpm e2e:run --project mobile-chrome tests/pr/mobile-pr-sidebar-automation-indicators.spec.ts
```
## Files likely touched
- `apps/web/components/github/pr-task-icon.tsx`
- `apps/web/components/github/pr-task-status-summary.tsx`
- `apps/web/hooks/domains/github/use-task-pr-tooltip-hydration.ts`
- `apps/web/components/task/task-contribution-icons.tsx`
- `apps/web/components/task/task-item-leading-badges.tsx`
- `apps/web/src/locales/*/github.json`
- `apps/web/e2e/tests/pr/pr-status-badge.spec.ts`
- `apps/web/e2e/tests/pr/mobile-pr-sidebar-automation-indicators.spec.ts`
## Dependencies
- Task 01 supplies the bounded automation flags to every task row.
## Risks
- The mobile icon interaction is nested inside a navigable row and must not
activate both the disclosure and task navigation.
- Lazy PR and option responses must retain workspace-generation guards so a
task switch cannot apply stale data.
## Parallelism
`sequential`
## Inputs
- Integration acceptance criteria 002.10 and 002.11.
- Task 01 bounded summary fields.
- Existing PR task tooltip, touch drawer, and automation matching helpers.
## Results
Implemented and verified. The PR icon renders independent yellow and purple
corner dots, exposes localized active-PR automation details through a lazy
desktop tooltip or touch drawer, and preserves row navigation and focus
behavior on mobile.
Verification: 94 focused web tests passed, lint/typecheck/i18n checks passed,
and the managed Chromium and Mobile Chrome sidebar E2E scenarios passed.
+6
View File
@@ -322,6 +322,12 @@ When GitHub puts a linked pull request in a merge queue, the PR status control s
The existing two automation switches also control merge-queue recovery. Auto-fix sends one actionable queue removal to the linked task agent and counts it as one auto-fix round. Auto-merge submits an eligible pull request through GitHub's queue-aware merge action. If GitHub removes a queue attempt, Kandev records the reason and waits for a new pull-request head before it submits another attempt; it never retries the same head automatically. An active queue entry is adopted when auto-merge is enabled, so enabling the option does not submit a duplicate request. Unknown, manual, and branch-protection removals remain visible but do not start automatic repair.
Each automatic merge request uses the pull-request head that passed the readiness checks. If GitHub reports a different head, Kandev stops the request. After a failed request, Kandev does not automatically repeat the same readiness state.
Use **Retry** to request one new evaluation for the selected linked pull request. Kandev refreshes the pull request and applies all current readiness and GitHub policy rules. **Retry** accepts the evaluation request. It does not report a completed merge.
Use **Refresh** for a state-loading error or another automation error. Refresh loads state only and does not authorize a merge. If GitHub shows an active queue entry or a merged pull request, Kandev marks the attempt accepted. It removes only the obsolete automatic-merge error.
**Your review is requested** matches the GitHub account connected to the task's workspace. The first observation is a quiet baseline. Any later transition to a request for that account wakes the agent, including the first new request after baselining and a re-review request after changes. Clearing a request rearms the next transition. If the workspace's connected GitHub account changes, Kandev quietly rebinds the task and re-establishes every linked PR's baseline; switching accounts does not itself create a prompt.
**PR merged** and **PR closed without merging** are separate subscriptions to the same kind of follow-up: waking the agent when review work ends. Each notifies once when its linked PR enters the selected terminal state. Kandev delivers lifecycle notifications to the task's active promptable session, preferring the primary session. It does not interrupt a busy session: it queues a message for delivery when that session is available. If the task has no promptable session, Kandev records the per-PR delivery error, creates no new session, and retries once a session becomes promptable.
+2
View File
@@ -196,6 +196,8 @@ When a task has multiple linked pull requests, use the PR selector in the Change
When several pull requests are linked to a task, hover the PR control in the desktop top bar or tap the PR status chip on mobile to open the tabbed CI surface. Each PR tab has a **Remove from task** button. Removing a tab only detaches that Kandev task association; it does not close or modify the GitHub pull request, its branch or commits, the task repositories, or sibling PR associations. Explicitly linking that PR again restores the association.
An automatic-merge error shows **Retry** in the selected PR tab on desktop and mobile. This action requests one new evaluation for that pull request. Kandev applies all current readiness rules before it sends another merge request. Other automation and state-loading errors show **Refresh**. Refresh loads the current state and does not authorize a merge.
<DocsVideo
webm="./media/feature-guides/diff-line-feedback.webm"
mp4="./media/feature-guides/diff-line-feedback.mp4"
@@ -111,6 +111,8 @@ same-head retry loop or reversing an intentional queue removal.
## Related requirements
- [GitHub PR Merge Queue](github-pr-merge-queue.md)
`REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002` owns attempt reservation,
explicit retry, and stale auto-merge error reconciliation.
- [Task PR Automation Controls](../../ui/requirements/ci-pr-automation.md)
- [Merge Queue Recovery Controls](../../ui/requirements/ci-pr-merge-queue-recovery-controls.md)
@@ -14,6 +14,18 @@ The integration system owns GitHub merge actions and merge-queue state. Users
must be able to merge an eligible pull request without leaving Kandev. Kandev
must show whether GitHub merged the pull request or added it to a merge queue.
The same provider contract owns automatic merge attempts from linked tasks.
Kandev must bind each attempt to the pull-request state that passed its readiness gates.
## Terminology
- **Readiness signature:** A stable identity for one pull-request head and its
observed merge gates.
- **Automatic attempt:** A merge request that Kandev starts after auto-merge
observes a ready pull request.
- **Explicit retry:** One user-requested evaluation of a prior failed automatic
attempt for one linked pull request.
## Requirements
### REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001: GitHub PR Merge Queue
@@ -39,12 +51,59 @@ state from the existing pull-request surfaces.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.13:** When GitHub rejects a merge request, Kandev shall show the error, preserve state, and leave the action available for retry.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001.14:** When users view queue state on desktop or mobile, Kandev shall provide the same outcome without hover-dependent controls or horizontal page overflow.
### REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002: Reliable automatic merge attempts
**Intent:** Automatic merge must act on the reviewed pull-request head without
repeating an unchanged side effect or leaving obsolete errors after GitHub accepts it.
#### Acceptance criteria
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.1:** When Kandev starts an
automatic merge, the request shall require the non-empty head SHA from the
fresh readiness snapshot. A different current head shall not merge.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.2:** Before Kandev calls GitHub,
it shall durably reserve the per-PR readiness signature and attempted head.
A restart or unchanged later poll shall not repeat that automatic request.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.3:** When a readiness gate or the
pull-request head changes, Kandev shall permit one new automatic attempt only
after every current gate passes.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.4:** When the user retries a
failed automatic merge, Kandev shall reevaluate only the named linked pull
request. The retry shall not bypass readiness, head binding, repository
scope, permissions, or GitHub policy.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.5:** When GitHub reports an
active queue entry or a merged pull request, Kandev shall reconcile the
attempt as accepted and clear only its obsolete auto-merge error.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.6:** When Kandev cannot persist
the automatic attempt reservation, it shall not call GitHub and shall show a
retryable per-PR error.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.7:** While GitHub reports a
pending asynchronous merge, Kandev shall request status no more than once per
second and shall stop when the bounded operation context ends.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.8:** When an upgrade finds a
recognized legacy auto-merge error, Kandev shall classify it so a later queue
or merged observation can clear it.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.9:** When users view an
auto-merge error on desktop or mobile, they shall have the same explicit
retry action. A load error shall keep a separate state-refresh action.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.10:** When auto-fix is enabled
for at least one active linked pull request, the task-row pull-request icon
shall show a yellow indicator at its top-left. When auto-merge is enabled,
it shall show a purple indicator at its top-right. Both indicators can
appear together.
- **AC-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002.11:** When a user examines the
task-row pull-request icon with a pointer, keyboard, or touch input, Kandev
shall identify the enabled automation settings and the active pull requests
that use them. Merged and closed pull requests shall not produce active
automation indicators.
## Out of scope
- Displaying or navigating the complete merge queue.
- Removing a pull request from the merge queue.
- Selecting between direct merge and queue entry when GitHub permits both.
- Changing Kandev's independent CI auto-merge setting.
- Changing the stored value or default of Kandev's independent CI auto-merge setting.
- Changing automation settings from the task-row pull-request indicator.
- Adding merge-queue behavior for GitLab merge requests.
## System design
@@ -53,5 +112,7 @@ state from the existing pull-request surfaces.
## Implementation plans
- [Automatic merge reliability plan](../../../plans/github-auto-merge-reliability/plan.md)
- [Sidebar automation indicators plan](../../../plans/github-sidebar-automation-indicators/plan.md)
- [Queue-status visibility plan](../../../plans/github-pr-merge-queue-status/plan.md)
- [Original queue-aware merge action plan](../../../plans/github-pr-merge-queue/plan.md)
@@ -2,6 +2,7 @@
status: draft
system: integrations
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-001
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-002
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003
@@ -24,6 +25,7 @@ Kandev keeps the existing one-minute poll interval and queue-aware merge API.
| Requirement | Design section |
| --- | --- |
| `REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002` | [Requeue flow](#requeue-flow), [Failure and recovery](#failure-and-recovery) |
| `REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-001` | [Provider observation](#provider-observation), [Persistence](#persistence) |
| `REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-002` | [Auto-fix flow](#auto-fix-flow) |
| `REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-RECOVERY-003` | [Requeue flow](#requeue-flow) |
@@ -88,6 +90,10 @@ publishes them to current automation and UI consumers.
removal. Values are `checks_failed`, `checks_timed_out`, `conflict`,
`manual`, `branch_protection`, and `unknown`.
The main merge-queue design owns the automatic attempt journal, typed error
kind, and explicit retry authorization. Recovery reads that journal but does not
define a second attempt state machine.
## Auto-fix flow
`handleTaskPRCIAutomationWithRefresh` evaluates queue evidence before normal PR
@@ -143,6 +149,10 @@ This observation also handles a user who enables auto-merge while the pull
request is already queued. The evaluator adopts the active entry and returns
without calling the merge API.
Adoption records the attempt as `accepted`. It clears a stale error only when
the stored error kind is `auto_merge`. A merged observation applies the same
reconciliation rule.
When Kandev first observes a removal without an earlier active observation, it
records a conservative baseline for the current head. This fallback prevents
an immediate same-head requeue.
@@ -176,6 +186,8 @@ The option combinations produce these outcomes:
- If removal evidence is not actionable, Kandev records the status only.
- If the current head SHA is absent, Kandev does not requeue automatically.
- If GitHub rejects a requeue request, the existing error row shows the error.
- If an `in_flight` attempt survives a restart, Kandev reconciles queue and
merged state before it fails the attempt and offers explicit retry.
- If a repair produces no new head, Kandev waits. A user can repair or requeue
the pull request on GitHub.
@@ -198,6 +210,7 @@ reads, dispatches, and queue requests to the automation surface.
## Related decisions and designs
- [Bind automatic merge attempts to the reviewed head](../../../decisions/2026-08-28-bind-github-auto-merge-attempts-to-reviewed-head.md)
- [GitHub PR Merge Queue requirements](../requirements/github-pr-merge-queue.md)
- [Task PR Automation Controls design](../../ui/system-design/ci-pr-automation-01.md)
- [PR agent notification decision](../../../decisions/0051-pr-agent-notifications-extend-task-pr-automation.md)
@@ -3,6 +3,7 @@ status: current
system: integrations
requirements:
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001
- REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002
created: 2026-08-24
owners:
- kandev
@@ -25,6 +26,7 @@ desktop and mobile behavior.
| Requirement | Design sections |
| --- | --- |
| `REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-001` | [Components](#components-and-responsibilities), [Data](#data-and-contracts), [Control flow](#control-flow), [Failure](#failure-and-recovery), [Presentation](#presentation-and-responsive-behavior) |
| `REQ-INTEGRATIONS-GITHUB-PR-MERGE-QUEUE-002` | [Data](#data-and-contracts), [Automatic merge](#automatic-merge), [Explicit retry](#explicit-retry), [Task-row projection](#task-row-automation-projection), [Failure](#failure-and-recovery), [Persistence](#persistence), [Presentation](#presentation-and-responsive-behavior) |
## Components and responsibilities
@@ -32,6 +34,8 @@ desktop and mobile behavior.
- `apps/backend/internal/github/client.go` defines the typed merge outcome.
- `gh_client.go` and `pat_client.go` call GitHub's asynchronous merge endpoint.
- The clients bind an automatic request to an expected head and pace pending
status reads within the request context.
- `graphql.go` reads and normalizes `mergeQueueEntry` state and metadata.
### Integration service and storage
@@ -44,13 +48,18 @@ desktop and mobile behavior.
the normal pull-request update.
- `models.go` owns the normalized `PRStatus` and persisted `TaskPR` fields.
- `store.go` owns the `github_task_prs` schema and all queue-field write paths.
- The CI automation store owns a durable per-pull-request merge-attempt journal.
- The automation service exposes an explicit retry command for one linked pull
request. The controller does not call the merge provider directly.
### Task projection
- `apps/backend/internal/task/statussummary` reduces full pull-request state to
a bounded task status.
a bounded task status, including aggregate active auto-fix and auto-merge
flags.
- `apps/backend/internal/backendapp/status_summary_adapter.go` supplies the
stored queue state during live updates and restart hydration.
stored queue and per-pull-request automation state during live updates and
restart hydration.
### Web application
@@ -58,8 +67,13 @@ desktop and mobile behavior.
- `apps/web/lib/types/github.ts` defines the queue-state and `TaskPR` fields.
- `pr-merge-button.tsx` controls eligibility, submission, feedback, and refresh.
- `pr-merge-queue-status.tsx` normalizes queue presentation and duration copy.
- The task icon, status chip, summary, and detail components reuse that
presentation model.
- `pr-ci-automation-controls.tsx` maps a typed automatic-merge error to the
explicit retry command. Loading errors keep their separate refresh action.
- `pr-task-icon.tsx` overlays bounded automation indicators on the task-row
pull-request icon and lazily hydrates per-pull-request details for its
pointer, keyboard, or touch disclosure.
- The task icon, status chip, summary, and detail components reuse the same
automation labels and per-pull-request option matching.
## Data and contracts
@@ -76,6 +90,16 @@ An empty state with null metadata means that no active queue entry is stored.
The same three fields appear in the `TaskPR` HTTP, boot, and WebSocket payloads.
The bounded task projection reduces active membership to `queued`.
`TaskStatusSummary.pull_request` also carries two optional aggregate booleans:
- `auto_fix_enabled` is true when at least one active linked pull request has
auto-fix enabled.
- `auto_merge_enabled` is true when at least one active linked pull request has
auto-merge enabled.
These fields are task-row decorations. They do not replace the per-pull-request
automation options, authorize automation, or carry an unbounded option list.
The existing merge endpoint remains:
```http
@@ -96,6 +120,49 @@ successful response is one of these objects:
The provider request uses `merge_action=default`. GitHub therefore selects the
allowed direct or queued path.
`Client.MergePR` accepts a request value with the merge method and an optional
expected head SHA. Automatic merge requests require a non-empty expected head.
The clients send it as GitHub's `sha` field. A different provider head fails the
request instead of merging a pull-request revision that Kandev did not review.
The manual merge action keeps its existing behavior until its separate contract
requires head binding.
GitHub returns the merge status at the response root. It returns the polling
UUID and failure message inside `details`. The provider clients use
`details.uuid` to poll a pending request and `details.message` to report a
failed request. A pending response without `details.uuid` is invalid.
The clients also decode `details.expected_head_sha` for error diagnostics.
`github_task_ci_pr_state` keeps the automatic attempt journal for each linked
pull request:
- `last_merge_signature` stores the readiness state that authorized an attempt.
- `last_merge_attempt_at` stores when Kandev reserved the attempt.
- `last_queue_attempt_head_sha` stores the head accepted by GitHub or observed
in the active queue.
- `last_merge_result` stores `in_flight`, `failed`, or `accepted`.
- `last_error_kind` identifies `auto_merge` errors separately from loading,
auto-fix, and other automation errors.
The readiness signature includes the task, repository, pull request, pull-request
lifecycle state, head SHA, check conclusion, mergeability, review decision,
review count, required-review presence and value, pending-check count, and
unresolved-thread count. Including lifecycle state prevents a closed pull
request from reusing an attempt reserved while it was open, including after a
later reopen.
The explicit retry endpoint is:
```http
POST /api/v1/github/tasks/:taskId/ci-automation/retry-merge
Content-Type: application/json
{"repository_id":"repo-id","pr_number":3117}
```
The endpoint returns `202 Accepted` after it durably authorizes a new evaluation.
This response does not claim that GitHub accepted or completed the merge.
## Control flow
### Merge request
@@ -111,6 +178,66 @@ allowed direct or queued path.
Only GitHub's `enqueued` result maps to `queued`. An already merged pull request
maps to `merged`. A provider failure remains retryable.
### Automatic merge
1. The evaluator refreshes the exact linked pull request.
2. It requires fresh state, a non-empty head SHA, and all readiness gates.
3. It computes the complete readiness signature.
4. Before the unchanged-signature guard, it consumes a pending one-shot retry
authorization for this exact repository and pull request, if one exists.
That authorization bypasses only the unchanged-signature guard. The
evaluator still requires fresh state, the current head, and every readiness
gate. Without an authorization, an unchanged `in_flight`, `failed`, or
`accepted` signature stops the automatic path.
5. It reserves an `in_flight` attempt in storage before any provider side
effect.
6. It calls the provider with the exact observed head SHA.
7. It records `failed` or `accepted` from the provider result. An accepted
result clears a prior `auto_merge` error for that pull request.
If the reservation cannot be stored, the evaluator does not call GitHub. A
changed readiness signature can authorize one later automatic attempt after all
gates pass.
### Pending polling
The provider waits at least one second between pending-status reads. The wait
observes cancellation and the existing two-minute request budget. A conflict
response resumes the request with its returned UUID. A missing, expired, or
unknown request fails with a diagnostic error.
### Explicit retry
The retry command authorizes one new evaluation for the exact repository and
pull-request number. It applies only to a failed attempt or to an expired
`in_flight` attempt. Expiration is an explicit transition:
`expired in_flight -> failed -> authorized retry`. A retry cannot be authorized
while the original attempt is still `in_flight`, and it does not bypass checks,
reviews, mergeability, thread, or head requirements.
The service persists the retry authorization and publishes the normal
automation evaluation event. The evaluator then refreshes the pull request and
runs the full gate sequence. The HTTP handler never calls GitHub directly.
### Task-row automation projection
The authoritative pull-request loader reads linked pull requests and their
per-pull-request automation options in bounded batches. It supplies the two
switches with each internal pull-request observation. The summary derives each
aggregate flag from open pull requests only.
The status-summary projector subscribes to `github.task_ci_options.updated`.
It refreshes the task's authoritative pull-request observations before it
publishes a complete replacement summary. Existing pull-request update events
use the same observations, so a merge, close, unlink, or option change removes
obsolete indicators without browser-side polling.
The task row reads only `status_summary`. It does not mount
`useTaskCIAutomationOptions` for every visible task and does not issue an HTTP
request per row. When the user opens the icon disclosure, one deduplicated lazy
request hydrates the full pull-request records and per-pull-request automation
options needed for detailed text.
### Queue observation
The batched GraphQL selection reads this field:
@@ -128,12 +255,17 @@ an authoritative GraphQL observation. It preserves all three fields after a
queue-unaware read. It clears them after an authoritative null, merge, or close.
The update then publishes `github.task_pr.updated` through the existing path.
An active queue entry reconciles the attempt journal to `accepted`. A merged
state does the same. Either observation clears only an error whose kind is
`auto_merge`. It preserves unrelated automation errors.
## State transitions
- An open pull request with no observed queue entry is not queued.
- A non-null authoritative entry creates or updates active queue membership.
- A later authoritative null removes active queue membership.
- A merged or closed state clears queue metadata and wins presentation priority.
- An active queue or merged observation marks the matching attempt accepted.
- A queue-unaware or failed read preserves the last complete observation.
- An unknown future non-empty state remains active and uses generic UI copy.
@@ -150,6 +282,15 @@ A failed GraphQL queue read preserves the last complete observation. The next
successful authoritative sync updates or clears it. This behavior also protects
queue state during restart recovery and mixed GraphQL, REST, and CLI refreshes.
An automatic provider failure records `failed`, stores an `auto_merge` error,
and blocks automatic repetition for the unchanged readiness signature. A changed
signature or an explicit retry can rearm the attempt.
After a process interruption, Kandev first reconciles a stored `in_flight`
attempt with authoritative queue and merged state. If neither state appears
before the attempt deadline, Kandev marks the attempt failed and exposes the
explicit retry. It does not resubmit the unchanged attempt automatically.
## Persistence
The queue fields use additive SQLite columns in `github_task_prs`. Fresh schema,
@@ -157,6 +298,15 @@ migration, create, replace, restore, and update paths round-trip the complete
entry. Existing rows start with no queue entry and converge after a successful
GraphQL status sync.
The attempt journal uses additive columns in `github_task_ci_pr_state`. A
startup migration classifies only recognized stable legacy merge-error prefixes
as `auto_merge`. An unknown or empty error kind is never cleared as an automatic
merge error.
Reservation, result, error-kind, and retry-authorization changes use storage
transactions. The existing per-PR singleflight remains an optimization. Durable
reservation is the correctness boundary across concurrent events and restarts.
The estimate remains a duration. Kandev does not convert it to a durable target
timestamp because GitHub can change the estimate on each observation.
@@ -166,6 +316,9 @@ The merge action uses the active workspace's personal-write GitHub route. It
requires the same pull-request permissions as GitHub's merge API. Kandev does
not bypass repository rules or elevate the user.
The retry endpoint uses the same task and workspace authorization. It accepts
only the exact pull request that is linked to the task.
## Presentation and responsive behavior
An active queue entry uses `#966600`. Terminal states take precedence. Queue
@@ -181,6 +334,29 @@ Desktop and mobile share state derivation and actions. Mobile uses the existing
Review surface and status drawer. The action has a touch-sized target, does not
depend on hover, and does not create document-level horizontal overflow.
The task-row pull-request icon is the nearest shipped status-summary exemplar.
It overlays a small yellow dot at the top-left for active auto-fix and a small
purple dot at the top-right for active auto-merge. A contrasting surface ring
keeps both dots distinct from every pull-request status color. The dots are
supplementary; accessible text names each enabled setting.
Fine-pointer hover and keyboard focus extend the existing pull-request tooltip
with an Automation section. The section identifies enabled settings by active
pull request when per-pull-request options differ. A coarse-pointer activation
uses the existing compact task status drawer pattern and a touch-sized icon
target. Both presentations reuse the same lazy data and view model. The task
row remains the primary navigation target, and the automation disclosure does
not change settings.
An `auto_merge` error shows Retry on desktop and mobile for the selected pull
request. Other stored automation errors show Refresh because repeating a merge
would not address them. Loading errors keep their existing retry of the state
request.
Mobile keeps the existing inset status drawer and its single scroll owner. The
shared error row has a target of at least 44 by 44 CSS pixels. This change does
not add a drawer, dialog, or navigation surface.
## Verification evidence
Focused backend coverage exists in the GitHub client, GraphQL conversion,
@@ -190,8 +366,14 @@ priority. Playwright coverage exists in:
- `apps/web/e2e/tests/pr/pr-merge-queue.spec.ts`
- `apps/web/e2e/tests/pr/mobile-pr-merge-queue.spec.ts`
- `apps/web/e2e/tests/pr/pr-status-badge.spec.ts`
- `apps/web/e2e/tests/pr/mobile-pr-sidebar-automation-indicators.spec.ts`
## Related delivery records
- [Bind automatic merge attempts to the reviewed head](../../../decisions/2026-08-28-bind-github-auto-merge-attempts-to-reviewed-head.md)
- [Separate task summary and session stream traffic](../../../decisions/2026-08-01-separate-task-summary-session-stream-traffic.md)
- [Automatic merge reliability plan](../../../plans/github-auto-merge-reliability/plan.md)
- [Sidebar automation indicators plan](../../../plans/github-sidebar-automation-indicators/plan.md)
- [Queue-status visibility plan](../../../plans/github-pr-merge-queue-status/plan.md)
- [Original queue-aware merge action plan](../../../plans/github-pr-merge-queue/plan.md)
@@ -4,7 +4,7 @@ system: platform
requirements:
- REQ-PLATFORM-BOUNDED-TASK-STATUS-DELIVERY-001
created: 2026-08-01
updated: 2026-08-27
updated: 2026-08-28
owners:
- kandev
---
@@ -74,7 +74,7 @@ The initial contract is:
| `pending_action` | `permission`, `clarification`, or absent | Constant |
| `active_error` | Optional session and task-repository IDs, stamp, time, preview, category, and actions | One preview and at most three known actions |
| `git` | Aggregate additions, deletions, changed files, ahead, and behind | Numeric totals only |
| `pull_request` | Count, bounded representative identity, and aggregate display state | Constant regardless of PR count |
| `pull_request` | Count, bounded representative identity, aggregate display state, and active GitHub automation flags | Constant regardless of PR count |
`pull_request.aggregate_state` is one of `failure`, `blocked`, `pending`,
`awaiting_review`, `ready`, `passing`, `draft`, `merged`, `closed`, or
@@ -136,6 +136,11 @@ remain during migration, but switchers use the summary when present.
GitHub domain and are loaded only by surfaces that need them. On projector
restart or compare-and-set rebase, configured keyed pull-request observations
are rehydrated even when the persisted aggregate is absent.
- Pull-request automation flags aggregate only active linked pull requests.
The summary can state whether any active pull request has auto-fix or
auto-merge enabled, but it never carries the per-pull-request option list.
Integration option updates refresh the authoritative keyed pull-request
observations through the existing task-summary projector.
- A semantic no-op does not increment `revision` or emit an update.
- Clients ignore a summary delta whose revision is not newer than the stored
revision.
@@ -294,6 +299,10 @@ intermediate replacement.
changes its Git tree, or receives a PR update, **WHEN** its summary revision
arrives, **THEN** desktop and mobile rows update without a session
subscription.
- **GIVEN** an active linked pull request changes its auto-fix or auto-merge
setting, **WHEN** its summary revision arrives, **THEN** desktop and mobile
task rows update their bounded automation indicators without a per-row
automation request.
- **GIVEN** an idle task receives Git or pull-request summary changes, **WHEN**
its replacement summary arrives, **THEN** `updated_at` can advance while
`last_activity_at` remains unchanged.