feat(analyst): этапы задачи — аналитик раскладывает на steps с критериями готовности, dev идёт по ним
Some checks failed
CI / test (push) Failing after 1m52s
CI / build-and-package (amd64, linux) (push) Failing after 1m3s
CI / build-and-package (amd64, windows) (push) Successful in 30s

This commit is contained in:
ki.sagidullin
2026-08-24 18:05:06 +05:00
parent 6546f18348
commit 6c0b903794
10 changed files with 286 additions and 50 deletions

View File

@@ -57,6 +57,7 @@ type AnalystResponse struct {
Repos json.RawMessage `json:"repos"` // список репо (основной); устойчив к строке Repos json.RawMessage `json:"repos"` // список репо (основной); устойчив к строке
Why string `json:"why"` Why string `json:"why"`
AC string `json:"ac"` AC string `json:"ac"`
Steps []storage.Step `json:"steps"`
Questions []string `json:"questions"` Questions []string `json:"questions"`
ChatReply string `json:"chat_reply"` ChatReply string `json:"chat_reply"`
AbortReason string `json:"abort_reason"` AbortReason string `json:"abort_reason"`
@@ -86,6 +87,22 @@ func (r *AnalystResponse) reposList() []string {
return out return out
} }
// stepsList возвращает этапы: модель может вернуть массив объектов либо
// пустой/отсутствующий — тогда nil. Записи без title отбрасываются.
func (r *AnalystResponse) stepsList() []storage.Step {
if r.Steps == nil {
return nil
}
var out []storage.Step
for _, st := range r.Steps {
if st.Title == "" {
continue
}
out = append(out, st)
}
return out
}
// Decide реализует core.Decider через открытый код. // Decide реализует core.Decider через открытый код.
func (a *Analyst) Decide(ctx context.Context, history []core.Message, draft storage.Task, force bool) (core.Decision, error) { func (a *Analyst) Decide(ctx context.Context, history []core.Message, draft storage.Task, force bool) (core.Decision, error) {
agent := a.Agent agent := a.Agent
@@ -109,6 +126,7 @@ func (a *Analyst) Decide(ctx context.Context, history []core.Message, draft stor
Repos: draft.EffectiveRepos(), Repos: draft.EffectiveRepos(),
Why: draft.Why, Why: draft.Why,
AC: draft.AC, AC: draft.AC,
Steps: draft.Steps,
History: hist, History: hist,
Force: force, Force: force,
} }
@@ -176,6 +194,9 @@ func (a *Analyst) Decide(ctx context.Context, history []core.Message, draft stor
if ar.AC != "" { if ar.AC != "" {
dec.Draft.AC = ar.AC dec.Draft.AC = ar.AC
} }
if steps := ar.stepsList(); len(steps) > 0 {
dec.Draft.Steps = steps
}
return dec, nil return dec, nil
} }
@@ -204,7 +225,7 @@ func validateResponse(ar *AnalystResponse) error {
return fmt.Errorf("phase=ask, но нет ни chat_reply, ни questions") return fmt.Errorf("phase=ask, но нет ни chat_reply, ни questions")
} }
case "propose": case "propose":
if ar.Title == "" && ar.Goal == "" && len(ar.Repos) == 0 && ar.Why == "" && ar.AC == "" { if ar.Title == "" && ar.Goal == "" && len(ar.Repos) == 0 && ar.Why == "" && ar.AC == "" && len(ar.stepsList()) == 0 {
return fmt.Errorf("phase=propose, но нет ни одного изменённого поля") return fmt.Errorf("phase=propose, но нет ни одного изменённого поля")
} }
case "ready": case "ready":
@@ -257,6 +278,19 @@ func formatVerdict(ar *AnalystResponse) string {
b.WriteString(", ac=") b.WriteString(", ac=")
b.WriteString(ar.AC) b.WriteString(ar.AC)
} }
if steps := ar.stepsList(); len(steps) > 0 {
b.WriteString(", steps=[")
var parts []string
for _, st := range steps {
s := st.Title
if st.AC != "" {
s += " → " + st.AC
}
parts = append(parts, s)
}
b.WriteString(strings.Join(parts, " | "))
b.WriteString("]")
}
if ar.AbortReason != "" { if ar.AbortReason != "" {
b.WriteString(", abort_reason=") b.WriteString(", abort_reason=")
b.WriteString(ar.AbortReason) b.WriteString(ar.AbortReason)

View File

@@ -240,6 +240,52 @@ func TestDecideProposeStringRepos(t *testing.T) {
} }
} }
// TestDecideProposeSteps — аналитик разложил задачу на этапы с критериями.
func TestDecideProposeSteps(t *testing.T) {
a := &Analyst{Runner: &mockRunner{result: &opencode.Result{
RC: 0,
Stdout: `{"type":"text","part":{"text":"{\"phase\":\"propose\",\"title\":\"Калькулятор\",\"steps\":[{\"title\":\"Модель\",\"ac\":\"операции + - * /\"},{\"title\":\"UI\"}]}"}}`,
}}, Worktree: "/tmp"}
history := []core.Message{{Role: "user", Content: "Сделай калькулятор"}}
dec, err := a.Decide(context.Background(), history, storage.Task{}, false)
if err != nil {
t.Fatalf("Decide err: %v", err)
}
if dec.Phase != "propose" {
t.Errorf("Phase = %q, want propose", dec.Phase)
}
if len(dec.Draft.Steps) != 2 {
t.Fatalf("len(Steps) = %d, want 2", len(dec.Draft.Steps))
}
if dec.Draft.Steps[0].Title != "Модель" || dec.Draft.Steps[0].AC != "операции + - * /" {
t.Errorf("Steps[0] = %q/%q, want Модель/операции + - * /", dec.Draft.Steps[0].Title, dec.Draft.Steps[0].AC)
}
if dec.Draft.Steps[1].Title != "UI" || dec.Draft.Steps[1].AC != "" {
t.Errorf("Steps[1] = %q/%q, want UI/(пусто)", dec.Draft.Steps[1].Title, dec.Draft.Steps[1].AC)
}
}
// TestProposeOnlyStepsValid — propose меняет только steps → валидно.
func TestProposeOnlyStepsValid(t *testing.T) {
a := &Analyst{Runner: &mockRunner{result: &opencode.Result{
RC: 0,
Stdout: `{"type":"text","part":{"text":"{\"phase\":\"propose\",\"steps\":[{\"title\":\"Шаг 1\"}],\"chat_reply\":\"Разбил на этапы\"}"}}`,
}}, Worktree: "/tmp"}
history := []core.Message{{Role: "user", Content: "test"}}
dec, err := a.Decide(context.Background(), history, storage.Task{}, false)
if err != nil {
t.Fatalf("Decide err: %v", err)
}
if dec.Phase != "propose" {
t.Errorf("Phase = %q, want propose", dec.Phase)
}
if len(dec.Draft.Steps) != 1 {
t.Fatalf("len(Steps) = %d, want 1", len(dec.Draft.Steps))
}
}
// TestFormatVerdict — человекочитаемое описание вердикта аналитика. // TestFormatVerdict — человекочитаемое описание вердикта аналитика.
func TestFormatVerdict(t *testing.T) { func TestFormatVerdict(t *testing.T) {
tests := []struct { tests := []struct {

View File

@@ -3,6 +3,8 @@ package analyst
import ( import (
"strings" "strings"
"text/template" "text/template"
"github.com/kamelion/ratatoskr-go/internal/storage"
) )
// promptTemplate — шаблон промпта для аналитика (opencode analyst-agent). // promptTemplate — шаблон промпта для аналитика (opencode analyst-agent).
@@ -23,6 +25,7 @@ var promptTemplate = template.Must(template.New("analyst").Parse(`Ты — ан
| repos | список репозиториев (имена на git-хосте; для связанных — все сразу) | | repos | список репозиториев (имена на git-хосте; для связанных — все сразу) |
| why | зачем это нужно, контекст | | why | зачем это нужно, контекст |
| ac | acceptance criteria — конкретный результат, что считается готовым | | ac | acceptance criteria — конкретный результат, что считается готовым |
| steps | (опционально) разбиение задачи на этапы: список {title, ac} с критерием готовности каждого этапа |
Изменяй в JSON только те поля, которые надо поменять; что менять не надо — пустой строкой. Изменяй в JSON только те поля, которые надо поменять; что менять не надо — пустой строкой.
@@ -51,6 +54,12 @@ var promptTemplate = template.Must(template.New("analyst").Parse(`Ты — ан
{{- else}} repos: (не задано){{end}} {{- else}} repos: (не задано){{end}}
{{if .Why}} why: {{.Why}}{{else}} why: (не задано){{end}} {{if .Why}} why: {{.Why}}{{else}} why: (не задано){{end}}
{{if .AC}} ac: {{.AC}}{{else}} ac: (не задано){{end}} {{if .AC}} ac: {{.AC}}{{else}} ac: (не задано){{end}}
{{if .Steps}}
steps:
{{- range .Steps}}
- {{.Title}}{{if .AC}}{{.AC}}{{end}}
{{- end}}
{{- else}} steps: (не задано){{end}}
**Ответь строго JSON-объектом, без лишнего текста:** **Ответь строго JSON-объектом, без лишнего текста:**
{ {
@@ -60,6 +69,7 @@ var promptTemplate = template.Must(template.New("analyst").Parse(`Ты — ан
"repos": ["имя_репо_1", "имя_репо_2"], "repos": ["имя_репо_1", "имя_репо_2"],
"why": "зачем (только если меняешь)", "why": "зачем (только если меняешь)",
"ac": "критерии (только если меняешь)", "ac": "критерии (только если меняешь)",
"steps": [{"title": "этап 1", "ac": "критерий этапа 1"}],
"questions": ["вопрос 1", "вопрос 2"], "questions": ["вопрос 1", "вопрос 2"],
"chat_reply": "твой ответ пользователю (на русском, естественно)", "chat_reply": "твой ответ пользователю (на русском, естественно)",
"abort_reason": "если phase=abort — причина" "abort_reason": "если phase=abort — причина"
@@ -73,6 +83,7 @@ type TemplateData struct {
Repos []string Repos []string
Why string Why string
AC string AC string
Steps []storage.Step
History string // отформатированная переписка History string // отформатированная переписка
Force bool Force bool
} }

View File

@@ -40,6 +40,12 @@ func IsTerminal(s Status) bool {
return model.IsTerminal(s) return model.IsTerminal(s)
} }
// Step — этап задачи с собственным критерием готовности.
type Step struct {
Title string `json:"title"`
AC string `json:"ac"` // acceptance criterion этапа
}
// Task — запись задачи в БД. // Task — запись задачи в БД.
type Task struct { type Task struct {
ID int64 `json:"id"` ID int64 `json:"id"`
@@ -50,6 +56,7 @@ type Task struct {
Repos []string `json:"repos"` // список репозиториев (основной) Repos []string `json:"repos"` // список репозиториев (основной)
Why string `json:"why"` Why string `json:"why"`
AC string `json:"ac"` // acceptance criteria AC string `json:"ac"` // acceptance criteria
Steps []Step `json:"steps"` // этапы задачи (опционально)
TaskTag string `json:"task_tag"` // UUID, стабильный на всю жизнь TaskTag string `json:"task_tag"` // UUID, стабильный на всю жизнь
Status Status `json:"status"` Status Status `json:"status"`
CreatedAt SQLiteTime `json:"created_at"` CreatedAt SQLiteTime `json:"created_at"`
@@ -88,6 +95,25 @@ func (t *Task) SetReposFromDB(repos string) {
_ = json.Unmarshal([]byte(repos), &t.Repos) _ = json.Unmarshal([]byte(repos), &t.Repos)
} }
// StepsJoined возвращает steps как одну строку (JSON-массив) для хранения в БД.
// Пустой список → пустая строка.
func (t *Task) StepsJoined() string {
if len(t.Steps) == 0 {
return ""
}
b, _ := json.Marshal(t.Steps)
return string(b)
}
// SetStepsFromDB заполняет Steps из сохранённой строки (JSON).
func (t *Task) SetStepsFromDB(steps string) {
if steps == "" {
t.Steps = nil
return
}
_ = json.Unmarshal([]byte(steps), &t.Steps)
}
// TraceStatus — алиас доменного статуса трассировки. // TraceStatus — алиас доменного статуса трассировки.
type TraceStatus = model.TraceStatus type TraceStatus = model.TraceStatus

View File

@@ -173,6 +173,13 @@ func (s *Storage) migrate(ctx context.Context) error {
return fmt.Errorf("%w: migrate add repos: %w", ErrDB, err) return fmt.Errorf("%w: migrate add repos: %w", ErrDB, err)
} }
} }
// Доп. колонка steps (этапы задачи). Idempotent.
if _, err := s.db.ExecContext(ctx,
`ALTER TABLE tasks ADD COLUMN steps TEXT NOT NULL DEFAULT ''`); err != nil {
if !isDuplicateColumn(err) {
return fmt.Errorf("%w: migrate add steps: %w", ErrDB, err)
}
}
return nil return nil
} }

View File

@@ -150,6 +150,44 @@ func TestUpdateTaskNotFound(t *testing.T) {
} }
} }
func TestCreateAndGetTask_Steps(t *testing.T) {
s, ctx := setupTestDB(t)
task := &Task{
ChatID: "tg://steps",
Title: "Steps task",
TaskTag: "steps-1",
Steps: []Step{
{Title: "Реализовать модель", AC: "структура готова"},
{Title: "Добавить API", AC: "эндпоинт отвечает"},
},
}
id, err := s.CreateTask(ctx, task)
if err != nil {
t.Fatalf("CreateTask: %v", err)
}
got, err := s.GetTask(ctx, id)
if err != nil {
t.Fatalf("GetTask: %v", err)
}
if len(got.Steps) != 2 {
t.Fatalf("steps len = %d, want 2", len(got.Steps))
}
if got.Steps[0].Title != "Реализовать модель" || got.Steps[0].AC != "структура готова" {
t.Fatalf("steps[0] = %q / %q, want модель / структура готова", got.Steps[0].Title, got.Steps[0].AC)
}
// апдейт этапов
got.Steps = append(got.Steps, Step{Title: "Ревью", AC: "пройден review"})
if err := s.UpdateTask(ctx, got); err != nil {
t.Fatalf("UpdateTask steps: %v", err)
}
got2, _ := s.GetTask(ctx, id)
if len(got2.Steps) != 3 {
t.Fatalf("steps len after update = %d, want 3", len(got2.Steps))
}
}
func TestListTasks(t *testing.T) { func TestListTasks(t *testing.T) {
s, ctx := setupTestDB(t) s, ctx := setupTestDB(t)
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {

View File

@@ -30,10 +30,10 @@ func (s *Storage) CreateTask(ctx context.Context, t *Task) (int64, error) {
} }
now := Now() now := Now()
res, err := s.db.ExecContext(ctx, ` res, err := s.db.ExecContext(ctx, `
INSERT INTO tasks (chat_id, title, goal, repo, repos, why, ac, task_tag, status, created_at, updated_at) INSERT INTO tasks (chat_id, title, goal, repo, repos, why, ac, steps, task_tag, status, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
t.ChatID, t.Title, t.Goal, t.Repo, t.ReposJoined(), t.Why, t.AC, t.ChatID, t.Title, t.Goal, t.Repo, t.ReposJoined(), t.Why, t.AC,
t.TaskTag, StatusDraft, now, now, t.StepsJoined(), t.TaskTag, StatusDraft, now, now,
) )
if err != nil { if err != nil {
return 0, fmt.Errorf("%w: create task: %w", ErrDB, err) return 0, fmt.Errorf("%w: create task: %w", ErrDB, err)
@@ -53,11 +53,12 @@ func (s *Storage) CreateTask(ctx context.Context, t *Task) (int64, error) {
func (s *Storage) GetTask(ctx context.Context, id int64) (*Task, error) { func (s *Storage) GetTask(ctx context.Context, id int64) (*Task, error) {
t := &Task{} t := &Task{}
var reposStr string var reposStr string
var stepsStr string
err := s.db.QueryRowContext(ctx, ` err := s.db.QueryRowContext(ctx, `
SELECT id, chat_id, title, goal, repo, repos, why, ac, task_tag, status, created_at, updated_at SELECT id, chat_id, title, goal, repo, repos, why, ac, steps, task_tag, status, created_at, updated_at
FROM tasks WHERE id = ?`, id).Scan( FROM tasks WHERE id = ?`, id).Scan(
&t.ID, &t.ChatID, &t.Title, &t.Goal, &t.Repo, &reposStr, &t.ID, &t.ChatID, &t.Title, &t.Goal, &t.Repo, &reposStr,
&t.Why, &t.AC, &t.TaskTag, &t.Status, &t.CreatedAt, &t.UpdatedAt, &t.Why, &t.AC, &stepsStr, &t.TaskTag, &t.Status, &t.CreatedAt, &t.UpdatedAt,
) )
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return nil, fmt.Errorf("%w: task %d", ErrNotFound, id) return nil, fmt.Errorf("%w: task %d", ErrNotFound, id)
@@ -66,6 +67,7 @@ func (s *Storage) GetTask(ctx context.Context, id int64) (*Task, error) {
return nil, fmt.Errorf("%w: get task %d: %w", ErrDB, id, err) return nil, fmt.Errorf("%w: get task %d: %w", ErrDB, id, err)
} }
t.SetReposFromDB(reposStr) t.SetReposFromDB(reposStr)
t.SetStepsFromDB(stepsStr)
return t, nil return t, nil
} }
@@ -94,9 +96,9 @@ func (s *Storage) UpdateTask(ctx context.Context, t *Task) error {
now := Now() now := Now()
res, err := s.db.ExecContext(ctx, ` res, err := s.db.ExecContext(ctx, `
UPDATE tasks UPDATE tasks
SET title=?, goal=?, repo=?, repos=?, why=?, ac=?, status=?, updated_at=? SET title=?, goal=?, repo=?, repos=?, why=?, ac=?, steps=?, status=?, updated_at=?
WHERE id=?`, WHERE id=?`,
t.Title, t.Goal, t.Repo, t.ReposJoined(), t.Why, t.AC, t.Status, now, t.ID, t.Title, t.Goal, t.Repo, t.ReposJoined(), t.Why, t.AC, t.StepsJoined(), t.Status, now, t.ID,
) )
if err != nil { if err != nil {
return fmt.Errorf("%w: update task %d: %w", ErrDB, t.ID, err) return fmt.Errorf("%w: update task %d: %w", ErrDB, t.ID, err)
@@ -114,13 +116,14 @@ func (s *Storage) UpdateTask(ctx context.Context, t *Task) error {
func (s *Storage) GetActiveTaskByChatID(ctx context.Context, chatID string) (*Task, error) { func (s *Storage) GetActiveTaskByChatID(ctx context.Context, chatID string) (*Task, error) {
t := &Task{} t := &Task{}
var reposStr string var reposStr string
var stepsStr string
err := s.db.QueryRowContext(ctx, ` err := s.db.QueryRowContext(ctx, `
SELECT id, chat_id, title, goal, repo, repos, why, ac, task_tag, status, created_at, updated_at SELECT id, chat_id, title, goal, repo, repos, why, ac, steps, task_tag, status, created_at, updated_at
FROM tasks FROM tasks
WHERE chat_id = ? AND status NOT IN ('success','cancelled','aborted','closed') WHERE chat_id = ? AND status NOT IN ('success','cancelled','aborted','closed')
ORDER BY updated_at DESC LIMIT 1`, chatID).Scan( ORDER BY updated_at DESC LIMIT 1`, chatID).Scan(
&t.ID, &t.ChatID, &t.Title, &t.Goal, &t.Repo, &reposStr, &t.ID, &t.ChatID, &t.Title, &t.Goal, &t.Repo, &reposStr,
&t.Why, &t.AC, &t.TaskTag, &t.Status, &t.CreatedAt, &t.UpdatedAt) &t.Why, &t.AC, &stepsStr, &t.TaskTag, &t.Status, &t.CreatedAt, &t.UpdatedAt)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return nil, fmt.Errorf("%w: no active task for chat %s", ErrNotFound, chatID) return nil, fmt.Errorf("%w: no active task for chat %s", ErrNotFound, chatID)
} }
@@ -128,6 +131,7 @@ func (s *Storage) GetActiveTaskByChatID(ctx context.Context, chatID string) (*Ta
return nil, fmt.Errorf("%w: get active task %s: %w", ErrDB, chatID, err) return nil, fmt.Errorf("%w: get active task %s: %w", ErrDB, chatID, err)
} }
t.SetReposFromDB(reposStr) t.SetReposFromDB(reposStr)
t.SetStepsFromDB(stepsStr)
return t, nil return t, nil
} }
@@ -149,7 +153,7 @@ func (s *Storage) ListTasks(ctx context.Context, filter TaskFilter) ([]*Task, er
args = append(args, filter.Limit, filter.Offset) args = append(args, filter.Limit, filter.Offset)
rows, err := s.db.QueryContext(ctx, ` rows, err := s.db.QueryContext(ctx, `
SELECT id, chat_id, title, goal, repo, repos, why, ac, task_tag, status, created_at, updated_at SELECT id, chat_id, title, goal, repo, repos, why, ac, steps, task_tag, status, created_at, updated_at
FROM tasks WHERE `+where+` ORDER BY updated_at DESC LIMIT ? OFFSET ?`, args...) FROM tasks WHERE `+where+` ORDER BY updated_at DESC LIMIT ? OFFSET ?`, args...)
if err != nil { if err != nil {
return nil, fmt.Errorf("%w: list tasks: %w", ErrDB, err) return nil, fmt.Errorf("%w: list tasks: %w", ErrDB, err)
@@ -160,11 +164,13 @@ func (s *Storage) ListTasks(ctx context.Context, filter TaskFilter) ([]*Task, er
for rows.Next() { for rows.Next() {
t := &Task{} t := &Task{}
var reposStr string var reposStr string
var stepsStr string
if err := rows.Scan(&t.ID, &t.ChatID, &t.Title, &t.Goal, &t.Repo, &reposStr, if err := rows.Scan(&t.ID, &t.ChatID, &t.Title, &t.Goal, &t.Repo, &reposStr,
&t.Why, &t.AC, &t.TaskTag, &t.Status, &t.CreatedAt, &t.UpdatedAt); err != nil { &t.Why, &t.AC, &stepsStr, &t.TaskTag, &t.Status, &t.CreatedAt, &t.UpdatedAt); err != nil {
return nil, fmt.Errorf("%w: scan task: %w", ErrDB, err) return nil, fmt.Errorf("%w: scan task: %w", ErrDB, err)
} }
t.SetReposFromDB(reposStr) t.SetReposFromDB(reposStr)
t.SetStepsFromDB(stepsStr)
tasks = append(tasks, t) tasks = append(tasks, t)
} }
return tasks, rows.Err() return tasks, rows.Err()

View File

@@ -3,6 +3,8 @@ package worker
import ( import (
"strings" "strings"
"text/template" "text/template"
"github.com/kamelion/ratatoskr-go/internal/storage"
) )
// devPromptTemplate — промпт для dev-агента при запуске задачи. // devPromptTemplate — промпт для dev-агента при запуске задачи.
@@ -20,6 +22,12 @@ var devPromptTemplate = template.Must(template.New("dev").Parse(`Ты — dev-а
{{if .Why}}Зачем: {{.Why}}{{end}} {{if .Why}}Зачем: {{.Why}}{{end}}
{{if .AC}}Критерии готовности: {{if .AC}}Критерии готовности:
{{.AC}}{{end}} {{.AC}}{{end}}
{{if .Steps}}
**Этапы (выполняй по порядку, у каждого свой критерий готовности):**
{{- range .Steps}}
{{.Title}}{{if .AC}} — готово, когда: {{.AC}}{{end}}
{{- end}}
{{end}}
**Инструкции:** **Инструкции:**
1. Рабочий каталог — общий корень, в котором лежат все репозитории по именам. 1. Рабочий каталог — общий корень, в котором лежат все репозитории по именам.
@@ -38,6 +46,7 @@ type DevPromptData struct {
Repos []string Repos []string
Why string Why string
AC string AC string
Steps []storage.Step
// ReviewFeedback — замечания ревьюера при повторном прогоне dev // ReviewFeedback — замечания ревьюера при повторном прогоне dev
// (не пусто → dev должен исправить именно это). // (не пусто → dev должен исправить именно это).

View File

@@ -255,6 +255,7 @@ func (w *Worker) runTask(ctx context.Context, task *storage.Task) (err error) {
Repos: repos, Repos: repos,
Why: task.Why, Why: task.Why,
AC: task.AC, AC: task.AC,
Steps: task.Steps,
Branch: branch, Branch: branch,
ReviewFeedback: reviewFeedbackList(branch, feedback), ReviewFeedback: reviewFeedbackList(branch, feedback),
} }

View File

@@ -725,6 +725,7 @@ func TestWorkerBadStatus(t *testing.T) {
} }
} }
// TestWorkerPromptRendered — dev-промпт собирается из полей задачи.
func TestWorkerPromptRendered(t *testing.T) { func TestWorkerPromptRendered(t *testing.T) {
s := setupWorkerDB(t) s := setupWorkerDB(t)
task := createReadyTask(t, s, "prompt-test") task := createReadyTask(t, s, "prompt-test")
@@ -758,6 +759,63 @@ func TestWorkerPromptRendered(t *testing.T) {
} }
} }
// TestWorkerPromptIncludesSteps — этапы задачи попадают в dev-промпт по порядку
// с критериями готовности.
func TestWorkerPromptIncludesSteps(t *testing.T) {
s := setupWorkerDB(t)
task := createReadyTask(t, s, "steps-test")
ctx := context.Background()
task.Steps = []storage.Step{
{Title: "Модель", AC: "операции готовы"},
{Title: "UI"},
}
if err := s.UpdateTask(ctx, task); err != nil {
t.Fatalf("update steps: %v", err)
}
w := &Worker{
Store: s,
Runner: &mockRunnerWorker{result: &opencode.Result{RC: 0, Stdout: "ok", SessionID: "s"}},
Worktree: t.TempDir(),
}
seedFakeRepo(t, w.Worktree, "steps-test")
_ = w.runTask(ctx, task)
traces, err := s.GetTraces(ctx, task.ID)
if err != nil {
t.Fatalf("get traces: %v", err)
}
tr := traces[0]
for _, want := range []string{"Этапы", "Модель", "операции готовы", "UI"} {
if !strings.Contains(tr.Prompt, want) {
t.Errorf("dev-промпт не содержит %q", want)
}
}
}
// TestRenderDevPromptSteps — прямой рендер dev-промпта с этапами.
func TestRenderDevPromptSteps(t *testing.T) {
prompt, err := RenderDevPrompt(DevPromptData{
Title: "Калькулятор",
AC: "работает",
Steps: []storage.Step{
{Title: "Модель", AC: "операции готовы"},
{Title: "UI"},
},
Branch: "feat/abc",
})
if err != nil {
t.Fatalf("render: %v", err)
}
for _, want := range []string{"Этапы", "Модель — готово, когда: операции готовы", "UI"} {
if !strings.Contains(prompt, want) {
t.Errorf("prompt не содержит %q", want)
}
}
}
func TestFeatureBranchName(t *testing.T) { func TestFeatureBranchName(t *testing.T) {
cases := []struct { cases := []struct {
tag string tag string