internal/core: ядро-машина состояний (ProcessTurn поверх storage) + история задач в БД
All checks were successful
build-test / build (push) Successful in 1m11s
All checks were successful
build-test / build (push) Successful in 1m11s
- status = единственный источник истины (collecting/ready как фазы диалога) - команды /start /cancel /skip /retry N /status N /continue N - Decider интерфейс (аналитик→opencode, мок для тестов) - task_history таблица для промпта аналитика - allow ready→collecting (правка черновика)
This commit is contained in:
55
internal/storage/history.go
Normal file
55
internal/storage/history.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// HistoryMsg — одна запись истории диалога.
|
||||
type HistoryMsg struct {
|
||||
Role string `json:"role"` // "user" | "assistant"
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// AppendHistory добавляет сообщение в историю задачи.
|
||||
func (s *Storage) AppendHistory(ctx context.Context, taskID int64, role, content string) error {
|
||||
now := Now()
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO task_history (task_id, role, content, created_at)
|
||||
VALUES (?, ?, ?, ?)`, taskID, role, content, now,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: append history: %w", ErrDB, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetHistory возвращает историю задачи, отсортированную по времени.
|
||||
func (s *Storage) GetHistory(ctx context.Context, taskID int64) ([]HistoryMsg, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT role, content FROM task_history
|
||||
WHERE task_id = ? ORDER BY id ASC`, taskID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: get history: %w", ErrDB, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var msgs []HistoryMsg
|
||||
for rows.Next() {
|
||||
var m HistoryMsg
|
||||
if err := rows.Scan(&m.Role, &m.Content); err != nil {
|
||||
return nil, fmt.Errorf("%w: scan history: %w", ErrDB, err)
|
||||
}
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
return msgs, rows.Err()
|
||||
}
|
||||
|
||||
// ClearHistory удаляет всю историю задачи (при /start).
|
||||
func (s *Storage) ClearHistory(ctx context.Context, taskID int64) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM task_history WHERE task_id = ?`, taskID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: clear history: %w", ErrDB, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
70
internal/storage/history_test.go
Normal file
70
internal/storage/history_test.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHistoryCRUD(t *testing.T) {
|
||||
s, ctx := setupTestDB(t)
|
||||
task := &Task{ChatID: "tg://hist", TaskTag: "history"}
|
||||
id, _ := s.CreateTask(ctx, task)
|
||||
|
||||
// append
|
||||
if err := s.AppendHistory(ctx, id, "user", "привет"); err != nil {
|
||||
t.Fatalf("AppendHistory: %v", err)
|
||||
}
|
||||
if err := s.AppendHistory(ctx, id, "assistant", "здравствуй"); err != nil {
|
||||
t.Fatalf("AppendHistory: %v", err)
|
||||
}
|
||||
if err := s.AppendHistory(ctx, id, "user", "сделай задачу"); err != nil {
|
||||
t.Fatalf("AppendHistory: %v", err)
|
||||
}
|
||||
|
||||
h, err := s.GetHistory(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetHistory: %v", err)
|
||||
}
|
||||
if len(h) != 3 {
|
||||
t.Fatalf("history len = %d, want 3", len(h))
|
||||
}
|
||||
if h[0].Role != "user" || h[0].Content != "привет" {
|
||||
t.Fatalf("h[0] = %+v", h[0])
|
||||
}
|
||||
if h[2].Content != "сделай задачу" {
|
||||
t.Fatalf("h[2] last = %q, want 'сделай задачу'", h[2].Content)
|
||||
}
|
||||
|
||||
// clear
|
||||
if err := s.ClearHistory(ctx, id); err != nil {
|
||||
t.Fatalf("ClearHistory: %v", err)
|
||||
}
|
||||
h, _ = s.GetHistory(ctx, id)
|
||||
if len(h) != 0 {
|
||||
t.Fatalf("history after clear len = %d, want 0", len(h))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryIsolatedPerTask(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, err := Open(ctx, ":memory:")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
|
||||
id1, _ := s.CreateTask(ctx, &Task{ChatID: "a", TaskTag: "1"})
|
||||
id2, _ := s.CreateTask(ctx, &Task{ChatID: "b", TaskTag: "2"})
|
||||
|
||||
_ = s.AppendHistory(ctx, id1, "user", "для задачи 1")
|
||||
_ = s.AppendHistory(ctx, id2, "user", "для задачи 2")
|
||||
|
||||
h1, _ := s.GetHistory(ctx, id1)
|
||||
h2, _ := s.GetHistory(ctx, id2)
|
||||
if len(h1) != 1 || h1[0].Content != "для задачи 1" {
|
||||
t.Fatalf("h1 wrong: %+v", h1)
|
||||
}
|
||||
if len(h2) != 1 || h2[0].Content != "для задачи 2" {
|
||||
t.Fatalf("h2 wrong: %+v", h2)
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ var AllStatuses = []Status{
|
||||
var validTransitions = map[Status][]Status{
|
||||
StatusDraft: {StatusCollecting, StatusCancelled, StatusAborted},
|
||||
StatusCollecting: {StatusReady, StatusDraft, StatusCancelled, StatusAborted},
|
||||
StatusReady: {StatusRunning, StatusCancelled, StatusAborted, StatusClosed},
|
||||
StatusReady: {StatusRunning, StatusCancelled, StatusAborted, StatusClosed, StatusCollecting}, // правка готового
|
||||
StatusRunning: {StatusSuccess, StatusFailed, StatusTimeout, StatusCancelled},
|
||||
StatusSuccess: {StatusClosed},
|
||||
StatusFailed: {StatusReady, StatusClosed, StatusCancelled}, // retry
|
||||
|
||||
@@ -132,6 +132,16 @@ func (s *Storage) migrate(ctx context.Context) error {
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_chat ON tasks(chat_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS task_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_history_task ON task_history(task_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS traces (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
|
||||
Reference in New Issue
Block a user