summaryrefslogtreecommitdiff
path: root/internal/api/stories.go
blob: 3d9d25a59163ebd003f64ff421f2997317838bc1 (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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package api

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
	"os/exec"
	"strings"
	"time"

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

// createStoryBranch creates a new git branch in localPath from origin/main
// and pushes it to origin. Idempotent: treats "already exists" as success.
func createStoryBranch(localPath, branchName string) error {
	// Fetch latest from origin so origin/main is up to date.
	if out, err := exec.Command("git", "-C", localPath, "fetch", "origin").CombinedOutput(); err != nil {
		return fmt.Errorf("git fetch: %w (output: %s)", err, string(out))
	}
	base := "origin/main"
	out, err := exec.Command("git", "-C", localPath, "checkout", "-b", branchName, base).CombinedOutput()
	if err != nil {
		if !strings.Contains(string(out), "already exists") {
			return fmt.Errorf("git checkout -b: %w (output: %s)", err, string(out))
		}
		// Branch exists; switch to it — idempotent.
		if out2, err2 := exec.Command("git", "-C", localPath, "checkout", branchName).CombinedOutput(); err2 != nil {
			return fmt.Errorf("git checkout: %w (output: %s)", err2, string(out2))
		}
	}
	if out, err := exec.Command("git", "-C", localPath, "push", "origin", branchName).CombinedOutput(); err != nil {
		return fmt.Errorf("git push: %w (output: %s)", err, string(out))
	}
	return nil
}

func (s *Server) handleListStories(w http.ResponseWriter, r *http.Request) {
	stories, err := s.store.ListStories()
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	if stories == nil {
		stories = []*task.Story{}
	}
	writeJSON(w, http.StatusOK, stories)
}

func (s *Server) handleCreateStory(w http.ResponseWriter, r *http.Request) {
	var st task.Story
	if err := json.NewDecoder(r.Body).Decode(&st); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON: " + err.Error()})
		return
	}
	if st.Name == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "name is required"})
		return
	}
	if st.ID == "" {
		st.ID = uuid.New().String()
	}
	if st.Status == "" {
		st.Status = task.StoryPending
	}
	if err := s.store.CreateStory(&st); err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusCreated, st)
}

func (s *Server) handleGetStory(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	st, err := s.store.GetStory(id)
	if err != nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "story not found"})
		return
	}
	writeJSON(w, http.StatusOK, st)
}

func (s *Server) handleListStoryTasks(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	if _, err := s.store.GetStory(id); err != nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "story not found"})
		return
	}
	tasks, err := s.store.ListTasksByStory(id)
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	if tasks == nil {
		tasks = []*task.Task{}
	}
	writeJSON(w, http.StatusOK, tasks)
}

func (s *Server) handleAddTaskToStory(w http.ResponseWriter, r *http.Request) {
	storyID := r.PathValue("id")
	st, err := s.store.GetStory(storyID)
	if err != nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "story not found"})
		return
	}
	_ = st

	var input struct {
		Name          string           `json:"name"`
		Description   string           `json:"description"`
		Project       string           `json:"project"`
		RepositoryURL string           `json:"repository_url"`
		Agent         task.AgentConfig `json:"agent"`
		Claude        task.AgentConfig `json:"claude"`
		Timeout       string           `json:"timeout"`
		Priority      string           `json:"priority"`
		Tags          []string         `json:"tags"`
		ParentTaskID  string           `json:"parent_task_id"`
	}
	if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON: " + err.Error()})
		return
	}
	if input.Agent.Instructions == "" && input.Claude.Instructions != "" {
		input.Agent = input.Claude
	}

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

	now := time.Now().UTC()
	t := &task.Task{
		ID:            uuid.New().String(),
		Name:          input.Name,
		Description:   input.Description,
		Project:       input.Project,
		RepositoryURL: input.RepositoryURL,
		Agent:         input.Agent,
		Priority:      task.Priority(input.Priority),
		Tags:          input.Tags,
		DependsOn:     []string{},
		Retry:         task.RetryConfig{MaxAttempts: 1, Backoff: "exponential"},
		State:         task.StatePending,
		StoryID:       storyID,
		ParentTaskID:  input.ParentTaskID,
		CreatedAt:     now,
		UpdatedAt:     now,
	}

	if t.Agent.Type == "" {
		t.Agent.Type = "claude"
	}
	if t.Priority == "" {
		t.Priority = task.PriorityNormal
	}
	if t.Tags == nil {
		t.Tags = []string{}
	}
	if input.Timeout != "" {
		dur, err := time.ParseDuration(input.Timeout)
		if err != nil {
			writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid timeout: " + err.Error()})
			return
		}
		t.Timeout.Duration = dur
	}

	// Auto-wire depends_on: new task depends on the last existing task (sorted ASC by created_at).
	if len(existing) > 0 {
		lastTask := existing[len(existing)-1]
		t.DependsOn = []string{lastTask.ID}
	}

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

