summaryrefslogtreecommitdiff
path: root/internal/api/webhook.go
blob: 8bf167651611bb8213cb67e3c21e50f08c7784df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package api

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"path/filepath"
	"strings"
	"time"

	"github.com/google/uuid"
	"github.com/thepeterstone/claudomator/internal/config"
	"github.com/thepeterstone/claudomator/internal/task"
)

// checkRunPayload is the GitHub check_run webhook payload.
type checkRunPayload struct {
	Action   string `json:"action"`
	CheckRun struct {
		Name       string `json:"name"`
		Conclusion string `json:"conclusion"`
		HTMLURL    string `json:"html_url"`
		HeadSHA    string `json:"head_sha"`
		CheckSuite struct {
			HeadBranch string `json:"head_branch"`
		} `json:"check_suite"`
	} `json:"check_run"`
	Repository struct {
		Name     string `json:"name"`
		FullName string `json:"full_name"`
	} `json:"repository"`
}

// workflowRunPayload is the GitHub workflow_run webhook payload.
type workflowRunPayload struct {
	Action      string `json:"action"`
	WorkflowRun struct {
		Name       string `json:"name"`
		Conclusion string `json:"conclusion"`
		HTMLURL    string `json:"html_url"`
		HeadSHA    string `json:"head_sha"`
		HeadBranch string `json:"head_branch"`
	} `json:"workflow_run"`
	Repository struct {
		Name     string `json:"name"`
		FullName string `json:"full_name"`
	} `json:"repository"`
}

// validateGitHubSignature checks the HMAC-SHA256 signature from GitHub.
func validateGitHubSignature(sig string, body []byte, secret string) bool {
	if !strings.HasPrefix(sig, "sha256=") {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write(body)
	expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(sig), []byte(expected))
}

// matchProject finds the best matching project for a repository name.
// Returns the single configured project as a fallback if there's only one.
func matchProject(projects []config.Project, repoName string) *config.Project {
	repoLower := strings.ToLower(repoName)
	for i := range projects {
		p := &projects[i]
		nameLower := strings.ToLower(p.Name)
		dirBase := strings.ToLower(filepath.Base(p.Dir))
		if strings.Contains(nameLower, repoLower) || strings.Contains(dirBase, repoLower) {
			return p
		}
	}
	if len(projects) == 1 {
		return &projects[0]
	}
	return nil
}

func (s *Server) handleGitHubWebhook(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "failed to read body", http.StatusBadRequest)
		return
	}

	// Validate HMAC signature if a secret is configured.
	if s.webhookSecret != "" {
		sig := r.Header.Get("X-Hub-Signature-256")
		if !validateGitHubSignature(sig, body, s.webhookSecret) {
			http.Error(w, "invalid signature", http.StatusUnauthorized)
			return
		}
	}

	eventType := r.Header.Get("X-GitHub-Event")
	switch eventType {
	case "check_run":
		s.handleCheckRunEvent(w, body)
	case "workflow_run":
		s.handleWorkflowRunEvent(w, body)
	default:
		w.WriteHeader(http.StatusNoContent)
	}
}

func (s *Server) handleCheckRunEvent(w http.ResponseWriter, body []byte) {
	var p checkRunPayload
	if err := json.Unmarshal(body, &p); err != nil {
		http.Error(w, "invalid JSON", http.StatusBadRequest)
		return
	}
	if p.Action != "completed" || p.CheckRun.Conclusion != "failure" {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	s.createCIFailureTask(w,
		p.Repository.Name,
		p.Repository.FullName,
		p.CheckRun.CheckSuite.HeadBranch,
		p.CheckRun.HeadSHA,
		p.CheckRun.Name,
		p.CheckRun.HTMLURL,
	)
}

func (s *Server) handleWorkflowRunEvent(w http.ResponseWriter, body []byte) {
	var p workflowRunPayload
	if err := json.Unmarshal(body, &p); err != nil {
		http.Error(w, "invalid JSON", http.StatusBadRequest)
		return
	}
	if p.Action != "completed" {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	if p.WorkflowRun.Conclusion != "failure" && p.WorkflowRun.Conclusion != "timed_out" {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	s.createCIFailureTask(w,
		p.Repository.Name,
		p.Repository.FullName,
		p.WorkflowRun.HeadBranch,
		p.WorkflowRun.HeadSHA,
		p.WorkflowRun.Name,
		p.WorkflowRun.HTMLURL,
	)
}

func (s *Server) createCIFailureTask(w http.ResponseWriter, repoName, fullName, branch, sha, checkName, htmlURL string) {
	project := matchProject(s.projects, repoName)

	instructions := fmt.Sprintf(
		"A CI failure has been detected and requires investigation.\n\n"+
			"Repository: %s\n"+
			"Branch: %s\n"+
			"Commit SHA: %s\n"+
			"Check/Workflow: %s\n"+
			"Run URL: %s\n\n"+
			"Please investigate the failure by:\n"+
			"1. Reviewing recent commits on the branch\n"+
			"2. Checking the CI logs at the URL above\n"+
			"3. Identifying the root cause of the failure\n"+
			"4. Fixing the root cause and ensuring the build passes",
		fullName, branch, sha, checkName, htmlURL,
	)

	now := time.Now().UTC()
	t := &task.Task{
		ID:   uuid.New().String(),
		Name: fmt.Sprintf("Fix CI failure: %s on %s", checkName, branch),
		Agent: task.AgentConfig{
			Type:         "claude",
			Instructions: instructions,
			MaxBudgetUSD: 3.0,
			AllowedTools: []string{"Read", "Edit", "Bash", "Glob", "Grep"},
		},
		Priority:  task.PriorityNormal,
		Tags:      []string{"ci", "auto"},
		DependsOn: []string{},
		Retry:     task.RetryConfig{MaxAttempts: 1, Backoff: "exponential"},
		State:     task.StatePending,
		CreatedAt: now,
		UpdatedAt: now,
	}
	if project != nil {
		t.Agent.ProjectDir = project.Dir
	}

	if err := s.store.CreateTask(t); err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}

	writeJSON(w, http.StatusOK, map[string]string{"task_id": t.ID})
}