summaryrefslogtreecommitdiff
path: root/docs/superpowers/plans/2026-04-03-task-project-fk.md
blob: 36e6a1805316c9872a8840e61355bffcf7053417 (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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
# Task → Project FK Migration Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Replace the loose `project TEXT` and `repository_url TEXT` fields on Task with a proper `project_id TEXT` FK to the projects table, and remove the runtime-populated `BranchName` field (it belongs on Story).

**Architecture:** Add `project_id` column to tasks table via additive migration; backfill from project name lookup via SQL; update `scanTask` to LEFT JOIN projects and resolve `repository_url` as `COALESCE(p.remote_url, t.repository_url)` so orphan (webhook) tasks still work; strip `Project`, `BranchName` from the Task struct and the three ADR-007 runtime patches that compensated for the old design.

**Tech Stack:** Go, SQLite (database/sql + mattn/go-sqlite3), standard library only.

---

## File Map

| File | Change |
|------|--------|
| `internal/task/task.go` | Remove `Project`, `RepositoryURL`, `BranchName` fields; add `ProjectID` |
| `internal/task/validator.go` | Drop `repository_url` required; require at least one of `project_id` / `repository_url` |
| `internal/task/validator_test.go` | Update `validTask()` helper |
| `internal/task/task_test.go` | `Project` → `ProjectID` references |
| `internal/storage/db.go` | Add migration + backfill; define `taskSelectSQL` helper with LEFT JOIN; update `scanTask`, `CreateTask`, `UpdateTask`; add `GetProjectByName` |
| `internal/storage/db_test.go` | Update project field references in task tests |
| `internal/executor/executor.go` | Remove four ADR-007 patches (RepositoryURL ×2, BranchName ×2) |
| `internal/executor/container.go` | Remove `t.BranchName` fallback; always resolve from story |
| `internal/executor/container_test.go` | Remove `BranchName` from direct task construction; test via story instead |
| `internal/executor/executor_test.go` | Minor: `Project` → `ProjectID` in any task literals |
| `internal/api/server.go` | `handleCreateTask`: accept `project_id`; drop `project`/`repository_url` input fields |
| `internal/api/webhook.go` | `createCIFailureTask`: use `GetProjectByName` to set `project_id`; keep `repository_url` fallback when no DB project matches |
| `internal/api/task_view.go` | No change — `RepositoryURL` still populated by JOIN |
| `internal/api/server_test.go` | Replace `repository_url`/`project` in JSON payloads with `project_id` |
| `internal/api/webhook_test.go` | Seed DB project before assertions; check `ProjectID` not `RepositoryURL` directly |
| `internal/cli/list.go` | `t.Project` → `t.ProjectID` |
| `internal/cli/status.go` | `t.Project` → `t.ProjectID` |

---

## Task 1: Update Task struct and validator

**Files:**
- Modify: `internal/task/task.go`
- Modify: `internal/task/validator.go`

- [ ] **Step 1: Write failing validator tests**

In `internal/task/validator_test.go`, replace the existing `validTask()` helper and add a new failing test:

```go
func validTask() *Task {
	return &Task{
		ID:        "test-id",
		Name:      "Valid Task",
		ProjectID: "proj-1",
		Agent: AgentConfig{
			Type:         "claude",
			Instructions: "do something",
		},
		Retry:    RetryConfig{MaxAttempts: 1, Backoff: "linear"},
		Priority: PriorityNormal,
	}
}

func TestValidate_MissingProjectIDAndRepositoryURL(t *testing.T) {
	tk := validTask()
	tk.ProjectID = ""
	if err := Validate(tk); err == nil {
		t.Error("expected error for missing project_id and repository_url")
	}
}

func TestValidate_RepositoryURLAloneIsValid(t *testing.T) {
	tk := validTask()
	tk.ProjectID = ""
	tk.RepositoryURL = "https://github.com/owner/repo.git"
	if err := Validate(tk); err != nil {
		t.Errorf("expected no error with repository_url set, got: %v", err)
	}
}
```

- [ ] **Step 2: Run to confirm failure**

```
go test ./internal/task/... 2>&1 | grep -E "FAIL|PASS|error"
```
Expected: compile error — `ProjectID` undefined on Task.

- [ ] **Step 3: Update `internal/task/task.go`**

Replace lines 76-85:
```go
// Before:
Project      string       `yaml:"project"        json:"project"`
RepositoryURL string      `yaml:"repository_url" json:"repository_url"`
// ...
BranchName        string        `yaml:"-"          json:"branch_name,omitempty"`

// After:
ProjectID    string       `yaml:"project_id"     json:"project_id"`
RepositoryURL string      `yaml:"-"              json:"repository_url,omitempty"` // derived at load time; not stored
```

Full replacement for lines 71-94:
```go
type Task struct {
	ID           string       `yaml:"id"             json:"id"`
	ParentTaskID string       `yaml:"parent_task_id" json:"parent_task_id"`
	Name         string       `yaml:"name"           json:"name"`
	Description  string       `yaml:"description"    json:"description"`
	ProjectID    string       `yaml:"project_id"     json:"project_id"`
	RepositoryURL string      `yaml:"-"              json:"repository_url,omitempty"`
	Agent        AgentConfig  `yaml:"agent"          json:"agent"`
	Timeout      Duration     `yaml:"timeout"        json:"timeout"`
	Retry        RetryConfig  `yaml:"retry"          json:"retry"`
	Priority     Priority     `yaml:"priority"       json:"priority"`
	Tags         []string     `yaml:"tags"           json:"tags"`
	DependsOn    []string     `yaml:"depends_on"     json:"depends_on"`
	StoryID          string        `yaml:"-" json:"story_id,omitempty"`
	State            State         `yaml:"-" json:"state"`
	RejectionComment string        `yaml:"-" json:"rejection_comment,omitempty"`
	QuestionJSON     string        `yaml:"-" json:"question,omitempty"`
	ElaborationInput string        `yaml:"-" json:"elaboration_input,omitempty"`
	Summary          string        `yaml:"-" json:"summary,omitempty"`
	Interactions     []Interaction `yaml:"-" json:"interactions,omitempty"`
	CreatedAt        time.Time     `yaml:"-" json:"created_at"`
	UpdatedAt        time.Time     `yaml:"-" json:"updated_at"`
}
```

- [ ] **Step 4: Update `internal/task/validator.go`**

Replace the `repository_url` check (lines 32-34) with:
```go
if t.ProjectID == "" && t.RepositoryURL == "" {
	ve.Add("project_id or repository_url is required")
}
```

- [ ] **Step 5: Fix `internal/task/task_test.go`**

Find lines that reference `task.Project` and replace with `task.ProjectID`:
```go
// Line ~106:
task := Task{ProjectID: "my-project"}
if task.ProjectID != "my-project" {
    t.Errorf("expected ProjectID 'my-project', got %q", task.ProjectID)
}
// Line ~126:
if tasks[0].ProjectID != "my-project" {
    t.Errorf("expected ProjectID 'my-project', got %q", tasks[0].ProjectID)
}
```

- [ ] **Step 6: Run tests**

```
go test ./internal/task/... 2>&1
```
Expected: all pass.

- [ ] **Step 7: Commit**

```bash
git add internal/task/task.go internal/task/validator.go internal/task/validator_test.go internal/task/task_test.go
git commit -m "refactor: replace Task.Project+RepositoryURL+BranchName with ProjectID FK"
```

---

## Task 2: Storage — migration, LEFT JOIN queries, scanTask

**Files:**
- Modify: `internal/storage/db.go`

- [ ] **Step 1: Write failing storage test**

In `internal/storage/db_test.go`, find the test around line 1017 (`TestTask_ProjectRoundTrip` or similar) and update it to use `ProjectID`:

```go
func TestTask_ProjectIDRoundTrip(t *testing.T) {
	db := testDB(t)

	// Seed a project so the FK resolves.
	proj := &task.Project{
		ID: "proj-rt", Name: "roundtrip-proj",
		RemoteURL: "https://github.com/owner/rt.git",
		Type: "web",
	}
	if err := db.UpsertProject(proj); err != nil {
		t.Fatalf("UpsertProject: %v", err)
	}

	now := time.Now().UTC().Truncate(time.Second)
	tk := &task.Task{
		ID:        "proj-task-1",
		Name:      "Task with project",
		ProjectID: "proj-rt",
		Agent:     task.AgentConfig{Type: "claude", Instructions: "do x"},
		Priority:  task.PriorityNormal,
		Retry:     task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
		Tags:      []string{},
		DependsOn: []string{},
		State:     task.StatePending,
		CreatedAt: now,
		UpdatedAt: now,
	}
	if err := db.CreateTask(tk); err != nil {
		t.Fatalf("CreateTask: %v", err)
	}

	got, err := db.GetTask("proj-task-1")
	if err != nil {
		t.Fatalf("GetTask: %v", err)
	}
	if got.ProjectID != "proj-rt" {
		t.Errorf("ProjectID: want %q, got %q", "proj-rt", got.ProjectID)
	}
	// RepositoryURL should be derived from the project via JOIN.
	if got.RepositoryURL != "https://github.com/owner/rt.git" {
		t.Errorf("RepositoryURL: want derived from project, got %q", got.RepositoryURL)
	}
}
```

- [ ] **Step 2: Run to confirm failure**

```
go test ./internal/storage/... 2>&1 | grep -E "FAIL|error|undefined"
```
Expected: compile errors — `ProjectID` undefined on task struct (old DB code still references `Project`).

- [ ] **Step 3: Add `project_id` migration and backfill to `db.go`**

In `migrate()`, append to the `migrations` slice (after the existing `story_id` migration):
```go
`ALTER TABLE tasks ADD COLUMN project_id TEXT`,
// Backfill project_id from the project name stored in the legacy 'project' column.
`UPDATE tasks SET project_id = (SELECT id FROM projects WHERE name = tasks.project) WHERE project IS NOT NULL AND project != '' AND project_id IS NULL`,
```

- [ ] **Step 4: Add `taskSelectSQL` constant and update `scanTask`**

Add a package-level constant just before `scanTask`:
```go
// taskSelectSQL is the base SELECT for all task queries.
// It LEFT JOINs projects so that RepositoryURL is always resolved:
// project-linked tasks use p.remote_url; orphan tasks fall back to t.repository_url.
const taskSelectSQL = `
SELECT t.id, t.name, t.description, t.elaboration_input, t.project_id,
       COALESCE(p.remote_url, t.repository_url, '') AS resolved_url,
       t.config_json, t.priority, t.timeout_ns, t.retry_json, t.tags_json,
       t.depends_on_json, t.parent_task_id, t.state, t.created_at, t.updated_at,
       t.rejection_comment, t.question_json, t.summary, t.interactions_json, t.story_id
FROM tasks t
LEFT JOIN projects p ON p.id = t.project_id`
```

Update `scanTask` to match the new column order (21 columns):
```go
func scanTask(row scanner) (*task.Task, error) {
	var (
		t                task.Task
		configJSON       string
		retryJSON        string
		tagsJSON         string
		depsJSON         string
		state            string
		priority         string
		timeoutNS        int64
		projectID        sql.NullString
		resolvedURL      sql.NullString
		parentTaskID     sql.NullString
		elaborationInput sql.NullString
		rejectionComment sql.NullString
		questionJSON     sql.NullString
		summary          sql.NullString
		interactionsJSON sql.NullString
		storyID          sql.NullString
	)
	err := row.Scan(
		&t.ID, &t.Name, &t.Description, &elaborationInput, &projectID, &resolvedURL,
		&configJSON, &priority, &timeoutNS, &retryJSON, &tagsJSON, &depsJSON,
		&parentTaskID, &state, &t.CreatedAt, &t.UpdatedAt,
		&rejectionComment, &questionJSON, &summary, &interactionsJSON, &storyID,
	)
	t.ProjectID = projectID.String
	t.RepositoryURL = resolvedURL.String
	t.ElaborationInput = elaborationInput.String
	t.ParentTaskID = parentTaskID.String
	t.RejectionComment = rejectionComment.String
	t.QuestionJSON = questionJSON.String
	t.Summary = summary.String
	t.StoryID = storyID.String
	if err != nil {
		return nil, err
	}
	t.State = task.State(state)
	t.Priority = task.Priority(priority)
	t.Timeout.Duration = time.Duration(timeoutNS)
	if err := json.Unmarshal([]byte(configJSON), &t.Agent); err != nil {
		return nil, fmt.Errorf("unmarshaling agent config: %w", err)
	}
	if err := json.Unmarshal([]byte(retryJSON), &t.Retry); err != nil {
		return nil, fmt.Errorf("unmarshaling retry: %w", err)
	}
	if err := json.Unmarshal([]byte(tagsJSON), &t.Tags); err != nil {
		return nil, fmt.Errorf("unmarshaling tags: %w", err)
	}
	if err := json.Unmarshal([]byte(depsJSON), &t.DependsOn); err != nil {
		return nil, fmt.Errorf("unmarshaling depends_on: %w", err)
	}
	raw := interactionsJSON.String
	if raw == "" {
		raw = "[]"
	}
	if err := json.Unmarshal([]byte(raw), &t.Interactions); err != nil {
		return nil, fmt.Errorf("unmarshaling interactions: %w", err)
	}
	return &t, nil
}
```

- [ ] **Step 5: Update all SELECT call sites to use `taskSelectSQL`**

Replace every hard-coded SELECT string that queries tasks with `taskSelectSQL + " WHERE ..."`.

**`GetTask`:**
```go
func (s *DB) GetTask(id string) (*task.Task, error) {
	row := s.db.QueryRow(taskSelectSQL+` WHERE t.id = ?`, id)
	return scanTask(row)
}
```

**`ListTasks`:**
```go
func (s *DB) ListTasks(filter TaskFilter) ([]*task.Task, error) {
	query := taskSelectSQL + ` WHERE 1=1`
	var args []interface{}
	if filter.State != "" {
		query += " AND t.state = ?"
		args = append(args, string(filter.State))
	}
	if !filter.Since.IsZero() {
		query += " AND t.updated_at > ?"
		args = append(args, filter.Since.UTC())
	}
	query += " ORDER BY t.created_at DESC"
	if filter.Limit > 0 {
		query += " LIMIT ?"
		args = append(args, filter.Limit)
	}
	rows, err := s.db.Query(query, args...)
	// ... rest unchanged
```

**`ListSubtasks`:**
```go
func (s *DB) ListSubtasks(parentID string) ([]*task.Task, error) {
	rows, err := s.db.Query(taskSelectSQL+` WHERE t.parent_task_id = ? ORDER BY t.created_at ASC`, parentID)
	// ... rest unchanged
```

**`ResetTaskForRetry`** (inner SELECT):
```go
t, err := scanTask(tx.QueryRow(taskSelectSQL+` WHERE t.id = ?`, id))
```

**`ListTasksByStory`:**
```go
rows, err := s.db.Query(taskSelectSQL+` WHERE t.story_id = ? ORDER BY t.created_at ASC`, storyID)
```

- [ ] **Step 6: Update `CreateTask` to write `project_id` instead of `project`/`repository_url`**

Replace the INSERT:
```go
_, err = s.db.Exec(`
	INSERT INTO tasks (id, name, description, elaboration_input, project_id, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, story_id)
	VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
	t.ID, t.Name, t.Description, t.ElaborationInput, t.ProjectID, t.RepositoryURL, string(configJSON), string(t.Priority),
	t.Timeout.Duration.Nanoseconds(), string(retryJSON), string(tagsJSON), string(depsJSON),
	t.ParentTaskID, string(t.State), t.CreatedAt.UTC(), t.UpdatedAt.UTC(), t.StoryID,
)
```

Note: `repository_url` is kept as a fallback column for orphan (webhook) tasks with no project.

- [ ] **Step 7: Update `TaskUpdate` struct and `UpdateTask`**

Replace `RepositoryURL string` with `ProjectID string` in `TaskUpdate`:
```go
type TaskUpdate struct {
	Name        string
	Description string
	ProjectID   string
	Config      task.AgentConfig
	Priority    task.Priority
	TimeoutNS   int64
	Retry       task.RetryConfig
	Tags        []string
	DependsOn   []string
}
```

Update the UPDATE query in `UpdateTask`:
```go
result, err := s.db.Exec(`
	UPDATE tasks
	SET name = ?, description = ?, project_id = ?, config_json = ?, priority = ?, timeout_ns = ?,
	    retry_json = ?, tags_json = ?, depends_on_json = ?, state = ?, updated_at = ?
	WHERE id = ?`,
	u.Name, u.Description, u.ProjectID, configJSON, string(u.Priority), u.TimeoutNS,
	retryJSON, tagsJSON, depsJSON, string(task.StatePending), now, id)