func (s *Server) handleUpdateStoryStatus(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	st, err := s.store.GetStory(id)
	if err != nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "story not found"})
		return
	}

	var input struct {
		Status task.StoryState `json:"status"`
	}
	if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON: " + err.Error()})
		return
	}
	if !task.ValidStoryTransition(st.Status, input.Status) {
		writeJSON(w, http.StatusConflict, map[string]string{
			"error": "invalid story status transition from " + string(st.Status) + " to " + string(input.Status),
		})
		return
	}
	if err := s.store.UpdateStoryStatus(id, input.Status); err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, map[string]string{"message": "story status updated", "story_id": id, "status": string(input.Status)})
}

func (s *Server) handleApproveStory(w http.ResponseWriter, r *http.Request) {
	var input struct {
		Name       string                    `json:"name"`
		BranchName string                    `json:"branch_name"`
		ProjectID  string                    `json:"project_id"`
		Tasks      []elaboratedStoryTask     `json:"tasks"`
		Validation elaboratedStoryValidation `json:"validation"`
	}
	if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON: " + err.Error()})
		return
	}
	if input.Name == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "name is required"})
		return
	}

	validationJSON, _ := json.Marshal(input.Validation)
	now := time.Now().UTC()
	story := &task.Story{
		ID:             uuid.New().String(),
		Name:           input.Name,
		ProjectID:      input.ProjectID,
		BranchName:     input.BranchName,
		ValidationJSON: string(validationJSON),
		Status:         task.StoryPending,
		CreatedAt:      now,
		UpdatedAt:      now,
	}
	if err := s.store.CreateStory(story); err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}

	var repoURL string
	if input.ProjectID != "" {
		if proj, err := s.store.GetProject(input.ProjectID); err == nil {
			repoURL = proj.RemoteURL
		}
	}

	taskIDs := make([]string, 0, len(input.Tasks))
	var prevTaskID string
	for _, tp := range input.Tasks {
		t := &task.Task{
			ID:            uuid.New().String(),
			Name:          tp.Name,
			Project:       input.ProjectID,
			RepositoryURL: repoURL,
			StoryID:       story.ID,
			Agent:         task.AgentConfig{Type: "claude", Instructions: tp.Instructions},
			Priority:      task.PriorityNormal,
			Tags:          []string{},
			DependsOn:     []string{},
			Retry:         task.RetryConfig{MaxAttempts: 1, Backoff: "exponential"},
			State:         task.StatePending,
			CreatedAt:     time.Now().UTC(),
			UpdatedAt:     time.Now().UTC(),
		}
		if prevTaskID != "" {
			t.DependsOn = []string{prevTaskID}
		}
		if err := s.store.CreateTask(t); err != nil {
			writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
			return
		}
		taskIDs = append(taskIDs, t.ID)

		var prevSubtaskID string
		for _, sub := range tp.Subtasks {
			st := &task.Task{
				ID:            uuid.New().String(),
				Name:          sub.Name,
				Project:       input.ProjectID,
				RepositoryURL: repoURL,
				StoryID:       story.ID,
				ParentTaskID:  t.ID,
				Agent:         task.AgentConfig{Type: "claude", Instructions: sub.Instructions},
				Priority:      task.PriorityNormal,
				Tags:          []string{},
				DependsOn:     []string{},
				Retry:         task.RetryConfig{MaxAttempts: 1, Backoff: "exponential"},
				State:         task.StatePending,
				CreatedAt:     time.Now().UTC(),
				UpdatedAt:     time.Now().UTC(),
			}
			if prevSubtaskID != "" {
				st.DependsOn = []string{prevSubtaskID}
			}
			if err := s.store.CreateTask(st); err != nil {
				writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
				return
			}
			prevSubtaskID = st.ID
		}
		prevTaskID = t.ID
	}

	// Create the story branch (non-fatal if it fails).
	if input.BranchName != "" && input.ProjectID != "" {
		if proj, err := s.store.GetProject(input.ProjectID); err == nil && proj.LocalPath != "" {
			if err := createStoryBranch(proj.LocalPath, input.BranchName); err != nil {
				s.logger.Warn("story approve: failed to create branch", "error", err, "branch", input.BranchName)
			}
		}
	}

	writeJSON(w, http.StatusCreated, map[string]interface{}{
		"story":    story,
		"task_ids": taskIDs,
	})
}

// handleStoryDeploymentStatus aggregates the deployment status across all tasks in a story.
// GET /api/stories/{id}/deployment-status
func (s *Server) handleStoryDeploymentStatus(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")

	story, err := s.store.GetStory(id)
	if err != nil {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "story not found"})
		return
	}

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

	// Collect all commits from the latest execution of each task.
	var allCommits []task.GitCommit
	for _, t := range tasks {
		exec, err := s.store.GetLatestExecution(t.ID)
		if err != nil {
			if err == sql.ErrNoRows {
				continue
			}
			writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
			return
		}
		allCommits = append(allCommits, exec.Commits...)
	}

	// Determine project remote URL for the deployment check.
	projectRemoteURL := ""
	if story.ProjectID != "" {
		if proj, err := s.store.GetProject(story.ProjectID); err == nil {
			projectRemoteURL = proj.RemoteURL
		}
	}

	status := deployment.Check(allCommits, projectRemoteURL)
	writeJSON(w, http.StatusOK, status)
}