```

- [ ] **Step 8: Add `GetProjectByName`**

```go
// GetProjectByName retrieves a project by its name field.
func (s *DB) GetProjectByName(name string) (*task.Project, error) {
	row := s.db.QueryRow(`SELECT id, name, remote_url, local_path, type, deploy_script FROM projects WHERE name = ?`, name)
	p := &task.Project{}
	if err := row.Scan(&p.ID, &p.Name, &p.RemoteURL, &p.LocalPath, &p.Type, &p.DeployScript); err != nil {
		return nil, err
	}
	return p, nil
}
```

- [ ] **Step 9: Fix the old `TestTask_ProjectRoundTrip` test in `db_test.go`**

Find and replace the test that asserts `got.Project != "my-project"` (around line 1017). Replace the entire test with the new `TestTask_ProjectIDRoundTrip` written in Step 1 above. Delete the old test.

Also find and replace the `TestUpdateTask` test's `RepositoryURL` field with `ProjectID`:
```go
// In the update test, change:
u := TaskUpdate{
    Name:      "Updated",
    ProjectID: "proj-upd",
    // ...
}
// And assert:
if got.ProjectID != "proj-upd" { ... }
```

- [ ] **Step 10: Run storage tests**

```
go test -count=1 ./internal/storage/... 2>&1
```
Expected: all pass.

- [ ] **Step 11: Commit**

```bash
git add internal/storage/db.go internal/storage/db_test.go
git commit -m "feat: add project_id FK to tasks; LEFT JOIN resolves repository_url at read time"
```

---

## Task 3: Remove ADR-007 patches from executor

**Files:**
- Modify: `internal/executor/executor.go`

- [ ] **Step 1: Remove RepositoryURL patches**

Delete these two blocks (they appear in both `execute` and `executeResume`):
```go
// DELETE this block (appears twice):
// Populate RepositoryURL from Project registry if missing (ADR-007).
if t.RepositoryURL == "" && t.Project != "" {
    if proj, err := p.store.GetProject(t.Project); err == nil && proj.RemoteURL != "" {
        t.RepositoryURL = proj.RemoteURL
    }
}
```

- [ ] **Step 2: Remove BranchName patches**

Delete these two blocks (also appear twice):
```go
// DELETE this block (appears twice):
// Populate BranchName from Story if missing (ADR-007).
if t.BranchName == "" && t.StoryID != "" {
    if story, err := p.store.GetStory(t.StoryID); err == nil && story.BranchName != "" {
        t.BranchName = story.BranchName
    }
}
```

- [ ] **Step 3: Build check**

```
go build ./internal/executor/... 2>&1
```
Expected: clean build.

- [ ] **Step 4: Run executor tests**

```
go test -count=1 ./internal/executor/... 2>&1 | tail -5
```
Expected: all pass.

- [ ] **Step 5: Commit**

```bash
git add internal/executor/executor.go
git commit -m "refactor: remove ADR-007 runtime patches for RepositoryURL and BranchName"
```

---

## Task 4: Clean up container runner

**Files:**
- Modify: `internal/executor/container.go`
- Modify: `internal/executor/container_test.go`

- [ ] **Step 1: Remove `t.BranchName` fallback in `container.go`**

Find lines 154-157:
```go
// Fall back to task-level BranchName (e.g. set explicitly by executor or tests).
if storyBranch == "" {
    storyBranch = t.BranchName
}
```
Delete these four lines. The container already resolves the branch from the story via the store lookup at lines 144-153; the fallback only existed for the (now-removed) `BranchName` field.

- [ ] **Step 2: Update container tests that set `BranchName` directly**

In `container_test.go`, find `TestContainerRunner_ClonesStoryBranch` (around line 544). It currently sets `BranchName: "story/my-feature"` directly on the task. Replace with a story + store setup:

```go
func TestContainerRunner_ClonesStoryBranch(t *testing.T) {
	// ... existing setup ...
	store := testContainerStore(t) // use the real test store
	story := &task.Story{
		ID:         "story-branch-1",
		Name:       "Branch Test",
		BranchName: "story/my-feature",
		ProjectID:  "",
		Status:     task.StoryInProgress,
	}
	if err := store.CreateStory(story); err != nil {
		t.Fatalf("CreateStory: %v", err)
	}

	tk := &task.Task{
		ID:            "story-branch-test",
		RepositoryURL: "https://example.com/repo.git",
		StoryID:       "story-branch-1",
		Agent:         task.AgentConfig{Type: "claude"},
	}
	// ... rest of assertions unchanged
```

Note: check whether `container_test.go` has a `testContainerStore` helper or uses a different pattern; adapt accordingly. The store reference in `ContainerRunner` is `r.Store` — ensure the runner is initialized with the test store.

- [ ] **Step 3: Run container tests**

```
go test -count=1 -run TestContainerRunner ./internal/executor/... 2>&1
```
Expected: all pass.

- [ ] **Step 4: Commit**

```bash
git add internal/executor/container.go internal/executor/container_test.go
git commit -m "refactor: remove Task.BranchName fallback in container runner; always resolve from story"
```

---

## Task 5: Update API handlers

**Files:**
- Modify: `internal/api/server.go`
- Modify: `internal/api/server_test.go`

- [ ] **Step 1: Update `handleCreateTask` in `server.go`**

Replace the input struct and task construction (lines ~447-488):

```go
func (s *Server) handleCreateTask(w http.ResponseWriter, r *http.Request) {
	var input struct {
		Name             string           `json:"name"`
		Description      string           `json:"description"`
		ElaborationInput string           `json:"elaboration_input"`
		ProjectID        string           `json:"project_id"`
		Agent            task.AgentConfig `json:"agent"`
		Claude           task.AgentConfig `json:"claude"` // legacy alias
		Timeout          string           `json:"timeout"`
		Priority         string           `json:"priority"`
		Tags             []string         `json:"tags"`
		ParentTaskID     string           `json:"parent_task_id"`
	}
	// ... decode unchanged ...

	t := &task.Task{
		ID:               uuid.New().String(),
		Name:             input.Name,
		Description:      input.Description,
		ElaborationInput: input.ElaborationInput,
		ProjectID:        input.ProjectID,
		Agent:            input.Agent,
		Priority:         task.Priority(input.Priority),
		Tags:             input.Tags,
		DependsOn:        []string{},
		Retry:            task.RetryConfig{MaxAttempts: 1, Backoff: "exponential"},
		State:            task.StatePending,
		CreatedAt:        now,
		UpdatedAt:        now,
		ParentTaskID:     input.ParentTaskID,
	}
	// ... rest unchanged
```

- [ ] **Step 2: Update `server_test.go` task payloads**

Replace every `"repository_url": "https://github.com/user/repo"` in JSON payloads with `"project_id": "test-proj"`.

First seed a project in `testServer` or `testServerWithRunner` so the FK is valid and `GetTask` returns `RepositoryURL` via JOIN. Add to `testServerWithRunner`:

```go
// Seed a default project for tests that don't need a specific one.
defaultProj := &task.Project{
	ID: "test-proj", Name: "test-project",
	RemoteURL: "https://github.com/user/repo",
	Type: "web",
}
if err := store.UpsertProject(defaultProj); err != nil {
	t.Fatalf("seed test project: %v", err)
}
```

Then in each test that previously sent `"repository_url": "..."`, use `"project_id": "test-proj"` instead.

Update assertions that checked `created.Project != "test-project"` to check `created.ProjectID != "test-proj"`.

- [ ] **Step 3: Run API tests**

```
go test -count=1 ./internal/api/... 2>&1 | grep -E "FAIL|ok"
```
Expected: all pass.

- [ ] **Step 4: Commit**

```bash
git add internal/api/server.go internal/api/server_test.go
git commit -m "feat: handleCreateTask accepts project_id; drop project/repository_url input fields"
```

---

## Task 6: Update webhook handler

**Files:**
- Modify: `internal/api/webhook.go`
- Modify: `internal/api/webhook_test.go`

- [ ] **Step 1: Add `GetProjectByName` to the `Store` interface in `server.go`**

Find the `store` interface (or wherever `GetProject` is declared in the api package). Add:
```go
GetProjectByName(name string) (*task.Project, error)
```

- [ ] **Step 2: Update `createCIFailureTask` in `webhook.go`**

Replace lines 203-224:
```go
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",
		Model:        "sonnet",
		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,
}

// Resolve project_id from DB using the config project name.
// If no DB project matches, fall back to storing the repo URL directly.
if project != nil {
	if dbProj, err := s.store.GetProjectByName(project.Name); err == nil {
		t.ProjectID = dbProj.ID
	} else {
		// No DB project yet — store URL directly so the executor can clone.
		t.RepositoryURL = fmt.Sprintf("https://github.com/%s.git", fullName)
	}
} else {
	t.RepositoryURL = fmt.Sprintf("https://github.com/%s.git", fullName)
}
```

- [ ] **Step 3: Update webhook tests**

In `webhook_test.go`, seed a DB project before the assertions that check `tk.RepositoryURL`. After the migration, `RepositoryURL` is derived from the project, so seed the project:

```go
// In TestHandleCheckRun_CreatesTask (and similar tests):
store.UpsertProject(&task.Project{
	ID: "myrepo-proj", Name: "myrepo",
	RemoteURL: "https://github.com/owner/myrepo.git",
	Type: "web",
})
// ...
// Check ProjectID instead of RepositoryURL directly:
if tk.ProjectID != "myrepo-proj" {
	t.Errorf("task project_id = %q, want myrepo-proj", tk.ProjectID)
}
// RepositoryURL is still populated via JOIN:
if tk.RepositoryURL != "https://github.com/owner/myrepo.git" {
	t.Errorf("task repository url = %q, want https://github.com/owner/myrepo.git", tk.RepositoryURL)
}
```

For tests where `matchProject` returns nil (no matching project), verify `t.RepositoryURL` is set directly (fallback path).

- [ ] **Step 4: Run webhook tests**

```
go test -count=1 -run TestHandle ./internal/api/... 2>&1
```
Expected: all pass.

- [ ] **Step 5: Commit**

```bash
git add internal/api/webhook.go internal/api/webhook_test.go internal/api/server.go
git commit -m "feat: webhook sets project_id via DB lookup; falls back to repository_url for unknown repos"
```

---

## Task 7: Update CLI

**Files:**
- Modify: `internal/cli/list.go`
- Modify: `internal/cli/status.go`

- [ ] **Step 1: Update `list.go`**

Find line ~55: `t.ID, t.Name, t.Project, ...`
Replace with: `t.ID, t.Name, t.ProjectID, ...`

- [ ] **Step 2: Update `status.go`**

Find lines ~42-44:
```go
if t.Project != "" {
    fmt.Printf("Project: %s\n", t.Project)
}
```
Replace with:
```go
if t.ProjectID != "" {
    fmt.Printf("Project: %s\n", t.ProjectID)
}
```

- [ ] **Step 3: Build check**

```
go build ./... 2>&1
```
Expected: clean.

- [ ] **Step 4: Commit**

```bash
git add internal/cli/list.go internal/cli/status.go
git commit -m "fix: CLI list/status use ProjectID"
```

---

## Task 8: Full test suite + production migration verification

- [ ] **Step 1: Run full test suite with race detector**

```
go test -race -count=1 ./... 2>&1 | grep -E "FAIL|ok|panic"
```
Expected: all packages pass.

- [ ] **Step 2: Verify production DB migration**

```bash
sqlite3 /site/doot.terst.org/data/claudomator.db "
SELECT t.id, t.name, t.project_id, COALESCE(p.remote_url, t.repository_url) as url
FROM tasks t LEFT JOIN projects p ON p.id = t.project_id
WHERE t.state NOT IN ('COMPLETED','CANCELLED')
ORDER BY t.created_at DESC LIMIT 10;"
```
Expected: `project_id` populated for tasks that had a `project` name; URL resolves correctly.

- [ ] **Step 3: Push and deploy**

```bash
git push local main
sudo ./scripts/deploy
```

---

## Self-Review

**Spec coverage check:**
- ✅ `Task.Project` removed → `ProjectID` added (Tasks 1, 2, 5, 6, 7)
- ✅ `Task.RepositoryURL` no longer stored directly; derived via LEFT JOIN (Task 2)
- ✅ `Task.BranchName` removed; container always resolves from story (Tasks 1, 4)
- ✅ ADR-007 patches removed (Task 3)
- ✅ `GetProjectByName` added to storage (Task 2 Step 8)
- ✅ Webhook falls back gracefully for unknown repos (Task 6)
- ✅ DB backfill migration in place (Task 2 Step 3)

**Placeholder scan:** No TBDs or incomplete steps found.

**Type consistency:** `ProjectID` used consistently throughout. `RepositoryURL` remains on Task struct (derived, not stored). `taskSelectSQL` constant referenced uniformly in all SELECT call sites.